/// <summary> /// Fakes the RetrieveAttributeRequest that checks if an attribute exists for a given entity /// For simpicity, it asumes all attributes exist /// </summary> /// <param name="context"></param> /// <param name="fakedService"></param> protected static OrganizationResponse FakeRetrieveAttributeRequest(XrmFakedContext context, IOrganizationService fakedService, RetrieveAttributeRequest req) { var response = new RetrieveAttributeResponse { }; return response; }
private static AttributeMetadata LoadAttributeMetadata(string entityLogicalName, string attributeLogicalName) { string cacheKey = entityLogicalName + "|" + attributeLogicalName; AttributeMetadata metaData = (AttributeMetadata)_attributeMetaData[cacheKey]; if (metaData == null) { RetrieveAttributeRequest request = new RetrieveAttributeRequest(); request.EntityLogicalName = entityLogicalName; request.LogicalName = attributeLogicalName; request.RetrieveAsIfPublished = true; RetrieveAttributeResponse response = (RetrieveAttributeResponse)OrganizationServiceProxy.Execute(request); metaData = response.AttributeMetadata; _attributeMetaData[cacheKey] = metaData; } return(metaData); }
public static string GetDropDownValue(string entityName, string attributeName, int attributeValue) { string DropDownText = string.Empty; OrganizationServiceProxy serviceProxy = CrmHelper.Connect(); RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)serviceProxy.Execute(attributeRequest); // Handle Picklist options if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Picklist) { PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)attributeResponse.AttributeMetadata; foreach (OptionMetadata option in picklist.OptionSet.Options) { if (option.Value == attributeValue) { DropDownText = option.Label.UserLocalizedLabel.Label; break; } } } // Handle Status options else if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Status) { StatusAttributeMetadata status = (StatusAttributeMetadata)attributeResponse.AttributeMetadata; foreach (StatusOptionMetadata option in status.OptionSet.Options) { if (option.Value == attributeValue) { DropDownText = option.Label.UserLocalizedLabel.Label; break; } } } return(DropDownText); }
public Dictionary <int, string> GetOptionSet(string entityName, string fieldName) { this._tracer.Trace("Method: GetOptionSet"); this._tracer.Trace("Parameters: entityName={0}, fieldName={1}", entityName, fieldName); Dictionary <int, string> options = new Dictionary <int, string>(); try { RetrieveAttributeRequest request = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = fieldName, RetrieveAsIfPublished = true }; this._tracer.Trace("Getting OptionSet"); RetrieveAttributeResponse response = (RetrieveAttributeResponse)this._sdk.Execute(request); this._tracer.Trace("OptionSet retrieved"); if (response != null && response.Results != null) { PicklistAttributeMetadata pam = (PicklistAttributeMetadata)response.AttributeMetadata; OptionMetadata[] omd = pam.OptionSet.Options.ToArray(); omd.ToList() .ForEach(o => { options.Add(o.Value.Value, o.Label.UserLocalizedLabel.Label); }); } this._tracer.Trace("Number of options found: {0}", options.Count); } catch (Exception ex) { this._tracer.Trace("Unable to retrieve OptionSet from CRM"); this._tracer.Trace(ex.ToString()); } return(options); }
public Dictionary <int, string> GetOptionSetValues(string entidade, string campo) { Dictionary <int, string> dic = new Dictionary <int, string>(); RetrieveAttributeRequest request = new RetrieveAttributeRequest(); request.EntityLogicalName = entidade; request.LogicalName = campo; request.RetrieveAsIfPublished = true; RetrieveAttributeResponse response = (RetrieveAttributeResponse)this.Provider.Execute(request); if (response.Results.Count > 0) { PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata; foreach (var item in picklist.OptionSet.Options) { dic.Add(item.Value.Value, item.Label.LocalizedLabels[0].Label); } } return(dic); }
public List <rows> listOptionSet(String entity, String attribute) { List <rows> Lrow = new List <rows>(); RetrieveAttributeRequest request = new RetrieveAttributeRequest { EntityLogicalName = entity, LogicalName = attribute, RetrieveAsIfPublished = true }; RetrieveAttributeResponse response = (RetrieveAttributeResponse)_serviceProxy.Execute(request); PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata; foreach (OptionMetadata rec in picklist.OptionSet.Options) { Lrow.Add(new rows() { Name = rec.Label.LocalizedLabels[0].Label, Value = Int32.Parse(rec.Value.ToString()) }); } return(Lrow); }
public static string GetPickListLabel(string entityName, string fieldName, int value, IOrganizationService service) { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = fieldName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse response = (RetrieveAttributeResponse)service.Execute(attributeRequest); EnumAttributeMetadata attributeMetadata = (EnumAttributeMetadata)response.AttributeMetadata; foreach (OptionMetadata optionMeta in attributeMetadata.OptionSet.Options) { if (optionMeta.Value == value) { return(optionMeta.Label.UserLocalizedLabel.Label); } } return(string.Empty); }
private AttributeMetadata GetAttributeMetadata(string entityName, string attributeName) { string attributeKey = entityName + attributeName; if (!AttributeMetadata.ContainsKey(attributeKey)) { try { RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)Context.OrganizationService.Execute(new RetrieveAttributeRequest() { EntityLogicalName = entityName, LogicalName = attributeName }); AttributeMetadata.Add(attributeKey, attributeResponse.AttributeMetadata); } catch { throw new InvalidPluginExecutionException(String.Format("{1} attribute does not exist on {0} entity, or entity does not exist.", entityName, attributeName)); } } return(AttributeMetadata[attributeKey]); }
internal static List <Tuple <string, int> > GetPicklistValues(IOrganizationService service, string entityLogicalName, string attributeLogicalName) { List <Tuple <string, int> > retVal = new List <Tuple <string, int> >(); RetrieveAttributeRequest rar = new RetrieveAttributeRequest() { EntityLogicalName = entityLogicalName, LogicalName = attributeLogicalName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse rarr = (RetrieveAttributeResponse)service.Execute(rar); if (rarr.AttributeMetadata.GetType().Name == "PicklistAttributeMetadata") { foreach (OptionMetadata om in ((PicklistAttributeMetadata)rarr.AttributeMetadata).OptionSet.Options) { retVal.Add(new Tuple <string, int>(om.Label.LocalizedLabels[0].Label, om.Value.Value)); } } else if (rarr.AttributeMetadata.GetType().Name == "StateAttributeMetadata") { foreach (OptionMetadata om in ((StateAttributeMetadata)rarr.AttributeMetadata).OptionSet.Options) { retVal.Add(new Tuple <string, int>(om.Label.LocalizedLabels[0].Label, om.Value.Value)); } } else if (rarr.AttributeMetadata.GetType().Name == "StatusAttributeMetadata") { foreach (OptionMetadata om in ((StatusAttributeMetadata)rarr.AttributeMetadata).OptionSet.Options) { retVal.Add(new Tuple <string, int>(om.Label.LocalizedLabels[0].Label, om.Value.Value)); } } return(retVal); }
public static string GetOptionsSetTextOnValue(IOrganizationService service, string entitySchemaName, string attributeSchemaName, int optionsetValue) { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entitySchemaName, LogicalName = attributeSchemaName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); string metadata = string.Empty; if (optionList.Length > 0) { metadata = (from a in optionList where a.Value == optionsetValue select a.Label.UserLocalizedLabel.Label).First(); } return(metadata); }
private void DoUpdate(IPluginExecutionContext context, IOrganizationService orgService) { //Entity vehicle = orgService.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet("new_vehicleowner")); //Entity preImage = context.PreEntityImages[C_ImageName]; //Entity postImage = context.PostEntityImages[C_ImageName]; Entity postImage = orgService.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet("customer")); //EntityReference preVehicleOwner = GetAmountValue(preImage); if (postImage.Contains("customer") != false) { EntityCollection ec = (EntityCollection)postImage["customer"]; postImage["new_customerlookup"] = null; for (int i = 0; i < ec.Entities.Count; i++) { if ((ec[i]["partyid"] as EntityReference).LogicalName == "account") { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = C_EntityName, LogicalName = "new_customerlookup", RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)orgService.Execute(attributeRequest); if (attributeResponse != null) { postImage["new_customerlookup"] = ec[i]["partyid"]; } } } orgService.Update(postImage); } }
public CRMPicklist CRMGetPicklist(CRMPicklist picklist) { OrganizationServiceProxy _serviceProxy; using (_serviceProxy = GetCRMConnection()) { try { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = picklist.EntityLogicalName, LogicalName = picklist.AttributeLogicalName }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeRequest); PicklistAttributeMetadata pick = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; StateAttributeMetadata a = new StateAttributeMetadata(); List <CRMPicklistOption> options = new List <CRMPicklistOption>(); foreach (OptionMetadata o in pick.OptionSet.Options) { CRMPicklistOption option = new CRMPicklistOption(); option.PicklistValue = o.Value.HasValue ? o.Value.Value : 0; option.PicklistLabel = o.Label.UserLocalizedLabel.Label; options.Add(option); } picklist.Picklist = options; } catch (Exception ex) { throw; } } return(picklist); }
/// <summary> /// /// </summary> /// <param name="entityName"></param> /// <param name="attributeName"></param> /// <returns></returns> public AttributeMetadata GetAttributeMetadata(string entityName, string attributeName) { string entityAndAttribute = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", entityName, attributeName); AttributeMetadata attributeMetadata = null; ValidateMetadata(); if (!_attributeMetadataCache.TryGetValue(entityAndAttribute, out attributeMetadata)) { if (!_attributeMetadataCache.TryGetValue(entityAndAttribute, out attributeMetadata)) { RetrieveAttributeRequest request = new RetrieveAttributeRequest(); request.EntityLogicalName = entityName; request.LogicalName = attributeName; RetrieveAttributeResponse response = (RetrieveAttributeResponse)svcAct.Command_Execute(request, "GetAttributeMetadata"); if (response != null) { attributeMetadata = response.AttributeMetadata; _attributeMetadataCache.TryAdd(String.Format(CultureInfo.InvariantCulture, "{0}.{1}", entityName, attributeName), attributeMetadata); _metadataLastValidatedAt = DateTime.UtcNow; } else { if (svcAct.LastException != null) { throw new DataverseOperationException($"Failed to resolve attribute metadata for {attributeName} in entity {entityName}.", svcAct.LastException); } else { throw new DataverseOperationException($"Failed to resolve attribute metadata for {attributeName} in entity {entityName}.", null); } } } } return(attributeMetadata); }
private string RetrieveOptionSetLabel(EntityReference entityReference, string attributeLogicalName, OptionSetValue optionSetValue, IOrganizationService organizationService) { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityReference.LogicalName, LogicalName = attributeLogicalName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = organizationService.Execute(attributeRequest) as RetrieveAttributeResponse; if (attributeResponse.AttributeMetadata is EnumAttributeMetadata) { OptionMetadataCollection options = ((EnumAttributeMetadata)attributeResponse.AttributeMetadata).OptionSet?.Options; if (options != null) { foreach (OptionMetadata option in options) { if (option != null && option.Value == optionSetValue.Value) { if (option.Label == null || option.Label.UserLocalizedLabel == null) { return(string.Empty); } else { return(option.Label.UserLocalizedLabel.Label); } } } } } return(string.Empty); //Unexpected type }
public void Can_get_attribute_metadata_generic() { var attributeMetadata = new AttributeMetadata(); RetrieveAttributeRequest request = null; var context = Substitute.For <ITransactionContext <Entity> >(); context.Service.Execute(Arg.Any <RetrieveAttributeRequest>()) .Returns(ci => { request = ci.ArgAt <RetrieveAttributeRequest>(0); var response = new RetrieveAttributeResponse { ["AttributeMetadata"] = attributeMetadata }; return(response); }); var retrievedAttributeMetadata = context.GetMetadata <xts_entity>(e => e.xts_attribute); Assert.Same(attributeMetadata, retrievedAttributeMetadata); Assert.Equal("xts_entity", request.EntityLogicalName); Assert.Equal("xts_attribute", request.LogicalName); Assert.False(request.RetrieveAsIfPublished); }
private int GetOptionSetId(String entityName, String fieldname, String optionSetName) { RetrieveAttributeRequest raRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = fieldname, RetrieveAsIfPublished = true }; RetrieveAttributeResponse raResponse = (RetrieveAttributeResponse)_dependencies.GetServiceContext().Execute(raRequest); PicklistAttributeMetadata paMetadata = (PicklistAttributeMetadata)raResponse.AttributeMetadata; OptionMetadata[] optionList = paMetadata.OptionSet.Options.ToArray(); foreach (OptionMetadata oMD in optionList) { var a = oMD.Label.LocalizedLabels[0].Label; var b = optionSetName; if (oMD.Label.LocalizedLabels[0].Label == optionSetName) { return(oMD.Value.Value); } } return(0); }
private RetrieveAttributeResponse ExecuteInternal(RetrieveAttributeRequest request) { var response = new RetrieveAttributeResponse(); var optionSet = new PicklistAttributeMetadata { OptionSet = new OptionSetMetadata() }; response.Results["AttributeMetadata"] = optionSet; var enumExpression = CrmServiceUtility.GetEarlyBoundProxyAssembly().GetTypes().Where(t => t.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0 && t.GetCustomAttributes(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), false).Length > 0 && t.Name.Contains(request.LogicalName)).ToList(); // Search By EntityLogicalName_LogicalName // Then By LogicName_EntityLogicalName // Then By LogicaName var enumType = enumExpression.FirstOrDefault(t => t.Name == request.EntityLogicalName + "_" + request.LogicalName) ?? enumExpression.FirstOrDefault(t => t.Name == request.LogicalName + "_" + request.EntityLogicalName) ?? enumExpression.FirstOrDefault(t => t.Name == request.LogicalName); AddEnumTypeValues(optionSet.OptionSet, enumType, String.Format("Unable to find local optionset enum for entity: {0}, attribute: {1}", request.EntityLogicalName, request.LogicalName)); return response; }
private RetrieveAttributeResponse ExecuteInternal(RetrieveAttributeRequest request) { var response = new RetrieveAttributeResponse(); var entityType = CrmServiceUtility.GetEarlyBoundProxyAssembly().GetTypes().FirstOrDefault(t => t.GetCustomAttribute <EntityLogicalNameAttribute>(true)?.LogicalName == request.EntityLogicalName); var propertyTypes = entityType?.GetProperties() .Where(p => p.GetCustomAttribute <AttributeLogicalNameAttribute>()?.LogicalName == request.LogicalName ).Select(p => p.PropertyType.IsGenericType ? p.PropertyType.GenericTypeArguments.First() : p.PropertyType).ToList(); var propertyType = propertyTypes?.Count == 1 ? propertyTypes[0] : propertyTypes?.FirstOrDefault(p => p != typeof(OptionSetValue) && p != typeof(EntityReference)); // Handle OptionSets/EntityReferences that may have multiple properties if (propertyType == null) { throw new Exception($"Unable to find a property for Entity {request.EntityLogicalName} and property {request.LogicalName} in {CrmServiceUtility.GetEarlyBoundProxyAssembly().FullName}"); } AttributeMetadata metadata; if (propertyType.IsEnum || propertyTypes.Any(p => p == typeof(OptionSetValue))) { metadata = CreateOptionSetAttributeMetadata(request, propertyType); } else if (propertyType == typeof(string)) { metadata = new StringAttributeMetadata(request.LogicalName); } else if (propertyTypes.Any(p => p == typeof(EntityReference))) { metadata = new LookupAttributeMetadata { LogicalName = request.LogicalName }; } #if !XRM_2013 else if (propertyType == typeof(Guid)) { metadata = new UniqueIdentifierAttributeMetadata { LogicalName = request.LogicalName }; } #endif else if (propertyType == typeof(bool)) { metadata = new BooleanAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(Money)) { metadata = new MoneyAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(int)) { metadata = new IntegerAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(long)) { metadata = new BigIntAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(DateTime)) { metadata = new DateTimeAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(double)) { metadata = new DoubleAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(decimal)) { metadata = new DecimalAttributeMetadata { LogicalName = request.LogicalName }; } else { throw new NotImplementedException($"Attribute Type of {propertyType.FullName} is not implemented."); } response.Results["AttributeMetadata"] = metadata; return(response); }
/// <summary> /// Create and configure the organization service proxy. /// Create few types of attributes. /// Insert status in the existing status list. /// Retrieve attribute. /// Update attribute. /// Update existing state value. /// Optionally delete/revert any attributes /// that were created/changed for this sample. /// </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 { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetWorkWithAttributes1> #region How to create attributes //<snippetWorkWithAttributes2> // Create storage for new attributes being created addedAttributes = new List <AttributeMetadata>(); // Create a boolean attribute BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = "new_boolean", DisplayName = new Label("Sample Boolean", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Boolean Attribute", _languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", _languageCode), 1), new OptionMetadata(new Label("False", _languageCode), 0) ) }; // Add to list addedAttributes.Add(boolAttribute); // Create a date time attribute DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata { // Set base properties SchemaName = "new_datetime", DisplayName = new Label("Sample DateTime", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("DateTime Attribute", _languageCode), // Set extended properties Format = DateTimeFormat.DateOnly, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(dtAttribute); // Create a decimal attribute DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata { // Set base properties SchemaName = "new_decimal", DisplayName = new Label("Sample Decimal", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Decimal Attribute", _languageCode), // Set extended properties MaxValue = 100, MinValue = 0, Precision = 1 }; // Add to list addedAttributes.Add(decimalAttribute); // Create a integer attribute IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata { // Set base properties SchemaName = "new_integer", DisplayName = new Label("Sample Integer", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Integer Attribute", _languageCode), // Set extended properties Format = IntegerFormat.None, MaxValue = 100, MinValue = 0 }; // Add to list addedAttributes.Add(integerAttribute); // Create a memo attribute MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata { // Set base properties SchemaName = "new_memo", DisplayName = new Label("Sample Memo", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Memo Attribute", _languageCode), // Set extended properties Format = StringFormat.TextArea, ImeMode = ImeMode.Disabled, MaxLength = 500 }; // Add to list addedAttributes.Add(memoAttribute); // Create a money attribute MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata { // Set base properties SchemaName = "new_money", DisplayName = new Label("Money Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Money Attribue", _languageCode), // Set extended properties MaxValue = 1000.00, MinValue = 0.00, Precision = 1, PrecisionSource = 1, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(moneyAttribute); // Create a picklist attribute PicklistAttributeMetadata pickListAttribute = new PicklistAttributeMetadata { // Set base properties SchemaName = "new_picklist", DisplayName = new Label("Sample Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Picklist Attribute", _languageCode), // Set extended properties // Build local picklist options OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata( new Label("Created", _languageCode), null), new OptionMetadata( new Label("Updated", _languageCode), null), new OptionMetadata( new Label("Deleted", _languageCode), null) } } }; // Add to list addedAttributes.Add(pickListAttribute); // Create a string attribute StringAttributeMetadata stringAttribute = new StringAttributeMetadata { // Set base properties SchemaName = "new_string", DisplayName = new Label("Sample String", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("String Attribute", _languageCode), // Set extended properties MaxLength = 100 }; // Add to list addedAttributes.Add(stringAttribute); // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship. // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type. // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK. foreach (AttributeMetadata anAttribute in addedAttributes) { // Create the request. CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = anAttribute }; // Execute the request. _serviceProxy.Execute(createAttributeRequest); Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName); } //</snippetWorkWithAttributes2> #endregion How to create attributes #region How to insert status //<snippetWorkWithAttributes3> // Use InsertStatusValueRequest message to insert a new status // in an existing status attribute. // Create the request. InsertStatusValueRequest insertStatusValueRequest = new InsertStatusValueRequest { AttributeLogicalName = "statuscode", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("Dormant", _languageCode), StateCode = 0 }; // Execute the request and store newly inserted value // for cleanup, used later part of this sample. _insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute( insertStatusValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertStatusValueRequest.Label.LocalizedLabels[0].Label, _insertedStatusValue); //</snippetWorkWithAttributes3> #endregion How to insert status #region How to retrieve attribute //<snippetWorkWithAttributes4> // Create the request RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_string", // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false. // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published. RetrieveAsIfPublished = false }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest); Console.WriteLine("Retrieved the attribute {0}.", attributeResponse.AttributeMetadata.SchemaName); //</snippetWorkWithAttributes4> #endregion How to retrieve attribute #region How to update attribute //<snippetWorkWithAttributes5> // Modify the retrieved attribute AttributeMetadata retrievedAttributeMetadata = attributeResponse.AttributeMetadata; retrievedAttributeMetadata.DisplayName = new Label("Update String Attribute", _languageCode); // Update an attribute retrieved via RetrieveAttributeRequest UpdateAttributeRequest updateRequest = new UpdateAttributeRequest { Attribute = retrievedAttributeMetadata, EntityName = Contact.EntityLogicalName, MergeLabels = false }; // Execute the request _serviceProxy.Execute(updateRequest); Console.WriteLine("Updated the attribute {0}.", retrievedAttributeMetadata.SchemaName); //</snippetWorkWithAttributes5> #endregion How to update attribute #region How to update state value //<snippetWorkWithAttributes6> // Modify the state value label from Active to Open. // Create the request. UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest { AttributeLogicalName = "statecode", EntityLogicalName = Contact.EntityLogicalName, Value = 1, Label = new Label("Open", _languageCode) }; // Execute the request. _serviceProxy.Execute(updateStateValue); Console.WriteLine( "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.", updateStateValue.AttributeLogicalName, updateStateValue.EntityLogicalName, updateStateValue.Label.LocalizedLabels[0].Label ); //</snippetWorkWithAttributes6> #endregion How to update state value #region How to insert a new option item in a local option set //<snippetWorkWithAttributes7> // Create a request. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request. int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, insertOptionValue); //</snippetWorkWithAttributes7> #endregion How to insert a new option item in a local option set #region How to change the order of options of a local option set //<snippetWorkWithAttributes8> // Use the RetrieveAttributeRequest message to retrieve // a attribute by it's logical name. RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_picklist", // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false. // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published. RetrieveAsIfPublished = false }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute( retrieveAttributeRequest); // Access the retrieved attribute. PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. OrderOptionRequest orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request _serviceProxy.Execute(orderOptionRequest); Console.WriteLine("Option Set option order changed"); //</snippetWorkWithAttributes8> #endregion How to change the order of options of a global option set // NOTE: All customizations must be published before they can be used. _serviceProxy.Execute(new PublishAllXmlRequest()); Console.WriteLine("Published all customizations."); //</snippetWorkWithAttributes1> DeleteRequiredRecords(promptForDelete); } } // 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; } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate _productVersion = Version.Parse(((RetrieveVersionResponse)service.Execute(new RetrieveVersionRequest())).Version); #region How to create attributes // Create storage for new attributes being created addedAttributes = new List <AttributeMetadata>(); // Create a boolean attribute var boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = "new_Boolean", LogicalName = "new_boolean", DisplayName = new Label("Sample Boolean", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Boolean Attribute", _languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", _languageCode), 1), new OptionMetadata(new Label("False", _languageCode), 0) ) }; // Add to list addedAttributes.Add(boolAttribute); // Create a date time attribute var dtAttribute = new DateTimeAttributeMetadata { // Set base properties SchemaName = "new_Datetime", LogicalName = "new_datetime", DisplayName = new Label("Sample DateTime", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("DateTime Attribute", _languageCode), // Set extended properties Format = DateTimeFormat.DateOnly, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(dtAttribute); // Create a decimal attribute var decimalAttribute = new DecimalAttributeMetadata { // Set base properties SchemaName = "new_Decimal", LogicalName = "new_decimal", DisplayName = new Label("Sample Decimal", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Decimal Attribute", _languageCode), // Set extended properties MaxValue = 100, MinValue = 0, Precision = 1 }; // Add to list addedAttributes.Add(decimalAttribute); // Create a integer attribute var integerAttribute = new IntegerAttributeMetadata { // Set base properties SchemaName = "new_Integer", LogicalName = "new_integer", DisplayName = new Label("Sample Integer", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Integer Attribute", _languageCode), // Set extended properties Format = IntegerFormat.None, MaxValue = 100, MinValue = 0 }; // Add to list addedAttributes.Add(integerAttribute); // Create a memo attribute var memoAttribute = new MemoAttributeMetadata { // Set base properties SchemaName = "new_Memo", LogicalName = "new_memo", DisplayName = new Label("Sample Memo", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Memo Attribute", _languageCode), // Set extended properties Format = StringFormat.TextArea, ImeMode = ImeMode.Disabled, MaxLength = 500 }; // Add to list addedAttributes.Add(memoAttribute); // Create a money attribute var moneyAttribute = new MoneyAttributeMetadata { // Set base properties SchemaName = "new_Money", LogicalName = "new_money", DisplayName = new Label("Money Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Money Attribue", _languageCode), // Set extended properties MaxValue = 1000.00, MinValue = 0.00, Precision = 1, PrecisionSource = 1, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(moneyAttribute); // Create a picklist attribute var pickListAttribute = new PicklistAttributeMetadata { // Set base properties SchemaName = "new_Picklist", LogicalName = "new_picklist", DisplayName = new Label("Sample Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Picklist Attribute", _languageCode), // Set extended properties // Build local picklist options OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata( new Label("Created", _languageCode), null), new OptionMetadata( new Label("Updated", _languageCode), null), new OptionMetadata( new Label("Deleted", _languageCode), null) } } }; // Add to list addedAttributes.Add(pickListAttribute); // Create a string attribute var stringAttribute = new StringAttributeMetadata { // Set base properties SchemaName = "new_String", LogicalName = "new_string", DisplayName = new Label("Sample String", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("String Attribute", _languageCode), // Set extended properties MaxLength = 100 }; // Add to list addedAttributes.Add(stringAttribute); //Multi-select attribute requires version 9.0 or higher. if (_productVersion > new Version("9.0")) { // Create a multi-select optionset var multiSelectOptionSetAttribute = new MultiSelectPicklistAttributeMetadata() { SchemaName = "new_MultiSelectOptionSet", LogicalName = "new_multiselectoptionset", DisplayName = new Label("Multi-Select OptionSet", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Multi-Select OptionSet description", _languageCode), OptionSet = new OptionSetMetadata() { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("First Option", _languageCode), null), new OptionMetadata(new Label("Second Option", _languageCode), null), new OptionMetadata(new Label("Third Option", _languageCode), null) } } }; // Add to list addedAttributes.Add(multiSelectOptionSetAttribute); } // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship. // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type. // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK. foreach (AttributeMetadata anAttribute in addedAttributes) { // Create the request. var createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = anAttribute }; // Execute the request. service.Execute(createAttributeRequest); Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName); } #endregion How to create attributes #region How to insert status // Use InsertStatusValueRequest message to insert a new status // in an existing status attribute. // Create the request. var insertStatusValueRequest = new InsertStatusValueRequest { AttributeLogicalName = "statuscode", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("Dormant", _languageCode), StateCode = 0 }; // Execute the request and store newly inserted value // for cleanup, used later part of this sample. _insertedStatusValue = ((InsertStatusValueResponse)service.Execute( insertStatusValueRequest)).NewOptionValue; Console.WriteLine("Created status named '{0}' with the value of {1}.", insertStatusValueRequest.Label.LocalizedLabels[0].Label, _insertedStatusValue); #endregion How to insert status #region How to retrieve attribute // Create the request var attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_string", RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest); Console.WriteLine("Retrieved the attribute {0}.", attributeResponse.AttributeMetadata.SchemaName); #endregion How to retrieve attribute #region How to update attribute // Modify the retrieved attribute var retrievedAttributeMetadata = attributeResponse.AttributeMetadata; retrievedAttributeMetadata.DisplayName = new Label("Update String Attribute", _languageCode); // Update an attribute retrieved via RetrieveAttributeRequest var updateRequest = new UpdateAttributeRequest { Attribute = retrievedAttributeMetadata, EntityName = Contact.EntityLogicalName, MergeLabels = false }; // Execute the request service.Execute(updateRequest); Console.WriteLine("Updated the attribute {0}.", retrievedAttributeMetadata.SchemaName); #endregion How to update attribute #region How to update state value // Modify the state value label from Active to Open. // Create the request. var updateStateValue = new UpdateStateValueRequest { AttributeLogicalName = "statecode", EntityLogicalName = Contact.EntityLogicalName, Value = 1, Label = new Label("Open", _languageCode) }; // Execute the request. service.Execute(updateStateValue); Console.WriteLine( "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.", updateStateValue.AttributeLogicalName, updateStateValue.EntityLogicalName, updateStateValue.Label.LocalizedLabels[0].Label ); #endregion How to update state value #region How to insert a new option item in a local option set // Create a request. var insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request. int insertOptionValue = ((InsertOptionValueResponse)service.Execute( insertOptionValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, insertOptionValue); #endregion How to insert a new option item in a local option set #region How to change the order of options of a local option set // Use the RetrieveAttributeRequest message to retrieve // a attribute by it's logical name. var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_picklist", RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute( retrieveAttributeRequest); // Access the retrieved attribute. var retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. var orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request service.Execute(orderOptionRequest); Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set // NOTE: All customizations must be published before they can be used. service.Execute(new PublishAllXmlRequest()); Console.WriteLine("Published all customizations."); #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// /// </summary> /// <param name="oAttribute"></param> /// <param name="attMetadata"></param> /// <returns></returns> static public string GetMetadataValue(object oAttribute, RetrieveAttributeResponse attMetadata) { string sReturn = string.Empty; if (oAttribute.GetType().Equals(typeof(Microsoft.Xrm.Sdk.OptionSetValue))) { OptionMetadata[] optionList = null; if (attMetadata.AttributeMetadata.GetType().FullName.Contains("PicklistAttributeMetadata")) { PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)attMetadata.AttributeMetadata; // Get the current options list for the retrieved attribute. optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); } else if (attMetadata.AttributeMetadata.GetType().FullName.Contains("StatusAttributeMetadata")) { StatusAttributeMetadata retrievedPicklistAttributeMetadata = (StatusAttributeMetadata)attMetadata.AttributeMetadata; // Get the current options list for the retrieved attribute. optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); } else if (attMetadata.AttributeMetadata.GetType().FullName.Contains("StateAttributeMetadata")) { StateAttributeMetadata retrievedPicklistAttributeMetadata = (StateAttributeMetadata)attMetadata.AttributeMetadata; // Get the current options list for the retrieved attribute. optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); } else { return(string.Empty); } // get the text values int i = int.Parse((oAttribute as Microsoft.Xrm.Sdk.OptionSetValue).Value.ToString()); for (int c = 0; c < optionList.Length; c++) { OptionMetadata opmetadata = (OptionMetadata)optionList.GetValue(c); if (opmetadata.Value == i) { sReturn = opmetadata.Label.UserLocalizedLabel.Label; break; } } } else if (oAttribute.GetType().Equals(typeof(Microsoft.Xrm.Sdk.Money))) { sReturn = (oAttribute as Microsoft.Xrm.Sdk.Money).Value.ToString(); } else if (oAttribute.GetType().Equals(typeof(Microsoft.Xrm.Sdk.EntityReference))) { sReturn = (oAttribute as Microsoft.Xrm.Sdk.EntityReference).Name; } else { sReturn = oAttribute.ToString(); } if (sReturn == null || sReturn.Length == 0) { sReturn = "No Value"; } return(sReturn); }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { Entity mortgage = (Entity)context.InputParameters["Target"]; try { WebRequest request = WebRequest.Create("http://revgroup4app.azurewebsites.net/api/mortgageriskscore"); WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string responseString = reader.ReadToEnd(); reader.Close(); response.Close(); MortgageRiskScore mrs = Helper.JsonDeserialize <MortgageRiskScore>(responseString); // example response: {"RiskScore":30} decimal RiskScore = mrs.RiskScore; Guid BaseAprGuid = new Guid("4C767953-36AD-E811-A968-000D3A1CA7D6"); Guid MarginGuid = new Guid("D6EF9022-7EAF-E811-A968-000D3A1CABCE"); Entity config = service.Retrieve("rev_configuration", BaseAprGuid, new ColumnSet("rev_value")); // getting the record for Base APR decimal BaseApr = decimal.Parse(config.Attributes["rev_value"].ToString()); config = service.Retrieve("rev_configuration", MarginGuid, new ColumnSet("rev_value")); // getting the record for Margin decimal Margin = decimal.Parse(config.Attributes["rev_value"].ToString()); Entity SalesTax = service.Retrieve("rev_salestax", ((EntityReference)mortgage.Attributes["rev_salestaxid"]).Id, new ColumnSet("rev_rate")); decimal Tax = decimal.Parse(SalesTax.Attributes["rev_rate"].ToString()); RetrieveAttributeRequest req = new RetrieveAttributeRequest { EntityLogicalName = "rev_mortgage", LogicalName = "rev_mortgageterm", RetrieveAsIfPublished = true }; RetrieveAttributeResponse res = (RetrieveAttributeResponse)service.Execute(req); PicklistAttributeMetadata metadata = (PicklistAttributeMetadata)res.AttributeMetadata; OptionMetadata[] optionList = metadata.OptionSet.Options.ToArray(); string selectedOptionLabel = string.Empty; foreach (OptionMetadata oMD in optionList) { if (oMD.Value == int.Parse(((OptionSetValue)mortgage.Attributes["rev_mortgageterm"]).Value.ToString())) { selectedOptionLabel = oMD.Label.UserLocalizedLabel.Label; } } decimal IP = 12; // interest period per year, should be 12 since we are calculating monthly payment decimal APR = BaseApr + Margin + (decimal)(Math.Log10((double)RiskScore) / 100) + Tax; decimal PV = ((Money)mortgage.Attributes["rev_mortgageamount"]).Value; // present value decimal R = APR / IP; // periodic interest rate decimal N = IP * decimal.Parse(selectedOptionLabel); // interest periods for overall time period decimal P = PV * R / (1 - (decimal)Math.Pow((double)(1 + R), (double)-N)); // monthly payment Money MonthlyPayment = new Money(P); mortgage.Attributes.Add("rev_finalapr", APR); mortgage.Attributes.Add("rev_mortgagepayment", MonthlyPayment); } catch (FaultException <OrganizationServiceFault> ex) { //throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex); throw new InvalidPluginExecutionException(ex.Message + " " + ex.StackTrace); } catch (Exception ex) { tracingService.Trace("MyPlugin: {0}", ex.Message + " " + ex.StackTrace); throw; } } }
public void SetPriority3() { var serviceProvider = new StubIServiceProvider(); var pluginContext = new StubIPluginExecutionContext(); var organizationService = new StubIOrganizationService(); pluginContext.PrimaryEntityNameGet = () => "incident"; pluginContext.PrimaryEntityIdGet = () => new Guid("54D94FC2-52AD-E511-8158-1458D04DB4D1"); Microsoft.Xrm.Sdk.ParameterCollection paramCollection = new Microsoft.Xrm.Sdk.ParameterCollection(); Entity incident = new Entity("incident"); incident.Id = new Guid("884A078B-0467-E711-80F5-3863BB3C0660"); incident.Attributes["statuscode"] = new OptionSetValue(2); incident.Attributes["smp_problembuilding"] = new EntityReference("smp_building", new Guid("884A078B-0467-E711-80F5-3863BB3C1560")) { Name = "building" }; incident.Attributes["new_problemroomnumber"] = new EntityReference("smp_room", new Guid("884A078B-0467-E711-80F5-3863BB3C0560")) { Name = "room" }; incident.Attributes["caseorigincode"] = new OptionSetValue(3); incident.Attributes["smp_duedate"] = "2018-01-08";////Convert.ToDateTime(null, CultureInfo.CurrentCulture); incident.Attributes["smp_portalsubmit"] = false; incident.Attributes["smp_duedatebybuildingtimezone"] = "2018-01-08"; ////incident.Attributes["smp_occureddatetimebybuildingtimezone"] = "2018-01-08"; //// incident["smp_submitteddatetime"] = Convert.ToDateTime(null, CultureInfo.CurrentCulture);//new DateTime(2018, 1, 8); incident["createdon"] = "2018-01-08"; incident["smp_problemoccureddatetime"] = "2018-01-08"; ////incident.Attributes["smp_submitteddatetimebybuildingtimezone"] = "2018-01-08"; ////incident.Attributes["smp_createddatetimebybuildingtimezone"] = "2018-01-08"; incident.Attributes["smp_priorityid"] = new EntityReference("smp_priority", Guid.Empty) { Name = "priority" }; incident.Attributes["smp_problemroomtype"] = new EntityReference("smp_roomtype", new Guid("884A078B-0466-E711-80F5-3863BB3C0560")) { Name = "roomtype" }; incident.Attributes["smp_problemclassid"] = new EntityReference("smp_problemclass", new Guid("884A078B-0468-E711-80F5-3863BB3C0560")) { Name = "problemClass" }; incident.Attributes["smp_problemtypeid"] = new EntityReference("smp_problemtype", new Guid("884A078B-0469-E711-80F5-3863BB3C0560")) { Name = "problemType" }; incident.Attributes["smp_priorityid"] = new EntityReference("smp_priority", Guid.Empty); incident.Attributes["smp_contact"] = new EntityReference("contact", Guid.NewGuid()); paramCollection.Add("Target", incident); pluginContext.InputParametersGet = () => paramCollection; Helper.Helper.PluginVariables(serviceProvider, pluginContext, organizationService, 20, "Create", null); organizationService.ExecuteOrganizationRequest = QueryBase => { if (QueryBase.RequestName == "RetrieveAttribute") { PicklistAttributeMetadata picklistAttributeMetadata = new PicklistAttributeMetadata(); picklistAttributeMetadata.OptionSet = new OptionSetMetadata(); picklistAttributeMetadata.OptionSet.Options.Add(new OptionMetadata(new Label(new LocalizedLabel("+02:30", 1033), (new LocalizedLabel[] { new LocalizedLabel("+02:30", 1033) })), 0)); picklistAttributeMetadata.OptionSet.Options.Add(new OptionMetadata(new Label(new LocalizedLabel("+03:30", 1033), (new LocalizedLabel[] { new LocalizedLabel("+03:30", 1033) })), 1)); picklistAttributeMetadata.OptionSet.Options.Add(new OptionMetadata(new Label(new LocalizedLabel("-04:30", 1033), (new LocalizedLabel[] { new LocalizedLabel("-04:30", 1033) })), 2)); RetrieveAttributeResponse response = new RetrieveAttributeResponse(); response.Results.Add("AttributeMetadata", picklistAttributeMetadata); return(response); } else if (QueryBase.RequestName == "LocalTimeFromUtcTime") { LocalTimeFromUtcTimeResponse localTimeResponse = new LocalTimeFromUtcTimeResponse(); ////localTimeResponse.Results.Add("", value); DateTime dateTime = Convert.ToDateTime(QueryBase.Parameters["UtcTime"]).AddMinutes(Convert.ToInt32(QueryBase.Parameters["TimeZoneCode"])); localTimeResponse.Results.Add("LocalTime", dateTime); return(localTimeResponse); } else if (QueryBase.RequestName == "UtcTimeFromLocalTime") { UtcTimeFromLocalTimeResponse utcTimeResponse = new UtcTimeFromLocalTimeResponse(); DateTime dateTime = Convert.ToDateTime(QueryBase.Parameters["LocalTime"]).AddMinutes(-Convert.ToInt32(QueryBase.Parameters["TimeZoneCode"])); utcTimeResponse.Results.Add("UtcTime", dateTime); return(utcTimeResponse); } return(null); }; organizationService.RetrieveStringGuidColumnSet = delegate(string entity, Guid guid, ColumnSet secondaryUserColumnSet) { if (entity == "smp_building") { Entity building = new Entity(entity); building.Id = Guid.NewGuid(); building["smp_timezoneid"] = new EntityReference("smp_timezone", Guid.NewGuid()); building["smp_isfinancialstatecampus"] = true; return(building); } else if (entity == "smp_timezone") { Entity timeZone = new Entity(entity); timeZone["smp_timezonename"] = "test timezone"; timeZone["smp_offset"] = new OptionSetValue(2); return(timeZone); } else if (entity == "smp_priority") { Entity priority = new Entity(entity); priority["smp_noofminutes"] = 100; return(priority); } else if (entity == "smp_roomtype") { Entity roomType = new Entity(entity); roomType["smp_zone"] = new OptionSetValue(1); return(roomType); } return(null); }; organizationService.RetrieveMultipleQueryBase = (query) => { EntityCollection collection = new EntityCollection(); string entityName = string.Empty; if (query.GetType().Name.Equals("FetchExpression")) { if (((FetchExpression)query).Query.Contains("<entity name='ava_keyvaluepair'>")) { entityName = "ava_keyvaluepair"; } } else if (query.GetType().Name.Equals("QueryExpression")) { entityName = ((QueryExpression)query).EntityName; } else { entityName = ((QueryByAttribute)query).EntityName; } if (entityName == "smp_providermatrix") { Entity matrix = new Entity("smp_providermatrix"); matrix.Id = new Guid("884A078B-0466-E711-80F5-3863BB3C0560"); matrix["smp_primaryproviderid"] = new EntityReference("account", new Guid("884A078B-0467-E711-80F5-3863BB3C1560")); collection.Entities.Add(matrix); } else if (entityName == "smp_room") { Entity room = new Entity(entityName); room["smp_name"] = "test room"; room["smp_roomid"] = new Guid("884A078B-0466-E711-80F5-3863BB3C0679"); collection.Entities.Add(room); } else if (entityName == "account") { Entity account = new Entity(entityName); account["accountid"] = new Guid("884A078B-0467-E711-80F5-3863BB3C1560"); account["statuscode"] = 1; collection.Entities.Add(account); } else if (entityName == "smp_slamatrix") { Entity slaMatrix = new Entity(entityName); slaMatrix["smp_priorityid"] = new EntityReference("smp_priority", new Guid("884A078B-0467-E711-80F5-3863BB3C1489")); slaMatrix["smp_starthours"] = 2; slaMatrix["smp_endhours"] = 1; collection.Entities.Add(slaMatrix); } else if (entityName == "smp_buildingworkhours") { ////Entity buildWorkHours = new Entity(entityName); ////buildWorkHours["smp_starthours"] = new OptionSetValue(1); ////buildWorkHours["smp_endhours"] = new OptionSetValue(2); ////buildWorkHours.FormattedValues["smp_starthours"] = "08:30"; ////buildWorkHours.FormattedValues["smp_endhours"] = "08:30"; ////collection.Entities.Add(buildWorkHours); } else if (entityName == "smp_weekdays") { Entity weekdays = new Entity(entityName); weekdays["smp_name"] = Convert.ToDateTime("09-03-2017 02:30 AM"); collection.Entities.Add(weekdays); } else if (entityName == "smp_configuration") { Entity configuration = new Entity(entityName); configuration["smp_value"] = "Production"; collection.Entities.Add(configuration); } else if (entityName == "systemuser") { Entity systemuser = new Entity(entityName); systemuser.Id = Guid.NewGuid(); systemuser["systemuserid"] = systemuser.Id; collection.Entities.Add(systemuser); } else if (entityName == "usersettings") { Entity usersettings = new Entity(entityName); usersettings["timezonecode"] = 85; collection.Entities.Add(usersettings); } return(collection); }; PreServiceRequestCreateSetPriority prioritySet = new PreServiceRequestCreateSetPriority(); prioritySet.Execute(serviceProvider); }
public void UpdateChildRecords(string relationshipName, string parentEntityType, string parentEntityId, string parentFieldNameToUpdate, string setValueToUpdate, string childFieldNameToUpdate, bool _UpdateonlyActive) { //1) Get child lookup field name RetrieveRelationshipRequest req = new RetrieveRelationshipRequest() { Name = relationshipName }; RetrieveRelationshipResponse res = (RetrieveRelationshipResponse)service.Execute(req); OneToManyRelationshipMetadata rel = (OneToManyRelationshipMetadata)res.RelationshipMetadata; string childEntityType = rel.ReferencingEntity; string childEntityFieldName = rel.ReferencingAttribute; //2) retrieve all child records QueryByAttribute querybyattribute = new QueryByAttribute(childEntityType); querybyattribute.ColumnSet = new ColumnSet(childEntityFieldName); if (!_UpdateonlyActive) { querybyattribute.Attributes.AddRange(childEntityFieldName); querybyattribute.Values.AddRange(new Guid(parentEntityId)); } else { querybyattribute.Attributes.AddRange(childEntityFieldName, "statecode"); querybyattribute.Values.AddRange(new Guid(parentEntityId), 0); } EntityCollection retrieved = service.RetrieveMultiple(querybyattribute); //2') retrieve parent fielv value var valueToUpdate = new object(); if (parentFieldNameToUpdate != null && parentFieldNameToUpdate != "") { Entity retrievedEntity = (Entity)service.Retrieve(parentEntityType, new Guid(parentEntityId), new ColumnSet(parentFieldNameToUpdate)); if (retrievedEntity.Attributes.Contains(parentFieldNameToUpdate)) { valueToUpdate = retrievedEntity.Attributes[parentFieldNameToUpdate]; } else { valueToUpdate = null; } } else { valueToUpdate = setValueToUpdate; } //3) update each child record foreach (Entity child in retrieved.Entities) { if (childEntityType.ToLower() == "dynamicpropertyinstance") { //pending... UpdateProductPropertiesRequest req2 = new UpdateProductPropertiesRequest(); // req2. break; } RetrieveAttributeRequest reqAtt = new RetrieveAttributeRequest(); reqAtt.EntityLogicalName = childEntityType; reqAtt.LogicalName = childFieldNameToUpdate; RetrieveAttributeResponse resAtt = (RetrieveAttributeResponse)service.Execute(reqAtt); bool valueToUpdateBool = false; AttributeMetadata meta = resAtt.AttributeMetadata; Entity entUpdate = new Entity(childEntityType); entUpdate.Id = child.Id; if (meta.AttributeType.Value.ToString() == "Boolean") { if (valueToUpdate is bool) { if ((bool)valueToUpdate == true) { valueToUpdate = "1"; } else { valueToUpdate = "0"; } } if (valueToUpdate == "1") { entUpdate.Attributes.Add(childFieldNameToUpdate, true); } else { entUpdate.Attributes.Add(childFieldNameToUpdate, false); } } else { if (meta.AttributeType.Value.ToString() == "Picklist" || meta.AttributeType.Value.ToString() == "Status") { if (valueToUpdate == null) { entUpdate.Attributes.Add(childFieldNameToUpdate, null); } else { if (valueToUpdate is OptionSetValue) { valueToUpdate = ((OptionSetValue)valueToUpdate).Value; } OptionSetValue opt = new OptionSetValue(Convert.ToInt32(valueToUpdate)); entUpdate.Attributes.Add(childFieldNameToUpdate, opt); } } else { entUpdate.Attributes.Add(childFieldNameToUpdate, valueToUpdate); } } service.Update(entUpdate); } }
public DataTable GetPicklist(string EntityLogicalName, string AttributeLogicalName) { DataTable retVal = new DataTable() { TableName = "Picklist " + AttributeLogicalName }; retVal.Columns.AddRange( new DataColumn[] { new DataColumn("Value", typeof(int)), new DataColumn("Label", typeof(string)) }); //need to detmine global or local RetrieveAttributeRequest rar = new RetrieveAttributeRequest() { EntityLogicalName = EntityLogicalName, LogicalName = AttributeLogicalName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse rarr = (RetrieveAttributeResponse)connection.OrganizationService.Execute(rar); if (rarr.AttributeMetadata.GetType().Name == "PicklistAttributeMetadata") { foreach (OptionMetadata om in ((PicklistAttributeMetadata)rarr.AttributeMetadata).OptionSet.Options) { DataRow dr = retVal.NewRow(); dr["Value"] = om.Value ?? 0; dr["Label"] = om.Label.LocalizedLabels[0].Label; retVal.Rows.Add(dr); } } else if (rarr.AttributeMetadata.GetType().Name == "StateAttributeMetadata") { foreach (OptionMetadata om in ((StateAttributeMetadata)rarr.AttributeMetadata).OptionSet.Options) { DataRow dr = retVal.NewRow(); dr["Value"] = om.Value ?? 0; dr["Label"] = om.Label.LocalizedLabels[0].Label; retVal.Rows.Add(dr); } } else if (rarr.AttributeMetadata.GetType().Name == "StatusAttributeMetadata") { foreach (OptionMetadata om in ((StatusAttributeMetadata)rarr.AttributeMetadata).OptionSet.Options) { DataRow dr = retVal.NewRow(); dr["Value"] = om.Value ?? 0; dr["Label"] = om.Label.LocalizedLabels[0].Label; retVal.Rows.Add(dr); } } else { throw new Exception("unknown picklist"); } return(retVal); }
protected override void Execute(CodeActivityContext executionContext) { //Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); //Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); EntityReference mortgageref = Mortgage.Get(executionContext); Entity mortgage = service.Retrieve(mortgageref.LogicalName, mortgageref.Id, new ColumnSet("modifiedon", "rev_mortgageterm", "rev_mortgagepayment")); RetrieveAttributeRequest retrieveAttrReq = new RetrieveAttributeRequest { EntityLogicalName = "rev_mortgage", LogicalName = "rev_mortgageterm", RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttrRes = (RetrieveAttributeResponse)service.Execute(retrieveAttrReq); PicklistAttributeMetadata metadata = (PicklistAttributeMetadata)retrieveAttrRes.AttributeMetadata; OptionMetadata[] optionList = metadata.OptionSet.Options.ToArray(); string selectedOptionLabel = string.Empty; foreach (OptionMetadata oMD in optionList) { if (oMD.Value == int.Parse(((OptionSetValue)mortgage.Attributes["rev_mortgageterm"]).Value.ToString())) { selectedOptionLabel = oMD.Label.UserLocalizedLabel.Label; } } ExecuteMultipleRequest execMultReq = new ExecuteMultipleRequest { Settings = new ExecuteMultipleSettings() { ContinueOnError = false, ReturnResponses = true }, Requests = new OrganizationRequestCollection() }; DateTime dueDate = ((DateTime)mortgage.Attributes["modifiedon"]).AddMonths(1); for (int i = 1; i <= int.Parse(selectedOptionLabel) * 12; ++i) { Entity mortgagepaymentrecord = new Entity("rev_mortgagepaymentrecord"); mortgagepaymentrecord.Attributes.Add("rev_name", "Payment Period " + i); mortgagepaymentrecord.Attributes.Add("rev_duedate", dueDate); mortgagepaymentrecord.Attributes.Add("rev_payment", (Money)mortgage.Attributes["rev_mortgagepayment"]); mortgagepaymentrecord.Attributes.Add("rev_mortgageid", mortgageref); CreateRequest createReq = new CreateRequest { Target = mortgagepaymentrecord }; execMultReq.Requests.Add(createReq); dueDate = dueDate.AddMonths(1); } ExecuteMultipleResponse execMultRes = (ExecuteMultipleResponse)service.Execute(execMultReq); }
/// <summary> /// Processes the non-global option sets /// </summary> /// <param name="dictionary">The <C>Dictionary</C> that contains the name value pairs for the option set.</param> /// <param name="entityName">The name of the <C>Entity</C> that the option set belongs to.</param> private void ProcessPickLists(Dictionary <string, object> dictionary, string entityName) { if (dictionary == null) { return; } OrganizationResponse langRes = null; foreach (string attributeName in dictionary.Keys) { string[] values = dictionary[attributeName] as string[]; if (values.Length < 1) { continue; } RetrieveAttributeRequest attribReq = new RetrieveAttributeRequest(); attribReq.EntityLogicalName = entityName; attribReq.LogicalName = attributeName; attribReq.RetrieveAsIfPublished = true; OrganizationRequest langReq = new OrganizationRequest("RetrieveAvailableLanguages"); // Get the attribute metadata for the state attribute. RetrieveAttributeResponse metadataRespone = null; try { metadataRespone = (RetrieveAttributeResponse)this.CrmAdapter.OrganizationService.Execute(attribReq); if (langRes == null) { langRes = this.CrmAdapter.OrganizationService.Execute(langReq); } } catch (Exception e) { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.MetadataClientPicklistExceptionMessage, entityName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataRetrieval }; } if (metadataRespone != null) { PicklistAttributeMetadata picklistAttrib = metadataRespone.AttributeMetadata as PicklistAttributeMetadata; int optionNumber = 200000; InsertOptionValueRequest insertRequest = new InsertOptionValueRequest(); insertRequest.AttributeLogicalName = picklistAttrib.LogicalName; insertRequest.EntityLogicalName = entityName; insertRequest.Label = new Label(); insertRequest.Value = new int?(); foreach (string picklistName in values) { try { var option = picklistAttrib.OptionSet.Options.FirstOrDefault(opt => opt.Label.UserLocalizedLabel.Label.Replace(NotInErp, string.Empty).Trim().ToUpperInvariant() == picklistName.ToUpperInvariant() || opt.Label.UserLocalizedLabel.Label.Replace("*", string.Empty).Trim().ToUpperInvariant() == picklistName.ToUpperInvariant()); optionNumber += picklistAttrib.OptionSet.Options.Count(); // Add new values if (option == null) { insertRequest.Value = optionNumber++; insertRequest.Label = CreateSingleLabel(picklistName, metadataRespone.AttributeMetadata.DisplayName.UserLocalizedLabel.LanguageCode); this.CrmAdapter.OrganizationService.Execute(insertRequest); } else if (option.Label.UserLocalizedLabel.Label != picklistName) { // Update existing values if they are different this.CrmAdapter.OrganizationService.Execute(new UpdateOptionValueRequest() { AttributeLogicalName = picklistAttrib.LogicalName, EntityLogicalName = entityName, Label = CreateSingleLabel(picklistName, option.Label.UserLocalizedLabel.LanguageCode), MergeLabels = false, Value = option.Value.Value }); } } catch (FaultException e) { if (e.Message.Contains("because another picklist or status option for this attribute already exists")) { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ValueExistsMessage, entityName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataCreation }; } else { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.AddingValueExceptionMessage, picklistName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataCreation }; } } } } } }
/// <summary> /// Demonstrates sharing records by exercising various access messages including: /// Grant, Modify, Revoke, RetrievePrincipalAccess, and /// RetrievePrincipalsAndAccess. /// </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) { try { Console.WriteLine("Export codeable concept pick list values"); string picklistmappingfilename = ConfigurationManager.AppSettings["cdm:conceptpicklistvalues"]; if (string.IsNullOrEmpty(picklistmappingfilename)) { Console.WriteLine("Error: could not find the pick list mapping file name value"); return; } // we need this to support communicating with Dynamics Online Instances ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //<snippetSharingRecords1> // 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; // set the properties to get back the codeable concept picklist values // from the picklist (optionset) RetrieveAttributeRequest retrieveEntityRequest = new RetrieveAttributeRequest { EntityLogicalName = "msemr_codeableconcept", LogicalName = "msemr_type", RetrieveAsIfPublished = true }; // execute the call and retrieve the actual metadata directly RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveEntityRequest); var attributeMetadata = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; // retrieve each option list item var optionList = (from o in attributeMetadata.OptionSet.Options select new { Value = o.Value, Text = o.Label.UserLocalizedLabel.Label }).ToList(); // the data we will write to the CSV file that get's used by our import program // remember what we are doing here, is making the mapping file between // the codeable concepts actual values, and the OptionSet "attribute" that // needs to be set when you import a codeable concept // so you have can either use the file we produce for you // or create a fresh one based on any new values that are added over time List <string> picklistmappingdata = new List <string>(); // iterate through each option and write out the value and text // this will enable us to map the "Text" value given to us in the // codeable concepts file that we generated OR if you generate some new ones // you can run this program again to create the mapping file // or at least have the copy that was generated for you int totalOptions = 0; foreach (var option in optionList) { totalOptions++; // add to our string list of options picklistmappingdata.Add(option.Text.Trim() + "," + option.Value.ToString().Trim()); //default to first string of the label // write out our option count Console.SetCursorPosition(0, Console.CursorTop); Console.Write("Total Options Found [" + totalOptions.ToString() + "]"); System.Threading.Thread.Sleep(0); } // if we don't have any don't write anything if (picklistmappingdata.Count > 0) { File.Delete(picklistmappingfilename); // Remove this line if you don't want to erase the current version File.WriteAllLines(picklistmappingfilename, picklistmappingdata); Console.SetCursorPosition(0, Console.CursorTop); Console.WriteLine("Created codeable concepts mapping file [" + picklistmappingfilename + "]"); } else { Console.WriteLine("Could not find any Codeable Concept Types"); } } } // 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 void ShareSecuredFieldCore(IOrganizationService service, string entityName, string attributeName, Guid objectId, Guid principalId, bool allowRead, bool allowUpdate, bool shareWithTeam = true) { // Create the request RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest); if (attributeResponse.AttributeMetadata != null && attributeResponse.AttributeMetadata.IsSecured != null && attributeResponse.AttributeMetadata.IsSecured.HasValue && attributeResponse.AttributeMetadata.IsSecured.Value) { // Create the query for retrieve User Shared Attribute permissions. QueryExpression queryPOAA = new QueryExpression("principalobjectattributeaccess"); queryPOAA.ColumnSet = new ColumnSet(new string[] { "readaccess", "updateaccess" }); queryPOAA.Criteria.FilterOperator = LogicalOperator.And; queryPOAA.Criteria.Conditions.Add(new ConditionExpression("attributeid", ConditionOperator.Equal, attributeResponse.AttributeMetadata.MetadataId)); queryPOAA.Criteria.Conditions.Add(new ConditionExpression("objectid", ConditionOperator.Equal, objectId)); queryPOAA.Criteria.Conditions.Add(new ConditionExpression("principalid", ConditionOperator.Equal, principalId)); // Execute the query. EntityCollection responsePOAA = service.RetrieveMultiple(queryPOAA); if (responsePOAA.Entities.Count > 0) { Entity poaa = responsePOAA.Entities[0]; if (allowRead || allowUpdate) { poaa["readaccess"] = allowRead; poaa["updateaccess"] = allowUpdate; service.Update(poaa); } else { service.Delete("principalobjectattributeaccess", poaa.Id); } } else { if (allowRead || allowUpdate) { // Create POAA entity for user Entity poaa = new Entity("principalobjectattributeaccess"); poaa["attributeid"] = attributeResponse.AttributeMetadata.MetadataId; poaa["objectid"] = new EntityReference(entityName, objectId); poaa["readaccess"] = allowRead; poaa["updateaccess"] = allowUpdate; if (shareWithTeam) { poaa["principalid"] = new EntityReference("team", principalId); } else { poaa["principalid"] = new EntityReference("systemuser", principalId); } service.Create(poaa); } } } }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Grab all Solution Components for a solution. QueryByAttribute componentQuery = new QueryByAttribute { EntityName = SolutionComponent.EntityLogicalName, ColumnSet = new ColumnSet("componenttype", "objectid", "solutioncomponentid", "solutionid"), Attributes = { "solutionid" }, // In your code, this value would probably come from another query. Values = { _primarySolutionId } }; IEnumerable <SolutionComponent> allComponents = service.RetrieveMultiple(componentQuery).Entities.Cast <SolutionComponent>(); foreach (SolutionComponent component in allComponents) { // For each solution component, retrieve all dependencies for the component. RetrieveDependentComponentsRequest dependentComponentsRequest = new RetrieveDependentComponentsRequest { ComponentType = component.ComponentType.Value, ObjectId = component.ObjectId.Value }; RetrieveDependentComponentsResponse dependentComponentsResponse = (RetrieveDependentComponentsResponse)service.Execute(dependentComponentsRequest); // If there are no dependent components, we can ignore this component. if (dependentComponentsResponse.EntityCollection.Entities.Any() == false) { continue; } // If there are dependencies upon this solution component, and the solution // itself is managed, then you will be unable to delete the solution. Console.WriteLine("Found {0} dependencies for Component {1} of type {2}", dependentComponentsResponse.EntityCollection.Entities.Count, component.ObjectId.Value, component.ComponentType.Value ); //A more complete report requires more code foreach (Dependency d in dependentComponentsResponse.EntityCollection.Entities) { DependencyReport(service, d); } } //Find out if any dependencies on a specific global option set would prevent it from being deleted // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)service.Execute( retrieveOptionSetRequest); _globalOptionSetId = retrieveOptionSetResponse.OptionSetMetadata.MetadataId; if (_globalOptionSetId != null) { //Use the global OptionSet MetadataId with the appropriate componenttype // to call RetrieveDependenciesForDeleteRequest RetrieveDependenciesForDeleteRequest retrieveDependenciesForDeleteRequest = new RetrieveDependenciesForDeleteRequest { ComponentType = (int)componenttype.OptionSet, ObjectId = (Guid)_globalOptionSetId }; RetrieveDependenciesForDeleteResponse retrieveDependenciesForDeleteResponse = (RetrieveDependenciesForDeleteResponse)service.Execute(retrieveDependenciesForDeleteRequest); Console.WriteLine(""); foreach (Dependency d in retrieveDependenciesForDeleteResponse.EntityCollection.Entities) { if (d.DependentComponentType.Value == 2)//Just testing for Attributes { String attributeLabel = ""; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { MetadataId = (Guid)d.DependentComponentObjectId }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); AttributeMetadata attmet = retrieveAttributeResponse.AttributeMetadata; attributeLabel = attmet.DisplayName.UserLocalizedLabel.Label; Console.WriteLine("An {0} named {1} will prevent deleting the {2} global option set.", (componenttype)d.DependentComponentType.Value, attributeLabel, _globalOptionSetName); } } } #region Clean up CleanUpSample(service); #endregion Clen up //DeleteRequiredRecords(promptForDelete); } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// Shows how to detect dependencies that may cause a managed solution to become /// un-deletable. /// /// Get all solution components of a solution /// For each solution component, list the dependencies upon that component. /// </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 { // 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(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetGetSolutionDependencies1> // Grab all Solution Components for a solution. QueryByAttribute componentQuery = new QueryByAttribute { EntityName = SolutionComponent.EntityLogicalName, ColumnSet = new ColumnSet("componenttype", "objectid", "solutioncomponentid", "solutionid"), Attributes = { "solutionid" }, // In your code, this value would probably come from another query. Values = { _primarySolutionId } }; IEnumerable<SolutionComponent> allComponents = _serviceProxy.RetrieveMultiple(componentQuery).Entities.Cast<SolutionComponent>(); foreach (SolutionComponent component in allComponents) { // For each solution component, retrieve all dependencies for the component. RetrieveDependentComponentsRequest dependentComponentsRequest = new RetrieveDependentComponentsRequest { ComponentType = component.ComponentType.Value, ObjectId = component.ObjectId.Value }; RetrieveDependentComponentsResponse dependentComponentsResponse = (RetrieveDependentComponentsResponse)_serviceProxy.Execute(dependentComponentsRequest); // If there are no dependent components, we can ignore this component. if (dependentComponentsResponse.EntityCollection.Entities.Any() == false) continue; // If there are dependencies upon this solution component, and the solution // itself is managed, then you will be unable to delete the solution. Console.WriteLine("Found {0} dependencies for Component {1} of type {2}", dependentComponentsResponse.EntityCollection.Entities.Count, component.ObjectId.Value, component.ComponentType.Value ); //A more complete report requires more code foreach (Dependency d in dependentComponentsResponse.EntityCollection.Entities) { DependencyReport(d); } } //</snippetGetSolutionDependencies1> //Find out if any dependencies on a specific global option set would prevent it from being deleted //<snippetGetSolutionDependencies8> // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute( retrieveOptionSetRequest); _globalOptionSetId = retrieveOptionSetResponse.OptionSetMetadata.MetadataId; if (_globalOptionSetId != null) { //Use the global OptionSet MetadataId with the appropriate componenttype // to call RetrieveDependenciesForDeleteRequest RetrieveDependenciesForDeleteRequest retrieveDependenciesForDeleteRequest = new RetrieveDependenciesForDeleteRequest { ComponentType = (int)componenttype.OptionSet, ObjectId = (Guid)_globalOptionSetId }; RetrieveDependenciesForDeleteResponse retrieveDependenciesForDeleteResponse = (RetrieveDependenciesForDeleteResponse)_serviceProxy.Execute(retrieveDependenciesForDeleteRequest); Console.WriteLine(""); foreach (Dependency d in retrieveDependenciesForDeleteResponse.EntityCollection.Entities) { if (d.DependentComponentType.Value == 2)//Just testing for Attributes { String attributeLabel = ""; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { MetadataId = (Guid)d.DependentComponentObjectId }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeRequest); AttributeMetadata attmet = retrieveAttributeResponse.AttributeMetadata; attributeLabel = attmet.DisplayName.UserLocalizedLabel.Label; Console.WriteLine("An {0} named {1} will prevent deleting the {2} global option set.", (componenttype)d.DependentComponentType.Value, attributeLabel, _globalOptionSetName); } } } //</snippetGetSolutionDependencies8> DeleteRequiredRecords(promptForDelete); } } // 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; } }
public void DataTypeParsingTest() { Mock <IOrganizationService> orgSvc = null; Mock <MoqHttpMessagehander> fakHttpMethodHander = null; ServiceClient cli = null; testSupport.SetupMockAndSupport(out orgSvc, out fakHttpMethodHander, out cli); // Set up Responses CreateResponse testCreate = new CreateResponse(); testCreate.Results.AddOrUpdateIfNotNull("accountid", testSupport._DefaultId); testCreate.Results.AddOrUpdateIfNotNull("id", testSupport._DefaultId); LookupAttributeMetadata lookupAttributeMeta1 = new LookupAttributeMetadata(); lookupAttributeMeta1.LogicalName = "field02"; lookupAttributeMeta1.Targets = new List <string>() { "account", "contact" }.ToArray(); RetrieveAttributeResponse attribfield02Resp = new RetrieveAttributeResponse(); attribfield02Resp.Results.AddOrUpdateIfNotNull("AttributeMetadata", lookupAttributeMeta1); LookupAttributeMetadata lookupAttributeMeta2 = new LookupAttributeMetadata(); lookupAttributeMeta2.LogicalName = "field07"; lookupAttributeMeta2.Targets = new List <string>() { "account" }.ToArray(); RetrieveAttributeResponse attribfield07Resp = new RetrieveAttributeResponse(); attribfield07Resp.Results.AddOrUpdateIfNotNull("AttributeMetadata", lookupAttributeMeta2); HttpResponseMessage createRespMsg = new HttpResponseMessage(System.Net.HttpStatusCode.OK); createRespMsg.Headers.Add("Location", $"https://deploymenttarget02.crm.dynamics.com/api/data/v9.1/accounts({testSupport._DefaultId})"); createRespMsg.Headers.Add("OData-EntityId", $"https://deploymenttarget02.crm.dynamics.com/api/data/v9.1/accounts({testSupport._DefaultId})"); // Setup handlers to deal with both orgRequest and WebAPI request. fakHttpMethodHander.Setup(s => s.Send(It.Is <HttpRequestMessage>(f => f.Method.ToString().Equals("post", StringComparison.OrdinalIgnoreCase)))).Returns(createRespMsg); orgSvc.Setup(f => f.Execute(It.Is <CreateRequest>(p => p.Target.LogicalName.Equals("account")))).Returns(testCreate); orgSvc.Setup(f => f.Execute(It.Is <RetrieveAttributeRequest>(p => p.LogicalName.Equals("field02", StringComparison.OrdinalIgnoreCase) && p.EntityLogicalName.Equals("account", StringComparison.OrdinalIgnoreCase)))).Returns(attribfield02Resp); orgSvc.Setup(f => f.Execute(It.Is <RetrieveAttributeRequest>(p => p.LogicalName.Equals("field07", StringComparison.OrdinalIgnoreCase) && p.EntityLogicalName.Equals("account", StringComparison.OrdinalIgnoreCase)))).Returns(attribfield07Resp); // Setup request for all datatypes // use create operation to setup request Dictionary <string, DataverseDataTypeWrapper> newFields = new Dictionary <string, DataverseDataTypeWrapper>(); newFields.Add("name", new DataverseDataTypeWrapper("CrudTestAccount", DataverseFieldType.String)); newFields.Add("Field01", new DataverseDataTypeWrapper(false, DataverseFieldType.Boolean)); newFields.Add("Field02", new DataverseDataTypeWrapper(testSupport._DefaultId, DataverseFieldType.Customer, "account")); newFields.Add("Field03", new DataverseDataTypeWrapper(DateTime.UtcNow, DataverseFieldType.DateTime)); newFields.Add("Field04", new DataverseDataTypeWrapper(64, DataverseFieldType.Decimal)); newFields.Add("Field05", new DataverseDataTypeWrapper(1.001, DataverseFieldType.Float)); newFields.Add("Field06", new DataverseDataTypeWrapper(testSupport._DefaultId, DataverseFieldType.Key)); newFields.Add("Field07", new DataverseDataTypeWrapper(testSupport._DefaultId, DataverseFieldType.Lookup, "account")); newFields.Add("Field08", new DataverseDataTypeWrapper(50, DataverseFieldType.Money)); newFields.Add("Field09", new DataverseDataTypeWrapper(100, DataverseFieldType.Number)); newFields.Add("Field010", new DataverseDataTypeWrapper(20, DataverseFieldType.Picklist)); newFields.Add("Field011", new DataverseDataTypeWrapper("RawValue", DataverseFieldType.Raw)); newFields.Add("Field012", new DataverseDataTypeWrapper(testSupport._DefaultId, DataverseFieldType.UniqueIdentifier)); Entity acctEntity = new Entity("account"); acctEntity.Attributes.Add("name", "CrudTestAccount"); acctEntity.Attributes.Add("Field01", false); acctEntity.Attributes.Add("Field02", new EntityReference("parentaccount", testSupport._DefaultId)); acctEntity.Attributes.Add("Field03", DateTime.UtcNow); acctEntity.Attributes.Add("Field04", 64); acctEntity.Attributes.Add("Field05", 1.001); acctEntity.Attributes.Add("Field08", 50); acctEntity.Attributes.Add("Field09", 100); acctEntity.Attributes.Add("Field010", new OptionSetValue(20)); // Test Helper create var respId = cli.CreateNewRecord("account", newFields); Assert.Equal(testSupport._DefaultId, respId); // Test entity create var response = cli.ExecuteOrganizationRequest(new CreateRequest() { Target = acctEntity }, useWebAPI: false); Assert.NotNull(response); respId = ((CreateResponse)response).id; Assert.Equal(testSupport._DefaultId, respId); // Test low level create respId = cli.Create(acctEntity); Assert.Equal(testSupport._DefaultId, respId); }