Esempio n. 1
0
        public void CreateAccountWithUserImporsonate()
        {
            ServiceReference1.ProxyServiceClient ProxyCRMServiceObj = new ServiceReference1.ProxyServiceClient();

            DateTime             startTime = DateTime.Now;
            IOrganizationService service   = CRMHelper.ConnectToMSCRM();
            DateTime             EndTime   = DateTime.Now;

            var DiffinSecond = (EndTime - startTime).TotalSeconds;

            Console.WriteLine("Total Time Taken in Connect in seconds :" + DiffinSecond);
            Guid UserId = getCurrentUserId(service);

            UserId = new Guid("3DE87036-0DA1-E511-80ED-3863BB3C2660");

            Guid accountId = ProxyCRMServiceObj.CreateAccountwithImporonatedUser(UserId.ToString());
        }
        public LoadAppResult LoadApplication(Guid uniqueId, Guid appId)
        {
            LoadAppResult appObject = null;

            if (appId == Guid.Empty)
            {
                appId = getAppIdbyAppUniqueId(uniqueId);
            }

            if (appId != Guid.Empty)
            {
                IOrganizationService service = CRMHelper.ConnectToMSCRM();
                QueryExpression      query   = new QueryExpression("annotation");
                query.ColumnSet = new ColumnSet(new string[] { "filename", "documentbody" });
                query.Criteria.AddCondition("objectid", ConditionOperator.Equal, appId);
                appObject = convertEntityToApplicationObject(service.RetrieveMultiple(query));
            }
            return(appObject);
        }
        public void DeleteWaitingJobs()
        {
            DateTime      DateFilter = DateTime.Now.AddDays(-1);
            List <string> statusList = new List <string>();

            statusList.Add("1");
            statusList.Add("3");
            QueryExpression query = new QueryExpression("asyncoperation");

            query.Criteria.AddCondition("statuscode", ConditionOperator.NotEqual, 30);
            query.Criteria.AddCondition("createdon", ConditionOperator.OnOrBefore, DateFilter);
            query.Criteria.AddCondition("operationtype", ConditionOperator.Equal, 10);
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            Console.WriteLine("IOrganization Service Object Created");
            EntityCollection EntityList = CRMHelper.RetrieveMultiple(query, service);
            int count = 1;
            ExecuteMultipleRequest mulitRequest = null;

            Console.WriteLine("Total Record to be Deleted are : " + EntityList.Entities.Count);
            for (int i = 0; i < EntityList.Entities.Count; i++)
            {
                if (i == 1 || i % 1000 == 0)
                {
                    mulitRequest = getNewObject();
                }
                Entity        Item          = EntityList.Entities[i];
                DeleteRequest deleteRequest = new DeleteRequest {
                    Target = Item.ToEntityReference()
                };
                mulitRequest.Requests.Add(deleteRequest);

                if (count % 1000 == 0 || count == EntityList.Entities.Count)
                {
                    // Execute all the requests in the request collection using a single web method call.
                    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(mulitRequest);
                    Console.WriteLine("Bunch of 1000 Record Deleted  & Total record Proceed are :" + count);
                }


                count++;
            }
        }
Esempio n. 4
0
        private void CreateAlternateKey(string entityName, List <string> entityFieldName, string keyDisplayName, string keyLogicalName)
        {
            EntityKeyMetadata Data = new EntityKeyMetadata();

            Data.KeyAttributes = entityFieldName.ToArray();
            Data.DisplayName   = new Label(keyDisplayName, 1033);
            Data.LogicalName   = keyLogicalName;
            Data.SchemaName    = keyLogicalName;

            CreateEntityKeyRequest request1 = new CreateEntityKeyRequest()
            {
                EntityKey  = Data,
                EntityName = entityName,
            };

            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            CreateEntityKeyResponse response = (CreateEntityKeyResponse)service.Execute(request1);
        }
        public void updateAnnotationforMSFT()
        {
            QueryExpression query      = new QueryExpression("annotation");
            LinkEntity      linkEntity = new LinkEntity("annotation", "apttus_xapps_application", "objectid", "apttus_xapps_applicationid", JoinOperator.Inner);

            linkEntity.LinkCriteria.AddCondition("apttus_name", ConditionOperator.Equal, "Agreement Uploader Dev 1");
            query.LinkEntities.Add(linkEntity);
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            EntityCollection annotationList = service.RetrieveMultiple(query);

            foreach (Entity annotation in annotationList.Entities)
            {
                Entity anotation1 = new Entity(annotation.LogicalName);
                anotation1.Attributes.Add("isdocument", true);
                anotation1.Id = annotation.Id;
                service.Update(anotation1);
            }
        }
Esempio n. 6
0
        public bool ImportSolution()
        {
            bool   _isSucceed            = false;
            string SolutionDirectory     = @"C:\Solution";
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            ImportSolutionRequest SolutionRequest;

            byte[] Solution;

            string[] files = Directory.GetFiles(SolutionDirectory);
            foreach (string file in files)
            {
                Solution        = File.ReadAllBytes(file);
                SolutionRequest = new ImportSolutionRequest();
                SolutionRequest.CustomizationFile = Solution;
                SolutionRequest.ImportJobId       = Guid.NewGuid();
                SolutionRequest.ConvertToManaged  = false;

                try
                {
                    service.Execute(SolutionRequest);
                    Entity ImportJob = new Entity("importjob");
                    ImportJob = service.Retrieve(ImportJob.LogicalName, SolutionRequest.ImportJobId, new ColumnSet(true));
                    XDocument xdoc = XDocument.Parse(ImportJob["data"].ToString());

                    string ImportSolutionName = xdoc.Descendants("solutionManifest").Descendants("UniqueName").First().Value;

                    bool SolutionImportResult = xdoc.Descendants("solutionManifest").Descendants("result").First().FirstAttribute.Value == "success" ? true : false;

                    //Guid? Solutionid = GetSDol
                }

                catch (Exception ex)
                {
                    continue;
                }
            }



            return(_isSucceed);
        }
        public List <Annotation> getAllAnnotationbyObjectId(Guid ObjectId)
        {
            List <Annotation> AnnotationList = new List <Annotation>();
            QueryExpression   query          = new QueryExpression("annotation");
            ColumnSet         cols           = new ColumnSet(new string[] { "annotationid", "filename", "documentbody", "subject", "mimetype", "notetext" });

            query.ColumnSet = cols;
            query.Criteria.AddCondition("objectid", ConditionOperator.Equal, ObjectId);
            query.Orders.Add(new OrderExpression("createdon", OrderType.Ascending));

            IOrganizationService service = CRMHelper.ConnectToMSCRM();
            EntityCollection     annotationEntityList = service.RetrieveMultiple(query);

            foreach (Entity Item in annotationEntityList.Entities)
            {
                AnnotationList.Add(BuildEntityObject(Item));
            }

            return(AnnotationList);
        }
        public void deactiveContacts(string EntityName)
        {
            DateTime        DateFilter = DateTime.Now.AddDays(-1);
            QueryExpression query      = new QueryExpression(EntityName);

            query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
            IOrganizationService service = CRMHelper.ConnectToMSCRM1();

            Console.WriteLine("IOrganization Service Object Created");
            EntityCollection       EntityList   = CRMHelper.RetrieveMultiple(query, service);
            ExecuteMultipleRequest mulitRequest = null;

            int offset = 1;

            Console.WriteLine("Total Record to be Deleted are : " + EntityList.Entities.Count);
            mulitRequest = getNewObject();
            for (int count = 0; count < EntityList.Entities.Count; count++)
            {
                if (offset % 200 == 0)
                {
                    // Execute all the requests in the request collection using a single web method call.
                    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(mulitRequest);
                    Console.WriteLine("Bunch of 200 Record Deleted  & Total record Proceed are : " + count);
                    mulitRequest = getNewObject();
                }
                Entity Item = EntityList.Entities[count];
                //StateCode = 1 and StatusCode = 2 for deactivating Account or Contact
                SetStateRequest setStateRequest = new SetStateRequest()
                {
                    EntityMoniker = new EntityReference
                    {
                        Id          = Item.Id,
                        LogicalName = Item.LogicalName
                    },
                    State  = new OptionSetValue(1),
                    Status = new OptionSetValue(2)
                };
                mulitRequest.Requests.Add(setStateRequest);
                offset = count + 1;
            }
        }
Esempio n. 9
0
        public EntityCollection getAllUSZipCode(IOrganizationService service)
        {
            QueryExpression query = new QueryExpression("new_zipcode");

            query.ColumnSet = new ColumnSet(new string[] { "new_zipcode", "new_country" });
            FilterExpression feOr = new FilterExpression(LogicalOperator.Or);

            for (char c = 'a'; c <= 'z'; c++)
            {
                feOr.AddCondition("new_zipcode", ConditionOperator.BeginsWith, c.ToString());
            }

            FilterExpression feAnd = new FilterExpression(LogicalOperator.And);

            feAnd.AddCondition("new_country", ConditionOperator.Equal, "US");
            query.Criteria.AddFilter(feAnd);
            query.Criteria.AddFilter(feOr);
            EntityCollection zipCodeList = CRMHelper.RetrieveMultiple(query, service);

            return(zipCodeList);
        }
Esempio n. 10
0
        public void insertQuoteDetail()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            Entity quoteDetail = new Entity("quotedetail");
            Guid   quoteId     = new Guid("DB064E35-6AEF-E511-80F4-3863BB346A70");

            quoteDetail.Attributes.Add("quoteid", new EntityReference("quote", quoteId));
            quoteDetail.Attributes.Add("apttus_qpconfig_adjustmenttype", new OptionSetValue(100000003));
            quoteDetail.Attributes.Add("apttus_qpconfig_linenumber", Convert.ToDecimal(1));
            quoteDetail.Attributes.Add("apttus_qpconfig_netprice", new Money(2366));
            quoteDetail.Attributes.Add("apttus_proposal_productid", new EntityReference("product", new Guid("305953c1-cab9-e511-80f1-3863bb34ea28")));
            quoteDetail.Attributes.Add("apttus_proposal_quantity", Convert.ToDecimal(1));
            quoteDetail.Attributes.Add("apttus_proposal_unit_price", new Money(2666));

            // if required
            quoteDetail.Attributes.Add("productid", new EntityReference("product", new Guid("305953c1-cab9-e511-80f1-3863bb34ea28")));
            quoteDetail.Attributes.Add("uomid", new EntityReference("uom", new Guid("97B0FD1B-DD58-4AD4-ACDD-EB270F959558")));

            service.Create(quoteDetail);
        }
        public void updatePhnAccounts()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            QueryExpression query = new QueryExpression("account");

            query.Criteria.AddCondition("new_includeinsalesfunnel", ConditionOperator.Equal, true);
            query.Criteria.AddCondition("new_accounttype", ConditionOperator.Equal, 3);
            query.Criteria.AddCondition("new_totalnoofdairycows", ConditionOperator.Null);

            EntityCollection accountLists = service.RetrieveMultiple(query);
            Random           random       = new Random();

            foreach (Entity Item in accountLists.Entities)
            {
                int    randomNumber = random.Next(0, 1000);
                Entity account      = new Entity("account");
                account.Attributes.Add("new_totalnoofdairycows", randomNumber);
                account.Id = Item.Id;
                service.Update(account);
            }
        }
Esempio n. 12
0
        public void getEntityNamebyCode()
        {
            string entityLogicalName = String.Empty;

            IOrganizationService service = CRMHelper.ConnectToMSCRM();
            int objectTypeCode           = 10150;

            MetadataFilterExpression EntityFilter = new MetadataFilterExpression(LogicalOperator.And);

            EntityFilter.Conditions.Add(new MetadataConditionExpression("ObjectTypeCode", MetadataConditionOperator.Equals, objectTypeCode));

            MetadataPropertiesExpression mpe = new MetadataPropertiesExpression();

            mpe.AllProperties = false;
            mpe.PropertyNames.Add("DisplayName");
            mpe.PropertyNames.Add("ObjectTypeCode");
            mpe.PropertyNames.Add("PrimaryIdAttribute");
            mpe.PropertyNames.Add("PrimaryNameAttribute");

            EntityQueryExpression entityQueryExpression = new EntityQueryExpression()
            {
                Criteria   = EntityFilter,
                Properties = mpe
            };



            RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest()
            {
                Query = entityQueryExpression
            };

            RetrieveMetadataChangesResponse initialRequest = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            if (initialRequest.EntityMetadata.Count == 1)
            {
                entityLogicalName = initialRequest.EntityMetadata[0].LogicalName;
            }
        }
Esempio n. 13
0
        public int getLoggedinUserLicense(Guid userId)
        {
            int licenseType = 0;

            QueryExpression query = new QueryExpression(XAUTHOR_LICENSE_ALLOCATION_ENTITY);

            query.ColumnSet = new ColumnSet(new string[] { "apttex_licensetype" });
            query.Criteria.AddCondition("apttex_assignedto", ConditionOperator.Equal, userId);
            query.Criteria.AddCondition("apttex_licensestatus", ConditionOperator.Equal, true);

            EntityCollection licenseAllocationEntSet = CRMHelper.ConnectToMSCRM().RetrieveMultiple(query);

            if (licenseAllocationEntSet.Entities.Count <= 0)
            {
                return(licenseType);
            }
            if (licenseAllocationEntSet.Entities[0].Attributes.Contains("apttex_licensetype") && licenseAllocationEntSet.Entities[0].Attributes["apttex_licensetype"] != null)
            {
                licenseType = licenseAllocationEntSet.Entities[0].GetAttributeValue <OptionSetValue>("apttex_licensetype").Value;
            }

            return(licenseType);
        }
Esempio n. 14
0
        public List <RetrieveEntityResponse> RetrieveEntities(List <string> entityNames)
        {
            List <RetrieveEntityResponse> entityResponses = new List <RetrieveEntityResponse>();
            var multipleRequest = new ExecuteMultipleRequest()
            {
                // Assign settings that define execution behavior: continue on error, return responses.
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                },


                // Create an empty organization request collection.
                Requests = new OrganizationRequestCollection()
            };

            foreach (string entityName in entityNames)
            {
                RetrieveEntityRequest updateRequest = new RetrieveEntityRequest()
                {
                    EntityFilters         = EntityFilters.Entity | EntityFilters.Attributes,
                    LogicalName           = entityName,
                    RetrieveAsIfPublished = true
                };
                multipleRequest.Requests.Add(updateRequest);
            }

            IOrganizationService    service  = CRMHelper.ConnectToMSCRM();
            ExecuteMultipleResponse response = (ExecuteMultipleResponse)service.Execute(multipleRequest);

            foreach (var item in response.Responses)
            {
                entityResponses.Add((RetrieveEntityResponse)item.Response);
            }
            return(entityResponses);
        }
Esempio n. 15
0
        public void updateQuote()
        {
            Guid quoteId = new Guid("83BCE3DA-26D7-E511-80EF-3863BB369D50");
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            Entity quote = new Entity("quote");

            quote.Id = quoteId;
            // update Discount %
            //decimal discPercentage = 10;
            //quote.Attributes.Add("discountpercentage", discPercentage);



            //update Discount Amount
            Money currency = new Money(110);

            quote.Attributes.Add("totaltax", currency);

            service.Update(quote);


            Entity item = service.Retrieve("quote", quoteId, new ColumnSet(new string[] { "totaltax" }));
        }
        public void updateAllEmployeeWithBulkRequest()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            Console.WriteLine("update All Employee Started");
            DateTime StartGetTime = DateTime.Now;

            Console.WriteLine("Start Method of All Employee :" + StartGetTime.ToString());
            EntityCollection List       = getAllEmployee();
            DateTime         EndGetTime = DateTime.Now;

            Console.WriteLine("End Method of All Employee at :" + EndGetTime.ToString());
            double DiffinSeconds = (EndGetTime - StartGetTime).TotalSeconds;

            Console.WriteLine("Method Took Time in Second:" + DiffinSeconds.ToString());
            StartGetTime = DateTime.Now;
            Console.WriteLine("Prepare Entity Collection to Update 500 Records" + StartGetTime.ToString());
            EntityCollection toUpdate = new EntityCollection();

            for (int cnt = 0; cnt < List.Entities.Count; cnt++)
            {
                if (cnt == 499)
                {
                    break;
                }
                Entity Item = new Entity("new_employee");
                Item.Id = List.Entities[cnt].Id;
                Item.Attributes.Add("new_jobtitle", "CRM Developer");
                toUpdate.Entities.Add(Item);
            }
            EndGetTime = DateTime.Now;
            double DiffinSecond = (EndGetTime - StartGetTime).TotalSeconds;

            Console.WriteLine("Completed Preparing Entity Collection to Update Request at :" + EndGetTime.ToString());

            // Create an ExecuteMultipleRequest object.

            var multipleRequest = new ExecuteMultipleRequest()
            {
                // Assign settings that define execution behavior: continue on error, return responses.
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                },
                // Create an empty organization request collection.
                Requests = new OrganizationRequestCollection()
            };

            // Add a UpdateRequest for each entity to the request collection.
            foreach (var entity in toUpdate.Entities)
            {
                UpdateRequest updateRequest = new UpdateRequest {
                    Target = entity
                };
                multipleRequest.Requests.Add(updateRequest);
            }

            // Execute all the requests in the request collection using a single web method call.
            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);

            EndGetTime   = DateTime.Now;
            DiffinSecond = (EndGetTime - StartGetTime).TotalSeconds;
            Console.WriteLine("Completed Updating 500 Records at : " + EndGetTime.ToString());
            Console.WriteLine("Total Operation Time in Second is :" + DiffinSecond);
            Console.ReadLine();
        }
        public void getAccountAnnotation()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();
            Guid attachmentId            = new Guid("1f3be793-1269-e611-80ea-5065f38af9f1");
            var  columnSets = new string[] { "filename", "documentbody" };

            /* Retrive Multiple Query */
            //QueryExpression RetrieveMultiple = new QueryExpression("annotation");
            //RetrieveMultiple.ColumnSet = new ColumnSet(columnSets);
            //LinkEntity linktoAccount = new LinkEntity("annotation", "account", "objectid", "accountid", JoinOperator.Inner);
            //linktoAccount.LinkCriteria.AddCondition("name", ConditionOperator.Equal, "Choho Winery");
            //RetrieveMultiple.LinkEntities.Add(linktoAccount);

            QueryExpression RetrieveMultiple = new QueryExpression("annotation");

            RetrieveMultiple.ColumnSet = new ColumnSet(columnSets);
            RetrieveMultiple.Criteria.AddCondition("annotationid", ConditionOperator.Equal, attachmentId);



            var conversionRequest = new QueryExpressionToFetchXmlRequest
            {
                Query = RetrieveMultiple
            };
            var response = (QueryExpressionToFetchXmlResponse)service.Execute(conversionRequest);

            // Use the converted query to make a retrieve multiple request to Microsoft Dynamics CRM.
            String RetrieveMultipleXML = response.FetchXml;


            EntityCollection retrieveMulipleCollection = service.RetrieveMultiple(RetrieveMultiple);


            Console.WriteLine("Retrieve Multiple Query Result with Length : " + readLength(retrieveMulipleCollection.Entities[0]));

            /****** End Here *********/


            /*  x-Author Query */
            QueryExpression xAthorQuery = new QueryExpression()
            {
                Distinct   = true,
                EntityName = "annotation",
                ColumnSet  = new ColumnSet(columnSets),
                Criteria   =
                {
                    Filters                =
                    {
                        new FilterExpression
                        {
                            FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
                            Conditions     =
                            {
                                new ConditionExpression("annotationid", ConditionOperator.Equal, attachmentId)
                            }
                        }
                    }
                }
            };

            conversionRequest = new QueryExpressionToFetchXmlRequest
            {
                Query = xAthorQuery
            };
            response = (QueryExpressionToFetchXmlResponse)service.Execute(conversionRequest);

            // Use the converted query to make a retrieve multiple request to Microsoft Dynamics CRM.
            RetrieveMultipleXML = response.FetchXml;


            EntityCollection xAthorQueryCollection = service.RetrieveMultiple(xAthorQuery);

            Console.WriteLine("Retrieve Multiple Query Result with Length : " + readLength(xAthorQueryCollection.Entities[0]));
            /******* End Here *******/

            /* Retrieve by Primary Key */
            Entity SingleResponse = service.Retrieve("annotation", attachmentId, new ColumnSet(columnSets));

            Console.WriteLine("Retrieve Multiple Query Result with Length : " + readLength(SingleResponse));

            Console.ReadLine();
        }
        public string getCurentUserLang()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            return(getUserLanguage(service));
        }
Esempio n. 19
0
        public void BulkUpsertRequest()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();
            //var multipleRequest = new ExecuteMultipleRequest()
            //{
            //    // Assign settings that define execution behavior: continue on error, return responses.
            //    Settings = new ExecuteMultipleSettings()
            //    {
            //        ContinueOnError = false,
            //        ReturnResponses = true
            //    },
            //    // Create an empty organization request collection.
            //    Requests = new OrganizationRequestCollection()
            //};

            //string accountKey = "accountnumber";
            //string keyValue = string.Empty;

            //// First Account Record
            //keyValue = "123";
            //Entity Account = new Entity("account", accountKey, "123");
            //Account.Attributes.Add("name", keyValue);

            //UpsertRequest upReq = new UpsertRequest();
            //upReq.Target = Account;
            //multipleRequest.Requests.Add(upReq);

            //// Second Account Record
            //keyValue = "456";
            //Account = new Entity("account", accountKey, keyValue);
            //Account.Attributes.Add("name", keyValue);

            //upReq = new UpsertRequest();
            //upReq.Target = Account;
            //multipleRequest.Requests.Add(upReq);

            //// Third Account Record
            //keyValue = "789";
            //Account = new Entity("account", accountKey, keyValue);
            //Account.Attributes.Add("name", keyValue);

            //// Third Account Record
            //keyValue = "7890";
            //Account = new Entity("account", accountKey, keyValue);
            //Account.Attributes.Add("name", keyValue);

            //upReq = new UpsertRequest();
            //upReq.Target = Account;
            //multipleRequest.Requests.Add(upReq);
            //ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);


            EntityKeyMetadata Data = new EntityKeyMetadata();

            Data.KeyAttributes = new string[] { "apttus_contactnumber" };
            Data.DisplayName   = new Label("Contact Number", 1033);
            Data.LogicalName   = "apttus_contactnumber";
            Data.SchemaName    = "apttus_telephone1";

            CreateEntityKeyRequest request1 = new CreateEntityKeyRequest()
            {
                EntityKey  = Data,
                EntityName = "contact",
            };
            CreateEntityKeyResponse response = (CreateEntityKeyResponse)service.Execute(request1);
        }
        public ExecuteMultipleResponse InsertBulkDataOnebyOne(int counter)
        {
            EntityCollection toInsert = new EntityCollection();

            for (int i = 1; i <= counter; i++)
            {
                Entity Task = new Entity("task");
                Task.Attributes["subject"] = "Task : " + i.ToString();
                toInsert.Entities.Add(Task);
            }

            IOrganizationService    orgServiceProxy = CRMHelper.ConnectToMSCRM();
            ExecuteMultipleResponse responseList    = null;
            DateTime StartTime = DateTime.Now;

            Console.WriteLine("Start One by One Process at : " + StartTime);
            int count = 0;

            foreach (var entity in toInsert.Entities)
            {
                // Create an ExecuteMultipleRequest object.
                ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
                {
                    // Assign settings that define execution behavior: continue on error, return responses.
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = true,
                        ReturnResponses = true
                    },
                    // Create an empty organization request collection.
                    Requests = new OrganizationRequestCollection()
                };

                if (count == 0)
                {
                    CreateRequest createRequest = new CreateRequest {
                        Target = entity
                    };
                    requestWithResults.Requests.Add(createRequest);
                }
                count++;
                if (responseList == null)
                {
                    ExecuteMultipleResponse responseWithResults = (ExecuteMultipleResponse)orgServiceProxy.Execute(requestWithResults);
                    responseList = responseWithResults;
                }
                else
                {
                    ExecuteMultipleResponseItem item = new ExecuteMultipleResponseItem();
                    try
                    {
                        Guid recordId = orgServiceProxy.Create(entity);
                        item.Fault    = null;
                        item.Response = new OrganizationResponse();

                        item.Response.Results = new ParameterCollection();
                        item.Response.Results.Add("id", recordId);
                    }
                    catch (Exception ex)
                    {
                        item.Fault.Message = ex.Message;
                        continue;
                    }
                    responseList.Responses.Add(item);
                }
            }
            DateTime endTime = DateTime.Now;

            Console.WriteLine("Completed One by One Process at : " + endTime);
            var diffInSeconds = (endTime - StartTime).TotalSeconds;

            Console.WriteLine("Total Time in Second : " + diffInSeconds);
            return(responseList);
        }
        public void getuserbyUserId()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            Entity user = service.Retrieve("systemuser", new Guid("34dbba6e-c858-e111-b538-1cc1deeae7d7"), new ColumnSet(true));
        }
Esempio n. 22
0
        public RetrieveEntityResponse RetrieveEntity(List <string> entityName)
        {
            RetrieveEntityResponse response1 = null;
            IOrganizationService   service   = CRMHelper.ConnectToMSCRM();

            foreach (string item in entityName)
            {
                RetrieveEntityRequest request = new RetrieveEntityRequest()
                {
                    EntityFilters         = EntityFilters.Attributes | EntityFilters.Relationships,
                    LogicalName           = item,
                    RetrieveAsIfPublished = true
                };

                RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);

                //var result1 = response.EntityMetadata.Attributes.Where(f => f.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired || f.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired);
                var AttributeList = response.EntityMetadata.Attributes.OrderBy(f => f.LogicalName);


                var allFields = response.EntityMetadata.Attributes;
                var result2   = response.EntityMetadata.Attributes.Where(f => f.IsLogical == false && f.AttributeType.Value.ToString() != "Virtual" && string.IsNullOrEmpty(f.AttributeOf) &&
                                                                         (f.IsValidForCreate.Value == true || f.IsValidForUpdate.Value == true || f.IsValidForAdvancedFind.Value == true));
                var Result3 = response.EntityMetadata.Attributes.Where(f => f.IsValidForAdvancedFind.Value == false || f.AttributeType.Value == AttributeTypeCode.Virtual);

                var Result4 = response.EntityMetadata.Attributes.Where(a => a.IsValidForAdvancedFind.Value == true && a.AttributeType.Value != AttributeTypeCode.Virtual);

                var Result5 = Result4.Where(f => f.IsValidForCreate == true || f.IsValidForUpdate == true);

                var           Result6      = Result4.Except(Result5).ToList();
                List <string> Level1Fields = result2.Select(f => f.LogicalName).ToList();

                //&& f.IsValidForAdvancedFind.Value == true && f.IsValidForCreate.Value ==true && f.IsValidForUpdate.Value == true);


                var           virtualList       = allFields.Where(f => f.AttributeType.Value == AttributeTypeCode.Virtual).ToList();
                List <string> virtualListString = virtualList.Select(f => f.LogicalName).ToList();

                var           attributeof       = allFields.Where(f => !string.IsNullOrEmpty(f.AttributeOf)).ToList();
                List <string> attributeOfString = attributeof.Select(f => f.LogicalName).ToList();

                var           combineList       = allFields.Where(f => f.AttributeType.Value == AttributeTypeCode.Virtual && !string.IsNullOrEmpty(f.AttributeOf)).ToList();
                List <string> combineListString = combineList.Select(f => f.LogicalName).ToList();

                var           isRenamabled    = allFields.Where(f => f.IsRenameable.Value == false).ToList();
                List <string> isrenablestring = isRenamabled.Select(f => f.LogicalName).ToList();

                var MissingFieldsfromAllFields  = allFields.Except(result2).ToList();
                var MissingFieldsFromAllFields2 = allFields.Except(Result3).ToList();



                //var result3 = result2.Where(f => f.IsValidForCreate.Value == true || f.IsValidForUpdate.Value == true  || f.IsValidForAdvancedFind.Value == true);
                //List<string> Level2Fields = result3.Select(f => f.LogicalName).ToList();

                //List<string> firstMainDiff = allFields.Except(Level1Fields).ToList();
                //List<string> secondMainDiff = allFields.Except(Level2Fields).ToList();
                //List<string> FirstSecondDiff = Level1Fields.Except(Level2Fields).ToList();
            }
            return(response1);
        }
Esempio n. 23
0
        public void GetAllEntity()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();



            Console.WriteLine("Starting Fetch Methods");
            DateTime startTime  = DateTime.Now;
            var      properties = new MetadataPropertiesExpression();

            properties.PropertyNames.AddRange("LogicalName", "DisplayName", "PrimaryIdAttribute", "PrimaryNameAttribute");

            //An entity query expression to combine the filter expressions and property expressions for the query.
            var entityQueryExpression = new EntityQueryExpression {
                Properties = properties,
            };

            //Retrieve the metadata for the query without a ClientVersionStamp
            var retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest
            {
                Query = entityQueryExpression
            };

            var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest);

            List <string> NameList  = new List <string>();
            List <string> emptyList = new List <string>();

            foreach (EntityMetadata item in response.EntityMetadata)
            {
                string name = item.DisplayName.UserLocalizedLabel != null ? item.DisplayName.UserLocalizedLabel.Label : item.SchemaName;

                NameList.Add(name);

                if (string.IsNullOrEmpty(name))
                {
                    emptyList.Add(item.LogicalName);
                }
            }

            NameList.Sort();

            DateTime endTime = DateTime.Now;

            Console.WriteLine("Time Taken with entityQueryExpress Method is :" + (endTime - startTime).TotalSeconds);

            startTime = DateTime.Now;

            RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
            {
                EntityFilters         = EntityFilters.Entity,
                RetrieveAsIfPublished = true
            };

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

            endTime = DateTime.Now;
            Console.WriteLine("Time Taken with RetrieveAllEntitiesRequest Method is :" + (endTime - startTime).TotalSeconds);

            foreach (EntityMetadata item in response1.EntityMetadata)
            {
                if (emptyList.Contains(item.LogicalName))
                {
                    Console.ReadLine();
                }
            }

            Console.ReadLine();
        }