private void ParseOptionSetValues(AttributeMetadata attribute)
 {
     if (attribute is PicklistAttributeMetadata)
     {
         var values = new NameValueCollection();
         PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)attribute;
         foreach (var c in optionMetadata.OptionSet.Options)
         {
             values.Add(ProcessName(c.Label.UserLocalizedLabel.Label), c.Value?.ToString());
         }
         OptionSetValues = values;
     }
     else if (attribute is StateAttributeMetadata)
     {
         var values = new NameValueCollection();
         StateAttributeMetadata optionMetadata = (StateAttributeMetadata)attribute;
         foreach (var c in optionMetadata.OptionSet.Options)
         {
             values.Add(ProcessName(c.Label.UserLocalizedLabel.Label), c.Value?.ToString());
         }
         OptionSetValues = values;
     }
     else if (attribute is StatusAttributeMetadata)
     {
         var values = new NameValueCollection();
         StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)attribute;
         foreach (var c in optionMetadata.OptionSet.Options)
         {
             values.Add(ProcessName(c.Label.UserLocalizedLabel.Label), c.Value?.ToString());
         }
         OptionSetValues = values;
     }
 }
Esempio n. 2
0
        public StatusAttributeMetadataControl(bool fillAllways
                                              , Entity entity
                                              , StatusAttributeMetadata attributeMetadataStatus
                                              , StateAttributeMetadata attributeMetadataState
                                              , int?initialValueStatus
                                              , int?initialValueState
                                              )
        {
            InitializeComponent();

            AttributeMetadataControlFactory.SetGroupBoxNameByAttributeMetadata(gbAttribute, attributeMetadataStatus);

            this._initialValueStatus = initialValueStatus;
            this._initialValueState  = initialValueState;

            this._fillAllways = fillAllways;

            this.AttributeMetadata       = attributeMetadataStatus;
            this._stateAttributeMetadata = attributeMetadataState;

            FillComboBox(entity);

            btnRemoveControl.IsEnabled = _fillAllways;

            btnRemoveControl.Visibility = btnRemoveControl.IsEnabled ? Visibility.Visible : Visibility.Collapsed;
            chBChanged.Visibility       = _fillAllways ? Visibility.Collapsed : Visibility.Visible;

            btnRestore.IsEnabled  = !_fillAllways;
            btnRestore.Visibility = btnRestore.IsEnabled ? Visibility.Visible : Visibility.Collapsed;
        }
        /// <summary>
        /// Converts all representations of the state property to an integer.
        /// </summary>
        /// <param name="stateName">The state to get the integer value of as a <c>string</c>.</param>
        /// <param name="entityName">The name of the entity type to get the state code for.</param>
        /// <param name="adapter">The <see cref="DynamicCrmAdapter"/> to use for calling into a CRM for resolving that state.</param>
        /// <returns>An <c>int</c> the represents the state.</returns>
        public static int ConvertStateNameToValue(string stateName, string entityName, DynamicCrmAdapter adapter)
        {
            if (adapter == null)
            {
                throw new ArgumentNullException("adapter");
            }

            RetrieveAttributeRequest attribReq = new RetrieveAttributeRequest()
            {
                EntityLogicalName = entityName, LogicalName = "statecode", RetrieveAsIfPublished = true
            };

            // Get the attribute metadata for the state attribute.
            RetrieveAttributeResponse metadataResponse = (RetrieveAttributeResponse)adapter.OrganizationService.Execute(attribReq);
            StateAttributeMetadata    picklistAttrib   = (StateAttributeMetadata)metadataResponse.AttributeMetadata;

            var picklistValue = from option in picklistAttrib.OptionSet.Options
                                where option.Label.UserLocalizedLabel.Label.ToUpperInvariant() == stateName.ToUpperInvariant()
                                select option.Value;

            // Ensure that both the returned list and the first item in the returned list are not null or empty.
            if ((picklistValue.Count() > 0) && (picklistValue.First() != null))
            {
                return(picklistValue.First().Value);
            }

            return(CRM2011AdapterUtilities.GetDefaultStateCodeValue(stateName));
        }
Esempio n. 4
0
        public StatusAttributeMetadataControl(
            StatusAttributeMetadata attributeMetadataStatus
            , StateAttributeMetadata attributeMetadataState
            , int?initialValueStatus
            , int?initialValueState
            , string statusFormattedValue
            , bool allwaysAddToEntity
            , bool showRestoreButton
            )
        {
            InitializeComponent();

            AttributeMetadataControlFactory.SetGroupBoxNameByAttributeMetadata(gbAttribute, attributeMetadataStatus);

            this._initialValueStatus          = initialValueStatus;
            this._initialValueState           = initialValueState;
            this._initialStatusFormattedValue = statusFormattedValue;

            this._allwaysAddToEntity = allwaysAddToEntity;

            this.AttributeMetadata       = attributeMetadataStatus;
            this._stateAttributeMetadata = attributeMetadataState;

            FillComboBox();

            Views.WindowBase.SetElementsEnabledAndVisible(allwaysAddToEntity, btnRemoveControl);

            Views.WindowBase.SetElementsEnabledAndVisible(showRestoreButton, btnRestore);

            Views.WindowBase.SetElementsVisible(showRestoreButton, chBChanged);
        }
Esempio n. 5
0
        public void GenerateAttributes()
        {
            var entityMetadata = new EntityMetadata {
                LogicalName = "ee_test", MetadataId = Guid.NewGuid(), DisplayName = new Label("Test", 1033)
            };
            var stringAttributeMetadata = new StringAttributeMetadata {
                LogicalName = "ee_teststring",
                MetadataId  = Guid.NewGuid(),
                DisplayName = new Label("Test String", 1033)
            }.Set(x => x.EntityLogicalName, entityMetadata.LogicalName);
            var picklistAttributeMetadata = new PicklistAttributeMetadata
            {
                LogicalName = "ee_testpicklist",
                MetadataId  = Guid.NewGuid(),
                DisplayName = new Label("Test Picklist", 1033)
            }.Set(x => x.EntityLogicalName, entityMetadata.LogicalName);
            var stateAttributeMetadata = new StateAttributeMetadata
            {
                LogicalName = "ee_teststate",
                MetadataId  = Guid.NewGuid(),
                DisplayName = new Label("Test State", 1033)
            }.Set(x => x.EntityLogicalName, entityMetadata.LogicalName);
            var imageAttributeMetadata = new ImageAttributeMetadata
            {
                LogicalName = "ee_testimage",
                MetadataId  = Guid.NewGuid(),
                DisplayName = new Label("Test Image", 1033)
            }.Set(x => x.EntityLogicalName, entityMetadata.LogicalName).Set(x => x.AttributeOf, "blah");

            organizationMetadata.Entities.Returns(new[] {
                entityMetadata.Set(x => x.Attributes, new AttributeMetadata [] { stringAttributeMetadata, picklistAttributeMetadata, stateAttributeMetadata, imageAttributeMetadata })
            });

            var f = Builder.Create <SolutionComponent>();

            f.Set(x => x.Regarding, entityMetadata.MetadataId);

            SolutionHelper.organisationService.RetrieveMultiple(Arg.Any <QueryExpression>())
            .Returns(new EntityCollection(new List <Entity> {
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, entityMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Entity),
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, stringAttributeMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Attribute),
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, picklistAttributeMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Attribute),
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, stateAttributeMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Attribute),
                Builder.Create <SolutionComponent>().Set(x => x.Regarding, imageAttributeMetadata.MetadataId).Set(x => x.ObjectTypeCode, ComponentType.Attribute)
            }));

            Assert.IsTrue(sut.GenerateAttribute(stringAttributeMetadata, serviceProvider));
            Assert.IsTrue(sut.GenerateAttribute(picklistAttributeMetadata, serviceProvider));
            Assert.IsTrue(sut.GenerateAttribute(stateAttributeMetadata, serviceProvider));
            Assert.IsTrue(sut.GenerateAttribute(imageAttributeMetadata, serviceProvider));
        }
Esempio n. 6
0
        public CRMPicklist CRMGetStateStatus(CRMPicklist picklist)
        {
            OrganizationServiceProxy _serviceProxy;

            using (_serviceProxy = GetCRMConnection())
            {
                try
                {
                    RetrieveAttributeRequest retrieveAttributeStateRequest = new RetrieveAttributeRequest
                    {
                        EntityLogicalName = picklist.EntityLogicalName,
                        LogicalName       = "statecode",
                    };
                    RetrieveAttributeResponse retrieveAttributeStateResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeStateRequest);

                    RetrieveAttributeRequest retrieveAttributeStatusRequest = new RetrieveAttributeRequest
                    {
                        EntityLogicalName = picklist.EntityLogicalName,
                        LogicalName       = "statuscode"
                    };
                    RetrieveAttributeResponse retrieveAttributeStatusResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeStatusRequest);

                    StateAttributeMetadata  state  = (StateAttributeMetadata)retrieveAttributeStateResponse.AttributeMetadata;
                    StatusAttributeMetadata status = (StatusAttributeMetadata)retrieveAttributeStatusResponse.AttributeMetadata;


                    List <CRMPicklistOption> options = new List <CRMPicklistOption>();
                    foreach (StatusOptionMetadata o in status.OptionSet.Options)
                    {
                        OptionMetadata s = state.OptionSet.Options.Where(p => p.Value.Value == o.State.Value).First();

                        CRMPicklistOption option = new CRMPicklistOption();
                        option.PicklistValue       = o.Value.HasValue ? o.Value.Value : 0;
                        option.PicklistLabel       = o.Label.UserLocalizedLabel.Label;
                        option.PicklistParentLabel = s.Label.UserLocalizedLabel.Label.ToString();
                        option.PicklistParentValue = s.Value.HasValue ? s.Value.Value : 0;
                        options.Add(option);
                    }
                    picklist.Picklist = options;
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            return(picklist);
        }
        /// <summary>
        /// Gets the options set text on value.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="entityName">Name of the entity.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <param name="selectedValue">The selected value.</param>
        /// <returns>The option set label</returns>
        internal static string GetOptionsSetTextOnValue(IOrganizationService service, string entityName, string attributeName, int selectedValue)
        {
            try
            {
                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest {
                    EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true
                };
                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
                OptionMetadata[]          optionList = null;
                if (((MemberInfo)retrieveAttributeResponse.AttributeMetadata.GetType()).Name.ToUpperInvariant() == "STATUSATTRIBUTEMETADATA")
                {
                    StatusAttributeMetadata retrievedPicklistAttributeMetadata = (StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }

                if (((MemberInfo)retrieveAttributeResponse.AttributeMetadata.GetType()).Name.ToUpperInvariant() == "PICKLISTATTRIBUTEMETADATA")
                {
                    PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }

                if (((MemberInfo)retrieveAttributeResponse.AttributeMetadata.GetType()).Name.ToUpperInvariant() == "STATEATTRIBUTEMETADATA")
                {
                    StateAttributeMetadata retrievedPicklistAttributeMetadata = (StateAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }

                string selectedOptionLabel = string.Empty;
                if (optionList.Length > 0)
                {
                    foreach (OptionMetadata oMD in optionList)
                    {
                        if (oMD.Value == selectedValue)
                        {
                            selectedOptionLabel = oMD.Label.UserLocalizedLabel.Label;
                            break;
                        }
                    }
                }

                return(selectedOptionLabel);
            }
            catch (FaultException)
            {
                return(string.Empty);
            }
        }
        private void GenerateStatusEnums(StatusAttributeMetadata statusAttr, StateAttributeMetadata stateAttr)
        {
            WriteLine();
            WriteLine("'StatusCodes': {");

            var options = CreateFileHandler.GetStatusOptionItems(statusAttr, stateAttr, this._listStringMap);

            WriteLine();

            // Формируем значения
            foreach (var item in options.OrderBy(op => op.LinkedStateCode).ThenBy(op => op.Value))
            {
                WriteLine(item.MakeStringJS());
            }

            WriteLine("},");
        }
        private void GenerateStateEnums(StateAttributeMetadata stateAttr, StatusAttributeMetadata statusAttr)
        {
            WriteLine();
            WriteLine("'StateCodes': {");

            var options = CreateFileHandler.GetStateOptionItems(statusAttr, stateAttr, this._listStringMap);

            WriteLine();

            // Формируем значения
            foreach (var item in options)
            {
                WriteLine(item.MakeStringJS());
            }

            WriteLine("},");
        }
Esempio n. 10
0
        private OptionMetadataCollection GetStateCodeOptionsSetTextOnValue(string entityName, string attributeName)
        {
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = entityName,
                LogicalName           = attributeName,
                RetrieveAsIfPublished = true
            };
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)Service.Execute(retrieveAttributeRequest);
            StateAttributeMetadata    attributeMetadata         = (StateAttributeMetadata)retrieveAttributeResponse?.AttributeMetadata;

            if (attributeMetadata == null)
            {
                return(null);
            }
            return(attributeMetadata?.OptionSet?.Options);
        }
Esempio n. 11
0
        public static string GetOptionSetTextGivenValue(this Entity entity, IOrganizationService service, string entityName, string attributeName, int selectedValue)
        {
            try
            {
                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest {
                    EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true
                };
                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
                OptionMetadata[]          optionList;

                if (attributeName == "statecode")
                {
                    StateAttributeMetadata retrievedPicklistAttributeMetadata = (StateAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }
                else if (attributeName == "statuscode")
                {
                    StatusAttributeMetadata retrievedPicklistAttributeMetadata = (StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }
                else
                {
                    PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }

                string selectedOptionValue = "";
                if (selectedValue != null)
                {
                    foreach (OptionMetadata oMD in optionList)
                    {
                        if (oMD.Value == selectedValue)
                        {
                            selectedOptionValue = oMD.Label.UserLocalizedLabel.Label;
                            break;
                        }
                    }
                }
                return(selectedOptionValue);
            }
            catch (System.ServiceModel.FaultException ex1)
            {
                string strEr = ex1.InnerException.Data.ToString();
                return("");
            }
        }
        private void GenerateStateEnums(StateAttributeMetadata stateAttr, StatusAttributeMetadata statusAttr)
        {
            WriteLine(",");
            WriteLine();
            WriteLine("'StateCodes': {");

            var options = GetStateOptionItems(statusAttr, stateAttr, this._listStringMap);

            WriteLine();

            bool first = true;

            // Формируем значения
            foreach (var item in options)
            {
                WriteCommaIfNotFirstLine(ref first);

                Write(item.MakeStringJS());
            }

            WriteLine();
            Write("}");
        }
        public void OptionSetBeanTest02()
        {
            LocalizedLabel lLabel = new LocalizedLabel("Option1", LANG_CODE);
            LocalizedLabel lLabel2 = new LocalizedLabel("Option2", LANG_CODE);

            StateAttributeMetadata meta = new StateAttributeMetadata();
            meta.OptionSet = new OptionSetMetadata()
            {
                Name = "optionSet",
                DisplayName = new Label("optiondisplay", LANG_CODE),
                Options =
                {
                     new OptionMetadata(new Label(lLabel, null), 1),
                     new OptionMetadata(new Label(lLabel2, null), null)
                }
            };

            OptionSetBean cls = new OptionSetBean(meta);

            Assert.True(cls.HasOptionSet());
            Assert.AreEqual("Option1", cls.GetValue(1), "ラベルあり");
            Assert.Null(cls.GetValue(2), "ラベルなし");
        }
Esempio n. 14
0
        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);
        }
        public void OptionSetBeanTest02()
        {
            LocalizedLabel lLabel  = new LocalizedLabel("Option1", LANG_CODE);
            LocalizedLabel lLabel2 = new LocalizedLabel("Option2", LANG_CODE);

            StateAttributeMetadata meta = new StateAttributeMetadata();

            meta.OptionSet = new OptionSetMetadata()
            {
                Name        = "optionSet",
                DisplayName = new Label("optiondisplay", LANG_CODE),
                Options     =
                {
                    new OptionMetadata(new Label(lLabel,  null), 1),
                    new OptionMetadata(new Label(lLabel2, null), null)
                }
            };

            OptionSetBean cls = new OptionSetBean(meta);

            Assert.True(cls.HasOptionSet());
            Assert.AreEqual("Option1", cls.GetValue(1), "ラベルあり");
            Assert.Null(cls.GetValue(2), "ラベルなし");
        }
Esempio n. 16
0
        /// <summary>
        /// フィールドのオプションセットを取得する。
        /// </summary>
        /// <param name="attr"></param>
        public OptionSetBean(AttributeMetadata attr)
        {
            valueMap = new Dictionary <int, Label>();
            PicklistAttributeMetadata picklistAttr = attr as PicklistAttributeMetadata;
            StateAttributeMetadata    stateAttr    = attr as StateAttributeMetadata;
            StatusAttributeMetadata   statusAttr   = attr as StatusAttributeMetadata;

            // オプションセットを取得する。
            OptionSetMetadata option = null;

            if (picklistAttr != null)
            {
                option = picklistAttr.OptionSet;
            }
            else if (stateAttr != null)
            {
                option = stateAttr.OptionSet;
            }
            else if (statusAttr != null)
            {
                option = statusAttr.OptionSet;
            }
            else
            {
                return;
            }


            foreach (OptionMetadata opt in option.Options)
            {
                if (opt.Value != null)
                {
                    valueMap.Add((int)opt.Value, opt.Label);
                }
            }
        }
        private void WriteStateStatusEnums()
        {
            StateAttributeMetadata  stateAttr  = null;
            StatusAttributeMetadata statusAttr = null;

            foreach (AttributeMetadata attrib in _entityMetadata.Attributes.OrderBy(attr => attr.LogicalName))
            {
                if (attrib is StatusAttributeMetadata)
                {
                    statusAttr = attrib as StatusAttributeMetadata;
                }
                else if (attrib is StateAttributeMetadata)
                {
                    stateAttr = attrib as StateAttributeMetadata;
                }
            }

            if (stateAttr != null && statusAttr != null)
            {
                GenerateStateEnums(stateAttr, statusAttr);

                GenerateStatusEnums(statusAttr, stateAttr);
            }
        }
Esempio n. 18
0
        /// <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);
        }
Esempio n. 19
0
        public static List <OptionItem> GetStateOptionItems(StatusAttributeMetadata statusAttr, StateAttributeMetadata stateAttr, List <StringMap> listStringMap)
        {
            var options = new List <OptionItem>();

            foreach (StateOptionMetadata optionValue in stateAttr.OptionSet.Options)
            {
                if (!optionValue.Value.HasValue)
                {
                    continue;
                }

                var defaultStatusCodeName = "Null";

                if (optionValue.DefaultStatus.HasValue)
                {
                    var statusOptionValue = statusAttr.OptionSet.Options.FirstOrDefault(op => op.Value.Value == optionValue.DefaultStatus.Value);

                    if (statusOptionValue != null)
                    {
                        string statusLabel = GetLocalizedLabel(statusOptionValue.Label);

                        defaultStatusCodeName = GetOptionSetValueName(statusLabel, statusOptionValue.Value.Value);
                    }
                    else
                    {
                        defaultStatusCodeName = string.Format("Not finded: {0}", optionValue.DefaultStatus.ToString());
                    }
                }

                var stateName = GetStateName(optionValue);

                if (!string.IsNullOrEmpty(stateName))
                {
                    int?displayOrder = null;

                    if (listStringMap != null)
                    {
                        var stringMap = listStringMap.FirstOrDefault(e =>
                                                                     string.Equals(e.AttributeName, stateAttr.LogicalName, StringComparison.InvariantCultureIgnoreCase) &&
                                                                     string.Equals(e.ObjectTypeCode, stateAttr.EntityLogicalName, StringComparison.InvariantCultureIgnoreCase) &&
                                                                     e.AttributeValue == optionValue.Value.Value
                                                                     );

                        if (stringMap != null)
                        {
                            displayOrder = stringMap.DisplayOrder;
                        }
                    }

                    var optionItem = new OptionItem()
                    {
                        FieldName = stateName,
                        Value     = optionValue.Value.Value,

                        Label       = optionValue.Label,
                        Description = optionValue.Description,

                        DefaultStatusCode     = optionValue.DefaultStatus,
                        DefaultStatusCodeName = defaultStatusCodeName,

                        InvariantName = optionValue.InvariantName,

                        DisplayOrder = displayOrder,

                        OptionMetadata = optionValue,
                    };

                    options.Add(optionItem);
                }
            }

            options = options.OrderBy(op => op.DisplayOrder).ToList();

            return(options);
        }
Esempio n. 20
0
 // ReSharper disable once UnusedParameter.Local
 private AttributeMetadata CloneAttributes(StateAttributeMetadata att)
 {
     return(new StateAttributeMetadata());
 }
Esempio n. 21
0
        /// <summary>
        /// </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();

                    //<snippetDumpPicklistInfo1>
                    #region How to dump attribute info
                    //<snippetDumpPicklistInfo2>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        // 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
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }

                                #region Attributes

                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                {
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                }
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    //</snippetDumpPicklistInfo2>
                    #endregion How to dump attribute info



                    Console.WriteLine("Done.");
                    //</snippetDumpPicklistInfo1>

                    //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;
            }
        }
Esempio n. 22
0
        public static IEnumerable <AttributeMetadata> GetGlobalMetadata()
        {
            var createdon = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime, "createdon")
            {
                LogicalName = "createdon"
            };

            yield return(createdon);

            var createdonbehalfby = new LookupAttributeMetadata()
            {
                SchemaName  = "createdonbehalfby",
                LogicalName = "createdonbehalfby"
            };

            yield return(createdonbehalfby);

            var createdby = new LookupAttributeMetadata()
            {
                SchemaName  = "createdby",
                LogicalName = "createdby"
            };

            yield return(createdby);

            var modifiedon = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime, "modifiedon")
            {
                LogicalName = "modifiedon"
            };

            yield return(modifiedon);

            var modifiedonbehalfby = new LookupAttributeMetadata()
            {
                SchemaName  = "modifiedonbehalfby",
                LogicalName = "modifiedonbehalfby"
            };

            yield return(modifiedonbehalfby);

            var modifiedby = new LookupAttributeMetadata()
            {
                SchemaName  = "modifiedby",
                LogicalName = "modifiedby"
            };

            yield return(modifiedby);

            var overridencreatedon = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime, "overridencreatedon")
            {
                LogicalName = "overridencreatedon"
            };

            yield return(overridencreatedon);

            var overridencreatedby = new LookupAttributeMetadata()
            {
                SchemaName  = "overridencreatedby",
                LogicalName = "overridencreatedby"
            };

            yield return(overridencreatedby);

            var statecode = new StateAttributeMetadata()
            {
                SchemaName  = "statecode",
                LogicalName = "statecode"
            };

            yield return(statecode);
        }
Esempio n. 23
0
        //<snippetStateModelTransitions.GetValidStatusOptions>
        /// <summary>
        /// Returns valid status option transitions regardless of whether state transitions are enabled for the entity
        /// </summary>
        /// <param name="entityLogicalName">The logical name of the entity</param>
        /// <param name="currentStatusValue">The current status of the entity instance</param>
        /// <returns>A list of StatusOptions that represent the valid transitions</returns>
        public List <StatusOption> GetValidStatusOptions(String entityLogicalName, int currentStatusValue)
        {
            List <StatusOption> validStatusOptions = new List <StatusOption>();

            //Check entity Metadata

            //Retrieve just one entity definition
            MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
            //Return the attributes and the EnforceStateTransitions property
            MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes", "EnforceStateTransitions" });

            //Retrieve only State or Status attributes
            MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.Or);

            attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
            attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State));

            //Retrieve only the OptionSet property of the attributes
            MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });

            //Set the query
            EntityQueryExpression query = new EntityQueryExpression()
            {
                Criteria       = entityFilter,
                Properties     = entityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Criteria = attributeFilter, Properties = attributeProperties
                }
            };

            //Retrieve the metadata
            RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest()
            {
                Query = query
            };
            RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);

            //Check the value of EnforceStateTransitions
            Boolean?EnforceStateTransitions = response.EntityMetadata[0].EnforceStateTransitions;

            //Capture the state and status attributes
            StatusAttributeMetadata statusAttribute = new StatusAttributeMetadata();
            StateAttributeMetadata  stateAttribute  = new StateAttributeMetadata();

            foreach (AttributeMetadata attributeMetadata in response.EntityMetadata[0].Attributes)
            {
                switch (attributeMetadata.AttributeType)
                {
                case AttributeTypeCode.Status:
                    statusAttribute = (StatusAttributeMetadata)attributeMetadata;
                    break;

                case AttributeTypeCode.State:
                    stateAttribute = (StateAttributeMetadata)attributeMetadata;
                    break;
                }
            }


            if (EnforceStateTransitions.HasValue && EnforceStateTransitions.Value == true)
            {
                //When EnforceStateTransitions is true use the TransitionData to filter the valid options
                foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
                {
                    if (option.Value == currentStatusValue)
                    {
                        if (option.TransitionData != String.Empty)
                        {
                            XDocument transitionData = XDocument.Parse(option.TransitionData);

                            IEnumerable <XElement> elements = (((XElement)transitionData.FirstNode)).Descendants();

                            foreach (XElement e in elements)
                            {
                                int    statusOptionValue = Convert.ToInt32(e.Attribute("tostatusid").Value);
                                String statusLabel       = GetOptionSetLabel(statusAttribute, statusOptionValue);

                                string stateLabel = String.Empty;
                                int?   stateValue = null;
                                foreach (StatusOptionMetadata statusOption in statusAttribute.OptionSet.Options)
                                {
                                    if (statusOption.Value.Value == statusOptionValue)
                                    {
                                        stateValue = statusOption.State.Value;
                                        stateLabel = GetOptionSetLabel(stateAttribute, stateValue.Value);
                                    }
                                }


                                validStatusOptions.Add(new StatusOption()
                                {
                                    StateLabel  = stateLabel,
                                    StateValue  = stateValue.Value,
                                    StatusLabel = statusLabel,
                                    StatusValue = option.Value.Value
                                });
                            }
                        }
                    }
                }
            }
            else
            {
                ////When EnforceStateTransitions is false do not filter the available options

                foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
                {
                    if (option.Value != currentStatusValue)
                    {
                        String statusLabel = "";
                        try
                        {
                            statusLabel = option.Label.UserLocalizedLabel.Label;
                        }
                        catch (Exception)
                        {
                            statusLabel = option.Label.LocalizedLabels[0].Label;
                        };

                        String stateLabel = GetOptionSetLabel(stateAttribute, option.State.Value);

                        validStatusOptions.Add(new StatusOption()
                        {
                            StateLabel  = stateLabel,
                            StateValue  = option.State.Value,
                            StatusLabel = statusLabel,
                            StatusValue = option.Value.Value
                        });
                    }
                }
            }
            return(validStatusOptions);
        }
Esempio n. 24
0
  //<snippetStateModelTransitions.GetValidStatusOptions>
  /// <summary>
  /// Returns valid status option transitions regardless of whether state transitions are enabled for the entity
  /// </summary>
  /// <param name="entityLogicalName">The logical name of the entity</param>
  /// <param name="currentStatusValue">The current status of the entity instance</param>
  /// <returns>A list of StatusOptions that represent the valid transitions</returns>
  public List<StatusOption> GetValidStatusOptions(String entityLogicalName, int currentStatusValue)
  {

   List<StatusOption> validStatusOptions = new List<StatusOption>();

   //Check entity Metadata

   //Retrieve just one entity definition
   MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
   entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
   //Return the attributes and the EnforceStateTransitions property
   MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes", "EnforceStateTransitions" });

   //Retrieve only State or Status attributes
   MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.Or);
   attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
   attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State));

   //Retrieve only the OptionSet property of the attributes
   MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });

   //Set the query
   EntityQueryExpression query = new EntityQueryExpression()
   {
    Criteria = entityFilter,
    Properties = entityProperties,
    AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }
   };

   //Retrieve the metadata
   RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = query };
   RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);

   //Check the value of EnforceStateTransitions
   Boolean? EnforceStateTransitions = response.EntityMetadata[0].EnforceStateTransitions;

   //Capture the state and status attributes
   StatusAttributeMetadata statusAttribute = new StatusAttributeMetadata();
   StateAttributeMetadata stateAttribute = new StateAttributeMetadata();

   foreach (AttributeMetadata attributeMetadata in response.EntityMetadata[0].Attributes)
   {
    switch (attributeMetadata.AttributeType)
    {
     case AttributeTypeCode.Status:
      statusAttribute = (StatusAttributeMetadata)attributeMetadata;
      break;
     case AttributeTypeCode.State:
      stateAttribute = (StateAttributeMetadata)attributeMetadata;
      break;
    }
   }


   if (EnforceStateTransitions.HasValue && EnforceStateTransitions.Value == true)
   {
    //When EnforceStateTransitions is true use the TransitionData to filter the valid options
    foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
    {
     if (option.Value == currentStatusValue)
     {
      if (option.TransitionData != String.Empty)
      {
       XDocument transitionData = XDocument.Parse(option.TransitionData);

       IEnumerable<XElement> elements = (((XElement)transitionData.FirstNode)).Descendants();

       foreach (XElement e in elements)
       {
        int statusOptionValue = Convert.ToInt32(e.Attribute("tostatusid").Value);
        String statusLabel = GetOptionSetLabel(statusAttribute, statusOptionValue);

        string stateLabel = String.Empty;
        int? stateValue = null;
        foreach (StatusOptionMetadata statusOption in statusAttribute.OptionSet.Options)
        {
         if (statusOption.Value.Value == statusOptionValue)
         {
          stateValue = statusOption.State.Value;
          stateLabel = GetOptionSetLabel(stateAttribute, stateValue.Value);
         }

        }


        validStatusOptions.Add(new StatusOption()
        {
         StateLabel = stateLabel,
         StateValue = stateValue.Value,
         StatusLabel = statusLabel,
         StatusValue = option.Value.Value
        });
       }
      }
     }
    }

   }
   else
   {
    ////When EnforceStateTransitions is false do not filter the available options

    foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
    {
     if (option.Value != currentStatusValue)
     {

      String statusLabel = "";
      try
      {
       statusLabel = option.Label.UserLocalizedLabel.Label;
      }
      catch (Exception)
      {
       statusLabel = option.Label.LocalizedLabels[0].Label;
      };

      String stateLabel = GetOptionSetLabel(stateAttribute, option.State.Value);

      validStatusOptions.Add(new StatusOption()
      {
       StateLabel = stateLabel,
       StateValue = option.State.Value,
       StatusLabel = statusLabel,
       StatusValue = option.Value.Value

      });
     }
    }
   }
   return validStatusOptions;

  }
Esempio n. 25
0
        [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
                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        // 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
                    };

                    // Retrieve the MetaData.
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }

                                #region Attributes

                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                {
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                }
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    Console.WriteLine("Done.");
                    #endregion Demonstrate
                }
                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();
            }
        }
 public StateAttributeMetadataInfo(StateAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
 // ReSharper disable once UnusedParameter.Local
 private AttributeMetadata CloneAttributes(StateAttributeMetadata att)
 {
     return new StateAttributeMetadata();
 }
        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;
        }
Esempio n. 29
0
        public static IEnumerable <EntityMetadata> FromEarlyBoundEntities(Assembly earlyBoundEntitiesAssembly)
        {
            List <EntityMetadata> entityMetadatas = new List <EntityMetadata>();

            foreach (var earlyBoundEntity in earlyBoundEntitiesAssembly.GetTypes())
            {
                EntityLogicalNameAttribute entityLogicalNameAttribute = GetCustomAttribute <EntityLogicalNameAttribute>(earlyBoundEntity);
                if (entityLogicalNameAttribute == null)
                {
                    continue;
                }
                EntityMetadata metadata = new EntityMetadata();
                metadata.LogicalName = entityLogicalNameAttribute.LogicalName;

                FieldInfo entityTypeCode = earlyBoundEntity.GetField("EntityTypeCode", BindingFlags.Static | BindingFlags.Public);
                if (entityTypeCode != null)
                {
                    metadata.SetFieldValue("_objectTypeCode", entityTypeCode.GetValue(null));
                }

                List <AttributeMetadata> attributeMetadatas = new List <AttributeMetadata>();
                List <ManyToManyRelationshipMetadata> manyToManyRelationshipMetadatas = new List <ManyToManyRelationshipMetadata>();
                List <OneToManyRelationshipMetadata>  oneToManyRelationshipMetadatas  = new List <OneToManyRelationshipMetadata>();
                List <OneToManyRelationshipMetadata>  manyToOneRelationshipMetadatas  = new List <OneToManyRelationshipMetadata>();

                var idProperty = earlyBoundEntity.GetProperty("Id");
                AttributeLogicalNameAttribute attributeLogicalNameAttribute;
                if (idProperty != null && (attributeLogicalNameAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(idProperty)) != null)
                {
                    metadata.SetFieldValue("_primaryIdAttribute", attributeLogicalNameAttribute.LogicalName);
                }

                var properties = earlyBoundEntity.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                 .Where(x => x.Name != "Id" && Attribute.IsDefined(x, typeof(AttributeLogicalNameAttribute)) ||
                                        Attribute.IsDefined(x, typeof(RelationshipSchemaNameAttribute)));

                foreach (var property in properties)
                {
                    RelationshipSchemaNameAttribute relationshipSchemaNameAttribute = GetCustomAttribute <RelationshipSchemaNameAttribute>(property);
                    attributeLogicalNameAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(property);

                    if (relationshipSchemaNameAttribute == null)
                    {
#if !FAKE_XRM_EASY
                        if (property.PropertyType == typeof(byte[]))
                        {
                            metadata.SetFieldValue("_primaryImageAttribute", attributeLogicalNameAttribute.LogicalName);
                        }
#endif
                        AttributeMetadata attributeMetadata;
                        if (attributeLogicalNameAttribute.LogicalName == "statecode")
                        {
                            attributeMetadata = new StateAttributeMetadata();
                        }
                        else if (attributeLogicalNameAttribute.LogicalName == "statuscode")
                        {
                            attributeMetadata = new StatusAttributeMetadata();
                        }
                        else if (attributeLogicalNameAttribute.LogicalName == metadata.PrimaryIdAttribute)
                        {
                            attributeMetadata = new AttributeMetadata();
                            attributeMetadata.SetSealedPropertyValue("AttributeType", AttributeTypeCode.Uniqueidentifier);
                        }
                        else
                        {
                            attributeMetadata = CreateAttributeMetadata(property.PropertyType);
                        }

                        attributeMetadata.SetFieldValue("_entityLogicalName", entityLogicalNameAttribute.LogicalName);
                        attributeMetadata.SetFieldValue("_logicalName", attributeLogicalNameAttribute.LogicalName);

                        attributeMetadatas.Add(attributeMetadata);
                    }
                    else
                    {
                        if (property.PropertyType.Name == "IEnumerable`1")
                        {
                            PropertyInfo peerProperty = property.PropertyType.GetGenericArguments()[0].GetProperties().SingleOrDefault(x => x.PropertyType == earlyBoundEntity && GetCustomAttribute <RelationshipSchemaNameAttribute>(x)?.SchemaName == relationshipSchemaNameAttribute.SchemaName);
                            if (peerProperty == null || peerProperty.PropertyType.Name == "IEnumerable`1") // N:N relationship
                            {
                                ManyToManyRelationshipMetadata relationshipMetadata = new ManyToManyRelationshipMetadata();
                                relationshipMetadata.SchemaName = relationshipSchemaNameAttribute.SchemaName;

                                manyToManyRelationshipMetadatas.Add(relationshipMetadata);
                            }
                            else // 1:N relationship
                            {
                                AddOneToManyRelationshipMetadata(earlyBoundEntity, property, property.PropertyType.GetGenericArguments()[0], peerProperty, oneToManyRelationshipMetadatas);
                            }
                        }
                        else //N:1 Property
                        {
                            AddOneToManyRelationshipMetadata(property.PropertyType, property.PropertyType.GetProperties().SingleOrDefault(x => x.PropertyType.GetGenericArguments().SingleOrDefault() == earlyBoundEntity && GetCustomAttribute <RelationshipSchemaNameAttribute>(x)?.SchemaName == relationshipSchemaNameAttribute.SchemaName), earlyBoundEntity, property, manyToOneRelationshipMetadatas);
                        }
                    }
                }
                if (attributeMetadatas.Any())
                {
                    metadata.SetSealedPropertyValue("Attributes", attributeMetadatas.ToArray());
                }
                if (manyToManyRelationshipMetadatas.Any())
                {
                    metadata.SetSealedPropertyValue("ManyToManyRelationships", manyToManyRelationshipMetadatas.ToArray());
                }
                if (manyToOneRelationshipMetadatas.Any())
                {
                    metadata.SetSealedPropertyValue("ManyToOneRelationships", manyToOneRelationshipMetadatas.ToArray());
                }
                if (oneToManyRelationshipMetadatas.Any())
                {
                    metadata.SetSealedPropertyValue("OneToManyRelationships", oneToManyRelationshipMetadatas.ToArray());
                }
                entityMetadatas.Add(metadata);
            }
            return(entityMetadatas);
        }
 public StateAttributeMetadataInfo(StateAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
Esempio n. 31
0
        public static List <Dynamics365State> GetStates(Dynamics365Entity entity, Dynamics365Connection connection)
        {
            ConnectionCache         cache    = new ConnectionCache(connection);
            string                  cacheKey = string.Format("GetStates:{0}", entity.LogicalName);
            List <Dynamics365State> states   = (List <Dynamics365State>)cache[cacheKey];

            if (states == null)
            {
                states = new List <Dynamics365State>();
                RetrieveEntityRequest request = new RetrieveEntityRequest()
                {
                    LogicalName           = entity.LogicalName,
                    EntityFilters         = EntityFilters.Attributes,
                    RetrieveAsIfPublished = false
                };

                using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy)
                {
                    RetrieveEntityResponse response      = (RetrieveEntityResponse)proxy.Execute(request);
                    StateAttributeMetadata stateMetadata = (StateAttributeMetadata)response.EntityMetadata.Attributes.FirstOrDefault(findField => findField is StateAttributeMetadata);

                    if (stateMetadata != null)
                    {
                        foreach (StateOptionMetadata stateOption in stateMetadata.OptionSet.Options)
                        {
                            Dynamics365State state = new Dynamics365State()
                            {
                                Code        = (int)stateOption.Value,
                                Name        = stateOption.Label.UserLocalizedLabel.Label,
                                LogicalName = stateMetadata.LogicalName
                            };
                            StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)response.EntityMetadata.Attributes.FirstOrDefault(findField => findField is StatusAttributeMetadata);

                            if (statusMetadata != null)
                            {
                                foreach (StatusOptionMetadata statusOption in statusMetadata.OptionSet.Options)
                                {
                                    if (statusOption.State == state.Code)
                                    {
                                        Dynamics365Status status = new Dynamics365Status()
                                        {
                                            Code        = (int)statusOption.Value,
                                            Name        = statusOption.Label.UserLocalizedLabel.Label,
                                            LogicalName = statusMetadata.LogicalName
                                        };
                                        state.Statuses.Add(status);
                                    }
                                }

                                //state.Statuses.Sort((status1, status2) => status1.Name.CompareTo(status2.Name));
                            }

                            states.Add(state);
                        }
                    }
                }

                //states.Sort((state1, state2) => state1.Name.CompareTo(state2.Name));
                cache[cacheKey] = states;
            }

            return(states);
        }