/// <summary> /// Provide a new implementation for finding a name for an OptionSet. If the /// OptionSet is not global, we want the name to be the concatenation of the Entity's /// name and the Attribute's name. Otherwise, we can use the default implementation. /// </summary> public String GetNameForOptionSet( EntityMetadata entityMetadata, OptionSetMetadataBase optionSetMetadata, IServiceProvider services) { // Ensure that the OptionSet is not global before using the custom // implementation. if (optionSetMetadata.IsGlobal.HasValue && !optionSetMetadata.IsGlobal.Value) { // Find the attribute which uses the specified OptionSet. var attribute = (from a in entityMetadata.Attributes where a.AttributeType == AttributeTypeCode.Picklist && ((EnumAttributeMetadata)a).OptionSet.MetadataId == optionSetMetadata.MetadataId select a).FirstOrDefault(); // Check for null, since statuscode attributes on custom entities are not // global, but their optionsets are not included in the attribute // metadata of the entity, either. if (attribute != null) { // Concatenate the name of the entity and the name of the attribute // together to form the OptionSet name. return String.Format("{0}{1}", DefaultNamingService.GetNameForEntity(entityMetadata, services), DefaultNamingService.GetNameForAttribute( entityMetadata, attribute, services)); } } return DefaultNamingService.GetNameForOptionSet( entityMetadata, optionSetMetadata, services); }
CodeTypeReference ITypeMappingService.GetTypeForAttributeType(EntityMetadata entityMetadata, AttributeMetadata attributeMetadata, IServiceProvider services) { var type = typeof (object); if (attributeMetadata.AttributeType.HasValue) { var key = attributeMetadata.AttributeType.Value; if (_attributeTypeMapping.ContainsKey(key)) { type = _attributeTypeMapping[key]; } else { if (key == AttributeTypeCode.PartyList) { return BuildCodeTypeReferenceForPartyList(services); } var attributeOptionSet = GetAttributeOptionSet(attributeMetadata); if (attributeOptionSet != null) { return BuildCodeTypeReferenceForOptionSet(attributeMetadata.LogicalName, entityMetadata, attributeOptionSet, services); } } if (type.IsValueType) { type = typeof (Nullable<>).MakeGenericType(new[] {type}); } } return TypeRef(type); }
public EntityExtractor(string entityName, List<EnviromentValue> enviromentValues, EntityMetadata entityDefine) { _entityDefine = entityDefine; EntityName = entityName; _enviromentValues = enviromentValues; }
public AttributePicker(EntityMetadata emd, IEnumerable<string> alreadySelectedAttributes, IOrganizationService service) { this.emd = emd; this.alreadySelectedAttributes = alreadySelectedAttributes; this.service = service; InitializeComponent(); }
private void AddEntityAttributesToList(EntityMetadata emd) { string groupName = string.Format("{0} ({1})", emd.DisplayName.UserLocalizedLabel.Label, emd.LogicalName); var group = new ListViewGroup {Header = groupName, Name = groupName}; lvAttributes.Groups.Add(@group); foreach (AttributeMetadata amd in emd.Attributes.Where(a => a.IsAuditEnabled != null && a.IsAuditEnabled.Value && a.AttributeOf == null)) { attributeInfos.Add(new AttributeInfo {Action = ActionState.None, InitialState = true, Amd = amd}); string displayName = amd.DisplayName != null && amd.DisplayName.UserLocalizedLabel != null ? amd.DisplayName.UserLocalizedLabel.Label : "N/A"; var itemAttr = new ListViewItem {Text = displayName, Tag = amd, Group = @group}; itemAttr.SubItems.Add(amd.LogicalName); lvAttributes.Items.Add(itemAttr); } }
protected override void AppendGetAutoincrementField(StringBuilder commandText, EntityMetadata entityMetadata) { commandText.Append("\nRETURNING ") .Append(DataService.EntityLiteProvider.StartQuote) .Append(entityMetadata.Properties[entityMetadata.AutogeneratedFieldName].SqlField.BaseColumnName) .Append(DataService.EntityLiteProvider.EndQuote).Append(";"); }
private static object GetSyncRecordId(object id, EntityMetadata metadata, Dictionary<string, object> syncParams) { if (!metadata.Attributes.Any(c =>syncParams.ContainsKey(c.PropertyName))) { return id; } var oldItem = DynamicRepository.Get(metadata, FilterCriteriaSet.And.Equal(id, metadata.PrimaryKeyPropertyName), ExternalMethodsCallMode.None).FirstOrDefault(); foreach(var p in syncParams) { if(metadata.Attributes.Any(c => c.PropertyName == p.Key)) { if ((oldItem as DynamicEntity)[p.Key].Equals(p.Value)) return id; } } FilterCriteriaSet compareFilter = FilterCriteriaSet.And; foreach (var p in syncParams) { if (metadata.Attributes.Any(c => c.PropertyName == p.Key)) { compareFilter.Merge(FilterCriteriaSet.And.Equal(p.Value, p.Key)); } } foreach (var attributeToCompare in metadata.Attributes.Where(a => a.ForCompare)) { compareFilter.Merge(FilterCriteriaSet.And.Equal((oldItem as DynamicEntity)[attributeToCompare.PropertyName], attributeToCompare.PropertyName)); } var item = DynamicRepository.Get(metadata, compareFilter, ExternalMethodsCallMode.None).FirstOrDefault(); return item != null ? (item as DynamicEntity).GetId() : id; }
public SqlServerGenerator(Type entityType) { var metadata = new EntityMetadata(entityType); IsIdentity = metadata.FirstOrDefault(x => x.IsIdentity) != null; var selectFields = string.Join(", ", metadata.Select(i => $"{i.DbName} AS {i.Name}")); var insertFields = string.Join(", ", metadata.Where(i => !i.IsIdentity).Select(i => i.DbName)); var insertValues = string.Join(", ", metadata.Where(i => !i.IsIdentity).Select(i => $"@{i.Name}")); var updatePairs = string.Join(", ", metadata.Where(i => !i.IsPrimaryKey).Select(i => $"{i.DbName} = @{i.Name}")); var whereCondition = string.Join(" AND ", metadata.Where(i => i.IsPrimaryKey).Select(i => $"{i.DbName} = @{i.Name}")); SelectAllSql = $"SELECT {selectFields} FROM {metadata.DbName}"; SelectSql = SelectAllSql; if (whereCondition.Length > 0) SelectSql += $" WHERE {whereCondition}"; InsertSql = $"INSERT INTO {metadata.DbName} ({insertFields}) VALUES ({insertValues})"; if (IsIdentity) { InsertSql += Environment.NewLine; InsertSql += "SELECT SCOPE_IDENTITY()"; } UpdateSql = $"UPDATE {metadata.DbName} SET {updatePairs}"; if (whereCondition.Length > 0) UpdateSql += $" WHERE {whereCondition}"; DeleteAllSql = $"DELETE FROM {metadata.DbName}"; DeleteSql = DeleteAllSql; if (whereCondition.Length > 0) DeleteSql += $" WHERE {whereCondition}"; CountSql = $"SELECT COUNT(1) FROM {metadata.DbName}"; }
private void AddEntityAttributesToList(EntityMetadata emd) { lvAttributes.Items.Clear(); foreach (AttributeMetadata amd in emd.Attributes.Where(a => a.IsAuditEnabled != null && a.IsAuditEnabled.Value && a.AttributeOf == null)) { var attributeInfo = attributeInfos.FirstOrDefault(a => a.Amd == amd); if (attributeInfo == null) { attributeInfos.Add(new AttributeInfo {Action = ActionState.None, InitialState = true, Amd = amd}); } else if (attributeInfo.Action == ActionState.Removed) { continue; } string displayName = amd.DisplayName != null && amd.DisplayName.UserLocalizedLabel != null ? amd.DisplayName.UserLocalizedLabel.Label : "N/A"; var itemAttr = new ListViewItem {Text = displayName, Tag = amd }; itemAttr.SubItems.Add(amd.LogicalName); lvAttributes.Items.Add(itemAttr); } }
public bool GenerateRelationship(RelationshipMetadataBase relationshipMetadata, EntityMetadata otherEntityMetadata, IServiceProvider services) { if (!GenerateEntityRelationships) { return false; } return DefaultService.GenerateRelationship(relationshipMetadata, otherEntityMetadata, services); }
internal OrganizationMetadata(EntityMetadata[] entities, OptionSetMetadataBase[] optionSets, SdkMessages messages) { Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name}); _entities = entities; _optionSets = optionSets; _sdkMessages = messages; Trace.TraceInformation("Exiting {0}", new object[] {MethodBase.GetCurrentMethod().Name}); }
public bool IsEntityPrimaryKey(string entityName, string attributeName) { if (_crmEntityMetaData == null) _crmEntityMetaData = GetCrmEntityMetaData(entityName); if (_crmEntityMetaData != null && _crmEntityMetaData.PrimaryIdAttribute == attributeName) return true; return false; }
public static AttributeDescription GetEntityCaptionAttribute(EntityMetadata metadata) { string[] columnCaptions = new string[] { "Code", "IdNumber", "NumberId", "Number", "Name", "Caption", "Id" }; int i = -1; var properties = metadata.PlainAttributes.Select(pa => pa.PropertyName); while (++i < columnCaptions.Count() && !properties.Contains(columnCaptions[i])) { } return i < columnCaptions.Count() ? metadata.GetAttributeByPropertyName(columnCaptions[i]) : null; }
public static FilterCriteriaSet GetProcessedFilter(EntityMetadata metadata) { var subquery = string.Format( "[{0}].[{1}].[{2}] IN (SELECT DISTINCT ProcessId FROM WorkflowHistory WHERE SecurityUserId IS NOT NULL AND SecurityUserId = '{3}')", metadata.SchemaName, metadata.TableName, metadata.PrimaryKeyPropertyName, (Guid)CommonSettings.CurrentEmployee.SecurityUserId); return FilterCriteriaSet.And.Custom(subquery); }
public void RefreshContent(EntityMetadata newEmd) { emd = newEmd; entityPropertyGrid.SelectedObject = new EntityMetadataInfo(emd); LoadAttributes(emd.Attributes); LoadOneToManyRelationships(emd.OneToManyRelationships); LoadManyToOneRelationships(emd.ManyToOneRelationships); LoadManyToManyRelationships(emd.ManyToManyRelationships); LoadPrivileges(emd.Privileges); }
public bool GenerateEntity(EntityMetadata entityMetadata, IServiceProvider services) { if (!DefaultService.GenerateEntity(entityMetadata, services)) { return false; } if (!EntityMetadata.ContainsKey(entityMetadata.LogicalName)) { EntityMetadata.Add(entityMetadata.LogicalName, entityMetadata); } return !EntitiesToSkip.Contains(entityMetadata.LogicalName); }
public Logic(IOrganizationService service, ConnectionDetail connectionDetail, EntityMetadata metadata, string tempPostFix, bool migrateData) { SupportsExecuteMultipleRequest = connectionDetail.OrganizationMajorVersion >= Crm2013 || (connectionDetail.OrganizationMajorVersion >= Crm2011 && int.Parse(connectionDetail.OrganizationVersion.Split('.')[3]) >= Rollup12); Service = service; TempPostfix = tempPostFix; MigrateData = migrateData; ValidLanguageCodes = GetValidLanguageCodes(); Metadata = metadata; }
public static ExternalMethodCallResult DeleteBudgetDictionary(EntityMetadata metadata, Dictionary<string, string> parameters, IEnumerable<DynamicEntity> entities) { ExternalMethodCallResult res = new ExternalMethodCallResult(true); List<string> views = null; if (parameters.ContainsKey("Views")) { views = parameters["Views"].Split(',').Select(c => c.Trim()).ToList(); } List<string> forms = null; if (parameters.ContainsKey("Forms")) { forms = parameters["Forms"].Split(',').Select(c => c.Trim()).ToList(); } string budgetColumnName = "BudgetId"; if (parameters.ContainsKey("Column")) { budgetColumnName = parameters["Column"]; } foreach (DynamicEntity e in entities) { if(parameters.ContainsKey("ValidateStoredProcedure")) { var paramsIn = new Dictionary<string, object>(); paramsIn.Add(budgetColumnName, e.GetId()); var paramsOut = new Dictionary<string, object>(); paramsOut.Add("ErrorMessage", string.Empty); DynamicRepository.ExecuteSP(parameters["ValidateStoredProcedure"],paramsIn,paramsOut); if (!string.IsNullOrWhiteSpace(paramsOut["ErrorMessage"] as string)) { res.AddGlobalError(paramsOut["ErrorMessage"].ToString()); res.Sucess = false; } } } if (res.Sucess) { foreach (DynamicEntity e in entities) { Budget b = new Budget(); b.DeleteEntityByViews(budgetColumnName, e.GetId(), views); b.DeleteEntityByForms(budgetColumnName, e.GetId(), forms); } } return res; }
string INamingService.GetNameForEntity(EntityMetadata entityMetadata, IServiceProvider services) { if (_knowNames.ContainsKey(entityMetadata.MetadataId.Value.ToString())) { return _knowNames[entityMetadata.MetadataId.Value.ToString()]; } var name = string.IsNullOrEmpty(StaticNamingService.GetNameForEntity(entityMetadata)) ? entityMetadata.SchemaName : StaticNamingService.GetNameForEntity(entityMetadata); var str2 = CreateValidTypeName(name); _knowNames.Add(entityMetadata.MetadataId.Value.ToString(), str2); return str2; }
public EntityMetadataBuilder(string entityName) { //Initialise Meatdata Entity = new EntityMetadata { LogicalName = entityName.ToLower(), SchemaName = entityName, IsActivity = false, IsActivityParty = false, OwnershipType = OwnershipTypes.UserOwned }; }
private void LoadRibbonCommands(EntityMetadata emd) { var commands = service.RetrieveMultiple(new QueryExpression("ribboncommand") { ColumnSet = new ColumnSet(true), Criteria = new FilterExpression { Conditions = { new ConditionExpression("commanddefinition", ConditionOperator.Like, "%Library=\"$webresource:%"), new ConditionExpression("entity", ConditionOperator.Equal, emd.LogicalName) } } }); foreach (var command in commands.Entities) { var commandDoc = new XmlDocument(); commandDoc.LoadXml(command.GetAttributeValue<string>("commanddefinition")); var actionsNode = commandDoc.SelectSingleNode("CommandDefinition/Actions"); foreach (XmlNode actionNode in actionsNode.ChildNodes) { if (actionNode.Attributes == null) continue; var libraryNode = actionNode.Attributes["Library"]; if (libraryNode == null) { continue; } var libraryName = libraryNode.Value; if (libraryName.Split(':').Length == 1) continue; var script = new Script(); script.EntityLogicalName = emd.LogicalName; script.EntityName = emd.DisplayName.UserLocalizedLabel.Label; script.ScriptLocation = libraryName.Split(':')[1]; script.MethodCalled = actionNode.Attributes["FunctionName"].Value; script.Event = ""; script.Attribute = ""; script.AttributeLogicalName = ""; script.Name = string.Empty; script.Type = "Ribbon Command"; Scripts.Add(script); } } }
public XrmEntityDefinition(EntityMetadata metadata) { var metadata1 = metadata; TableName = metadata1.LogicalName; DisplayName = metadata1.DisplayName.UserLocalizedLabel != null ? metadata1.DisplayName.UserLocalizedLabel.Label : metadata1.LogicalName; CrmFields =(from x in metadata.Attributes select new XrmEntityFieldDefinition(x)); }
public static ExternalMethodCallResult CopyBudgetDictionary(EntityMetadata metadata, Dictionary<string, string> parameters, IEnumerable<DynamicEntity> entities) { List<string> forms = null; List<string> trivialFormsToCopy = null; if (parameters.ContainsKey("Forms")) { forms = parameters["Forms"].Split(',').Select(c => c.Trim()).ToList(); trivialFormsToCopy = forms.Where(f => !BusinessEntitiesCreations.ContainsKey(f)).ToList(); } foreach (DynamicEntity e in entities) { var b = new Budget(); var versions = DynamicRepository.GetByView("BudgetVersion", FilterCriteriaSet.And.Equal(e.GetId(), "BudgetId").Merge(FilterCriteriaSet.And.Equal(true, "IsCurrent"))); if (versions.Count == 0) { var v = DynamicRepository.NewByView("BudgetVersion"); v.Id = Guid.NewGuid(); v.Name = "1"; v.BudgetId = e.GetId(); v.IsCurrent = true; DynamicRepository.InsertByView("BudgetVersion", new List<dynamic>() { v }, ExternalMethodsCallMode.None); } var filters = new Dictionary<string, FilterCriteriaSet> { { "ContractForBudgetCopy", FilterCriteriaSet.And.Custom("ContractStatusId = 1") } }; var replaces = b.CopyEntityByForms("BudgetId", CommonSettings.CurrentBudget.Id, e.GetId(), trivialFormsToCopy, filters); if (forms == null) continue; foreach (var k in BusinessEntitiesCreations.Keys) { if (!forms.Any(f => f.Equals(k))) continue; BusinessEntitiesCreations[k].Invoke(e.GetId(), CommonSettings.CurrentBudget.Id, replaces); } } return new ExternalMethodCallResult(true); }
public static void ResetIcons(EntityMetadata emd, IOrganizationService service) { emd.IconSmallName = ""; emd.IconMediumName = ""; emd.IconLargeName = ""; var request = new UpdateEntityRequest { Entity = emd }; service.Execute(request); string parameterXml = string.Format("<importexportxml ><entities><entity>{0}</entity></entities></importexportxml>", emd.LogicalName); var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml }; service.Execute(publishRequest); }
public static bool VisibilityAccessCheck(EntityMetadata metadata, Guid id, FilterCriteriaSet visibilityFilter) { if (visibilityFilter.IsEmpty) return true; var accessFilter = FilterCriteriaSet.Or.Merge(visibilityFilter) .Merge(CommonMethods.GetInboxFilter(metadata)) .Merge(CommonMethods.GetProcessedFilter(metadata)); accessFilter = FilterCriteriaSet.And.Equal(id, metadata.PrimaryKeyPropertyName).Merge(accessFilter); var cnt = metadata.Count(accessFilter); return cnt == 1; }
public string GetNameForAttribute(EntityMetadata entityMetadata, AttributeMetadata attributeMetadata, IServiceProvider services) { List<string> specifiedNames; string attributeName; if (EntityAttributeSpecifiedNames.TryGetValue(entityMetadata.LogicalName.ToLower(), out specifiedNames) && specifiedNames.Any(s => string.Equals(s, attributeMetadata.LogicalName, StringComparison.OrdinalIgnoreCase))) { attributeName = specifiedNames.First(s => string.Equals(s, attributeMetadata.LogicalName, StringComparison.OrdinalIgnoreCase)); } else { attributeName = DefaultService.GetNameForAttribute(entityMetadata, attributeMetadata, services); } return attributeName; }
public static string RetrieveAttributeDisplayName(EntityMetadata emd, string attributeName, string fetchXml, IOrganizationService oService) { string rAttributeName = attributeName; string rEntityName = string.Empty; if (attributeName.Contains(".")) { string[] data = attributeName.ToLower().Split('.'); if (!string.IsNullOrEmpty(fetchXml)) { XmlDocument fetchDoc = new XmlDocument(); fetchDoc.LoadXml(fetchXml); XmlNode aliasNode = fetchDoc.SelectSingleNode("//link-entity[@alias='" + data[0] + "']"); if (aliasNode != null) { EntityMetadata relatedEmd = RetrieveEntity(aliasNode.Attributes["name"].Value, oService); AttributeMetadata relatedamd = (from attr in relatedEmd.Attributes where attr.LogicalName == data[1] select attr).FirstOrDefault(); if (relatedamd == null) { return string.Format("(unknown:{0})", attributeName); } return relatedamd.DisplayName.UserLocalizedLabel.Label; } } return "(not found)"; } else { AttributeMetadata attribute = (from attr in emd.Attributes where attr.LogicalName == attributeName select attr).FirstOrDefault(); if (attribute == null) { return string.Format("(unknown:{0})", attributeName); } return attribute.DisplayName.UserLocalizedLabel.Label; } }
string INamingService.GetNameForAttribute(EntityMetadata entityMetadata, AttributeMetadata attributeMetadata, IServiceProvider services) { if (_knowNames.ContainsKey(entityMetadata.MetadataId.Value.ToString() + attributeMetadata.MetadataId.Value)) { return _knowNames[entityMetadata.MetadataId.Value.ToString() + attributeMetadata.MetadataId.Value]; } var name = StaticNamingService.GetNameForAttribute(attributeMetadata) ?? attributeMetadata.SchemaName; name = CreateValidName(name); var service = (INamingService) services.GetService(typeof (INamingService)); if (_reservedAttributeNames.Contains(name) || (name == service.GetNameForEntity(entityMetadata, services))) { name = name + "1"; } _knowNames.Add(entityMetadata.MetadataId.Value.ToString() + attributeMetadata.MetadataId.Value, name); return name; }
public void Simple_Test() { var md = new EntityMetadata(typeof(Simple)); Assert.Equal(2, md.Count); Assert.Equal("Simple", md.Name); Assert.Equal("Simple", md.DbName); Assert.Equal("Id", md[0].Name); Assert.Equal("Id", md[0].DbName); Assert.True(md[0].IsPrimaryKey); Assert.True(md[0].IsIdentity); Assert.Equal("Text", md[1].Name); Assert.Equal("Text", md[1].DbName); Assert.False(md[1].IsPrimaryKey); Assert.False(md[1].IsIdentity); }
public EntityPropertiesControl(EntityMetadata emd, ListViewColumnsSettings lvcSettings) { InitializeComponent(); this.emd = emd; this.lvcSettings = (ListViewColumnsSettings)lvcSettings.Clone(); ListViewColumnHelper.AddColumnsHeader(attributeListView, typeof(AttributeMetadataInfo), ListViewColumnsSettings.AttributeFirstColumns, this.lvcSettings.AttributeSelectedAttributes, new string[] { }); ListViewColumnHelper.AddColumnsHeader(OneToManyListView, typeof(OneToManyRelationshipMetadataInfo), ListViewColumnsSettings.RelFirstColumns, this.lvcSettings.OtmRelSelectedAttributes, new string[] { }); ListViewColumnHelper.AddColumnsHeader(manyToOneListView, typeof(OneToManyRelationshipMetadataInfo), ListViewColumnsSettings.RelFirstColumns, this.lvcSettings.OtmRelSelectedAttributes, new string[] { }); ListViewColumnHelper.AddColumnsHeader(manyToManyListView, typeof(ManyToManyRelationshipMetadataInfo), ListViewColumnsSettings.RelFirstColumns, this.lvcSettings.MtmRelSelectedAttributes, new string[] { }); ListViewColumnHelper.AddColumnsHeader(privilegeListView, typeof(SecurityPrivilegeInfo), ListViewColumnsSettings.PrivFirstColumns, this.lvcSettings.PrivSelectedAttributes, new string[] { }); attributesSplitContainer.Panel2Collapsed = true; manyToManySplitContainer.Panel2Collapsed = true; manyToOneSplitContainer.Panel2Collapsed = true; oneToManySplitContainer.Panel2Collapsed = true; privilegeSplitContainer.Panel2Collapsed = true; RefreshContent(emd); }
private void BwDisplayViewDoWork(object sender, DoWorkEventArgs e) { try { if (ListViewDelegates.GetSelectedItems(lvSourceViews).Count() > 1) { ColumnHeader header = new ColumnHeader(); header.Width = 380; header.Text = "Layout preview cannot be displayed when multiple views are selected."; ListViewDelegates.AddColumn(lvSourceViewLayoutPreview, header); } else { // Gets current view data Entity currentSelectedView = (Entity)ListViewDelegates.GetSelectedItems(lvSourceViews)[0].Tag; string layoutXml = currentSelectedView["layoutxml"].ToString(); string fetchXml = currentSelectedView.Contains("fetchxml") ? currentSelectedView["fetchxml"].ToString() : string.Empty; string currentEntityDisplayName = ListViewDelegates.GetSelectedItems(lvEntities)[0].Text; EntityMetadata currentEmd = entitiesCache.Find( delegate(EntityMetadata emd) { return(emd.DisplayName.UserLocalizedLabel.Label == currentEntityDisplayName); }); XmlDocument layoutDoc = new XmlDocument(); layoutDoc.LoadXml(layoutXml); EntityMetadata emdWithItems = MetadataHelper.RetrieveEntity(currentEmd.LogicalName, service); ListViewItem item = new ListViewItem(); foreach (XmlNode columnNode in layoutDoc.SelectNodes("grid/row/cell")) { ColumnHeader header = new ColumnHeader(); header.Text = MetadataHelper.RetrieveAttributeDisplayName(emdWithItems, columnNode.Attributes["name"].Value, fetchXml, service); header.Width = int.Parse(columnNode.Attributes["width"].Value); ListViewDelegates.AddColumn(lvSourceViewLayoutPreview, header); if (string.IsNullOrEmpty(item.Text)) { item.Text = columnNode.Attributes["width"].Value + "px"; } else { item.SubItems.Add(columnNode.Attributes["width"].Value + "px"); } } ListViewDelegates.AddItem(lvSourceViewLayoutPreview, item); GroupBoxDelegates.SetEnableState(gbSourceViewLayout, true); } } catch (Exception error) { CommonDelegates.DisplayMessageBox(ParentForm, "Error while displaying view: " + error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public string GetNameForEntitySet(EntityMetadata entityMetadata, IServiceProvider services) { return(DefaultNamingService.GetNameForEntitySet(entityMetadata, services)); }
bool ICodeWriterFilterService.GenerateRelationship(RelationshipMetadataBase relationshipMetadata, EntityMetadata otherEntityMetadata, IServiceProvider services) { return(this.DefaultService.GenerateRelationship(relationshipMetadata, otherEntityMetadata, services)); }
public static void SetSealedPropertyValue(this EntityMetadata entityMetadata, string sPropertyName, object value) { entityMetadata.GetType().GetProperty(sPropertyName).SetValue(entityMetadata, value, null); }
public static void SetAttributeCollection(this EntityMetadata entityMetadata, IEnumerable <AttributeMetadata> attributes) { entityMetadata.GetType().GetProperty("Attributes").SetValue(entityMetadata, attributes.ToList().ToArray(), null); }
public bool GenerateRelationship(RelationshipMetadataBase relationshipMetadata, EntityMetadata otherEntityMetadata, IServiceProvider services) { return(_defaultService.GenerateRelationship(relationshipMetadata, otherEntityMetadata, services)); }
private static Entity GetDocumentLocation(OrganizationServiceContext context, Entity entity, EntityMetadata entityMetadata, Entity spSite) { var locations = context.CreateQuery(SharePointDocumentLocationLogicalName) .Where(docLoc => docLoc.GetAttributeValue <EntityReference>("regardingobjectid").Id == entity.Id && docLoc.GetAttributeValue <int>("statecode") == 0) .OrderBy(docLoc => docLoc.GetAttributeValue <DateTime>("createdon")) .ToArray(); Entity location; if (locations.Count() > 1) { // Multiple doc locations found, choose the first created. location = locations.First(); } else if (locations.Count() == 1) { location = locations.First(); } else { // No document locations found, create an auto-generated one. var autoGeneratedRelativeUrl = "{0}_{1}".FormatWith( entity.GetAttributeValue <string>(entityMetadata.PrimaryNameAttribute), entity.Id.ToString("N").ToUpper()); location = context.AddOrGetExistingDocumentLocationAndSave <Entity>(spSite, entity, autoGeneratedRelativeUrl); } if (location == null) { throw new Exception("A document location couldn't be found or created for the entity."); } return(location); }
public static string GetDisplayLabel(this EntityMetadata oEntityMD) { var oEntityNameLabel = oEntityMD.DisplayName.LocalizedLabels.FirstOrDefault(); if (oEntityNameLabel != null) return oEntityNameLabel.Label; return ""; }
/// <summary> /// Processes all nodes in dense format from the PrimitiveGroup and adds them to the output queue. /// </summary> /// <param name="block">The PrimitiveBlock that contains specified PrimitiveGroup.</param> /// <param name="group">The PrimitiveGroup with nodes to process.</param> private void ProcessDenseNodes(PrimitiveBlock block, PrimitiveGroup group) { if (group.DenseNodes == null) { return; } long idStore = 0; long latStore = 0; long lonStore = 0; int keyValueIndex = 0; long timestampStore = 0; long changesetStore = 0; int userIdStore = 0; int usernameIdStore = 0; for (int i = 0; i < group.DenseNodes.Id.Count; i++) { idStore += group.DenseNodes.Id[i]; lonStore += group.DenseNodes.Longitude[i]; latStore += group.DenseNodes.Latitude[i]; double lat = 1E-09 * (block.LatOffset + (block.Granularity * latStore)); double lon = 1E-09 * (block.LonOffset + (block.Granularity * lonStore)); List <Tag> tags = new List <Tag>(); if (group.DenseNodes.KeysVals.Count > 0) { while (group.DenseNodes.KeysVals[keyValueIndex] != 0) { string key = block.StringTable[group.DenseNodes.KeysVals[keyValueIndex++]]; string value = block.StringTable[group.DenseNodes.KeysVals[keyValueIndex++]]; tags.Add(new Tag(key, value)); } //Skip '0' used as delimiter keyValueIndex++; } EntityMetadata metadata = null; if (this.Settings.ReadMetadata && group.DenseNodes.DenseInfo != null) { timestampStore += group.DenseNodes.DenseInfo.Timestamp[i]; changesetStore += group.DenseNodes.DenseInfo.Changeset[i]; userIdStore += group.DenseNodes.DenseInfo.UserId[i]; usernameIdStore += group.DenseNodes.DenseInfo.UserNameIndex[i]; metadata = new EntityMetadata() { Changeset = (int)changesetStore, Timestamp = _unixEpoch.AddMilliseconds(timestampStore * block.DateGranularity), Uid = userIdStore, User = block.StringTable[usernameIdStore], Version = group.DenseNodes.DenseInfo.Version[i], Visible = true }; if (group.DenseNodes.DenseInfo.Visible.Count > 0) { metadata.Visible = group.DenseNodes.DenseInfo.Visible[i]; } } NodeInfo parsed = new NodeInfo((int)idStore, lat, lon, new TagsCollection(tags), metadata); _cache.Enqueue(parsed); } }
public EntityMetadataHolder(EntityMetadata entityMetadata, LookupAttributeMetadataHolder[] lookupAttributeMetadataHolders) { EntityMetadata = entityMetadata; LookupAttributeMetadataHolders = lookupAttributeMetadataHolders; }
/// <summary> /// We don't want to generate any relationships. /// </summary> public bool GenerateRelationship(RelationshipMetadataBase relationshipMetadata, EntityMetadata otherEntityMetadata, IServiceProvider services) { return(false); }
private static void FillParametersInFetch(EntityMetadata entityMetadata, XElement fetchXmlDoc, string searchText) { var filterElements = fetchXmlDoc .DescendantsAndSelf() .Where(IsQuickFindFields) .ToList(); foreach (var filter in filterElements) { filter.Attribute("isquickfindfields").Remove(); var conditionElements = filter .Descendants() .Where(IsConditionElement) .ToList(); foreach (var condition in conditionElements) { string attributeName = condition.Attribute("attribute")?.Value; string value = condition.Attribute("value")?.Value; if (string.IsNullOrEmpty(attributeName)) { continue; } if (string.Equals(value, "{0}", StringComparison.InvariantCultureIgnoreCase)) { var attr = entityMetadata.Attributes.FirstOrDefault(a => string.Equals(a.LogicalName, attributeName, StringComparison.InvariantCultureIgnoreCase)); if (attr == null) { condition.Remove(); continue; } if (string.IsNullOrEmpty(searchText)) { condition.Remove(); continue; } switch (attr.AttributeType.Value) { case AttributeTypeCode.Memo: case AttributeTypeCode.String: condition.Attribute("value").Value = searchText.Replace("*", "%") + "%"; break; case AttributeTypeCode.Boolean: if (bool.TryParse(searchText, out bool boolValue)) { condition.Attribute("value").Value = boolValue.ToString(); } else { condition.Remove(); } break; case AttributeTypeCode.Customer: case AttributeTypeCode.Lookup: case AttributeTypeCode.Owner: if (entityMetadata.Attributes.FirstOrDefault(a => string.Equals(a.LogicalName, attributeName + "name", StringComparison.InvariantCultureIgnoreCase)) == null) { condition.Remove(); } else { condition.Attribute("attribute").Value += "name"; if (string.IsNullOrEmpty(searchText)) { condition.Attribute("value").Value = "%"; } else { condition.Attribute("value").Value = searchText.Replace("*", "%") + "%"; } } break; case AttributeTypeCode.DateTime: if (DateTime.TryParse(searchText, out var dt)) { condition.Attribute("value").Value = dt.ToString("yyyy-MM-dd"); } else { condition.Remove(); } break; case AttributeTypeCode.Decimal: case AttributeTypeCode.Double: case AttributeTypeCode.Money: if (decimal.TryParse(searchText, out decimal decimalValue)) { condition.Attribute("value").Value = decimalValue.ToString(CultureInfo.InvariantCulture); } else { condition.Remove(); } break; case AttributeTypeCode.Integer: if (int.TryParse(searchText, out int intValue)) { condition.Attribute("value").Value = intValue.ToString(CultureInfo.InvariantCulture); } else { condition.Remove(); } break; case AttributeTypeCode.Picklist: if (attr is PicklistAttributeMetadata picklistAttribute) { FillOptionSetValue(searchText, condition, picklistAttribute.OptionSet.Options); } break; case AttributeTypeCode.State: if (attr is StateAttributeMetadata stateAttributeMetadata) { FillOptionSetValue(searchText, condition, stateAttributeMetadata.OptionSet.Options); } break; case AttributeTypeCode.Status: if (attr is StatusAttributeMetadata statusAttributeMetadata) { FillOptionSetValue(searchText, condition, statusAttributeMetadata.OptionSet.Options); } break; } } else if (string.Equals(value, "{1}", StringComparison.InvariantCultureIgnoreCase)) { } } if (!filter.HasElements) { filter.Remove(); } } }
public static string GetAttributeFormattedValue(string attributeLogicalName, int?languageCode, Entity entity, AttributeMetadata attributeMetadata, IOrganizationService organizationService) { string formattedValue = string.Empty; //Null validation if (attributeMetadata != null) { object atrributeValue = null; switch (attributeMetadata.AttributeType.Value) { case AttributeTypeCode.String: case AttributeTypeCode.Memo: formattedValue = GetAttributeValue <string>(attributeLogicalName, entity); break; case AttributeTypeCode.Uniqueidentifier: atrributeValue = GetAttributeValue <Guid?>(attributeLogicalName, entity); if (atrributeValue != null) { formattedValue = ((Guid)atrributeValue).ToString(); } break; case AttributeTypeCode.DateTime: atrributeValue = GetAttributeValue <DateTime?>(attributeLogicalName, entity); if (atrributeValue != null) { formattedValue = ((DateTime)atrributeValue).ToOADate().ToString(); } break; case AttributeTypeCode.Boolean: atrributeValue = GetAttributeValue <Boolean?>(attributeLogicalName, entity); if (atrributeValue != null) { formattedValue = atrributeValue.ToString().ToLowerInvariant(); } break; case AttributeTypeCode.Customer: case AttributeTypeCode.Owner: case AttributeTypeCode.Lookup: atrributeValue = GetAttributeValue <EntityReference>(attributeLogicalName, entity); if (atrributeValue != null) { EntityReference entityReference = (EntityReference)atrributeValue; if (entityReference != null) { formattedValue = entityReference.Name; //Null validation if (string.IsNullOrEmpty(formattedValue)) { //Get entity metadata EntityMetadata entyMetadata = RetrieveEntityMetadata(entityReference.LogicalName, EntityFilters.Entity, organizationService); //Null validation if (entyMetadata != null) { //Get entity related to entity Entity _entity = RetrieveEntity(entityReference, new string[] { entyMetadata.PrimaryNameAttribute }, organizationService); //Null validation if (_entity != null) { formattedValue = GetAttributeValue <string>(entyMetadata.PrimaryNameAttribute, _entity); } } } } } break; case AttributeTypeCode.BigInt: atrributeValue = GetAttributeValue <long?>(attributeLogicalName, entity); if (atrributeValue != null) { formattedValue = ((long)atrributeValue).ToString(CultureInfo.InvariantCulture); } break; case AttributeTypeCode.Integer: atrributeValue = GetAttributeValue <int?>(attributeLogicalName, entity); if (atrributeValue != null) { formattedValue = ((int)atrributeValue).ToString(CultureInfo.InvariantCulture); } break; case AttributeTypeCode.Picklist: case AttributeTypeCode.State: case AttributeTypeCode.Status: atrributeValue = GetAttributeValue <OptionSetValue>(attributeLogicalName, entity); //Null validation if (atrributeValue != null) { int selectedValue = ((OptionSetValue)atrributeValue).Value; string optionLabel = string.Empty; OptionSetMetadata optionSetMetadata = null; //Check attribute metadata type if (attributeMetadata is PicklistAttributeMetadata) { optionSetMetadata = ((PicklistAttributeMetadata)attributeMetadata).OptionSet; } else if (attributeMetadata is StateAttributeMetadata) { optionSetMetadata = ((StateAttributeMetadata)attributeMetadata).OptionSet; } else if (attributeMetadata is StatusAttributeMetadata) { optionSetMetadata = ((StatusAttributeMetadata)attributeMetadata).OptionSet; } //Null validation if (optionSetMetadata != null) { //Get option metadata from option set metadata by selected value OptionMetadata optionMetadata = optionSetMetadata.Options.FirstOrDefault(item => item.Value.Value.Equals(selectedValue)); //Null validation if (optionMetadata != null) { formattedValue = GetDisplayName(optionMetadata.Label, languageCode); } } } break; case AttributeTypeCode.Money: atrributeValue = GetAttributeValue <Money>(attributeLogicalName, entity); if (atrributeValue != null) { formattedValue = ((Money)atrributeValue).Value.ToString(CultureInfo.InvariantCulture); } break; case AttributeTypeCode.Decimal: atrributeValue = GetAttributeValue <decimal?>(attributeLogicalName, entity); if (atrributeValue != null) { formattedValue = ((decimal)atrributeValue).ToString(CultureInfo.InvariantCulture); } break; case AttributeTypeCode.Double: atrributeValue = GetAttributeValue <double?>(attributeLogicalName, entity); if (atrributeValue != null) { formattedValue = ((double)atrributeValue).ToString(CultureInfo.InvariantCulture); } break; } } return(formattedValue); }
private string EntityNamingLogic(EntityMetadata entityMetadata) { return(entityMetadata.DisplayName()); }
/// <summary> /// Adds metadata of an entity /// </summary> /// <param name="emd">Entity metadata</param> /// <param name="sheet">Worksheet where to write</param> public void AddEntityMetadata(EntityMetadata emd, ExcelWorksheet sheet) { attributesHeaderAdded = false; lineNumber = 1; sheet.Cells[lineNumber, 1].Value = "Entity"; sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.BackgroundColor.SetColor(Color.PowderBlue); sheet.Cells[lineNumber, 1].Style.Font.Bold = true; var emdDisplayName = emd.DisplayName.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode); sheet.Cells[lineNumber, 2].Value = emd.DisplayName.LocalizedLabels.Count == 0 ? emd.SchemaName : emdDisplayName != null ? emdDisplayName.Label : null; lineNumber++; sheet.Cells[lineNumber, 1].Value = ("Plural Display Name"); sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.BackgroundColor.SetColor(Color.PowderBlue); sheet.Cells[lineNumber, 1].Style.Font.Bold = true; var emdDisplayCollectionName = emd.DisplayCollectionName.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode); sheet.Cells[lineNumber, 2].Value = (emd.DisplayCollectionName.LocalizedLabels.Count == 0 ? "N/A" : emdDisplayCollectionName != null ? emdDisplayCollectionName.Label : null); lineNumber++; sheet.Cells[lineNumber, 1].Value = ("Description"); sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.BackgroundColor.SetColor(Color.PowderBlue); sheet.Cells[lineNumber, 1].Style.Font.Bold = true; var emdDescription = emd.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == settings.DisplayNamesLangugageCode); sheet.Cells[lineNumber, 2].Value = (emd.Description.LocalizedLabels.Count == 0 ? "N/A" : emdDescription != null ? emdDescription.Label : null); lineNumber++; sheet.Cells[lineNumber, 1].Value = ("Schema Name"); sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.BackgroundColor.SetColor(Color.PowderBlue); sheet.Cells[lineNumber, 1].Style.Font.Bold = true; sheet.Cells[lineNumber, 2].Value = (emd.SchemaName); lineNumber++; sheet.Cells[lineNumber, 1].Value = ("Logical Name"); sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.BackgroundColor.SetColor(Color.PowderBlue); sheet.Cells[lineNumber, 1].Style.Font.Bold = true; sheet.Cells[lineNumber, 2].Value = (emd.LogicalName); lineNumber++; sheet.Cells[lineNumber, 1].Value = ("Object Type Code"); sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.BackgroundColor.SetColor(Color.PowderBlue); sheet.Cells[lineNumber, 1].Style.Font.Bold = true; sheet.Cells[lineNumber, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left; if (emd.ObjectTypeCode != null) { sheet.Cells[lineNumber, 1].Value = (emd.ObjectTypeCode.Value); } lineNumber++; sheet.Cells[lineNumber, 1].Value = ("Is Custom Entity"); sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.BackgroundColor.SetColor(Color.PowderBlue); sheet.Cells[lineNumber, 1].Style.Font.Bold = true; sheet.Cells[lineNumber, 2].Value = (emd.IsCustomEntity != null && emd.IsCustomEntity.Value); sheet.Cells[lineNumber, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left; lineNumber++; sheet.Cells[lineNumber, 1].Value = ("Ownership Type"); sheet.Cells[lineNumber, 1].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[lineNumber, 1].Style.Fill.BackgroundColor.SetColor(Color.PowderBlue); sheet.Cells[lineNumber, 1].Style.Font.Bold = true; if (emd.OwnershipType != null) { sheet.Cells[lineNumber, 2].Value = (emd.OwnershipType.Value); } lineNumber++; lineNumber++; }
/// <summary> /// Draw on a Visio page the entity relationships defined in the passed-in relationship collection. /// </summary> /// <param name="entity">Core entity</param> /// <param name="rect">Shape representing the core entity</param> /// <param name="relationshipCollection">Collection of entity relationships to draw</param> /// <param name="areReferencingRelationships">Whether or not the core entity is the referencing entity in the relationship</param> /// <param name="worker">The worker.</param> /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param> private void DrawRelationships(EntityMetadata entity, VisioApi.Shape rect, RelationshipMetadataBase[] relationshipCollection, bool areReferencingRelationships, BackgroundWorker worker, DoWorkEventArgs e) { ManyToManyRelationshipMetadata currentManyToManyRelationship = null; OneToManyRelationshipMetadata currentOneToManyRelationship = null; EntityMetadata entity2 = null; AttributeMetadata attribute2 = null; AttributeMetadata attribute = null; Guid metadataID = Guid.NewGuid(); bool isManyToMany = false; // Draw each relationship in the relationship collection. foreach (RelationshipMetadataBase entityRelationship in relationshipCollection) { if (worker.CancellationPending) { e.Cancel = true; return; } entity2 = null; if (entityRelationship is ManyToManyRelationshipMetadata) { isManyToMany = true; currentManyToManyRelationship = entityRelationship as ManyToManyRelationshipMetadata; // The entity passed in is not necessarily the originator of this relationship. if (String.Compare(entity.LogicalName, currentManyToManyRelationship.Entity1LogicalName, true) != 0) { entity2 = GetEntityMetadata(currentManyToManyRelationship.Entity1LogicalName); } else { entity2 = GetEntityMetadata(currentManyToManyRelationship.Entity2LogicalName); } attribute2 = GetAttributeMetadata(entity2, entity2.PrimaryIdAttribute); attribute = GetAttributeMetadata(entity, entity.PrimaryIdAttribute); metadataID = currentManyToManyRelationship.MetadataId.Value; } else if (entityRelationship is OneToManyRelationshipMetadata) { isManyToMany = false; currentOneToManyRelationship = entityRelationship as OneToManyRelationshipMetadata; entity2 = GetEntityMetadata(areReferencingRelationships ? currentOneToManyRelationship.ReferencingEntity : currentOneToManyRelationship.ReferencedEntity); attribute2 = GetAttributeMetadata(entity2, areReferencingRelationships ? currentOneToManyRelationship.ReferencingAttribute : currentOneToManyRelationship.ReferencedAttribute); attribute = GetAttributeMetadata(entity, areReferencingRelationships ? currentOneToManyRelationship.ReferencedAttribute : currentOneToManyRelationship.ReferencingAttribute); metadataID = currentOneToManyRelationship.MetadataId.Value; } // Verify relationship is either ManyToManyMetadata or OneToManyMetadata if (entity2 != null) { if (_processedRelationships.Contains(metadataID)) { // Skip relationships we have already drawn continue; } else { // Record we are drawing this relationship _processedRelationships.Add(metadataID); // Define convenience variables based upon the direction of referencing with respect to the core entity. VisioApi.Shape rect2; // Do not draw relationships involving the entity itself, SystemUser, BusinessUnit, // or those that are intentionally excluded. string selectedEntityFound = selectedEntitiesNames.Find(en => en == entity2.LogicalName); if (String.Compare(entity2.LogicalName, "systemuser", true) != 0 && String.Compare(entity2.LogicalName, "businessunit", true) != 0 && String.Compare(entity2.LogicalName, rect.Name, true) != 0 && (selectedEntityFound != null) && String.Compare(entity.LogicalName, "systemuser", true) != 0 && String.Compare(entity.LogicalName, "businessunit", true) != 0) { // Either find or create a shape that represents this secondary entity, and add the name of // the involved attribute to the shape's text. try { rect2 = rect.ContainingPage.Shapes.get_ItemU(entity2.LogicalName); int processedEntity2Index = _processedEntities.FindIndex(pe => pe.entityName == entity2.LogicalName); if (!_processedEntities[processedEntity2Index].attributes.Exists(a => a == attribute2.LogicalName) && dbp.showForeignKeys) { rect2.get_CellsSRC(VISIO_SECTION_OJBECT_INDEX, (short)VisioApi.VisRowIndices.visRowXFormOut, (short)VisioApi.VisCellIndices.visXFormHeight).ResultIU += 0.25; rect2.Text += getAttributeValue(attribute2); _processedEntities[processedEntity2Index].attributes.Add(attribute2.LogicalName); } } catch (System.Runtime.InteropServices.COMException) { rect2 = DrawEntityRectangle(rect.ContainingPage, entity2); int processedEntity2Index = _processedEntities.FindIndex(pe => pe.entityName == entity2.LogicalName); if (!_processedEntities[processedEntity2Index].attributes.Exists(a => a == attribute2.LogicalName) && dbp.showForeignKeys) { rect2.Text += getAttributeValue(attribute2); _processedEntities[processedEntity2Index].attributes.Add(attribute2.LogicalName); } } // Add the name of the involved attribute to the core entity's text, if not already present. int processedEntityIndex = _processedEntities.FindIndex(pe => pe.entityName == entity.LogicalName); if (!_processedEntities[processedEntityIndex].attributes.Exists(a => a == attribute.LogicalName) && dbp.showForeignKeys) { rect.get_CellsSRC(VISIO_SECTION_OJBECT_INDEX, (short)VisioApi.VisRowIndices.visRowXFormOut, (short)VisioApi.VisCellIndices.visXFormHeight).ResultIU += HEIGHT; rect.Text += getAttributeValue(attribute); _processedEntities[processedEntityIndex].attributes.Add(attribute.LogicalName); } // Draw the directional, dynamic connector between the two entity shapes. if (areReferencingRelationships) { DrawDirectionalDynamicConnector(rect, rect2, isManyToMany, entityRelationship.SchemaName); } else { DrawDirectionalDynamicConnector(rect2, rect, isManyToMany, entityRelationship.SchemaName); } } } } } }
private void LoadFields(string entity) { EntityMetadata metadata = null; if (_entities.TryGetValue(entity, out metadata)) { var displayName = GetEntityDisplayName(metadata); WorkAsync(new WorkAsyncInfo { Message = string.Format($"Loading {displayName}..."), Work = (worker, args) => { args.Result = CrmHelper.GetEntityAttributes(Service, entity); }, PostWorkCallBack = (args) => { if (args.Error != null) { MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var result = args.Result as RetrieveMetadataChangesResponse; if (result != null) { var entityMetadata = (EntityMetadataCollection)result.EntityMetadata; if (entityMetadata.Count == 1) { var entMetadata = entityMetadata[0]; _attributes = entMetadata.Attributes.ToDictionary(m => m.LogicalName); var attributes = entMetadata.Attributes.Select(a => new AttributeMetadataModel() { DisplayName = GetAttributeDisplayName(a), LogicalName = a.LogicalName, IsView = a.IsPrimaryName ?? false }) .OrderBy(a => a.DisplayName) .ThenBy(a => a.LogicalName).ToList(); // use unbound grid to support column sorting foreach (var item in attributes) { var rowIndex = dgvFields.Rows.Add(item.DisplayName, item.LogicalName, item.IsMatch, item.IsView); // disable matching on primary id column if (_attributes[item.LogicalName].IsPrimaryId ?? false) { DisableCheckboxCell(dgvFields.Rows[rowIndex].Cells["colMatch"] as DataGridViewCheckBoxCell); } if (!(_attributes[item.LogicalName].IsValidForRead ?? true)) { DisableCheckboxCell(dgvFields.Rows[rowIndex].Cells["colMatch"] as DataGridViewCheckBoxCell); DisableCheckboxCell(dgvFields.Rows[rowIndex].Cells["colView"] as DataGridViewCheckBoxCell); } } } else { MessageBox.Show("Metadata not found for entity " + displayName, "Load attribute metadata", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Metadata not found for entity " + displayName, "Load attribute metadata", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }); } }
public static void SetAttributeCollection(this EntityMetadata entityMetadata, AttributeMetadata[] attributes) { //AttributeMetadata is internal set in a sealed class so... just doing this entityMetadata.GetType().GetProperty("Attributes").SetValue(entityMetadata, attributes, null); }
public AnnotationDeleteResult(IAnnotation note, CrmEntityPermissionProvider provider, OrganizationServiceContext context, EntityMetadata entityMetadata = null) { Annotation = note; if (note.Entity == null) { return; } PermissionsExist = provider.PermissionsExist; PermissionGranted = provider.TryAssert(context, CrmEntityPermissionRight.Delete, note.Entity, entityMetadata, regarding: note.Regarding); }
public static EntityMetadata DeSerialiseEntityMetadata(EntityMetadata item, XmlNode entity) { foreach (XmlNode node in entity.ChildNodes) { Dictionary <string, object> itemValues = (Dictionary <string, object>)(object) item; string localName = XmlHelper.GetLocalName(node); string fieldName = localName.Substr(0, 1).ToLowerCase() + localName.Substr(1); // This converts to camel case so we can use the import types from script# // Check nil and don't set the value to save time/space if (node.Attributes.Count == 1 && node.Attributes[0].Name == "i:nil") { continue; } switch (localName) { // String values case "IconLargeName": case "IconMediumName": case "IconSmallName": case "LogicalName": case "PrimaryIdAttribute": case "PrimaryNameAttribute": case "RecurrenceBaseEntityLogicalName": case "ReportViewName": case "SchemaName": case "PrimaryImageAttribute": itemValues[fieldName] = XmlHelper.GetNodeTextValue(node); break; // Bool values case "AutoRouteToOwnerQueue": case "CanBeInManyToMany": case "CanBePrimaryEntityInRelationship": case "CanBeRelatedEntityInRelationship": case "CanCreateAttributes": case "CanCreateCharts": case "CanCreateForms": case "CanCreateViews": case "CanModifyAdditionalSettings": case "CanTriggerWorkflow": case "IsActivity": case "IsActivityParty": case "IsAuditEnabled": case "IsAvailableOffline": case "IsChildEntity": case "IsConnectionsEnabled": case "IsCustomEntity": case "IsCustomizable": case "IsDocumentManagementEnabled": case "IsDuplicateDetectionEnabled": case "IsEnabledForCharts": case "IsImportable": case "IsIntersect": case "IsMailMergeEnabled": case "IsManaged": case "IsReadingPaneEnabled": case "IsRenameable": case "IsValidForAdvancedFind": case "IsValidForQueue": case "IsVisibleInMobile": itemValues[fieldName] = Attribute.DeSerialise(node, AttributeTypes.Boolean_); break; // Int Values case "ActivityTypeMask": case "ObjectTypeCode": itemValues[fieldName] = Attribute.DeSerialise(node, AttributeTypes.Int_); break; case "Attributes": item.Attributes = new List <AttributeMetadata>(); foreach (XmlNode childNode in node.ChildNodes) { AttributeMetadata a = new AttributeMetadata(); item.Attributes.Add(MetadataSerialiser.DeSerialiseAttributeMetadata(a, childNode)); } break; ////Label case "Description": case "DisplayCollectionName": case "DisplayName": Label label = new Label(); itemValues[fieldName] = MetadataSerialiser.DeSerialiseLabel(label, node); break; } } return(item); }
private async Task StartWatcherInternal() { try { LogMessage("SourceWatcher : Start"); DirectoryInfo srcDirectoryInfo = new DirectoryInfo(_localScriptsPath); foreach (DirectoryInfo srcSubDirInfo in srcDirectoryInfo.GetDirectories()) { LogMessage($"Scanning in folder : {srcSubDirInfo.FullName}"); var files = srcSubDirInfo.GetFiles().OrderByDescending(p => p.LastWriteTimeUtc); var csxFile = files.FirstOrDefault(p => p.Extension.Equals(".csx", StringComparison.OrdinalIgnoreCase)); var asmFile = files.FirstOrDefault(p => p.Extension.Equals(".dll", StringComparison.OrdinalIgnoreCase)); var packageJsonFile = files.FirstOrDefault(p => p.Name.Equals("package.json", StringComparison.CurrentCultureIgnoreCase)); var metadataFile = files.FirstOrDefault(p => p.Name.Equals("metadata.json", StringComparison.OrdinalIgnoreCase)); string scriptText = string.Empty; if (csxFile != default(FileInfo)) { scriptText = await File.ReadAllTextAsync(csxFile.FullName); } EntityType entityType = EntityType.Signal; if (packageJsonFile != null) { var configFile = await FileHelper.GetFileContentAsync(packageJsonFile.FullName); var config = JsonConvert.DeserializeObject <PackageConfig>(configFile); entityType = string.Equals(config.Type, "gist", StringComparison.OrdinalIgnoreCase) ? EntityType.Gist : EntityType.Signal; } string metadata = string.Empty; if (metadataFile != default(FileInfo)) { metadata = await File.ReadAllTextAsync(metadataFile.FullName); } EntityMetadata scriptMetadata = new EntityMetadata(scriptText, entityType, metadata); EntityInvoker invoker = new EntityInvoker(scriptMetadata); if (asmFile == default(FileInfo)) { LogWarning($"No Assembly file (.dll). Skipping cache update"); continue; } LogMessage($"Loading assembly : {asmFile.FullName}"); Assembly asm = Assembly.LoadFrom(asmFile.FullName); if (_invokerDictionary.TryGetValue(entityType, out ICache <string, EntityInvoker> cache)) { invoker.InitializeEntryPoint(asm); LogMessage($"Updating cache with new invoker with id : {invoker.EntryPointDefinitionAttribute.Id}"); cache.AddOrUpdate(invoker.EntryPointDefinitionAttribute.Id, invoker); } else { LogMessage($"No invoker cache exist for {entityType}"); } } } catch (Exception ex) { LogException(ex.Message, ex); } finally { LogMessage("SourceWatcher : End"); } }
public void Update(EntityMetadata meta) { UpdateMeta(meta.Metadata); }
/// <summary> /// returns entity data for a given entity /// </summary> /// <param name="requestType">What type of entity data do you want</param> /// <param name="entityName">name of the entity to query</param> /// <returns></returns> public EntityMetadata GetEntityMetadata(EntityFilters requestType, String entityName) { EntityMetadata entityMetadata = null; ValidateMetadata(); // if the update is for an existing item, and its for sub components, update just the item, do not reset the overall cache update bool bSelectiveUpdate = false; if (!_entityMetadataCache.TryGetValue(entityName, out entityMetadata)) { entityMetadata = null; } if (entityMetadata != null && (int)requestType > (int)EntityFilters.Default) { switch (requestType) { case EntityFilters.All: if (entityMetadata.Attributes == null || entityMetadata.Privileges == null || (entityMetadata.ManyToOneRelationships == null || entityMetadata.OneToManyRelationships == null || entityMetadata.ManyToManyRelationships == null)) { bSelectiveUpdate = true; } break; case EntityFilters.Attributes: if (entityMetadata.Attributes == null) { bSelectiveUpdate = true; } break; case EntityFilters.Privileges: if (entityMetadata.Privileges == null) { bSelectiveUpdate = true; } break; case EntityFilters.Relationships: if (entityMetadata.ManyToOneRelationships == null || entityMetadata.OneToManyRelationships == null || entityMetadata.ManyToManyRelationships == null) { bSelectiveUpdate = true; } break; default: break; } } if (entityMetadata == null || bSelectiveUpdate) { RetrieveEntityRequest request = new RetrieveEntityRequest(); request.LogicalName = entityName; request.EntityFilters = requestType; RetrieveEntityResponse response = (RetrieveEntityResponse)svcAct.CdsCommand_Execute(request, "GetEntityMetadata"); if (response != null) { entityMetadata = response.EntityMetadata; if (!_entityMetadataCache.ContainsKey(entityName)) { _entityMetadataCache.TryAdd(entityName, entityMetadata); } else { _entityMetadataCache[entityName] = entityMetadata; } if (!bSelectiveUpdate) { TouchMetadataDate(); } } } return(entityMetadata); }
/// <summary> /// Ideally, we wouldn't generate any entities, but we must in order to leverage /// the logic in CrmSvcUtil. If an entity which contains a custom OptionSet /// attribute is not generated, then the custom OptionSet will not be generated, /// either. We will remove these in our ICustomizeCodeDomService implementation. /// </summary> public bool GenerateEntity(EntityMetadata entityMetadata, IServiceProvider services) { return(EntityFilterService.GenerateEntity(entityMetadata, services)); }
public DetectorCompilationService(EntityMetadata entityMetadata, ScriptOptions scriptOptions) : base(entityMetadata, scriptOptions) { }
protected override SqlCommand[] BuildCreateTableCommands(ISyntaxProvider syntax, EntityMetadata metadata, IProperty[] properties) { var sb = new StringBuilder(); sb.AppendFormat("create table {0}\n(\n", Quote(syntax, metadata.TableName)); var count = properties.Length; for (var i = 0; i < count; i++) { AppendFieldToBuilder(sb, syntax, properties[i]); if (i != count - 1) { sb.Append(","); } sb.AppendLine(); } //主键 var primaryPeoperties = properties.Where(s => s.Info.IsPrimaryKey).ToArray(); if (primaryPeoperties.Length > 0) { sb.Append(","); sb.AppendFormat("constraint PK_{0} primary key (", Quote(syntax, metadata.TableName)); for (var i = 0; i < primaryPeoperties.Length; i++) { if (i != 0) { sb.Append(","); } sb.Append(Quote(syntax, primaryPeoperties[i].Info.FieldName)); } sb.Append(")"); } sb.Append(")\n"); return(new SqlCommand[] { sb.ToString() }); }
/// <summary> /// Draw an "Entity" Rectangle /// </summary> /// <param name="page">The Page on which to draw</param> /// <param name="entity">The entity to draw</param> /// <returns>The newly drawn rectangle</returns> private VisioApi.Shape DrawEntityRectangle(VisioApi.Page page, EntityMetadata entity) { VisioApi.Shape rect = page.DrawRectangle(X_POS1, Y_POS1, X_POS2, Y_POS2); rect.Name = entity.LogicalName; if (dbp.entityLabelDisplay == 1) { rect.Text = entity.DisplayName.UserLocalizedLabel.Label + " "; } else if (dbp.entityLabelDisplay == 2) { rect.Text = entity.DisplayName.UserLocalizedLabel.Label + " [" + entity.LogicalName + "] "; } else { rect.Text = entity.LogicalName + " "; } // Determine the shape fill color based on entity ownership. string fillColor; switch (entity.OwnershipType.Value) { case OwnershipTypes.BusinessOwned: fillColor = "RGB(255,202,176)"; // Light orange break; case OwnershipTypes.OrganizationOwned: fillColor = "RGB(255,255,176)"; // Light yellow break; case OwnershipTypes.UserOwned: fillColor = "RGB(204,255,204)"; // Light green break; default: fillColor = "RGB(255,255,255)"; // White break; } // Set the fill color, placement properties, and line weight of the shape. rect.get_CellsSRC(VISIO_SECTION_OJBECT_INDEX, (short)VisioApi.VisRowIndices.visRowMisc, (short)VisioApi.VisCellIndices.visLOFlags).Formula = ((int)VisioApi.VisCellVals.visLOFlagsPlacable).ToString(); if (dbp.showOwnership) { rect.get_CellsSRC(VISIO_SECTION_OJBECT_INDEX, (short)VisioApi.VisRowIndices.visRowFill, (short)VisioApi.VisCellIndices.visFillForegnd).FormulaU = fillColor; } // Update the style of the entity name VisioApi.Characters characters = rect.Characters; characters.Begin = 0; characters.End = entity.LogicalName.Length; characters.set_CharProps((short)VisioApi.VisCellIndices.visCharacterStyle, (short)VisioApi.VisCellVals.visBold); characters.set_CharProps((short)VisioApi.VisCellIndices.visCharacterColor, (short)VisioApi.VisDefaultColors.visDarkBlue); characters.set_CharProps((short)VisioApi.VisCellIndices.visCharacterSize, NAME_CHARACTER_SIZE); //set the font family of the text to segoe for the visio 2013. if (VersionName == "15.0") { characters.set_CharProps((short)VisioApi.VisCellIndices.visCharacterFont, (short)FONT_STYLE); } _processedEntities.Add(new ProcessedEntity { entityName = entity.LogicalName, attributes = new List <string> { entity.PrimaryIdAttribute } }); //Add Primary Key attribute if (dbp.showPrimaryKeys) { rect.get_CellsSRC(VISIO_SECTION_OJBECT_INDEX, (short)VisioApi.VisRowIndices.visRowXFormOut, (short)VisioApi.VisCellIndices.visXFormHeight).ResultIU += HEIGHT; AttributeMetadata attribute = GetAttributeMetadata(entity, entity.PrimaryIdAttribute); rect.Text += getAttributeValue(attribute) + " [PK]"; } return(rect); }
public AggregationRoot(EntitySet set, AggregationConfig config, EntityMetadata metadata) : base(set, config) { _result = new AggregationResult(metadata, config, 0); }
public NoteRecord(IAnnotation annotation, DataAdapterDependencies dataAdapterDependencies, CrmEntityPermissionProvider provider, EntityMetadata entityMetadata = null, bool readGranted = false) : base(annotation.Entity, dataAdapterDependencies.GetServiceContext(), provider, entityMetadata, readGranted) { if (annotation == null) { throw new ArgumentNullException("annotation"); } SetPropertyValues(annotation, dataAdapterDependencies); }
protected override SqlCommand[] BuildAddFieldCommands(ISyntaxProvider syntax, EntityMetadata metadata, IProperty[] properties) { var sb = new StringBuilder(); sb.AppendFormat("alter table {0} add ", Quote(syntax, metadata.TableName)); var count = properties.Length; for (var i = 0; i < count; i++) { AppendFieldToBuilder(sb, syntax, properties[i]); if (i != count - 1) { sb.Append(","); } sb.AppendLine(); } return(new SqlCommand[] { sb.ToString() }); }