how to run code when Microsoft toast notification button is pressed in javascript - visual-studio-2017

I am trying to make a microsoft toast notification that has buttons or so called "actions"
in this code i have 3 buttons A,B,C and i want to check if any of them are clicked and if so the run a line of code
just for example if A is clicked then run debug.log('A')
how can i do that?
(im new to visual studio and javascript)
document.addEventListener('keydown', logKey);
function logKey(e) {
var notifLib = Microsoft.Toolkit.Uwp.Notifications;
var toastContent = new notifLib.ToastContent();
var toastVisual = new notifLib.ToastVisual();
var toastBindingGeneric = new notifLib.ToastBindingGeneric();
var adaptiveText = new notifLib.AdaptiveText();
adaptiveText.text = "Hello World";
toastBindingGeneric.children.push(adaptiveText);
adaptiveText = new notifLib.AdaptiveText();
adaptiveText.text = "This is a simple toast message";
toastBindingGeneric.children.push(adaptiveText);
toastVisual.bindingGeneric = toastBindingGeneric;
toastContent.visual = toastVisual;
var toastActionsCustom = new notifLib.ToastActionsCustom();
var toastButton = new notifLib.ToastButton("a", "action=at&userId=1");
toastButton.activationType = notifLib.ToastActivationType.background;
toastActionsCustom.buttons.push(toastButton);
toastButton = new notifLib.ToastButton("b", "action=b&userId=1");
toastButton.activationType = notifLib.ToastActivationType.background;
toastActionsCustom.buttons.push(toastButton);
toastButton = new notifLib.ToastButton("c", "action=b&userId=1");
toastButton.activationType = notifLib.ToastActivationType.background;
toastActionsCustom.buttons.push(toastButton);
toastContent.actions = toastActionsCustom;
// Create the toast notification
var toastNotif = new Windows.UI.Notifications.ToastNotification(toastContent.getXml());
// And send the notification
Windows.UI.Notifications.ToastNotificationManager.createToastNotifier().show(toastNotif);
};

for UWP applications, when the notification button is pressed, the activated event of the application will be triggered. In javascript, it can be written like this:
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (activatedEventArgs) {
if (activatedEventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.toastNotification) {
console.log(activatedEventArgs.argument);
}
});
If you are using WinJs to build your application, you can find the corresponding code block that handles the click of the Toast notification in the app.onactivated event in main.js
...
else if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.arguments) {
}
...
}
...

Related

How to get current filters from PowerBi embedded export report

I am using powerbi embedded and I would like an export button similar to the one used on powerbi.com, that asks if you want to apply the current filters or not.
How can I get the current filters in javaScript in such a way that these can be passed to the back end, or to the javascript api to generate a PDF?
I am using the following code to generate the PDF currently, I just don't know how to get the current configuration current filters and current page selected in javaScript
public PowerBiExportViewModel CreateExport(Guid groupId,
Guid reportId,
IEnumerable<PowerBiReportPage> reportPages,
FileFormat fileFormat,
string urlFilter,
TimeSpan timeOut)
{
var errorMessage = string.Empty;
Stream stream = null;
var fileSuffix = string.Empty;
var securityToken = GetAccessToken();
using (var client = new PowerBIClient(new Uri(BaseAddress), new TokenCredentials(securityToken, "Bearer")))
{
var powerBiReportExportConfiguration = new PowerBIReportExportConfiguration
{
Settings = new ExportReportSettings
{
Locale = "en-gb",
IncludeHiddenPages = false
},
Pages = reportPages?.Select(pn => new ExportReportPage { PageName = pn.Name }).ToList(),
ReportLevelFilters = !string.IsNullOrEmpty(urlFilter) ? new List<ExportFilter>() { new ExportFilter(urlFilter) } : null,
};
var exportRequest = new ExportReportRequest
{
Format = fileFormat,
PowerBIReportConfiguration = powerBiReportExportConfiguration
};
var export = client.Reports.ExportToFileInGroupAsync(groupId, reportId, exportRequest).Result;
You can go to PowerBi playground and play around with their sample report. Next to "Embed" button you have "Interact" and option to get filters. In response you get JSON with filters. If you are too lazy to go there, here is the code it created for me
// Get a reference to the embedded report HTML element
var embedContainer = $('#embedContainer')[0];
// Get a reference to the embedded report.
report = powerbi.get(embedContainer);
// Get the filters applied to the report.
try {
const filters = await report.getFilters();
Log.log(filters);
}
catch (errors) {
Log.log(errors);
}

Google Meet: How can i catch the url?

I need to open a new google meet room, and send it. I can't use standard "share" button in app. I need to catch the final url.
I can't catch that with curl (it's not a normal redirect).
My idea is that i need to open a request/link in background or in the same page, wait some second and catch the link, after i can release the page and user can enter.
Do you know something that can help me?
Edit:
Yes, i had miss to tell that i need to generate a room from a click and catch the url from code. Generally, i should to make this with Google Calendar API, but in this case i can't.
I use google Calendar API. I make a webApp for my organization, that from a form (with user information to send togheter meet link) make a google calendar event with google meet room (from google loggedin user account), catch the link and send it by a smsGateway.
function FormForMeet (Args) {
// get calendar name, if it already exists
var meetsCalendar = CalendarApp.getCalendarsByName ('CalendarName');
Logger.log (meetsCalendar.length)
if (meetsCalendar.length> = 1) {
// if some calendar be found, it catch the first, obviously here you can use some differet method. I had choose this because I don't expect to find more than 1
var calendar = meetsCalendar [0] .getId ();
}
else
{
// If miss, create new one.
var calendar = CalendarApp.createCalendar ('CalendarName', {summary: 'descrip Calendar',
// set a color of calendar label :D
color: CalendarApp.Color.PURPLE});
calendar = calendar.getId ();
}
// Call function to create meet
var LinkMeet = CreateConference_ (calendar);
// here you can use what you want for send Args + LinkMeet);
// if you want return link
return LinkMeet;
}
// Function to create Conference. You can obviously use the code up without make a new function.
function CreateConference_ (calendarId) {
// Custom of event, here I created the conferences according to my needs (now, with 1 h / conference)
var now = new Date ();
var start = new Date (now.getTime ()). toISOString ();
var end = new Date (now.getTime () + (1 * 60 * 60 * 1000)). toISOString ();
// generate random string to request
var rdmreqId = genStrg ();
var event = {
"end": {
"dateTime": end
},
"start": {
"dateTime": start
},
"summary": "conferenceName",
"conferenceData": {
"createRequest": {
"conferenceSolutionKey": {
"type": "hangoutsMeet"
},
"requestId": rdmreqId
}
}
};
// insert event in calendar
event = Calendar.Events.insert (event, calendarId, {
"conferenceDataVersion": 1});
// if use the function you can return the link to send
return event.hangoutLink
}
// random strind
function genStrg () {
var data = "something";
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789! # # $% & <> * -";
for (var j = 2; j <= data.length; j ++) {
text = ""; // Reset text to empty string
for (var i = 0; i <possible.length; i ++) {
text + = possible.charAt (Math.floor (Math.random () * possible.length));
}
return text;
}
}
all google meet links look something like this:
https://meet.google.com/abc-defg-hij
You should be able to just copy and paste this link from your browser page. If someone enters this link, they will be taken to the meet lobby and they can enter at any time.
If you can't access this link for some reason, like if you're on mobile, you have to put your meet code (the abc-defg-hij) at the end of the aforementioned url.
edit: You actually can find the link if you're on mobile by going into your meeting lobby and scrolling down until you get to "joining information". Under that there should be the meeting link and the numbers to join by phone.

How to running method webservice in background from android xamarin form

I want running this method UpdateStatus when he close app
It is my coding method UpdateStatus in android:
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
Could you help me ?
In the Android, When you close your applcation, based on my research, above code can not be run, because all of threads or services will be killed when applcation is killed.
If you want to run above code when application in the background, you can can use background service to achieve that, due to background execution limits in Android 8.0 or later, if you code need some time to execute, and you want code running stably, Foreground Services is a good choice.
In xamarin forms, you can use dependenceService in the OnSleep method of App.xaml.cs
OnSleep - called each time the application goes to the background.
You can create a interface.
IService.cs
public interface IService
{
void Start();
}
Then achieved DependentService to start a Foreground Service.
[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
[Service]
public class DependentService : Service, IService
{
public void Start()
{
var intent = new Intent(Android.App.Application.Context,
typeof(DependentService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
Android.App.Application.Context.StartForegroundService(intent);
}
else
{
Android.App.Application.Context.StartService(intent);
}
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
public override StartCommandResult OnStartCommand(Intent intent,
StartCommandFlags flags, int startId)
{
// From shared code or in your PCL
CreateNotificationChannel();
string messageBody = "service starting";
var notification = new Notification.Builder(this, "10111")
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText(messageBody)
.SetSmallIcon(Resource.Drawable.main)
.SetOngoing(true)
.Build();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
//==============================do you work=====================
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
return StartCommandResult.Sticky;
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
}
Here is similar thread:
How to create service doing work at period time in Xamarin.Forms?

Getting error as 'Expected invocation on the mock at least once, but was never performed' after executing unit test

I have below code which navigates from one page to other using Navigation Service in Xamarin forms.
On clicking on Observation button it executes ObservationsCommand as shown below.
public Command ObservationsCommand => new Command(async () => await OnObservationsCommandAsync());
After clicking on Observation button it navigates to next page passing the selected data to the navigation service as shown
private async Task OnObservationsCommandAsync()
{
ObservationDetailsParameter selectedData = new ObservationDetailsParameter
{
Cage = DisplayedCage,
Dossiers = DossierList.SelectedItems
};
await _navigationService.NavigateToAsync<ObservationDetailsViewModel>(selectedData);
}
Below is the code for unit test
[Fact]
public void TestOnObservationsCommandAsync()
{
var mockNavigationService = new Mock<INavigationService>();
var mockCageDetailsService = new MockCageDetailsService();
var mockObservationDetailsService = new MockObservationDetailsService();
var mockSettingsService = new MockSettingsService();
Cage _displayedCage = new Cage { Id = 11 };
Dossier _dossier1 = new Dossier { Id = 841 };
var _dossierList = new SelectableItemCollection<Dossier>
{
_dossier1
};
_dossierList.SelectAll();
var cageObsViewModel = new CageObsViewModel(mockNavigationService.Object, mockCageDetailsService, mockSettingsService);
var mockObservationDetailsParameter = new
Mock<IObservationDetailsParameter>();
mockObservationDetailsParameter.Setup(x =>
x.Cage).Returns(_displayedCage);
mockObservationDetailsParameter.Setup(x => x.Dossiers
).Returns(_dossierList.SelectedItems );
cageObsViewModel.DisplayedCage = mockObservationDetailsParameter .Object .Cage ;
cageObsViewModel.DossierList = _dossierList;
// Act
cageObsViewModel.ObservationsCommand.Execute(null);
mockNavigationService.Verify((s) => s.NavigateToAsync<ObservationDetailsViewModel>(mockObservationDetailsParameter.Object));
}
However after executing this test i get error as 'Expected invocation on the mock at least once, but was never performed.'
Will you please help?
This is an example of a unit test I have to verify navigation after successful login.
[Fact]
public async Task ValidCredentials()
{
//Mock login -> false
var authenticationServiceMock = new Mock<IAuthenticationService>();
authenticationServiceMock
.Setup(s => s.Login(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult(true));
LoginViewModel viewModel = new LoginViewModel(authenticationServiceMock.Object);
await viewModel.InitializeAsync(null);
viewModel.UserName.Value = "johann#mail.com";
viewModel.Password.Value = "1234!Maaaa";
viewModel.LoginCommand.Execute(null);
navigationServiceMock.Verify((s) => s.NavigateToAsync<HomeViewModel>());
}
As I am using AutoFac and my ViewModelBase gets the NavigationService instance by itself this is my test setup:
public LoginViewModelTests()
{
ContainerBuilder builder = new ContainerBuilder();
navigationServiceMock = new Mock<INavigationService>();
navigationServiceMock.SetReturnsDefault<Task>(Task.FromResult(0));
builder.RegisterInstance<INavigationService>(navigationServiceMock.Object);
ViewModelLocator.RegisterDependencies(builder);
}
If it is not clear enough let me know and we can review it to better adapt to your case.

ConnectFailure with HttpRequest in Xamarin

I'm using the free version of Xamarin Studio to do some test. In aprticular I'm trying to connect to web Service but I receive the ConnectFailure (Network unreachable) when I debug the application.
This is my code
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Our code will go here
// Get our UI controls from the loaded layout
EditText phoneNumberText = FindViewById<EditText>(Resource.Id.editText1);
Button translateButton = FindViewById<Button>(Resource.Id.button1);
Button callButton = FindViewById<Button>(Resource.Id.button2);
// Disable the "Call" button
callButton.Enabled = false;
// Add code to translate number
string translatedNumber = string.Empty;
var rxcui = "198440";
var request = HttpWebRequest.Create(string.Format(#"http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/{0}/allinfo", rxcui));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if(string.IsNullOrWhiteSpace(content)) {
Console.Out.WriteLine("Response contained empty body...");
}
else {
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
//Assert.NotNull(content);
}
}
}
}
}
I don't understand if this is an error caused by the free version or it's me.
Please help me.
Thanks