Exemplo n.º 1
0
    public void UsesGetOrCreateSiteId()
    {
        var version = CreateUmbracoVersion(9, 3, 1);
        var siteIdentifierServiceMock   = new Mock <ISiteIdentifierService>();
        var usageInformationServiceMock = new Mock <IUsageInformationService>();
        var sut = new TelemetryService(
            Mock.Of <IManifestParser>(),
            version,
            siteIdentifierServiceMock.Object,
            usageInformationServiceMock.Object,
            Mock.Of <IMetricsConsentService>());
        Guid guid;

        sut.TryGetTelemetryReportData(out _);
        siteIdentifierServiceMock.Verify(x => x.TryGetOrCreateSiteIdentifier(out guid), Times.Once);
    }
        public async Task DeletesUserAndAndCanRespsectEmailAllowedSetting(bool emailAllowed, bool deleteSuccess)
        {
            Config.RespectEmailContactSetting = true;
            User.EmailAllowed = emailAllowed;
            AccountManager.Setup(x => x.DeleteAccount(It.IsAny <User>(), It.IsAny <string>())).ReturnsAsync(deleteSuccess);

            var processed = await Target.HandleAsync(Message);

            Assert.True(processed);
            TelemetryService.Verify(x => x.TrackDeleteResult(Message.Source, deleteSuccess), Times.Once);
            MessageService.Verify(
                x => x.SendMessageAsync(It.IsAny <IEmailBuilder>(), It.IsAny <bool>(), It.IsAny <bool>()),
                Times.Exactly(emailAllowed ? 1 : 0));
            TelemetryService.Verify(x => x.TrackEmailSent(It.IsAny <string>(), It.IsAny <bool>()), Times.Exactly(emailAllowed ? 1 : 0));
            TelemetryService.Verify(x => x.TrackEmailBlocked(It.IsAny <string>()), Times.Exactly(emailAllowed ? 0 : 1));
        }
        public override d0 GetResponse()
        {
            try
            {
                // checks
                if (_telemetryRequest == null || _telemetryRequest.Token == null)
                {
                    return(new d0
                    {
                        Success = false,
                    });
                }

                var result = false;

                if (TokenService.IsValidToken(_telemetryRequest.Token))
                {
                    TelemetryService.UpdateData(_telemetryRequest);
                    result = true;
                }

                // create response packet
                d0 responsePacket;
                using (var stream = new MemoryStream())
                {
                    var dataContractSerializer = new DataContractSerializer(typeof(TelemetryResponse));
                    dataContractSerializer.WriteObject(stream, new TelemetryResponse());

                    responsePacket = new d0
                    {
                        Success = result
                    };
                }

                return(responsePacket);
            }
            catch (Exception e)
            {
                ConsoleLogger.Write(e.ToString(), ConsoleColor.Red);
            }

            return(new d0
            {
                Success = false
            });
        }
Exemplo n.º 4
0
    public void ReturnsSemanticVersionWithoutBuild()
    {
        var version = CreateUmbracoVersion(9, 1, 1, "-rc", "-ad2f4k2d");

        var metricsConsentService = new Mock <IMetricsConsentService>();

        metricsConsentService.Setup(x => x.GetConsentLevel()).Returns(TelemetryLevel.Detailed);
        var sut = new TelemetryService(
            Mock.Of <IManifestParser>(),
            version,
            CreateSiteIdentifierService(),
            Mock.Of <IUsageInformationService>(),
            metricsConsentService.Object);

        var result = sut.TryGetTelemetryReportData(out var telemetry);

        Assert.IsTrue(result);
        Assert.AreEqual("9.1.1-rc", telemetry.Version);
    }
        public string RecordErrorForSubscriber(Subscription subscriber, Event @event, Exception exception)
        {
            var errorMessage = ConstructErrorMessage(subscriber, @event.Message,
                                                     exception.InnerException?.Message ?? exception.Message);

            Console.WriteLine(errorMessage);

            var telemetryService = new TelemetryService();

            telemetryService.LogTelemetry("0", "business-event", "subscription-error", new {
                Subscriber    = subscriber,
                MessageHeader = @event.Message.Header,
                EventHeader   = @event.Header,
                Exception     = exception,
                Message       = errorMessage
            });

            return(errorMessage);
        }
Exemplo n.º 6
0
        public void OnlyParsesIfValidId(string guidString, bool shouldSucceed)
        {
            var globalSettings = CreateGlobalSettings(guidString);
            var version        = CreateUmbracoVersion(9, 1, 1);
            var sut            = new TelemetryService(globalSettings, Mock.Of <IManifestParser>(), version);

            var result = sut.TryGetTelemetryReportData(out var telemetry);

            Assert.AreEqual(shouldSucceed, result);
            if (shouldSucceed)
            {
                // When toString is called on a GUID it will to lower, so do the same to our guidString
                Assert.AreEqual(guidString.ToLower(), telemetry.Id.ToString());
            }
            else
            {
                Assert.IsNull(telemetry);
            }
        }
Exemplo n.º 7
0
            public async Task AllowsEmptyObject()
            {
                var json = JsonConvert.SerializeObject(new Dictionary <string, string[]>());

                CloudBlob
                .Setup(x => x.OpenReadAsync(It.IsAny <AccessCondition>()))
                .ReturnsAsync(() => new MemoryStream(Encoding.UTF8.GetBytes(json)));

                var output = await Target.ReadLatestIndexedAsync();

                Assert.Empty(output.Result);
                Assert.Equal(ETag, output.AccessCondition.IfMatchETag);

                TelemetryService.Verify(
                    x => x.TrackReadLatestIndexedOwners(
                        /* packageIdCount: */ 0,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
            public async Task AllowsEmptyObject()
            {
                var json = JsonConvert.SerializeObject(new Dictionary <string, string[]>());

                CloudBlob
                .Setup(x => x.OpenReadAsync(It.IsAny <AccessCondition>()))
                .ReturnsAsync(() => new MemoryStream(Encoding.UTF8.GetBytes(json)));

                var output = await Target.ReadLatestIndexedAsync(AccessCondition.Object, StringCache);

                Assert.Empty(output.Data);
                Assert.Equal(ETag, output.Metadata.ETag);

                TelemetryService.Verify(
                    x => x.TrackReadLatestIndexedPopularityTransfers(
                        /*outgoingTransfers: */ 0,
                        /*modified: */ true,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
        public string RecordErrorForSubscriber(Subscription subscriber, Event @event, InvokeResponse response)
        {
            var errorMessage = ConstructErrorMessage(subscriber, @event.Message,
                                                     $"{response.StatusCode + " " + response.FunctionError + " " + response.Payload }");

            Console.WriteLine(errorMessage);

            var telemetryService = new TelemetryService();

            telemetryService.LogTelemetry("0", "business-event", "subscription-error", new
            {
                Subscriber    = subscriber,
                MessageHeader = @event.Message.Header,
                EventHeader   = @event.Header,
                Response      = response,
                Message       = errorMessage
            });

            return(errorMessage);
        }
        public string RecordErrorForSubscriber(Subscription subscriber, Event @event, HttpResponseMessage response)
        {
            var errorMessage = ConstructErrorMessage(subscriber, @event.Message,
                                                     $"{response.StatusCode + " " + response.ReasonPhrase + " " + response.Content.ReadAsStringAsync().Result }");

            Console.WriteLine(errorMessage);

            var telemetryService = new TelemetryService();

            telemetryService.LogTelemetry("0", "business-event", "subscription-error", new
            {
                Subscriber    = subscriber,
                MessageHeader = @event.Message.Header,
                EventHeader   = @event.Header,
                Response      = response,
                Message       = errorMessage
            });

            return(errorMessage);
        }
Exemplo n.º 11
0
            public void FindsRemovedOwner()
            {
                var oldData = OwnersData("NuGet.Core: NuGet, Microsoft");
                var newData = OwnersData("NuGet.Core: NuGet");

                var changes = Target.CompareOwners(oldData, newData);

                var pair = Assert.Single(changes);

                Assert.Equal("NuGet.Core", pair.Key);
                Assert.Equal(new[] { "NuGet" }, pair.Value);

                TelemetryService.Verify(
                    x => x.TrackOwnerSetComparison(
                        /*oldCount: */ 1,
                        /*newCount: */ 1,
                        /*changeCount: */ 1,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
Exemplo n.º 12
0
            public void IgnoresCaseChanges()
            {
                OldData.AddTransfer("PackageA", "packageb");
                OldData.AddTransfer("PackageA", "PackageC");

                NewData.AddTransfer("packagea", "PACKAGEB");
                NewData.AddTransfer("PackageA", "packageC");

                var changes = Target.ComparePopularityTransfers(OldData, NewData);

                Assert.Empty(changes);

                TelemetryService.Verify(
                    x => x.TrackPopularityTransfersSetComparison(
                        /*oldCount: */ 1,
                        /*newCount: */ 1,
                        /*changeCount: */ 0,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
Exemplo n.º 13
0
        private void InitializeServices()
        {
            // register our configuration service and initialize it
            SimpleIoc.Default.Register <ConfigurationService>();
            ConfigurationService configurationService = (ConfigurationService)SimpleIoc.Default.GetInstance <ConfigurationService>();

            if (null != configurationService)
            {
                // run this synchronously
                AsyncHelper.RunSync(() => configurationService.Initialize());
            }

            // register our localization service and initialize it
            SimpleIoc.Default.Register <LocalizationService>();
            LocalizationService localizationService = (LocalizationService)SimpleIoc.Default.GetInstance <LocalizationService>();

            if (null != localizationService)
            {
                // async here might lead to a race condition, but no signs so far
                //localizationService.Initialize();
                AsyncHelper.RunSync(() => localizationService.Initialize());
            }

            // initialize the telemetry service
            SimpleIoc.Default.Register <TelemetryService>();
            TelemetryService telemetryService = (TelemetryService)SimpleIoc.Default.GetInstance <TelemetryService>();

            if (null != telemetryService)
            {
                if (null != configurationService)
                {
                    // DO NOT try to run this asynchronously; MetroLog hangs when invoked async
                    //AsyncHelper.RunSync(() => telemetryService.Initialize(configurationService.Configuration.TelemetryKey));
                    telemetryService.Initialize(configurationService.Configuration.IsTelemetryEnabled,
                                                configurationService.Configuration.TelemetryKey);

                    // log app start
                    TelemetryService.Current?.LogTelemetryEvent(TelemetryEvents.StartApplication);
                }
            }
        }
Exemplo n.º 14
0
            public void FindsNoChanges()
            {
                var oldData = OwnersData(
                    "NuGet.Core: NuGet, Microsoft",
                    "NuGet.Versioning: NuGet, Microsoft");
                var newData = OwnersData(
                    "NuGet.Core: NuGet, Microsoft",
                    "NuGet.Versioning: NuGet, Microsoft");

                var changes = Target.CompareOwners(oldData, newData);

                Assert.Empty(changes);

                TelemetryService.Verify(
                    x => x.TrackOwnerSetComparison(
                        /*oldCount: */ 2,
                        /*newCount: */ 2,
                        /*changeCount: */ 0,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
            public async Task SerializesVersionsSortedOrder()
            {
                var newData = new PopularityTransferData();

                newData.AddTransfer("PackageB", "PackageA");
                newData.AddTransfer("PackageB", "PackageB");

                newData.AddTransfer("PackageA", "PackageC");
                newData.AddTransfer("PackageA", "packagec");
                newData.AddTransfer("PackageA", "packageC");
                newData.AddTransfer("PackageA", "PackageB");

                newData.AddTransfer("PackageC", "PackageZ");

                await Target.ReplaceLatestIndexedAsync(newData, AccessCondition.Object);

                // Pretty-ify the JSON to make the assertion clearer.
                var json = Assert.Single(SavedStrings);

                json = JsonConvert.DeserializeObject <JObject>(json).ToString();

                Assert.Equal(@"{
  ""PackageA"": [
    ""PackageB"",
    ""PackageC""
  ],
  ""PackageB"": [
    ""PackageA"",
    ""PackageB""
  ],
  ""PackageC"": [
    ""PackageZ""
  ]
}", json);
                TelemetryService.Verify(
                    x => x.TrackReplaceLatestIndexedPopularityTransfers(
                        /*outgoingTransfers: */ 3),
                    Times.Once);
                ReplaceLatestIndexedPopularityTransfersDurationMetric.Verify(x => x.Dispose(), Times.Once);
            }
Exemplo n.º 16
0
            public void FindsRemovedToPackage()
            {
                OldData.AddTransfer("PackageA", "PackageB");
                OldData.AddTransfer("PackageA", "PackageC");

                NewData.AddTransfer("PackageA", "PackageB");

                var changes = Target.ComparePopularityTransfers(OldData, NewData);

                var pair = Assert.Single(changes);

                Assert.Equal("PackageA", pair.Key);
                Assert.Equal(new[] { "PackageB" }, pair.Value);

                TelemetryService.Verify(
                    x => x.TrackPopularityTransfersSetComparison(
                        /*oldCount: */ 1,
                        /*newCount: */ 1,
                        /*changeCount: */ 1,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
            public async Task ReadsPopularityTransfers()
            {
                var json = JsonConvert.SerializeObject(new Dictionary <string, string[]>
                {
                    {
                        "windowsazure.servicebus",
                        new[] { "Azure.Messaging.ServiceBus" }
                    },
                    {
                        "WindowsAzure.Storage",
                        new[] { "Azure.Storage.Blobs", "Azure.Storage.Queues" }
                    },
                    {
                        "ZDuplicate",
                        new[] { "packageA", "packagea", "PACKAGEA", "packageB" }
                    },
                });

                CloudBlob
                .Setup(x => x.OpenReadAsync(It.IsAny <AccessCondition>()))
                .ReturnsAsync(() => new MemoryStream(Encoding.UTF8.GetBytes(json)));

                var output = await Target.ReadLatestIndexedAsync(AccessCondition.Object, StringCache);

                Assert.Equal(3, output.Data.Count);
                Assert.Equal(new[] { "windowsazure.servicebus", "WindowsAzure.Storage", "ZDuplicate" }, output.Data.Keys.ToArray());
                Assert.Equal(new[] { "Azure.Messaging.ServiceBus" }, output.Data["windowsazure.servicebus"].ToArray());
                Assert.Equal(new[] { "Azure.Storage.Blobs", "Azure.Storage.Queues" }, output.Data["WindowsAzure.Storage"].ToArray());
                Assert.Equal(new[] { "packageA", "packageB" }, output.Data["ZDuplicate"].ToArray());
                Assert.Equal(ETag, output.Metadata.ETag);

                CloudBlobContainer.Verify(x => x.GetBlobReference("popularity-transfers/popularity-transfers.v1.json"), Times.Once);
                TelemetryService.Verify(
                    x => x.TrackReadLatestIndexedPopularityTransfers(
                        /*outgoingTransfers: */ 3,
                        /*modified: */ true,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
Exemplo n.º 18
0
        public void RespectsAllowPackageTelemetry()
        {
            var globalSettings = CreateGlobalSettings();
            var version        = CreateUmbracoVersion(9, 1, 1);

            PackageManifest[] manifests =
            {
                new () { PackageName = "DoNotTrack",      AllowPackageTelemetry = false },
                new () { PackageName = "TrackingAllowed", AllowPackageTelemetry = true  }
            };
            var manifestParser = CreateManifestParser(manifests);
            var sut            = new TelemetryService(globalSettings, manifestParser, version);

            var success = sut.TryGetTelemetryReportData(out var telemetry);

            Assert.IsTrue(success);
            Assert.Multiple(() =>
            {
                Assert.AreEqual(1, telemetry.Packages.Count());
                Assert.AreEqual("TrackingAllowed", telemetry.Packages.First().Name);
            });
        }
Exemplo n.º 19
0
            public void DetectsDecreaseDueToMissingId()
            {
                var oldData = new DownloadData();

                oldData.SetDownloadCount(IdA, V1, 7);
                oldData.SetDownloadCount(IdA, V2, 1);
                oldData.SetDownloadCount(IdB, V1, 1);
                var newData = new DownloadData();

                newData.SetDownloadCount(IdB, V1, 1);

                var delta = Target.Compare(oldData, newData);

                Assert.Equal(KeyValuePair.Create(IdA, 0L), Assert.Single(delta));
                VerifyDecreaseTelemetry(Times.Exactly(2));
                TelemetryService.Verify(
                    x => x.TrackDownloadCountDecrease(
                        IdA,
                        V1,
                        true,
                        true,
                        7,
                        false,
                        false,
                        0),
                    Times.Once);
                TelemetryService.Verify(
                    x => x.TrackDownloadCountDecrease(
                        IdA,
                        V2,
                        true,
                        true,
                        1,
                        false,
                        false,
                        0),
                    Times.Once);
            }
Exemplo n.º 20
0
        private async void RefreshUI()
        {
            switch (MusicPlayerState)
            {
            case MediaPlaybackState.Playing:
                TelemetryService.WriteEvent("MusicPlaying");
                MusicPlayerStatusText = MusicPlayerStatusPlayingText;
                break;

            case MediaPlaybackState.Paused:
                MusicPlayerStatusText = MusicPlayerStatusPausedText;
                break;

            case MediaPlaybackState.Opening:
                MusicPlayerStatusText = MusicPlayerStatusLoadingText;
                break;

            case MediaPlaybackState.Buffering:
                MusicPlayerStatusText = MusicPlayerStatusLoadingText;
                break;

            default:
                MusicPlayerStatusText = MusicPlayerStatusDefaultText;
                break;
            }

            if (SelectedMediaIndex >= 0 && SelectedMediaIndex < MediaFileCollection.Count)
            {
                _currentFile = MediaFileCollection.ElementAt(SelectedMediaIndex);
                await RefreshMediaInfoAsync(_currentFile);
            }
            else
            {
                SongTitleText       = string.Empty;
                SongArtistText      = string.Empty;
                SongThumbnailSource = DefaultPicture;
            }
        }
        public TelemetryServiceTest()
        {
            _dateTimeServiceStub = new DateTimeServiceStub
            {
                Now = DateTime.Now
            };

            _httpContext = new DefaultHttpContext
            {
                Request =
                {
                    Method   = "GET",
                    Protocol = "http",
                    Host     = new HostString("localhost", 80),
                    Path     = PathString.FromUriComponent("/budgets/06/2016")
                }
            };

            _exceptionRepository = new InMemoryRepository <TelemetryException>();
            _eventRepository     = new InMemoryRepository <TelemetryEvent>();
            _timingRepository    = new InMemoryRepository <TelemetryTiming>();
            _telemetryService    = new TelemetryService(_exceptionRepository, _eventRepository, _timingRepository, _dateTimeServiceStub);
        }
Exemplo n.º 22
0
            public async Task AllowsMissingBlob()
            {
                CloudBlob
                .Setup(x => x.OpenReadAsync(It.IsAny <AccessCondition>()))
                .ThrowsAsync(new StorageException(
                                 new RequestResult
                {
                    HttpStatusCode = (int)HttpStatusCode.NotFound,
                },
                                 message: "Not found.",
                                 inner: null));

                var output = await Target.ReadLatestIndexedAsync();

                Assert.Empty(output.Result);
                Assert.Equal("*", output.AccessCondition.IfNoneMatchETag);

                TelemetryService.Verify(
                    x => x.TrackReadLatestIndexedOwners(
                        /* packageIdCount: */ 0,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
Exemplo n.º 23
0
        private void UpdateManager_OnUpdateOperationError(object sender, StorePackageUpdateStateEventArgs e)
        {
            switch (e.State)
            {
            case StorePackageUpdateState.ErrorLowBattery:
                AppService.DisplayDialog(AppUpdateDialogHeaderText, BatteryLowErrorText);
                TelemetryService.WriteEvent("AppUpdateError", new
                {
                    StorePackageUpdateState = StorePackageUpdateState.ErrorLowBattery
                });
                break;

            case StorePackageUpdateState.ErrorWiFiRecommended:
                AppService.DisplayDialog(AppUpdateDialogHeaderText, ConnectionErrorText);
                TelemetryService.WriteEvent("AppUpdateError", new
                {
                    StorePackageUpdateState = StorePackageUpdateState.ErrorWiFiRecommended
                });
                break;

            case StorePackageUpdateState.ErrorWiFiRequired:
                AppService.DisplayDialog(AppUpdateDialogHeaderText, ConnectionErrorText);
                TelemetryService.WriteEvent("AppUpdateError", new
                {
                    StorePackageUpdateState = StorePackageUpdateState.ErrorWiFiRequired
                });
                break;

            case StorePackageUpdateState.OtherError:
                AppService.DisplayDialog(AppUpdateDialogHeaderText, UnknownErrorText);
                TelemetryService.WriteEvent("AppUpdateError", new
                {
                    StorePackageUpdateState = StorePackageUpdateState.OtherError
                });
                break;
            }
        }
Exemplo n.º 24
0
            public void FindsNoChanges()
            {
                OldData.AddTransfer("PackageA", "PackageB");
                OldData.AddTransfer("PackageA", "PackageC");
                OldData.AddTransfer("Package1", "Package3");
                OldData.AddTransfer("Package1", "Package2");

                NewData.AddTransfer("PackageA", "PackageC");
                NewData.AddTransfer("PackageA", "PackageB");
                NewData.AddTransfer("Package1", "Package2");
                NewData.AddTransfer("Package1", "Package3");

                var changes = Target.ComparePopularityTransfers(OldData, NewData);

                Assert.Empty(changes);

                TelemetryService.Verify(
                    x => x.TrackPopularityTransfersSetComparison(
                        /*oldCount: */ 2,
                        /*newCount: */ 2,
                        /*changeCount: */ 0,
                        It.IsAny <TimeSpan>()),
                    Times.Once);
            }
Exemplo n.º 25
0
        protected override async Task RunInternalAsync(CancellationToken cancellationToken)
        {
            using (Logger.BeginScope($"Logging for {{{TelemetryConstants.Destination}}}", Destination.AbsoluteUri))
                using (TelemetryService.TrackDuration(TelemetryConstants.JobLoopSeconds))
                    using (var client = CreateHttpClient())
                    {
                        uint packagesDeleted;
                        uint packagesCreated;
                        uint packagesEdited;

                        client.Timeout = Timeout;

                        var packageCatalogItemCreator = PackageCatalogItemCreator.Create(
                            client,
                            TelemetryService,
                            Logger,
                            PreferredPackageSourceStorage);

                        do
                        {
                            packagesDeleted = 0;
                            packagesCreated = 0;
                            packagesEdited  = 0;

                            // baseline timestamps
                            var catalogProperties = await CatalogProperties.ReadAsync(CatalogStorage, TelemetryService, cancellationToken);

                            var lastCreated = catalogProperties.LastCreated ?? (StartDate ?? Constants.DateTimeMinValueUtc);
                            var lastEdited  = catalogProperties.LastEdited ?? lastCreated;
                            var lastDeleted = catalogProperties.LastDeleted ?? lastCreated;

                            if (lastDeleted == Constants.DateTimeMinValueUtc)
                            {
                                lastDeleted = SkipCreatedPackagesProcessing ? lastEdited : lastCreated;
                            }

                            try
                            {
                                if (lastDeleted > Constants.DateTimeMinValueUtc)
                                {
                                    using (TelemetryService.TrackDuration(TelemetryConstants.DeletedPackagesSeconds))
                                    {
                                        Logger.LogInformation("CATALOG LastDeleted: {CatalogDeletedTime}", lastDeleted.ToString("O"));

                                        var deletedPackages = await GetDeletedPackages(AuditingStorage, lastDeleted);

                                        packagesDeleted = (uint)deletedPackages.SelectMany(x => x.Value).Count();
                                        Logger.LogInformation("FEED DeletedPackages: {DeletedPackagesCount}", packagesDeleted);

                                        // We want to ensure a commit only contains each package once at most.
                                        // Therefore we segment by package id + version.
                                        var deletedPackagesSegments = SegmentPackageDeletes(deletedPackages);
                                        foreach (var deletedPackagesSegment in deletedPackagesSegments)
                                        {
                                            lastDeleted = await Deletes2Catalog(
                                                deletedPackagesSegment, CatalogStorage, lastCreated, lastEdited, lastDeleted, cancellationToken);

                                            // Wait for one second to ensure the next catalog commit gets a new timestamp
                                            Thread.Sleep(TimeSpan.FromSeconds(1));
                                        }
                                    }
                                }

                                if (!SkipCreatedPackagesProcessing)
                                {
                                    using (TelemetryService.TrackDuration(TelemetryConstants.CreatedPackagesSeconds))
                                    {
                                        Logger.LogInformation("CATALOG LastCreated: {CatalogLastCreatedTime}", lastCreated.ToString("O"));

                                        var createdPackages = await GalleryDatabaseQueryService.GetPackagesCreatedSince(lastCreated, Top);

                                        packagesCreated = (uint)createdPackages.SelectMany(x => x.Value).Count();
                                        Logger.LogInformation("DATABASE CreatedPackages: {CreatedPackagesCount}", packagesCreated);

                                        lastCreated = await CatalogWriterHelper.WritePackageDetailsToCatalogAsync(
                                            packageCatalogItemCreator,
                                            createdPackages,
                                            CatalogStorage,
                                            lastCreated,
                                            lastEdited,
                                            lastDeleted,
                                            MaxDegreeOfParallelism,
                                            createdPackages : true,
                                            updateCreatedFromEdited : false,
                                            cancellationToken : cancellationToken,
                                            telemetryService : TelemetryService,
                                            logger : Logger);
                                    }
                                }

                                using (TelemetryService.TrackDuration(TelemetryConstants.EditedPackagesSeconds))
                                {
                                    Logger.LogInformation("CATALOG LastEdited: {CatalogLastEditedTime}", lastEdited.ToString("O"));

                                    var editedPackages = await GalleryDatabaseQueryService.GetPackagesEditedSince(lastEdited, Top);

                                    packagesEdited = (uint)editedPackages.SelectMany(x => x.Value).Count();
                                    Logger.LogInformation("DATABASE EditedPackages: {EditedPackagesCount}", packagesEdited);

                                    lastEdited = await CatalogWriterHelper.WritePackageDetailsToCatalogAsync(
                                        packageCatalogItemCreator,
                                        editedPackages,
                                        CatalogStorage,
                                        lastCreated,
                                        lastEdited,
                                        lastDeleted,
                                        MaxDegreeOfParallelism,
                                        createdPackages : false,
                                        updateCreatedFromEdited : SkipCreatedPackagesProcessing,
                                        cancellationToken : cancellationToken,
                                        telemetryService : TelemetryService,
                                        logger : Logger);
                                }
                            }
                            finally
                            {
                                TelemetryService.TrackMetric(TelemetryConstants.DeletedPackagesCount, packagesDeleted);

                                if (!SkipCreatedPackagesProcessing)
                                {
                                    TelemetryService.TrackMetric(TelemetryConstants.CreatedPackagesCount, packagesCreated);
                                }

                                TelemetryService.TrackMetric(TelemetryConstants.EditedPackagesCount, packagesEdited);
                            }
                        } while (packagesDeleted > 0 || packagesCreated > 0 || packagesEdited > 0);
                    }
        }
Exemplo n.º 26
0
        public App()
        {
            // save a pointer to ourself
            App.Current = this;

            InitializeComponent();

            // app lifecycle event handlers
            EnteredBackground  += OnEnteredBackground;
            Suspending         += OnSuspending;
            Resuming           += OnResuming;
            UnhandledException += OnUnhandledException;

            // we want full screen, but leave this off during dev
            ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.FullScreen;
            //ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto;

            // we want landscape only
            DisplayOrientations orientations = DisplayOrientations.Landscape;

            DisplayInformation.AutoRotationPreferences = orientations;

            // Deferred execution until used. Check https://msdn.microsoft.com/library/dd642331(v=vs.110).aspx for further info on Lazy<T> class.
            _activationService = new Lazy <ActivationService>(CreateActivationService);

            // register our configuration service and initialize it
            SimpleIoc.Default.Register <ConfigurationService>();
            ConfigurationService configurationService = (ConfigurationService)SimpleIoc.Default.GetInstance <ConfigurationService>();

            if (null != configurationService)
            {
                // run this synchronously
                AsyncHelper.RunSync(() => configurationService.Initialize());
            }

            // register our localization service and initialize it
            SimpleIoc.Default.Register <LocalizationService>();
            LocalizationService localizationService = (LocalizationService)SimpleIoc.Default.GetInstance <LocalizationService>();

            if (null != localizationService)
            {
                // async here might lead to a race condition, but no signs so far
                //localizationService.Initialize();
                AsyncHelper.RunSync(() => localizationService.Initialize());
            }

            // initialize the telemetry service
            SimpleIoc.Default.Register <TelemetryService>();
            TelemetryService telemetryService = (TelemetryService)SimpleIoc.Default.GetInstance <TelemetryService>();

            if (null != telemetryService)
            {
                if (null != configurationService)
                {
                    // DO NOT try to run this asynchronously; MetroLog hangs when invoked async
                    //AsyncHelper.RunSync(() => telemetryService.Initialize(configurationService.Configuration.TelemetryKey));
                    telemetryService.Initialize(configurationService.Configuration.IsTelemetryEnabled,
                                                configurationService.Configuration.TelemetryKey);

                    // log app start
                    TelemetryService.Current?.LogTelemetryEvent(TelemetryEvents.StartApplication);
                }
            }
        }
Exemplo n.º 27
0
        public static async Task MainAsync(string[] args)
        {
            if (args.Length > 0 && string.Equals("dbg", args[0], StringComparison.OrdinalIgnoreCase))
            {
                args = args.Skip(1).ToArray();
                Debugger.Launch();
            }

            NgJob job = null;

            try
            {
                // Get arguments
                var arguments = CommandHelpers.GetArguments(args, 1);

                // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled.
                ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

                // Determine the job name
                if (args.Length == 0)
                {
                    throw new ArgumentException("Missing job name argument.");
                }

                var jobName = args[0];
                TelemetryConfiguration.Active.TelemetryInitializers.Add(new JobNameTelemetryInitializer(jobName));

                // Configure ApplicationInsights
                ApplicationInsights.Initialize(arguments.GetOrDefault <string>(Arguments.InstrumentationKey));

                // Create an ILoggerFactory
                var loggerConfiguration = LoggingSetup.CreateDefaultLoggerConfiguration(withConsoleLogger: true);
                loggerConfiguration.WriteTo.File("Log.txt", retainedFileCountLimit: 3, fileSizeLimitBytes: 1000000, rollOnFileSizeLimit: true);

                var loggerFactory = LoggingSetup.CreateLoggerFactory(loggerConfiguration, LogEventLevel.Debug);

                // Create a logger that is scoped to this class (only)
                _logger = loggerFactory.CreateLogger <Program>();

                var cancellationTokenSource = new CancellationTokenSource();

                // Create an ITelemetryService
                var telemetryService = new TelemetryService(new TelemetryClient());

                // Allow jobs to set global custom dimensions
                TelemetryConfiguration.Active.TelemetryInitializers.Add(new JobPropertiesTelemetryInitializer(telemetryService));

                job = NgJobFactory.GetJob(jobName, telemetryService, loggerFactory);
                await job.RunAsync(arguments, cancellationTokenSource.Token);
            }
            catch (ArgumentException ae)
            {
                _logger?.LogError("A required argument was not found or was malformed/invalid: {Exception}", ae);

                Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase());
            }
            catch (Exception e)
            {
                _logger?.LogCritical("A critical exception occured in ng.exe! {Exception}", e);
            }

            Trace.Close();
            TelemetryConfiguration.Active.TelemetryChannel.Flush();
        }
Exemplo n.º 28
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            if (_people == null)
            {
                _people = await PeopleService.GetPeopleLisAtAsync();
            }

            var mess = await result as IMessageActivity;

            if (context.ConversationData.ContainsKey(Constants.LAST_PERSON_KEY))
            {
                var lastPerson = context.ConversationData.GetValue <Person>(Constants.LAST_PERSON_KEY);

                var guessResult = _people.FindByName(mess.Text);
                if (guessResult.Count > 3 && guessResult.Contains(lastPerson, new PersonComparer()))
                {
                    await context.PostAsync("That is too generic. Try again.");

                    context.Wait(MessageReceivedAsync);
                }
                else if (guessResult.Contains(lastPerson, new PersonComparer()))
                {
                    // správná odpověď
                    TelemetryService.SendTelemetry(new TelemetryModel("correct", lastPerson.Name));

                    await context.PostAsync("✔️ Correct!");

                    // zvednout skóre
                    if (context.ConversationData.ContainsKey(Constants.SECOND_CHANCE))
                    {
                        await context.PostAsync("That's **0.5** points for you.");

                        await Utils.ChangeScoreAsync(context, 0.5);

                        context.ConversationData.RemoveValue(Constants.SECOND_CHANCE);
                    }
                    else
                    {
                        await context.PostAsync("That's **2** points for you.");

                        await Utils.ChangeScoreAsync(context, 2);
                    }

                    // DEBUG
                    //context.Done(1.0);
                    //return;

                    // zobrazit další
                    await GoNext(context);
                }
                else
                {
                    // špatná odpověď - dáme nápovědu, pokud už nejsme v nápovědě :)
                    TelemetryService.SendTelemetry(new TelemetryModel("incorrect", lastPerson.Name));

                    if (context.ConversationData.ContainsKey(Constants.SECOND_CHANCE))
                    {
                        await context.PostAsync($"❌ That is not correct. Let's try another speaker.");

                        context.ConversationData.RemoveValue(Constants.SECOND_CHANCE);

                        await GoNext(context);
                    }
                    else
                    {
                        await context.PostAsync("Not correct. I'll give you a hint. But it will be for less points. This person's name is one of those:");

                        var msg = context.MakeMessage();
                        msg.Attachments.Add(PrepareButtonsCard(_people.GetRandomPeople(lastPerson, 5).Select(p => p.Name).ToArray()).ToAttachment());
                        await context.PostAsync(msg);

                        context.ConversationData.SetValue(Constants.SECOND_CHANCE, "true");

                        context.Wait(MessageReceivedAsync);
                    }
                }
            }
            else
            {
                await GoNext(context);
            }
        }
 /// <summary>
 /// Is called, when the TelemetryToggleSwitch is clicked. Calls SetUseTelemetry of TelemetryService.
 /// </summary>
 private void TelemetryToggleSwitch_Toggled(object sender, RoutedEventArgs e)
 {
     TelemetryService.SetUseTelemetry(((ToggleSwitch)sender).IsOn);
 }
Exemplo n.º 30
0
 public TelemetryController(TelemetryService telemetryService)
 {
     _telemetryService = telemetryService;
 }