Esempio n. 1
0
        /// <summary>
        /// Get the usage amount based on whether it's download/upload and onpeak/offpeak/total
        /// </summary>
        /// <param name="usage">The usage</param>
        /// <param name="directionPeakType">One of the magic strings depicting download/upload and onpeak/offpeak/total</param>
        /// <returns></returns>
        private double getUsageData(UsageData usage, string directionPeakType)
        {
            switch (directionPeakType)   // ugly as hell, I know
            {
            case "Download onpeak":
                return(usage.OnPeakDownload);

            case "Upload onpeak":
                return(usage.OnPeakUpload);

            case "Download offpeak":
                return(usage.OffPeakDownload);

            case "Upload offpeak":
                return(usage.OffPeakUpload);

            case "Download total":
                return(usage.OnPeakDownload + usage.OffPeakDownload);

            case "Upload total":
                return(usage.OnPeakUpload + usage.OffPeakUpload);

            default:
                throw new Exception("Wrong directionPeakType, baka");
            }
        }
Esempio n. 2
0
 public GetPricesRequest()
 {
     UsageData      = new UsageData();
     SpendData      = new SpendData();
     EstimatorData  = new EstimatorData();
     CustomFeatures = new Dictionary <string, string>();
 }
Esempio 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);
        }
Esempio n. 4
0
        static IUsageService CreateUsageService(UsageData data)
        {
            var result = Substitute.For <IUsageService>();

            result.ReadLocalData().Returns(data);
            return(result);
        }
Esempio n. 5
0
        private void ClockOnSecondChange(object clock, DataEventArgs dataInformation)
        {
            var      usageData = new UsageData();
            DateTime date_time = SetTime();
            var      time      = date_time.ToString("mm:ss");

            using (var context = new MetricsContext())
            {
                var metrics =
                    context.ComputerDetails.FirstOrDefault(n => n.Name == dataInformation.Name);
                if (metrics != null)
                {
                    metrics.UsageDataCollection.Add(new UsageData()
                    {
                        CpuUsage               = dataInformation.CpuUsage,
                        AvailableDiskSpaceGb   = dataInformation.AvailableDiskSpaceGb,
                        RamUsage               = dataInformation.RamUsage,
                        AverageDiskQueueLength = dataInformation.AverageDiskQueueLength,
                        Time = date_time
                    });
                    context.SaveChanges();
                }
            }
            cpuUsageTextBox.Text               = dataInformation.CpuUsage.ToString();
            ramUsageTextBox.Text               = dataInformation.RamUsage.ToString();
            availableDiskSpaceText.Text        = dataInformation.AvailableDiskSpaceGb.ToString();
            averagediskqueueLengthTextBox.Text = dataInformation.AverageDiskQueueLength.ToString();

            chart1.Series[0].Points.AddXY(time, dataInformation.RamUsage);
            chart1.Series[1].Points.AddXY(time, dataInformation.CpuUsage);
            chart1.Series[2].Points.AddXY(time, dataInformation.AvailableDiskSpaceGb);
            averageDiskQueueLengthChart.Series[0].Points.AddXY(time,
                                                               dataInformation.AverageDiskQueueLength);
            OnlyTenPointsInTheGraph();
        }
Esempio n. 6
0
 public BoltStateMachineV1SPI(UsageData usageData, LogService logging, Authentication authentication, TransactionStateMachineSPI transactionStateMachineSPI)
 {
     this._usageData      = usageData;
     this._errorReporter  = new ErrorReporter(logging);
     this._authentication = authentication;
     this._transactionSpi = transactionStateMachineSPI;
     this._version        = BOLT_SERVER_VERSION_PREFIX + Version.Neo4jVersion;
 }
Esempio n. 7
0
    public string LoadUsage(string sSKU, string sSessionID)
    {
        try
        {
            //don't allow iOS 6 (or any browsers) to cache responses
            System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (!ValidateSession(sSessionID))
            {
                return(sInvalidSession);
            }

            //Convert JSON string to object list
            List <UsageData> oUsageList = new List <UsageData>();
            UsageData        oUsage     = null;

            using (SqlConnection oCN = new SqlConnection(ConfigurationManager.ConnectionStrings["CN_INSIDER"].ConnectionString))
            {
                oCN.Open();
                using (SqlCommand oCMD = new SqlCommand("", oCN))
                {
                    oCMD.CommandText = "SELECT iID, sItemCode, sType, CONVERT(varchar(10), dtTran, 101) As dtTran, CONVERT(varchar(10), dtRequired, 101) As dtRequired, iUnits, sNotes"
                                       + " FROM SKUP2_FutureUsage"
                                       + " WHERE sItemCode = @sSKU"
                                       + " ORDER BY SKUP2_FutureUsage.dtTran";
                    oCMD.Parameters.AddWithValue("@sSKU", sSKU);

                    using (SqlDataReader oDR = oCMD.ExecuteReader())
                    {
                        while (oDR.Read())
                        {
                            oUsage                 = new UsageData();
                            oUsage.iID             = oDR["iID"].ToString();
                            oUsage.sItemCode       = oDR["sItemCode"].ToString();
                            oUsage.dtTran          = oDR["dtTran"].ToString();
                            oUsage.dtTran_Init     = oUsage.dtTran;
                            oUsage.dtRequired      = oDR["dtRequired"].ToString();
                            oUsage.dtRequired_Init = oUsage.dtRequired;
                            oUsage.sType           = oDR["sType"].ToString();
                            oUsage.sType_Init      = oUsage.sType;
                            oUsage.iUnits          = oDR["iUnits"].ToString();
                            oUsage.iUnits_Init     = oUsage.iUnits;
                            oUsage.sNotes          = oDR["sNotes"].ToString();
                            oUsage.sNotes_Init     = oUsage.sNotes;
                            oUsageList.Add(oUsage);
                        }
                    }
                }
            }

            return(new JavaScriptSerializer().Serialize(oUsageList));
        }
        catch (Exception ex)
        {
            return("WS Error: " + ex.Message.ToString());
        }
    }
Esempio n. 8
0
        private void UsageSelected(object sender, ItemClickEventArgs e)
        { // Select usage to view details on
            ListView  lst = sender as ListView;
            UsageData u   = e.ClickedItem as UsageData;

            AppDebug.Line($"Selected usage on [{u.StartTimeString}]");
            UsageContext.DisplayUsage = u;
            Frame.Navigate(typeof(UsageDisplay));
        }
Esempio n. 9
0
 /// <remarks/>
 public void ReportUsageAsync(UsageData data, object userState)
 {
     if ((this.ReportUsageOperationCompleted == null))
     {
         this.ReportUsageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnReportUsageOperationCompleted);
     }
     this.InvokeAsync("ReportUsage", new object[] {
         data
     }, this.ReportUsageOperationCompleted, userState);
 }
Esempio n. 10
0
        internal DefaultUdcInformationCollector(Config config, DataSourceManager dataSourceManager, UsageData usageData)
        {
            this._config    = config;
            this._usageData = usageData;

            if (dataSourceManager != null)
            {
                dataSourceManager.AddListener(new ListenerAnonymousInnerClass(this));
            }
        }
Esempio n. 11
0
        private static void Test(string[] usageData, double expectedResult)
        {
            RateCardData rc = GetRateCardTestData();
            var          ud = new UsageData();

            ud.Values = GetUsageValues(usageData);

            var data = Client.Combine(rc, ud);

            Assert.AreEqual(expectedResult, data.TotalCosts);
        }
Esempio n. 12
0
        public Task <bool> SendLocalUsage(string userId, List <ExampleUsage> usage)
        {
            // Should be working now.
            //return TaskEx.FromResult(true);

            UsageData request = new UsageData()
            {
                UserId = userId, Usage = usage
            };

            return(Post <UsageData>(request, "Submit"));
        }
Esempio n. 13
0
        private static UsageData GetComponent(Node node)
        {
            var ud = node.Components.Get <UsageData>();

            if (ud == null)
            {
                ud = new UsageData();
                node.Components.Add(ud);
                createdComponents.Add(ud);
            }
            return(ud);
        }
Esempio n. 14
0
        private async void SubmitFeedback(object sender, TappedRoutedEventArgs e) // Send feedback to server
        {
            HttpResponseMessage res = null;
            UsageUpdateRequest  req;

            double[] ranks = new double[4];

            ranks = GetRanks(questionDictionary);

            try
            { // Build request for server
                progressRing.IsActive = true;
                GlobalContext.CurrentUser.UsageSessions.LastOrDefault().usageFeedback = questionDictionary;

                UsageData use    = GlobalContext.CurrentUser.UsageSessions.LastOrDefault();
                string    userId = GlobalContext.CurrentUser.Data.UserID;

                req = new UsageUpdateRequest(use.UsageStrain.Name, use.UsageStrain.ID,
                                             userId,
                                             ((DateTimeOffset)use.StartTime).ToUnixTimeMilliseconds(),
                                             ((DateTimeOffset)use.EndTime).ToUnixTimeMilliseconds(),
                                             ranks[0], ranks[1], ranks[2], use.HeartRateMax, use.HeartRateMin, (int)use.HeartRateAverage, ranks[3],
                                             questionDictionary);

                res = await HttpManager.Manager.Post(Constants.MakeUrl("usage"), req); // Send request

                if (res != null)
                { // Request sent successfully
                    if (res.IsSuccessStatusCode)
                    {
                        Status.Text = "Usage update Successful!";
                        var index = GlobalContext.CurrentUser.UsageSessions.Count - 1;
                        GlobalContext.CurrentUser.UsageSessions[index].UsageId = res.GetContent()["body"];
                        PagesUtilities.SleepSeconds(0.5);
                        Frame.Navigate(typeof(DashboardPage));
                    }
                    else
                    {
                        Status.Text = "Usage update failed! Status = " + res.StatusCode;
                    }
                }
                else
                {
                    Status.Text = "Usage update failed!\nPost operation failed";
                }

                Frame.Navigate(typeof(DashboardPage));
            }
            catch (Exception x)
            {
                AppDebug.Exception(x, "UsageUpdate");
            }
        }
Esempio n. 15
0
 public async Task WriteLocalData(UsageData data)
 {
     try
     {
         Directory.CreateDirectory(Path.GetDirectoryName(storePath));
         var json = SimpleJson.SerializeObject(data);
         await WriteAllTextAsync(storePath, json);
     }
     catch (Exception ex)
     {
         log.Error(ex, "Failed to write usage data");
     }
 }
Esempio n. 16
0
 public async Task WriteLocalData(UsageData data)
 {
     try
     {
         Directory.CreateDirectory(Path.GetDirectoryName(storePath));
         var json = SimpleJson.SerializeObject(data);
         await WriteAllTextAsync(storePath, json);
     }
     catch
     {
         // log.Warn("Failed to write usage data", ex);
     }
 }
Esempio n. 17
0
 public BoltServer(DatabaseManager databaseManager, JobScheduler jobScheduler, ConnectorPortRegister connectorPortRegister, NetworkConnectionTracker connectionTracker, UsageData usageData, Config config, Clock clock, Monitors monitors, LogService logService, DependencyResolver dependencyResolver)
 {
     this._databaseManager       = databaseManager;
     this._jobScheduler          = jobScheduler;
     this._connectorPortRegister = connectorPortRegister;
     this._connectionTracker     = connectionTracker;
     this._usageData             = usageData;
     this._config             = config;
     this._clock              = clock;
     this._monitors           = monitors;
     this._logService         = logService;
     this._dependencyResolver = dependencyResolver;
 }
Esempio n. 18
0
        void WriteDynamicDataToDb()
        {
            UsageData usageData = new UsageData();

            usageData.CpuUsage               = dataManager.GetCpuUsage();
            usageData.RamUsage               = dataManager.GetRamUsage();
            usageData.AvailableDiskSpaceGb   = dataManager.GetAvailableDiskSpaceGb();
            usageData.AverageDiskQueueLength = dataManager.GetAverageDiskQueueLength();
            usageData.Time             = DateTime.Now;
            detail.UsageDataCollection = new List <UsageData>();
            detail.UsageDataCollection.Add(usageData);
            context.UsageDatas.Add(usageData);
            context.SaveChanges();
        }
        static IUsageService CreateUsageService(
            UsageData data,
            bool sameDay   = true,
            bool sameWeek  = true,
            bool sameMonth = true)
        {
            var result = Substitute.For <IUsageService>();

            result.ReadLocalData().Returns(data);
            result.IsSameDay(DateTimeOffset.Now).ReturnsForAnyArgs(sameDay);
            result.IsSameWeek(DateTimeOffset.Now).ReturnsForAnyArgs(sameWeek);
            result.IsSameMonth(DateTimeOffset.Now).ReturnsForAnyArgs(sameMonth);
            return(result);
        }
            public async Task ShouldWriteUpdatedData()
            {
                var data = new UsageData {
                    Model = new UsageModel()
                };
                var service = CreateUsageService(data);
                var target  = new UsageTracker(
                    CreateServiceProvider(),
                    service);

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

                await service.Received(1).WriteLocalData(data);
            }
Esempio n. 21
0
        public void UpdateDynamicComputerData()
        {
            var usageData = new UsageData();
            var manager   = new FullDataManager();

            usageData.AvailableDiskSpaceGb   = Int32.Parse(manager.GetMetric(ComputerMetrics.AvailableDiskSpace));
            usageData.AverageDiskQueueLength = Int32.Parse(manager.GetMetric(ComputerMetrics.AverageDiskQueueLength));
            usageData.CpuUsage = Int32.Parse(manager.GetMetric(ComputerMetrics.CpuUsage));
            usageData.RamUsage = Int32.Parse(manager.GetMetric(ComputerMetrics.RamUsage));
            usageData.Time     = DateTime.Now;
            computerDetail.UsageDataCollection.Add(usageData);
            context.UsageDatas.Add(usageData);
            context.SaveChanges();
        }
Esempio n. 22
0
        /// <summary>
        /// Combines the ratecard data with the usage data.
        /// </summary>
        /// <param name="rateCardData">RateCard data</param>
        /// <param name="usageData">Usage data</param>
        /// <returns>The costs of the resources (combined data of ratecard and usage api)</returns>
        public static ResourceCostData Combine(RateCardData rateCardData, UsageData usageData)
        {
            ResourceCostData rcd = new ResourceCostData()
            {
                Costs        = new List <ResourceCosts>(),
                RateCardData = rateCardData
            };

            // get all used meter ids
            var meterIds = (from x in usageData.Values select x.Properties.MeterId).Distinct().ToList();

            // aggregates all quantity and will be used to calculate costs (e.g. if quantity is included for free)
            // Dictionary<MeterId, Dictionary<YearAndMonthOfBillingCycle, aggregatedQuantity>>
            Dictionary <string, Dictionary <string, double> > aggQuant = meterIds.ToDictionary(x => x, x => new Dictionary <string, double>());

            foreach (var usageValue in usageData.Values)
            {
                string meterId  = usageValue.Properties.MeterId;
                var    rateCard = (from x in rateCardData.Meters where x.MeterId.Equals(meterId, StringComparison.OrdinalIgnoreCase) select x).FirstOrDefault();

                if (rateCard == null) // e.g. ApplicationInsights: there is no ratecard data for these
                {
                    continue;
                }

                var billingCycleId = GetBillingCycleIdentifier(usageValue.Properties.UsageStartTimeAsDate);
                if (!aggQuant[meterId].ContainsKey(billingCycleId))
                {
                    aggQuant[meterId].Add(billingCycleId, 0.0);
                }

                var usedQuantity = aggQuant[meterId][billingCycleId];

                var curcosts = GetMeterRate(rateCard.MeterRates, rateCard.IncludedQuantity, usedQuantity, usageValue.Properties.Quantity);

                aggQuant[meterId][billingCycleId] += usageValue.Properties.Quantity;

                rcd.Costs.Add(new ResourceCosts()
                {
                    RateCardMeter   = rateCard,
                    UsageValue      = usageValue,
                    CalculatedCosts = curcosts.Item1,
                    BillableUnits   = curcosts.Item2
                });
            }

            return(rcd);
        }
Esempio n. 23
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 bool AddNewItem(UsageData usageData)
 {
     using (var context = new MetrixContext())
     {
         try
         {
             context.UsageDatas.Add(usageData);
             context.SaveChanges();
         }
         catch
         {
             return(false);
         }
         return(true);
     }
 }
Esempio n. 25
0
        public async Task ShouldIncrementCounter()
        {
            var model = UsageModel.Create(Guid.NewGuid());

            model.Measures.NumberOfClones = 4;
            var usageService = CreateUsageService(model);
            var target       = new UsageTracker(
                CreateServiceProvider(),
                usageService,
                CreatePackageSettings());

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

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

            Assert.AreEqual(5, result.Reports[0].Measures.NumberOfClones);
        }
Esempio n. 26
0
        async Task Send()
        {
            var uri    = new Uri("http://localhost:40000");
            var server = new MetricsServer.Server(uri.Host, uri.Port);

            server.Start();

            var client = new HttpClient();

            client.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var request = new HttpRequestMessage(HttpMethod.Post, new Uri(uri, "/api/usage/visualstudio"));

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

            model.Dimensions.AppVersion     = "9.9.9";
            model.Dimensions.Lang           = "en-us";
            model.Dimensions.VSVersion      = "14";
            model.Measures.NumberOfStartups = 1;

            var data = new UsageData();

            data.Reports = new List <UsageModel> {
                model
            };

            request.Content = SerializeRequest(model);

            HttpResponseMessage response = null;

            try
            {
                response = await client.SendAsync(request);
            }
            catch (Exception ex)
            {
                Debugger.Break();
            }
            var ret = await response.Content.ReadAsStringAsync();

            Console.WriteLine(response.ToString());
            Console.WriteLine(ret);

            server.Stop();
        }
Esempio n. 27
0
        public static void Register(Task task, long ticks)
        {
            var       id = task.InitialEnumeratorType.ToString();
            UsageData ud;

            if (records.ContainsKey(id))
            {
                ud = records[id];
            }
            else
            {
                ud          = new UsageData(id);
                records[id] = ud;
            }
            ud.ConsumedTicks += ticks;
            ud.Updates       += 1;
        }
Esempio n. 28
0
 private void ListView_RightTapped(object sender, RightTappedRoutedEventArgs e)
 {
     try
     { // Open right click menu
         ListView lst = sender as ListView;
         selectedUsage = ((FrameworkElement)e.OriginalSource).DataContext as UsageData;
         if (selectedUsage != null)
         {
             UsageMenu.ShowAt(lst, e.GetPosition(lst));
             AppDebug.Line($"Right click usage on [{selectedUsage.StartTimeString}]");
         }
     }
     catch (Exception x)
     {
         AppDebug.Exception(x, "ListView_RightTapped");
     }
 }
Esempio n. 29
0
        //seriesTypes = {"Cpu usage", "Average disk quequ lenght", "Used ram"};
        public void FillCharts(Chart cCpuChar, Chart cRam, string[] seriesTypes, DataManager data, string userName)
        {
            UsageData useData = new UsageData(data.GetComputerCpuUsage(), data.GetRam(), 50, data.GetComputerAverageLenght());

            SetCharValues(cCpuChar, useData.CpuUsage, _timer, seriesTypes[0]);
            SetCharValues(cCpuChar, useData.AverageDiskQueueLength, _timer, seriesTypes[1]);
            SetCharValues(cRam, useData.RamUsage, _timer, seriesTypes[2]);

            if (cCpuChar.Series[seriesTypes[0]].Points.Count > MaxPoints)
            {
                cRam.Series[seriesTypes[2]].Points.RemoveAt(0);
                cCpuChar.Series[seriesTypes[1]].Points.RemoveAt(0);;
                cCpuChar.Series[seriesTypes[0]].Points.RemoveAt(0);
                cCpuChar.ResetAutoValues();
                cRam.ResetAutoValues();
            }
            _timer += 5;
        }
Esempio n. 30
0
        /// <summary>
        /// Updates the device properties.
        /// </summary>
        /// <param name="usageData">The new usage data.</param>
        private void UpdateDeviceProperties(UsageData usageData)
        {
            if (usageData.UsageTimestamp <= _usageData.UsageTimestamp)
            {
                return;
            }

            _usageData = usageData;

            foreach (var property in _properties)
            {
                var newValue = property.GetValue(usageData, null);
                if (newValue != null)
                {
                    DevicePropertyChangeNotification(property.Name, newValue);
                }
            }

            DevicePropertyChangeNotification("DemandCost", CalculateDemandPrice());
        }
Esempio n. 31
0
 /// <remarks/>
 public void ReportUsageAsync(UsageData data, object userState) {
     if ((this.ReportUsageOperationCompleted == null)) {
         this.ReportUsageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnReportUsageOperationCompleted);
     }
     this.InvokeAsync("ReportUsage", new object[] {
                 data}, this.ReportUsageOperationCompleted, userState);
 }
Esempio n. 32
0
 public void ReportUsage(UsageData data) {
     this.Invoke("ReportUsage", new object[] {
                 data});
 }
Esempio n. 33
0
 /// <remarks/>
 public System.IAsyncResult BeginReportUsage(UsageData data, System.AsyncCallback callback, object asyncState) {
     return this.BeginInvoke("ReportUsage", new object[] {
                 data}, callback, asyncState);
 }
Esempio n. 34
0
 /// <remarks/>
 public void ReportUsageAsync(UsageData data) {
     this.ReportUsageAsync(data, null);
 }