public static string GetDataServiceCrmAssociationSetUri(this Entity entity, string portalName, Relationship relationship, string serviceBaseUri) { if (string.IsNullOrEmpty(relationship.SchemaName)) { return(null); } try { var portal = PortalCrmConfigurationManager.CreatePortalContext(portalName); var context = portal.ServiceContext; EntitySetInfo entitySetInfo; RelationshipInfo associationInfo; if (!OrganizationServiceContextInfo.TryGet(context, entity, out entitySetInfo) || !entitySetInfo.Entity.RelationshipsBySchemaName.TryGetValue(relationship, out associationInfo)) { return(null); } return(GetDataServicePropertyUri(entity, associationInfo.Property.Name, serviceBaseUri)); } catch (InvalidOperationException) { return(null); } }
public IEntityAttributeUpdate Create(OrganizationServiceContext serviceContext, Entity entity, string attributeLogicalName) { EntitySetInfo entitySetInfo; AttributeInfo attributeInfo; if (OrganizationServiceContextInfo.TryGet(serviceContext, entity, out entitySetInfo) && entitySetInfo.Entity.EntityType == entity.GetType() && entitySetInfo.Entity.AttributesByLogicalName.TryGetValue(attributeLogicalName, out attributeInfo)) { if (entitySetInfo.Entity.PrimaryKeyProperty.CrmPropertyAttribute.LogicalName == attributeInfo.CrmPropertyAttribute.LogicalName) { throw new InvalidOperationException("Can't create an update for the primary key attribute {0}.".FormatWith(attributeLogicalName)); } return(new ReflectionEntityAttributeUpdate(entity, attributeInfo)); } var attributeMetadata = _getAttributeMetadata(entity.LogicalName, attributeLogicalName); if (attributeMetadata != null) { if (attributeMetadata.IsPrimaryId.GetValueOrDefault()) { throw new InvalidOperationException("Can't create an update for the primary key attribute {0}.".FormatWith(attributeLogicalName)); } return(new MetadataEntityAttributeUpdate(entity, attributeMetadata)); } ADXTrace.Instance.TraceWarning(TraceCategory.Application, @"Unable to create CMS update for entity ""{0}"", attribute ""{1}"". Discarding value.".FormatWith(entity.LogicalName, attributeLogicalName)); return(new NonexistentAttributeUpdate(entity)); }
protected override void OnLoad(EventArgs args) { Entity snippet; var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName); var context = portal.ServiceContext; var website = portal.Website; if (TryGetSnippetEntity(context, website, SnippetName, out snippet)) { DataItem = snippet; if (string.IsNullOrEmpty(PropertyName)) { EntitySetInfo entitySetInfo; if (OrganizationServiceContextInfo.TryGet(context, snippet, out entitySetInfo)) { var attributeInfo = entitySetInfo.Entity.AttributesByLogicalName["adx_value"]; PropertyName = attributeInfo.Property.Name; } } } else { DataItem = DefaultText; } base.OnLoad(args); }
private static EntitySetInfo GetEntitySetInfo(Type crmDataContextType, string crmEntityName) { EntitySetInfo entitySetInfo; OrganizationServiceContextInfo.TryGet(crmDataContextType, crmEntityName, out entitySetInfo); return(entitySetInfo); }
private static string GetPrimaryKeyPropertyName(Type crmDataContextType, string crmEntityName) { EntitySetInfo entitySetInfo; if (!OrganizationServiceContextInfo.TryGet(crmDataContextType, crmEntityName, out entitySetInfo) || entitySetInfo.Entity.PrimaryKeyProperty == null) { return(null); } return(entitySetInfo.Entity.PrimaryKeyProperty.Property.Name); }
private static string GetPropertyName(OrganizationServiceContext context, Entity entity, string logicalName) { EntitySetInfo esi; AttributeInfo ai; if (OrganizationServiceContextInfo.TryGet(context, entity, out esi) && esi.Entity.AttributesByLogicalName.TryGetValue(logicalName, out ai)) { return(ai.Property.Name); } throw new InvalidOperationException("The '{0}' entity does not contain an attribute with the logical name '{1}'.".FormatWith(entity, logicalName)); }
private Type GetEntityType(string entityLogicalName) { var portal = PortalContext; var context = portal.ServiceContext; EntitySetInfo info; if (OrganizationServiceContextInfo.TryGet(context.GetType(), entityLogicalName, out info)) { return(info.Entity.EntityType); } return(null); }
protected virtual string GetAttributeLogicalNameFromPropertyName(OrganizationServiceContext serviceContext, string entityLogicalName, string propertyName) { EntitySetInfo entitySetInfo; if (OrganizationServiceContextInfo.TryGet(serviceContext.GetType(), entityLogicalName, out entitySetInfo) && entitySetInfo.Entity != null) { AttributeInfo attributeInfo; if (entitySetInfo.Entity.AttributesByPropertyName.TryGetValue(propertyName, out attributeInfo) && attributeInfo.CrmPropertyAttribute != null) { return(attributeInfo.CrmPropertyAttribute.LogicalName); } } return(propertyName.ToLowerInvariant()); }
private static Entity CreateEntityOfType(OrganizationServiceContext serviceContext, string entityLogicalName) { EntitySetInfo entitySetInfo; if (OrganizationServiceContextInfo.TryGet(serviceContext.GetType(), entityLogicalName, out entitySetInfo)) { try { return((Entity)Activator.CreateInstance(entitySetInfo.Entity.EntityType)); } catch { return(new Entity(entityLogicalName)); } } return(new Entity(entityLogicalName)); }
/// <summary> /// For internal use only. /// </summary> /// <param name="context"></param> /// <param name="entity"></param> /// <param name="sourceEntityName"></param> /// <param name="websiteID"></param> /// <returns></returns> public static bool TryGetWebsiteIDFromParentLinkForEntityInPendingChanges(OrganizationServiceContext context, Entity entity, string sourceEntityName, out EntityReference websiteID) { var portalContext = context as CrmOrganizationServiceContext; if (portalContext == null) { throw new ArgumentException("The 'context' object must be of the type '{0}'.".FormatWith(typeof(CrmOrganizationServiceContext))); } // Get AddLink changes that reference our new entity. var relevantChanges = portalContext.Log.Where(l => l.Operation == CrmOrganizationServiceContext.UpdatableOperation.AddReferenceToCollection && l.Resource == entity && l.Target.LogicalName == sourceEntityName); foreach (var change in relevantChanges) { EntitySetInfo entitySetInfo; RelationshipInfo crmAssociationInfo; if (!OrganizationServiceContextInfo.TryGet(context.GetType(), change.Target.LogicalName, out entitySetInfo) || !entitySetInfo.Entity.RelationshipsByPropertyName.TryGetValue(change.PropertyName, out crmAssociationInfo)) { continue; } // If it's a 1-to-many relationship, we've found a parent link. if (crmAssociationInfo.IsCollection) { websiteID = change.Target.GetAttributeValue <EntityReference>("adx_websiteid"); return(true); } } websiteID = null; return(false); }
protected static Entity GetServiceOperationEntityByID(OrganizationServiceContext context, string entitySet, Guid entityID) { OrganizationServiceContextInfo contextInfo; EntitySetInfo entitySetInfo; if (!OrganizationServiceContextInfo.TryGet(context.GetType(), out contextInfo) || !contextInfo.EntitySetsByPropertyName.TryGetValue(entitySet, out entitySetInfo)) { throw new DataServiceException(404, @"Entity set ""{0}"" is not exposed by this service.".FormatWith(entitySet)); } var entityType = entitySetInfo.Entity.EntityType; if (entityType == null) { throw new DataServiceException(404, @"Unable to retrieve data type for entity set ""{0}"".".FormatWith(entitySet)); } var entityName = entitySetInfo.Entity.EntityLogicalName.LogicalName; var entityPrimaryKeyName = entitySetInfo.Entity.PrimaryKeyProperty.CrmPropertyAttribute.LogicalName; var dynamicEntityWrapper = context.CreateQuery(entityName) .Where(e => e.GetAttributeValue <Guid>(entityPrimaryKeyName) == entityID) .FirstOrDefault(); if (dynamicEntityWrapper == null) { throw new DataServiceException(404, @"Entity with ID ""{0}"" not found in entity set ""{1}"".".FormatWith(entityID, entitySet)); } var entity = dynamicEntityWrapper; if (entity == null) { throw new DataServiceException(404, @"Entity with ID ""{0}"" not found in entity set ""{1}"".".FormatWith(entityID, entitySet)); } return(entity); }
public static string GetCrmEntitySetSchemaMap(this Type crmDataContextType, string crmEntityName) { return(ObjectCacheManager.Get("microsoft.xrm.portal:entity-schema-map:json:{0}:{1}".FormatWith(crmDataContextType.FullName, crmEntityName), cache => { EntitySetInfo entitySetInfo; if (!OrganizationServiceContextInfo.TryGet(crmDataContextType, crmEntityName, out entitySetInfo) || entitySetInfo.Entity == null || entitySetInfo.Entity.EntityLogicalName == null) { throw new InvalidOperationException(@"Unable to retrieve entity set information for entity name ""{0}"".".FormatWith(crmEntityName)); } var properties = entitySetInfo.Entity.AttributesByLogicalName.Values; var schemaMap = properties.ToDictionary(info => info.CrmPropertyAttribute.LogicalName, info => info.Property.Name); var json = schemaMap.SerializeByJson(new Type[] { }); return json; })); }
public virtual IEnumerable <SiteMapChildInfo> GetSiteMapChildren(OrganizationServiceContext context, string siteMapProvider, string startingNodeUrl, string cmsServiceBaseUri) { if (string.IsNullOrEmpty(siteMapProvider)) { throw new DataServiceException(400, "siteMapProvider cannot be null or empty"); } if (startingNodeUrl == null) { throw new DataServiceException(400, "startingNodeUrl cannot be null"); } var provider = SiteMap.Providers[siteMapProvider]; if (provider == null) { throw new DataServiceException(404, @"Site map provider with name ""{0}"" not found.".FormatWith(siteMapProvider)); } var startingNode = provider.FindSiteMapNode(startingNodeUrl); if (startingNode == null) { throw new DataServiceException(404, @"Starting site map node with URL ""{0}"" not found.".FormatWith(startingNodeUrl)); } var childInfos = new List <SiteMapChildInfo>(); foreach (SiteMapNode childNode in startingNode.ChildNodes) { var crmNode = childNode as CrmSiteMapNode; if (crmNode == null || crmNode.Entity == null) { continue; } var entity = context.MergeClone(crmNode.Entity); var info = new SiteMapChildInfo { Title = crmNode.Title, EntityUri = string.IsNullOrEmpty(cmsServiceBaseUri) ? entity.GetDataServiceUri() : entity.GetDataServiceUri(cmsServiceBaseUri), HasPermission = TryAssertCrmEntityRight(context, entity, CrmEntityRight.Change) }; EntitySetInfo entitySetInfo; AttributeInfo propertyInfo; if (!OrganizationServiceContextInfo.TryGet(context, entity, out entitySetInfo) || !entitySetInfo.Entity.AttributesByLogicalName.TryGetValue("adx_displayorder", out propertyInfo) || propertyInfo.Property.PropertyType != typeof(int?)) { continue; } info.DisplayOrder = (int?)propertyInfo.GetValue(entity); info.DisplayOrderPropertyName = propertyInfo.Property.Name; childInfos.Add(info); } return(childInfos); }
private static List <Tuple <string, string> > RemoveFiles(ICommandContext commandContext) { var errors = new List <Tuple <string, string> >(); var targetHashes = (commandContext.Parameters["targets[]"] ?? string.Empty).Split(','); if (!targetHashes.Any()) { return(errors); } var portal = commandContext.CreatePortalContext(); var website = portal.Website.ToEntityReference(); var security = commandContext.CreateSecurityProvider(); var dataServiceProvider = commandContext.CreateDependencyProvider().GetDependency <ICmsDataServiceProvider>(); foreach (var targetHash in targetHashes) { var serviceContext = commandContext.CreateServiceContext(); Entity target; if (!TryGetTargetEntity(serviceContext, targetHash, website, out target)) { errors.Add(new Tuple <string, string>(targetHash, ResourceManager.GetString("Unable_To_Retrieve_Target_Entity_For_Given_Hash_Error"))); continue; } try { OrganizationServiceContextInfo serviceContextInfo; EntitySetInfo entitySetInfo; if (dataServiceProvider != null && OrganizationServiceContextInfo.TryGet(serviceContext.GetType(), out serviceContextInfo) && serviceContextInfo.EntitySetsByEntityLogicalName.TryGetValue(target.LogicalName, out entitySetInfo)) { dataServiceProvider.DeleteEntity(serviceContext, entitySetInfo.Property.Name, target.Id); } else { if (!security.TryAssert(serviceContext, target, CrmEntityRight.Change)) { errors.Add(new Tuple <string, string>(GetDisplayName(target), ResourceManager.GetString("Delete_Permission_Denied_For_Target_Entity_Error"))); continue; } CrmEntityInactiveInfo inactiveInfo; if (CrmEntityInactiveInfo.TryGetInfo(target.LogicalName, out inactiveInfo)) { serviceContext.SetState(inactiveInfo.InactiveState, inactiveInfo.InactiveStatus, target); } else { serviceContext.DeleteObject(target); serviceContext.SaveChanges(); } } } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("{0} {1}", ResourceManager.GetString("Deleting_File_Exception"), e.ToString())); errors.Add(new Tuple <string, string>(GetDisplayName(target), e.Message)); } } return(errors); }
public override IEnumerable <SiteMapChildInfo> GetSiteMapChildren(OrganizationServiceContext context, string siteMapProvider, string startingNodeUrl, string cmsServiceBaseUri) { if (string.IsNullOrEmpty(siteMapProvider)) { throw new DataServiceException(400, "siteMapProvider cannot be null or empty."); } if (startingNodeUrl == null) { throw new DataServiceException(400, "startingNodeUrl cannot be null."); } var provider = SiteMap.Providers[siteMapProvider]; if (provider == null) { throw new DataServiceException(404, "Site map provider with name {0} not found.".FormatWith(siteMapProvider)); } var startingNode = provider.FindSiteMapNode(startingNodeUrl); if (startingNode == null) { throw new DataServiceException(404, "Starting site map node with URL {0} not found.".FormatWith(startingNodeUrl)); } var entityStartingNode = startingNode as CrmSiteMapNode; if (entityStartingNode == null || entityStartingNode.Entity == null) { return(new List <SiteMapChildInfo>()); } var childEntities = GetChildEntities(context, context.MergeClone(entityStartingNode.Entity)); var validChildEntities = childEntities .Select(e => context.MergeClone(e)) .Where(e => TryAssertCrmEntityRight(context, e, CrmEntityRight.Read)) .ToList(); validChildEntities.Sort(new EntitySiteMapDisplayOrderComparer()); var childInfos = validChildEntities.Select(e => { var info = new ExtendedSiteMapChildInfo { Title = GetEntityTitle(e), EntityUri = null, HasPermission = TryAssertCrmEntityRight(context, e, CrmEntityRight.Change), Id = e.Id, LogicalName = e.LogicalName, HiddenFromSiteMap = e.Attributes.Contains("adx_hiddenfromsitemap") && e.GetAttributeValue <bool?>("adx_hiddenfromsitemap").GetValueOrDefault(), }; EntitySetInfo entitySetInfo; AttributeInfo propertyInfo; if (OrganizationServiceContextInfo.TryGet(context, e, out entitySetInfo) && entitySetInfo.Entity.AttributesByLogicalName.TryGetValue("adx_displayorder", out propertyInfo) && propertyInfo.Property.PropertyType == typeof(int?)) { info.DisplayOrder = (int?)propertyInfo.GetValue(e); info.DisplayOrderPropertyName = propertyInfo.Property.Name; } return(info); }); return(childInfos.ToArray()); }
public override void AddEntityMetadata(string portalName, IEditableCrmEntityControl control, Control container, Entity entity) { if (control == null || container == null || entity == null) { return; } var serviceContext = PortalCrmConfigurationManager.CreateServiceContext(portalName); var portalContext = PortalCrmConfigurationManager.CreatePortalContext(portalName); var metadata = ((RetrieveEntityResponse)serviceContext.Execute(new RetrieveEntityRequest { EntityFilters = EntityFilters.Entity, LogicalName = entity.LogicalName })).EntityMetadata; var refetchedEntity = serviceContext.CreateQuery(entity.LogicalName).FirstOrDefault(e => e.GetAttributeValue <Guid>(metadata.PrimaryIdAttribute) == entity.Id); if (entity.LogicalName == "adx_weblinkset") { // Output the service reference for the web link set itself. AddEntityServiceReference(control, entity, entity.GetAttributeValue <string>("adx_name"), container); // Output the service reference for the child web links of the set. AddEntityAssocationSetServiceReferenceForWebLinkSet(control, entity, "adx_weblinkset_weblink".ToRelationship(), container); AddEntityAssocationSetServiceReference(portalName, control, entity, "adx_weblinkset_weblink".ToRelationship(), container, "xrm-entity-{0}-update-ref"); AddEntitySetSchemaMap(control, "adx_weblink", container); // Output the service reference and schema map for site web pages (required to create new web links). AddEntitySetServiceReference(control, "adx_webpage", container); AddEntitySetSchemaMap(control, "adx_webpage", container); string weblinkDeleteUriTemplate; if (TryGetCrmEntityDeleteDataServiceUriTemplate(control, "adx_weblink", out weblinkDeleteUriTemplate)) { AddServiceReference(control, weblinkDeleteUriTemplate, "xrm-uri-template xrm-entity-adx_weblink-delete-ref", container); } // Output the service reference and schema map for site publishing states (required to create new web links). AddEntitySetServiceReference(control, "adx_publishingstate", container); AddEntitySetSchemaMap(control, "adx_publishingstate", container); } else { string serviceUri; if (!TryGetDataServiceEntityUri(control, entity, out serviceUri)) { return; } // Add the service reference to the bound entity. container.Controls.Add(new HyperLink { CssClass = "xrm-entity-ref", NavigateUrl = VirtualPathUtility.ToAbsolute(serviceUri), Text = string.Empty }); string entityUrlServiceUri; // Add the service reference for getting the URL of the bound entity. if (TryGetCrmEntityUrlDataServiceUri(control, entity, out entityUrlServiceUri)) { AddServiceReference(control, entityUrlServiceUri, "xrm-entity-url-ref", container, "GetEntityUrl"); } var crmEntityName = entity.LogicalName; AddEntitySetSchemaMap(control, crmEntityName, container); // If the entity is "deletable", add a service reference for soft-delete of the entity. if (DeletableEntityNames.Contains(crmEntityName)) { string deleteServiceUri; if (TryGetCrmEntityDeleteDataServiceUri(control, entity, out deleteServiceUri)) { AddServiceReference(control, deleteServiceUri, "xrm-entity-delete-ref", container); } } if (FileAttachmentEntityNames.Contains(crmEntityName)) { string fileAttachmentServiceUri; if (TryGetCrmEntityFileAttachmentDataServiceUri(control, entity, out fileAttachmentServiceUri)) { AddServiceReference(control, fileAttachmentServiceUri, "xrm-entity-attachment-ref", container); } } // Add the service references on which the creation of various entities are dependent. foreach (var dependencyEntityName in DependencyEntityNames) { AddEntitySetServiceReference(control, dependencyEntityName, container); AddEntitySetSchemaMap(control, dependencyEntityName, container); } // Add the service reference URI Templates for the notes associated with given entity types. foreach (var fileAttachmentEntity in FileAttachmentEntityNames) { string uriTemplate; if (TryGetCrmEntityFileAttachmentDataServiceUriTemplate(control, fileAttachmentEntity, out uriTemplate)) { AddServiceReference(control, uriTemplate, "xrm-uri-template xrm-entity-{0}-attachment-ref".FormatWith(fileAttachmentEntity), container); } } // Add the service reference URI Templates for getting URLs for specific entity types. foreach (var urlEntityName in UrlEntityNames) { string uriTemplate; if (TryGetCrmEntityUrlDataServiceUriTemplate(control, urlEntityName, out uriTemplate)) { AddServiceReference(control, uriTemplate, "xrm-uri-template xrm-entity-{0}-url-ref".FormatWith(urlEntityName), container, "GetEntityUrl"); } } IEnumerable <Relationship> childAssociations; if (ChildAssociationsByEntityName.TryGetValue(crmEntityName, out childAssociations)) { foreach (var childAssociation in childAssociations) { AddEntityAssocationSetServiceReference(portalName, control, entity, childAssociation, container); } } Relationship parentalRelationship2; // Output the URL path of parent entity to the DOM (mostly to be read if the entity is deleted--the user // will then be redirected to the parent). if (_parentalRelationshipsByEntityName.TryGetValue(crmEntityName, out parentalRelationship2)) { var parent = refetchedEntity.GetRelatedEntity(serviceContext, parentalRelationship2); var urlProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency <IEntityUrlProvider>(); var parentPath = urlProvider.GetApplicationPath(serviceContext, parent ?? refetchedEntity); if (parentPath != null) { AddServiceReference(control, parentPath.AbsolutePath, "xrm-entity-parent-url-ref", container); } } // Output the sitemarkers of the current web page into the DOM. if (crmEntityName == "adx_webpage") { foreach (var siteMarker in refetchedEntity.GetRelatedEntities(serviceContext, "adx_webpage_sitemarker")) { var siteMarkerRef = new HtmlGenericControl("span"); siteMarkerRef.Attributes["class"] = "xrm-entity-adx_webpage_sitemarker"; siteMarkerRef.Attributes["title"] = siteMarker.GetAttributeValue <string>("adx_name"); container.Controls.Add(siteMarkerRef); } AddEntitySetSchemaMap(control, "adx_webfile", container); EntitySetInfo entitySetInfo; if (OrganizationServiceContextInfo.TryGet(GetCrmDataContextType(), "adx_communityforum", out entitySetInfo)) { AddEntitySetSchemaMap(control, "adx_communityforum", container); AddEntitySetServiceReference(control, "adx_communityforum", container); } if (OrganizationServiceContextInfo.TryGet(GetCrmDataContextType(), "adx_event", out entitySetInfo)) { AddEntitySetSchemaMap(control, "adx_event", container); AddEntitySetServiceReference(control, "adx_event", container); } AddEntitySetSchemaMap(control, "adx_shortcut", container); AddEntitySetServiceReference(control, "adx_webpage", container); AddEntitySetServiceReference(control, "adx_webfile", container); AddPublishingTransitionSetServiceReference(control, container); } if (entity.LogicalName == "adx_event") { AddEntitySetSchemaMap(control, "adx_eventschedule", container); AddPicklistMetadata(serviceContext, control, "adx_eventschedule", "adx_recurrence", container); } } var previewPermission = new PreviewPermission(portalContext.ServiceContext, portalContext.Website); if (previewPermission.IsPermitted) { var previewPermittedMetadata = new HtmlGenericControl("span"); previewPermittedMetadata.Attributes["class"] = "xrm-preview-permitted"; previewPermittedMetadata.Attributes["style"] = "display:none;"; container.Controls.Add(previewPermittedMetadata); } Relationship parentalRelationship; // Output the URL path of parent entity to the DOM (mostly to be read if the entity is deleted--the user // will then be redirected to the parent). if (_parentalRelationshipsByEntityName.TryGetValue(entity.LogicalName, out parentalRelationship)) { var parent = refetchedEntity.GetRelatedEntity(serviceContext, parentalRelationship); var urlProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency <IEntityUrlProvider>(); var parentPath = urlProvider.GetApplicationPath(serviceContext, parent ?? refetchedEntity); if (parentPath != null) { AddServiceReference(control, parentPath.AbsolutePath, "xrm-adx-entity-parent-url-ref", container); } } }