/// <summary> /// Report that a new remote session (runspace) is created. /// </summary> internal static void ReportRemoteSessionCreated( System.Management.Automation.Runspaces.RunspaceConnectionInfo connectionInfo) { RemoteSessionType sessionType = RemoteSessionType.Unknown; RemoteConfigurationType configurationType = RemoteConfigurationType.Unknown; if (connectionInfo is System.Management.Automation.Runspaces.NewProcessConnectionInfo) { sessionType = RemoteSessionType.LocalProcess; configurationType = RemoteConfigurationType.PSDefault; } else { System.Management.Automation.Runspaces.WSManConnectionInfo wsManConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.WSManConnectionInfo; if (wsManConnectionInfo != null) { sessionType = RemoteSessionType.WinRMRemote; // Parse configuration name from ShellUri: // ShellUri = 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell' // ConfigName = 'Microsoft.PowerShell' string configurationName = wsManConnectionInfo.ShellUri; if (!string.IsNullOrEmpty(configurationName)) { int index = configurationName.LastIndexOf('/'); if (index > -1) { configurationName = configurationName.Substring(index + 1); } } configurationType = GetConfigurationTypefromName(configurationName); } else { System.Management.Automation.Runspaces.VMConnectionInfo vmConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.VMConnectionInfo; if (vmConnectionInfo != null) { sessionType = RemoteSessionType.HyperVRemote; configurationType = GetConfigurationTypefromName(vmConnectionInfo.ConfigurationName); } else { System.Management.Automation.Runspaces.ContainerConnectionInfo containerConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.ContainerConnectionInfo; if (containerConnectionInfo != null) { sessionType = RemoteSessionType.ContainerRemote; configurationType = GetConfigurationTypefromName( (containerConnectionInfo.ContainerProc != null) ? containerConnectionInfo.ContainerProc.ConfigurationName : string.Empty); } } } } TelemetryWrapper.TraceMessage("PSNewRemoteSession", new { Type = sessionType, Configuration = configurationType }); }
private WebResourcePublishCommand(AsyncPackage package, OleMenuCommandService commandService, IVsSettingsManager vsSettingsManager) { m_token = new CancellationToken(); m_pane = new Guid("A8E3D03E-28C9-4900-BD48-CEEDEC35E7E6"); m_service = new DteService(vsSettingsManager); m_package = package ?? throw new ArgumentNullException(nameof(package)); m_telemetry = new TelemetryWrapper(m_service.Version, VersionHelper.GetVersionFromManifest()); if (commandService != null) { var deployMenuCommandID = new CommandID(CommandSet, DeployCommandId); var deployMenuItem = new OleMenuCommand(DeployMenuItemCallback, deployMenuCommandID); deployMenuItem.BeforeQueryStatus += HandleDeployMenuState; commandService.AddCommand(deployMenuItem); var initializeMenuCommandId = new CommandID(CommandSet, InitCommandId); var initMenuItem = new OleMenuCommand(InitMenuItemCallback, initializeMenuCommandId); initMenuItem.BeforeQueryStatus += HandleInitMenuState; commandService.AddCommand(initMenuItem); var singeDeplotMenuCommandId = new CommandID(CommandSet, SingleDeployCommandId); var initSingleDeploy = new OleMenuCommand(SingleDeployMenuItemCallback, singeDeplotMenuCommandId); initSingleDeploy.BeforeQueryStatus += HandleSingleDeployMenuState; commandService.AddCommand(initSingleDeploy); // Fix for enable/disable states HandleInitMenuState(initMenuItem, null); HandleDeployMenuState(deployMenuItem, null); } }
public void Publish(DeployConfigurationModel deployConfiguration, TelemetryWrapper telemetry, string singleResourceName, string project, string projectPath, string basePath) { try { Action <string> reportAction = (m) => { ReportProgress?.Invoke(this, m); }; var context = new XrmService(deployConfiguration.DynamicsSettings, deployConfiguration.Solution, telemetry, reportAction); var sourceControl = new VersioningService(projectPath, basePath, deployConfiguration.Branch, reportAction, telemetry); var sourceControlResult = sourceControl.QueryLocalRepository(); // Must resolve conflicts or something went wrong with TFS interaction if (!sourceControlResult.Continue && sourceControlResult.Changes == null) { return; } var changeList = sourceControlResult.Changes; if (!string.IsNullOrEmpty(singleResourceName)) { var filteredChangeList = sourceControlResult.Changes.Where(x => x.FileName.Equals(singleResourceName)).ToArray(); changeList = filteredChangeList; } PublishImpl(context, sourceControl, deployConfiguration, telemetry, changeList, project); } catch (Exception exception) { ReportProgress?.Invoke(this, $"[ERROR] => {exception.Message}\n"); if (!(exception is ToolkitException)) { telemetry.TrackExceptionWithCustomMetrics(exception); } } }
public XrmService(DynamicsConnectionSettings connectionSettings, string solution, TelemetryWrapper telemetry, Action <string> report) { try { m_progress = report; m_telemetry = telemetry; m_solution = solution; m_service = new Lazy <IOrganizationService>(() => { var crmServiceClient = new CrmServiceClient(connectionSettings.ToString()); IOrganizationService service = crmServiceClient as IOrganizationService; if (service == null) { throw new NullReferenceException("Unable to instantiate IOrganizationService"); } return(service); }); } catch (Exception exception) { m_progress?.Invoke($"[ERROR] => {exception.Message}"); m_telemetry.TrackExceptionWithCustomMetrics(exception); } }
public NewPublishSettingsPageViewModel(DteService service, TelemetryWrapper telemetry) { SaveConfigurationCommand = new RelayCommand <DialogWindow>((w) => Save(w)); NavigateToPatGuide = new RelayCommand(() => NavigateToUrl()); Configuration = new DeployConfigurationModelFacade(); m_service = service; m_telemetry = telemetry; }
public VersioningService(string solutionPath, string baseProjectPath, string branch, Action <string> reportProgress, TelemetryWrapper telemetry) { m_progress = reportProgress; m_telemetry = telemetry; m_repoPath = solutionPath; m_basePath = baseProjectPath; m_branch = $@"refs/heads/{branch}"; m_username = "******"; }
public override Task OnPageEnteringAsync(WizardEnteringArgs args) { base.Wizard.IsNextEnabled = WebHookReceiverOptions.Any(x => x.IsChecked == true); base.Wizard.Pages[1].IsEnabled = WebHookReceiverOptions.Any(x => x.IsChecked == true); TelemetryWrapper.StartPageView("Select Receivers"); return(base.OnPageEnteringAsync(args)); }
/// <summary> /// Report Get-Help requests, how many results are returned, and how long it took. /// </summary> internal static void ReportGetHelpTelemetry(string name, int topicsFound, long timeInMS, bool updatedHelp) { TelemetryWrapper.TraceMessage("PSHelpRequest", new { TopicCount = topicsFound, TimeInMS = timeInMS, RanUpdateHelp = updatedHelp, HelpTopic = name, }); }
public override Task <ConnectedServiceConfigurator> CreateConfiguratorAsync(ConnectedServiceProviderContext context) { ConnectedServiceInstance instance = new ConnectedServiceInstance(); ConnectedServiceConfigurator configurator = new AddWebHookWizard(context, instance); TelemetryWrapper.Refresh(); TelemetryWrapper.RecordEvent("WebHook Experience Started"); return(Task.FromResult(configurator)); }
private void InstallPackage(string name, string version) { NuGetInstaller.InstallPackage(NuGetConstants.DefaultFeedUrl, Project, name, version, false); // record the telemetry for the nuget install TelemetryWrapper.RecordEvent("NuGet Install", properties: new Dictionary <string, string>() { { "Package", name }, { "Version", version } }); }
/// <summary> /// Report that a new local session (runspace) is created /// </summary> internal static void ReportLocalSessionCreated( System.Management.Automation.Runspaces.InitialSessionState iss, System.Management.Automation.Host.TranscriptionData transcriptionData) { bool isConstrained = (iss != null) && (iss.DefaultCommandVisibility != SessionStateEntryVisibility.Public) && (iss.LanguageMode != PSLanguageMode.FullLanguage); bool isTranscripting = (transcriptionData != null) && (transcriptionData.SystemTranscript != null); TelemetryWrapper.TraceMessage("PSNewLocalSession", new { Constrained = isConstrained, Transcripting = isTranscripting }); }
/// <summary> /// Called after there are no more open runspaces. In some host applications, this could /// report multiple exits. /// </summary> public static void ReportExitTelemetry(IHostProvidesTelemetryData ihptd) { TelemetryWrapper.TraceMessage("PSHostStop", new { InteractiveCommandCount = ihptd != null ? ihptd.InteractiveCommandCount : 0, TabCompletionTimes = s_tabCompletionTimes, TabCompletionCounts = s_tabCompletionCounts, TabCompletionResultCounts = s_tabCompletionResultCounts, SessionTime = (DateTime.Now - s_sessionStartTime).TotalMilliseconds }); // In case a host opens another runspace, we will want another PSHostStart event, // so reset our flag here to allow that event to fire. s_anyPowerShellSessionOpen = 0; }
public override Task <PageNavigationResult> OnPageLeavingAsync(WizardLeavingArgs args) { if (!Instance.Metadata.ContainsKey(Constants.MetadataKeyForStoringReceiverSecrets)) { Instance.Metadata.Add(Constants.MetadataKeyForStoringReceiverSecrets, new List <WebHookReceiverSecret>()); } ((List <WebHookReceiverSecret>)Instance.Metadata[Constants.MetadataKeyForStoringReceiverSecrets]).Clear(); foreach (var item in ReceiverSecrets) { ((List <WebHookReceiverSecret>)Instance.Metadata[Constants.MetadataKeyForStoringReceiverSecrets]).Add(item); } TelemetryWrapper.EndPageView(); return(base.OnPageLeavingAsync(args)); }
/// <summary> /// Called either after opening a runspace (the default), or by the host application. /// </summary> public static void ReportStartupTelemetry(IHostProvidesTelemetryData ihptd) { // Avoid reporting startup more than once, except if we report "exited" and // another runspace gets opened. if (Interlocked.CompareExchange(ref s_anyPowerShellSessionOpen, 1, 0) == 1) { return; } bool is32Bit; #if CORECLR is32Bit = IntPtr.Size == 4; #else is32Bit = !Environment.Is64BitProcess; #endif var psversion = PSVersionInfo.PSVersion.ToString(); var hostName = Process.GetCurrentProcess().ProcessName; if (ihptd != null) { TelemetryWrapper.TraceMessage("PSHostStart", new { Interactive = ihptd.HostIsInteractive ? HostIsInteractive.Iteractive : HostIsInteractive.NonInteractive, ProfileLoadTime = ihptd.ProfileLoadTimeInMS, ReadyForInputTime = ihptd.ReadyForInputTimeInMS, Is32Bit = is32Bit, PSVersion = psversion, ProcessName = hostName, }); } else { TelemetryWrapper.TraceMessage("PSHostStart", new { Interactive = HostIsInteractive.Unknown, ProfileLoadTime = 0, ReadyForInputTime = 0, Is32Bit = is32Bit, PSVersion = psversion, ProcessName = hostName, }); } s_sessionStartTime = DateTime.Now; }
/// <summary> /// Report that a module was loaded, but only do so for modules that *might* be authored by Microsoft. We can't /// be 100% certain, but we'll ignore non-Microsoft module names when looking at any data, so it's best to /// at least attempt avoiding collecting data we'll ignore. /// </summary> internal static void ReportModuleLoad(PSModuleInfo foundModule) { var modulePath = foundModule.Path; var companyName = foundModule.CompanyName; bool couldBeMicrosoftModule = (modulePath != null && (modulePath.StartsWith(Utils.DefaultPowerShellAppBase, StringComparison.OrdinalIgnoreCase) || // The following covers both 64 and 32 bit Program Files by assuming 32bit is just ...\Program Files + " (x86)" modulePath.StartsWith(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), StringComparison.OrdinalIgnoreCase))) || (companyName != null && foundModule.CompanyName.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase)); if (couldBeMicrosoftModule) { TelemetryWrapper.TraceMessage("PSImportModule", new { ModuleName = foundModule.Name, Version = foundModule.Version.ToString() }); } }
public override Task OnPageEnteringAsync(WizardEnteringArgs args) { TelemetryWrapper.StartPageView("Configure Receivers"); Wizard.IsNextEnabled = false; Wizard.IsFinishEnabled = true; ReceiverSecrets.Clear(); var selectedReceiverOptions = Instance.Metadata[Constants.MetadataKeyForStoringSelectedReceivers] as IEnumerable <WebHookReceiverOption>; if (selectedReceiverOptions != null) { foreach (var option in selectedReceiverOptions) { ReceiverSecrets.Add(new WebHookReceiverSecret(option)); } } return(base.OnPageEnteringAsync(args)); }
internal static void ReportTabCompletionTelemetry(long elapsedMilliseconds, int count, CompletionResultType completionResultType) { // We'll collect some general statistics. int idx = (int)completionResultType; if (idx >= 0 && idx <= (int)CompletionResultType.DynamicKeyword) { s_tabCompletionTimes[idx] += elapsedMilliseconds; s_tabCompletionCounts[idx]++; s_tabCompletionResultCounts[idx] += count; } // Also write an event for any slow tab completion (> 250ms). if (elapsedMilliseconds > 250) { TelemetryWrapper.TraceMessage("PSSlowTabCompletion", new { Time = elapsedMilliseconds, Count = count, Type = completionResultType, }); } }
/// <summary> /// Report some telemetry about the scripts that are run /// </summary> internal static void ReportScriptTelemetry(Ast ast, bool dotSourced, long compileTimeInMS) { if (ast.Parent != null || !TelemetryWrapper.IsEnabled) { return; } Task.Run(() => { var extent = ast.Extent; var text = extent.Text; var hash = text.GetHashCode(); // Ignore 'prompt' so we don't generate an event for every 'prompt' that is invoked. // (We really should only create 'prompt' once, but we don't. if (hash == s_promptHashCode) { return; } var visitor = new ScriptBlockTelemetry(); ast.Visit(visitor); var scriptFileType = ScriptFileType.None; var fileName = extent.File; if (fileName != null) { var ext = System.IO.Path.GetExtension(fileName); if (".ps1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Ps1; } else if (".psd1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Psd1; } else if (".psm1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Psm1; } else { // Reachable? scriptFileType = ScriptFileType.Other; } } TelemetryWrapper.TraceMessage("PSScriptDetails", new { Hash = hash, IsDotSourced = dotSourced, ScriptFileType = scriptFileType, Length = text.Length, LineCount = extent.EndLineNumber - extent.StartLineNumber, CompileTimeInMS = compileTimeInMS, StatementCount = visitor.StatementCount, CountOfCommands = visitor.CountOfCommands, CountOfDotSourcedCommands = visitor.CountOfDotSourcedCommands, MaxArrayLength = visitor.MaxArraySize, ArrayLiteralCount = visitor.ArrayLiteralCount, ArrayLiteralCumulativeSize = visitor.ArrayLiteralCumulativeSize, MaxStringLength = visitor.MaxStringSize, StringLiteralCount = visitor.StringLiteralCount, StringLiteralCumulativeSize = visitor.StringLiteralCumulativeSize, MaxPipelineDepth = visitor.MaxPipelineDepth, PipelineCount = visitor.PipelineCount, FunctionCount = visitor.FunctionCount, ScriptBlockCount = visitor.ScriptBlockCount, ClassCount = visitor.ClassCount, EnumCount = visitor.EnumCount, CommandsCalled = visitor.CommandsCalled, }); }); }
/// <summary> /// Public API to expose Telemetry in PowerShell /// Provide meaningful message. Ex: PSCONSOLE_START, PSRUNSPACE_START /// arguments are of anonymous type. Ex: new { PSVersion = "5.0", PSRemotingProtocolVersion = "2.2"} /// </summary> public static void TraceMessage <T>(string message, T arguments) { TelemetryWrapper.TraceMessage(message, arguments); }
public override Task <PageNavigationResult> OnPageLeavingAsync(WizardLeavingArgs args) { TelemetryWrapper.EndPageView(); return(base.OnPageLeavingAsync(args)); }
/// <summary> /// Report when Get-Command fails to find something. /// </summary> internal static void ReportGetCommandFailed(string[] name, long timeInMS) { TelemetryWrapper.TraceMessage("PSGetCommandFailed", new { TimeInMS = timeInMS, CommandNames = name }); }
private void PublishImpl(XrmService context, VersioningService gitvc, DeployConfigurationModel deployConfiguration, TelemetryWrapper telemetry, RawChanges[] changes, string project) { try { ChangeManagerService container = new ChangeManagerService(changes, deployConfiguration.Prefix, context); telemetry.TrackCustomEventWithCustomMetrics("Deploy Started", new MetricData("Project Name", project)); if (container.WebResources.Count > 0) { ReportProgress?.Invoke(this, $"[DYNAMICS] => Found {container.WebResources.Count} Web Resource."); ReportProgress?.Invoke(this, $"[DYNAMICS] => '{deployConfiguration.Prefix}' used as base path."); ReportProgress?.Invoke(this, $"[DYNAMICS] => Fetching '{deployConfiguration.Solution}' solution from CRM."); container.EnsureContinue(deployConfiguration.Solution, deployConfiguration.Prefix); ReportProgress?.Invoke(this, $"[DYNAMICS] => Publishing changes to the CRM."); var faultedFlushResult = context.Flush(container.BuildRequestList(deployConfiguration.Solution)); if (!faultedFlushResult && deployConfiguration.CheckInEnabled) { ReportProgress?.Invoke(this, $"[AZOPS] => Commit & Push in progress."); gitvc.CommitAndPush(deployConfiguration.Password); } ReportProgress?.Invoke(this, $"[AZOPS] => Publish completed."); } telemetry.TrackCustomEventWithCustomMetrics("Deploy Finished", new MetricData("Project Name", project)); } catch (Exception exception) { ReportProgress?.Invoke(this, $"[ERROR] => {exception.Message}\n"); if (!(exception is ToolkitException)) { telemetry.TrackExceptionWithCustomMetrics(exception); } } }
public async override Task <AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct) { AddServiceInstanceResult result = new AddServiceInstanceResult( Resources.ConnectedServiceProjectFolderName, new Uri(Resources.MoreInfoUrl)); Project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy); string projectNamespace = Project.Properties.Item("DefaultNamespace").Value.ToString(); // get the collection of keys to be added var receiverSecrets = context.ServiceInstance.Metadata[Constants.MetadataKeyForStoringReceiverSecrets] as IEnumerable <WebHookReceiverSecret>; // install all of the base WebHook NuGets await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, Resources.LogMessageGettingCoreNuGets); InstallPackage("Microsoft.AspNet.WebApi.WebHost", "5.2.3"); InstallPackage("Microsoft.AspNet.WebHooks.Common", "1.2.0-beta3a"); InstallPackage("Microsoft.AspNet.WebHooks.Receivers", "1.2.0-beta3a"); // remember the list of providers selected List <string> providers = new List <string>(); using (EditableXmlConfigHelper configHelper = context.CreateEditableXmlConfigHelper()) { // iterate over the selected hook receivers foreach (var item in receiverSecrets) { // add the keys in the web.config for each provider configHelper.SetAppSetting(item.ReceiverSecretConfigSettingName, item.Secret); // pull in the NuGet for the receiver await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, string.Format(Resources.LogMessageGettingReceiver, item.Option.Name)); InstallPackage(item.Option.NuGetPackage, item.Option.NuGetVersionOverride); var classNamePrefix = ((string.IsNullOrEmpty(item.Option.ConfigWireupOverride)) ? item.Option.Name : item.Option.ConfigWireupOverride); var receiverName = ((string.IsNullOrEmpty(item.Option.ReceiverNameOverride)) ? classNamePrefix : item.Option.ReceiverNameOverride); var incomingType = ((string.IsNullOrEmpty(item.Option.IncomingTypeOverride)) ? "JObject" : item.Option.IncomingTypeOverride); // add the handler code to the project await GeneratedCodeHelper .GenerateCodeFromTemplateAndAddToProject( context, "WebHookHandler", string.Format($@"WebHookHandlers\{classNamePrefix}WebHookHandler.cs"), new Dictionary <string, object> { { "ns", projectNamespace }, { "classNamePrefix", classNamePrefix }, { "receiverName", receiverName }, { "incomingType", incomingType } }); // remember this provider providers.Add(classNamePrefix); // record the telemetry for the receiver TelemetryWrapper.RecordEvent($"{item.Option.Name}"); } // add the code to the project to configure all of the providers await GeneratedCodeHelper .GenerateCodeFromTemplateAndAddToProject( context, "WebHookConfig", string.Format($@"App_Start\WebHookConfig.cs"), new Dictionary <string, object> { { "ns", projectNamespace }, { "providers", providers.ToArray() } }); // persist the configuration changes configHelper.Save(); } // record that we finished TelemetryWrapper.RecordEvent("WebHook Experience Completed"); // return return(result); }
public NewPublishSettingsPage(DteService dteService, TelemetryWrapper telemetry) { InitializeComponent(); DataContext = new NewPublishSettingsPageViewModel(dteService, telemetry); }