TrackEvent() публичный статический Метод

Tracks an event to ApplicationInsights.
public static TrackEvent ( string key, string>.IDictionary properties = null ) : void
key string
properties string>.IDictionary
Результат void
        /// <summary>
        /// Deletes a record of Car
        /// </summary>
        /// <param name="id">Identifies the car to be removed</param>
        /// <returns>An empty <see cref="DomainResponse"/></returns>
        public async Task <DomainResponse> DeleteAsync(Guid id)
        {
            Telemetry.TrackEvent("Delete Record");
            await Repository.DeleteAsync <Car>(id.ToString());

            return(Response(new DomainResponse()));
        }
Пример #2
0
        private async Task UpdateRuntime()
        {
            Trace.WriteLine($"Updating runtime from: {Settings.RuntimeExtensionPackageUrl}");
            Telemetry.TrackEvent("RuntimeUpdate", new Dictionary <string, string> {
                { "runtimeSource", Settings.RuntimeExtensionPackageUrl }
            });

            string extensionFilePath = Path.ChangeExtension(Path.GetTempFileName(), "zip");

            using (var client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(Settings.RuntimeExtensionPackageUrl);

                response.EnsureSuccessStatusCode();


                using (var fileStream = File.OpenWrite(extensionFilePath))
                {
                    await response.Content.CopyToAsync(fileStream);
                }
            }

            await _kuduClient.DeleteDirectory("SiteExtensions", true);

            await _kuduClient.UploadZip("/", extensionFilePath);

            Trace.WriteLine($"Updated to function runtime version: {Settings.RuntimeVersion}");
        }
Пример #3
0
        void windowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            double sessionMin = 0;

            try
            {
                TimeSpan sessionSpan = DateTime.UtcNow - utcSessionStart;
                sessionMin = sessionSpan.TotalMinutes;
            }
            catch
            { }

            Telemetry.TrackEvent("App.Shutdown", new Dictionary <string, string>
            {
                { "SessionMin", sessionMin.ToString("#") }
            });
            Telemetry.Flush();
            // Store the current window position
            var w = sender as Window;

            //Properties.Settings.Default.MainWindowPlacement = w.GetPlacement();
            //Properties.Settings.Default.Save();
            Options.WindowPosition = w.GetPlacement();
            _window.Closing       -= windowClosing;
        }
Пример #4
0
        private ITaskRunnerNode LoadHierarchy(string configPath)
        {
            ITaskRunnerNode root = new TaskRunnerNode(Constants.TASK_CATEGORY);

            string workingDirectory = Path.GetDirectoryName(configPath);

            var scripts = TaskParser.LoadTasks(configPath);

            Telemetry.TrackEvent("Tasks loaded");

            if (scripts == null)
            {
                return(root);
            }

            TaskRunnerNode tasks = new TaskRunnerNode("Scripts");

            tasks.Description = "Scripts specified in the \"scripts\" JSON element.";
            root.Children.Add(tasks);

            foreach (string script in scripts)
            {
                TaskRunnerNode task = new TaskRunnerNode(script, true)
                {
                    Command     = new TaskRunnerCommand(workingDirectory, "cmd.exe", $"/c npm run {script} --color=always"),
                    Description = $"Runs the '{script}' script",
                };

                tasks.Children.Add(task);
            }

            return(root);
        }
Пример #5
0
        protected void DeleteCategory(int id)
        {
            Category cat = _categories.FirstOrDefault(p => p.Id == id);

            if (cat.Products == null || cat.Products.Count == 0)
            {
                try
                {
                    Repository.Delete(cat);
                    _categories.Remove(cat);
                    _sortedCategories.Remove(cat);
                    Telemetry.TrackEvent("CategoryDelete");
                }
                catch (Exception ex)
                {
                    Telemetry.TrackException(ex);
                    ToastService.ShowError("Kon categorie niet verwijderen.");
                }
            }
            else
            {
                Telemetry.TrackEvent("CategoryDeleteFail");
                ToastService.ShowError("Categorie heeft producten.");
            }
        }
Пример #6
0
        public static async System.Threading.Tasks.Task Main(string[] args)
        {
            if (InDocker)
            {
                Console.WriteLine($@"Aggregator {RequestHelper.AggregatorVersion} started in Docker mode.
{RuntimeInformation.FrameworkDescription}
{RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant()})
");

                Telemetry.InitializeTelemetry();
                Telemetry.TrackEvent("Docker Host Start");

                var host = CreatePlainHostBuilder(args).Build();
                //HACK https://stackoverflow.com/a/56079178
                var repo = (IApiKeyRepository)host.Services.GetService(typeof(IApiKeyRepository));
                await repo.LoadAsync();

                await host.RunAsync();

                Telemetry.TrackEvent("Docker Host End");
                Telemetry.Shutdown();
            }
            else
            {
                Console.WriteLine("Unsupported run mode, exiting.");
            }
        }
Пример #7
0
        private void AddConfig(object sender, EventArgs e)
        {
            var question = MessageBox.Show($"This will delete all output files from the project.\r\rDo you want to continue?", Constants.VSIX_NAME, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (question == DialogResult.No)
            {
                return;
            }

            var item = ProjectHelpers.GetSelectedItems().FirstOrDefault();

            if (item == null || item.Properties == null)
            {
                return;
            }

            string configFile = item.Properties.Item("FullPath").Value.ToString();

            var configs = ConfigHandler.GetConfigs(configFile);

            foreach (Config config in configs)
            {
                string outputFile = config.GetAbsoluteOutputFile().FullName;
                ProjectHelpers.DeleteFileFromProject(outputFile);
            }

            Telemetry.TrackEvent("VS clean output files");
        }
Пример #8
0
        private async Task InitializeSite()
        {
            Telemetry.TrackEvent(new EventTelemetry("EnvironmentInitialization"));

            Trace.WriteLine("Initializing environment...");

            await StopSite();

            await AddSettings();

            _kuduClient = new KuduClient($"https://{Settings.SiteName}.scm.azurewebsites.net", Settings.SitePublishingUser, Settings.SitePublishingPassword);

            await UpdateRuntime();

            await UpdateSiteContents();

            await StartSite();

            await InitializeFunctionKeys();

            Trace.WriteLine("Restarting site...");
            await RestartSite();

            Trace.WriteLine("Environment initialized.");
            Telemetry.TrackEvent(new EventTelemetry("EnvironmentInitialized"));
        }
Пример #9
0
        private void InstallExtension(IVsExtensionRepository repository, IVsExtensionManager manager, KeyValuePair <string, string> product)
        {
#if DEBUG
            System.Threading.Thread.Sleep(1000);
            return;
#endif

            try
            {
                GalleryEntry entry = repository.CreateQuery <GalleryEntry>(includeTypeInQuery: false, includeSkuInQuery: true, searchSource: "ExtensionManagerUpdate")
                                     .Where(e => e.VsixID == product.Key)
                                     .AsEnumerable()
                                     .FirstOrDefault();

                if (entry != null)
                {
                    IInstallableExtension installable = repository.Download(entry);
                    manager.Install(installable, false);

                    Telemetry.TrackEvent(installable.Header.Name);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
Пример #10
0
        public void Call_TrackEvent_WithMetricInEvent()
        {
            var telemetry = new Telemetry(_client);

            const string eventName = "EventName";

            const string telemetryMetricEventKey   = "A";
            const double telemetryMetricEventValue = 5;
            var          telemetryMetrics          = new TelemetryMetrics()
            {
                [telemetryMetricEventKey] = telemetryMetricEventValue
            };

            telemetry.TrackEvent(eventName, null, telemetryMetrics);

            _client.Received().TrackEvent(eventName,
                                          Arg.Is <Dictionary <string, string> >(data =>
                                                                                data == null ||
                                                                                data.Count == 0),
                                          Arg.Is <Dictionary <string, double> >(metrics =>
                                                                                metrics != null &&
                                                                                metrics.Count == 1 &&
                                                                                // ReSharper disable once CompareOfFloatsByEqualityOperator
                                                                                metrics[telemetryMetricEventKey] == telemetryMetricEventValue)
                                          );
        }
Пример #11
0
        private async System.Threading.Tasks.Task LintSelectedFiles(object sender, EventArgs e)
        {
            var           paths = ProjectHelpers.GetSelectedItemPaths();
            List <string> files = new List <string>();

            foreach (string path in paths)
            {
                if (Directory.Exists(path))
                {
                    var children = GetFiles(path, "*.*");
                    files.AddRange(children.Where(c => LinterService.IsFileSupported(c)));
                }
                else if (File.Exists(path) && LinterService.IsFileSupported(path))
                {
                    files.Add(path);
                }
            }

            if (files.Any())
            {
                await LinterService.Lint(true, files.ToArray());

                Telemetry.TrackEvent($"VS Lint Files");
            }
            else
            {
                WebLinterPackage.Dte.StatusBar.Text = "No files found to lint";
            }
        }
Пример #12
0
 public static void Log(object value)
 {
     if (value != null)
     {
         Telemetry.TrackEvent(value.ToString());
     }
 }
        private void SendTelemetry(JobModel job, List <OutstandingJobResult> processingJobsPresent = null, List <long?> jobsWithoutSubmissionSummariesPresent = null)
        {
            var properties = new Dictionary <string, string>
            {
                { TelemetryKeys.JobId, job.DcJobId.Value.ToString() },
                { TelemetryKeys.JobType, job.JobType.ToString("G") },
                { TelemetryKeys.Ukprn, job.Ukprn?.ToString() ?? string.Empty },
                { TelemetryKeys.InternalJobId, job.DcJobId.ToString() },
                { TelemetryKeys.CollectionPeriod, job.CollectionPeriod.ToString() },
                { TelemetryKeys.AcademicYear, job.AcademicYear.ToString() },
                { TelemetryKeys.Status, job.Status.ToString("G") }
            };

            if (processingJobsPresent != null)
            {
                properties.Add("InProgressJobsCount", processingJobsPresent.Count.ToString());
                properties.Add("InProgressJobsList", string.Join(", ", processingJobsPresent.Select(j => j.ToJson())));
            }


            if (jobsWithoutSubmissionSummariesPresent != null)
            {
                properties.Add("jobsWithoutSubmissionSummariesCount", jobsWithoutSubmissionSummariesPresent.Count.ToString());
                properties.Add("jobsWithoutSubmissionSummaries", string.Join(", ", jobsWithoutSubmissionSummariesPresent.Select(j => j.ToJson())));
            }

            Telemetry.TrackEvent("PeriodEndStart Job Status Update", properties, new Dictionary <string, double>());
        }
        protected override IEnumerable <JSONCompletionEntry> GetEntries(JSONCompletionContext context)
        {
            var member = context.ContextItem as JSONMember;

            if (member == null || member.UnquotedNameText != "version")
            {
                yield break;
            }

            string name = (member.Parent?.Parent as JSONMember)?.UnquotedNameText;

            if (string.IsNullOrEmpty(name))
            {
                yield break;
            }

            var versions = VSPackage.Manager.Provider.GetVersionsAsync(name).Result;

            if (versions != null)
            {
                int index = 0;
                Telemetry.TrackEvent("Completion for version");

                foreach (var version in versions)
                {
                    yield return(new SimpleCompletionEntry(version, KnownMonikers.Version, context.Session, ++index));
                }
            }
        }
 void OptionsSaved(object sender, EventArgs e)
 {
     _extensions     = VSPackage.Options.FileExtensions.Split(';');
     _ignorePatterns = VSPackage.Options.GetIgnorePatterns();
     _watcher.EnableRaisingEvents = VSPackage.Options.EnableReload;
     Telemetry.TrackEvent("Updated settings");
 }
Пример #16
0
        private void RemoveTrailingWhitespace(ITextBuffer buffer)
        {
            bool foundWhitespace = false;

            using (ITextEdit edit = buffer.CreateEdit())
            {
                ITextSnapshot snap = edit.Snapshot;

                foreach (ITextSnapshotLine line in snap.Lines)
                {
                    string text   = line.GetText();
                    int    length = text.Length;
                    while (--length >= 0 && Char.IsWhiteSpace(text[length]))
                    {
                        ;
                    }
                    if (length < text.Length - 1)
                    {
                        int start = line.Start.Position;
                        edit.Delete(start + length + 1, text.Length - length - 1);
                        foundWhitespace = true;
                    }
                }

                edit.Apply();
            }

            if (foundWhitespace)
            {
                Telemetry.TrackEvent("On save");
            }
        }
Пример #17
0
        private void LogConfigSettings(CreationType creationType)
        {
            var properties = Settings.ExtensionConfig.GetType().GetProperties().ToDictionary(
                k => k.Name,
                v => v.GetValue(Settings.ExtensionConfig)?.ToString() ?? string.Empty);

            foreach (var kvp in properties.ToList())
            {
                if (kvp.Key.ToLower().EndsWith("list"))
                {
                    properties.Add(kvp.Key + "Count", string.IsNullOrWhiteSpace(kvp.Value)
                        ? "0"
                        : kvp.Value.Split('|').Length.ToString());
                }
            }

            properties["AudibleCompletionNotification"] = Settings.AudibleCompletionNotification.ToString();
            properties["CrmSvcUtilRelativePath"]        = Settings.CrmSvcUtilRelativePath;
            properties["IncludeCommandLine"]            = Settings.IncludeCommandLine.ToString();
            properties["MaskPassword"]    = Settings.MaskPassword.ToString();
            properties["SupportsActions"] = Settings.SupportsActions.ToString();
            properties["UseCrmOnline"]    = Settings.UseCrmOnline.ToString();
            properties["Version"]         = Settings.Version;
            properties["CreationType"]    = creationType.ToString();

            if (Telemetry.Enabled)
            {
                TxtOutput.AppendText($"Tracking {creationType} Generation Event." + Environment.NewLine);
                Telemetry.TrackEvent("ConfigSettings", properties);
            }
            else
            {
                TxtOutput.AppendText("Tracking not enabled!  Please consider allowing the Xrm Tool Box to send anonymous statistics via the Configuration --> Settings -- Data Collect.  This allows reporting for which features are used and what features can be deprecated." + Environment.NewLine);
            }
        }
 protected void Submit()
 {
     if (_editContext.Validate())
     {
         _product.ProductNumber = Regex.Replace(_product.ProductNumber, @"\s+", "");
         if (!Repository.ProductDuplicateExists(_product.Id, _product.ProductNumber))
         {
             try
             {
                 Repository.Save(_product);
                 _product.Category.Products.Add(_product);
                 ToastService.ShowSuccess("Product: " + _product.Description + " werd toegevoegd in categorie: " + _product.Category.CategoryName);
                 Telemetry.TrackEvent("NonUniqueProductNumber");
                 NavigationManager.NavigateTo("/beheer");
             }
             catch (Exception ex)
             {
                 Telemetry.TrackException(ex);
                 ToastService.ShowError("Kon product niet opslaan.");
             }
         }
         else
         {
             Telemetry.TrackEvent("NonUniqueProductNumber");
             ToastService.ShowError("Product met identiek productnummer bestaat al.");
         }
     }
 }
        public IActionResult OpportunityDetails(string courseid, string distance, int?oppid, string postcode)
        {
            Telemetry.TrackEvent($"Logging: Started: Controller = {nameof(CourseDirectoryController)}: Action = {nameof(OpportunityDetails)}: {nameof(Environment.MachineName)} = {Environment.MachineName}: {nameof(CorrelationContextAccessor.CorrelationContext.CorrelationId)} = {CorrelationContextAccessor.CorrelationContext.CorrelationId}");

            //Parmeters
            var dtStart = DateTime.Now;

            if (!ModelState.IsValid)
            {
                Telemetry.TrackEvent($"CourseSearch: ModelState Invalid: Controller = {nameof(CourseDirectoryController)}: Action = {nameof(OpportunityDetails)}: {nameof(Environment.MachineName)} = {Environment.MachineName}: {nameof(CorrelationContextAccessor.CorrelationContext.CorrelationId)} = {CorrelationContextAccessor.CorrelationContext.CorrelationId}");
                return(View());
            }

            var result = Service.CourseItemDetail(courseid, oppid);

            if (!CourseDirectory.IsSuccessfulResult(result, Telemetry, "Course Detail", courseid, dtStart))
            {
                return(View(nameof(Error), new Models.ErrorViewModel()
                {
                    RequestId = "OpportunityDetails: " + courseid + ". " + (null != result ? result.Error : string.Empty)
                }));
            }

            //DEBUG_FIX - Add the flush to see if working straightaway ASB TODO AGain is this correct as wont get called if ModelState is Invalid
            Telemetry.Flush();

            Telemetry.TrackEvent($"Logging: Ended: Controller = {nameof(CourseDirectoryController)}: Action = {nameof(OpportunityDetails)}: {nameof(Environment.MachineName)} = {Environment.MachineName}: {nameof(CorrelationContextAccessor.CorrelationContext.CorrelationId)} = {CorrelationContextAccessor.CorrelationContext.CorrelationId}");

            return(View(nameof(CourseDetails), new CourseDetailViewModel(result.Value, !string.IsNullOrEmpty(distance) ? distance : string.Empty, postcode, oppid)
            {
            }));
        }
Пример #20
0
        private ITaskRunnerNode LoadHierarchy(string configPath)
        {
            ITaskRunnerNode root = new TaskRunnerNode(Constants.TASK_CATEGORY);

            var scripts   = TaskParser.LoadTasks(configPath);
            var hierarchy = GetHierarchy(scripts.Keys);

            if (hierarchy == null)
            {
                return(root);
            }

            var defaults = hierarchy.Where(h => Constants.ALL_DEFAULT_TASKS.Contains(h.Key));

            TaskRunnerNode defaultTasks = new TaskRunnerNode("Defaults");

            defaultTasks.Description = "Default predefined npm commands.";
            root.Children.Add(defaultTasks);
            AddCommands(configPath, scripts, defaults, defaultTasks);

            if (hierarchy.Count != defaults.Count())
            {
                var customs = hierarchy.Except(defaults);

                TaskRunnerNode customTasks = new TaskRunnerNode("Custom");
                customTasks.Description = "Custom npm commands.";
                root.Children.Add(customTasks);

                AddCommands(configPath, scripts, customs, customTasks);
            }

            Telemetry.TrackEvent("Tasks loaded");

            return(root);
        }
Пример #21
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public MqttSubscriber(OnEntityUpdated onEntityUpdatedCallback, OnConnectionResult onConnectionResultCallback)
        {
            MqttFactory = new MqttFactory();
            MqttClient  = MqttFactory.CreateMqttClient();

            OnEntityUpdatedCallback    = onEntityUpdatedCallback ?? throw new ArgumentNullException(nameof(onEntityUpdatedCallback));
            OnConnectionResultCallback = onConnectionResultCallback ?? throw new ArgumentNullException(nameof(onConnectionResultCallback));

            // Handle message received callbacks
            MqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                string entityId = $"{e.ApplicationMessage.Topic.Split('/')[1]}.{e.ApplicationMessage.Topic.Split('/')[2]}";

                Telemetry.TrackTrace(
                    nameof(MqttClient.ApplicationMessageReceivedHandler),
                    new Dictionary <string, string>
                {
                    [nameof(Entity.EntityId)] = entityId,
                });

                OnEntityUpdatedCallback();
            });

            // Handle subscription connection
            MqttClient.UseConnectedHandler(async e =>
            {
                MqttClientSubscribeResult result = await MqttClient.SubscribeAsync(new TopicFilterBuilder()
                                                                                   .WithTopic(SettingsControl.MqttTopic)
                                                                                   .Build());

                Telemetry.TrackEvent(
                    nameof(MqttClient.ConnectedHandler),
                    new Dictionary <string, string>
                {
                    [nameof(MqttClient.IsConnected)]        = MqttClient.IsConnected.ToString(),
                    [nameof(MqttClientSubscribeResultCode)] = result.Items.FirstOrDefault()?.ResultCode.ToString(),
                });

                OnConnectionResultCallback(MqttClient.IsConnected);
            });

            // Handle disconnects
            MqttClient.UseDisconnectedHandler(async e =>
            {
                // Only attempt to reconnect when desired
                if (AttemptReconnectOnDisconnect)
                {
                    Telemetry.TrackEvent(
                        nameof(MqttClient.DisconnectedHandler),
                        new Dictionary <string, string>(e.ToDictionary())
                    {
                        [nameof(MqttClient.IsConnected)] = MqttClient.IsConnected.ToString(),
                    });

                    await Task.Delay(TimeSpan.FromSeconds(1));

                    await Connect();
                }
            });
        }
        void HandleResult(CompressionResult result, int count)
        {
            string name = Path.GetFileName(result.OriginalFileName);

            if (result.Saving > 0 && File.Exists(result.ResultFileName))
            {
                if (_dte.SourceControl.IsItemUnderSCC(result.OriginalFileName) && !_dte.SourceControl.IsItemCheckedOut(result.OriginalFileName))
                {
                    _dte.SourceControl.CheckOutItem(result.OriginalFileName);
                }

                File.Copy(result.ResultFileName, result.OriginalFileName, true);
                File.Delete(result.ResultFileName);

                string text = "Compressed " + name + " by " + result.Saving + " bytes / " + result.Percent + "%";
                _dte.StatusBar.Progress(true, text, count, _selectedPaths.Count + 1);

                Logger.Log(result.ToString());
                string ext     = Path.GetExtension(result.OriginalFileName).ToLowerInvariant().Replace(".jpeg", ".jpg");
                var    metrics = new Dictionary <string, double> {
                    { "saving", result.Saving }
                };
                Telemetry.TrackEvent(ext, metrics: metrics);
            }
            else
            {
                _dte.StatusBar.Progress(true, name + " is already optimized", AmountCompleted: count, Total: _selectedPaths.Count + 1);
                Logger.Log(name + " is already optimized");

                if (result.Processed)
                {
                    Telemetry.TrackEvent("Already optimized");
                }
            }
        }
Пример #23
0
        public JSONItemValidationResult ValidateItem(JSONParseItem item, IJSONValidationContext context)
        {
            JSONMember member = item as JSONMember;
            JSONMember icons  = item?.Parent?.FindType <JSONMember>();

            if (icons != null && icons.UnquotedNameText == "icons")
            {
                string folder = Path.GetDirectoryName(item.JSONDocument.DocumentLocation);
                string file   = Path.Combine(folder, member.UnquotedValueText);

                if (!File.Exists(file))
                {
                    JsonErrorTag error = new JsonErrorTag
                    {
                        Flags    = JSONErrorFlags.ErrorListError | JSONErrorFlags.UnderlineRed,
                        Item     = member.Value,
                        Start    = member.Value.Start,
                        AfterEnd = member.Value.AfterEnd,
                        Length   = member.Value.Length,
                        Text     = $"The file \"{member.UnquotedValueText}\" does not exist"
                    };

                    Telemetry.TrackEvent("Icon file missing");
                    context.AddError(error);
                }
            }

            return(JSONItemValidationResult.Continue);
        }
Пример #24
0
        void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            double sessionMin = 0;

            try
            {
                TimeSpan sessionSpan = DateTime.UtcNow - _utcSessionStart;
                sessionMin = sessionSpan.TotalMinutes;
            }
            catch
            {
                // swallow all errors
            }

            if (Options.AnyExternalAccessAllowed())
            {
                Telemetry.TrackEvent("App.Shutdown", new Dictionary <string, string>
                {
                    { "SessionMin", sessionMin.ToString("#") }
                });
                Telemetry.Flush();
            }

            // Store the current window position
            var w = sender as Window;

            Options.WindowPosition = w.GetPlacement();
            _window.Closing       -= WindowClosing;
        }
Пример #25
0
        protected override async Task OnInitializedAsync()
        {
            var auth      = await AuthenticationStateTask;
            var stockUser = UserRepository.GetByEmail(auth.User.Identity.Name);

            if (stockUser == null || stockUser.StockRole != StockRole.ADMIN)
            {
                Telemetry.TrackEvent("AccessDenied");
                NavigationManager.NavigateTo("/accessdenied");
                return;
            }

            try
            {
                _categories = await Repository.GetAllAsync <Category>();

                _sortedCategories = new List <Category>(_categories);
                _suppliers        = await Repository.GetAllAsync <Supplier>();

                _sortedSuppliers = new List <Supplier>(_suppliers);
            } catch (Exception e)
            {
                Telemetry.TrackException(e);
                ToastService.ShowWarning("Probleem bij het inladen van data, herlaad de pagina.");
            }
        }
Пример #26
0
        private async void ExportEventSummaryToCSV(int?count = null)
        {
            Telemetry.TrackEvent(TelemetryCategory.Export, Telemetry.TelemetryEvent.Export.Summary);

            var saveDialog = new SaveFileDialog();

            saveDialog.AddExtension = true;
            saveDialog.FileName     = "band_export.csv";
            saveDialog.DefaultExt   = ".csv";

            var result = saveDialog.ShowDialog();

            if (result == true)
            {
                _summaryExportProgressDialog = await((MetroWindow)(Window.GetWindow(this))).ShowProgressAsync("Exporting Data", "...");
                _summaryExportProgressDialog.SetCancelable(true); // TODO: this needs to be implemented. No event?
                _summaryExportProgressDialog.SetProgress(0);

                var progressIndicator = new Progress <BandCloudExportProgress>(ReportSummaryExportProgress);

                await BandCloudManager.Instance.ExportEventsSummaryToCSV(count, ExportSettings, saveDialog.FileName, progressIndicator);

                _summaryExportProgressDialog.CloseAsync();

                if (ExportSettings.OpenFileAfterExport)
                {
                    Process.Start(saveDialog.FileName);
                }

                SaveExportSettings();
            }
        }
Пример #27
0
        private void AddConfig(object sender, EventArgs e)
        {
            var question = MessageBox.Show($"This will remove the file from {Constants.CONFIG_FILENAME}.\r\rDo you want to continue?", Constants.VSIX_NAME, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (question == DialogResult.Cancel)
            {
                return;
            }

            ConfigHandler handler = new ConfigHandler();

            Telemetry.TrackEvent("VS remove config");

            try
            {
                foreach (Config config in _configs)
                {
                    handler.RemoveConfig(config);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                WebCompilerPackage._dte.StatusBar.Text = $"Could not update {Constants.CONFIG_FILENAME}. Make sure it's not write-protected or has syntax errors.";
            }
        }
Пример #28
0
        private async void btnExportAll_Click(object sender, RoutedEventArgs e)
        {
            var folderDialog = new CommonOpenFileDialog();

            folderDialog.Title            = "Where should I save your data?";
            folderDialog.IsFolderPicker   = true;
            folderDialog.EnsureFileExists = true;
            folderDialog.EnsurePathExists = true;
            folderDialog.EnsureValidNames = true;
            folderDialog.EnsureReadOnly   = false;
            folderDialog.Multiselect      = false;
            folderDialog.ShowPlacesList   = true;

            if (folderDialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                Telemetry.TrackEvent(TelemetryCategory.Export, Telemetry.TelemetryEvent.Export.Full);

                var folder = folderDialog.FileName;

                BandCloudManager.Instance.Events.Clear();

                _fullExportProgressDialog = await((MetroWindow)(Window.GetWindow(this))).ShowProgressAsync("Exporting Full Activity Data", "Loading Activities list...");
                _fullExportProgressDialog.SetCancelable(true); // TODO: this needs to be implemented. No event?
                _fullExportProgressDialog.SetIndeterminate();

                // HACK HACK HACK HACK
                // TODO: add a Cancelled Event into the MahApps.Metro library

                // polling method to cancel the export if the user requests that it be cancelled
                Task.Run(async() =>
                {
                    while (_fullExportProgressDialog != null && _fullExportProgressDialog.IsOpen)
                    {
                        if (_fullExportProgressDialog.IsCanceled)
                        {
                            BandCloudManager.Instance.CancelFullExport = true;

                            Telemetry.TrackEvent(TelemetryCategory.Export, Telemetry.TelemetryEvent.Export.FullCancelled);

                            // we'd exit from the while loop anyway, but only when the progress dialog finally exits
                            // which can take up to 10 seconds, so might as well shut this down asap
                            return;
                        }

                        await Task.Delay(500);
                    }
                });

                await LoadEvents();

                var progressIndicator = new Progress <BandCloudExportProgress>(ReportFullExportProgress);

                // TODO: progress reporter
                await BandCloudManager.Instance.ExportFullEventData(folder, ExportSettings, progressIndicator);

                _fullExportProgressDialog.CloseAsync();

                SaveExportSettings();
            }
        }
Пример #29
0
        public static int Run(string[] args)
        {
            var sessionId =
                Environment.GetEnvironmentVariable(MSBuildForwardingApp.TelemetrySessionIdEnvironmentVariableName);

            // senderCount: 0 to disable sender.
            // When senders in different process running at the same
            // time they will read from the same global queue and cause
            // sending duplicated events. Disable sender to reduce it.
            var telemetry = new Telemetry(new FirstTimeUseNoticeSentinel(),
                                          sessionId,
                                          senderCount: 0);
            var logger = new TelemetryLogger(null);

            if (telemetry.Enabled)
            {
                logger = new TelemetryLogger((name, props, measures) =>
                {
                    if (telemetry.Enabled)
                    {
                        telemetry.TrackEvent($"template/{name}", props, measures);
                    }
                });
            }

            return(New3Command.Run(CommandName, CreateHost(), logger, FirstRun, args));
        }
        /// <summary>
        /// Get All records of Car
        /// </summary>
        /// <returns></returns>
        public async Task <DomainResponse> GetAllAsync()
        {
            Telemetry.TrackEvent("GetAll Records");
            var records = await Repository.GetAsync <Car>(x => true);

            return(Response(records));
        }