private async Task <EntityMetadata> GetEntityMetadata(string entityName) { if (_cacheEntityMetadata.ContainsKey(entityName)) { return(_cacheEntityMetadata[entityName]); } if (_cacheEntityNotExists.Contains(entityName)) { return(null); } var repositoryEntityMetadata = new EntityMetadataRepository(_service); ToggleControls(false, Properties.OutputStrings.GettingEntityMetadataFormat1, entityName); var entityMetadata = await repositoryEntityMetadata.GetEntityMetadataAsync(entityName); ToggleControls(true, Properties.OutputStrings.GettingEntityMetadataCompletedFormat1, entityName); if (entityMetadata != null) { _cacheEntityMetadata[entityName] = entityMetadata; } else { this._iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.EntityNotExistsInConnectionFormat2, entityName, _service.ConnectionData.Name); _cacheEntityNotExists.Add(entityName); } return(entityMetadata); }
private void WriteContent(string entityLogicalName, List <FormTab> tabs) { var repository = new EntityMetadataRepository(_service); this._entityMetadata = repository.GetEntityMetadata(entityLogicalName); WriteNamespace(); WriteLine(); string tempNamespace = !string.IsNullOrEmpty(this._service.ConnectionData.NamespaceClassesJavaScript) ? this._service.ConnectionData.NamespaceClassesJavaScript + "." : string.Empty; string objectName = string.Format("{0}{1}_form_main", tempNamespace, _entityMetadata.LogicalName); string objectDeclaration = !string.IsNullOrEmpty(tempNamespace) ? objectName : "var " + objectName; string constructorName = GetConstructorName(objectName); WriteObjectStart(objectDeclaration, constructorName); WriteTabs(tabs); WriteSubgrids(tabs); WriteWebResources(tabs); WriteQuickViewForms(tabs); WriteConstantsAndFunctions(objectName); WriteObjectEnd(objectDeclaration, constructorName); }
private static async Task GetEntityMetadataInformationAsync(IOrganizationServiceExtented service , string entityLogicalName , ConcurrentDictionary <string, IEnumerable <OneToManyRelationshipMetadataViewItem> > connectionEntityOneToMany , ConcurrentDictionary <string, IEnumerable <OneToManyRelationshipMetadataViewItem> > connectionEntityManyToOne , ConcurrentDictionary <string, Task> cacheMetadataTask ) { var repository = new EntityMetadataRepository(service); var metadata = await repository.GetEntityMetadataAttributesAsync(entityLogicalName, EntityFilters.Relationships); if (metadata != null) { if (metadata.OneToManyRelationships != null && !connectionEntityOneToMany.ContainsKey(entityLogicalName)) { connectionEntityOneToMany.TryAdd(entityLogicalName, metadata.OneToManyRelationships.Select(e => new OneToManyRelationshipMetadataViewItem(e)).ToList()); } if (metadata.ManyToOneRelationships != null && !connectionEntityManyToOne.ContainsKey(entityLogicalName)) { connectionEntityManyToOne.TryAdd(entityLogicalName, metadata.ManyToOneRelationships.Select(e => new OneToManyRelationshipMetadataViewItem(e)).ToList()); } } if (cacheMetadataTask.ContainsKey(entityLogicalName)) { cacheMetadataTask.TryRemove(entityLogicalName, out _); } }
private void WriteContent(string entityLogicalName, string objectName, string constructorName, FormInformation formInfo) { var repository = new EntityMetadataRepository(_service); this._entityMetadata = repository.GetEntityMetadata(entityLogicalName); WriteContentInternal(entityLogicalName, objectName, constructorName, formInfo); }
private async Task ShowExistingEntities() { if (!this.IsControlsEnabled) { return; } var service = await GetService(); ToggleControls(service.ConnectionData, false, Properties.WindowStatusStrings.LoadingEntities); _itemsSourceEntityList.Clear(); _itemsSourceEntityKeyList.Clear(); IEnumerable <EntityMetadataViewItem> list = Enumerable.Empty <EntityMetadataViewItem>(); try { if (service != null) { if (!_cacheEntityMetadata.ContainsKey(service.ConnectionData.ConnectionId)) { EntityMetadataRepository repository = new EntityMetadataRepository(service); var temp = await repository.GetEntitiesForEntityAttributeExplorerAsync(EntityFilters.Entity); _cacheEntityMetadata.Add(service.ConnectionData.ConnectionId, temp); } list = _cacheEntityMetadata[service.ConnectionData.ConnectionId].Select(e => new EntityMetadataViewItem(e)).ToList(); } } catch (Exception ex) { this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex); } string textName = string.Empty; txtBFilterEnitity.Dispatcher.Invoke(() => { textName = txtBFilterEnitity.Text.Trim().ToLower(); }); list = FilterEntityList(list, textName); LoadEntities(list); ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.LoadingEntitiesCompletedFormat1, list.Count()); ShowExistingEntityKeys(); }
protected async Task <IEnumerable <EntityMetadata> > GetEntityMetadataEnumerable(IOrganizationServiceExtented service) { if (!_cacheEntityMetadata.ContainsKey(service.ConnectionData.ConnectionId)) { var repository = new EntityMetadataRepository(service); var temp = await repository.GetEntitiesDisplayNameWithPrivilegesAsync(); _cacheEntityMetadata.Add(service.ConnectionData.ConnectionId, temp); } return(_cacheEntityMetadata[service.ConnectionData.ConnectionId]); }
protected async Task <IEnumerable <EntityMetadata> > GetEntityMetadataEnumerable(IOrganizationServiceExtented service) { if (!_cacheEntityMetadata.ContainsKey(service.ConnectionData.ConnectionId)) { var repository = new EntityMetadataRepository(service); var temp = await repository.GetEntitiesForEntityAttributeExplorerAsync(EntityFilters.Entity); _cacheEntityMetadata.Add(service.ConnectionData.ConnectionId, temp); } return(_cacheEntityMetadata[service.ConnectionData.ConnectionId]); }
private async Task CheckingEntitiesOwnership(ConnectionData connectionData, CommonConfiguration commonConfig) { var service = await ConnectAndWriteToOutputAsync(connectionData); if (service == null) { return; } StringBuilder content = new StringBuilder(); content.AppendLine(Properties.OutputStrings.ConnectingToCRM); content.AppendLine(connectionData.GetConnectionDescription()); content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine(); EntityMetadataRepository repositoryEntity = new EntityMetadataRepository(service); var allEntities = await repositoryEntity.GetEntitiesDisplayNameAsync(); var groups = allEntities.GroupBy(ent => ent.OwnershipType).OrderBy(gr => gr.Key); foreach (var gr in groups) { content.AppendLine(); int count = gr.Count(); string name = "Null"; if (gr.Key.HasValue) { name = gr.Key.Value.ToString(); } content.AppendFormat(Properties.OutputStrings.EntitiesWithOwnershipFormat2, name, count).AppendLine(); gr.OrderBy(ent => ent.LogicalName).ToList().ForEach(ent => content.AppendLine(_tabSpacer + ent.LogicalName)); } commonConfig.CheckFolderForExportExists(this._iWriteToOutput); string fileName = string.Format("{0}.Entities with Ownership at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss")); string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatedFileWithEntitiesOwnershipFormat1, filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); }
private async Task LoadEntityMetadataAsync(IEnumerable <string> entityNames) { if (!entityNames.Any()) { return; } var repository = new EntityMetadataRepository(_service); var entities = await repository.GetEntitiesWithAttributesFullAsync(entityNames); foreach (var entityMetadata in entities) { _entityMetadataCache[entityMetadata.LogicalName] = entityMetadata; } }
private async Task RetrieveEntityInformation() { try { ToggleControls(false, Properties.OutputStrings.GettingEntityMetadataFormat1, _entityName); var repositoryEntityMetadata = new EntityMetadataRepository(_service); this._entityMetadata = await repositoryEntityMetadata.GetEntityMetadataAsync(_entityName); ToggleControls(true, Properties.OutputStrings.GettingEntityMetadataCompletedFormat1, _entityName); FilterEntityAttributes(null); } catch (Exception ex) { _iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex); } }
private static async Task GetEntityMetadataInformationAsync(IOrganizationServiceExtented service, string entityLogicalName, ConcurrentDictionary <string, IEnumerable <EntityKeyMetadataViewItem> > cacheEntityKey, ConcurrentDictionary <string, Task> cacheMetadataTask) { var repository = new EntityMetadataRepository(service); var metadata = await repository.GetEntityMetadataAttributesAsync(entityLogicalName, EntityFilters.All); if (metadata != null && metadata.Keys != null) { if (!cacheEntityKey.ContainsKey(entityLogicalName)) { cacheEntityKey.TryAdd(entityLogicalName, metadata.Keys.Select(e => new EntityKeyMetadataViewItem(e)).ToList()); } } if (cacheMetadataTask.ContainsKey(entityLogicalName)) { cacheMetadataTask.TryRemove(entityLogicalName, out _); } }
private async void btnSelectAttributes_Click(object sender, RoutedEventArgs e) { if (!_entityName.IsValidEntityName()) { return; } if (_entityMetadata == null) { ToggleControls(false, Properties.OutputStrings.GettingEntityMetadataFormat1, this._entityName); var repository = new EntityMetadataRepository(_service); _entityMetadata = await repository.GetEntityMetadataAsync(_entityName); ToggleControls(true, Properties.OutputStrings.GettingEntityMetadataCompletedFormat1, this._entityName); } if (_entityMetadata == null) { return; } ToggleControls(false, Properties.OutputStrings.UpdatingImageAttributesFormat1, this._entityName); var form = new WindowAttributeMultiSelect(_iWriteToOutput , _service , _entityMetadata.MetadataId.Value , _entityMetadata.Attributes , txtBAttributes.Text.Trim() ); if (form.ShowDialog().GetValueOrDefault()) { txtBAttributes.Text = form.GetAttributes(); txtBAttributes.ToolTip = GetImageTooltip(txtBAttributes.Text); } ToggleControls(true, Properties.OutputStrings.UpdatingImageAttributesCompletedFormat1, this._entityName); }
public void Should_Get_Metadata() { // arrange var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"]; var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString }, new CrmClientCredentialsProvider()); var sut = new EntityMetadataRepository(serviceProvider); // act var contactMetadata = sut.GetEntityMetadata("contact"); // assert Assert.That(contactMetadata, Is.Not.Null); Assert.That(contactMetadata, Is.Not.Null); Assert.That(contactMetadata.Attributes, Is.Not.Null); Assert.That(contactMetadata.Attributes.FirstOrDefault(a => a.LogicalName == "firstname"), Is.Not.Null); Assert.That(contactMetadata.Attributes.FirstOrDefault(a => a.LogicalName == "lastname"), Is.Not.Null); }
private async void btnSelectAttributes_Click(object sender, RoutedEventArgs e) { string entityName = cmBPrimaryEntity.SelectedItem?.ToString(); if (!entityName.IsValidEntityName()) { return; } ToggleControls(false, Properties.OutputStrings.GettingEntityMetadataFormat1, entityName); var repository = new EntityMetadataRepository(_service); var entityMetadata = await repository.GetEntityMetadataAsync(entityName); ToggleControls(true, Properties.OutputStrings.GettingEntityMetadataCompletedFormat1, entityName); if (entityMetadata == null) { return; } ToggleControls(false, Properties.OutputStrings.UpdatingStepFilteringAttributesFormat1, entityName); var form = new WindowAttributeMultiSelect(_iWriteToOutput , _service , entityMetadata.MetadataId.Value , entityMetadata.Attributes , txtBFilteringBAttributes.Text.Trim() ); if (form.ShowDialog().GetValueOrDefault()) { txtBFilteringBAttributes.Text = form.GetAttributes(); } ToggleControls(true, Properties.OutputStrings.UpdatingStepFilteringAttributesCompletedFormat1, entityName); }
public MetadataProviderService(EntityMetadataRepository repository) { this._repository = repository; }
private async Task RetrieveEntityInformation() { try { ToggleControls(false, Properties.WindowStatusStrings.GettingEntityMetadataFormat1, _entityName); var repositoryEntityMetadata = new EntityMetadataRepository(_service); this._entityMetadata = await repositoryEntityMetadata.GetEntityMetadataWithAttributesAsync(_entityName); ToggleControls(true, Properties.WindowStatusStrings.GettingEntityMetadataCompletedFormat1, _entityName); if (this._entityMetadata != null && this._entityMetadata.Attributes != null ) { var stateCodeAttributeMetadata = this._entityMetadata.Attributes.OfType <StateAttributeMetadata>().FirstOrDefault(); var statusCodeAttributeMetadata = this._entityMetadata.Attributes.OfType <StatusAttributeMetadata>().FirstOrDefault(); if (stateCodeAttributeMetadata != null && stateCodeAttributeMetadata.OptionSet != null && stateCodeAttributeMetadata.OptionSet.Options != null && statusCodeAttributeMetadata != null && statusCodeAttributeMetadata.OptionSet != null && statusCodeAttributeMetadata.OptionSet.Options != null ) { foreach (var statusCodeOption in statusCodeAttributeMetadata .OptionSet .Options .OfType <StatusOptionMetadata>() .OrderBy(o => o.State) .ThenBy(o => o.Value) ) { var stateCodeOption = stateCodeAttributeMetadata.OptionSet.Options.OfType <StateOptionMetadata>().FirstOrDefault(o => o.Value == statusCodeOption.State); if (stateCodeOption != null) { string stateName = CreateFileHandler.GetLocalizedLabel(stateCodeOption.Label); string statusName = CreateFileHandler.GetLocalizedLabel(statusCodeOption.Label); _sourceStatusCodes.Add(new StatusCodeViewItem( stateCodeOption.Value.Value , stateName , statusCodeOption.Value.Value , statusName , stateCodeOption.Label , statusCodeOption.Label , statusCodeOption )); } } } } FilterStatusCodes(); } catch (Exception ex) { _iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex); } }
private async Task <string> TrasnferAudit() { StringBuilder content = new StringBuilder(); await _comparerSource.InitializeConnection(_iWriteToOutput, content, "Connection CRM Source.", "Connection CRM Target."); string operation = string.Format(Properties.OperationNames.TransferingAuditFormat2, ConnectionSource.Name, ConnectionTarget.Name); content.AppendLine(_iWriteToOutput.WriteToOutputStartOperation(null, operation)); var repositorySource = new EntityMetadataRepository(_comparerSource.Service1); var repositoryTarget = new EntityMetadataRepository(_comparerSource.Service2); var taskSource = repositorySource.GetEntitiesWithAttributesForAuditAsync(); var taskTarget = repositoryTarget.GetEntitiesWithAttributesForAuditAsync(); var listEntityMetadataSource = await taskSource; content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Entities in {0}: {1}", ConnectionSource.Name, listEntityMetadataSource.Count())); var listEntityMetadataTarget = await taskTarget; content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Entities in {0}: {1}", ConnectionTarget.Name, listEntityMetadataTarget.Count())); var commonEntityMetadata = new List <LinkedEntities <EntityMetadata> >(); foreach (var entityMetadata1 in listEntityMetadataSource.OrderBy(e => e.LogicalName)) { { var entityMetadata2 = listEntityMetadataTarget.FirstOrDefault(e => string.Equals(e.LogicalName, entityMetadata1.LogicalName, StringComparison.InvariantCultureIgnoreCase)); if (entityMetadata2 != null) { commonEntityMetadata.Add(new LinkedEntities <EntityMetadata>(entityMetadata1, entityMetadata2)); continue; } } } HashSet <string> entitiesToPublish = new HashSet <string>(); var entitiesToEnableAudit = commonEntityMetadata.Where( e => e.Entity1.IsAuditEnabled != null && e.Entity1.IsAuditEnabled.Value && e.Entity2.IsAuditEnabled != null && e.Entity2.IsAuditEnabled.CanBeChanged && e.Entity2.IsAuditEnabled.Value == false ).ToList(); if (entitiesToEnableAudit.Any()) { content .AppendLine() .AppendFormat("Enabling Audit on Entities: {0}", entitiesToEnableAudit.Count) .AppendLine(); foreach (var entityLink in entitiesToEnableAudit.OrderBy(e => e.Entity1.LogicalName)) { content.AppendLine(_tabSpacer + entityLink.Entity1.LogicalName); entitiesToPublish.Add(entityLink.Entity1.LogicalName); try { entityLink.Entity2.IsAuditEnabled.Value = true; await repositoryTarget.UpdateEntityMetadataAsync(entityLink.Entity2); } catch (Exception ex) { var desc = DTEHelper.GetExceptionDescription(ex); content.AppendLine(desc); } } } bool first = true; foreach (var entityLink in commonEntityMetadata.OrderBy(e => e.Entity1.LogicalName)) { var query = from source in entityLink.Entity1.Attributes join target in entityLink.Entity2.Attributes on source.LogicalName equals target.LogicalName where source.IsAuditEnabled != null && string.IsNullOrEmpty(source.AttributeOf) && string.IsNullOrEmpty(target.AttributeOf) && source.IsAuditEnabled.Value && target.IsAuditEnabled != null && target.IsAuditEnabled.CanBeChanged && target.IsAuditEnabled.Value == false orderby target.LogicalName select target; foreach (var attribute in query) { if (first) { content .AppendLine() .AppendLine("Enabling Audit on Attributes:") .AppendLine(); first = false; } content .AppendFormat(_tabSpacer + "{0}.{1}", attribute.EntityLogicalName, attribute.LogicalName) .AppendLine(); entitiesToPublish.Add(attribute.EntityLogicalName); try { attribute.IsAuditEnabled.Value = true; await repositoryTarget.UpdateAttributeMetadataAsync(attribute); } catch (Exception ex) { var desc = DTEHelper.GetExceptionDescription(ex); content.AppendLine(desc); } } } if (entitiesToPublish.Any()) { content .AppendLine() .AppendFormat("Publish Entities: {0}", entitiesToPublish.Count) .AppendLine(); foreach (var item in entitiesToPublish.OrderBy(s => s)) { content.AppendLine(_tabSpacer + item); } var repositoryPublish = new PublishActionsRepository(_comparerSource.Service2); try { await repositoryPublish.PublishEntitiesAsync(entitiesToPublish); } catch (Exception ex) { var desc = DTEHelper.GetExceptionDescription(ex); content.AppendLine(desc); } } content.AppendLine().AppendLine().AppendLine(_iWriteToOutput.WriteToOutputEndOperation(null, operation)); string fileName = string.Format("OrgTransfer Audit from {0} to {1} at {2}.txt" , this.ConnectionSource.Name , this.ConnectionTarget.Name , DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss")); string filePath = Path.Combine(_folder, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); return(filePath); }
private static async Task LoadOrganizationDataAsync(OrganizationServiceExtentedProxy service, OrganizationDetail organizationDetail, WhoAmIResponse whoAmIResponse = null) { try { Guid?idOrganization = null; if (organizationDetail != null) { idOrganization = organizationDetail.OrganizationId; service.ConnectionData.OrganizationInformationExpirationDate = DateTime.Now.AddHours(_hoursOrganizationInformation); service.ConnectionData.FriendlyName = organizationDetail.FriendlyName; service.ConnectionData.OrganizationId = organizationDetail.OrganizationId; service.ConnectionData.OrganizationVersion = organizationDetail.OrganizationVersion; service.ConnectionData.OrganizationState = organizationDetail.State.ToString(); service.ConnectionData.UniqueOrgName = organizationDetail.UniqueName; service.ConnectionData.UrlName = organizationDetail.UrlName; if (organizationDetail.Endpoints.ContainsKey(EndpointType.OrganizationService)) { var organizationUrlEndpoint = organizationDetail.Endpoints[EndpointType.OrganizationService]; if (string.IsNullOrEmpty(service.ConnectionData.OrganizationUrl) && !string.IsNullOrEmpty(organizationUrlEndpoint) ) { service.ConnectionData.OrganizationUrl = organizationUrlEndpoint; } } if (organizationDetail.Endpoints.ContainsKey(EndpointType.WebApplication)) { var publicUrl = organizationDetail.Endpoints[EndpointType.WebApplication]; if (string.IsNullOrEmpty(service.ConnectionData.PublicUrl) && !string.IsNullOrEmpty(publicUrl) ) { service.ConnectionData.PublicUrl = publicUrl; } } } if (!idOrganization.HasValue) { if (whoAmIResponse == null) { whoAmIResponse = await service.ExecuteAsync <WhoAmIResponse>(new WhoAmIRequest()); } idOrganization = whoAmIResponse.OrganizationId; } service.ConnectionData.DefaultLanguage = string.Empty; service.ConnectionData.BaseCurrency = string.Empty; service.ConnectionData.DefaultLanguage = string.Empty; service.ConnectionData.InstalledLanguagePacks = string.Empty; if (idOrganization.HasValue) { var organization = await service .RetrieveAsync <Organization>(Organization.EntityLogicalName, idOrganization.Value, new ColumnSet(Organization.Schema.Attributes.languagecode, Organization.Schema.Attributes.basecurrencyid)) ; if (organization.BaseCurrencyId != null) { service.ConnectionData.BaseCurrency = organization.BaseCurrencyId.Name; } var request = new RetrieveInstalledLanguagePacksRequest(); var response = await service.ExecuteAsync <RetrieveInstalledLanguagePacksResponse>(request); var rep = new EntityMetadataRepository(service); var isEntityExists = rep.IsEntityExists(LanguageLocale.EntityLogicalName); if (isEntityExists) { var repository = new LanguageLocaleRepository(service); if (organization.LanguageCode.HasValue) { var lang = (await repository.GetListAsync(organization.LanguageCode.Value)).FirstOrDefault(); if (lang != null) { service.ConnectionData.DefaultLanguage = lang.ToString(); } else { service.ConnectionData.DefaultLanguage = LanguageLocale.GetLocaleName(organization.LanguageCode.Value); } } if (response.RetrieveInstalledLanguagePacks != null && response.RetrieveInstalledLanguagePacks.Any()) { var list = await repository.GetListAsync(response.RetrieveInstalledLanguagePacks); service.ConnectionData.InstalledLanguagePacks = string.Join(",", list.OrderBy(s => s.LocaleId.Value, LocaleComparer.Comparer).Select(l => l.ToString())); } } else { if (organization.LanguageCode.HasValue) { service.ConnectionData.DefaultLanguage = LanguageLocale.GetLocaleName(organization.LanguageCode.Value); } if (response.RetrieveInstalledLanguagePacks != null && response.RetrieveInstalledLanguagePacks.Any()) { service.ConnectionData.InstalledLanguagePacks = string.Join(",", response.RetrieveInstalledLanguagePacks.OrderBy(s => s, LocaleComparer.Comparer).Select(l => LanguageLocale.GetLocaleName(l))); } } } if (string.IsNullOrEmpty(service.ConnectionData.PublicUrl) && !string.IsNullOrEmpty(service.ConnectionData.OrganizationUrl) ) { var orgUrl = service.ConnectionData.OrganizationUrl.TrimEnd('/'); if (orgUrl.EndsWith("/XRMServices/2011/Organization.svc", StringComparison.InvariantCultureIgnoreCase)) { var lastIndex = orgUrl.LastIndexOf("/XRMServices/2011/Organization.svc", StringComparison.InvariantCultureIgnoreCase); var publicUrl = orgUrl.Substring(0, lastIndex + 1).TrimEnd('/'); service.ConnectionData.PublicUrl = publicUrl; } } } catch (Exception ex) { DTEHelper.WriteExceptionToOutput(service.ConnectionData, ex); } }
private async Task RetrieveEntityInformation() { try { ToggleControls(false, Properties.WindowStatusStrings.GettingEntityMetadataFormat1, _entityName); var repositoryEntityMetadata = new EntityMetadataRepository(_service); this._entityMetadata = await repositoryEntityMetadata.GetEntityMetadataWithAttributesAsync(_entityName); ToggleControls(true, Properties.WindowStatusStrings.GettingEntityMetadataCompletedFormat1, _entityName); if (this._entityMetadata != null) { if (_entityId != Guid.Empty) { ToggleControls(false, Properties.WindowStatusStrings.GettingEntityFormat1, _entityId); var repositoryGeneric = new GenericRepository(_service, this._entityMetadata); this._entityInstance = await repositoryGeneric.GetEntityByIdAsync(_entityId, new ColumnSet(true)); ToggleControls(true, Properties.WindowStatusStrings.GettingEntityCompletedFormat1, _entityId); if (this._entityInstance != null) { base.SwitchEntityDatesToLocalTime(new[] { this._entityInstance }); SetWindowTitle(string.Format("Edit Entity {0} - {1}", _entityName, _entityId)); this.Dispatcher.Invoke(() => { btnSaveAsCopyEntity.IsEnabled = true; btnSaveAsCopyEntity.Visibility = Visibility.Visible; }); this._attributeChecker = a => a.IsValidForUpdate.GetValueOrDefault() && !_ignoredAttributes.Contains(a.LogicalName); foreach (var attributeValue in this._entityInstance.Attributes.OrderBy(a => a.Key)) { var attributeMetadata = this._entityMetadata.Attributes.FirstOrDefault(a => string.Equals(a.LogicalName, attributeValue.Key, StringComparison.InvariantCultureIgnoreCase)); if (attributeMetadata != null && string.IsNullOrEmpty(attributeMetadata.AttributeOf) && _attributeChecker(attributeMetadata) ) { UserControl control = null; this.Dispatcher.Invoke(() => { control = _controlFactory.CreateControlForAttribute(_service, false, this._entityMetadata, attributeMetadata, _entityInstance, attributeValue.Value); }); if (control != null) { _listAttributeControls.Add(control); } } } } else { SetWindowTitle(string.Format("Create Entity {0} - {1}", _entityName, _entityId)); } } else { SetWindowTitle(string.Format("Create Entity {0}", _entityName)); } } FilterEntityAttributes(null); } catch (Exception ex) { _iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex); } }
private async Task CheckingPluginStepsRequiredComponents(ConnectionData connectionData, CommonConfiguration commonConfig) { if (connectionData == null) { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection); return; } StringBuilder content = new StringBuilder(); content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM)); content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription())); // Подключаемся к CRM. var service = await QuickConnection.ConnectAsync(connectionData); if (service == null) { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name); return; } content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint)); var repository = new PluginSearchRepository(service); var search = await repository.FindAllAsync(new List<PluginStage>(), string.Empty, string.Empty, string.Empty); var querySteps = search.SdkMessageProcessingStep .OrderBy(ent => ent.EventHandler.Name) .ThenBy(ent => ent.PrimaryObjectTypeCodeName) .ThenBy(ent => ent.SdkMessageId.Name, new MessageComparer()) .ThenBy(ent => ent.Stage.Value) .ThenBy(ent => ent.Mode.Value) .ThenBy(ent => ent.Rank) .ThenBy(ent => ent.Name) ; EntityMetadataRepository repositoryMetadata = new EntityMetadataRepository(service); DependencyRepository dependencyRepository = new DependencyRepository(service); var listMetaData = await repositoryMetadata.GetEntitiesWithAttributesAsync(); var dictEntity = new Dictionary<Guid, EntityMetadata>(); var dictAttribute = new Dictionary<Guid, AttributeMetadata>(); bool hasInfo = false; foreach (var metaEntity in listMetaData) { dictEntity.Add(metaEntity.MetadataId.Value, metaEntity); foreach (var metaAttribute in metaEntity.Attributes) { dictAttribute.Add(metaAttribute.MetadataId.Value, metaAttribute); } } foreach (var step in querySteps) { var listRequired = await dependencyRepository.GetRequiredComponentsAsync((int)ComponentType.SdkMessageProcessingStep, step.Id); var stepEntities = GetSetEntites(step); var stepAttributes = GetSetStepAttributes(step); var componentsEntities = GetSetComponentsEntites(listRequired, dictEntity); var componentsAttributes = GetSetComponentsAttributes(listRequired, dictAttribute); bool entitiesIsSame = stepEntities.SequenceEqual(componentsEntities); bool attributesIsSame = stepAttributes.SequenceEqual(componentsAttributes); if (!entitiesIsSame || !attributesIsSame) { if (content.Length > 0) { content.AppendLine().AppendLine().AppendLine(); } content.AppendFormat("{0} Primary {1} Secondary {2} Message {3} Stage {4} Rank {5} Status {6} FilteringAttributes {7}", step.EventHandler?.Name ?? "Unknown" , step.PrimaryObjectTypeCodeName , step.SecondaryObjectTypeCodeName , step.SdkMessageId?.Name ?? "Unknown" , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value) , step.Rank.ToString() , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode] , step.FilteringAttributesStringsSorted ).AppendLine(); if (!entitiesIsSame) { hasInfo = true; content.AppendLine("Conflict in entites."); content.Append("Entities in plugin step description"); if (stepEntities.Count > 0) { content.AppendLine(":"); foreach (var item in stepEntities) { content.AppendFormat(" {0}", item).AppendLine(); } } else { content.AppendLine(" are empty."); } content.Append("Entities in required components"); if (componentsEntities.Count > 0) { content.AppendLine(":"); foreach (var item in componentsEntities) { content.AppendFormat(" {0}", item).AppendLine(); } } else { content.AppendLine(" are empty."); } } if (!attributesIsSame) { hasInfo = true; content.AppendLine("Conflict in attributes."); content.Append("Attributes in plugin step description"); if (componentsEntities.Count > 0) { content.AppendLine(":"); foreach (var item in stepAttributes) { content.AppendFormat(" {0}", item).AppendLine(); } } else { content.AppendLine(" are empty."); } content.Append("Attributes in required components"); if (componentsAttributes.Count > 0) { content.AppendLine(":"); foreach (var item in componentsAttributes) { content.AppendFormat(" {0}", item).AppendLine(); } } else { content.AppendLine(" are empty."); } } } } if (!hasInfo) { content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No conflicts were found.")); } string fileName = string.Format("{0}.Checking Plugin Steps Required Components at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss")); if (string.IsNullOrEmpty(commonConfig.FolderForExport)) { _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty); commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath(); } else if (!Directory.Exists(commonConfig.FolderForExport)) { _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport); commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath(); } string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Steps Required Components: {0}", filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); }
private async Task RetrieveEntityInformation(Entity entity) { try { ToggleControls(false, Properties.OutputStrings.GettingEntityMetadataFormat1, _entityName); var repositoryEntityMetadata = new EntityMetadataRepository(_service); this._entityMetadata = await repositoryEntityMetadata.GetEntityMetadataWithAttributesAsync(_entityName); ToggleControls(true, Properties.OutputStrings.GettingEntityMetadataCompletedFormat1, _entityName); if (this._entityMetadata != null) { if (_entityId.HasValue && _entityId != Guid.Empty) { ToggleControls(false, Properties.OutputStrings.GettingEntityFormat1, _entityId); var repositoryGeneric = new GenericRepository(_service, this._entityMetadata); entity = await repositoryGeneric.GetEntityByIdAsync(_entityId.Value, ColumnSetInstances.AllColumns); ToggleControls(true, Properties.OutputStrings.GettingEntityCompletedFormat1, _entityId); if (entity != null) { this._editingState = EditingState.Editing; SetWindowTitle(string.Format("Edit Entity {0} - {1}", _entityName, _entityId)); this._attributeChecker = a => a.IsValidForUpdate.GetValueOrDefault() && !_ignoredAttributes.Contains(a.LogicalName); } else { SetWindowTitle(string.Format("Create Entity {0} - {1}", _entityName, _entityId)); } } else { SetWindowTitle(string.Format("Create Entity {0}", _entityName)); } if (entity != null) { var allwaysAddToEntity = this._editingState == EditingState.Creating; base.SwitchEntityDatesToLocalTime(new[] { entity }); foreach (var attributeValue in entity.Attributes.OrderBy(a => a.Key)) { var attributeMetadata = this._entityMetadata.Attributes.FirstOrDefault(a => string.Equals(a.LogicalName, attributeValue.Key, StringComparison.InvariantCultureIgnoreCase)); if (attributeMetadata != null && string.IsNullOrEmpty(attributeMetadata.AttributeOf) && _attributeChecker(attributeMetadata) ) { UserControl control = null; this.Dispatcher.Invoke(() => { control = _controlFactory.CreateControlForAttribute(this._iWriteToOutput, _service, this._entityMetadata, attributeMetadata, entity, attributeValue.Value, allwaysAddToEntity, true); if (control is IAttributeMetadataControl <AttributeMetadata> attributeControl) { attributeControl.RemoveControlClicked += AttributeControl_RemoveControlClicked; } }); if (control != null) { _listAttributeControls.Add(control); } } } } } FilterEntityAttributes(null); } catch (Exception ex) { _iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex); } }
private async Task CheckingPluginImagesRequiredComponents(ConnectionData connectionData, CommonConfiguration commonConfig) { if (connectionData == null) { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection); return; } StringBuilder content = new StringBuilder(); content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM)); content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription())); // Подключаемся к CRM. var service = await QuickConnection.ConnectAsync(connectionData); if (service == null) { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name); return; } content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint)); var repository = new PluginSearchRepository(service); var repositoryImage = new SdkMessageProcessingStepImageRepository(service); var listImages = await repositoryImage.GetAllImagesAsync(); var queryImages = listImages .OrderBy(image => image.Contains("sdkmessageprocessingstep.eventhandler") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.eventhandler").Value as EntityReference).Name : "Null") .ThenBy(image => image.PrimaryObjectTypeCodeName) .ThenBy(image => image.SecondaryObjectTypeCodeName) .ThenBy(image => image.Contains("sdkmessageprocessingstep.sdkmessageid") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.sdkmessageid").Value as EntityReference).Name : "Null", new MessageComparer()) .ThenBy(image => image.Contains("sdkmessageprocessingstep.stage") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.stage").Value as OptionSetValue).Value : 0) .ThenBy(image => image.Contains("sdkmessageprocessingstep.mode") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.mode").Value as OptionSetValue).Value : 0) .ThenBy(image => image.Contains("sdkmessageprocessingstep.rank") ? (int)image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.rank").Value : 0) .ThenBy(image => image.FormattedValues.ContainsKey("sdkmessageprocessingstep.statuscode") ? image.FormattedValues["sdkmessageprocessingstep.statuscode"] : "") .ThenBy(image => image.FormattedValues.ContainsKey(SdkMessageProcessingStepImage.Schema.Attributes.imagetype) ? image.FormattedValues[SdkMessageProcessingStepImage.Schema.Attributes.imagetype] : "") .ThenBy(image => image.Name) .ThenBy(image => image.EntityAlias) .ThenBy(image => image.Attributes1StringsSorted) ; EntityMetadataRepository repositoryMetadata = new EntityMetadataRepository(service); var dependencyRepository = new DependencyRepository(service); var listMetaData = await repositoryMetadata.GetEntitiesWithAttributesAsync(); var dictEntity = new Dictionary<Guid, EntityMetadata>(); var dictAttribute = new Dictionary<Guid, AttributeMetadata>(); foreach (var metaEntity in listMetaData) { dictEntity.Add(metaEntity.MetadataId.Value, metaEntity); foreach (var metaAttribute in metaEntity.Attributes) { dictAttribute.Add(metaAttribute.MetadataId.Value, metaAttribute); } } bool hasInfo = false; foreach (var image in queryImages) { var listRequired = await dependencyRepository.GetRequiredComponentsAsync((int)ComponentType.SdkMessageProcessingStepImage, image.Id); var stepEntities = GetSetEntites(image); var stepAttributes = GetSetImageAttributes(image); var componentsEntities = GetSetComponentsEntites(listRequired, dictEntity); var componentsAttributes = GetSetComponentsAttributes(listRequired, dictAttribute); bool entitiesIsSame = stepEntities.SequenceEqual(componentsEntities); bool attributesIsSame = stepAttributes.SequenceEqual(componentsAttributes); string pluginType = image.Contains("sdkmessageprocessingstep.eventhandler") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.eventhandler").Value as EntityReference).Name : "Null"; string sdkMessage = image.Contains("sdkmessageprocessingstep.sdkmessageid") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.sdkmessageid").Value as EntityReference).Name : "Null"; int stage = image.Contains("sdkmessageprocessingstep.stage") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.stage").Value as OptionSetValue).Value : 0; int mode = image.Contains("sdkmessageprocessingstep.mode") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.mode").Value as OptionSetValue).Value : 0; int rank = image.Contains("sdkmessageprocessingstep.rank") ? (int)image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.rank").Value : 0; string status = image.FormattedValues.ContainsKey("sdkmessageprocessingstep.statuscode") ? image.FormattedValues["sdkmessageprocessingstep.statuscode"] : ""; if (!entitiesIsSame || !attributesIsSame) { hasInfo = true; if (content.Length > 0) { content.AppendLine().AppendLine().AppendLine(); } //handler.SetHeader("PluginType", "Primary Entity", "Secondary Entity", "Message", "Stage", "Rank", "Status", "ImageType", "Name", "EntityAlias", "Attributes"); content.AppendFormat("{0} Primary {1} Secondary {2} Message {3} Stage {4} Rank {5} Status {6} ImageType {7} Name {8} EntityAlias {9} Attributes {10}" , pluginType , image.PrimaryObjectTypeCodeName , image.SecondaryObjectTypeCodeName , sdkMessage , SdkMessageProcessingStepRepository.GetStageName(stage, mode) , rank.ToString() , status , image.FormattedValues[SdkMessageProcessingStepImage.Schema.Attributes.imagetype] , image.Name , image.EntityAlias , image.Attributes1StringsSorted ).AppendLine(); if (!entitiesIsSame) { content.AppendLine("Conflict in entites."); content.Append("Entities in plugin step description"); if (stepEntities.Count > 0) { content.AppendLine(":"); foreach (var item in stepEntities) { content.AppendFormat(" {0}", item).AppendLine(); } } else { content.AppendLine(" are empty."); } content.Append("Entities in required components"); if (componentsEntities.Count > 0) { content.AppendLine(":"); foreach (var item in componentsEntities) { content.AppendFormat(" {0}", item).AppendLine(); } } else { content.AppendLine(" are empty."); } } if (!attributesIsSame) { content.AppendLine("Conflict in attributes."); content.Append("Attributes in plugin step description"); if (componentsEntities.Count > 0) { content.AppendLine(":"); foreach (var item in stepAttributes) { content.AppendFormat(" {0}", item).AppendLine(); } } else { content.AppendLine(" are empty."); } content.Append("Attributes in required components"); if (componentsAttributes.Count > 0) { content.AppendLine(":"); foreach (var item in componentsAttributes) { content.AppendFormat(" {0}", item).AppendLine(); } } else { content.AppendLine(" are empty."); } } } } if (!hasInfo) { content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No conflicts were found.")); } string fileName = string.Format("{0}.Checking Plugin Images Required Components at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss")); if (string.IsNullOrEmpty(commonConfig.FolderForExport)) { _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty); commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath(); } else if (!Directory.Exists(commonConfig.FolderForExport)) { _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport); commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath(); } string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Images Required Components: {0}", filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); }
private async Task CheckingEntitiesOwnership(ConnectionData connectionData, CommonConfiguration commonConfig) { if (connectionData == null) { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection); return; } StringBuilder content = new StringBuilder(); content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM)); content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription())); // Подключаемся к CRM. var service = await QuickConnection.ConnectAsync(connectionData); if (service == null) { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name); return; } content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint)); EntityMetadataRepository repositoryEntity = new EntityMetadataRepository(service); var allEntities = await repositoryEntity.GetEntitiesDisplayNameAsync(); var groups = allEntities.GroupBy(ent => ent.OwnershipType).OrderBy(gr => gr.Key); foreach (var gr in groups) { content.AppendLine(); int count = gr.Count(); string name = "Null"; if (gr.Key.HasValue) { name = gr.Key.Value.ToString(); } content.AppendFormat("Entities with Ownership {0}: {1}", name, count).AppendLine(); gr.OrderBy(ent => ent.LogicalName).ToList().ForEach(ent => content.AppendLine(tabSpacer + ent.LogicalName)); } string fileName = string.Format("{0}.Entities with Ownership at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss")); if (string.IsNullOrEmpty(commonConfig.FolderForExport)) { _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty); commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath(); } else if (!Directory.Exists(commonConfig.FolderForExport)) { _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport); commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath(); } string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Entities with Ownership: {0}", filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); }