private EntityReference GetProviderTeam(IOrganizationService service, Guid caseid)
        {
            ////trace.Trace(caseid.ToString());
            string           query  = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                                          <entity name='incident'>
                                                            <attribute name='customerid' />
                                                            <attribute name='incidentid' />
                                                            <order attribute='incidentid' descending='false' />
                                                            <filter type='and'>
                                                              <condition attribute='incidentid' operator='eq' value='" + caseid + @"' />
                                                            </filter>
                                                            <link-entity name='account' from='accountid' to='customerid' link-type='inner' alias='aa'>
                                                              <attribute name='smp_providerteam' />
                                                            </link-entity>
                                                          </entity>
                                                        </fetch>";
            EntityCollection result = service.RetrieveMultiple(new FetchExpression(query));

            if (result != null && result.Entities.Count > 0)
            {
                AliasedValue providerTeamAlias = result.Entities[0].GetAttributeValue <AliasedValue>("aa.smp_providerteam");
                return((EntityReference)providerTeamAlias.Value);
            }

            return(null);
        }
        private static object ProcessAliasedValue(CrmAttributeStore attribute, object attributeValue)
        {
            var aliasedValue = (JObject)attribute.AttributeValue;

            if (aliasedValue["Value"].Any())
            {
                try
                {
                    var entValue = aliasedValue["Value"];

                    if (entValue["Name"] != null)
                    {
                        var aliasedValueLookup = new AliasedValue((string)aliasedValue["EntityLogicalName"], (string)aliasedValue["AttributeLogicalName"], (string)entValue["Name"]);
                        attributeValue = aliasedValueLookup;
                    }
                    else if (entValue["Value"] != null)
                    {
                        var aliasedValueLookup = new AliasedValue((string)aliasedValue["EntityLogicalName"], (string)aliasedValue["AttributeLogicalName"], (string)entValue["Value"]);
                        attributeValue = aliasedValueLookup;
                    }
                }
                catch (Exception ex)
                {
                    throw new ConfigurationException($"Unsupported type used for alias {(string)aliasedValue["EntityLogicalName"]}, only EntityReference and string are supported, error:{ex.ToString()}", ex);
                }
            }
            else
            {
                var aliasedValueLookup = new AliasedValue((string)aliasedValue["EntityLogicalName"], (string)aliasedValue["AttributeLogicalName"], (string)aliasedValue["Value"]);
                attributeValue = aliasedValueLookup;
            }

            return(attributeValue);
        }
예제 #3
0
        /// <summary>
        /// Om entiteten innehåller attribut från länkade entiteter efter läsning så måste aliaset för den länkade entiteten anges.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="linkedEntityAlias"></param>
        /// <param name="name"></param>
        /// <param name="default"></param>
        /// <returns></returns>
        public static T PropertyLinkedEntity <T>(this Entity entity, string linkedEntityAlias, string name, T @default)
        {
            var defaultValue = new AliasedValue(linkedEntityAlias, name, @default);
            var value        = (T)entity.GetAttribute(linkedEntityAlias + "." + name, defaultValue).Value;

            return(value);
        }
예제 #4
0
        public int CountNNRelationship(string relationshipName, string countIdName)
        {
            string numberAlias = "numberofentities";

            XDocument xDocument = new XDocument(
                new XElement("fetch", new XAttribute("aggregate", true),
                             new XElement("entity", new XAttribute("name", entityName),
                                          new XElement("link-entity", new XAttribute("from", idName), new XAttribute("name", relationshipName), new XAttribute("to", idName),
                                                       new XElement("attribute", new XAttribute("name", countIdName), new XAttribute("aggregate", "count"), new XAttribute("alias", numberAlias))),
                                          new XElement("filter",
                                                       new XElement("condition", new XAttribute("attribute", idName), new XAttribute("operator", "eq"), new XAttribute("value", Id))))));

            FetchExpression fetchExpression = new FetchExpression(xDocument.ToString());

            EntityCollection entityCollection = Connection.Service.RetrieveMultiple(fetchExpression);

            int collectionCount = entityCollection.Entities.Count;

            if (collectionCount == 0)
            {
                return(0);
            }

            if (collectionCount != 1)
            {
                throw new Exception("wrong collection count");
            }

            Entity entity = entityCollection.Entities[0];

            AliasedValue aliasedValue = (AliasedValue)entity.Attributes[numberAlias];

            return((int)aliasedValue.Value);
        }
        private object ConvertCRMValueToSharePointValue <T>(string crmEntityAlias, string crmFieldName, object value)
        {
            object result = null;

            if (value is AliasedValue)
            {
                AliasedValue aliasedValue = value as AliasedValue;

                result = (T)aliasedValue.Value;
            }
            else
            {
                result = (T)value;
            }

            //Conversions to support SharePoint
            if (result is OptionSetValue)
            {
                //if (string.IsNullOrEmpty(crmEntityAlias) || string.IsNullOrEmpty(crmFieldName))
                //{
                //    throw new Exception("Error converting CRM Value to SharePoint Value; CRM Entity Alias or CRM Field Name not specified");
                //}

                //result = Query.GetCRMOptionsetText(AdminService, crmEntityAlias, crmFieldName, ((OptionSetValue)result).Value);
            }
            else if (result is bool)
            {
                result = (bool)result ? "Yes" : "No";
            }

            return(result);
        }
예제 #6
0
        /// <summary>
        /// Get attribute value for regarding attribute
        /// </summary>
        /// <param name="attribute">attribute name</param>
        /// <param name="entity">entity object</param>
        /// <returns>Entity reference for regarding attribute</returns>
        private static EntityReference GetRegardingAttributeValue(string attribute, Entity entity)
        {
            string          attributeType  = Convert.ToString(entity.Attributes[attribute].GetType(), CultureInfo.InvariantCulture);
            EntityReference attributeValue = null;

            switch (attributeType)
            {
            // EntityReference
            case "Microsoft.Xrm.Sdk.EntityReference":
                attributeValue = (EntityReference)entity.Attributes[attribute];
                break;

            // Guid Value
            case "System.Guid":
                attributeValue = new EntityReference(entity.LogicalName, (Guid)entity.Attributes[attribute]);
                break;

            // Aliased Value
            case "Microsoft.Xrm.Sdk.AliasedValue":
                string aliasedAttributeType = Convert.ToString(((AliasedValue)entity.Attributes[attribute]).Value.GetType(), CultureInfo.InvariantCulture);
                if (aliasedAttributeType == "Microsoft.Xrm.Sdk.EntityReference")
                {
                    attributeValue = (EntityReference)((AliasedValue)entity.Attributes[attribute]).Value;
                }
                else if (aliasedAttributeType == "System.Guid")
                {
                    AliasedValue attributeValueAlias = (AliasedValue)entity.Attributes[attribute];
                    attributeValue = new EntityReference(attributeValueAlias.EntityLogicalName, (Guid)attributeValueAlias.Value);
                }

                break;
            }

            return(attributeValue);
        }
예제 #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="crmAttribute"></param>
        /// <returns></returns>
        public static string GetAttributeStringValue(object crmAttribute)
        {
            OptionSetValue osv = crmAttribute as OptionSetValue;

            if (null != osv)
            {
                return(osv.Value.ToString());
            }

            Money mnVal = crmAttribute as Money;

            if (null != mnVal)
            {
                return(mnVal.Value.ToString());
            }

            AliasedValue alVal = crmAttribute as AliasedValue;

            if (null != alVal)
            {
                return(alVal.Value.ToString());
            }

            EntityReference er = crmAttribute as EntityReference;

            if (null != er)
            {
                return(er.Id.ToString());
            }

            return(crmAttribute.ToString());
        }
예제 #8
0
        public static string GetFieldValueAsString(Entity entity, string attributeName)
        {
            string sendValue = string.Empty;

            if (entity.Attributes.Contains(attributeName))
            {
                object value = entity.Attributes[attributeName];

                if (value != null)
                {
                    if (value.GetType() == typeof(AliasedValue))
                    {
                        AliasedValue aliasedValue = value as AliasedValue;

                        if (aliasedValue.Value != null)
                        {
                            sendValue = Convert.ToString(aliasedValue.Value);
                        }
                    }
                    else
                    {
                        sendValue = Convert.ToString(value);
                    }
                }
            }
            return(sendValue);
        }
        private Guid FindReplacementValue(EntityWrapper entity, string alias)
        {
            List <AliasedValue> aliasses = entity.OriginalEntity.Attributes
                                           .Where(s => s.Key.StartsWith(alias, StringComparison.InvariantCulture))
                                           .Select(a => a.Value as AliasedValue).ToList();

            int pos = 0;

            while (pos < aliasses.Count)
            {
                var    item       = aliasses[pos];
                string lookUpName = metCache.GetLookUpEntityName(item.EntityLogicalName, item.AttributeLogicalName);

                if (lookUpName == "businessunit" && (string)item.Value == mappingConfiguration.SourceRootBUName)
                {
                    var entRefValue = new EntityReference(lookUpName, targetBusinessUnitId);
                    aliasses[pos] = new AliasedValue(item.EntityLogicalName, item.AttributeLogicalName, entRefValue);
                    logger.LogVerbose($"Found Id:{entRefValue.Id} for entity {entRefValue.LogicalName} by name {entRefValue.Name} for {alias}, RootBU");
                }
                else if (lookUpName != null)
                {
                    var rec = targetRepo.FindEntitiesByName(lookUpName, (string)item.Value);
                    if (rec.Count == 1)
                    {
                        var entRefValue = new EntityReference(lookUpName, rec.First().Id);
                        aliasses[pos] = new AliasedValue(item.EntityLogicalName, item.AttributeLogicalName, entRefValue);
                        logger.LogVerbose($"Found Id:{entRefValue.Id} for entity {entRefValue.LogicalName} by name {entRefValue.Name} for {alias}");
                    }
                    else
                    {
                        logger.LogWarning($"Cannot find unique record, found {rec.Count} for {lookUpName} and Name {item.Value} for {alias}");
                        return(Guid.Empty);
                    }
                }

                pos++;
            }

            Guid replaceGuid = Guid.Empty;

            foreach (var rule in EntitySpecificRules)
            {
                try
                {
                    if (rule.ProcessImport(alias, aliasses, out object replaceCandidate))
                    {
                        replaceGuid = (Guid)replaceCandidate;
                        logger.LogVerbose($"FindReplacementValue: Entity:{entity.LogicalName}:{entity.Id} found Guid {replaceGuid} for {alias}");
                        break;
                    }
                }
                catch (Exception ex)
                {
                    logger.LogWarning($"FindReplacementValue: Entity:{entity.LogicalName}:{entity.Id}, Rule {rule.GetType().Name} for {alias} Error:{ex.Message}");
                }
            }

            return(replaceGuid);
        }
예제 #10
0
        /// <summary>
        /// Gets the formatted value.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <returns></returns>
        private string getFormattedValue(Entity entity, string attributeName)
        {
            KeyValuePair <string, object> kvp            = new KeyValuePair <string, object>();
            KeyValuePair <string, string> formattedValue = new KeyValuePair <string, string>();
            string value = "";

            if (entity.FormattedValues.Keys.Contains(attributeName))
            {
                formattedValue = entity.FormattedValues.First(k => k.Key == attributeName);
                value          = formattedValue.Value;
            }
            else if (entity.Attributes.Keys.Contains(attributeName))
            {
                kvp = entity.Attributes.First(k => k.Key == attributeName);

                Type t = kvp.Value.GetType();
                if (t.Name == "EntityReference")
                {
                    EntityReference er = (EntityReference)kvp.Value;
                    if (er.Name != null)
                    {
                        value = er.Name;
                    }
                }
                else if (t.Name == "AliasedValue")
                {
                    AliasedValue av = (AliasedValue)kvp.Value;
                    Type         t2 = av.Value.GetType();
                    if (t2.Name == "EntityReference")
                    {
                        EntityReference er2 = (EntityReference)av.Value;
                        if (er2.Name != null)
                        {
                            value = er2.Name;
                        }
                    }
                    else
                    {
                        value = av.Value.ToString();
                    }
                }
                else if (t.Name == "OptionSetValue")
                {
                    OptionSetValue osv = (OptionSetValue)kvp.Value;
                    value = osv.Value.ToString();
                }
                else if (attributeName == "entityimage" && t.Name == "Byte[]")
                {
                    byte[] binaryData = (byte[])kvp.Value;
                    value = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);
                }
                else
                {
                    value = kvp.Value.ToString();
                }
            }
            return(value);
        }
        private void InsertRow(ExcelWorksheet worksheet, Entity user, Entity role, int rowNumber)
        {
            // Add User
            this.PrepareCells(worksheet, worksheet.Cells[rowNumber, 1], Color.Black, Color.Empty, user[ModelSystemUser.Fields.FullName]);

            // Add Role
            AliasedValue retrievedName = role[ModelRole.Fields.RetrievedName] as AliasedValue;

            this.PrepareCells(worksheet, worksheet.Cells[rowNumber, 2], Color.Black, Color.Empty, retrievedName.Value);
        }
        public static Entity GetAliasedEntityLateBound(Entity entity, string aliasedEntityName, string aliasedEntityIdField)
        {
            var entityLogicalName = aliasedEntityName; //EntityHelper.GetEntityLogicalName<T>();
            var aliasedEntity     = new Entity();
            var idAttribute       = aliasedEntityIdField;

            foreach (var entry in entity.Attributes)
            {
                AliasedValue aliased = null;

                if (entry.Value is AliasedValue)
                {
                    aliased = (AliasedValue)entry.Value;
                }

                if (entry.Value is AliasedValue && aliased.EntityLogicalName == entityLogicalName &&
                    (
                        (aliasedEntityName == null && // No Entity Attribute Name Specified
                         (entry.Key.Contains(".") || entry.Key == aliased.AttributeLogicalName || aliased.AttributeLogicalName == idAttribute))
                        // And the key contains a "." or is an exact match on the aliased attribute logical name.  This keeps groupings that may not be the same type (Date Group by Day) from populating the aliased entity
                        // The one exception for this is the Id. which we want to include if we can
                        ||
                        (aliasedEntityName != null &&                   // Or an Entity Attribute Name is specified, and
                         entry.Key.StartsWith(aliasedEntityName + ".")) // it starts with the aliasedEntityName + ".
                    ))
                {
                    aliasedEntity[aliased.AttributeLogicalName] = aliased.Value;
                    if (entity.FormattedValues.TryGetValue(entry.Key, out string formattedValue))
                    {
                        aliasedEntity.FormattedValues[aliased.AttributeLogicalName] = formattedValue;
                    }
                }
            }

            // Remove names for Entity References.
            foreach (var entry in aliasedEntity.Attributes.Where(a => a.Key.EndsWith("name")).ToList())
            {
                var nonNameAttribute = entry.Key.Substring(0, entry.Key.Length - "name".Length);
                if (aliasedEntity.Contains(nonNameAttribute))
                {
                    if (aliasedEntity[nonNameAttribute] is EntityReference entityRef && entityRef.Name == (string)entry.Value)
                    {
                        aliasedEntity.Attributes.Remove(entry.Key);
                    }
                }
            }


            if (aliasedEntity.Attributes.Contains(idAttribute))
            {
                aliasedEntity.Id = (Guid)aliasedEntity[idAttribute];
            }

            return(aliasedEntity);
        }
예제 #13
0
        public void GetAliasedEntityGenericTest2()
        {
            /// Setup test data
            String mainEntityLogicalName    = "account";
            String linkedEntityLogicalName1 = "testentity";

            String       attributeLogicalName1 = "name";
            String       value1        = "Grunin Artem";
            AliasedValue aliasedValue1 = new AliasedValue(linkedEntityLogicalName1, attributeLogicalName1, value1);

            String       attributeLogicalName2 = "birthdate";
            DateTime?    value2        = new DateTime(1985, 8, 8);
            AliasedValue aliasedValue2 = new AliasedValue(linkedEntityLogicalName1, attributeLogicalName2, value2);

            /// Create Entity
            String alias1       = "ac";
            String aliasedName1 = $"{alias1}.{attributeLogicalName1}";
            String aliasedName2 = $"{alias1}.{attributeLogicalName2}";

            /// Create main entity
            Entity entity = new Entity(mainEntityLogicalName);

            /// Add main entity attributes
            entity.Attributes.Add("name", "FixRM");
            entity.Attributes.Add("accountnumber", "1");
            entity.Attributes.Add("statecode", new OptionSetValue(0));

            /// Add linked entity attributes
            entity.Attributes.Add(aliasedName1, aliasedValue1);
            entity.Attributes.Add(aliasedName2, aliasedValue2);

            TestEntity actualEntity;

            /// Test
            actualEntity = entity.GetAliasedEntity <TestEntity>(alias1);

            /// Instance is correct type
            Assert.IsNotNull(actualEntity);
            Assert.IsInstanceOfType(actualEntity, typeof(TestEntity));

            /// attribute values of early bound entity are ok
            Assert.AreEqual <String>(actualEntity.LogicalName, linkedEntityLogicalName1);
            Assert.AreEqual <int>(2, actualEntity.Attributes.Count);

            String actualAttributeValue1 = actualEntity.GetAttributeValue <String>(attributeLogicalName1);

            Assert.IsNotNull(actualAttributeValue1);
            Assert.AreEqual <String>(value1, actualAttributeValue1);

            DateTime?actualAttributeValue2 = actualEntity.GetAttributeValue <DateTime?>(attributeLogicalName2);

            Assert.IsNotNull(actualAttributeValue2);
            Assert.AreEqual <DateTime?>(value2, actualAttributeValue2);
        }
예제 #14
0
        public EntityCollection RetrieveMultiple(Microsoft.Xrm.Sdk.Query.QueryBase query)
        {
            EntityCollection collection       = new EntityCollection();
            AliasedValue     maxAccountNumber = new AliasedValue("account", "intnumber_max", 10);
            Entity           entity           = new Entity();

            entity.Attributes.Add("intnumber_max", maxAccountNumber);
            collection.Entities.Add(entity);

            return(collection);
        }
예제 #15
0
        public static T GetAliasedValue <T>(this Entity target, string key, T defaultValue = default(T))
        {
            if (!target.Contains(key) || target[key] is null)
            {
                return(defaultValue);
            }

            AliasedValue value = target.GetAttributeValue <AliasedValue>(key);

            return((T)value.Value);
        }
예제 #16
0
        public void GetAttributeValueForCsvAliasedValue()
        {
            var input     = new AliasedValue("contact", "contactid", Guid.NewGuid().ToString());
            var attribute = new CrmAttributeStore(new KeyValuePair <string, object>("firstname", input))
            {
                AttributeType = "Microsoft.Xrm.Sdk.AliasedValue"
            };

            var actual = EntityConverterHelper.GetAttributeValueForCsv(attribute);

            actual.Should().Be(input.Value);
        }
예제 #17
0
        public EntityReference GetRootEntityReference(Guid accountId)
        {
            Account         crmAccount    = new Account();
            EntityReference entityRef     = new EntityReference(LogicalName, accountId);
            EntityReference rootEntityRef = new EntityReference(LogicalName, accountId);

            string accountId1   = string.Format("{0}.{1}", AccountAlias1, crmAccount.Id.Key);
            string accountName1 = string.Format("{0}.{1}", AccountAlias1, crmAccount.Name.Key);

            string accountId2   = string.Format("{0}.{1}", AccountAlias2, crmAccount.Id.Key);
            string accountName2 = string.Format("{0}.{1}", AccountAlias2, crmAccount.Name.Key);

            string parentAccountId2 = string.Format("{0}.{1}", AccountAlias2, crmAccount.ParentAccountId.Key);

            AliasedValue aliasValue = null;

            for (; entityRef != null;)
            {
                List <Entity> accountSet = SvcHelper.RetrieveMultiple(new FetchExpression(GetFetchXml(entityRef.Id)));
                entityRef = null;
                if (accountSet[0].Contains(accountId2))
                {
                    if (accountSet[0].Contains(parentAccountId2))
                    {
                        aliasValue = accountSet[0].GetAttributeValue <AliasedValue>(parentAccountId2);
                        entityRef  = (EntityReference)aliasValue.Value;
                    }
                    else
                    {
                        aliasValue       = accountSet[0].GetAttributeValue <AliasedValue>(accountId2);
                        rootEntityRef.Id = (Guid)aliasValue.Value;
                        if (accountSet[0].Contains(accountName2))
                        {
                            aliasValue         = accountSet[0].GetAttributeValue <AliasedValue>(accountName2);
                            rootEntityRef.Name = (string)aliasValue.Value;
                        }
                    }
                }
                else if (accountSet[0].Contains(accountId1))
                {
                    aliasValue       = accountSet[0].GetAttributeValue <AliasedValue>(accountId1);
                    rootEntityRef.Id = (Guid)aliasValue.Value;
                    if (accountSet[0].Contains(accountName1))
                    {
                        aliasValue         = accountSet[0].GetAttributeValue <AliasedValue>(accountName1);
                        rootEntityRef.Name = (string)aliasValue.Value;
                    }
                }
            }

            return(rootEntityRef);
        }
예제 #18
0
        public void FetchXMLExpressionLinked(IOrganizationService service, string accountId)
        {
            var contactFirstName = default(object);
            var contactLastName  = default(object);
            var contactFullName  = default(object);

            string fetchXML = string.Format(@"<fetch version='1.0' output-format='xml-platform' no-lock='true' mapping='logical'>
                                        <entity name='account'>
                                            <attribute name='name' />                                                                                
                                            <filter type='and'>
                                                <condition attribute='statuscode' operator='eq' value='1' />                                            
                                                <condition attribute='accountid' operator='eq' value='{0}' />
                                            </filter>                                        
                                            <link-entity name='contact' from='contactid' to='primarycontactid' alias='ab'>
                                                 <attribute name='fullname' alias='as_fullname' />
                                                 <attribute name='firstname' alias='as_firstname' />                                             
                                                 <attribute name='lastname' alias='as_lastname' />
                                            </link-entity>
                                        </entity>
                                    </fetch>", accountId.ToString());

            var fetchExp = new FetchExpression(fetchXML);

            EntityCollection accountEntity = service.RetrieveMultiple(fetchExp);

            if (accountEntity.Entities.Count > 0)
            {
                //Primary Contact Fullname
                AliasedValue avContactFullname = accountEntity.Entities[0].GetAttributeValue <AliasedValue>("as_fullname");
                if (avContactFullname != null)
                {
                    contactFullName = avContactFullname.Value;
                }
                //Primary Contact Firstname
                AliasedValue avContactFirstname = accountEntity.Entities[0].GetAttributeValue <AliasedValue>("as_firstname");
                if (avContactFirstname != null)
                {
                    contactFirstName = avContactFirstname.Value;
                }
                //Primary Contact Lastname
                AliasedValue avContactLastname = accountEntity.Entities[0].GetAttributeValue <AliasedValue>("as_lastname");
                if (avContactLastname != null)
                {
                    contactLastName = avContactLastname.Value;
                }
                //to get optionset value
                int statusValue = ((OptionSetValue)accountEntity.Entities[0].GetAttributeValue <AliasedValue>("statusoption").Value).Value;

                var AccountLookupName = ((EntityReference)(accountEntity.Entities[0].GetAttributeValue <AliasedValue>("accountid").Value)).Name;
                var AccountLookupID   = ((EntityReference)(accountEntity.Entities[0].GetAttributeValue <AliasedValue>("accountid").Value)).Id;
            }
        }
        public static T GetAliasedValue <T>(this Entity Target, string EntityAlias, string FieldName, T DefaultValue)
        {
            string key = string.Format("{0}.{1}", EntityAlias, FieldName);

            if (!Target.Contains(key) || Target[key] is null)
            {
                return(DefaultValue);
            }

            AliasedValue value = Target.GetAttributeValue <AliasedValue>(key);

            return((T)value.Value);
        }
예제 #20
0
        private Guid ImportSolutionInTargetOrg(ITracingService tracingService, byte[] fileContent, EntityCollection credentials, string username, string password)
        {
            Guid asyncOperationId = Guid.Empty;
            IOrganizationService targetOrganizationService = null;

            //AliasedValue usernameAliasVal = credentials.Entities[0].GetAttributeValue<AliasedValue>("aa.devops_userid");
            //AliasedValue passwordAliasVal = credentials.Entities[0].GetAttributeValue<AliasedValue>("aa.devops_userpassword");
            AliasedValue orgSvcAliasVal = credentials.Entities[0].GetAttributeValue <AliasedValue>("aa.devops_orgserviceurl");

            //string userName = string.Empty;
            //string password = string.Empty;
            string orgSvcUrl = string.Empty;

            if (orgSvcAliasVal != null)
            {
                //userName = usernameAliasVal.Value.ToString();
                //password = passwordAliasVal.Value.ToString();
                orgSvcUrl = orgSvcAliasVal.Value.ToString();
            }

            ClientCredentials clientCredentials = new ClientCredentials();

            clientCredentials.UserName.UserName = username;
            clientCredentials.UserName.Password = password;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            tracingService.Trace($"Trying to create new OrganizationServiceProxy");
            targetOrganizationService = new OrganizationServiceProxy(new Uri(orgSvcUrl),
                                                                     null, clientCredentials, null);

            if (targetOrganizationService != null)
            {
                tracingService.Trace($"Starting import in target organization");
                var request = new ImportSolutionRequest()
                {
                    CustomizationFile = fileContent,
                    OverwriteUnmanagedCustomizations = OverWrite
                };
                var requestAsync = new ExecuteAsyncRequest
                {
                    Request = request
                };

                var asyncResp = (ExecuteAsyncResponse)targetOrganizationService.Execute(requestAsync);
                tracingService.Trace($"Executed the Import Request");

                asyncOperationId = asyncResp.AsyncJobId;
            }
            return(asyncOperationId);
        }
예제 #21
0
        public static T GetAliasedValue <T>(this Entity target, string key, T defaultValue = default)
        {
            _ = target ?? throw new ArgumentNullException(nameof(target));
            _ = key ?? throw new ArgumentNullException(nameof(key));

            if (!target.Contains(key) || target[key] is null)
            {
                return(defaultValue);
            }

            AliasedValue value = target.GetAttributeValue <AliasedValue>(key);

            return((T)value.Value);
        }
예제 #22
0
        public void updateContactOwner()
        {
            QueryExpression query = new QueryExpression("contact");

            query.ColumnSet = new ColumnSet(new string[] { "new_parentaccount", "ownerid", "fullname" });
            LinkEntity contactLink = new LinkEntity("contact", "account", "new_parentaccount", "accountid", JoinOperator.Inner);

            contactLink.EntityAlias = "Company";
            contactLink.Columns     = new ColumnSet(new string[] { "ownerid" });
            query.LinkEntities.Add(contactLink);
            IOrganizationService   service      = CRMHelper.ConnectToMSCRM1();
            EntityCollection       contactList  = CRMHelper.RetrieveMultiple(query, service);
            ExecuteMultipleRequest mulitRequest = null;
            int offset = 1;

            Console.WriteLine("Total Record to be Deleted are : " + contactList.Entities.Count);
            mulitRequest = getNewObject();
            for (int count = 0; count < contactList.Entities.Count; count++)
            {
                Guid   OwnerId     = Guid.Empty;
                string fullName    = string.Empty;
                string accountName = string.Empty;
                if (contactList.Entities[count].Attributes.Contains("fullname"))
                {
                    fullName = contactList.Entities[count].Attributes["fullname"].ToString();
                }

                AliasedValue    val        = (AliasedValue)contactList.Entities[count].Attributes["Company.ownerid"];
                EntityReference ownerIdRef = (EntityReference)val.Value;
                OwnerId = ownerIdRef.Id;

                accountName = ownerIdRef.Name;
                Guid   ContactOwner = contactList.Entities[count].GetAttributeValue <EntityReference>("ownerid").Id;
                Entity contact      = new Entity("contact");
                if (ContactOwner != OwnerId)
                {
                    Console.WriteLine("Miss-Match Owner of For Contact : " + fullName + " And Account is : " + accountName);
                    contact.Id = contactList.Entities[count].Id;
                    contact.Attributes.Add("ownerid", new EntityReference("systemuser", OwnerId));
                    UpdateRequest updateRequest = new UpdateRequest {
                        Target = contact
                    };
                    mulitRequest.Requests.Add(updateRequest);
                }
            }
            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(mulitRequest);

            Console.ReadLine();
        }
예제 #23
0
        // Checks if a companies house member already exists
        private bool IsCorporateMemberAlreadyLinked(Entity existingLink, CompaniesHouseMember companiesHouseMember)
        {
            _crmTracing.Trace($"IsCorporateMemberAlreadyLinked {companiesHouseMember}");

            if (existingLink.Attributes.Contains(Account.ParentChildAccountManyToManyRelationshipAlias + "." + Account.CompanyNumberField) &&
                companiesHouseMember.identification != null)
            {
                AliasedValue value = existingLink.Attributes[Account.ParentChildAccountManyToManyRelationshipAlias + "." + Account.CompanyNumberField] as AliasedValue;
                if (value != null && value.Value.ToString().Trim() == companiesHouseMember.identification.registration_number.Trim())
                {
                    // Matching account with the same company reg number exists
                    return(true);
                }
            }
            return(false);
        }
예제 #24
0
파일: VoService.cs 프로젝트: Voingod/RMP
        public void Deactivate()
        {
            var entities       = new VoMainScriptRepository(_service).GetEntities();
            var groupsEntities = entities.GroupBy(g => g.Id)
                                 .ToDictionary(k => k.Key, i => i.Select(z => z.Attributes).ToList());

            foreach (var item in groupsEntities)
            {
                int countRecords    = 0;
                int allRecordsCount = item.Value.Count;

                for (int i = 0; i < item.Value.Count; i++)
                {
                    if (!item.Value[i].Contains("new_vo_two_main2.new_account"))
                    {
                        break;
                    }
                    EntityReference VoMainScriptAccount   = (EntityReference)item.Value[i]["new_account"];
                    AliasedValue    aliesNewAccount       = (AliasedValue)item.Value[i]["new_vo_two_main2.new_account"];
                    EntityReference VoTwoMainAccount      = (EntityReference)aliesNewAccount.Value;
                    var             VoMainScriptAccountId = VoMainScriptAccount.Id;
                    var             VoTwoMainAccountId    = VoTwoMainAccount.Id;
                    if (VoMainScriptAccountId != VoTwoMainAccountId)
                    {
                        continue;
                    }
                    countRecords++;
                }

                if (countRecords == allRecordsCount)
                {
                    var            record = item.Value[countRecords - 1];
                    OptionSetValue state  = (OptionSetValue)record["statecode"];
                    if (state.Value == 0)
                    {
                        var output = record["new_name"] + ": " + record["new_vo_main_scriptid"] + " WAS DEACTIVATE";
                        Trace.WriteLine(output);
                        Console.WriteLine(output);
                        deactivateService.DeactivateRecord("new_vo_main_script", (Guid)record["new_vo_main_scriptid"], _service);
                    }
                    else
                    {
                        Console.WriteLine(record["new_name"] + ": already inactive!!!");
                    }
                }
            }
        }
예제 #25
0
 public static AliasedValue FetchAggregate(string fetchXml, IOrganizationService service, string aliasName = "aValue")
 {
     try {
         AliasedValue     x           = null;
         EntityCollection eCollection = service.RetrieveMultiple(new FetchExpression(fetchXml));
         var oEntity = eCollection.Entities.FirstOrDefault();
         if (oEntity != null)
         {
             x = oEntity.GetAttributeValue <AliasedValue>(aliasName);
         }
         return(x);
     } catch (System.ServiceModel.FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> exFalt) {
         throw;
     } catch (System.Exception) {
         throw;
     }
 }
예제 #26
0
        private static void ReadAliassedValue(CsvReader reader, Entity entity, int idx, string aliasAttrName)
        {
            List <string> aliases  = aliasAttrName.Split('.').ToList();
            string        entName  = aliases[2];
            string        attrName = aliases.Last();

            if (reader.TryGetField(typeof(string), idx, out object obj))
            {
                if (entName == "isRootBU")
                {
                    entName = "businessunit";
                }

                AliasedValue alias = new AliasedValue(entName, attrName, obj);
                entity.Attributes[aliasAttrName] = alias;
            }
        }
예제 #27
0
        /// <summary>
        /// To prepare partylist for contact
        /// </summary>
        /// <param name="aliasValue"></param>
        /// <returns></returns>
        private EntityCollection GetPartyList(AliasedValue aliasValue)
        {
            trace.Trace("Processing GetPartyList - start");
            var customers = new EntityCollection();

            if (aliasValue != null)
            {
                var party = new Entity(EntityName.ActivityParty);
                party[Attributes.ActivityParty.PartyId] = new EntityReference()
                {
                    LogicalName = aliasValue.EntityLogicalName, Id = Guid.Parse(aliasValue.Value.ToString())
                };
                customers.Entities.Add(party);
            }
            trace.Trace("Processing GetPartyList - end");
            return(customers);
        }
예제 #28
0
        private string GetAliasedValue(Entity SaleEntity, string AttributeName, AliasTypes AliasType = AliasTypes.String)
        {
            string Value = "";

            if (SaleEntity.Attributes.ContainsKey(AttributeName))
            {
                AliasedValue Alias = SaleEntity.GetAttributeValue <AliasedValue>(AttributeName);
                if (Alias != null)
                {
                    if (AliasType == AliasTypes.String)
                    {
                        if (Alias.Value != null)
                        {
                            Value = Alias.Value.ToString();
                        }
                    }
                    else if (AliasType == AliasTypes.DateTime)
                    {
                        if (Alias.Value != null)
                        {
                            Value = ((DateTime)Alias.Value).ToString("yyyy-MM-dd");
                        }
                    }
                    else if (AliasType == AliasTypes.OptionSet)
                    {
                        if (Alias.Value != null)
                        {
                            Value = ((OptionSetValue)Alias.Value).Value.ToString();
                        }
                    }
                    else if (AliasType == AliasTypes.EntityReference)
                    {
                        if (Alias.Value != null)
                        {
                            Value = ((EntityReference)Alias.Value).Name.ToString();
                        }
                    }
                }
            }
            else
            {
                //Logger.LogException(new ArgumentNullException(), PriorityLevel.MEDIUM, AttributeName + " has no value", IOrganizationService);
            }

            return(Value);
        }
        /// <summary>
        /// Gets the display string for a CRM property value
        /// </summary>
        /// <param name="entity">Entity to retreive the property from</param>
        /// <param name="attributeName">Name of the property</param>
        /// <returns></returns>
        public static string GetValueDisplayString(this Entity entity, string attributeName)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (!entity.Contains(attributeName))
            {
                return(null);
            }

            string formattedValue = null;

            if (entity.FormattedValues.Contains(attributeName))
            {
                formattedValue = entity.FormattedValues[attributeName];
            }

            if (String.IsNullOrEmpty(formattedValue))
            {
                object valueObject = entity[attributeName];

                AliasedValue aliased = valueObject as AliasedValue;
                if (aliased != null)
                {
                    valueObject = aliased.Value;
                }

                if (valueObject != null)
                {
                    EntityReference reference = valueObject as EntityReference;
                    if (reference != null)
                    {
                        formattedValue = reference.Name;
                    }
                    else
                    {
                        formattedValue = valueObject.ToString();
                    }
                }
            }
            return(formattedValue);
        }
예제 #30
0
        /// <summary>
        /// Modify to mock CRM Organization Service actions
        /// </summary>
        /// <param name="serviceMock">The Organization Service to mock</param>
        /// <returns>Configured Organization Service</returns>
        private static Mock <IOrganizationService> ZeroAttachmentsSetup(Mock <IOrganizationService> serviceMock)
        {
            EntityCollection queryResult = new EntityCollection();

            Entity emailCount = new Entity("email")
            {
                Id = Guid.Empty
            };
            AliasedValue a = new AliasedValue("email", "activityid", 0);

            emailCount["count"] = a;

            queryResult.Entities.Add(emailCount);

            serviceMock.Setup(t =>
                              t.RetrieveMultiple(It.IsAny <FetchExpression>()))
            .ReturnsInOrder(queryResult);

            return(serviceMock);
        }