private static Entity CreateInvoiceFromOrder(OrganizationServiceContext context, Guid salesOrderId) { ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); var convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = salesOrderId, ColumnSet = invoiceColumns }; var convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)context.Execute(convertOrderRequest); var invoice = convertOrderResponse.Entity; var setStateRequest = new SetStateRequest() { EntityMoniker = invoice.ToEntityReference(), State = new OptionSetValue(2), Status = new OptionSetValue(100001) }; var setStateResponse = (SetStateResponse)context.Execute(setStateRequest); invoice = context.CreateQuery("invoice").Where(i => i.GetAttributeValue <Guid>("invoiceid") == convertOrderResponse.Entity.Id).FirstOrDefault(); return(invoice); }
public void SetState(T entity, int stateValue) { var request = new SetStateRequest { State = new OptionSetValue(stateValue), EntityMoniker = new EntityReference(entity.LogicalName, entity.Id) }; service.Execute(request); }
public static Entity GetOrganizationEntity(this OrganizationServiceContext serviceContext, string[] columns = null) { // when we make a switch to 2015 sdk, we should just replace this with the new RetrieveOrganizationRequest/Response. if (columns == null) { columns = new[] { "name" }; } return(((RetrieveResponse)serviceContext.Execute(new RetrieveRequest { ColumnSet = new ColumnSet(columns), Target = new EntityReference("organization", ((WhoAmIResponse)serviceContext.Execute(new WhoAmIRequest())).OrganizationId) })).Entity); }
private static IEnumerable <Entity> FetchEntities(OrganizationServiceContext serviceContext, Fetch fetch) { if (fetch == null) { return(Enumerable.Empty <Entity>()); } var entityResult = new List <Entity>(); fetch.PageNumber = 1; while (true) { var response = (RetrieveMultipleResponse)serviceContext.Execute(fetch.ToRetrieveMultipleRequest()); entityResult.AddRange(response.EntityCollection.Entities); if (!response.EntityCollection.MoreRecords || string.IsNullOrEmpty(response.EntityCollection.PagingCookie)) { break; } fetch.PageNumber++; fetch.PagingCookie = response.EntityCollection.PagingCookie; } return(entityResult); }
/// <summary> /// Retrieve the product count for a specified campaign /// </summary> /// <param name="serviceContext">OrganizationServiceContext</param> /// <param name="campaignId">Campaign ID</param> /// <returns>Product count</returns> public static int FetchCampaignProductCount(this OrganizationServiceContext serviceContext, Guid campaignId) { var fetchXml = XDocument.Parse(@" <fetch mapping=""logical"" aggregate=""true""> <entity name=""product""> <attribute name=""productid"" aggregate=""count"" alias=""count"" /> <link-entity name=""campaignitem"" from=""entityid"" to=""productid"" visible=""false"" link-type=""outer""> <filter type=""and""> <condition attribute=""campaignid"" operator=""eq"" /> </filter> </link-entity> </entity> </fetch>" ); var campaignIdAttribute = fetchXml.XPathSelectElement("//condition[@attribute='campaignid']"); if (campaignIdAttribute == null) { throw new InvalidOperationException("Unable to select the campaignid filter element."); } campaignIdAttribute.SetAttributeValue("value", campaignId.ToString()); var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.ToString()) }); return((int)response.EntityCollection.Entities.First().GetAttributeValue <AliasedValue>("count").Value); }
/// <summary> /// Retrieve the review count for a specified product /// </summary> /// <param name="serviceContext">OrganizationServiceContext</param> /// <param name="productId">Product ID</param> /// <returns>Review count</returns> public static int FetchProductReviewCount(this OrganizationServiceContext serviceContext, Guid productId) { var fetchXml = XDocument.Parse(@" <fetch mapping=""logical"" aggregate=""true""> <entity name=""adx_review""> <attribute name=""adx_product"" aggregate=""count"" alias=""count"" /> <filter type=""and""> <condition attribute=""adx_product"" operator=""eq"" /> <condition attribute=""statecode"" operator=""eq"" value=""0"" /> <condition attribute=""adx_publishtoweb"" operator=""eq"" value=""1"" /> </filter> </entity> </fetch>" ); var productIdAttribute = fetchXml.XPathSelectElement("//condition[@attribute='adx_product']"); if (productIdAttribute == null) { throw new InvalidOperationException("Unable to select the adx_product filter element."); } productIdAttribute.SetAttributeValue("value", productId.ToString()); var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.ToString()) }); return((int)response.EntityCollection.Entities.First().GetAttributeValue <AliasedValue>("count").Value); }
/// <summary> /// Retrieve the product count for a specified brand. /// </summary> /// <param name="serviceContext"></param> /// <param name="brandId">The Product (product) brand (adx_brandid).</param> /// <returns></returns> public static int FetchBrandProductCount(this OrganizationServiceContext serviceContext, Guid brandId) { var fetchXml = XDocument.Parse(@" <fetch mapping=""logical"" aggregate=""true""> <entity name=""product""> <attribute name=""productid"" aggregate=""count"" alias=""count"" /> <filter type=""and""> <condition attribute=""adx_brand"" operator=""eq"" /> <condition attribute=""statecode"" operator=""eq"" value=""0"" /> </filter> </entity> </fetch>" ); var vendorNameAttribute = fetchXml.XPathSelectElement("//condition[@attribute='adx_brand']"); if (vendorNameAttribute == null) { throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_brand filter")); } vendorNameAttribute.SetAttributeValue("value", brandId.ToString()); var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.ToString()) }); return(response.EntityCollection.Entities.First().GetAttributeAliasedValue <int>("count")); }
protected static bool TryGetPicklistOptions(OrganizationServiceContext serviceContext, string entityName, string propertyName, out Dictionary <int, string> options) { options = null; try { var response = (RetrieveEntityResponse)serviceContext.Execute(new RetrieveEntityRequest { LogicalName = entityName, EntityFilters = EntityFilters.Attributes }); var attribute = response.EntityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == propertyName) as PicklistAttributeMetadata; if (attribute == null) { return(false); } options = attribute.OptionSet.Options .Where(o => o.Value.HasValue) .ToDictionary(o => o.Value.Value, o => o.Label.GetLocalizedLabelString()); return(true); } catch { return(false); } }
private static string GetPrimaryIdAttributeLogicalName(OrganizationServiceContext serviceContext, string entityLogicalName) { if (serviceContext == null) { throw new ArgumentNullException("serviceContext"); } var entityFilter = new MetadataFilterExpression(LogicalOperator.And); entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName)); var response = (RetrieveMetadataChangesResponse)serviceContext.Execute(new RetrieveMetadataChangesRequest { Query = new EntityQueryExpression { Criteria = entityFilter, Properties = new MetadataPropertiesExpression("LogicalName", "PrimaryIdAttribute") } }); var entity = response.EntityMetadata.FirstOrDefault(e => e.LogicalName == entityLogicalName); if (entity == null) { throw new InvalidOperationException(ResourceManager.GetString("PrimaryIdAttribute_For_Entity_Retrieve_Exception".FormatWith(entityLogicalName))); } return(entity.PrimaryIdAttribute); }
private bool FindAndDeactivateEntity(DateTime date) { using (var orgContext = new OrganizationServiceContext(this.service)) { var currencyFromCrm = (from i in orgContext.CreateQuery <sl_ExchangeRate>() where i.sl_RelevanceDate < date.ToUniversalTime().AddHours(_ToCrmUTCDate) && i.statecode == sl_ExchangeRateState.Active select i).ToList(); if (currencyFromCrm.Count == 0) { return(false); } // деактивация устаревших курсов State = Close foreach (var item in currencyFromCrm) { SetStateRequest deactivateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(sl_ExchangeRate.EntityLogicalName, item.Id), State = new OptionSetValue(1), Status = new OptionSetValue(-1) }; orgContext.Execute(deactivateRequest); } return(true); } }
private IQueryable <Entity> GetLookupRecords(string fetchXml, OrganizationServiceContext context) { var fetch = Fetch.Parse(fetchXml); var crmEntityPermissionProvider = new CrmEntityPermissionProvider(); crmEntityPermissionProvider.TryApplyRecordLevelFiltersToFetch(context, CrmEntityPermissionRight.Read, fetch); crmEntityPermissionProvider.TryApplyRecordLevelFiltersToFetch(context, CrmEntityPermissionRight.Append, fetch); // Apply Content Access Level filtering var contentAccessLevelProvider = new ContentAccessLevelProvider(); contentAccessLevelProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetch); // Apply Product filtering var productAccessProvider = new ProductAccessProvider(); productAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetch); var response = (RetrieveMultipleResponse)context.Execute(fetch.ToRetrieveMultipleRequest()); var data = response.EntityCollection; if (data == null || data.Entities == null) { return(null); } return(data.Entities.AsQueryable()); }
/// <summary> /// Get the data for the chart by executing the <see cref="Query"/>. If <see cref="EntityPermissionsEnabled"/> then the <see cref="CrmEntityPermissionProvider"/> is used to apply filters and links to the <see cref="Query"/> to provide record level security filtering. /// </summary> /// <param name="serviceContext">The <see cref="OrganizationServiceContext"/> to be used to make the service call to retrieve the data.</param> /// <returns>A collection of <see cref="Entity"/> records.</returns> private IEnumerable <Entity> RetrieveData(OrganizationServiceContext serviceContext) { if (this.Query == null) { return(Enumerable.Empty <Entity>()); } if (this.EntityPermissionsEnabled) { var crmEntityPermissionProvider = new CrmEntityPermissionProvider(); var result = crmEntityPermissionProvider.TryApplyRecordLevelFiltersToFetch(serviceContext, CrmEntityPermissionRight.Read, this.Query); this.EntityPermissionDenied = !result.GlobalPermissionGranted && !result.PermissionGranted; if (this.EntityPermissionDenied) { return(Enumerable.Empty <Entity>()); } } this.Query.NoLock = true; var response = (RetrieveMultipleResponse)serviceContext.Execute(this.Query.ToRetrieveMultipleRequest()); var data = response.EntityCollection.Entities; return(data); }
public ICollection GenerateFields(Control control) { var layoutXml = XElement.Parse(_savedQuery.GetAttributeValue <string>("layoutxml")); var cellNames = layoutXml.Element("row").Elements("cell").Select(cell => cell.Attribute("name")).Where(name => name != null); var fetchXml = XElement.Parse(_savedQuery.GetAttributeValue <string>("fetchxml")); var entityName = fetchXml.Element("entity").Attribute("name").Value; var response = _context.Execute(new RetrieveEntityRequest { LogicalName = entityName, EntityFilters = EntityFilters.Attributes }) as RetrieveEntityResponse; var attributeMetadatas = response.EntityMetadata.Attributes; var fields = from name in cellNames let attributeMetadata = attributeMetadatas.FirstOrDefault(metadata => metadata.LogicalName == name.Value) where attributeMetadata != null select new BoundField { DataField = name.Value, SortExpression = name.Value, HeaderText = attributeMetadata.DisplayName.UserLocalizedLabel.Label // MSBug #120122: No need to URL encode--encoding is handled by webcontrol rendering layer. }; return(fields.ToList()); }
protected void AssertStateTransitionIsValid(OrganizationServiceContext context, Entity entity, UpdateOperations operations) { // This is not an update of an existing entity (may be Add, or Delete) -- nothing to check. if (operations != UpdateOperations.Change) { return; } var response = (RetrieveResponse)context.Execute(new RetrieveRequest { Target = new EntityReference(entity.LogicalName, entity.Id), ColumnSet = new ColumnSet("adx_publishingstateid") }); var preUpdateEntity = response.Entity; // Publishing state has not changed -- nothing to check. if (entity.GetAttributeValue <EntityReference>("adx_publishingstateid") == preUpdateEntity.GetAttributeValue <EntityReference>("adx_publishingstateid")) { return; } var portalContext = PortalCrmConfigurationManager.CreatePortalContext(PortalName); var transitionSecurityProvider = PortalCrmConfigurationManager.CreateDependencyProvider().GetDependency <IPublishingStateTransitionSecurityProvider>(); transitionSecurityProvider.Assert( context, portalContext.Website, preUpdateEntity.GetAttributeValue <EntityReference>("adx_publishingstateid") == null ? Guid.Empty : preUpdateEntity.GetAttributeValue <EntityReference>("adx_publishingstateid").Id, entity.GetAttributeValue <EntityReference>("adx_publishingstateid") == null ? Guid.Empty : entity.GetAttributeValue <EntityReference>("adx_publishingstateid").Id); }
public static int FetchCount(this OrganizationServiceContext serviceContext, string entityLogicalName, string countAttributeLogicalName, Action <Action <string, string, string> > addFilterConditions, Action <Action <string, string, string> > addOrFilterConditions = null) { var fetchXml = XDocument.Parse(@" <fetch mapping=""logical"" aggregate=""true""> <entity> <attribute aggregate=""countcolumn"" distinct=""true"" alias=""count"" /> <filter type=""and"" /> <filter type=""or"" /> </entity> </fetch>" ); var entity = fetchXml.Descendants("entity").First(); entity.SetAttributeValue("name", entityLogicalName); entity.Descendants("attribute").First().SetAttributeValue("name", countAttributeLogicalName); var andFilter = entity.Descendants("filter").First(); addFilterConditions(andFilter.AddFetchXmlFilterCondition); if (addOrFilterConditions != null) { var orFilter = entity.Descendants("filter").Last(); addOrFilterConditions(orFilter.AddFetchXmlFilterCondition); } var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.ToString()) }); return(response.EntityCollection.Entities.First().GetAttributeAliasedValue <int>("count")); }
protected virtual bool TryAssertByCrmEntitySecurityProvider(OrganizationServiceContext context, EntityReference regardingId) { if (regardingId == null) { return(false); } // determine the primary ID attribute var request = new RetrieveEntityRequest { LogicalName = regardingId.LogicalName, EntityFilters = EntityFilters.Entity }; var response = context.Execute(request) as RetrieveEntityResponse; var primaryIdAttribute = response.EntityMetadata.PrimaryIdAttribute; var regarding = context.CreateQuery(regardingId.LogicalName).FirstOrDefault(e => e.GetAttributeValue <Guid>(primaryIdAttribute) == regardingId.Id); if (regarding == null) { return(false); } // assert read access on the regarding entity var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName); return(securityProvider.TryAssert(context, regarding, CrmEntityRight.Read)); }
/// <summary> /// Function to make connection to specified server /// </summary> public void ConnectToServer() { string uriString; //Initialize the config file InitializeKeys(); // Setup credential _clientCreds = new ClientCredentials(); switch (_serverConfiguration["AuthenticationType"]) { case "IFD": _clientCreds.UserName.UserName = _serverConfiguration["ServerUser"]; _clientCreds.UserName.Password = _serverConfiguration["ServerPassword"]; uriString = "https://" + _serverConfiguration["ServerName"] + "/XRMServices/2011/Organization.svc"; break; case "OnPrem": default: _clientCreds.Windows.ClientCredential.UserName = _serverConfiguration["ServerUser"]; _clientCreds.Windows.ClientCredential.Password = _serverConfiguration["ServerPassword"]; _clientCreds.Windows.ClientCredential.Domain = _serverConfiguration["ServerName"] + "dom"; uriString = "http://" + _serverConfiguration["ServerName"] + "/" + _serverConfiguration["ServerOrgName"] + "/XRMServices/2011/Organization.svc"; break; } // The DeviceIdManager class registers a computing device with Windows Live ID, through the generation of a device ID and password, // and optionally stores that information in an encrypted format on the local disk for later reuse. // This will fail here as this vm don't have access to the Internet therefore there is no way for it to generate a device ID with login.live.com //_deviceCreds = DeviceIdManager.LoadOrRegisterDevice(); // Connect to Crm WCF endpoint try { using (_serviceProxy = new OrganizationServiceProxy(new Uri(uriString), null, _clientCreds, null)) { // require early bound type support _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); _service = (IOrganizationService)_serviceProxy; WhoAmIRequest request = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)orgContext.Execute(request); Console.WriteLine("Your Crm user Guid is {0}", userResponse.UserId); orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId; Console.WriteLine("Your CRM Org ID is {0}:", orgId); } } catch (Exception ex) { Console.WriteLine(ex); } }
protected static void AddRelatedRecordFilterToFetch(OrganizationServiceContext serviceContext, Fetch fetch, string filterRelationshipName, string filterEntityName, Guid filterValue) { if (fetch == null || fetch.Entity == null) { return; } var entityName = fetch.Entity.Name; if (string.IsNullOrWhiteSpace(filterRelationshipName) || string.IsNullOrWhiteSpace(filterEntityName) || filterValue == Guid.Empty) { return; } var entityRequest = new RetrieveEntityRequest { RetrieveAsIfPublished = false, LogicalName = entityName, EntityFilters = EntityFilters.Relationships }; var entityResponse = serviceContext.Execute(entityRequest) as RetrieveEntityResponse; if (entityResponse == null) { throw new ApplicationException("RetrieveEntityRequest failed for lookup target entity type {0}".FormatWith(entityName)); } var relationshipManyToOne = entityResponse.EntityMetadata.ManyToOneRelationships.FirstOrDefault(r => r.SchemaName == filterRelationshipName); if (relationshipManyToOne != null) { var attribute = relationshipManyToOne.ReferencedEntity == entityName ? relationshipManyToOne.ReferencedAttribute : relationshipManyToOne.ReferencingAttribute; var filter = new Filter { Type = LogicalOperator.And, Conditions = new List <Condition> { new Condition { Attribute = attribute, Operator = ConditionOperator.Equal, Value = filterValue } } }; AddFilterToFetch(fetch, filter); } else { throw new ApplicationException(string.Format("RetrieveRelationshipRequest failed for lookup filter relationship name {0}", filterRelationshipName)); } }
private static Entity Retrieve(OrganizationServiceContext serviceContext, EntityReference target) { var request = new RetrieveRequest { Target = target, ColumnSet = new ColumnSet(true) }; var response = serviceContext.Execute(request) as RetrieveResponse; return(response == null ? null : response.Entity); }
private static EntityMetadata GetEntityMetadata(OrganizationServiceContext serviceContext, string logicalName) { var response = (RetrieveEntityResponse)serviceContext.Execute(new RetrieveEntityRequest { LogicalName = logicalName, EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships }); return(response.EntityMetadata); }
private static EntityReference[] FilterAlreadyAssociated(OrganizationServiceContext serviceContext, Relationship relationship, EntityReference target, EntityReference[] relatedEntities) { var metadataResponse = (RetrieveRelationshipResponse)serviceContext.Execute(new RetrieveRelationshipRequest { Name = relationship.SchemaName }); var manyToManyMetadata = metadataResponse.RelationshipMetadata as ManyToManyRelationshipMetadata; if (manyToManyMetadata == null) { return(relatedEntities); } string targetIntersectAttribute; string relatedEntityLogicalName; string relatedEntityIntersectAttribute; if (string.Equals(manyToManyMetadata.Entity1LogicalName, target.LogicalName, StringComparison.Ordinal)) { targetIntersectAttribute = manyToManyMetadata.Entity1IntersectAttribute; relatedEntityLogicalName = manyToManyMetadata.Entity2LogicalName; relatedEntityIntersectAttribute = manyToManyMetadata.Entity2IntersectAttribute; } else { targetIntersectAttribute = manyToManyMetadata.Entity2IntersectAttribute; relatedEntityLogicalName = manyToManyMetadata.Entity1LogicalName; relatedEntityIntersectAttribute = manyToManyMetadata.Entity1IntersectAttribute; } var result = serviceContext.RetrieveMultiple(new QueryExpression(manyToManyMetadata.IntersectEntityName) { NoLock = true, ColumnSet = new ColumnSet(relatedEntityIntersectAttribute), Criteria = { Filters = { new FilterExpression(LogicalOperator.And) { Conditions = { new ConditionExpression(targetIntersectAttribute, ConditionOperator.Equal, target.Id), new ConditionExpression(relatedEntityIntersectAttribute, ConditionOperator.In, relatedEntities.Select(e => e.Id).ToArray()) }, } } } }); var alreadyAssociated = result.Entities .Select(e => new EntityReference(relatedEntityLogicalName, e.GetAttributeValue <Guid>(relatedEntityIntersectAttribute))); return(relatedEntities.Except(alreadyAssociated).ToArray()); }
private static TResult Execute <TResponse, TResult>( this OrganizationServiceContext service, OrganizationRequest request, Func <TResponse, TResult> selector) where TResponse : OrganizationResponse { var response = service.Execute <TResponse>(request); return(response != null?selector(response) : default(TResult)); }
/// <summary> /// Retrieve EntityMetadata /// </summary> /// <param name="serviceContext">OrganizationServiceContext</param> /// <returns>EntityMetadata</returns> private EntityMetadata GetRelatedEntityMetadata(OrganizationServiceContext serviceContext) { var metadataRequest = new RetrieveEntityRequest() { EntityFilters = EntityFilters.All, LogicalName = LogicalName, RetrieveAsIfPublished = false }; return(((RetrieveEntityResponse)serviceContext.Execute(metadataRequest)).EntityMetadata); }
internal static EntityMetadata GetIncidentMetadata(OrganizationServiceContext serviceContext) { var retrieveAttributeRequest = new RetrieveEntityRequest { LogicalName = "incident", EntityFilters = EntityFilters.Attributes }; var response = (RetrieveEntityResponse)serviceContext.Execute(retrieveAttributeRequest); return(response.EntityMetadata); }
/// <summary> /// Adds Content Access Level and Product Filtering to fetch /// </summary> /// <param name="annotation">Annotation</param> /// <param name="context">Context</param> /// <param name="contentAccessLevelProvider">content Access Level Provider</param> /// <param name="productAccessProvider">product Access Provider</param> private bool AssertKnowledgeArticleCalAndProductFiltering(Entity annotation, OrganizationServiceContext context, ContentAccessLevelProvider contentAccessLevelProvider, ProductAccessProvider productAccessProvider) { if (!contentAccessLevelProvider.IsEnabled() & !productAccessProvider.IsEnabled()) { // If CAL and Product Filtering is not enabled then we must not restrict access to the article. This will also eliminate an unnecessary knowledge article query. return(true); } var entityReference = annotation.GetAttributeValue <EntityReference>("objectid"); var fetch = new Fetch(); var knowledgeArticleFetch = new FetchEntity("knowledgearticle") { Filters = new List <Filter> { new Filter { Type = LogicalOperator.And, Conditions = new List <Condition> { new Condition("knowledgearticleid", ConditionOperator.Equal, entityReference.Id) } } }, Links = new List <Link>() }; fetch.Entity = knowledgeArticleFetch; // Apply Content Access Level filtering. If it is not enabled the fetch will not be modified contentAccessLevelProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetch); // Apply Product filtering. If it is not enabled the fetch will not be modified. productAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetch); var kaResponse = (RetrieveMultipleResponse)context.Execute(fetch.ToRetrieveMultipleRequest()); var isValid = kaResponse.EntityCollection.Entities.Any(); if (isValid) { if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)) { PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "TryCreateHandler CAL/PF passed", 1, annotation.ToEntityReference(), "read"); } return(true); } if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)) { PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "TryCreateHandler CAL/PF failed", 1, annotation.ToEntityReference(), "read"); } return(false); }
private static IDictionary <string, EntityMetadata> GetEntityDictionary(OrganizationServiceContext serviceContext) { var response = (RetrieveMetadataChangesResponse)serviceContext.Execute(new RetrieveMetadataChangesRequest { Query = new EntityQueryExpression { Properties = new MetadataPropertiesExpression("LogicalName"), } }); return(response.EntityMetadata.ToDictionary(e => e.LogicalName, StringComparer.OrdinalIgnoreCase)); }
public static EntityMetadata GetEntityMetadata(OrganizationServiceContext serviceContext, string entityLogicalName) { var retrieveAttributeRequest = new RetrieveEntityRequest { LogicalName = entityLogicalName, EntityFilters = EntityFilters.Attributes }; var response = (RetrieveEntityResponse)serviceContext.Execute(retrieveAttributeRequest); return(response.EntityMetadata); }
/// <summary> /// Retrieve the label of an Option Set value. /// </summary> /// <param name="context"></param> /// <param name="entityLogicalName"></param> /// <param name="attributeLogicalName"></param> /// <param name="value"></param> /// <param name="languageCode"></param> /// <returns>Label of the Option Set value.</returns> public static string GetOptionSetLabelByValue(OrganizationServiceContext context, string entityLogicalName, string attributeLogicalName, int value, int?languageCode) { if (string.IsNullOrEmpty(entityLogicalName) || string.IsNullOrEmpty(attributeLogicalName)) { return(string.Empty); } string cachedLabel; var cachedItemToFind = string.Format("{0}:{1}:{2}", entityLogicalName, attributeLogicalName, value); if (OptionSetLabelCache.TryGetValue(cachedItemToFind, out cachedLabel)) { return(cachedLabel); } var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = attributeLogicalName }; var retrieveAttributeResponse = (RetrieveAttributeResponse)context.Execute(retrieveAttributeRequest); var retrievedPicklistAttributeMetadata = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; var option = retrievedPicklistAttributeMetadata.OptionSet.Options.FirstOrDefault(o => o.Value == value); if (option == null) { return(string.Empty); } var label = option.Label.GetLocalizedLabelString(); if (languageCode != null) { foreach (var item in option.Label.LocalizedLabels.Where(item => item.LanguageCode == languageCode)) { label = item.Label; break; } } if (option.Value.HasValue) { OptionSetLabelCache[cachedItemToFind] = label; } return(label); }
public static string GetOptionSetValueLabel(this OrganizationServiceContext serviceContext, string entityLogicalName, string attributeLogicalName, int?optionSetValue, int?languageCode) { if (serviceContext == null) { throw new ArgumentNullException("serviceContext"); } if (entityLogicalName == null) { throw new ArgumentNullException("entityLogicalName"); } if (attributeLogicalName == null) { throw new ArgumentNullException("attributeLogicalName"); } if (optionSetValue == null) { return(null); } var response = (RetrieveAttributeResponse)serviceContext.Execute(new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = attributeLogicalName, }); if (response == null) { return(null); } var enumMetadata = response.AttributeMetadata as EnumAttributeMetadata; if (enumMetadata == null) { return(null); } var option = enumMetadata.OptionSet.Options.FirstOrDefault(o => o.Value == optionSetValue.Value); if (option == null) { return(string.Empty); } var localizedLabel = option.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == (languageCode ?? 0)); var label = localizedLabel == null?option.Label.GetLocalizedLabelString() : localizedLabel.Label; return(label); }
private static bool TryAssertPortalCommentPermission(OrganizationServiceContext context, CrmEntityPermissionProvider entityPermissionProvider, CrmEntityPermissionRight right, EntityReference target) { var response = context.Execute <RetrieveResponse>(new RetrieveRequest { Target = target, ColumnSet = new ColumnSet("regardingobjectid"), }); var regarding = response.Entity.GetAttributeValue <EntityReference>("regardingobjectid"); return(regarding != null && entityPermissionProvider.TryAssert(context, right, target, regarding: regarding)); }
/// <summary> /// This method first connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetBasicContextExamples1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery<SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery<UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery<UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery<Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
private bool FindAndDeactivateEntity(DateTime date) { using (var orgContext = new OrganizationServiceContext(this.service)) { var currencyFromCrm = (from i in orgContext.CreateQuery<sl_ExchangeRate>() where i.sl_RelevanceDate < date.ToUniversalTime().AddHours(_ToCrmUTCDate) && i.statecode == sl_ExchangeRateState.Active select i).ToList(); if (currencyFromCrm.Count == 0) { return true; } // деактивация устаревших курсов State = Close foreach (var item in currencyFromCrm) { SetStateRequest deactivateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(sl_ExchangeRate.EntityLogicalName, item.Id), State = new OptionSetValue(1), Status = new OptionSetValue(-1) }; orgContext.Execute(deactivateRequest); } return true; } }
private bool FindAndDeactivateEntity(DateTime date) { using (var orgContext = new OrganizationServiceContext(this.service)) { var currencyFromCrm = (from i in orgContext.CreateQuery<new_exchangerates>() where i.new_date < date && i.statecode == new_exchangeratesState.Active select i).ToList(); if (currencyFromCrm.Count == 0) { return false; } // деактивация устаревших курсов State = Close foreach (var item in currencyFromCrm) { SetStateRequest deactivateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(new_exchangerates.EntityLogicalName, item.Id), State = new OptionSetValue(1), Status = new OptionSetValue(-1) }; orgContext.Execute(deactivateRequest); } return true; } }