/// <summary>
        /// Views the usage.
        /// </summary>
        /// <param name="customerId">The customer identifier.</param>
        /// <param name="subscriptionId">The subscription identifier.</param>
        /// <returns>The HTML template for the view usage page.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="customerId"/> is empty or null.
        /// or
        /// <paramref name="subscriptionId"/> is empty or null.
        /// </exception>
        public async Task <ActionResult> ViewUsage(string customerId, string subscriptionId)
        {
            Customer     customer;
            Subscription subscription;

            customerId.AssertNotEmpty(nameof(customerId));
            subscriptionId.AssertNotEmpty(nameof(subscriptionId));

            try
            {
                customer = await this.Service.PartnerOperations.GetCustomerAsync(customerId);

                subscription = await this.Service.PartnerOperations.GetSubscriptionAsync(customerId, subscriptionId);

                UsageModel usageModel = new UsageModel()
                {
                    CompanyName              = customer.CompanyProfile.CompanyName,
                    CustomerId               = customerId,
                    SubscriptionId           = subscriptionId,
                    SubscriptionFriendlyName = subscription.FriendlyName,
                    Usage = await this.Service.PartnerOperations
                            .GetSubscriptionUsageAsync(customerId, subscriptionId, DateTime.Now.AddMonths(-1), DateTime.Now)
                };


                return(this.View(usageModel));
            }
            finally
            {
                customer     = null;
                subscription = null;
            }
        }
Exemplo n.º 2
0
        static void ClearCounters(UsageModel usage, bool weekly, bool monthly)
        {
            usage.NumberOfStartups                    = 0;
            usage.NumberOfClones                      = 0;
            usage.NumberOfReposCreated                = 0;
            usage.NumberOfReposPublished              = 0;
            usage.NumberOfGists                       = 0;
            usage.NumberOfOpenInGitHub                = 0;
            usage.NumberOfLinkToGitHub                = 0;
            usage.NumberOfLogins                      = 0;
            usage.NumberOfUpstreamPullRequests        = 0;
            usage.NumberOfPullRequestsOpened          = 0;
            usage.NumberOfLocalPullRequestsCheckedOut = 0;
            usage.NumberOfLocalPullRequestPulls       = 0;
            usage.NumberOfLocalPullRequestPushes      = 0;
            usage.NumberOfForkPullRequestsCheckedOut  = 0;
            usage.NumberOfForkPullRequestPulls        = 0;
            usage.NumberOfForkPullRequestPushes       = 0;

            if (weekly)
            {
                usage.NumberOfStartupsWeek = 0;
            }

            if (monthly)
            {
                usage.NumberOfStartupsMonth = 0;
            }
        }
Exemplo n.º 3
0
        async Task <UsageModel> GetCurrentReport(UsageData data)
        {
            var current = data.Reports.FirstOrDefault(x => x.Dimensions.Date.Date == DateTimeOffset.Now.Date);

            if (current == null)
            {
                var guid = await service.GetUserGuid();

                current = UsageModel.Create(guid);
                data.Reports.Add(current);
            }

            current.Dimensions.Lang        = CultureInfo.InstalledUICulture.IetfLanguageTag;
            current.Dimensions.CurrentLang = CultureInfo.CurrentCulture.IetfLanguageTag;
            current.Dimensions.AppVersion  = AssemblyVersionInformation.Version;
            current.Dimensions.VSVersion   = vsservices.VSVersion;

            if (connectionManager.Connections.Any(x => x.HostAddress.IsGitHubDotCom()))
            {
                current.Dimensions.IsGitHubUser = true;
            }

            if (connectionManager.Connections.Any(x => !x.HostAddress.IsGitHubDotCom()))
            {
                current.Dimensions.IsEnterpriseUser = true;
            }

            return(current);
        }
        /// <summary>
        /// Views the usage.
        /// </summary>
        /// <param name="customerId">The customer identifier.</param>
        /// <param name="subscriptionId">The subscription identifier.</param>
        /// <returns>The HTML template for the view usage page.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="customerId"/> is empty or null.
        /// or
        /// <paramref name="subscriptionId"/> is empty or null.
        /// </exception>
        public async Task <ActionResult> ViewUsage(string customerId, string subscriptionId)
        {
            Customer     customer;
            Subscription subscription;

            customerId.AssertNotEmpty(nameof(customerId));
            subscriptionId.AssertNotEmpty(nameof(subscriptionId));

            try
            {
                customer = await Provider.PartnerOperations.GetCustomerAsync(customerId).ConfigureAwait(false);

                subscription = await Provider.PartnerOperations.GetSubscriptionAsync(customerId, subscriptionId).ConfigureAwait(false);

                UsageModel usageModel = new UsageModel()
                {
                    CompanyName              = customer.CompanyProfile.CompanyName,
                    CustomerId               = customerId,
                    SubscriptionId           = subscriptionId,
                    SubscriptionFriendlyName = subscription.FriendlyName,
                };

                usageModel.Usage.AddRange(await Provider.PartnerOperations
                                          .GetSubscriptionUsageAsync(customerId, subscriptionId, DateTime.Now.AddMonths(-1), DateTime.Now)
                                          .ConfigureAwait(false));

                return(View(usageModel));
            }
            finally
            {
                customer     = null;
                subscription = null;
            }
        }
Exemplo n.º 5
0
        static StringContent SerializeRequest(UsageModel model)
        {
            var serializer = new SimpleJsonSerializer();
            var dictionary = ToModelDictionary(model);

            return(new StringContent(serializer.Serialize(dictionary), Encoding.UTF8, "application/json"));
        }
Exemplo n.º 6
0
        public async Task IncrementsLoginCount()
        {
            var apiClient = Substitute.For <IApiClient>();

            apiClient.HostAddress.Returns(HostAddress.GitHubDotComHostAddress);
            apiClient.GetOrCreateApplicationAuthenticationCode(
                Args.TwoFactorChallengCallback, Args.String, Args.Boolean)
            .Returns(Observable.Return(new ApplicationAuthorization("S3CR3TS")));
            apiClient.GetUser().Returns(Observable.Return(CreateOctokitUser("baymax")));
            var hostCache    = new InMemoryBlobCache();
            var modelService = Substitute.For <IModelService>();
            var loginManager = Substitute.For <ILoginManager>();

            loginManager.Login(HostAddress.GitHubDotComHostAddress, Arg.Any <IGitHubClient>(), "baymax", "aPassword").Returns(CreateOctokitUser("baymax"));
            var loginCache = new TestLoginCache();
            var usage      = Substitute.For <IUsageTracker>();
            var host       = new RepositoryHost(apiClient, modelService, loginManager, loginCache, usage);

            var result = await host.LogIn("baymax", "aPassword");

            var model = new UsageModel();

            await usage.Received().IncrementCounter(
                Arg.Is <Expression <Func <UsageModel, int> > >(x =>
                                                               ((MemberExpression)x.Body).Member.Name == nameof(model.NumberOfLogins)));
        }
Exemplo n.º 7
0
        public async Task ShouldWriteUpdatedData()
        {
            var model = UsageModel.Create(Guid.NewGuid());

            //model.Dimensions.AppVersion = AssemblyVersionInformation.Version;
            model.Dimensions.Lang         = CultureInfo.InstalledUICulture.IetfLanguageTag;
            model.Dimensions.CurrentLang  = CultureInfo.CurrentCulture.IetfLanguageTag;
            model.Measures.NumberOfClones = 1;
            var service = CreateUsageService(model);

            var target = new UsageTracker(
                CreateServiceProvider(),
                service,
                CreatePackageSettings(),
                new JoinableTaskContext(),
                vsTelemetry: false);

            await target.IncrementCounter(x => x.NumberOfClones);

            await service.Received(1).WriteLocalData(Arg.Is <UsageData>(data =>
                                                                        data.Reports.Count == 1 &&
                                                                        data.Reports[0].Dimensions.Date.Date == DateTimeOffset.Now.Date &&
                                                                        //data.Reports[0].Dimensions.AppVersion == AssemblyVersionInformation.Version &&
                                                                        data.Reports[0].Dimensions.Lang == CultureInfo.InstalledUICulture.IetfLanguageTag &&
                                                                        data.Reports[0].Dimensions.CurrentLang == CultureInfo.CurrentCulture.IetfLanguageTag &&
                                                                        data.Reports[0].Measures.NumberOfClones == 2
                                                                        ));
        }
Exemplo n.º 8
0
        public async Task FirstTickShouldIncrementLaunchCount()
        {
            var service       = CreateUsageService(UsageModel.Create(Guid.NewGuid()));
            var targetAndTick = CreateTargetAndGetTick(CreateServiceProvider(), service);

            await targetAndTick.Item2();

            await service.Received(1).WriteLocalData(Arg.Any <UsageData>());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PSHpcCacheUsageModels"/> class.
 /// PSHpcCacheUsageModels.
 /// </summary>
 /// <param name="usagemodel"> usagemodel.</param>
 public PSHpcCacheUsageModels(UsageModel usagemodel)
 {
     if (usagemodel != null)
     {
         this.Name       = usagemodel.ModelName;
         this.TargetType = usagemodel.TargetType;
         this.Display    = usagemodel.Display.Description;
     }
 }
Exemplo n.º 10
0
        async Task SendUsage(UsageModel usage, bool includeWeekly, bool includeMonthly)
        {
            if (client == null)
            {
                throw new GitHubLogicException("SendUsage should not be called when there is no IMetricsService");
            }

            var model = usage.Clone(includeWeekly, includeMonthly);
            await client.PostUsage(model);
        }
Exemplo n.º 11
0
 static IUsageService CreateUsageService(
     UsageModel model = null)
 {
     return(CreateUsageService(new UsageData
     {
         Reports = model != null ? new List <UsageModel> {
             model
         } : new List <UsageModel>()
     }));
 }
Exemplo n.º 12
0
 //Insert and Update new record
 public Task <int> SaveItemAsync(UsageModel obj)
 {
     if (obj.UsageID != 0)
     {
         return(db.UpdateAsync(obj));
     }
     else
     {
         return(db.InsertAsync(obj));
     }
 }
Exemplo n.º 13
0
        public static StringContent SerializeRequest(UsageModel model)
        {
            var serializer = new SimpleJsonSerializer();
            var dictionary = new Dictionary <string, object>
            {
                { ToJsonPropertyName("Dimensions"), ToModelDictionary(model.Dimensions) },
                { ToJsonPropertyName("Measures"), ToModelDictionary(model.Measures) }
            };

            return(new StringContent(serializer.Serialize(dictionary), Encoding.UTF8, "application/json"));
        }
Exemplo n.º 14
0
 static IUsageService CreateUsageService(
     UsageModel model,
     bool sameDay   = true,
     bool sameWeek  = true,
     bool sameMonth = true)
 {
     return(CreateUsageService(new UsageData
     {
         LastUpdated = DateTimeOffset.Now,
         Model = model
     }, sameDay, sameWeek, sameMonth));
 }
Exemplo n.º 15
0
        public async Task TickShouldNotSendDataIfSameDay()
        {
            var serviceProvider = CreateServiceProvider();
            var targetAndTick   = CreateTargetAndGetTick(
                serviceProvider,
                CreateUsageService(UsageModel.Create(Guid.NewGuid())));

            await targetAndTick.Item2();

            var metricsService = serviceProvider.TryGetService <IMetricsService>();
            await metricsService.DidNotReceive().PostUsage(Arg.Any <UsageModel>());
        }
Exemplo n.º 16
0
        public async Task SubsequentTickShouldNotIncrementLaunchCount()
        {
            var service       = CreateUsageService(UsageModel.Create(Guid.NewGuid()));
            var targetAndTick = CreateTargetAndGetTick(CreateServiceProvider(), service);

            await targetAndTick.Item2();

            service.ClearReceivedCalls();
            await targetAndTick.Item2();

            await service.DidNotReceiveWithAnyArgs().WriteLocalData(null);
        }
Exemplo n.º 17
0
        public async Task <bool> SaveUsage()
        {
            DateTime dateTime          = DateTime.Now;
            var      timeApp           = "";
            DateTime timeOfDayGreeting = DateTime.Now;

            if (timeOfDayGreeting.Hour >= 5 && timeOfDayGreeting.Hour < 12)
            {
                timeApp = "Morning Application";
            }
            else if (timeOfDayGreeting.Hour >= 12 && timeOfDayGreeting.Hour < 18)
            {
                timeApp = "Afternoon Application";
            }
            else if (timeOfDayGreeting.Hour >= 19 && timeOfDayGreeting.Hour < 23)
            {
                timeApp = "Night Time Application";
            }
            else
            {
                timeApp = "Midnight Application";
            }
            if (!string.IsNullOrEmpty(_applicationType) || !string.IsNullOrEmpty(_note))
            {
                UsageModel usage = new UsageModel()
                {
                    Title       = _applicationType,
                    Description = _note,
                    Date        = DateTime.Now,
                    Image       = "header",
                    Duration    = dateTime.ToString("hh:mm tt"),
                    Venue       = timeApp
                };

                //Add New Usage
                await App.SQLiteDb.SaveItemAsync(usage);

                ApplicationType = string.Empty;
                Note            = string.Empty;
                await PopupNavigation.Instance.PushAsync(new MessageModal("Added Record"), true);

                //RecordViewModel recordViewModel = new RecordViewModel();
                //recordViewModel.GetDbUses();
                return(true);
            }
            else
            {
                await PopupNavigation.Instance.PushAsync(new MessageModal("Whoops!! Please try again"), true);

                return(false);
            }
        }
Exemplo n.º 18
0
        UsageModel UpdateModelUserData(UsageModel model)
        {
            if (connectionManager.Connections.Any(x => x.HostAddress.IsGitHubDotCom()))
            {
                model.IsGitHubUser = true;
            }

            if (connectionManager.Connections.Any(x => !x.HostAddress.IsGitHubDotCom()))
            {
                model.IsEnterpriseUser = true;
            }
            return(model);
        }
Exemplo n.º 19
0
            public async Task ShouldIncrementCounter()
            {
                var model = new UsageModel {
                    NumberOfClones = 4
                };
                var target = new UsageTracker(
                    CreateServiceProvider(),
                    CreateUsageService(model));

                await target.IncrementCounter(x => x.NumberOfClones);

                Assert.That(5, Is.EqualTo(model.NumberOfClones));
            }
        public async Task UpdatesMetricsWhenRepositoryClonedAsync(string cloneUrl, int numberOfCalls, string counterName)
        {
            var vsGitServices = Substitute.For <IVSGitServices>();
            var usageTracker  = Substitute.For <IUsageTracker>();
            var cloneService  = CreateRepositoryCloneService(vsGitServices: vsGitServices, usageTracker: usageTracker);

            await cloneService.CloneRepository(cloneUrl, @"c:\dev\bar");

            var model = UsageModel.Create(Guid.NewGuid());

            await usageTracker.Received(numberOfCalls).IncrementCounter(
                Arg.Is <Expression <Func <UsageModel.MeasuresModel, int> > >(x =>
                                                                             ((MemberExpression)x.Body).Member.Name == counterName));
        }
Exemplo n.º 21
0
        public JsonResult DecreaseQty(UsageModel model)
        {
            // Update model to your db
            //  foreach (var item in model) {
            //      model.ID = item.ID;
            //      model.Description = item.Description;
            //      model.QtyAvailable = item.QtyAvailable;
            //      model.UserQty = item.UserQty * -1;
            //  }

            string message = "Success - Decrease Quantity - Usage";

            return(Json(message, JsonRequestBehavior.AllowGet));
        }
        public async Task UpdatesMetricsWhenDefaultClonePath(string targetPath, string defaultPath, int numberOfCalls, string counterName)
        {
            var vsGitServices = Substitute.For <IVSGitServices>();

            vsGitServices.GetLocalClonePathFromGitProvider().Returns(defaultPath);
            var usageTracker = Substitute.For <IUsageTracker>();
            var cloneService = CreateRepositoryCloneService(usageTracker: usageTracker, vsGitServices: vsGitServices);

            await cloneService.CloneRepository("https://github.com/foo/bar", targetPath);

            var model = UsageModel.Create(Guid.NewGuid());

            await usageTracker.Received(numberOfCalls).IncrementCounter(
                Arg.Is <Expression <Func <UsageModel.MeasuresModel, int> > >(x =>
                                                                             ((MemberExpression)x.Body).Member.Name == counterName));
        }
Exemplo n.º 23
0
        public async Task PostUsage(UsageModel model)
        {
            var request = new Request
            {
                Method      = HttpMethod.Post,
                BaseAddress = centralUri,
                Endpoint    = new Uri("api/usage/visualstudio", UriKind.Relative),
            };

            request.Headers.Add("User-Agent", productHeader.ToString());

            request.Body        = SerializeRequest(model);
            request.ContentType = "application/json";

            await httpClient.Value.Send(request);
        }
Exemplo n.º 24
0
        async Task <UsageModel> UpdateModelUserData(UsageModel model)
        {
            model.Guid = await service.GetUserGuid();

            if (connectionManager.Connections.Any(x => x.HostAddress.IsGitHubDotCom()))
            {
                model.IsGitHubUser = true;
            }

            if (connectionManager.Connections.Any(x => !x.HostAddress.IsGitHubDotCom()))
            {
                model.IsEnterpriseUser = true;
            }

            return(model);
        }
        public async Task UpdatesMetricsWhenRepositoryCloned()
        {
            var serviceProvider = Substitutes.ServiceProvider;
            var operatingSystem = serviceProvider.GetOperatingSystem();
            var vsGitServices   = serviceProvider.GetVSGitServices();
            var usageTracker    = Substitute.For <IUsageTracker>();
            var cloneService    = new RepositoryCloneService(operatingSystem, vsGitServices, usageTracker);

            await cloneService.CloneRepository("https://github.com/foo/bar", "bar", @"c:\dev");

            var model = new UsageModel();

            await usageTracker.Received().IncrementCounter(
                Arg.Is <Expression <Func <UsageModel, int> > >(x =>
                                                               ((MemberExpression)x.Body).Member.Name == nameof(model.NumberOfClones)));
        }
Exemplo n.º 26
0
        public async Task TickShouldSendDataIfDifferentDay()
        {
            var model = UsageModel.Create(Guid.NewGuid());

            model.Dimensions.Date = DateTimeOffset.Now.AddDays(-2);

            var serviceProvider = CreateServiceProvider();
            var targetAndTick   = CreateTargetAndGetTick(
                serviceProvider,
                CreateUsageService(model));

            await targetAndTick.Item2();

            var metricsService = serviceProvider.TryGetService <IMetricsService>();
            await metricsService.Received(1).PostUsage(Arg.Any <UsageModel>());
        }
Exemplo n.º 27
0
        public async Task ShouldDisposeTimerIfMetricsServiceNotFound()
        {
            var service    = CreateUsageService(UsageModel.Create(Guid.NewGuid()));
            var disposed   = false;
            var disposable = Disposable.Create(() => disposed = true);

            service.StartTimer(null, new TimeSpan(), new TimeSpan()).ReturnsForAnyArgs(disposable);

            var targetAndTick = CreateTargetAndGetTick(
                CreateServiceProvider(hasMetricsService: false),
                service);

            await targetAndTick.Item2();

            Assert.True(disposed);
        }
Exemplo n.º 28
0
        public async Task ShouldIncrementCounter()
        {
            var model = new UsageModel {
                NumberOfClones = 4
            };
            var usageService = CreateUsageService(model);
            var target       = new UsageTracker(
                CreateServiceProvider(),
                usageService);

            await target.IncrementCounter(x => x.NumberOfClones);

            UsageData result = usageService.ReceivedCalls().First(x => x.GetMethodInfo().Name == "WriteLocalData").GetArguments()[0] as UsageData;

            Assert.AreEqual(5, result.Model.NumberOfClones);
        }
        public async Task UpdatesMetricsWhenRepositoryClonedAsync(string cloneUrl, int numberOfCalls, string counterName)
        {
            var serviceProvider = Substitutes.ServiceProvider;
            var operatingSystem = serviceProvider.GetOperatingSystem();
            var vsGitServices   = serviceProvider.GetVSGitServices();
            var graphqlFactory  = Substitute.For <IGraphQLClientFactory>();
            var usageTracker    = Substitute.For <IUsageTracker>();
            var cloneService    = new RepositoryCloneService(operatingSystem, vsGitServices, graphqlFactory, usageTracker);

            await cloneService.CloneRepository(cloneUrl, @"c:\dev\bar");

            var model = UsageModel.Create(Guid.NewGuid());

            await usageTracker.Received(numberOfCalls).IncrementCounter(
                Arg.Is <Expression <Func <UsageModel.MeasuresModel, int> > >(x =>
                                                                             ((MemberExpression)x.Body).Member.Name == counterName));
        }
Exemplo n.º 30
0
        async Task SendUsage(UsageModel usage, bool weekly, bool monthly)
        {
            Debug.Assert(client != null, "SendUsage should not be called when there is no IMetricsService");

            if (connectionManager.Connections.Any(x => x.HostAddress.IsGitHubDotCom()))
            {
                usage.IsGitHubUser = true;
            }

            if (connectionManager.Connections.Any(x => !x.HostAddress.IsGitHubDotCom()))
            {
                usage.IsEnterpriseUser = true;
            }

            var model = usage.Clone(weekly, monthly);
            await client.PostUsage(model);
        }