Back arrow does not work when UWP launched from WinForms app - winrt-xaml

So we are integrating the old with the new.
I am launching my UWP app from within our WinForms app.
When I navigate around the UWP app, the back button does not work. When launching the UWP app normally everything works fine.
Here is my winforms launching code:
Uri uri = new Uri($"companies:");
//see declarations in package.appxmanifest in winten app.
string targetPackageFamilyName = "81e1fc62-68df-45f5-ac35-c86d1277e2db_2zt4j53vqbz02";
// see added protocol declaration in package.appxmanifest in win10 app
var supportStatus = await Launcher.QueryUriSupportAsync(
uri,
LaunchQuerySupportType.Uri,
targetPackageFamilyName);
if (supportStatus != LaunchQuerySupportStatus.Available)
{
var msg = "Can't launch because the app we need is " + supportStatus.ToString();
}
else
{
var options = new LauncherOptions { TargetApplicationPackageFamilyName = targetPackageFamilyName };
var success = await Launcher.LaunchUriAsync(uri, options);
}
And here is the receiving code
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
switch (eventArgs.Uri.Scheme)
{
case "companies":
NavigationService.Navigate(typeof(Views.CompaniesPage));
break;
case "company":
NavigationService.Navigate(typeof(Views.CompanyEditPage), eventArgs.Uri.Query);
break;
case "query":
NavigationService.Navigate(typeof(Views.QueryPage));
break;
default:
break;
}
}
else
{
NavigationService.Navigate(typeof(Views.CompaniesPage));
await Task.Yield();
}
}

Related

.Net Maui iOS app with Silent Push Notifications ReceivedRemoteNotification or DidReceiveRemoteNotification never gets called

I'm using Plugin.Firebase and my own APN Server. I can send a message with an alert payload. This works just fine. If I send a message with a content-available payload, nothing happens.
I'm using the current version of the .Net 7 release. My target is iOS 16. My test device is an iPhone 12 running iOS 15.7.
Here are some key components of my AppDelegate.
This has been added to FinishedLaunching.
var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
{
//this.Log($"RequestAuthorization: {granted}" + (error != null ? $" with error: {error.LocalizedDescription}" : string.Empty));
if (granted && error == null)
{
this.InvokeOnMainThread(() =>
{
UIApplication.SharedApplication.RegisterForRemoteNotifications();
//this.InitFirebase();
UNUserNotificationCenter.Current.Delegate = this;
});
}
});
Here is DidReceiveRemoteNotification.
https://learn.microsoft.com/en-us/dotnet/api/uikit.uiapplicationdelegate.didreceiveremotenotification?view=xamarin-ios-sdk-12
//App is in the foreground
[Foundation.Export("application:didReceiveRemoteNotification:fetchCompletionHandler:")]
public void DidReceiveRemoteNotification(UIKit.UIApplication application, Foundation.NSDictionary userInfo, Action<UIKit.UIBackgroundFetchResult> completionHandler)
{
SentrySdk.CaptureMessage("DidReceiveNotificationResponse = " + "yes");
ProcessNotification(userInfo, false);
completionHandler(UIBackgroundFetchResult.NewData);
}
Here is ReceivedRemoteNotification.
https://learn.microsoft.com/en-us/dotnet/api/uikit.uiapplicationdelegate.receivedremotenotification?view=xamarin-ios-sdk-12
//App is in the background
[Foundation.Export("application:didReceiveRemoteNotification:")]
public void ReceivedRemoteNotification(UIKit.UIApplication application, Foundation.NSDictionary userInfo)
{
SentrySdk.CaptureMessage("ReceivedRemoteNotification = " + "yes");
ProcessNotification(userInfo, false);
}
Here is the APS payload.
public AppleNotificationSilent()
{
//Id = id;
Aps = new ApsPayload
{
//AlertBody = new ApsPayload.Alert
//{
// Title = title,
// SubTitle = subtitle,
// Body = message
//},
//Alert = "",
ContentAvailable = 1,
//PushType = "background",
//Priority = 5,
CustomKey = "GetData" //THIS WORKS
};
//CustomKey = "GetData";
}
Here is what ContentAvailable looks like.
[JsonProperty("content-available")]
public int ContentAvailable { get; set; }
Finally, I've changed the following headers for silent push.
apns-push-type = "background"
apns-priority = 5
I've noticed that the overrides for DidReceiveRemoteNotification and ReceivedRemoteNotification aren't found. This was supposed to added to the .Net 7 Maui release. I've also noticed that the decoration Export for both methods is the same except for fetchCompletionHandler in DidReceiveRemoteNotification.
Here is some additional information on how this is supposed to work.
https://learn.microsoft.com/en-us/xamarin/ios/app-fundamentals/backgrounding/ios-backgrounding-techniques/updating-an-application-in-the-background
https://learn.microsoft.com/en-us/xamarin/ios/platform/user-notifications/enhanced-user-notifications?source=recommendations&tabs=macos
https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app
Does anyone know why this isn't working? Thanks!
BEGIN UPDATE 1
A silent push notification will call this method when the app is open and in the foreground.
// App is in the foreground
[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
SentrySdk.CaptureMessage("DidReceiveNotificationResponse = " + "yes");
ShowLocalNotification();
//this.Log($"{nameof(DidReceiveNotificationResponse)}: " + response.Notification.Request.Content.UserInfo);
completionHandler();
}
END UPDATE 1
BEGIN UPDATE 2
After adding the fix found in the answer, all silent push notifications are now handled by DidReceiveRemoteNotification.
END UPDATE 2
Make sure you have this in your csprog file. I'm now able to receive silent push notifications when the app is open / being used, open / in the background, and while not running at all.
https://github.com/dotnet/maui/issues/6259#issuecomment-1109359755
Here is what mine looks like.
<PropertyGroup>
<MtouchExtraArgs>--optimize:-static-block-to-delegate-lookup</MtouchExtraArgs>
<CodesignKey>iPhone Developer</CodesignKey>
</PropertyGroup>
The weird part about this is that all the silent push messages are being handled by DidReceiveRemoteNotification.

Xamarin.Firebase.iOS.CloudMessaging fails on Messaging.SharedInstance.Delegate

I have tried many different versions of sample / example code, but I cannot get Cloud Messaging to work on iOS (14.5).
The line
Messaging.SharedInstance.Delegate = this;
Always fails with SharedInstance being null.
To test, I created a new Xamarin Forms project, I added the Nuget package Xamarin.Firebase.iOS.CloudMessaging version 4.7.1, and I added the GoogleServices-Info.plist file and set the Build Action to BundleResource.
I added the following code to AppDelegate:
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate, IMessagingDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
try
{
global::Xamarin.Forms.Forms.Init();
Firebase.Core.App.Configure();
LoadApplication(new App());
// Register your app for remote notifications.
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// iOS 10 or later
var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
Console.WriteLine(granted);
});
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = this;
// For iOS 10 data message (sent via FCM)
Messaging.SharedInstance.Delegate = this;
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
The above code fails on the line "Messaging.SharedInstance.Delegate = this;".
This issue is also on the GitHub issues section:
https://github.com/xamarin/GoogleApisForiOSComponents/issues/486

Support for interruptions in bot

Do you know if there is way to implement global message handlers that can support commands like stop, bye, cancel, exit Virtual assistant bot ? I am trying to implement something like this.
I have a virtual assistant built already and it has couple of Skills or Skill Bots.
When user is in the multi turn conversation with a Skill, user should be able to exit out of skill by commands like stop, bye, cancel, exit.
I found old v3 doc but nothing for v4.
Check the documentations provided here Handling User Interruption They explain how to handle user interruption for SDK v4
Find below an example of how you can configure this in the Virtual Assistant.
In your MainDialog.cs
Add the following for your OnContinueDialogAsync: Keeping in mind that you can change and edit this as you see fit just be sure to check the OnInterruptDialogAsync result (status in this example) before you continue
protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
var status = await OnInterruptDialogAsync(innerDc, cancellationToken).ConfigureAwait(false);
if (status == InterruptionAction.Resume)
{
// Resume the waiting dialog after interruption
await innerDc.RepromptDialogAsync().ConfigureAwait(false);
return EndOfTurn;
}
else if (status == InterruptionAction.Waiting)
{
// Stack is already waiting for a response, shelve inner stack
return EndOfTurn;
}
else
{
var activity = innerDc.Context.Activity;
if (activity.IsStartActivity())
{
await OnStartAsync(innerDc).ConfigureAwait(false);
}
switch (activity.Type)
{
case ActivityTypes.Message:
{
// Note: This check is a workaround for adaptive card buttons that should map to an event (i.e. startOnboarding button in intro card)
if (activity.Value != null)
{
await OnEventAsync(innerDc).ConfigureAwait(false);
}
else
{
var result = await innerDc.ContinueDialogAsync().ConfigureAwait(false);
switch (result.Status)
{
case DialogTurnStatus.Empty:
{
await RouteAsync(innerDc).ConfigureAwait(false);
break;
}
case DialogTurnStatus.Complete:
{
// End active dialog
await innerDc.EndDialogAsync().ConfigureAwait(false);
break;
}
default:
{
break;
}
}
}
// If the active dialog was ended on this turn (either on single-turn dialog, or on continueDialogAsync) run CompleteAsync method.
if (innerDc.ActiveDialog == null)
{
await CompleteAsync(innerDc).ConfigureAwait(false);
}
break;
}
case ActivityTypes.Event:
{
//do something for event activity
break;
}
case ActivityTypes.Invoke:
{
// Used by Teams for Authentication scenarios.
break;
}
default:
{
await OnSystemMessageAsync(innerDc).ConfigureAwait(false);
break;
}
}
return EndOfTurn;
}
}
And override OnInterruptDialogAsync like below example:
This example includes LUIS but you can do whatever you want in OnInterruptDialogAsync
protected override async Task<InterruptionAction> OnInterruptDialogAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
{
var result = InterruptionAction.NoAction;
if (dc.Context.Activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(dc.Context.Activity.Text))
{
// get current activity locale
var localeConfig = _services.GetCognitiveModels();
// check general luis intent
localeConfig.LuisServices.TryGetValue("General", out var luisService);
if (luisService == null)
{
throw new Exception("The specified LUIS Model could not be found in your Skill configuration.");
}
else
{
var luisResult = await luisService.RecognizeAsync<GeneralLuis>(dc.Context, cancellationToken);
var topIntent = luisResult.TopIntent();
if (topIntent.score > 0.5)
{
switch (topIntent.intent)
{
case GeneralLuis.Intent.Cancel:
{
result = await OnCancel(dc);
break;
}
case GeneralLuis.Intent.Help:
{
result = await OnHelp(dc);
break;
}
case GeneralLuis.Intent.Logout:
{
result = await OnLogout(dc);
break;
}
}
}
}
}
return result;
}

How can I authenticate a Windows Domain user from a .NET Core application running on Linux

Suppose I have a .NET Core console app that accepts a user name and password, the app is running on Linux. How can I validate that the user name and password are valid on a Windows domain controller (running on the same network as the Linux machine)?
Thanks to the suggestion from #gabriel-luci, I cobbled together this primitive example of using Novell.Directory.Ldap.NETStandard from others that I found.
using Novell.Directory.Ldap;
using System;
namespace ConsoleApp
{
class Program
{
static void Main()
{
Console.Write("Host: ");
var dc = Console.ReadLine();
Console.Write("Domain\\User: ");
var parts = Console.ReadLine().Split("\\");
var domain = parts[0];
var user = parts[1];
Console.Write("Password: ");
var pass = Console.ReadLine();
try
{
using (var ldap = new LdapConnection { SecureSocketLayer = false })
{
ldap.Connect(dc, LdapConnection.DefaultPort);
ldap.Bind($"{user}#{domain}", pass);
if (!ldap.Bound)
{
Console.Write("Not ");
}
Console.WriteLine("Valid");
}
}
catch (LdapException e)
{
Console.WriteLine(e.Message);
}
}
}
}
It worked just fine from win-x64 and linux-arm when I tested it against a Windows 2012 domain controller runningin a VM..

ZXing.Net.Mobile Sample.WindowsUniversal Sample Not Scanning

Testing this to incorporate into Win 10 UWP app to scan 1D barcodes (format 39 & 128). I have updated latest through nuget 2.0.4.46. Referenced post at http://www.yortondotnet.com/2015/07/mobile-barcode-scanning-with-zxingnet.html regarding some options setting prior to scan() with no luck. The scanner (camera) opens but never recognizes a barcode scan successfully - or failure for that matter. It seems nothing is happening whatsoever. I have included straight, pertinent sample code with some options modifications for review. I have gotten Scandit API to work and was going to try Manateeworks but both are really costly and not an option. I am developing on Surface Pro 3 (Win 10) and that build will also be target machines when complete.
public sealed partial class MainPage : Page
{
UIElement customOverlayElement = null;
MobileBarcodeScanner scanner;
public MainPage()
{
this.InitializeComponent();
//Create a new instance of our scanner
scanner = new MobileBarcodeScanner(this.Dispatcher);
scanner.Dispatcher = this.Dispatcher;
}
private void buttonScanDefault_Click(object sender, RoutedEventArgs e)
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of our default overlay
scanner.TopText = "Hold camera up to barcode";
scanner.BottomText = "Camera will automatically scan barcode\r\n\r\nPress the 'Back' button to Cancel";
// GWS Set Options
var options = new MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.CODE_128
};
options.AutoRotate = false;
options.TryHarder = false;
options.TryInverted = false;
//Start scanning
scanner.Scan(options).ContinueWith(t =>
{
if (t.Result != null)
HandleScanResult(t.Result);
});
}
private void buttonScanContinuously_Click(object sender, RoutedEventArgs e)
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of our default overlay
scanner.TopText = "Hold camera up to barcode";
scanner.BottomText = "Camera will automatically scan barcode\r\n\r\nPress the 'Back' button to Cancel";
// GWS Set Options
var options = new MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.CODE_128
};
options.AutoRotate = false;
options.TryHarder = false;
options.TryInverted = false;
//Start scanning
scanner.ScanContinuously(options, async (result) =>
{
var msg = "Found Barcode: " + result.Text;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
await MessageBox(msg);
});
});
}
async void HandleScanResult(ZXing.Result result)
{
string msg = "";
if (result != null && !string.IsNullOrEmpty(result.Text))
msg = "Found Barcode: " + result.Text;
else
msg = "Scanning Canceled!";
await MessageBox(msg);
}
}
Simon,
I have the exact same problem. I tested your code with the latest nuget 2.1.47, the problem still exists.
You need to download the latest from Github and add the following projects (or DLLs) to your project:
ZXing.Net (project: zxing.portable.csproj)
ZXing.Net.Mobile.Core
ZXing.Net.Mobile.WindowsUniversal
I have tested your code and it works fine. I hope this help.
Cheers,
Sam
I think that the problem in the hardware you are testing with. Surface Pro 3 (Win 10) does not have an auto focus camera. I've never succeed to scan with ZXing using my Surface Pro 3, while the same application is working fine with my other windows 10 device.

Resources