Visual Studio App Center Analytics Not working for Xamarin Forms Android Project - xamarin

I am using Visual Studio App Center for my Xamarin Forms Android Application for capturing the Analytics(Events and Crashes)
I am configuring crashes and analytics in OnStart of my App.Xaml.cs
AppCenter.Start($"android={Settings.Current.AppCenterAnalyticsAndroid};" +
typeof(Analytics), typeof(Crashes));
And for invoking the Events I am calling the below Method.
public void TrackEvent(string name, Dictionary<string, string> properties = null)
{
Analytics.SetEnabledAsync(true).ConfigureAwait(false);
Analytics.TrackEvent(name, properties);
}
Crashes are logging correctly in App Center But the events are not.
Also I can see the corresponding entries in Log Flow

Your app secret string is invalid because it contains + typeof(Analytics), it should be , typeof(Analytics).
Since you used the android key/value delimiter we could extract the appSecret and make it work with Crashes, but typeof(Analytics) ended up in the wrong appSecret parameter string.

You shouldn't need to add Analytics.SetEnabledAsync(true).ConfigureAwait(false);
Simply Call Analytics.TrackEvent(name, properties); (it doesn't need to be in a task anyways. I track my events in the Construtor of pages, for example.
Also, when you run the application, you get a debug Message confirming that AppCenter has been configured correctly, check if that is the case.
And, it may take a while, for them to appear in the Events.

Related

Need to store handled exceptions globally without calling the save log method inside Every catch in xamarin.forms

try
{
int c = 0;
int a = 5 / c;
}
catch (Exception ex)
{
}
Need to write Handled Exceptions globally in one place and without calling the errorlog method in each and every catch block in xamarin.forms and expect to get details in mainactivity for android and appdelegate for ios or any comman place in xamarin.forms
In your case you could use App Center . App Center Crashes will automatically generate a crash log every time your app crashes. The log is first written to the device's storage and when the user starts the app again, the crash report will be sent to App Center. Collecting crashes works for both beta and live apps, i.e. those submitted to the App Store. Crash logs contain valuable information for you to help fix the crash.
App Center Crashes provides you with an API to generate a test crash for easy testing of the SDK. This API checks for debug vs release configurations. So you can only use it when debugging as it won't work for release apps.
Crashes.GenerateTestCrash();
If your app crashed previously, you can get details about the last crash.
ErrorReport crashReport = await Crashes.GetLastSessionCrashReportAsync();
Set this callback if you want to decide if a particular crash needs to be processed or not. For example, there could be a system level crash that you'd want to ignore and that you don't want to send to App Center.
Crashes.ShouldProcessErrorReport = (ErrorReport report) =>
{
// Check the report in here and return true or false depending on the ErrorReport.
return true;
};
For more details about App Center you could check Get Started with Xamarin .

Logging via TraceSource in Xamarin (UWP)

I just want to log to console and to a log file, using a standard TraceSource, in my Xamarin app that will run on UWP, Mac OS X, iOS and Android. I'm developing/debugging on UWP.
TraceSource, TraceListener, and TextWriterTraceListener are indeed all available in .Net Standard library, so perhaps I'm setting it up incorrectly? Most places on the Internet insist on setting up trace listeners in an app.config file, but this is not applicable nor possible for Xamarin apps. So here is my logging initialization code, mostly based on an example in Microsoft docs:
private void SetupLogging()
{
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out, "consoleTraceListener"));
string logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Application.log");
if (!File.Exists(logFilePath)) File.Create(logFilePath);
var logFileTraceListener = new TextWriterTraceListener(logFilePath, "logFileTraceListener");
Trace.Listeners.Add(logFileTraceListener);
Trace.Write("Test");
Trace.TraceInformation("Logging Initialized. Log file location: " + logFilePath);
Trace.Flush();
}
When I run this in a Xamarin UWP app, a file is created but nothing is written to it, nor can I find anything in the Output of the program (there is no ConsoleTraceListener so I'm trying to write a TextWriterTraceListener to Console.Out). Can someone provide a working example for Xamarin? (I haven't tried the Android or iOS apps yet; want to get UWP on the local machine working first.)
The problem is that you passed wrong string parameter to TextWriterTraceListener method. Please try to pass Stream parameter. You could use following code directly. by the way, you'd better use LocalApplicationData SpecialFolder that could be accessed successfully within uwp.
private void SetupLogging()
{
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out, "consoleTraceListener"));
string logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Application.log");
if (!File.Exists(logFilePath))
{
File.Create(logFilePath);
}
var logFileTraceListener = new TextWriterTraceListener(File.Open(logFilePath,FileMode.Open), "logFileTraceListener");
Trace.Listeners.Add(logFileTraceListener);
Trace.Write("Test");
Trace.TraceInformation("Logging Initialized. Log file location: " + logFilePath);
Trace.Flush();
}

How do I deal with a possible exception in a Xamarin Forms application deployed to iOS or Android?

I have a finished application which I would like to make available to run on the iOS and Android platforms.  I have tested the application as much as possible and it works without problem.  But I know there is always the chance that something might go wrong and I could get an exception.
My question is how can I deal with this or what should I do. What happens on the phone, if a Forms application is deployed and there is an exception.
Would appreciate any advice or even links as to how this is handled.
If an exception is thrown and not handled by your code, the app will stop working (i.e. crash).
In order to handle these crashes we are using MS AppCenter (the successor to HockeyApp/Xamarin AppInsights).
You'll have to create a project there (one for each platform), and add the NuGet package to your projects. Afterwards you can initialize it with
AppCenter.Start("ios={Your App Secret};android={Your App Secret}",
typeof(Crashes)); // you'll get the app secrets from appcenter.ms
Crashes will be logged to AppCenter now and you'll be informed whenever there is a new crash.
Please note that it's best practice (if not required by law), that you ask the user for consent before sending the crash report (see here). You are using the delegate Crashes.ShouldAwaitUserConfirmation for that matter. You could for example show an action sheet with Acr.UserDialogs
private bool AwaitUserConfirmation()
{
// you should of course use your own strings
UserDialogs.Instance.ActionSheet(
new ActionSheetConfig
{
Title = "Oopsie",
Message = "The app crashed. Send crash to developers.",
Options = new List<ActionSheetOption>
{
new ActionSheetOption("Sure", () => Crashes.NotifyUserConfirmation(UserConfirmation.Send)),
new ActionSheetOption("Yepp, and don't bug be again.", () => Crashes.NotifyUserConfirmation(UserConfirmation.AlwaysSend)),
new ActionSheetOption("Nope", () => Crashes.NotifyUserConfirmation(UserConfirmation.DontSend))
}
});
return true;
}

Xamarin Forms - How to open specific page after clicking on notification when the app is closed?

I'm actually working on a Xamarin Forms application that need push notifications. I use the Plugin.PushNotification plugin.
When the app is running in the foreground or is sleeping (OnSleep), I have no problem to open a specific page when I click on a notification that I receive. But I was wondering how can I do that when the app is closed. Thanks!
I finally found the answer by myself and I want to share it in case someone needs it.
Nota bene: according to the official documentation of the plugin, it's Xam.Plugin.PushNotification that is deprecated. I use the new version of this plugin, Plugin.PushNotification which uses FCM for Android and APS for iOS.
There is no significant differences to open a notif when the app is running, is sleeping or is closed. Just add the next callback method in the OnCreate method (MyProject.Droid > MainApplication > OnCreate) and FinishedLaunching method (MyProject.iOS > AppDelegate > FinishedLaunching):
CrossPushNotification.Current.OnNotificationOpened += (s, p) =>
{
// manage your notification here with p.Data
App.NotifManager.ManageNotif(p.Data);
};
Common part
App.xaml.cs
// Static fields
// *************************************
public static NotifManager NotifManager;
// Constructor
// *************************************
public App()
{
...
NotifManager = new NotifManager();
...
}
NotifManager.cs
public class NotifManager
{
// Methods
// *************************************
public void ManageNotif(IDictionary<string, object> data)
{
// 1) switch between the different data[key] you have in your project and parse the data you need
// 2) pass data to the view with a MessagingCenter or an event
}
}
Unfortunately there is no succinct answer for either platform. Generally speaking, you need to tell the OS what to do when it starts the app as a result of the push notification. On both platforms, you should also consider what API level you are targeting, otherwise it won't work or even crash the app.
On iOS, you will need to implement this method in AppDelegate appropriately: FinishedLaunching(UIApplication application, NSDictionary launchOptions). The launchOptions will have the payload from the push notification for you to determine what to do with it (e.g. what page to open). For more information on iOS, Xamarin's documentation is a good place to start.
Android has a more complicated topology in terms of more drastic differences between API levels, whether you are using GCM/FCM, as well as requiring more code components. However, to answer the question directly, you will need to handle this in OnCreate(Bundle savedInstanceState) of your main Activity. If you are using Firebase, the push notification payload is available in Intent.Extras. Again, Xamarin's documentation has a good walkthrough.
Finally, note that the Plugin.PushNotification library you are using has been deprecated. I suggest you either change your library and/or your implementation soon. Part of the reason that library has been deprecated is because Google has deprecated the underlying Google Cloud Messaging (GCM) service, which will be decommissioned on April 11, 2019.

Change Parse Application when App is running

I have an Android Application that works with locals instalations and I want use it with diferents Parse applications. Each instalation administrator will contract with Parse directly. When app start it will look for the keys for parse.
I wonder how to change the Parse App linkeded in the Android App once this is running
I have tried to call Parse.initialize (context, apllicationId, clientKey) twice but it doesn't work. I have tried the app register in diferent Parse App every time you start the App link with a different Parse App
It´s always linked only with the first application
public void onCreate(final Bundle icicle){
super.onCreate(icicle);
final Context context = this;
setContentView(R.layout.ssa);
getActionBar().hide();
// Getting the global variables
fmGlobalsBean = Utilities.getGlobals(this);
if(!"".equals(fmGlobalsBean.getUrl_server())){
Parse.initialize(contexto, "p4IWkTRc0WTdKkMH6r60hjYzwX1TIXChy8VcDvPb", "KhkcX4G3dqVpRawHyIYfnHAWqj1H2vyhwD3wINlQ");
ParseInstallation.getCurrentInstallation().saveInBackground();
ParsePush.subscribeInBackground(fmGlobalsBean.getUrl_server());
}
else
{
Parse.initialize(this, "Y3xgZ58u4Qcn9TrovFqCOe4PBzhURjXooZ3vDKgB", "ealo3nm4wa4lbJ7KrSR2OSf60DZiUjEUjdUJTQzs");
ParseInstallation.getCurrentInstallation().saveInBackground();
ParsePush.subscribeInBackground("INITIAL");
}
}

Resources