public Host(IStaticApplicationInfo applicationInfo, FunctionsHostConfiguration configuration, ILogger logger, uint processId, Stopwatch stopwatch, Guid invocationId) { this.processId = processId; this.stopwatch = stopwatch; this.applicationInfo = applicationInfo; this.configuration = configuration; this.hostName = Environment.MachineName; bool cloud = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("REACTIVE_MACHINE_DIR")); CombinedLogger = new CombinedLogger(logger, configuration, processId, cloud); HostLogger = new LoggerWrapper(CombinedLogger, $"[p{processId:d3} host] ", configuration.HostLogLevel); ApplicationLogger = new LoggerWrapper(CombinedLogger, $"[p{processId:d3} application] ", configuration.ApplicationLogLevel); RuntimeLogger = new LoggerWrapper(CombinedLogger, $"[p{processId:d3} runtime] ", configuration.RuntimeLogLevel); this.application = Compilation.Compile <TStaticApplicationInfo>(applicationInfo, configuration); this.invocationId = invocationId; this.payloadSerializer = new DataContractSerializer(typeof(List <KeyValuePair <long, IMessage> >), application.SerializableTypes); this.payloadSerializerLoopback = new DataContractSerializer(typeof(List <IMessage>), application.SerializableTypes); this.Connections = new EventHubsConnections(processId, HostLogger, configuration.ehConnectionString); if (application.TryGetConfiguration <ReactiveMachine.TelemetryBlobWriter.Configuration>(out var config)) { this.collectHostEvents = config.CollectHostEvents; this.blobTelemetryListener = new TelemetryCollector(config, application, processId, this.GetType()); } }
public void TestInitialise() { _context = new TelloCommanderDbContextFactory().CreateDbContext(null); _monitor = new MockDroneStatusMonitor(); _collector = new TelemetryCollector(_context, _monitor); _monitor.Listen(0); }
public async Task ExecuteAsync_WithOnlyRoot_SendsTelemetry() { string rootAddress = "https://localhost/"; ArrangeInputs($"connect {rootAddress}", out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out IPreferences preferences, fileContents: ""); TelemetryCollector telemetry = new TelemetryCollector(); ConnectCommand connectCommand = new ConnectCommand(preferences, telemetry); await connectCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); Assert.Single(telemetry.Telemetry); TelemetryCollector.CollectedTelemetry collectedTelemetry = telemetry.Telemetry[0]; Assert.Equal("connect", collectedTelemetry.EventName, ignoreCase: true); Assert.Equal("True", collectedTelemetry.Properties["RootSpecified"]); Assert.Equal("False", collectedTelemetry.Properties["BaseSpecified"]); Assert.Equal("False", collectedTelemetry.Properties["OpenApiSpecified"]); Assert.Equal("False", collectedTelemetry.Properties["OpenApiFound"]); }
public void CreateSolutionMetric_Returns_Expected_Metric() { var solutionPath = "C:/Users/CustomerName/nopCommerce/src/NopCommerce.sln"; var encryptedSolutionPath = "462eb7f46af82bd5155ef9f28ca3f5f638f702a7423b105478fa3d9267a344da"; var solutionName = "testSolution"; var encryptedSolutionName = "204ca3d6a6e14bf11f8e0992afc0276d262585065fe37ab595a5cba5bbbcb766"; var targetFramework = "netcoreapp3.1"; string version = "testVersion"; string source = "test_cli"; string tag = "test"; double analysisTime = 0; var date = DateTime.Now; var sha256hash = SHA256.Create(); var solutionDetail = new SolutionDetails { SolutionName = solutionName, SolutionFilePath = solutionPath, ApplicationGuid = "test-application-guid", SolutionGuid = "test-solution-guid", RepositoryUrl = "https://github.com/test-project", }; var actualSolutionMetric = TelemetryCollector.createSolutionMetric(solutionDetail, targetFramework, version, source, analysisTime, tag, sha256hash, date); Assert.AreEqual(actualSolutionMetric.solutionPath, encryptedSolutionPath); Assert.AreEqual(actualSolutionMetric.solutionName, encryptedSolutionName); Assert.AreEqual(actualSolutionMetric.ApplicationGuid, "test-application-guid"); Assert.AreEqual(actualSolutionMetric.SolutionGuid, "test-solution-guid"); Assert.AreEqual(actualSolutionMetric.RepositoryUrl, "https://github.com/test-project"); }
public void ShouldUnregisterToEventEnqueuedEvent() { EventQueueManager.Instance.GetType(); // trigger lazy initialization EventQueueManager.OnEventEnqueued(EventPriority.High, 1); EventQueueManager.ResetInstance(); EventQueueManager.Instance.GetType(); // trigger lazy initialization EventQueueManager.OnEventEnqueued(EventPriority.High, 1); Assert.AreEqual(2, TelemetryCollector.GetDataAndReset()[CounterType.EnqueuedHighPriorityEvent]); }
public TelemetryListenerArray(ReactiveMachine.TelemetryBlobWriter.Configuration config, ICompiledApplication application, Type hosttype, string deploymentId, DateTime deploymentTimestamp) { listeners = new TelemetryCollector[application.NumberProcesses]; for (uint i = 0; i < application.NumberProcesses; i++) { listeners[i] = new TelemetryCollector(config, application, i, hosttype); } this.deploymentId = deploymentId; this.deploymentTimestamp = deploymentTimestamp; }
public void TestCollectorsResetOnGetData() { SetCollectors(); var data = TelemetryCollector.GetDataAndReset(); data = TelemetryCollector.GetDataAndReset(); Assert.IsFalse(data.Any(x => x.Value != 0)); }
private void SetCollectors() { TelemetryCollector.GetDataAndReset(); CounterType.MessagesUnder4KB.Get().IncrementBy(smallMsg); CounterType.SendSuccesfully.Get().IncrementBy(sentMsg); CounterType.SendFailed.Get().IncrementBy(failedMsg); CounterType.DroppedHighPriorityEvent.Get().IncrementBy(droppedHigh); CounterType.EnqueuedHighPriorityEvent.Get().IncrementBy(enqueuedHigh); CounterType.DroppedLowPriorityEvent.Get().IncrementBy(droppedLow); CounterType.EnqueuedLowPriorityEvent.Get().IncrementBy(enqueuedLow); }
public async Task ExecuteAsync_WithUnknownHeader_SendsTelemetryWithHashedHeaderName() { ArrangeInputs(parseResultSections: "set header name value", out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult); TelemetryCollector telemetry = new TelemetryCollector(); SetHeaderCommand setHeaderCommand = new SetHeaderCommand(telemetry); await setHeaderCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); Assert.Single(telemetry.Telemetry); TelemetryCollector.CollectedTelemetry collectedTelemetry = telemetry.Telemetry[0]; Assert.Equal("SetHeader", collectedTelemetry.EventName); Assert.Equal(Sha256Hasher.Hash("name"), collectedTelemetry.Properties["HeaderName"]); Assert.Equal("False", collectedTelemetry.Properties["IsValueEmpty"]); }
public void CreateProjectMetric_Returns_Expected_Metric() { var targetFramework = "netcoreapp3.1"; var projectGuid = Guid.NewGuid().ToString(); var projectName = "TestProject"; var encryptedProjectName = "d1bedc36a331502eba246acba9b58c0b27912d9a8fe753b703f6ee5bbfd483c6"; var projectDetails = new ProjectDetails { ProjectName = projectName, ProjectFilePath = "pathToFile", ProjectGuid = projectGuid, ProjectType = "FormatA", TargetFrameworks = new List <string> { "one", "two" }, PackageReferences = new List <PackageVersionPair> { new PackageVersionPair { PackageId = "System.Diagnostics.Tools", Version = "4.1.2" }, new PackageVersionPair { PackageId = "", Version = "" } }, ProjectReferences = new List <ProjectReference> { new ProjectReference { ReferencePath = "a" }, new ProjectReference { ReferencePath = "b" }, new ProjectReference { ReferencePath = "c" } }, IsBuildFailed = false }; var date = DateTime.Now; var sha256hash = SHA256.Create(); string version = "testVersion"; string source = "test_cli"; string tag = "test"; double analysisTime = 0; var actualProjectMetric = TelemetryCollector.createProjectMetric(projectDetails, targetFramework, version, source, analysisTime, tag, sha256hash, date); Assert.AreEqual(actualProjectMetric.projectGuid, projectGuid); Assert.AreEqual(actualProjectMetric.projectName, encryptedProjectName); }
public async Task ExecuteAsync_WithGetAndUnknownName_SendsTelemetryWithHashedName() { Arrange("pref set preferenceName value", out HttpState httpState, out MockedShellState shellState, out ICoreParseResult parseResult, out UserFolderPreferences preferences); TelemetryCollector telemetry = new TelemetryCollector(); PrefCommand command = new PrefCommand(preferences, telemetry); await command.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); Assert.Single(telemetry.Telemetry); TelemetryCollector.CollectedTelemetry collectedTelemetry = telemetry.Telemetry[0]; Assert.Equal("Preference", collectedTelemetry.EventName); Assert.Equal("Set", collectedTelemetry.Properties["GetOrSet"]); Assert.Equal(Sha256Hasher.Hash("preferenceName"), collectedTelemetry.Properties["PreferenceName"]); }
public async Task ExecuteAsync_WithSet_SendsTelemetry() { Arrange($"pref set {WellKnownPreference.DefaultEditorCommand} value", out HttpState httpState, out MockedShellState shellState, out ICoreParseResult parseResult, out UserFolderPreferences preferences); TelemetryCollector telemetry = new TelemetryCollector(); PrefCommand command = new PrefCommand(preferences, telemetry); await command.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); Assert.Single(telemetry.Telemetry); TelemetryCollector.CollectedTelemetry collectedTelemetry = telemetry.Telemetry[0]; Assert.Equal("Preference", collectedTelemetry.EventName); Assert.Equal("Set", collectedTelemetry.Properties["GetOrSet"]); Assert.Equal(WellKnownPreference.DefaultEditorCommand, collectedTelemetry.Properties["PreferenceName"]); }
public async Task ExecuteAsync_WithPathAndOptions_SendsTelemetry() { // Arrange string expectedPath = "/path"; string expectedMethod = "GET"; ArrangeInputs(commandText: $"{expectedMethod} {expectedPath} --no-formatting --header Content-Length=20", baseAddress: _baseAddress, path: _path, urlsWithResponse: _urlsWithResponse, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out MockedFileSystem fileSystem, out IPreferences preferences); TelemetryCollector telemetry = new TelemetryCollector(); GetCommand getCommand = new GetCommand(fileSystem, preferences, telemetry); // Act await getCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); // Assert Assert.Single(telemetry.Telemetry); TelemetryCollector.CollectedTelemetry collectedTelemetry = telemetry.Telemetry[0]; Assert.Equal(TelemetryEventNames.HttpCommand, collectedTelemetry.EventName, ignoreCase: true); Assert.Equal(expectedMethod, collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_Method]); Assert.Equal("True", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_PathSpecified]); Assert.Equal("True", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_NoFormattingSpecified]); Assert.Equal("True", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_HeaderSpecified]); Assert.Equal("False", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_ResponseHeadersFileSpecified]); Assert.Equal("False", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_StreamingSpecified]); Assert.Equal("False", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_NoBodySpecified]); Assert.Equal("False", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_RequestBodyContentSpecified]); Assert.Equal("False", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_RequestBodyFileSpecified]); Assert.Equal("False", collectedTelemetry.Properties[TelemetryPropertyNames.HttpCommand_ResponseBodyFileSpecified]); }
/// <summary> /// Connect to the drone then repeatedly prompt for and send commands /// </summary> /// <param name="enableStatusMonitor"></param> public void Run(bool enableStatusMonitor = true) { char[] separators = { ' ' }; TelemetryCollector collector = null; TelloCommanderDbContext context = null; try { Connect(); if (enableStatusMonitor) { _monitor.Listen(DroneStatusMonitor.DefaultTelloStatusPort); } Console.WriteLine(); Console.WriteLine("You are connected to the Tello in API mode"); bool haveCommand; do { Console.WriteLine(); Console.Write("Enter command or hit ENTER to quit : "); string command = Console.ReadLine(); haveCommand = !string.IsNullOrEmpty(command); if (haveCommand) { Console.WriteLine($"Command : {command}"); try { string[] words = command.Trim().Split(separators, StringSplitOptions.RemoveEmptyEntries); switch (words[0]) { case "?": ReportDroneStatus(); LastResponse = "ok"; break; case "startcapture": int.TryParse(words[2], out int intervalMilliseconds); _monitor.StartCapture(words[1], intervalMilliseconds); LastResponse = "ok"; break; case "stopcapture": _monitor.StopCapture(); LastResponse = "ok"; break; case "startdbcapture": int.TryParse(words[3], out int collectionInterval); string[] filters = (words.Length > 4) ? words[4].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) : null; context = new TelloCommanderDbContextFactory().CreateDbContext(null); collector = new TelemetryCollector(context, _monitor); collector.Start(words[1], words[2], collectionInterval, filters); LastResponse = "ok"; break; case "stopdbcapture": if (collector != null) { collector.Stop(); context.Dispose(); collector = null; } LastResponse = "ok"; break; default: RunCommand(command); break; } Console.WriteLine($"Response: {LastResponse}"); } catch (Exception ex) { Console.WriteLine($"Error : {ex.Message}"); } } }while (haveCommand); _monitor.Stop(); Disconnect(); } catch (Exception ex) { Console.WriteLine($"Error Connecting: {ex.Message}"); } }
static void Main(string[] args) { PortingAssistantCLI cli = new PortingAssistantCLI(); cli.HandleCommand(args); var logConfiguration = new LoggerConfiguration().Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.Console(); var assemblypath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var telemetryConfiguration = JsonSerializer.Deserialize <TelemetryConfiguration>(File.ReadAllText(Path.Combine(assemblypath, "PortingAssistantTelemetryConfig.json"))); var configuration = new PortingAssistantConfiguration(); var roamingFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); var logs = Path.Combine(roamingFolder, "Porting Assistant for .NET", "logs"); var logFilePath = Path.Combine(logs, "portingAssistant-client-cli.log"); var metricsFilePath = Path.Combine(logs, "portingAssistant-client-cli.metrics"); string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion; var outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] (Porting Assistant Client CLI) (" + version + ") (" + cli.Tag + ") {SourceContext}: {Message:lj}{NewLine}{Exception}"; Serilog.Formatting.Display.MessageTemplateTextFormatter tf = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, CultureInfo.InvariantCulture); logConfiguration.WriteTo.File( logFilePath, rollingInterval: RollingInterval.Infinite, rollOnFileSizeLimit: false, outputTemplate: outputTemplate); Log.Logger = logConfiguration.CreateLogger(); if (cli.isSchema) { if (cli.schemaVersion) { Console.WriteLine(Common.Model.Schema.version); } } if (cli.isAssess) { try { TelemetryCollector.Builder(Log.Logger, metricsFilePath); var portingAssistantBuilder = PortingAssistantBuilder.Build(configuration, logConfig => logConfig.SetMinimumLevel(LogLevel.Debug) .AddSerilog(logger: Log.Logger, dispose: true)); var portingAssistantClient = portingAssistantBuilder.GetPortingAssistant(); var reportExporter = portingAssistantBuilder.GetReportExporter(); var solutionSettings = cli.IgnoreProjects != null && cli.IgnoreProjects.Count != 0 ? new AnalyzerSettings { IgnoreProjects = cli.IgnoreProjects, TargetFramework = cli.Target } : new AnalyzerSettings { IgnoreProjects = new List <string>(), TargetFramework = cli.Target }; var startTime = DateTime.Now; Task <SolutionAnalysisResult> analyzeResults; if (solutionSettings.UseGenerator) { analyzeResults = AnalyzeSolutionGenerator(portingAssistantClient, cli.SolutionPath, solutionSettings); } else { analyzeResults = portingAssistantClient.AnalyzeSolutionAsync(cli.SolutionPath, solutionSettings); analyzeResults.Wait(); } if (analyzeResults.IsCompletedSuccessfully) { reportExporter.GenerateJsonReport(analyzeResults.Result, cli.OutputPath); TelemetryCollector.SolutionAssessmentCollect(analyzeResults.Result, cli.Target, "1.8.0", $"Porting Assistant Client CLI", DateTime.Now.Subtract(startTime).TotalMilliseconds, cli.Tag); } else { Log.Logger.Error("err generated solution analysis report"); } if (cli.PortingProjects != null && cli.PortingProjects.Count != 0) { var PortingProjectResults = analyzeResults.Result.ProjectAnalysisResults .Where(project => cli.PortingProjects.Contains(project.ProjectName)); var FilteredRecommendedActions = PortingProjectResults .SelectMany(project => project.PackageAnalysisResults.Values .Where(package => { var comp = package.Result.CompatibilityResults.GetValueOrDefault(cli.Target); return(comp.Compatibility != Compatibility.COMPATIBLE && comp.CompatibleVersions.Count != 0); }) .SelectMany(package => package.Result.Recommendations.RecommendedActions)); var PortingRequest = new PortingRequest { Projects = analyzeResults.Result.SolutionDetails.Projects.Where(p => cli.PortingProjects.Contains(p.ProjectName)).ToList(), SolutionPath = cli.SolutionPath, TargetFramework = cli.Target.ToString(), RecommendedActions = FilteredRecommendedActions.ToList(), IncludeCodeFix = true }; var portingResults = portingAssistantClient.ApplyPortingChanges(PortingRequest); reportExporter.GenerateJsonReport(portingResults, cli.SolutionPath, cli.OutputPath); } UploadLogs(cli.Profile, telemetryConfiguration, logFilePath, metricsFilePath, logs); } catch (Exception ex) { Log.Logger.Error(ex, "error when using the tools :"); UploadLogs(cli.Profile, telemetryConfiguration, logFilePath, metricsFilePath, logs); Environment.Exit(-1); } } }
// Define a method that performs the authentication process // using a Facebook sign-in. private async System.Threading.Tasks.Task AuthenticateAsync(MobileServiceAuthenticationProvider provider) { if (NetworkHelper.IsNetworkAvailable() == false) { await MessageHelper.ShowMessage(CommonSettings.LoginNoNetworkMessage); return; } this.ViewModel.OperationInProgress = true; string username = "", email = "", authProvider = "", authProviderUserId = ""; try { // Change 'MobileService' to the name of your MobileServiceClient instance. // Sign-in using Facebook authentication. user = await App.TechReadyServicesClient .LoginAsync(provider); if (user != null) { var userInfo = await App.TechReadyServicesClient.InvokeApiAsync("UserInfo", HttpMethod.Get, null); //if (userInfo != null) //{ // Frame.Navigate(typeof(UserRegisterationPage)) //} if (userInfo != null) { switch (provider) { case MobileServiceAuthenticationProvider.Facebook: username = (string)userInfo["facebook"]["name"] ?? ""; email = (string)userInfo["facebook"]["email"] ?? ""; authProvider = "facebook"; authProviderUserId = user.UserId; break; case MobileServiceAuthenticationProvider.MicrosoftAccount: username = (string)userInfo["microsoft"]["name"] ?? ""; email = (string)userInfo["microsoft"]["emails"]["account"] ?? ""; authProvider = "microsoft"; authProviderUserId = user.UserId; break; case MobileServiceAuthenticationProvider.Twitter: username = (string)userInfo["twitter"]["Name"] ?? ""; authProvider = "twitter"; authProviderUserId = user.UserId; break; } Frame.Navigate(typeof(UserRegisterationPage), JsonConvert.SerializeObject( new UserRegistrationPageNavigationParameter("LoginPage") { Email = email, Username = username, AuthProvider = authProvider, AuthProviderUserId = authProviderUserId })); } } } catch (Exception ex) { TelemetryCollector.ReportExepction(ex); } finally { this.ViewModel.OperationInProgress = false; } //var dialog = new MessageDialog(message); //dialog.Commands.Add(new UICommand("OK")); //await dialog.ShowAsync(); }
/// <inheritdoc /> protected override List <IEvent> GetEventsImpl() { var data = TelemetryCollector.GetDataAndReset(); return(GenerateTelemetryEventsFromCounterData(data)); }