Example #1
0
        protected override void OnStart()
        {
            if (!AppCenter.Configured)
            {
                AppCenterLog.Assert(LogTag, "AppCenter.LogLevel=" + AppCenter.LogLevel);
                AppCenter.LogLevel = LogLevel.Verbose;
                AppCenterLog.Info(LogTag, "AppCenter.LogLevel=" + AppCenter.LogLevel);
                AppCenterLog.Info(LogTag, "AppCenter.Configured=" + AppCenter.Configured);

                // Set callbacks
                Crashes.ShouldProcessErrorReport    = ShouldProcess;
                Crashes.ShouldAwaitUserConfirmation = ConfirmationHandler;
                Crashes.GetErrorAttachments         = GetErrorAttachmentsCallback;
                Distribute.ReleaseAvailable         = OnReleaseAvailable;

                // Event handlers
                Crashes.SendingErrorReport      += SendingErrorReportHandler;
                Crashes.SentErrorReport         += SentErrorReportHandler;
                Crashes.FailedToSendErrorReport += FailedToSendErrorReportHandler;
                Push.PushNotificationReceived   += PrintNotification;

                AppCenterLog.Assert(LogTag, "AppCenter.Configured=" + AppCenter.Configured);

                if (!StartType.OneCollector.Equals(StartTypeUtils.GetPersistedStartType()))
                {
                    AppCenter.SetLogUrl("https://in-integration.dev.avalanch.es");
                }

                Distribute.SetInstallUrl("https://install.portal-server-core-integration.dev.avalanch.es");
                Distribute.SetApiUrl("https://api-gateway-core-integration.dev.avalanch.es/v0.1");
                var updateTrack = TrackUpdateUtils.GetPersistedUpdateTrack();
                if (updateTrack != null)
                {
                    Distribute.UpdateTrack = updateTrack.Value;
                }
                if (Current.Properties.TryGetValue(Constants.AutomaticUpdateCheckKey, out object persistedObject) && !(bool)persistedObject)
                {
                    Distribute.DisableAutomaticCheckForUpdate();
                }
                AppCenter.Start(GetTokensString(), typeof(Analytics), typeof(Crashes), typeof(Distribute));
                if (Current.Properties.ContainsKey(Constants.UserId) && Current.Properties[Constants.UserId] is string id)
                {
                    AppCenter.SetUserId(id);
                }

                // Work around for SetUserId race condition.
                AppCenter.Start(typeof(Push));
                AppCenter.IsEnabledAsync().ContinueWith(enabled =>
                {
                    AppCenterLog.Info(LogTag, "AppCenter.Enabled=" + enabled.Result);
                });
                AppCenter.GetInstallIdAsync().ContinueWith(installId =>
                {
                    AppCenterLog.Info(LogTag, "AppCenter.InstallId=" + installId.Result);
                });
                AppCenterLog.Info(LogTag, "AppCenter.SdkVersion=" + AppCenter.SdkVersion);
                Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
                {
                    AppCenterLog.Info(LogTag, "Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
                });
                Crashes.GetLastSessionCrashReportAsync().ContinueWith(task =>
                {
                    AppCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.StackTrace=" + task.Result?.StackTrace);
                });
            }
        }
Example #2
0
 static void SentErrorReportHandler(object sender, SentErrorReportEventArgs e)
 {
     AppCenterLog.Info(LogTag, "Sent error report");
 }
Example #3
0
 static void FailedToSendErrorReportHandler(object sender, FailedToSendErrorReportEventArgs e)
 {
     AppCenterLog.Info(LogTag, "Failed to send error report");
 }
Example #4
0
 public override void DidFailSendingEventLog(MSAnalytics analytics, MSEventLog eventLog, NSError error)
 {
     AppCenterLog.Debug(App.LogTag, "Failed to send event with error: " + error);
 }
        protected override void OnStart()
        {
            if (!AppCenter.Configured)
            {
                AppCenterLog.Assert(LogTag, "AppCenter.LogLevel=" + AppCenter.LogLevel);
                AppCenter.LogLevel = LogLevel.Verbose;
                AppCenterLog.Info(LogTag, "AppCenter.LogLevel=" + AppCenter.LogLevel);
                AppCenterLog.Info(LogTag, "AppCenter.Configured=" + AppCenter.Configured);

                // Set callbacks
                Crashes.ShouldProcessErrorReport    = ShouldProcess;
                Crashes.ShouldAwaitUserConfirmation = ConfirmationHandler;
                Crashes.GetErrorAttachments         = GetErrorAttachmentsCallback;
                Distribute.ReleaseAvailable         = OnReleaseAvailable;
                Distribute.WillExitApp        = OnWillExitApp;
                Distribute.NoReleaseAvailable = OnNoReleaseAvailable;

                // Event handlers
                Crashes.SendingErrorReport      += SendingErrorReportHandler;
                Crashes.SentErrorReport         += SentErrorReportHandler;
                Crashes.FailedToSendErrorReport += FailedToSendErrorReportHandler;

                AppCenterLog.Assert(LogTag, "AppCenter.Configured=" + AppCenter.Configured);

                var updateTrack = TrackUpdateUtils.GetPersistedUpdateTrack();
                if (updateTrack != null)
                {
                    Distribute.UpdateTrack = updateTrack.Value;
                }
                if (Current.Properties.TryGetValue(Constants.AutomaticUpdateCheckKey, out object persistedObject) && !(bool)persistedObject)
                {
                    Distribute.DisableAutomaticCheckForUpdate();
                }
                if (Current.Properties.ContainsKey(Constants.StorageMaxSize) && Current.Properties[Constants.StorageMaxSize] is long size)
                {
                    AppCenter.SetMaxStorageSizeAsync(size);
                }
                AppCenter.Start(GetTokensString(), typeof(Analytics), typeof(Crashes), typeof(Distribute));
                if (Current.Properties.ContainsKey(Constants.UserId) && Current.Properties[Constants.UserId] is string id)
                {
                    AppCenter.SetUserId(id);
                }
                AppCenter.IsEnabledAsync().ContinueWith(enabled =>
                {
                    AppCenterLog.Info(LogTag, "AppCenter.Enabled=" + enabled.Result);
                });
                AppCenter.GetInstallIdAsync().ContinueWith(installId =>
                {
                    AppCenterLog.Info(LogTag, "AppCenter.InstallId=" + installId.Result);
                });
                AppCenterLog.Info(LogTag, "AppCenter.SdkVersion=" + AppCenter.SdkVersion);
                Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
                {
                    AppCenterLog.Info(LogTag, "Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
                });
                Crashes.GetLastSessionCrashReportAsync().ContinueWith(task =>
                {
                    AppCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.StackTrace=" + task.Result?.StackTrace);
                });
            }
        }
Example #6
0
 bool ShouldProcess(ErrorReport report)
 {
     AppCenterLog.Info(LogTag, "Determining whether to process error report");
     return(true);
 }
Example #7
0
 public override void WillSendEventLog(MSAnalytics analytics, MSEventLog eventLog)
 {
     AppCenterLog.Debug(App.LogTag, "Will send event");
 }
Example #8
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get the ViewPager and set it's PagerAdapter so that it can display items
            var viewPager = FindViewById(Resource.Id.viewpager) as ViewPager;

            viewPager.Adapter = new PagerAdapter(SupportFragmentManager, this);

            // Give the TabLayout the ViewPager
            var tabLayout = FindViewById(Resource.Id.tablayout) as TabLayout;

            tabLayout.SetupWithViewPager(viewPager);

            // App Center integration
            AppCenterLog.Assert(LogTag, "AppCenter.LogLevel=" + AppCenter.LogLevel);
            AppCenter.LogLevel = LogLevel.Verbose;
            AppCenterLog.Info(LogTag, "AppCenter.LogLevel=" + AppCenter.LogLevel);
            AppCenterLog.Info(LogTag, "AppCenter.Configured=" + AppCenter.Configured);

            // Set event handlers
            Crashes.SendingErrorReport      += SendingErrorReportHandler;
            Crashes.SentErrorReport         += SentErrorReportHandler;
            Crashes.FailedToSendErrorReport += FailedToSendErrorReportHandler;
            // Set callbacks
            Crashes.ShouldProcessErrorReport    = ShouldProcess;
            Crashes.ShouldAwaitUserConfirmation = ConfirmationHandler;

            Distribute.ReleaseAvailable   = OnReleaseAvailable;
            Distribute.NoReleaseAvailable = OnNoReleaseAvailable;
            AppCenterLog.Assert(LogTag, "AppCenter.Configured=" + AppCenter.Configured);
            AppCenter.SetLogUrl("https://in-integration.dev.avalanch.es");
            var prefs            = GetSharedPreferences("AppCenter", FileCreationMode.Private);
            var storageSizeValue = prefs.GetLong(Constants.StorageSizeKey, 0);

            if (storageSizeValue > 0)
            {
                AppCenter.SetMaxStorageSizeAsync(storageSizeValue);
            }
            Distribute.SetInstallUrl("https://install.portal-server-core-integration.dev.avalanch.es");
            Distribute.SetApiUrl("https://asgard-int.trafficmanager.net/api/v0.1");
            AppCenter.Start("bff0949b-7970-439d-9745-92cdc59b10fe", typeof(Analytics), typeof(Crashes), typeof(Distribute));
            AppCenter.IsEnabledAsync().ContinueWith(enabled =>
            {
                AppCenterLog.Info(LogTag, "AppCenter.Enabled=" + enabled.Result);
            });
            AppCenter.GetInstallIdAsync().ContinueWith(installId =>
            {
                AppCenterLog.Info(LogTag, "AppCenter.InstallId=" + installId.Result);
            });
            Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
            {
                AppCenterLog.Info(LogTag, "Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
            });
            Crashes.GetLastSessionCrashReportAsync().ContinueWith(report =>
            {
                AppCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.DotNetStackTrace=" + report.Result?.StackTrace);
                AppCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.JavaStackTrace=" + report.Result?.AndroidDetails?.StackTrace);
            });
        }
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();

            Title       = "My Cart";
            restActions = new RestActions();
            _minprice   = UserSession.MinPrice();
            var bounds = UIScreen.MainScreen.Bounds;

            if (_unpaidOrder == false)
            {
                _loadingOverlay = new LoadingOverlay(bounds, "Refreshing Cart...");
                View.Add(_loadingOverlay);
                cartItemList = await LoadCartItems(UserSession.GetUserId());

                _loadingOverlay.Hide(0);
            }

            _loadingOverlay = new LoadingOverlay(bounds, "Loading Locations and Delivery times...");
            View.Add(_loadingOverlay);
            locationStingList = await LoadLocationList();

            deliveryTimeList = await LoadDeliveryTimeList();

            _loadingOverlay.Hide();


#pragma warning disable 618
            _deliveryAddressActionSheet = new UIActionSheet("Select Delivery Address", null, cancelTitle: "Cancel", destroy: null, other: locationStingList);

            _deliveryTimeActionSheet = new UIActionSheet("Select Delivery Time", null, cancelTitle: "Cancel", destroy: null, other: deliveryTimeList);
#pragma warning restore 618

            //set minimum date
            DateTime date = DateTime.Now;
            currentNsDate = (NSDate)DateTime.SpecifyKind(date, DateTimeKind.Utc);
            deliveryDate  = currentNsDate.ToString(); //set as default date
            if (_unpaidOrder)
            {
                deliveryDate = _order.ORDER_DATE_TIME.ToString("dd/MM/yyyy"); //"09:35:37"

                deliveryTime = _order.ORDER_TIME;

                deliveryLocation    = _order.LOCATION.LOCATION_NAME;
                _selectedLocationId = _order.LOCATION_ID;

                NSDate orderNsDate = (NSDate)DateTime.SpecifyKind(_order.ORDER_DATE_TIME, DateTimeKind.Utc);
                ;

                //set the current values

                BtnDeliveryAddress.SetTitle(deliveryLocation, UIControlState.Normal);
                BtnDeliveryTime.SetTitle(deliveryTime, UIControlState.Normal);
                deliveryDatePicker.SetDate(orderNsDate, true);
                deliveryDatePicker.MaximumDate = orderNsDate;

                //btnViewItems.Hidden = true;
            }



            /*btnViewItems.TouchUpInside += (e, s) =>
             * {
             *  // create the view controller for your initial view - using storyboard, code, etc
             *  CartItemsViewController cartItemsViewController = this.Storyboard.InstantiateViewController(controllerName) as CartItemsViewController;
             *  if (cartItemsViewController != null)
             *  {
             *      cartItemsViewController.SetCartItems(cartItemList);
             *      NavigationController.PushViewController(cartItemsViewController, true);
             *  }
             * };*/

            BtnDeliveryAddress.TouchUpInside += (e, s) => { _deliveryAddressActionSheet.ShowInView(View); };

            BtnDeliveryTime.TouchUpInside += (e, s) => { _deliveryTimeActionSheet.ShowInView(View); };

            deliveryDatePicker.ValueChanged += (e, s) =>
            {
                deliveryDatePicker.MinimumDate = currentNsDate; //set minimum date to current date
                deliveryDate = deliveryDatePicker.Date.ToString();
            };

            _deliveryAddressActionSheet.Clicked += (btn_sender, args) =>
            {
                try
                {
                    if (args.ButtonIndex >= 0)
                    {
                        var selectedIndex = args.ButtonIndex;

                        deliveryLocation = locationStingList[selectedIndex];

                        BtnDeliveryAddress.SetTitle(deliveryLocation, UIControlState.Normal);

                        _selectedLocationId = GetLocationId(locationList, deliveryLocation);
                    }

                    Console.WriteLine("{0} Clicked", args.ButtonIndex);
                }
                catch (Exception e)
                {
                    AppCenterLog.Error("ERROR", e.Message, e);
                }
            };

            _deliveryTimeActionSheet.Clicked += (btn_sender, args) =>
            {
                try
                {
                    if (args.ButtonIndex >= 0)
                    {
                        var selectedIndex = args.ButtonIndex;

                        deliveryTime = deliveryTimeList[selectedIndex];
                        BtnDeliveryTime.SetTitle(deliveryTime, UIControlState.Normal);
                    }

                    Console.WriteLine("{0} Clicked", args.ButtonIndex);
                }
                catch (Exception e)
                {
                    AppCenterLog.Error("ERROR", e.Message, e);
                }
            };

            BtnPay.TouchUpInside += async(e, s) =>
            {
                //let us validate the data
                if (IsLocationSelected() && IsTimeSelected() && IsDateSelected())
                {
                    //check minimum purchase price
                    if (_total >= _minprice)
                    {
                        //create new order
                        if (_unpaidOrder)
                        {
                            //let us update the order and proceed
                            OpenCheckout(_order);
                        }
                        else
                        {
                            await CreateOrderFromCart();
                        }
                    }
                    else
                    {
                        var least = _minprice.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));
                        MessagingActions.ShowAlert("Minimum Price",
                                                   $"Please make a purchase of at least {least} to be eligible for delivery");
                    }
                }
                else
                {
                    MessagingActions.ShowAlert("Incomplete Info", "Ensure delivery location,date and time are specified");
                }
            };
        }
        async void RunMBaaSAsync(object sender, EventArgs e)
        {
            try
            {
                userInfo = await Auth.SignInAsync();

                if (userInfo.AccountId != null)
                {
                    Application.Current.Properties[AccountId] = userInfo.AccountId;
                    SignInInformationButton.Text = "User authenticated";
                }
                AppCenterLog.Info(App.LogTag, "Auth.SignInAsync succeeded accountId=" + userInfo.AccountId);
            }
            catch (Exception ex)
            {
                AppCenterLog.Error(App.LogTag, "Auth scenario failed", ex);
                Crashes.TrackError(ex);
            }
            try
            {
                var list = await Data.ListAsync <CustomDocument>(DefaultPartitions.UserDocuments);

                foreach (var doc in list)
                {
                    AppCenterLog.Info(App.LogTag, "List result=" + JsonConvert.SerializeObject(doc));
                }
                var document = list.CurrentPage.Items.First();
                AppCenterLog.Info(App.LogTag, "List first result=" + JsonConvert.SerializeObject(document));
                document = await Data.DeleteAsync <CustomDocument>(document.Id, DefaultPartitions.UserDocuments);

                AppCenterLog.Info(App.LogTag, "Delete result=" + JsonConvert.SerializeObject(document));
            }
            catch (Exception ex)
            {
                AppCenterLog.Error(App.LogTag, "Data list/delete first scenario failed", ex);
                Crashes.TrackError(ex);
            }
            try
            {
                var objectCollection = new List <Uri>();
                objectCollection.Add(new Uri("http://google.com/"));
                objectCollection.Add(new Uri("http://microsoft.com/"));
                objectCollection.Add(new Uri("http://facebook.com/"));
                var primitiveCollection = new List <int>();
                primitiveCollection.Add(1);
                primitiveCollection.Add(2);
                primitiveCollection.Add(3);
                var dict = new Dictionary <string, Uri>();
                dict.Add("key1", new Uri("http://google.com/"));
                dict.Add("key2", new Uri("http://microsoft.com/"));
                dict.Add("key3", new Uri("http://facebook.com/"));
                var customDoc = new CustomDocument
                {
                    Id                 = Guid.NewGuid(),
                    TimeStamp          = DateTime.UtcNow,
                    SomeNumber         = 123,
                    SomeObject         = dict,
                    SomePrimitiveArray = new int[] { 1, 2, 3 },
                    SomeObjectArray    = new CustomDocument[] {
                        new CustomDocument {
                            Id                      = Guid.NewGuid(),
                            TimeStamp               = DateTime.UtcNow,
                            SomeNumber              = 123,
                            SomeObject              = dict,
                            SomePrimitiveArray      = new int[] { 1, 2, 3 },
                            SomeObjectCollection    = objectCollection,
                            SomePrimitiveCollection = primitiveCollection
                        }
                    },
                    SomeObjectCollection    = objectCollection,
                    SomePrimitiveCollection = primitiveCollection,
                    Custom = new CustomDocument
                    {
                        Id                      = Guid.NewGuid(),
                        TimeStamp               = DateTime.UtcNow,
                        SomeNumber              = 123,
                        SomeObject              = dict,
                        SomePrimitiveArray      = new int[] { 1, 2, 3 },
                        SomeObjectCollection    = objectCollection,
                        SomePrimitiveCollection = primitiveCollection
                    }
                };
                var id       = customDoc.Id.ToString();
                var document = await Data.ReplaceAsync(id, customDoc, DefaultPartitions.UserDocuments);

                AppCenterLog.Info(App.LogTag, "Replace result=" + JsonConvert.SerializeObject(document));
                document = await Data.ReadAsync <CustomDocument>(id, DefaultPartitions.UserDocuments);

                AppCenterLog.Info(App.LogTag, "Read result=" + JsonConvert.SerializeObject(document));
            }
            catch (Exception ex)
            {
                AppCenterLog.Error(App.LogTag, "Data person scenario failed", ex);
                Crashes.TrackError(ex);
            }
        }
Example #11
0
 void OnNoReleaseAvailable()
 {
     AppCenterLog.Info(LogTag, "No release available callback invoked.");
 }
Example #12
0
        /// <summary>
        /// Asynchronously retrieves logs from storage and flags them to avoid duplicate retrievals on subsequent calls
        /// </summary>
        /// <param name="channelName">Name of the channel to retrieve logs from</param>
        /// <param name="limit">The maximum number of logs to retrieve</param>
        /// <param name="logs">A list to which the retrieved logs will be added</param>
        /// <returns>A batch ID for the set of returned logs; null if no logs are found</returns>
        /// <exception cref="StorageException"/>
        public async Task <string> GetLogsAsync(string channelName, int limit, List <Log> logs)
        {
            var task = new Task <string>(() =>
            {
                logs?.Clear();
                var retrievedLogs = new List <Log>();
                AppCenterLog.Debug(AppCenterLog.LogTag,
                                   $"Trying to get up to {limit} logs from storage for {channelName}");
                var idPairs = new List <Tuple <Guid?, long> >();
                var failedToDeserializeALog = false;
                var retrievedEntries        =
                    _storageAdapter.GetAsync <LogEntry>(entry => entry.Channel == channelName, limit)
                    .Result;
                foreach (var entry in retrievedEntries)
                {
                    if (_pendingDbIdentifiers.Contains(entry.Id))
                    {
                        continue;
                    }
                    try
                    {
                        var log = LogSerializer.DeserializeLog(entry.Log);
                        retrievedLogs.Add(log);
                        idPairs.Add(Tuple.Create(log.Sid, Convert.ToInt64(entry.Id)));
                    }
                    catch (JsonException e)
                    {
                        AppCenterLog.Error(AppCenterLog.LogTag, "Cannot deserialize a log in storage", e);
                        failedToDeserializeALog = true;
                        _storageAdapter.DeleteAsync <LogEntry>(row => row.Id == entry.Id)
                        .Wait();
                    }
                }
                if (failedToDeserializeALog)
                {
                    AppCenterLog.Warn(AppCenterLog.LogTag, "Deleted logs that could not be deserialized");
                }
                if (idPairs.Count == 0)
                {
                    AppCenterLog.Debug(AppCenterLog.LogTag,
                                       $"No available logs in storage for channel '{channelName}'");
                    return(null);
                }

                // Process the results
                var batchId = Guid.NewGuid().ToString();
                ProcessLogIds(channelName, batchId, idPairs);
                logs?.AddRange(retrievedLogs);
                return(batchId);
            });

            try
            {
                _queue.Add(task);
            }
            catch (InvalidOperationException)
            {
                throw new StorageException("The operation has been cancelled");
            }

            _flushSemaphore.Release();
            return(await task.ConfigureAwait(false));
        }
 void OnWillExitApp()
 {
     AppCenterLog.Info(LogTag, "App will close callback invoked.");
 }
Example #14
0
 static PlatformCrashes()
 {
     AppCenterLog.Info(Crashes.LogTag, "Set up Xamarin crash handler.");
     AndroidEnvironment.UnhandledExceptionRaiser += OnUnhandledException;
 }
 public Task WaitStorageOperationsAsync()
 {
     ThrowIfDisposed();
     AppCenterLog.Debug(AppCenterLog.LogTag, "Waiting for storage to finish operations.");
     return(_storage.WaitOperationsAsync(WaitStorageTimeout));
 }
 public void OnSendingFailed(ILog log, Java.Lang.Exception e)
 {
     AppCenterLog.Debug(App.LogTag, "Analytics listener OnSendingFailed with exception: " + e);
 }
Example #17
0
 static Crashes()
 {
     AppCenterLog.Info(LogTag, "Set up Xamarin crash handler.");
     AndroidEnvironment.UnhandledExceptionRaiser += OnUnhandledException;
     AndroidCrashes.SetListener(new AndroidCrashListener());
 }
 public void OnSendingSucceeded(ILog log)
 {
     AppCenterLog.Debug(App.LogTag, "Analytics listener OnSendingSucceeded");
 }
Example #19
0
        private void InitializeAppCenter()
        {
            // TODO: Add implementation here.

            if (!AppCenter.Configured)
            {
                Crashes.SendingErrorReport += (sender, e) =>
                {
                    string message = "Sending error report";
                    AppCenterLog.Info(Settings.AppName, message);

                    var         args   = e as SendingErrorReportEventArgs;
                    ErrorReport report = args.Report;

                    if (report.Exception != null)
                    {
                        AppCenterLog.Info(Settings.AppName, report.Exception.ToString());
                    }
                    else if (report.AndroidDetails != null)
                    {
                        AppCenterLog.Info(Settings.AppName, report.AndroidDetails.ThreadName);
                    }

                    // Show modal page displaying status of crash report.
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        Tuple <string, bool> values  = new Tuple <string, bool>(message, true);
                        FreshBasePageModel pageModel = GetCurrentPageModel();
                        pageModel.CoreMethods.PushPageModel <ModalActivityViewModel>(values, true);
                    });
                };

                Crashes.SentErrorReport += (sender, e) =>
                {
                    AppCenterLog.Info(Settings.AppName, "Sent error report");

                    var         args   = e as SentErrorReportEventArgs;
                    ErrorReport report = args.Report;

                    if (report.Exception != null)
                    {
                        AppCenterLog.Info(Settings.AppName, report.Exception.ToString());
                    }
                    else
                    {
                        AppCenterLog.Info(Settings.AppName, "No system exception was found");
                    }

                    if (report.AndroidDetails != null)
                    {
                        AppCenterLog.Info(Settings.AppName, report.AndroidDetails.ThreadName);
                    }
                };

                Crashes.FailedToSendErrorReport += (sender, e) =>
                {
                    string message = "Failed to send error report.  Please check your internet connection.";
                    AppCenterLog.Info(Settings.AppName, message);

                    var         args   = e as FailedToSendErrorReportEventArgs;
                    ErrorReport report = args.Report;

                    if (report.Exception != null)
                    {
                        AppCenterLog.Info(Settings.AppName, report.Exception.ToString());
                    }
                    else if (report.AndroidDetails != null)
                    {
                        AppCenterLog.Info(Settings.AppName, report.AndroidDetails.ThreadName);
                    }

                    if (e.Exception != null)
                    {
                        AppCenterLog.Info(Settings.AppName, "There is an exception associated with the failure");
                    }

                    // Show modal page displaying status of crash report.
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        Tuple <string, bool> values  = new Tuple <string, bool>(message, false);
                        FreshBasePageModel pageModel = GetCurrentPageModel();
                        pageModel.CoreMethods.PushPageModel <ModalActivityViewModel>(values, true);
                    });
                };

                Crashes.ShouldAwaitUserConfirmation = () =>
                {
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        Current.MainPage.DisplayActionSheet("Uh Oh.  Sorry I crashed.  Do you want to send a crash report?", "Cancel", null, "Send", "Always Send", "Don't Send")
                        .ContinueWith((arg) =>
                        {
                            var answer = arg.Result;
                            UserConfirmation userConfirmationSelection;

                            if (answer == "Send")
                            {
                                userConfirmationSelection = UserConfirmation.Send;
                            }
                            else if (answer == "Always Send")
                            {
                                userConfirmationSelection = UserConfirmation.AlwaysSend;
                            }
                            else
                            {
                                userConfirmationSelection = UserConfirmation.DontSend;
                            }

                            Crashes.NotifyUserConfirmation(userConfirmationSelection);
                        });
                    });

                    return(true);
                };

                Crashes.HasCrashedInLastSessionAsync().ContinueWith((arg) =>
                {
                    //MainThread.BeginInvokeOnMainThread(() =>
                    //{
                    //    try
                    //    {
                    //        Task<bool> didAppCrash = Crashes.HasCrashedInLastSessionAsync();

                    //        if (didAppCrash.Result)
                    //        {
                    //            Current.MainPage.DisplayAlert("Oops", "We noticed the app crashed on you.  Sorry for the inconvenience.", "Ok");
                    //        }
                    //    }
                    //    catch (Exception exception)
                    //    {
                    //        Debug.WriteLine(exception.Message);
                    //    }
                    //});
                });

                Push.PushNotificationReceived += (sender, e) =>
                {
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        // Summarize the notification title and message.
                        StringBuilder summary = new StringBuilder
                                                    ("Push Notification Received \n\tNotification Title: " + e.Title + "\n\tMessage: " + e.Message);

                        bool isContentAvailable = false;
                        string searchText       = String.Empty;

                        // If receiving custom data, add to the summary.
                        if (e.CustomData != null)
                        {
                            summary.AppendLine("\nCustom Data:");

                            foreach (KeyValuePair <string, string> value in e.CustomData)
                            {
                                summary.AppendLine("\t" + value.Key + "\t" + value.Value);

                                switch (value.Key)
                                {
                                case "content-available":

                                    isContentAvailable = Convert.ToBoolean(value.Value);
                                    break;

                                case "SearchText":

                                    searchText = value.Value;
                                    break;
                                }
                            }

                            if (!String.IsNullOrEmpty(searchText))
                            {
                                FreshBasePageModel freshBasePageModel = GetCurrentPageModel();

                                if (freshBasePageModel is HomeViewModel)
                                {
                                    HomeViewModel homeViewModel = freshBasePageModel as HomeViewModel;
                                    homeViewModel.SearchCommand.Execute(searchText);
                                }
                            }
                        }

                        //Current.MainPage.DisplayAlert("Push Notification Received", summary.ToString(), "Ok");
                    });
                };

                // Initialize AppCenter SDK
                AppCenter.Start
                (
                    String.Format
                    (
                        "ios={0};android={1};"
                        , Settings.AppCenterSecretiOS
                        , Settings.AppCenterSecretAndroid
                    )
                    , typeof(Analytics)
                    , typeof(Crashes)
                    , typeof(Push)
                );
            }
        }
 public void OnBeforeSending(ILog log)
 {
     AppCenterLog.Debug(App.LogTag, "Analytics listener OnBeforeSendingEventLog");
 }
Example #21
0
 public override void DidSucceedSendingEventLog(MSAnalytics analytics, MSEventLog eventLog)
 {
     AppCenterLog.Debug(App.LogTag, "Did send event");
 }
Example #22
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get the ViewPager and set it's PagerAdapter so that it can display items
            var viewPager = FindViewById(Resource.Id.viewpager) as ViewPager;

            viewPager.Adapter = new PagerAdapter(SupportFragmentManager, this);

            // Give the TabLayout the ViewPager
            var tabLayout = FindViewById(Resource.Id.tablayout) as TabLayout;

            tabLayout.SetupWithViewPager(viewPager);

            // App Center integration
            AppCenterLog.Assert(LogTag, "AppCenter.LogLevel=" + AppCenter.LogLevel);
            AppCenter.LogLevel = LogLevel.Verbose;
            AppCenterLog.Info(LogTag, "AppCenter.LogLevel=" + AppCenter.LogLevel);
            AppCenterLog.Info(LogTag, "AppCenter.Configured=" + AppCenter.Configured);

            // Set event handlers
            Crashes.SendingErrorReport      += SendingErrorReportHandler;
            Crashes.SentErrorReport         += SentErrorReportHandler;
            Crashes.FailedToSendErrorReport += FailedToSendErrorReportHandler;

            // Set callbacks
            Crashes.ShouldProcessErrorReport    = ShouldProcess;
            Crashes.ShouldAwaitUserConfirmation = ConfirmationHandler;

            Distribute.ReleaseAvailable = OnReleaseAvailable;
            AppCenterLog.Assert(LogTag, "AppCenter.Configured=" + AppCenter.Configured);
            AppCenter.SetLogUrl("https://in-integration.dev.avalanch.es");
            Distribute.SetInstallUrl("http://install.asgard-int.trafficmanager.net");
            Distribute.SetApiUrl("https://asgard-int.trafficmanager.net/api/v0.1");

            // Enable Firebase Analytics if set
            var enableAnalytics = Preferences.SharedPreferences.GetBoolean(Constants.FirebaseAnalyticsEnabledKey, false);

            if (enableAnalytics)
            {
                Push.EnableFirebaseAnalytics();
            }

            Push.PushNotificationReceived += PrintNotification;

            AppCenter.Start("bff0949b-7970-439d-9745-92cdc59b10fe", typeof(Analytics), typeof(Crashes),
                            typeof(Push), typeof(Distribute));

            AppCenter.IsEnabledAsync().ContinueWith(enabled =>
            {
                AppCenterLog.Info(LogTag, "AppCenter.Enabled=" + enabled.Result);
            });
            AppCenter.GetInstallIdAsync().ContinueWith(installId =>
            {
                AppCenterLog.Info(LogTag, "AppCenter.InstallId=" + installId.Result);
            });
            Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
            {
                AppCenterLog.Info(LogTag, "Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
            });
            Crashes.GetLastSessionCrashReportAsync().ContinueWith(report =>
            {
                AppCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.Exception=" + report.Result?.Exception);
                AppCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.Throwable=" + report.Result?.AndroidDetails?.Throwable);
            });
        }
Example #23
0
 static void PlatformSetUserId(string userId)
 {
     AppCenterLog.Error(AppCenterLog.LogTag, "AppCenter.SetUserId is not supported on Windows.");
 }
Example #24
0
        public void Verbose(string tag, string message, Exception ex = null)
        {
            var collectedMessage = CollectExceptionDetails(message, ex);

            AppCenterLog.Verbose(tag, collectedMessage, ex);
        }