Tumgik
ben2code-blog · 7 years
Text
Create a Xamarin.Forms  Todo app with C#  backend  (part 3.2) : push notification
This tutorial shows you how to add a cloud-based backend service to a Xamarin.Forms mobile app using an Azure Mobile App backend. You will create both a new Mobile App backend and a simple Todo list Xamarin.Forms app that stores app data in Azure. part 3 of a cross platform mobile application using xamarin.forms
youtube
Configure and run the Android project (optional)
Enable Firebase Cloud Messaging (FCM)
Sign in to the Firebase console. Create a new Firebase project if you don't already have one.
After your project is created, click Add Firebase to your Android app and follow the instructions provided.
In the Firebase console, click the cog for your project and then click Project Settings.
Click the Cloud Messaging tab in your project settings, and copy the value of the Server key and Sender ID. These values will be used later to configure the notification hub access policy, and your notification handler in the app
Configure the Mobile Apps back end to send push requests by using FCM
in the Azure portal, click Browse All > App Services, and click your Mobile Apps back end. Under Settings, click App Service Push, and then click your notification hub name.
Go to Google (GCM), enter the FCM server key you obtained from the Firebase console, and then click Save
Your service is now configured to work with Firebase Cloud Messaging.
Add push notifications to the Android project
Add Google Cloud Messaging Client component
Open the MainActivity.cs project file, and add the following statement at the top of the file:
using Gcm.Client;
Add the following code to the OnCreate method after the call to LoadApplication:
try { // Check to ensure everything's set up right GcmClient.CheckDevice(this); GcmClient.CheckManifest(this); // Register for push notifications System.Diagnostics.Debug.WriteLine("Registering..."); GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS); } catch (Java.Net.MalformedURLException) { CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Error"); } catch (Exception e) { CreateAndShowDialog(e.Message, "Error"); }
Add a new CreateAndShowDialog helper method
private void CreateAndShowDialog(String message, String title) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetMessage (message); builder.SetTitle (title); builder.Create().Show (); }
Add a new CreateAndShowDialog helper method :
private void CreateAndShowDialog(String message, String title) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetMessage (message); builder.SetTitle (title); builder.Create().Show (); }
Add the following code to the MainActivity class:
// Create a new instance field for this activity. static MainActivity instance = null; // Return the current activity instance. public static MainActivity CurrentActivity { get { return instance; } }
After that initialize the instance variable at the beginning of the OnCreate method.
Add a new class file to the Droid project named GcmService.cs and add the following permission requests at the top of the file, after the using statements and before the namespace declaration :
[assembly: Permission(Name = "@[email protected]_MESSAGE")] [assembly: UsesPermission(Name = "@[email protected]_MESSAGE")] [assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")] [assembly: UsesPermission(Name = "android.permission.INTERNET")] [assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")] //GET_ACCOUNTS is only needed for android versions 4.0.3 and below [assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
Add the following class definition to the namespace :
[BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)] [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "@PACKAGE_NAME@" })] [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "@PACKAGE_NAME@" })] [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "@PACKAGE_NAME@" })] public class PushHandlerBroadcastReceiver : GcmBroadcastReceiverBase { public static string[] SENDER_IDS = new string[] { "" }; }
Replace the empty GcmService class with the following code :
[Service] public class GcmService : GcmServiceBase { public static string RegistrationID { get; private set; } public GcmService() : base(PushHandlerBroadcastReceiver.SENDER_IDS){} }
Add the following code to the GcmService class :
protected override void OnRegistered(Context context, string registrationId) { Log.Verbose("PushHandlerBroadcastReceiver", "GCM Registered: " + registrationId); RegistrationID = registrationId; var push = TodoItemManager.DefaultManager.CurrentClient.GetPush(); MainActivity.CurrentActivity.RunOnUiThread(() => Register(push, null)); } public async void Register(Microsoft.WindowsAzure.MobileServices.Push push, IEnumerable tags) { try { const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}"; JObject templates = new JObject(); templates["genericMessage"] = new JObject { {"body", templateBodyGCM} }; await push.RegisterAsync(RegistrationID, templates); Log.Info("Push Installation Id", push.InstallationId.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); Debugger.Break(); } } Note that this code uses the `messageParam` parameter in the template registration.
Add the following code that implements OnMessage:
protected override void OnMessage(Context context, Intent intent) { Log.Info("PushHandlerBroadcastReceiver", "GCM Message Received!"); var msg = new StringBuilder(); if (intent != null && intent.Extras != null) { foreach (var key in intent.Extras.KeySet()) msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString()); } //Store the message var prefs = GetSharedPreferences(context.PackageName, FileCreationMode.Private); var edit = prefs.Edit(); edit.PutString("last_msg", msg.ToString()); edit.Commit(); string message = intent.Extras.GetString("message"); if (!string.IsNullOrEmpty(message)) { createNotification("New todo item!", "Todo item: " + message); return; } string msg2 = intent.Extras.GetString("msg"); if (!string.IsNullOrEmpty(msg2)) { createNotification("New hub message!", msg2); return; } createNotification("Unknown message details", msg.ToString()); } void createNotification(string title, string desc) { //Create notification var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; //Create an intent to show ui var uiIntent = new Intent(this, typeof(MainActivity)); //Use Notification Builder NotificationCompat.Builder builder = new NotificationCompat.Builder(this); //Create the notification //we use the pending intent, passing our ui intent over which will get called //when the notification is tapped. var notification = builder.SetContentIntent(PendingIntent.GetActivity(this, 0, uiIntent, 0)) .SetSmallIcon(Android.Resource.Drawable.SymActionEmail) .SetTicker(title) .SetContentTitle(title) .SetContentText(desc) //Set the notification sound .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)) //Auto cancel will remove the notification once the user touches it .SetAutoCancel(true).Build(); //Show the notification notificationManager.Notify(1, notification); }
GcmServiceBase also requires you to implement the OnUnRegistered and OnError handler methods :
protected override void OnUnRegistered(Context context, string registrationId) { Log.Error("PushHandlerBroadcastReceiver", "Unregistered RegisterationId : " + registrationId); } protected override void OnError(Context context, string errorId) { Log.Error("PushHandlerBroadcastReceiver", "GCM Error: " + errorId); }
(adsbygoogle = window.adsbygoogle || []).push({});
0 notes
ben2code-blog · 7 years
Text
New Improvements of Xamarin In Visual Studio 2017
Deliver quality mobile apps
With Xamarin’s advanced debugging, profiling tools, and unit test generation features, it’s faster and easier than ever for you to build, connect, and tune native mobile apps for Android, iOS, and Windows. You can also choose to develop mobile apps with Apache Cordova or build C++ cross platform libraries.
Deliver software faster
Together with Visual Studio Team Services and Team Foundation Server, seamlessly deliver software to any targeted platform. Extend DevOps processes to SQL Server through Redgate integration and safely automate database deployments from Visual Studio. Xamarin Test Recorder, together with Xamarin test cloud let you test on thousands of physical devices right from within the IDE.
Xamarin Inspector
Visualize and debug your live app !!
The Inspector integrates with the app debugging workflow of your IDE, serving as a debugging or diagnostics aid when inspecting your running app. Live app inspection is available for enterprise customers. Let us know if you run into any bugs.
Mobile Center: Xamarin support, detailed app analytics, and more
Mobile Center works with you, wherever you are, and whatever your toolset. Any iOS or Android developer working in Objective-C, Swift, Java, or React Native or Xamarin, you can take advantage of everything we offer, from continuous integration to testing to release management and analytics.
Xamarin.Forms Previewer
With our latest release for Visual Studio and Visual Studio for Mac, we have made many enhancements to the Xamarin.Forms Previewer to increase the range of supported controls and XAML constructs. Additionally, with your feedback, we have been able to make the previewer much more reliable, including the initialization process. Be sure that you have the latest Java 1.8 x64 installed, as it is required for Android previewing.
Improved Xamarin.Forms XAML IntelliSense
Opening any Xamarin.Forms XAML document now provides a significantly improved IntelliSense experience in Visual Studio 2017. The new code completion engine supports bindings, custom properties, custom controls, converters, and much more. We know you are going to love it!
New & Updated Templatese
In this release, we created new templates for Visual Studio 2017 and Visual Studio for Mac to reflect this reality. By just clicking a few buttons, you can bootstrap your next mobile project with a mobile app for iOS, Android, and Windows 10 that includes tabbed navigation, MVVM, settings, and more. By clicking “Host in the cloud,” you can take your mobile project to the next level by provisioning a backend for your mobile app, complete with client-side code for online/offline synchronization and automatic conflict resolution.
Stay Tuned , we will publish More Updates soon
Download Visual Studio 2017 from here : https://goo.gl/eiZ2om
0 notes
ben2code-blog · 7 years
Text
Create a Xamarin.Forms  Todo app with C#  backend  (part 3.1) :push notification
This tutorial shows you how to add a cloud-based backend service to a Xamarin.Forms mobile app using an Azure Mobile App backend. You will create both a new Mobile App backend and a simple Todo list Xamarin.Forms app that stores app data in Azure. part 3 of a cross platform mobile application using xamarin.forms.
youtube
Adding push notification Configure a notification hub The Mobile Apps feature of Azure App Service uses Azure Notification Hubs to send pushes, so you will be configuring a notification hub for your mobile app.
In the Azure portal, go to App Services, and then click your app back end. Under Settings, click Push.
Click Connect to add a notification hub resource to the app. You can either create a hub or connect to an existing one.
Update the server project to send push notifications In this section, you update code in your existing Mobile Apps back-end project to send a push notification every time a new item is added
In Visual Studio, right-click the server project and click Manage NuGet Packages. Search for
Microsoft.Azure.NotificationHubs
, and then click Install. This installs the Notification Hubs library for sending notifications from your back end.
In the server project, open Controllers > TodoItemController.cs, and add the following using statements:
using System.Collections.Generic;
using Microsoft.Azure.NotificationHubs;
using Microsoft.Azure.Mobile.Server.Config;
In the PostTodoItem method, add the following code after the call to InsertAsync: get the settings for server project. httpconfiguration config="this.Configuration;" mobileappsettingsdictionary notification hubs credentials mobile app. string notificationhubname="settings.NotificationHubName;" notificationhubconnection="settings" .connections create a new hub client. notificationhubclient .createclientfromconnectionstring sending message so that all template registrations contain will receive notifications. this includes apns gcm wns and mpns registrations. dictionary> templateParams = new Dictionary(); templateParams["messageParam"] = item.Text + " was added to the list."; try { // Send the push notification and log the results. var result = await hub.SendTemplateNotificationAsync(templateParams); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); } the last step is to : Republish the server project
0 notes
ben2code-blog · 7 years
Text
Create a Xamarin.Forms  Todo app with C#  backend  (part2) : Authentication
This tutorial shows you how to add a cloud-based backend service to a Xamarin.Forms mobile app using an Azure Mobile App backend. You will create both a new Mobile App backend and a simple Todo list Xamarin.Forms app that stores app data in Azure.
part 2 of a cross platform mobile application using xamarin.forms.
youtube
Adding c# backend
1-Register your app for authentication and configure App Services
First, you need to register your app at an identity provider’s site, and then you will set the provider-generated credentials in the Mobile Apps back end .
Log on to the Azure portal, and navigate to your application. Copy your URL. You will use this to configure your Twitter app.
Navigate to the Twitter Developers website, sign in with your Twitter account credentials, and click Create New App.
Type in the Name and a Description for your new app. Paste in your application’s URL for the Website value. Then, for the Callback URL, paste the Callback URL you copied earlier , for callback add : /.auth/login/twitter/callback
Back in the Azure portal, navigate to your application. Click Settings, and then Authentication / Authorization.* If the Authentication / Authorization feature is not enabled, turn the switch to On.
Click Twitter. Paste in the App ID and App Secret values which you obtained previously. Then click OK. 2-Restrict permissions to authenticated users
In the server project, navigate to Controllers > TodoItemController.cs. Add the [Authorize] attribute to the TodoItemController class
3-Add authentication to the portable class library
In Visual Studio or Xamarin Studio, open App.cs from the project with Portable in the name, which is Portable Class Library project, then add "using System.Threading.Tasks;"
In App.cs, add the following IAuthenticate interface definition immediately before the App class definition.
add the following static members to the App class :
Open TodoList.xaml from the Portable Class Library project, add the following Button :
Open TodoList.xaml.cs from the Portable Class Library project, then add :bool authenticated = false;
Replace the OnAppearing method with the following code:
Add the following handler for the Clicked event :
1 note · View note
ben2code-blog · 7 years
Text
Create a Xamarin.Forms  Todo app with C#  backend (part1)
This tutorial shows you how to add a cloud-based backend service to a Xamarin.Forms mobile app using an Azure Mobile App backend. You will create both a new Mobile App backend and a simple Todo list Xamarin.Forms app that stores app data in Azure.
part 1 of a cross platform mobile application using xamarin.forms. Adding c# backend
youtube
0 notes
ben2code-blog · 7 years
Text
Get ready  !
Soon we are going to launch a serie of xamarin , asp.net and other cool stuff in my blog
0 notes