Пример #1
0
        protected override void OnStart()
        {
            MobileCenter.Start($"android={Keys.MobileCenter.AndroidToken};ios={Keys.MobileCenter.iOSToken}",
                               typeof(Analytics), typeof(Crashes), typeof(Push));

            Push.PushNotificationReceived += OnIncomingPayloadReceived;
            CrossConnectivity.Current.ConnectivityChanged += OnConnectivityChanged;
            if (false)
            {
                var l = new AnimationView();
            }                                                     //Warm up the library

            base.OnStart();

            //Load up the registered player, if one exists
            var installId = MobileCenter.GetInstallIdAsync().Result;

            Logger.Instance.WriteLine($"Install ID: {installId}");

            LoadRegisteredPlayer();
            SetMainPage();

            EvaluateConnectivity();
            WakeUpServer();
        }
Пример #2
0
        async Task ExecuteSendPushNotificationCommand(string tag)
        {
            var id = await MobileCenter.GetInstallIdAsync();

            var content = new NotificationContent();
            var target  = new NotificationTarget();

            content.Body  = "This is a test!";
            content.Title = "push sent from mobile device";

            target.Devices = new string[] { id.ToString() };

            //if (!string.IsNullOrEmpty(tag))
            //target.Audiences = new List<string>() { tag };

            var push = new MobileCenterNotification();

            push.Content = content;
            push.Target  = target;

            push.Content.CustomData = new Dictionary <string, string>()
            {
                { "hello", "mahdi" }
            };

            var httpclient = new HttpClient();

            var jsonin = JsonConvert.SerializeObject(push);

            var res = await httpclient.PostAsync <string>("http://mobilecenterpush.azurewebsites.net/api/sendpush", push);
        }
        private void TriggerIngestion(State state, IList <Log> logs, string batchId)
        {
            // Before sending logs, trigger the sending event for this channel
            if (SendingLog != null)
            {
                foreach (var eventArgs in logs.Select(log => new SendingLogEventArgs(log)))
                {
                    SendingLog?.Invoke(this, eventArgs);
                }
            }

            // If the optional Install ID has no value, default to using empty GUID
            // TODO When InstallId will really be async, we should not use Result anymore
            var rawInstallId = MobileCenter.GetInstallIdAsync().Result;
            var installId    = rawInstallId.HasValue ? rawInstallId.Value : Guid.Empty;

            using (var serviceCall = _ingestion.PrepareServiceCall(_appSecret, installId, logs))
            {
                serviceCall.ExecuteAsync().ContinueWith(completedTask =>
                {
                    var ingestionException = completedTask.Exception?.InnerException as IngestionException;
                    if (ingestionException == null)
                    {
                        HandleSendingSuccess(state, batchId);
                    }
                    else
                    {
                        HandleSendingFailure(state, batchId, ingestionException);
                    }
                });
            }
        }
 protected override void OnAppearing()
 {
     base.OnAppearing();
     if (InstallIdLabel != null)
     {
         InstallIdLabel.Text = MobileCenter.GetInstallIdAsync().Result?.ToString();
     }
 }
Пример #5
0
        async public Task <bool> RegisterPlayer()
        {
            if (string.IsNullOrWhiteSpace(Email) || string.IsNullOrWhiteSpace(Alias))
            {
                throw new Exception("Please specify an email and alias.");
            }

            var email = Email;             //We toy with a copy because the two-way binding will cause the TextChanged event to fire
            var split = email.Split('@');

            if (split.Length == 2)
            {
                if (split[1].ToLower() == "hbo.com")                //GoT character
                {
                    //Randomize the email (which serves as the primary key) so it doesn't conflict w/ other demo games
                    var rand = Guid.NewGuid().ToString().Substring(0, 7).ToLower();
                    email = $"{split[0]}-{rand}@{split[1]}";
                }
            }

            bool isAppropriate = false;
            var  task          = new Task(() =>
            {
                var aliasValid = App.Instance.DataService.IsTextValidAppropriate(Alias.Trim()).Result;
                var emailValid = App.Instance.DataService.IsTextValidAppropriate(Email.Trim()).Result;

                isAppropriate = aliasValid && emailValid;
            });

            await task.RunProtected();

            if (!task.WasSuccessful())
            {
                return(false);
            }

            if (!isAppropriate)
            {
                Hud.Instance.ShowToast("Inappropriate content was detected");
                return(false);
            }

            var player = new Player
            {
                Avatar    = Avatar,
                Email     = email.Trim(),
                Alias     = Alias.Trim(),
                InstallId = MobileCenter.GetInstallIdAsync().Result.ToString(),
            };

            var args = new KVP {
                { "email", player.Email }, { "firstName", player.Alias }, { "avatar", player.Avatar }
            };

            Analytics.TrackEvent("Player registered", args);
            App.Instance.SetPlayer(player);
            return(true);
        }
Пример #6
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);

            // Mobile Center integration
            MobileCenterLog.Assert(LogTag, "MobileCenter.LogLevel=" + MobileCenter.LogLevel);
            MobileCenter.LogLevel = LogLevel.Verbose;
            MobileCenterLog.Info(LogTag, "MobileCenter.LogLevel=" + MobileCenter.LogLevel);
            MobileCenterLog.Info(LogTag, "MobileCenter.Configured=" + MobileCenter.Configured);

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

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

            Distribute.ReleaseAvailable = OnReleaseAvailable;

            MobileCenterLog.Assert(LogTag, "MobileCenter.Configured=" + MobileCenter.Configured);
            MobileCenter.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");
            MobileCenter.Start("bff0949b-7970-439d-9745-92cdc59b10fe", typeof(Analytics), typeof(Crashes), typeof(Distribute));

            MobileCenter.IsEnabledAsync().ContinueWith(enabled =>
            {
                MobileCenterLog.Info(LogTag, "MobileCenter.Enabled=" + enabled.Result);
            });
            MobileCenter.GetInstallIdAsync().ContinueWith(installId =>
            {
                MobileCenterLog.Info(LogTag, "MobileCenter.InstallId=" + installId.Result);
            });
            Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
            {
                MobileCenterLog.Info(LogTag, "Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
            });
            Crashes.GetLastSessionCrashReportAsync().ContinueWith(report =>
            {
                MobileCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.Exception=" + report.Result?.Exception);
                MobileCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.Throwable=" + report.Result?.AndroidDetails?.Throwable);
            });
        }
Пример #7
0
        public App()
        {
            InitializeComponent();
            MainPage = new NavigationPage(new MainPuppetPage());

            MobileCenterLog.Assert(LogTag, "MobileCenter.LogLevel=" + MobileCenter.LogLevel);
            MobileCenter.LogLevel = LogLevel.Verbose;
            MobileCenterLog.Info(LogTag, "MobileCenter.LogLevel=" + MobileCenter.LogLevel);
            MobileCenterLog.Info(LogTag, "MobileCenter.Configured=" + MobileCenter.Configured);

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

            MobileCenterLog.Assert(LogTag, "MobileCenter.Configured=" + MobileCenter.Configured);
            MobileCenter.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");
            RealUserMeasurements.SetRumKey("b1919553367d44d8b0ae72594c74e0ff");
            MobileCenter.Start($"uwp={UwpKey};android={AndroidKey};ios={IosKey}",
                               typeof(Analytics), typeof(Crashes), typeof(Distribute), typeof(Push), typeof(RealUserMeasurements));

            // Need to use reflection because moving this to the Android specific
            // code causes crash. (Unable to access properties before init is called).
            if (Xamarin.Forms.Device.RuntimePlatform == Xamarin.Forms.Device.Android)
            {
                if (!Properties.ContainsKey(OthersContentPage.FirebaseEnabledKey))
                {
                    Properties[OthersContentPage.FirebaseEnabledKey] = false;
                }

                if ((bool)Properties[OthersContentPage.FirebaseEnabledKey])
                {
                    typeof(Push).GetRuntimeMethod("EnableFirebaseAnalytics", new Type[0]).Invoke(null, null);
                }
            }

            MobileCenter.IsEnabledAsync().ContinueWith(enabled =>
            {
                MobileCenterLog.Info(LogTag, "MobileCenter.Enabled=" + enabled.Result);
            });
            MobileCenter.GetInstallIdAsync().ContinueWith(installId =>
            {
                MobileCenterLog.Info(LogTag, "MobileCenter.InstallId=" + installId.Result);
            });
            MobileCenterLog.Info(LogTag, "MobileCenter.SdkVersion=" + MobileCenter.SdkVersion);
            Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
            {
                MobileCenterLog.Info(LogTag, "Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
            });
            Crashes.GetLastSessionCrashReportAsync().ContinueWith(report =>
            {
                MobileCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.Exception=" + report.Result?.Exception);
            });
        }
        public void GetInstallId()
        {
            var fakeInstallId = Guid.NewGuid();

            _settingsMock.Setup(settings => settings.GetValue(MobileCenter.InstallIdKey, It.IsAny <Guid>())).Returns(fakeInstallId);
            var installId = MobileCenter.GetInstallIdAsync().Result;

            Assert.IsTrue(installId.HasValue);
            Assert.AreEqual(installId.Value, fakeInstallId);
        }
Пример #9
0
        protected override void OnStart()
        {
            MobileCenter.LogLevel               = LogLevel.Verbose;
            Crashes.ShouldProcessErrorReport    = ShouldProcess;
            Crashes.ShouldAwaitUserConfirmation = ConfirmationHandler;
            Crashes.GetErrorAttachments         = GetErrorAttachments;
            Distribute.ReleaseAvailable         = OnReleaseAvailable;
            MobileCenter.Start($"uwp={uwpKey};android={androidKey};ios={iosKey}",
                               typeof(Analytics), typeof(Crashes), typeof(Distribute));

            MobileCenter.GetInstallIdAsync().ContinueWith(installId =>
            {
                MobileCenterLog.Info(LogTag, "MobileCenter.InstallId=" + installId.Result);
            });
            Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
            {
                MobileCenterLog.Info(LogTag, "Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
            });
            Crashes.GetLastSessionCrashReportAsync().ContinueWith(report =>
            {
                MobileCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.Exception=" + report.Result?.Exception);
            });



            //just a dumb way to push and pull some data from the cache
            MainPage.Appearing += (x, y) =>
            {
                _BlobCache.GetObject <SomeObject>("test")
                .Catch((KeyNotFoundException ke) => Observable.Return <SomeObject>(null))
                .SelectMany(someClass =>
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                    {
                        Current.MainPage.DisplayActionSheet($"{someClass?.ToString() ?? "null"}", null, null, $"{someClass?.ToString() ?? "null"}", $"{someClass?.ToString() ?? "null"}", $"{someClass?.ToString() ?? "null"}").ContinueWith((arg) =>
                        {
                        });
                    });
                    return(_BlobCache.InsertObject("test",
                                                   new SomeObject()
                    {
                        Property1 = "1234",
                        Property2 = "4321"
                    }
                                                   ));
                })
                .SelectMany(_ => _BlobCache.Flush())
                .SelectMany(_ => _BlobCache.GetObject <SomeObject>("test"))
                .Subscribe(someclass =>
                {
                }
                           );
            };
            // Handle when your app starts
        }
Пример #10
0
        void LoadRegisteredPlayer()
        {
            if (!string.IsNullOrWhiteSpace(Settings.Player))
            {
                var player = JsonConvert.DeserializeObject <Player>(Settings.Player);

                if (player == null)
                {
                    return;
                }

                player.InstallId = MobileCenter.GetInstallIdAsync().Result.ToString();
                Player           = player;
            }
        }
Пример #11
0
        public static void Run()
        {
            CrossVersionTracking.Current.Track();

            Log.Debug($"\n{CrossVersionTracking.Current}");

            Settings.RegisterDefaultSettings();

            Microsoft.Azure.Mobile.Crashes.Crashes.GetErrorAttachments = (report) => new List <Microsoft.Azure.Mobile.Crashes.ErrorAttachmentLog>
            {
                Microsoft.Azure.Mobile.Crashes.ErrorAttachmentLog.AttachmentWithText(CrossVersionTracking.Current.ToString(), "versionhistory.txt")
            };


#if __IOS__
            Microsoft.Azure.Mobile.Distribute.Distribute.DontCheckForUpdatesInDebug();
#elif __ANDROID__
            Settings.VersionNumber = CrossVersionTracking.Current.CurrentVersion;

            Settings.BuildNumber = CrossVersionTracking.Current.CurrentBuild;
#endif

            if (!string.IsNullOrEmpty(Keys.MobileCenter.AppSecret))
            {
                Log.Debug("Starting Mobile Center...");

                MobileCenter.Start(Keys.MobileCenter.AppSecret,
                                   typeof(Microsoft.Azure.Mobile.Analytics.Analytics),
                                   typeof(Microsoft.Azure.Mobile.Crashes.Crashes),
                                   typeof(Microsoft.Azure.Mobile.Distribute.Distribute));
            }
            else
            {
                Log.Debug("To use Mobile Center, add your App Secret to Keys.MobileCenter.AppSecret");
            }

            Task.Run(async() =>
            {
                var installId = await MobileCenter.GetInstallIdAsync();

                Settings.UserReferenceKey = installId?.ToString("N");
            });
        }
Пример #12
0
        public static void Run()
        {
            CrossVersionTracking.Current.Track();

            Log.Debug(CrossVersionTracking.Current.ToString());


            Settings.RegisterDefaultSettings();

            // Send installed version history with crash reports
            Crashes.GetErrorAttachments = (report) => new List <ErrorAttachmentLog>
            {
                ErrorAttachmentLog.AttachmentWithText(CrossVersionTracking.Current.ToString(), "versionhistory.txt")
            };

            if (!string.IsNullOrEmpty(Settings.MobileCenterKey))
            {
                Log.Debug("Starting Mobile Center...");

                MobileCenter.Start(Settings.MobileCenterKey, typeof(Analytics), typeof(Crashes), typeof(Distribute));
            }
            else
            {
                Log.Debug("To use Mobile Center, add your App Secret to Keys.MobileCenter.AppSecret");
            }

            Task.Run(async() =>
            {
                var installId = await MobileCenter.GetInstallIdAsync();

                Settings.UserReferenceKey = installId?.ToString("N");
            });

#if __IOS__
            Distribute.DontCheckForUpdatesInDebug();
#elif __ANDROID__
            Settings.VersionNumber = CrossVersionTracking.Current.CurrentVersion;

            Settings.BuildNumber = CrossVersionTracking.Current.CurrentBuild;

            Settings.VersionDescription = $"{CrossVersionTracking.Current.CurrentVersion} ({CrossVersionTracking.Current.CurrentBuild})";
#endif
        }
        protected override void OnStart()
        {
            MobileCenter.LogLevel               = LogLevel.Verbose;
            Crashes.ShouldProcessErrorReport    = ShouldProcess;
            Crashes.ShouldAwaitUserConfirmation = ConfirmationHandler;
            Crashes.GetErrorAttachments         = GetErrorAttachments;
            Distribute.ReleaseAvailable         = OnReleaseAvailable;
            MobileCenter.Start($"uwp={uwpKey};android={androidKey};ios={iosKey}",
                               typeof(Analytics), typeof(Crashes), typeof(Distribute), typeof(Push));

            MobileCenter.GetInstallIdAsync().ContinueWith(installId =>
            {
                MobileCenterLog.Info(LogTag, "MobileCenter.InstallId=" + installId.Result);
            });
            Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
            {
                MobileCenterLog.Info(LogTag, "Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
            });
            Crashes.GetLastSessionCrashReportAsync().ContinueWith(report =>
            {
                MobileCenterLog.Info(LogTag, "Crashes.LastSessionCrashReport.Exception=" + report.Result?.Exception);
            });
        }
Пример #14
0
        protected override async void OnStart()
        {
            // Handle when your app starts
            switch (Xamarin.Forms.Device.RuntimePlatform)
            {
            case Xamarin.Forms.Device.iOS:
                await MobileCenterHelpers.Start(MobileCenterConstants.MobileCenterAPIKey_iOS);

                break;

            case Xamarin.Forms.Device.Android:
                await MobileCenterHelpers.Start(MobileCenterConstants.MobileCenterAPIKey_Droid);

                break;

            default:
                throw new Exception("Runtime Platform Not Supported");
            }

            var id = MobileCenter.GetInstallIdAsync().Result;

            MobileCenterHelpers.TrackEvent("App started", "INSTALL ID", id.ToString());
        }
Пример #15
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            Push.PushNotificationReceived += (sender, es) => {
                // Add the notification message and title to the message
                var summary = $"Push notification received:" +
                              $"\n\tNotification title: {es.Title}" +
                              $"\n\tMessage: {es.Message}";

                // If there is custom data associated with the notification,
                // print the entries
                if (es.CustomData != null)
                {
                    summary += "\n\tCustom data:\n";
                    foreach (var key in es.CustomData.Keys)
                    {
                        summary += $"\t\t{key} : {es.CustomData[key]}\n";
                    }
                }

                // Send the notification summary to debug output
                System.Diagnostics.Debug.WriteLine(summary);
            };
            MobileCenter.LogLevel = LogLevel.Verbose;
            // TODO: 1.2 - Ensure we use ALL of the window space.  That means we have to make sure we follow the safe area of the screen!
            // ApplicationView.GetForCurrentView().SetDesiredBoundsMode(ApplicationViewBoundsMode.UseCoreWindow);

            // TODO: 5.1 - If we want a ten foot view, we probably want color safe colors as well.  This dictionary solves that for default styles.
            //if (App.IsTenFoot)
            //{
            //    // use TV colorsafe values
            //    this.Resources.MergedDictionaries.Add(new ResourceDictionary
            //    {
            //        Source = new Uri("ms-appx:///TvSafeColors.xaml")
            //    });
            //}
            //MobileCenter code
            //MobileCenter.SetLogUrl("https://in-staging-south-centralus.staging.avalanch.es");
            MobileCenter.SetCountryCode("China");
            MobileCenter.Start("84599058-77f7-4801-9e62-bdbb7bf7293d", typeof(Analytics), typeof(Crashes), typeof(Push));
            //Analytics.Enabled = true;

            var installid = MobileCenter.GetInstallIdAsync();

            System.Diagnostics.Debug.WriteLine("InstallId=" + installid.Result.ToString());
            Push.CheckLaunchedFromNotification(e);


            ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;

            if (titleBar != null)
            {
                Color titleBarColor = (Color)App.Current.Resources["SystemChromeMediumColor"];
                titleBar.BackgroundColor       = titleBarColor;
                titleBar.ButtonBackgroundColor = titleBarColor;
            }

            MainPage shell = Window.Current.Content as MainPage;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (shell == null)
            {
                // Create a AppShell to act as the navigation context and navigate to the first page
                shell = new MainPage();

                // Set the default language
                shell.Language = Windows.Globalization.ApplicationLanguages.Languages[0];

                shell.AppFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Should load state from previous run
                }
            }

            // Place our app shell in the current Window
            Window.Current.Content = shell;

            if (shell.AppFrame.Content == null)
            {
                // When the navigation stack isn't restored, navigate to the first page
                // suppressing the initial entrance animation.
                shell.AppFrame.Navigate(typeof(AllPresidentsView), e.Arguments, new Windows.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());
            }

            // Ensure the current window is active
            Window.Current.Activate();

            ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(320, 200));
        }