private async Task EnsureVirtualConnectionClientCreated() { // Asynchronous equivalent to a 'lock(...) { ... }' await _connectionCreationSemaphore.WaitAsync(); try { if (_virtualConnectionClient == null) { _physicalConnection = StreamConnection.Create(); var connection = await _physicalConnection.Open(_socketAddress); _virtualConnectionClient = new VirtualConnectionClient(connection); _virtualConnectionClient.OnError += (ex) => { // This callback is fired only if there's a protocol-level failure (e.g., child process disconnected // unexpectedly). It does *not* fire when RPC calls return errors. Since there's been a protocol-level // failure, this Node instance is no longer usable and should be discarded. _connectionHasFailed = true; OutputLogger.LogError(0, ex, ex.Message); }; } } finally { _connectionCreationSemaphore.Release(); } }
public void SolutionEventsOnBeforeClosing() { try { if (!(GetGlobalService(typeof(DTE)) is DTE dte)) { throw new ArgumentNullException(Core.Resources.Resource.ErrorMessage_ErrorAccessingDTE); } SharedGlobals.SetGlobal("UseCrmIntellisense", null, dte); if (SharedGlobals.GetGlobal("CrmService", dte) != null) { SharedGlobals.SetGlobal("CrmService", null, dte); } if (SharedGlobals.GetGlobal("CrmMetadata", dte) != null) { SharedGlobals.SetGlobal("CrmMetadata", null, dte); OutputLogger.WriteToOutputWindow("Clearing metadata", MessageType.Info); } } catch (Exception ex) { ExceptionHandler.LogException(Logger, null, ex); throw; } }
public static bool ImportSolution(CrmServiceClient client, string path) { var solutionBytes = FileSystem.GetFileBytes(path); if (solutionBytes == null) { return(false); } try { var request = new ImportSolutionRequest { CustomizationFile = solutionBytes, OverwriteUnmanagedCustomizations = true, PublishWorkflows = true, ImportJobId = Guid.NewGuid() }; client.Execute(request); ExLogger.LogToFile(Logger, $"{Resource.Message_ImportedSolution}: {path}", LogLevel.Info); OutputLogger.WriteToOutputWindow($"{Resource.Message_ImportedSolution}: {path}", MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorImportingSolution, ex); return(false); } }
public void ResolveImports(ITextProvider text, ISassDocument document, IDocumentManager documentManager) { try { if (Filename == null || Filename.Value == null) { return; } var path = ImportResolver.ResolvePath(Filename.Value, text, document.Source.Directory); if (string.IsNullOrEmpty(path)) { return; } var importFile = new FileInfo(path); if (importFile.Exists) { Document = documentManager.Import(importFile, document); } } catch (Exception ex) { OutputLogger.Log(ex, "Failed to process reference file."); } }
public static void GetMetadata(CrmServiceClient client) { try { using (client) { RetrieveAllEntitiesRequest metaDataRequest = new RetrieveAllEntitiesRequest { EntityFilters = EntityFilters.Entity | EntityFilters.Attributes }; RetrieveAllEntitiesResponse metaDataResponse = (RetrieveAllEntitiesResponse)client.Execute(metaDataRequest); ProcessMetadata(metaDataResponse); } } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow( "Error Retrieving Metadata From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); } catch (Exception ex) { OutputLogger.WriteToOutputWindow( "Error Retrieving Metadata From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); } }
public static string EncodedImage(string filePath, FileExtensionType extension) { try { switch (extension) { case FileExtensionType.Ico: return(ImageEncoding.EncodeIco(filePath)); case FileExtensionType.Gif: case FileExtensionType.Jpg: case FileExtensionType.Png: return(ImageEncoding.EncodeImage(filePath, extension)); case FileExtensionType.Svg: return(ImageEncoding.EncodeSvg(filePath)); default: return(null); } } catch (Exception ex) { OutputLogger.WriteToOutputWindow(Resource.Error_ErrorEncodingImage, MessageType.Error); ExceptionHandler.LogException(Logger, Resource.Error_ErrorEncodingImage, ex); return(null); } }
public void Test() { var logger = new OutputLogger(output); var config = DefaultConfig.Instance.With(logger); var summary = BenchmarkRunner.Run<PerformanceUnitTest>(config); // Sanity checks, to be sure that the different benchmarks actually run var testOutput = logger.GetLog(); Assert.Contains("// ### Slow Benchmark called ###" + Environment.NewLine, testOutput); Assert.Contains("// ### Fast Benchmark called ###" + Environment.NewLine, testOutput); // Check that slow benchmark is actually slower than the fast benchmark! var slowBenchmarkRun = summary.GetRunsFor<PerformanceUnitTest>(r => r.SlowBenchmark()).First(); var fastBenchmarkRun = summary.GetRunsFor<PerformanceUnitTest>(r => r.FastBenchmark()).First(); Assert.True(slowBenchmarkRun.GetAverageNanoseconds() > fastBenchmarkRun.GetAverageNanoseconds(), string.Format("Expected SlowBenchmark: {0:N2} ns to be MORE than FastBenchmark: {1:N2} ns", slowBenchmarkRun.GetAverageNanoseconds(), fastBenchmarkRun.GetAverageNanoseconds())); Assert.True(slowBenchmarkRun.GetOpsPerSecond() < fastBenchmarkRun.GetOpsPerSecond(), string.Format("Expected SlowBenchmark: {0:N2} Ops to be LESS than FastBenchmark: {1:N2} Ops", slowBenchmarkRun.GetOpsPerSecond(), fastBenchmarkRun.GetOpsPerSecond())); // Whilst we're at it, let's do more specific Asserts as we know what the elasped time should be var slowBenchmarkReport = summary.GetReportFor<PerformanceUnitTest>(r => r.SlowBenchmark()); var fastBenchmarkReport = summary.GetReportFor<PerformanceUnitTest>(r => r.FastBenchmark()); foreach (var slowRun in slowBenchmarkReport.GetResultRuns()) Assert.InRange(slowRun.GetAverageNanoseconds() / 1000.0 / 1000.0, low: 98, high: 102); foreach (var fastRun in fastBenchmarkReport.GetResultRuns()) Assert.InRange(fastRun.GetAverageNanoseconds() / 1000.0 / 1000.0, low: 14, high: 17); }
public static bool UpdateAndPublishSingle(CrmServiceClient client, List <Entity> webResources) { //CRM 2011 < UR12 try { OrganizationRequestCollection requests = CreateUpdateRequests(webResources); foreach (OrganizationRequest request in requests) { client.Execute(request); OutputLogger.WriteToOutputWindow("Uploaded Web Resource", MessageType.Info); } string publishXml = CreatePublishXml(webResources); PublishXmlRequest publishRequest = CreatePublishRequest(publishXml); client.Execute(publishRequest); OutputLogger.WriteToOutputWindow("Published Web Resource(s)", MessageType.Info); return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow("Error Updating And Publishing Web Resource(s) To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(false); } catch (Exception ex) { OutputLogger.WriteToOutputWindow("Error Updating And Publishing Web Resource(s) To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
public static bool UpdateAndPublishSingle(CrmServiceClient client, List <Entity> webResources) { //CRM 2011 < UR12 try { OrganizationRequestCollection requests = CreateUpdateRequests(webResources); foreach (OrganizationRequest request in requests) { client.Execute(request); OutputLogger.WriteToOutputWindow(Resource.Message_UploadedWebResource, MessageType.Info); } string publishXml = CreatePublishXml(webResources); PublishXmlRequest publishRequest = CreatePublishRequest(publishXml); client.Execute(publishRequest); OutputLogger.WriteToOutputWindow(Resource.Message_PublishedWebResources, MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorUpdatingPublishingWebResources, ex); return(false); } }
public static bool Uninstall(DTE dte, Project project) { try { var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); if (componentModel == null) { return(false); } var uninstaller = componentModel.GetService <IVsPackageUninstaller>(); NuGetProcessor.UnInstallPackage(uninstaller, project, ExtensionConstants.IlMergeNuGet); OutputLogger.WriteToOutputWindow(Resource.Message_ILMergeUninstalled, MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorUninstallingILMerge, ex); return(false); } }
public static void AddFileFromTemplate(Project project, string templatePartialPath, string filename) { try { var codebase = Assembly.GetExecutingAssembly().CodeBase; var uri = new Uri(codebase, UriKind.Absolute); var path = Path.GetDirectoryName(uri.LocalPath); if (string.IsNullOrEmpty(path)) { OutputLogger.WriteToOutputWindow($"{Resource.ErrorMessage_FindTemplateDirectory}: {path}", MessageType.Error); return; } //TODO: update path for localization var templatePath = Path.Combine(path, $@"ItemTemplates\CSharp\D365 DevEx\1033\{templatePartialPath}.vstemplate"); project.ProjectItems.AddFromTemplate(templatePath, filename); } catch (Exception ex) { ExceptionHandler.LogException(Logger, $"{Resource.ErrorMessage_CreateFileFromTemplate}: {filename}", ex); MessageBox.Show($"{Resource.ErrorMessage_CreateFileFromTemplate}: {filename}"); } }
public static bool ImportSolution(CrmServiceClient client, string path) { byte[] solutionBytes = CrmDeveloperExtensions2.Core.FileSystem.GetFileBytes(path); if (solutionBytes == null) { return(false); } try { ImportSolutionRequest request = new ImportSolutionRequest { //TODO: make configurable CustomizationFile = solutionBytes, OverwriteUnmanagedCustomizations = true, PublishWorkflows = true, ImportJobId = Guid.NewGuid() }; ImportSolutionResponse response = (ImportSolutionResponse)client.Execute(request); return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow("Error Importing Solution To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(false); } catch (Exception ex) { OutputLogger.WriteToOutputWindow("Error Importing Solution To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
public static bool UpdateCrmAssembly(CrmServiceClient client, CrmAssembly crmAssembly, string assebmlyPath) { try { Entity assembly = new Entity("pluginassembly") { Id = crmAssembly.AssemblyId, ["content"] = Convert.ToBase64String(CrmDeveloperExtensions2.Core.FileSystem.GetFileBytes(assebmlyPath)) }; client.Update(assembly); return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow( "Error Updating Assembly In CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(false); } catch (Exception ex) { OutputLogger.WriteToOutputWindow( "Error Updating Assembly In CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
public static bool SetSolutionXmlVersion(Project project, Version newVersion) { try { bool isValid = ValidateSolutionXml(project); if (!isValid) { return(false); } Version oldVersion = GetSolutionXmlVersion(project); if (newVersion < oldVersion) { OutputLogger.WriteToOutputWindow("Unexpected error setting Solution.xml version: new version cannot be lower than old version", MessageType.Error); return(false); } string solutionXmlPath = GetSolutionXmlPath(project); XmlDocument doc = new XmlDocument(); doc.Load(solutionXmlPath); XmlNodeList versionNodes = doc.GetElementsByTagName("Version"); versionNodes[0].InnerText = newVersion.ToString(); doc.Save(solutionXmlPath); return(true); } catch (Exception ex) { OutputLogger.WriteToOutputWindow("Unexpected error setting Solution.xml version: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
private static void ProcessMetadata(RetrieveAllEntitiesResponse metaDataResponse) { ExLogger.LogToFile(Logger, Resource.Message_ProcessingMetadata, LogLevel.Info); OutputLogger.WriteToOutputWindow(Resource.Message_ProcessingMetadata, MessageType.Info); var entities = metaDataResponse.EntityMetadata; Metadata = new List <CompletionValue>(); var entityTriggerCharacter = UserOptionsHelper.GetOption <string>(UserOptionProperties.IntellisenseEntityTriggerCharacter); var entityFieldCharacter = UserOptionsHelper.GetOption <string>(UserOptionProperties.IntellisenseFieldTriggerCharacter); foreach (var entityMetadata in entities) { Metadata.Add(new CompletionValue($"{entityTriggerCharacter}{entityMetadata.LogicalName}", entityMetadata.LogicalName, GetDisplayName(entityMetadata.DisplayName), MetadataType.Entity)); Metadata.Add(new CompletionValue($"{entityTriggerCharacter}{entityMetadata.LogicalName}{entityFieldCharacter}?field?", $"{entityTriggerCharacter}{entityMetadata.LogicalName}", GetDisplayName(entityMetadata.DisplayName), MetadataType.None)); foreach (var attribute in entityMetadata.Attributes.Where(attribute => attribute.IsValidForCreate.GetValueOrDefault() || attribute.IsValidForUpdate.GetValueOrDefault() || attribute.IsValidForRead.GetValueOrDefault())) { Metadata.Add(new CompletionValue($"{entityTriggerCharacter}{entityMetadata.LogicalName}_{attribute.LogicalName}", attribute.LogicalName, $"{GetDisplayName(attribute.DisplayName)}: {attribute.AttributeType.GetValueOrDefault()}", MetadataType.Attribute)); } } Metadata = Metadata.OrderBy(m => m.Name).ToList(); }
public static string CreateToolPath() { var spPath = UserOptionsHelper.GetOption <string>(UserOptionProperties.SolutionPackagerToolPath); if (string.IsNullOrEmpty(spPath)) { OutputLogger.WriteToOutputWindow(Resource.ErrorMessage_SetSolutionPackagerPath, MessageType.Error); return(null); } if (!spPath.EndsWith("\\", StringComparison.CurrentCultureIgnoreCase)) { spPath += "\\"; } var toolPath = @"""" + spPath + "SolutionPackager.exe" + @""""; if (File.Exists(spPath + "SolutionPackager.exe")) { return(toolPath); } OutputLogger.WriteToOutputWindow($"S{Resource.ErrorMessage_SolutionPackagerNotFound}: {spPath}", MessageType.Error); return(null); }
public static bool AddWebResourceToSolution(CrmServiceClient client, string uniqueName, Guid webResourceId) { try { var scRequest = new AddSolutionComponentRequest { ComponentType = 61, SolutionUniqueName = uniqueName, ComponentId = webResourceId }; client.Execute(scRequest); ExLogger.LogToFile(Logger, Resource.Message_NewWebResourceAddedSolution, LogLevel.Info); OutputLogger.WriteToOutputWindow(Resource.Message_NewWebResourceAddedSolution, MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorAddingWebResourceSolution, ex); return(false); } }
public static string CreateToolPath(DTE dte) { CrmDeveloperExtensions2.Core.UserOptionsGrid.GetSolutionPackagerToolPath(dte); string spPath = CrmDeveloperExtensions2.Core.UserOptionsGrid.GetSolutionPackagerToolPath(dte); if (string.IsNullOrEmpty(spPath)) { OutputLogger.WriteToOutputWindow("Please set the Solution Packager path in options", MessageType.Error); return(null); } if (!spPath.EndsWith("\\")) { spPath += "\\"; } string toolPath = @"""" + spPath + "SolutionPackager.exe" + @""""; if (!File.Exists(spPath + "SolutionPackager.exe")) { OutputLogger.WriteToOutputWindow($"SolutionPackager.exe not found at: {spPath}", MessageType.Error); return(null); } return(toolPath); }
public static bool AddWebResourceToSolution(CrmServiceClient client, string uniqueName, Guid webResourceId) { try { AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest { ComponentType = 61, SolutionUniqueName = uniqueName, ComponentId = webResourceId }; AddSolutionComponentResponse response = (AddSolutionComponentResponse)client.Execute(scRequest); OutputLogger.WriteToOutputWindow("New Web Resource Added To Solution: " + response.id, MessageType.Info); return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow( "Error adding web resource to solution: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(false); } catch (Exception ex) { OutputLogger.WriteToOutputWindow( "Error adding web resource to solution: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
public static bool AddAssemblyToSolution(CrmServiceClient client, Guid assemblyId, string uniqueName) { try { var scRequest = new AddSolutionComponentRequest { ComponentType = 91, SolutionUniqueName = uniqueName, ComponentId = assemblyId }; client.Execute(scRequest); ExLogger.LogToFile(Logger, $"{Resource.Message_AssemblyAddedSolution}: {uniqueName} - {assemblyId}", LogLevel.Info); OutputLogger.WriteToOutputWindow($"{Resource.Message_AssemblyAddedSolution}: {uniqueName} - {assemblyId}", MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorAddingAssemblySolution, ex); return(false); } }
public async Task TestCreateReadUpdateDeleteConfiguration() { var now = DateTime.UtcNow; const string systemId = "TestSystemId"; const string originalPersonIdFieldName = "OriginalPersonIdFieldName"; const string updatedPersonIdFieldName = "UpdatedPersonIdFieldName"; var testConfiguration = new PowerofficeConfiguration { AcceptedOrganisationStatuses = new[] { "AcceptedOrganisationStatuses1", "AcceptedOrganisationStatuses2" }, AcceptedOrganisationTypes = new[] { "AcceptedOrganisationTypes1", "AcceptedOrganisationTypes2" }, DeliveryIdFieldName = "DeliveryIdFieldName", Disabled = true, LastSuccessfulCopyFromErpHeartbeat = now, LastSuccessfulCopyToErpHeartbeat = now, OrganisationCodeFieldName = "OrganisationCodeFieldName", OrganisationIdFieldName = "OrganisationIdFieldName", PersonIdFieldName = originalPersonIdFieldName, PowerofficeClientKey = new Guid("7931f515-1114-4215-940a-aa18c3b49f31"), PrimaryContactCheckboxFieldName = "PrimaryContactCheckboxFieldName", ProductCodeFieldName = "ProductCodeFieldName", ProductIdFieldName = "ProductIdFieldName", ProductNameFieldName = "ProductNameFieldName", WebcrmApiKey = "WebcrmApiKey", WebcrmSystemId = systemId }; bool isValid = testConfiguration.Validate(out var results); foreach (var result in results) { OutputLogger.LogTrace(result.ErrorMessage); } isValid.Should().BeTrue(); results.Should().HaveCount(0); await ConfigService.SavePowerofficeConfiguration(testConfiguration); var loadedConfiguration = ConfigService.LoadPowerofficeConfiguration(systemId); loadedConfiguration.Should().NotBeNull(); loadedConfiguration.Disabled.Should().BeTrue(); loadedConfiguration.PersonIdFieldName.Should().Be(originalPersonIdFieldName); loadedConfiguration.WebcrmSystemId.Should().Be(systemId); loadedConfiguration.PersonIdFieldName = updatedPersonIdFieldName; await ConfigService.SavePowerofficeConfiguration(loadedConfiguration); var updatedConfiguration = ConfigService.LoadPowerofficeConfiguration(systemId); updatedConfiguration.PersonIdFieldName.Should().Be(updatedPersonIdFieldName); await ConfigService.DeletePowerofficeConfiguration(updatedConfiguration); var deletedConfiguration = ConfigService.LoadPowerofficeConfiguration(systemId); deletedConfiguration.Should().BeNull(); }
public static bool UpdateAndPublishMultiple(CrmServiceClient client, List <Entity> webResources) { //CRM 2011 UR12+ try { ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; emRequest.Requests = CreateUpdateRequests(webResources); string publishXml = CreatePublishXml(webResources); emRequest.Requests.Add(CreatePublishRequest(publishXml)); bool wasError = false; ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)client.Execute(emRequest); foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) { continue; } OutputLogger.WriteToOutputWindow( "Error Updating And Publishing Web Resource(s) To CRM: " + responseItem.Fault.Message + Environment.NewLine + responseItem.Fault.TraceText, MessageType.Error); wasError = true; } if (wasError) { return(false); } OutputLogger.WriteToOutputWindow("Updated And Published Web Resource(s)", MessageType.Info); return(true); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow("Error Updating And Publishing Web Resource(s) To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(false); } catch (Exception ex) { OutputLogger.WriteToOutputWindow("Error Updating And Publishing Web Resource(s) To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(false); } }
public static void LogProcessError(Logger logger, string message, string errorDataReceived) { string output = FormatProcessErrorOutput(message, errorDataReceived); ExtensionLogger.LogToFile(logger, output, LogLevel.Error); OutputLogger.WriteToOutputWindow(output, MessageType.Error); }
public static void LogException(Logger logger, string message, Exception ex) { string output = FormatExceptionOutput(message, ex); ExtensionLogger.LogToFile(logger, output, LogLevel.Error); OutputLogger.WriteToOutputWindow(output, MessageType.Error); }
public static void LogCrmConnectionError(Logger logger, string message, CrmConnectionManager crmConnectionManager) { string output = FormatCrmConnectionErrorOutput(crmConnectionManager); ExtensionLogger.LogToFile(logger, output, LogLevel.Error); OutputLogger.WriteToOutputWindow(output, MessageType.Error); }
public void WriteLine(string format, params object[] args) { if (format == null) { return; } OutputLogger.WriteToOutputWindow(string.Format(format, args), MessageType.Info); }
public static List <Guid> DeletePluginTracesFromCrm(CrmServiceClient client, Guid[] pluginTraceLogIds) { List <Guid> deletedPluginTraceLogIds = new List <Guid>(); try { ExecuteMultipleRequest executeMultipleRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = true, ReturnResponses = true } }; foreach (Guid pluginTraceLogId in pluginTraceLogIds) { DeleteRequest request = new DeleteRequest { Target = new EntityReference("plugintracelog", pluginTraceLogId) }; executeMultipleRequest.Requests.Add(request); } ExecuteMultipleResponse executeMultipleResponse = (ExecuteMultipleResponse)client.Execute(executeMultipleRequest); foreach (var responseItem in executeMultipleResponse.Responses) { if (responseItem.Response != null) { deletedPluginTraceLogIds.Add(pluginTraceLogIds[responseItem.RequestIndex]); continue; } if (responseItem.Fault != null) { OutputLogger.WriteToOutputWindow( "Error Deleting Plug-in Trace Log From CRM: " + responseItem.Fault, MessageType.Error); } } } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow( "Error Deleting Plug-in Trace Log(s) From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); } catch (Exception ex) { OutputLogger.WriteToOutputWindow( "Error Deleting Plug-in Trace Log(s) From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); } return(deletedPluginTraceLogIds); }
/// <summary> /// 全Loggerの次のイベントの処理が完了するまで同期的に待機する. /// </summary> public void WaitEvents() { var outputTask = _taskFactory.StartNew(() => { OutputLogger.WaitEvent(); }); var inputTask = _taskFactory.StartNew(() => { InputLogger.WaitEvent(); }); var errorOutputTask = _taskFactory.StartNew(() => { ErrorOutputLogger.WaitEvent(); }); outputTask.Wait(); inputTask.Wait(); errorOutputTask.Wait(); }
public void ParamsSupportPropertyWithPublicSetter() { var logger = new OutputLogger(Output); var config = CreateSimpleConfig(logger); CanExecute<ParamsTestProperty>(config); foreach (var param in new[] { 1, 2 }) Assert.Contains($"// ### New Parameter {param} ###" + Environment.NewLine, logger.GetLog()); Assert.DoesNotContain($"// ### New Parameter {default(int)} ###" + Environment.NewLine, logger.GetLog()); }
public static bool UpdateAndPublishMultiple(CrmServiceClient client, List <Entity> webResources) { //CRM 2011 UR12+ try { var emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; emRequest.Requests = CreateUpdateRequests(webResources); var publishXml = CreatePublishXml(webResources); emRequest.Requests.Add(CreatePublishRequest(publishXml)); var wasError = false; var emResponse = (ExecuteMultipleResponse)client.Execute(emRequest); foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) { continue; } ExLogger.LogToFile(Logger, Resource.ErrorMessage_ErrorUpdatingPublishingWebResources, LogLevel.Info); OutputLogger.WriteToOutputWindow(Resource.ErrorMessage_ErrorUpdatingPublishingWebResources, MessageType.Error); wasError = true; } if (wasError) { return(false); } ExLogger.LogToFile(Logger, Resource.Message_UpdatedPublishedWebResources, LogLevel.Info); OutputLogger.WriteToOutputWindow(Resource.Message_UpdatedPublishedWebResources, MessageType.Info); return(true); } catch (Exception ex) { ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorUpdatingPublishingWebResources, ex); return(false); } }
public static void Main() { var logger = new OutputLogger(); var warningLogger = new WarningLogger(logger); var errorLogger = new ErrorLogger(new UpperCaseLoggerDecorator(logger)); const string message = "decorator works!"; logger.Log(message); warningLogger.Log(message); errorLogger.Log(message); }
public static EntityCollection RetrieveSolutionsFromCrm(CrmServiceClient client) { try { QueryExpression query = new QueryExpression { EntityName = "solution", ColumnSet = new ColumnSet("friendlyname", "solutionid", "uniquename"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "isvisible", Operator = ConditionOperator.Equal, Values = { true } }, new ConditionExpression { AttributeName = "ismanaged", Operator = ConditionOperator.Equal, Values = { false } } } }, Orders = { new OrderExpression { AttributeName = "friendlyname", OrderType = OrderType.Ascending } } }; EntityCollection solutions = client.RetrieveMultiple(query); return(solutions); } catch (FaultException <OrganizationServiceFault> crmEx) { OutputLogger.WriteToOutputWindow( "Error Retrieving Solutions From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error); return(null); } catch (Exception ex) { OutputLogger.WriteToOutputWindow( "Error Retrieving Solutions From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error); return(null); } }
public void CleanupMethodRunsTest() { var logger = new OutputLogger(Output); var config = CreateSimpleConfig(logger); CanExecute<CleanupAttributeBenchmarks>(config); string log = logger.GetLog(); Assert.Contains(CleanupCalled + System.Environment.NewLine, log); Assert.True( log.IndexOf(CleanupCalled + System.Environment.NewLine) > log.IndexOf(BenchmarkCalled + System.Environment.NewLine)); }
public void CustomToolchainsAreSupported() { var logger = new OutputLogger(Output); var generator = new MyGenerator(); var builder = new MyBuilder(); var executor = new MyExecutor(); var myToolchain = new Toolchain("My", generator, builder, executor); var job = new Job(Job.Dry) { Infrastructure = { Toolchain = myToolchain} }; var config = CreateSimpleConfig(logger).With(job); CanExecute<ToolchainBenchmark>(config, fullValidation: false); Assert.True(generator.Done); Assert.True(builder.Done); Assert.True(executor.Done); }
public void ExtraColumnsCanBeDefined() { var logger = new OutputLogger(Output); var columns = new[] { StatisticColumn.StdDev, StatisticColumn.Min, StatisticColumn.Q1, StatisticColumn.Median, StatisticColumn.Q3, StatisticColumn.Max, StatisticColumn.OperationsPerSecond, StatisticColumn.P85, StatisticColumn.P95, StatisticColumn.P95 }; var config = DefaultConfig.Instance.With(CreateJob()).With(logger).With(columns); var summary = CanExecute<Target>(config); var table = summary.Table; var headerRow = table.FullHeader; foreach (var column in columns) Assert.True(headerRow.Contains(column.ColumnName)); }
public void RunStrategiesAreSupported() { var logger = new OutputLogger(Output); var config = ManualConfig.CreateEmpty() .With(DefaultColumnProviders.Instance) .With(logger) .With(new Job(Job.Dry) { Run = { RunStrategy = RunStrategy.ColdStart} }) .With(new Job(Job.Dry) { Run = { RunStrategy = RunStrategy.Throughput } }); var results = CanExecute<ModeBenchmarks>(config); Assert.Equal(4, results.Benchmarks.Count()); Assert.Equal(1, results.Benchmarks.Count(b => b.Job.Run.RunStrategy == RunStrategy.ColdStart && b.Target.Method.Name == "BenchmarkWithVoid")); Assert.Equal(1, results.Benchmarks.Count(b => b.Job.Run.RunStrategy == RunStrategy.ColdStart && b.Target.Method.Name == "BenchmarkWithReturnValue")); Assert.Equal(1, results.Benchmarks.Count(b => b.Job.Run.RunStrategy == RunStrategy.Throughput && b.Target.Method.Name == "BenchmarkWithVoid")); Assert.Equal(1, results.Benchmarks.Count(b => b.Job.Run.RunStrategy == RunStrategy.Throughput && b.Target.Method.Name == "BenchmarkWithReturnValue")); string testLog = logger.GetLog(); Assert.Contains("// ### Benchmark with void called ###", testLog); Assert.Contains("// ### Benchmark with return value called ###", testLog); Assert.DoesNotContain("No benchmarks found", logger.GetLog()); }
/// <summary> /// 指定されたロガーに蓄積されたログを表示します。 /// </summary> /// <param name="logger">ロガーオブジェクト。</param> private static void ShowLogs(OutputLogger logger) { foreach (var output in logger.Outputs) { if (output.Category == OutputCategory.Error && options.SuppressError || output.Category == OutputCategory.Warn && options.SuppressWarning || output.Category == OutputCategory.Info && options.SuppressInfo) continue; if (output.Category == OutputCategory.Error && options.EnableColor) Console.ForegroundColor = ConsoleColor.Red; if (output.Category == OutputCategory.Warn && options.EnableColor) Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("{0}{1}: {2}", GetCategoryName(output.Category), output.Position, output.Message); Console.ResetColor(); if (output.SourceCode != null && options.EnableCodePointing) { int length = output.Code == null ? 0 : output.Code.Length; var strs = output.SourceCode.GeneratePointingStrings(output.Position, length); if (output.Position.Line > 1) Console.WriteLine("| " + output.SourceCode.GetLine(output.Position.Line - 1)); foreach (var s in strs) Console.WriteLine("| " + s); } } }