Exemplo n.º 1
0
        private async Task DoWork(object state)
        {
            TaskState taskState = (TaskState)state;
            Stopwatch stopwatch = new Stopwatch();

            while (active)
            {
                taskState.Status = State.Running;
                if (!await CanProcess() && downloadersActive)
                {
                    taskState.Status = State.Paused;
                    await Task.Delay(250);

                    continue;
                }

                if (!PageProcessingQueue.IsEmpty)
                {
                    UnparsedPage page;
                    if (!PageProcessingQueue.TryDequeue(out page))
                    {
                        //another thread grabbed the page
                        continue;
                    }
                    stopwatch.Time(() =>
                    {
                        return(ProcessThreadPage(page.Thread, page.Html));
                    },
                                   (long time) => TelemetryManager.Incriment(TelemetryType.processed_pages, taskState.Id, time)
                                   );
                }

                if (!ProcessingQueue.IsEmpty)
                {
                    UnparsedThread thread;
                    if (!ProcessingQueue.TryDequeue(out thread))
                    {
                        continue;
                    }

                    stopwatch.Time(() =>
                    {
                        ProcessThread(thread.Id, thread.Html);
                    },
                                   (long time) => TelemetryManager.Incriment(TelemetryType.processed_threads, taskState.Id, time)
                                   );
                }
                else if (!downloadersActive) //Queue is empty, no more downloads are being performed, set active to false after 1s delay
                {
                    taskState.Status = State.Paused;
                    await Task.Delay(1000);

                    active = false;
                    break;
                }
            }
            taskState.Status = State.Complete;
        }
Exemplo n.º 2
0
 // Start is called before the first frame update
 void Start()
 {
     tm         = FindObjectOfType <TelemetryManager>();
     cm         = FindObjectOfType <CameraMotion>();
     batteryUI  = GameObject.FindGameObjectWithTag("batteryUI").transform;
     velocityUI = GameObject.FindGameObjectWithTag("velocityUI").transform;
     stateUI    = GameObject.FindGameObjectWithTag("stateUI").transform;
     rotationUI = GameObject.FindGameObjectWithTag("rotationUI").transform;
 }
Exemplo n.º 3
0
        protected void Application_Start()
        {
            TelemetryManager.Setup("d0a63409-84bf-4f88-a8cf-8440ce670471");
            SiteUtil.SetDefaultConnectionLimit();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GamesController.StartUpdatingCache(); //make sure caching starts as soon as site is up

            InitMvc();
        }
Exemplo n.º 4
0
        /// <summary>
        /// Updates the subreddit list
        /// </summary>
        /// <param name="newSubreddits"></param>
        private void UpdateSubredditList(List <Subreddit> newSubreddits)
        {
            try
            {
                var insertCount = 0;
                for (var newListCount = 0; newListCount < newSubreddits.Count; newListCount++)
                {
                    var newSubreddit = newSubreddits[newListCount];

                    // Set some UI properties.
                    newSubreddit.FavIconUri  = newSubreddit.IsFavorite ? "ms-appx:///Assets/MainPage/FavoriteIcon.png" : "ms-appx:///Assets/MainPage/NotFavoriteIcon.png";
                    newSubreddit.DisplayName = newSubreddit.DisplayName.ToLower();

                    // If the two are the same, just update them.
                    if (_subreddits.Count > insertCount && _subreddits[insertCount].Id.Equals(newSubreddit.Id))
                    {
                        // If they are the same just update it
                        _subreddits[insertCount].DisplayName = newSubreddit.DisplayName;
                        _subreddits[insertCount].FavIconUri  = newSubreddit.FavIconUri;
                        _subreddits[insertCount].IsFavorite  = newSubreddit.IsFavorite;
                        _subreddits[insertCount].Title       = newSubreddit.Title;
                    }
                    // (subreddit insert) If the next element in the new list is the same as the current element in the old list, insert.
                    else if (_subreddits.Count > insertCount && newSubreddits.Count > newListCount + 1 && newSubreddits[newListCount + 1].Id.Equals(_subreddits[insertCount].Id))
                    {
                        _subreddits.Insert(insertCount, newSubreddit);
                    }
                    // (subreddit remove) If the current element in the new list is the same as the next element in the old list.
                    else if (_subreddits.Count > insertCount + 1 && newSubreddits.Count > newListCount && newSubreddits[newListCount].Id.Equals(_subreddits[insertCount + 1].Id))
                    {
                        _subreddits.RemoveAt(insertCount);
                    }
                    // If the old list is still larger than the new list, replace
                    else if (_subreddits.Count > insertCount)
                    {
                        _subreddits[insertCount] = newSubreddit;
                    }
                    // Or just add.
                    else
                    {
                        _subreddits.Add(newSubreddit);
                    }
                    insertCount++;
                }

                // Remove any extra subreddits
                while (_subreddits.Count > newSubreddits.Count)
                {
                    _subreddits.RemoveAt(_subreddits.Count - 1);
                }
            }
            catch (Exception e)
            {
                TelemetryManager.ReportUnexpectedEvent(this, "UpdateSubredditListFailed", e);
                App.BaconMan.MessageMan.DebugDia("UpdateSubredditListFailed", e);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Fired when we should load the content.
        /// </summary>
        public async void OnPrepareContent()
        {
            // Defer so we give the UI time to work.
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                var headerText = "";
                var minorText  = "";

                if (_contentPanelBase.Source.IsSelf)
                {
                    headerText = "There's no content here!";
                    minorText  = "Scroll down to view the discussion.";
                }
                else
                {
                    _content = MiscellaneousHelper.TryToFindRedditContentInLink(_contentPanelBase.Source.Url);

                    switch (_content.Type)
                    {
                    case RedditContentType.Subreddit:
                        headerText = "This post links to a subreddit";
                        minorText  = $"Tap anywhere to view /r/{_content.Subreddit}";
                        break;

                    case RedditContentType.Comment:
                        headerText = "This post links to a comment thread";
                        minorText  = "Tap anywhere to view it";
                        break;

                    case RedditContentType.Post:
                        headerText = "This post links to a reddit post";
                        minorText  = $"Tap anywhere to view it";
                        break;

                    case RedditContentType.User:
                        headerText = "This post links to a reddit user page";
                        minorText  = $"Tap anywhere to view {_content.User}";
                        break;

                    case RedditContentType.Website:
                        // This shouldn't happen
                        App.BaconMan.MessageMan.DebugDia("Got website back when prepare on reddit content control");
                        TelemetryManager.ReportUnexpectedEvent(this, "GotWebsiteOnPrepareRedditContent");
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                ui_headerText.Text = headerText;
                ui_minorText.Text  = minorText;

                // Hide loading
                _contentPanelBase.FireOnLoading(false);
            });
        }
Exemplo n.º 6
0
        public void Setup()
        {
            TestCommon.ResetInternalStaticCaches();
            _testReceiver = new _TestReceiver();
            var serviceBundle = TestCommon.CreateServiceBundleWithCustomHttpManager(null, clientId: ClientId);

            _telemetryManager = new TelemetryManager(serviceBundle.Config, serviceBundle.PlatformProxy, _testReceiver.HandleTelemetryEvents);
            _trackingEvent    = new _TestEvent("tracking event", CorrelationId);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Called when we should update the inbox and send any notifications.
        /// </summary>
        /// <param name="newNotifications"></param>
        /// <param name="currentMessages"></param>
        public async Task UpdateInboxMessages(List <Tuple <string, string, string> > newNotifications, List <Message> currentMessages)
        {
            // Make sure we are enabled and in a good state
            if (ShowInboxOnBand && await EnsureBandTileState())
            {
                try
                {
                    var pairedBand = await GetPairedBand();

                    if (pairedBand == null)
                    {
                        // We don't have a band.
                        return;
                    }

                    // Try to connect to the band.
                    using (var bandClient = await BandClientManager.Instance.ConnectAsync(pairedBand))
                    {
                        foreach (var newNote in newNotifications)
                        {
                            var title = newNote.Item1;
                            var body  = newNote.Item2;

                            // If the body is empty move the title to the body so it wraps
                            if (string.IsNullOrWhiteSpace(body))
                            {
                                body  = title;
                                title = "";
                            }

                            // If we have a title clip it to only two words. The title can't be very long and
                            // looks odd if it is clipped on the band.
                            var firstSpace = string.IsNullOrWhiteSpace(title) ? -1 : title.IndexOf(' ');
                            if (firstSpace != -1)
                            {
                                if (title != null)
                                {
                                    var secondSpace = title.IndexOf(' ', firstSpace + 1);
                                    if (secondSpace != -1)
                                    {
                                        title = title.Substring(0, secondSpace);
                                    }
                                }
                            }

                            // Send the message.
                            await bandClient.NotificationManager.SendMessageAsync(_bandTileGuid, title, body, DateTimeOffset.Now, Microsoft.Band.Notifications.MessageFlags.ShowDialog);
                        }
                    }
                }
                catch (Exception e)
                {
                    _baconMan.MessageMan.DebugDia("failed to update band message", e);
                    TelemetryManager.ReportUnexpectedEvent(this, "FailedToUpdateBandMessages", e);
                }
            }
        }
Exemplo n.º 8
0
        public void TestRecordStatusReportWithRollback()
        {
            var report = new JObject();

            report.Add(STATUS_KEY, DEPLOYMENT_FAILED_STATUS);

            TelemetryManager.RecordStatusReported(report);
            Assert.IsTrue(true);
        }
 public void Initialize()
 {
     TestCommon.ResetInternalStaticCaches();
     _myReceiver       = new MyReceiver();
     _serviceBundle    = TestCommon.CreateServiceBundleWithCustomHttpManager(null, clientId: ClientId);
     _logger           = _serviceBundle.DefaultLogger;
     _platformProxy    = _serviceBundle.PlatformProxy;
     _crypto           = _platformProxy.CryptographyManager;
     _telemetryManager = new TelemetryManager(_serviceBundle.Config, _platformProxy, _myReceiver.HandleTelemetryEvents);
 }
Exemplo n.º 10
0
        private void Favorite_Tapped(object sender, TappedRoutedEventArgs e)
        {
            // Get the subreddit from the sender
            var sub = ((sender as Grid).DataContext as Subreddit);

            // Reverse the status
            App.BaconMan.SubredditMan.SetFavorite(sub.Id, !sub.IsFavorite);

            TelemetryManager.ReportEvent(this, "SubredditListFavoriteTapped");
        }
Exemplo n.º 11
0
        /// <summary>
        /// Fired then the post sort is tapped
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommentSort_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var element   = sender as FrameworkElement;
            var textBlock = FindCommentSortText(element);

            if (textBlock != null)
            {
                FlyoutBase.ShowAttachedFlyout(textBlock);
            }
            TelemetryManager.ReportEvent(this, "UserProfileCommentSort");
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!disposing)
            {
                return;
            }

            this.telemetryManager?.Dispose();
            this.telemetryManager = null;
        }
Exemplo n.º 13
0
 void prepareSingleton()
 {
     if (instance == null)
     {
         instance = this;
         DontDestroyOnLoad(this);
     }
     else
     {
         Destroy(this);
     }
 }
Exemplo n.º 14
0
        public void InitPropertiesTest()
        {
            TelemetryManager tm = new TelemetryManager((TestCommon.Instance.BuildContextFactory() as TestPnPContextFactory).GetGlobalSettingsOptions());
            var initProps       = tm.PopulateInitProperties();

            Assert.IsTrue(initProps.ContainsKey("PnPCoreSDKVersion"));
            Assert.IsTrue(!string.IsNullOrEmpty(initProps["PnPCoreSDKVersion"]));
            Assert.IsTrue(initProps.ContainsKey("AADTenantId"));
            Assert.IsTrue(!string.IsNullOrEmpty(initProps["AADTenantId"]));
            Assert.IsTrue(initProps.ContainsKey("OS"));
            Assert.IsTrue(!string.IsNullOrEmpty(initProps["OS"]));
        }
Exemplo n.º 15
0
 /// <summary>
 /// Fired when the user taps prfile in the menu.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ProfileGrid_Tapped(object sender, TappedRoutedEventArgs e)
 {
     if (App.BaconMan.UserMan.IsUserSignedIn)
     {
         // Navigate to the user.
         var args = new Dictionary <string, object>();
         args.Add(PanelManager.NavArgsUserName, App.BaconMan.UserMan.CurrentUser.Name);
         _panelManager.Navigate(typeof(UserProfile), App.BaconMan.UserMan.CurrentUser.Name, args);
         TelemetryManager.ReportEvent(this, "GoToProfileViaGlobalMenu");
     }
     ToggleMenu(false);
 }
Exemplo n.º 16
0
        public void TestGetUpdateReportNegative()
        {
            var inputNoLabel = new JObject();

            inputNoLabel.Add(DEPLOYMENT_KEY_KEY, "depKeyParam");
            Assert.IsNull(TelemetryManager.GetUpdateReport(inputNoLabel));

            var inputNoKey = new JObject();

            inputNoKey.Add(LABEL_KEY, "labelParam");
            Assert.IsNull(TelemetryManager.GetUpdateReport(inputNoKey));
        }
Exemplo n.º 17
0
        public void TestGetUpdateReportNoPreviousUpdate()
        {
            var input = new JObject();

            input.Add(DEPLOYMENT_KEY_KEY, "depKeyParam");
            input.Add(LABEL_KEY, "labelParam");

            var output = TelemetryManager.GetUpdateReport(input);

            Assert.IsNotNull(output);
            Assert.IsTrue(output.ToString(Formatting.None).Contains("\"status\":\"DeploymentSucceeded\""));
        }
Exemplo n.º 18
0
        private void TrackTelemetryData(TelemetryType type)
        {
            switch (type)
            {
            case TelemetryType.Event:
                Dictionary <string, string> properties = new Dictionary <string, string> ();
                properties.Add("Xamarin Key", "Custom Property Value");
                TelemetryManager.TrackEvent("My custom event", properties);
                break;

            case TelemetryType.Metric:
                TelemetryManager.TrackMetric("My custom metric", 2.2);
                break;

            case TelemetryType.Message:
                TelemetryManager.TrackTrace("My custom message");
                break;

            case TelemetryType.PageView:
                TelemetryManager.TrackPageView("My custom page view");
                break;

            case TelemetryType.Session:
                ApplicationInsights.RenewSessionWithId(new DateTime().Date.ToString());
                break;

            case TelemetryType.HandledException:
                try {
                    throw(new NullReferenceException());
                }catch (Exception e) {
                    // App shouldn't crash because of that
                }
                break;

            case TelemetryType.UnhandledException:
                int value = 1 / int.Parse("0");
                break;

            case TelemetryType.UnmanagedSignal:
                                #if __IOS__
                DummyLibrary.TriggerSignalCrash();
                                #endif
                break;

            case TelemetryType.UnmanagedException:
                DummyLibrary.TriggerExceptionCrash();
                break;

            default:
                break;
            }
        }
Exemplo n.º 19
0
        public void TestRecordStatusReportWithoutRollback()
        {
            var reportSuccess = new JObject();

            reportSuccess.Add(STATUS_KEY, DEPLOYMENT_SUCCEEDED_STATUS);
            TelemetryManager.RecordStatusReported(reportSuccess);

            var reportNoStatus = new JObject();

            TelemetryManager.RecordStatusReported(reportNoStatus);

            Assert.IsTrue(true);
        }
        protected override void Initialize()
        {
            base.Initialize();

            var activeSolutionTracker = this.GetMefService <IActiveSolutionBoundTracker>();

            Debug.Assert(activeSolutionTracker != null, "Failed to resolve 'IActiveSolutionBoundTracker'.");

            var telemetryRepository = new TelemetryDataRepository();

            this.telemetryManager = new TelemetryManager(activeSolutionTracker, telemetryRepository, new TelemetryClient(),
                                                         new TelemetryTimer(telemetryRepository, new TimerFactory()), new KnownUIContextsWrapper());
        }
Exemplo n.º 21
0
        private void CopyPermalink_Click(object sender, RoutedEventArgs e)
        {
            // Get the post and copy the url into the clipboard
            var post = (sender as FrameworkElement)?.DataContext as Post;
            var data = new DataPackage();

            if (post != null)
            {
                data.SetText("http://www.reddit.com" + post.Permalink);
            }
            Clipboard.SetContent(data);
            TelemetryManager.ReportEvent(this, "CopyLinkTapped");
        }
Exemplo n.º 22
0
 /// <summary>
 /// Hide the loading text when the markdown is done.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void MarkdownBox_OnMarkdownReady(object sender, MarkdownReadyArgs e)
 {
     if (e.WasError)
     {
         _contentPanelBase.FireOnFallbackToBrowser();
         TelemetryManager.ReportUnexpectedEvent(this, "FailedToShowMarkdown", e.Exception);
     }
     else
     {
         // Hide loading
         _contentPanelBase.FireOnLoading(false);
     }
 }
Exemplo n.º 23
0
        /// <summary>
        /// Saves, unsaves, hides, or unhides a reddit item.
        /// </summary>
        /// <returns>Returns null if it fails or the user doesn't exist.</returns>
        public static async Task <bool> SaveOrHideRedditItem(BaconManager baconMan, string redditId, bool?save, bool?hide)
        {
            if (!baconMan.UserMan.IsUserSignedIn)
            {
                baconMan.MessageMan.ShowSigninMessage(save.HasValue ? "save item" : "hide item");
                return(false);
            }

            var wasSuccess = false;

            try
            {
                // Make the data
                var data = new List <KeyValuePair <string, string> > {
                    new KeyValuePair <string, string>("id", redditId)
                };

                string url;
                if (save.HasValue)
                {
                    url = save.Value ? "/api/save" : "/api/unsave";
                }
                else if (hide.HasValue)
                {
                    url = hide.Value ? "/api/hide" : "/api/unhide";
                }
                else
                {
                    return(false);
                }

                // Make the call
                var jsonResponse = await baconMan.NetworkMan.MakeRedditPostRequestAsString(url, data);

                if (jsonResponse.Contains("{}"))
                {
                    wasSuccess = true;
                }
                else
                {
                    TelemetryManager.ReportUnexpectedEvent("MisHelper", "failed to save or hide item, unknown response");
                    baconMan.MessageMan.DebugDia("failed to save or hide item, unknown response");
                }
            }
            catch (Exception e)
            {
                TelemetryManager.ReportUnexpectedEvent("MisHelper", "failed to save or hide item", e);
                baconMan.MessageMan.DebugDia("failed to save or hide item", e);
            }
            return(wasSuccess);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Assuming there are images, this does the rotation of the lock screen images.
        /// </summary>
        /// <returns></returns>
        private async Task DoImageRotation(UpdateTypes type)
        {
            try
            {
                var wasSuccess = false;
                switch (type)
                {
                case UpdateTypes.LockScreen:
                    wasSuccess = await DoSingleImageRotation(UpdateTypes.LockScreen);

                    break;

                case UpdateTypes.Desktop:
                    wasSuccess = await DoSingleImageRotation(UpdateTypes.Desktop);

                    break;

                case UpdateTypes.Band:
                    wasSuccess = await DoSingleImageRotation(UpdateTypes.Band);

                    break;

                case UpdateTypes.All:
                    break;

                default:
                {
                    var firstSuccess = await DoSingleImageRotation(UpdateTypes.LockScreen);

                    var secondSuccess = await DoSingleImageRotation(UpdateTypes.Desktop);

                    var thirdSuccess = await DoSingleImageRotation(UpdateTypes.Band);

                    wasSuccess = firstSuccess && secondSuccess && thirdSuccess;
                    break;
                }
                }

                // If we successfully updated set the time.
                if (wasSuccess)
                {
                    LastImageUpdate = DateTime.Now;
                }
            }
            catch (Exception e)
            {
                _baconMan.MessageMan.DebugDia("Failed to set background image", e);
                TelemetryManager.ReportUnexpectedEvent(this, "Failed to set background image", e);
            }
        }
Exemplo n.º 25
0
        public async void OnNavigatingTo()
        {
            // Set the status bar color and get the size returned. If it is not 0 use that to move the
            // color of the page into the status bar.
            var statusBarHeight = await _host.SetStatusBar(null, 0);

            ApplicationSettingsRoot.Margin  = new Thickness(0, -statusBarHeight, 0, 0);
            ApplicationSettingsRoot.Padding = new Thickness(0, statusBarHeight, 0, 0);

            _takeAction = false;
            TelemetryManager.ReportEvent(this, "ApplicationSettings");
            AnalyticCollection.IsOn = App.BaconMan.UiSettingsMan.AnalyticCollection;
            _takeAction             = true;
        }
Exemplo n.º 26
0
 /// <summary>
 /// Fires FireOnDestroyContnet on the UI thread.
 /// </summary>
 /// <param name="host"></param>
 /// <param name="panel"></param>
 private async Task FireOnDestroyContent(IContentPanelBase panelBase)
 {
     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
     {
         try
         {
             panelBase.OnDestroyContent();
         }
         catch (Exception e)
         {
             App.BaconMan.MessageMan.DebugDia("FireOnRemovePanel failed", e);
             TelemetryManager.ReportUnexpectedEvent(this, "FireOnRemovePanelFailed", e);
         }
     });
 }
Exemplo n.º 27
0
        private void ViewUser_Click(object sender, RoutedEventArgs e)
        {
            // Get the post
            var post = (sender as FrameworkElement)?.DataContext as Post;

            if (post != null)
            {
                var args = new Dictionary <string, object> {
                    { PanelManager.NavArgsUserName, post.Author }
                };
                _host.Navigate(typeof(UserProfile), post.Author, args);
            }

            TelemetryManager.ReportEvent(this, "SubredditNavToUser");
        }
        public void SilentRefreshFailedNoCacheItemFoundTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle        = ServiceBundle.CreateWithCustomHttpManager(httpManager);
                var aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager());
                var authority            = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false);
                _cache = new TokenCache()
                {
                    ClientId      = MsalTestConstants.ClientId,
                    ServiceBundle = serviceBundle
                };

                httpManager.AddInstanceDiscoveryMockHandler();

                var parameters = new AuthenticationRequestParameters()
                {
                    Authority = authority,
                    ClientId  = MsalTestConstants.ClientId,
                    Scope     = ScopeHelper.CreateSortedSetFromEnumerable(
                        new[]
                    {
                        "some-scope1",
                        "some-scope2"
                    }),
                    TokenCache     = _cache,
                    Account        = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null),
                    RequestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))
                };

                var crypto           = PlatformProxyFactory.GetPlatformProxy().CryptographyManager;
                var telemetryManager = new TelemetryManager();

                try
                {
                    var request = new SilentRequest(serviceBundle, parameters, ApiEvent.ApiIds.None, false);
                    Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None);
                    var authenticationResult         = task.Result;
                    Assert.Fail("MsalUiRequiredException should be thrown here");
                }
                catch (AggregateException ae)
                {
                    var exc = ae.InnerException as MsalUiRequiredException;
                    Assert.IsNotNull(exc, "Actual exception type is " + ae.InnerException.GetType());
                    Assert.AreEqual(MsalUiRequiredException.NoTokensFoundError, exc.ErrorCode);
                }
            }
        }
        internal ServiceBundle(
            ApplicationConfiguration config,
            bool shouldClearCaches = false)
        {
            Config = config;

            ApplicationLogger = new MsalLogger(
                Guid.Empty,
                config.ClientName,
                config.ClientVersion,
                config.LogLevel,
                config.EnablePiiLogging,
                config.IsDefaultPlatformLoggingEnabled,
                config.LoggingCallback);

            PlatformProxy = config.PlatformProxy ?? PlatformProxyFactory.CreatePlatformProxy(ApplicationLogger);
            HttpManager   = config.HttpManager ?? new HttpManager(
                config.HttpClientFactory ??
                PlatformProxy.CreateDefaultHttpClientFactory());

            HttpTelemetryManager = new HttpTelemetryManager();
            if (config.TelemetryConfig != null)
            {
                // This can return null if the device isn't sampled in.  There's no need for processing MATS events if we're not going to send them.
                Mats = TelemetryClient.CreateMats(config, PlatformProxy, config.TelemetryConfig);
                MatsTelemetryManager = Mats?.TelemetryManager ??
                                       new TelemetryManager(config, PlatformProxy, config.TelemetryCallback);
            }
            else
            {
                MatsTelemetryManager = new TelemetryManager(config, PlatformProxy, config.TelemetryCallback);
            }

            InstanceDiscoveryManager = new InstanceDiscoveryManager(
                HttpManager,
                shouldClearCaches,
                config.CustomInstanceDiscoveryMetadata,
                config.CustomInstanceDiscoveryMetadataUri);

            WsTrustWebRequestManager = new WsTrustWebRequestManager(HttpManager);
            ThrottlingManager        = SingletonThrottlingManager.GetInstance();
            DeviceAuthManager        = config.DeviceAuthManagerForTest ?? PlatformProxy.CreateDeviceAuthManager();

            if (shouldClearCaches)
            {
                AuthorityManager.ClearValidationCache();
            }
        }
 internal ServiceBundle(
     IHttpClientFactory httpClientFactory = null,
     IHttpManager httpManager             = null,
     ITelemetryReceiver telemetryReceiver = null,
     IValidatedAuthoritiesCache validatedAuthoritiesCache = null,
     IAadInstanceDiscovery aadInstanceDiscovery           = null,
     IWsTrustWebRequestManager wsTrustWebRequestManager   = null,
     bool shouldClearCaches = false)
 {
     HttpManager               = httpManager ?? new HttpManager(httpClientFactory);
     TelemetryManager          = new TelemetryManager(telemetryReceiver ?? Telemetry.GetInstance());
     ValidatedAuthoritiesCache = validatedAuthoritiesCache ?? new ValidatedAuthoritiesCache(shouldClearCaches);
     AadInstanceDiscovery      = aadInstanceDiscovery ?? new AadInstanceDiscovery(HttpManager, TelemetryManager, shouldClearCaches);
     WsTrustWebRequestManager  = wsTrustWebRequestManager ?? new WsTrustWebRequestManager(HttpManager);
     PlatformProxy             = PlatformProxyFactory.GetPlatformProxy();
 }