示例#1
0
        public void Execute(IServiceProvider serviceProvider)
        {
            var context =
                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);
            var altKey  = new KeyAttributeCollection();

            altKey.Add("cr90f_name", context.InputParameters["name"]);

            var report = new Entity
            {
                KeyAttributes         = altKey,
                LogicalName           = "cr90f_report",
                ["cr90f_description"] = context.InputParameters["description"],
                ["cr90f_priority"]    = context.InputParameters["priority"],
                ["cr90f_name"]        = context.InputParameters["name"]
            };
            var request = new UpsertRequest
            {
                Target = report
            };
            var response = (UpsertResponse)service.Execute(request);
            var result   = response.RecordCreated ? "Record created" : "Record updated";

            context.OutputParameters["result"] = result;
        }
        public void Upsert_Creates_Record_When_It_Does_Not_Exist_Using_Alternate_Key()
        {
            var context = new XrmFakedContext();

            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            context.InitializeMetadata(Assembly.GetExecutingAssembly());
            var service = context.GetOrganizationService();

            var metadata = context.GetEntityMetadataByName("contact");

            metadata.SetFieldValue("_keys", new EntityKeyMetadata[]
            {
                new EntityKeyMetadata()
                {
                    KeyAttributes = new string[] { "firstname" }
                }
            });
            context.SetEntityMetadata(metadata);
            var contact = new Contact()
            {
                FirstName = "FakeXrm",
                LastName  = "Easy"
            };

            contact.KeyAttributes.Add("firstname", contact.FirstName);

            var request = new UpsertRequest()
            {
                Target = contact
            };

            var response = (UpsertResponse)service.Execute(request);

            Assert.Equal(true, response.RecordCreated);
        }
        public void Upsert_Updates_Record_When_It_Exists()
        {
            var context = new XrmFakedContext();

            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            var service = context.GetOrganizationService();

            var contact = new Contact()
            {
                Id        = Guid.NewGuid(),
                FirstName = "FakeXrm"
            };

            context.Initialize(new[] { contact });

            contact = new Contact()
            {
                Id        = contact.Id,
                FirstName = "FakeXrm2",
                LastName  = "Easy"
            };

            var request = new UpsertRequest()
            {
                Target = contact
            };


            var response       = (UpsertResponse)service.Execute(request);
            var contactUpdated = context.CreateQuery <Contact>().FirstOrDefault();

            Assert.Equal(false, response.RecordCreated);
            Assert.Equal("FakeXrm2", contactUpdated.FirstName);
        }
        public void Upsert_Creates_Record_When_It_Does_Not_Exist()
        {
            var context = new XrmFakedContext();

            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            var service = context.GetOrganizationService();

            var contact = new Contact()
            {
                Id        = Guid.NewGuid(),
                FirstName = "FakeXrm",
                LastName  = "Easy"
            };

            var request = new UpsertRequest()
            {
                Target = contact
            };

            var response = (UpsertResponse)service.Execute(request);

            var contactCreated = context.CreateQuery <Contact>().FirstOrDefault();

            Assert.Equal(true, response.RecordCreated);
            Assert.NotNull(contactCreated);
        }
        protected override string GetRequestDescription(OrganizationRequest request)
        {
            UpsertRequest upsertRequest = (UpsertRequest)request;
            string        values        = string.Join(", ", upsertRequest.Target.Attributes.Select(attribute => GetAttributeValueString(attribute.Value)));

            return(string.Format(Properties.Resources.Dynamics365UpsertOperationRequestDescription, Entity.DisplayName, values));
        }
示例#6
0
        public async Task Upsert <TKey>(TKey key, UpdateOperation[] updateOperations)
        {
            var updateRequest = new UpsertRequest <TKey>(
                SpaceId,
                key,
                updateOperations);

            await LogicalConnection.SendRequestWithEmptyResponse(updateRequest).ConfigureAwait(false);
        }
示例#7
0
        public void Upsert(Entity entity)
        {
            UpsertRequest request = new UpsertRequest()
            {
                Target = entity
            };

            this.Service.Execute(request);
        }
示例#8
0
        /// <summary>
        /// Applies the current action
        /// </summary>
        /// <param name="crm1">The first (left) crm instance</param>
        /// <param name="crm2">The second (right) crm instance</param>
        public void ApplyTo(IOrganizationService crm1, IOrganizationService crm2)
        {
            var crm = this.TargetEnvironmentIndex == 1 ? crm1 : crm2;

            var request = new UpsertRequest
            {
                Target = this.Entity
            };

            crm.Execute(request);
        }
        public void ProcessUpsert(String Filename)
        {
            Console.WriteLine("Executing upsert operation.....");
            XmlTextReader tr   = new XmlTextReader(Filename);
            XmlDocument   xdoc = new XmlDocument();

            xdoc.Load(tr);
            XmlNodeList xnlNodes = xdoc.DocumentElement.SelectNodes("/products/product");

            foreach (XmlNode xndNode in xnlNodes)
            {
                String productCode     = xndNode.SelectSingleNode("Code").InnerText;
                String productName     = xndNode.SelectSingleNode("Name").InnerText;
                String productCategory = xndNode.SelectSingleNode("Category").InnerText;
                String productMake     = xndNode.SelectSingleNode("Make").InnerText;

                //use alternate key for product
                Entity productToCreate = new Entity("sample_product", "sample_productcode", productCode);

                productToCreate["sample_name"]     = productName;
                productToCreate["sample_category"] = productCategory;
                productToCreate["sample_make"]     = productMake;
                UpsertRequest request = new UpsertRequest()
                {
                    Target = productToCreate
                };

                try
                {
                    // Execute UpsertRequest and obtain UpsertResponse.
                    UpsertResponse response = (UpsertResponse)_serviceProxy.Execute(request);
                    if (response.RecordCreated)
                    {
                        Console.WriteLine("New record {0} is created!", productName);
                    }
                    else
                    {
                        Console.WriteLine("Existing record {0} is updated!", productName);
                    }
                }

                // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
                catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
                {
                    throw;
                }
            }
            // Prompts to view the sample_product entity records.
            // If you choose "y", IE will be launched to display the new or updated records.
            if (PromptForView())
            {
                ViewEntityListInBrowser();
            }
        }
示例#10
0
        //VERSIONCHECK 7.1.0.0
        public static UpsertResponse Upsert(this IOrganizationService service, Entity entity)
        {
            var req = new UpsertRequest()
            {
                Target = entity
            };
            var resp = service.Execute(req) as UpsertResponse;

            entity.Id = resp.Target?.Id ?? entity.Id;
            return(resp);
        }
        protected override List <OrganizationRequest> CreateOrganisationRequests(DataRow row, CancellationToken cancel, IProgress <ExecutionProgress> progress)
        {
            List <OrganizationRequest> requests       = new List <OrganizationRequest>();
            EntityMetadata             entityMetadata = Entity.GetEntityMetadata(Connection);
            UpsertRequest request = new UpsertRequest()
            {
                Target = CreateEntityFromDataRow(row, cancel, progress)
            };

            AddDuplicateDetectionParameter(request);
            requests.Add(request);

            return(requests);
        }
示例#12
0
        private static void SaveToServerSingle(Entity[] entities, string connectionstring)
        {
            var service = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionstring);

            foreach (var e in entities)
            {
                var upsert = new UpsertRequest()
                {
                    Target = e
                };
                var resp    = (UpsertResponse)service.Execute(upsert);
                var created = resp.RecordCreated ? "created" : "updated";
                log($"Record {created}");
            }
        }
        public static XrmResponse UpsertEntity(Entity entityRecord, IOrganizationService service)
        {
            if (entityRecord == null)
            {
                return(null);
            }
            if (service == null)
            {
                return(null);
            }

            XrmResponse xrmResponse = null;

            if (service != null)
            {
                UpsertRequest request = new UpsertRequest()
                {
                    Target = entityRecord
                };



                // Execute UpsertRequest and obtain UpsertResponse.
                UpsertResponse response = (UpsertResponse)service.Execute(request);
                if (response.RecordCreated)
                {
                    xrmResponse = new XrmResponse
                    {
                        Id         = response.Target.Id.ToString(),
                        EntityName = entityRecord.LogicalName,
                        Create     = true
                    }
                }
                ;
                else
                {
                    xrmResponse = new XrmResponse()
                    {
                        Id         = response.Target.Id.ToString(),
                        EntityName = entityRecord.LogicalName,
                        Create     = false
                    }
                };
            }


            return(xrmResponse);
        }
示例#14
0
        public static void ProcessUpsert(CrmServiceClient service, String Filename)
        {
            Console.WriteLine("Executing upsert operation.....");
            XmlTextReader tr   = new XmlTextReader(Filename);
            XmlDocument   xdoc = new XmlDocument();

            xdoc.Load(tr);
            XmlNodeList xnlNodes = xdoc.DocumentElement.SelectNodes("/products/product");

            foreach (XmlNode xndNode in xnlNodes)
            {
                String productCode     = xndNode.SelectSingleNode("Code").InnerText;
                String productName     = xndNode.SelectSingleNode("Name").InnerText;
                String productCategory = xndNode.SelectSingleNode("Category").InnerText;
                String productMake     = xndNode.SelectSingleNode("Make").InnerText;

                //use alternate key for product
                Entity productToCreate = new Entity("sample_product", "sample_productcode", productCode);

                productToCreate["sample_name"]     = productName;
                productToCreate["sample_category"] = productCategory;
                productToCreate["sample_make"]     = productMake;
                var request = new UpsertRequest()
                {
                    Target = productToCreate
                };

                try
                {
                    // Execute UpsertRequest and obtain UpsertResponse.
                    var response = (UpsertResponse)service.Execute(request);
                    if (response.RecordCreated)
                    {
                        Console.WriteLine("New record {0} is created!", productName);
                    }
                    else
                    {
                        Console.WriteLine("Existing record {0} is updated!", productName);
                    }
                }

                // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
                catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
                {
                    throw;
                }
            }
        }
示例#15
0
        /// <summary>
        /// Creates or Updates a row, depending if it already exists in the targeted environment
        /// </summary>
        /// <param name="service">Dataverse Organization service</param>
        /// <param name="record">Row to process</param>
        /// <returns>A value that indicates if the row was created (true) or updated (false)</returns>
        public static bool Upsert(this IOrganizationService service, Entity record)
        {
            var request = new UpsertRequest
            {
                Target = record
            };

            var response = (UpsertResponse)service.Execute(request);

            if (response.RecordCreated)
            {
                record.Id = response.Target.Id;
            }

            return(response.RecordCreated);
        }
示例#16
0
        public UpsertResponse Upsert(Entity entity, Guid callerId)
        {
            #region Parameters check
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            #endregion

            var service = GetService(callerId);

            var request = new UpsertRequest {
                Target = entity
            };

            return((UpsertResponse)service.Execute(request));
        }
示例#17
0
        private Guid CreateSdkImage(Guid stepId, XmlElement sdkstepImageNode, string messageName, IOrganizationService service)
        {
            Guid   createdImageId = Guid.Empty;
            Entity image          = new Entity("sdkmessageprocessingstepimage", new Guid(sdkstepImageNode.GetAttribute("Id")));

            switch (messageName)
            {
            case "Create":
                image["messagepropertyname"] = "Id";
                break;

            case "SetState":
            case "SetStateDynamicEntity":
                image["messagepropertyname"] = "EntityMoniker";
                break;

            case "Send":
            case "DeliverIncoming":
            case "DeliverPromote":
                image["messagepropertyname"] = "EmailId";
                break;

            default:
                image["messagepropertyname"] = "Target";
                break;
            }

            Console.WriteLine("Registering the sdk image: " + sdkstepImageNode.GetAttribute("Name"));
            image["imagetype"]   = new OptionSetValue(Convert.ToInt32(sdkstepImageNode.GetAttribute("ImageType")));
            image["entityalias"] = sdkstepImageNode.GetAttribute("EntityAlias");
            image["name"]        = sdkstepImageNode.GetAttribute("Name");
            image["attributes"]  = sdkstepImageNode.GetAttribute("Attributes");
            image["sdkmessageprocessingstepid"] = new EntityReference("sdkmessageprocessingstep", stepId);
            UpsertRequest upsertsdkImage = new UpsertRequest();

            upsertsdkImage.Target = image;
            UpsertResponse upsertSdkImageReponse = (UpsertResponse)service.Execute(upsertsdkImage);

            if (upsertSdkImageReponse.RecordCreated)
            {
                createdImageId = upsertSdkImageReponse.Target.Id;
            }

            return(createdImageId);
        }
示例#18
0
        public void TestUpsertAll()
        {
            using (var context = new Xrm(orgAdminUIService))
            {
                var account1 = new Account {
                    Name = "Account 1"
                };
                var account2 = new Account {
                    Name = "Account 2"
                };

                var _account1id = orgAdminUIService.Create(account1);
                Assert.AreEqual(1,
                                context.AccountSet
                                .Where(x => x.Name.StartsWith("Account"))
                                .ToList().Count
                                );
                Assert.AreEqual("Account 1", context.AccountSet.First().Name);

                var bla = Account.Retrieve_dg_name(orgAdminUIService, "Account 2");

                context.ClearChanges();
                var req = new UpsertRequest
                {
                    Target = new Account {
                        Name = "New Account 1", Id = _account1id
                    }
                };
                var resp = orgAdminUIService.Execute(req) as UpsertResponse;
                Assert.IsFalse(resp.RecordCreated);
                Assert.AreEqual(1,
                                context.AccountSet
                                .Where(x => x.Name.StartsWith("New Account"))
                                .ToList().Count);
                Assert.AreEqual("New Account 1", context.AccountSet.First().Name);

                context.ClearChanges();
                req.Target = account2;
                resp       = orgAdminUIService.Execute(req) as UpsertResponse;
                Assert.IsTrue(resp.RecordCreated);
                Assert.AreEqual(2, context.AccountSet.AsEnumerable().Where(
                                    x => x.Name.StartsWith("Account") || x.Name.StartsWith("New Account")).Count());
            }
        }
示例#19
0
        public void Write(UpsertRequest <T> value, IMsgPackWriter writer)
        {
            writer.WriteMapHeader(3);

            _keyConverter.Write(Key.SpaceId, writer);
            _uintConverter.Write(value.SpaceId, writer);

            _keyConverter.Write(Key.Tuple, writer);
            _tupleConverter.Write(value.Tuple, writer);

            _keyConverter.Write(Key.Ops, writer);
            writer.WriteArrayHeader((uint)value.UpdateOperations.Length);

            foreach (var updateOperation in value.UpdateOperations)
            {
                var operationConverter = updateOperation.GetConverter(_context);
                operationConverter.Write(updateOperation, writer);
            }
        }
示例#20
0
        /// <summary>
        /// Обновить или создать запись
        /// </summary>
        /// <param name="name">Наименование веб-ресурса</param>
        /// <param name="filePath">Путь до файла</param>
        /// <param name="type">Тип веб-ресурса</param>
        public Entity CreateOrUpdate(string name, string filePath, WebResourceType type = WebResourceType.Auto)
        {
            var idRecord = RetrieveWebresource(name);
            var record   = CreateRecord(name, filePath, type);

            if (idRecord?.Id != null)
            {
                record.Id = idRecord.Id;
            }

            var upsertReq = new UpsertRequest
            {
                Target = record
            };

            var ret = OrganizationService.Execute(upsertReq) as UpsertResponse;

            record.Id = ret?.Target.Id ?? Guid.Empty;
            return(record);
        }
示例#21
0
        private void ReProcessFailedForEntity(IOrganizationService targetService, string entityName, ColumnSet columns, CrmBulkServiceManager bulkMgr)
        {
            QueryExpression queryFailed = new QueryExpression("ctccrm_entitychangefailed");

            queryFailed.ColumnSet = new ColumnSet(new string[] { "ctccrm_recordid", "ctccrm_retrycount" });
            queryFailed.Criteria  = new FilterExpression();
            queryFailed.Criteria.AddCondition("ctccrm_name", ConditionOperator.Equal, entityName);

            ConditionExpression limitRetry  = new ConditionExpression("ctccrm_retrycount", ConditionOperator.LessThan, 6);
            ConditionExpression retryNullOK = new ConditionExpression("ctccrm_retrycount", ConditionOperator.Null);
            var filterRetry = new FilterExpression(LogicalOperator.Or);

            filterRetry.AddCondition(limitRetry);
            filterRetry.AddCondition(retryNullOK);
            queryFailed.Criteria.Filters.Add(filterRetry);


            QueryToAction(targetService, queryFailed, (entityList) =>
            {
                foreach (var entity in entityList.Entities)
                {
                    try
                    {
                        var sourceEntity = _Service.Retrieve(entityName, Guid.Parse(entity.GetAttributeValue <string>("ctccrm_recordid")), columns);
                        TrimFieldsFromChanges(sourceEntity);
                        UpsertRequest targetReq = new UpsertRequest();
                        targetReq.Target        = sourceEntity;
                        DeleteRequest deleteReq = new DeleteRequest();
                        deleteReq.Target        = entity.ToEntityReference();
                        bulkMgr.BulkTransaction(new OrganizationRequest[] { targetReq, deleteReq });
                    }
                    catch (Exception ex)
                    {
                        int retryCount = entity.GetAttributeValue <int>("ctccrm_retrycount");
                        retryCount++;
                        entity["ctccrm_retrycount"] = retryCount;
                        targetService.Update(entity);
                    }
                }
            });
        }
        private void ApplyUpsertRecords(RetrieveAllEntitiesResponse SourceMetaData, string logicalName, Entity RecordToClone)
        {
            if (chkUpsertRecords.Checked)
            {
                var primaryIdAttribute = SourceMetaData.EntityMetadata.First(entityMetaData => entityMetaData.LogicalName == logicalName).PrimaryIdAttribute;

                RecordToClone.KeyAttributes.Add(primaryIdAttribute, RecordToClone.Id);

                var upsertReq = new UpsertRequest()
                {
                    Target = RecordToClone
                };

                var resp    = (UpsertResponse)lastTargetService.Value.Execute(upsertReq);
                var created = resp.RecordCreated;
            }
            else
            {
                lastTargetService.Value.Create(RecordToClone);
            }
        }
示例#23
0
        private Guid RegisterWorkflowTypes(EntityReference pluginAssembly, XmlElement workflowTypeNode, IOrganizationService service)
        {
            Guid   workflowTypeId   = Guid.Empty;
            Entity pluginTypeEntity = new Entity("plugintype", new Guid(workflowTypeNode.GetAttribute("Id")));

            pluginTypeEntity["typename"]                  = workflowTypeNode.GetAttribute("TypeName");
            pluginTypeEntity["friendlyname"]              = workflowTypeNode.GetAttribute("friendlyname");
            pluginTypeEntity["name"]                      = workflowTypeNode.GetAttribute("Name");
            pluginTypeEntity["pluginassemblyid"]          = pluginAssembly;
            pluginTypeEntity["workflowactivitygroupname"] = workflowTypeNode.GetAttribute("WorkflowActivityGroupName");
            pluginTypeEntity["isworkflowactivity"]        = true;
            UpsertRequest upsertPluginTypeRequest = new UpsertRequest();

            upsertPluginTypeRequest.Target = pluginTypeEntity;
            UpsertResponse upsertPluginTypeResponse = (UpsertResponse)service.Execute(upsertPluginTypeRequest);

            if (upsertPluginTypeResponse.RecordCreated)
            {
                workflowTypeId = upsertPluginTypeResponse.Target.Id;
            }

            return(workflowTypeId);
        }
示例#24
0
        public override async Task <UpsertResponse> Upsert(UpsertRequest request, ServerCallContext context)
        {
            await _localSessionRepo.UpsertSession(request.Session);

            return(new UpsertResponse());
        }
示例#25
0
        public static ExecuteTransactionRequest ProcessRecord(AdhocImportRecord record, Entity sku, Entity businessUnit)
        {
            if (record == null)
            {
                return(null);
            }

            var reqExecTransaction = new ExecuteTransactionRequest()
            {
                Requests = new OrganizationRequestCollection()
            };

            Entity durable = new Entity("dsr_durable", "dsr_serialnumber", record.UnitSerialNumber);

            var skuDsrName        = sku.Contains("dsr_name") ? sku.GetAttributeValue <string>("dsr_name") : string.Empty;
            var skuDsrDisplayname = sku.Contains("dsr_displayname") ? sku.GetAttributeValue <string>("dsr_displayname") : string.Empty;

            durable["dsr_name"]        = $"{skuDsrName} - {record.UnitSerialNumber}";
            durable["dsr_displayname"] = skuDsrDisplayname;

            durable["dsr_islegacywarranty"] = record.IsLegacyWarranty;

            if (!String.IsNullOrWhiteSpace(record.ProductSku))
            {
                durable["new_skunumber"] = record.ProductSku;
                durable["dsr_skuid"]     = new EntityReference(sku.LogicalName, sku.Id);
            }
            durable["dsr_relatedbusinessunit"] = businessUnit == null ? null : new EntityReference(businessUnit.LogicalName, businessUnit.Id);
            durable["dsr_shipdate"]            = record.ShipDate;

            if (!String.IsNullOrWhiteSpace(record.OrderNumber))
            {
                durable["dsr_ordernumber"] = record.OrderNumber;
            }

            if (!String.IsNullOrWhiteSpace(record.InvoiceNumber))
            {
                durable["dsr_invoicenumber"] = record.InvoiceNumber;
            }

            durable["dsr_registrationdate"] = record.RegistrationDate;

            UpsertRequest upsertDurableRequest = new UpsertRequest();

            upsertDurableRequest.Target = durable;
            reqExecTransaction.Requests.Add(upsertDurableRequest);


            if (businessUnit != null && record.RegistrationDate != null)
            {
                Entity contact = new Entity("contact", Guid.NewGuid());
                contact["firstname"]     = record.RegistrantFirstName;
                contact["lastname"]      = record.RegistrantLastName;
                contact["emailaddress1"] = record.RegistrantEmail;
                contact["dsr_abonumber"] = record.RegistrationAboNumber;

                CreateRequest createContactRequest = new CreateRequest()
                {
                    Target = contact
                };
                reqExecTransaction.Requests.Add(createContactRequest);

                Entity registration = new Entity("dsr_registration", Guid.NewGuid());
                registration["dsr_name"]               = $"Registration: {record.RegistrantEmail} Serial: {record.UnitSerialNumber}";
                registration["dsr_businessunitid"]     = new EntityReference("businessunit", businessUnit.Id);
                registration["dsr_productid"]          = new EntityReference("dsr_durable", "dsr_serialnumber", record.UnitSerialNumber);
                registration["dsr_customerid"]         = new EntityReference("contact", contact.Id);
                registration["dsr_registrationdate"]   = record.RegistrationDate;
                registration["new_registrationsource"] = string.IsNullOrWhiteSpace(record.RegistrationSource) ? "adhoc -file-import" : record.RegistrationSource;

                CreateRequest createRegistrationRequest = new CreateRequest()
                {
                    Target = registration
                };
                reqExecTransaction.Requests.Add(createRegistrationRequest);


                Entity upsertDurable = new Entity("dsr_durable", "dsr_serialnumber", record.UnitSerialNumber);
                upsertDurable["dsr_relatedregistration"] = new EntityReference(registration.LogicalName, registration.Id);
                UpsertRequest upsertDurableReq = new UpsertRequest()
                {
                    Target = upsertDurable
                };
                reqExecTransaction.Requests.Add(upsertDurableReq);
            }



            if (record.IsLegacyWarranty)
            {
                TimeSpan duration        = record.WarrantyEndDate.Value - record.WarrantyStartDate.Value;
                Entity   serviceContract = new Entity("dsr_servicecontract", Guid.NewGuid());
                serviceContract["dsr_name"]       = $"Legacy Service Contract - {record.UnitSerialNumber}";
                serviceContract["dsr_startdate"]  = record.WarrantyStartDate;
                serviceContract["dsr_scduration"] = duration.Days;
                serviceContract["dsr_productid"]  = new EntityReference("dsr_durable", "dsr_serialnumber", record.UnitSerialNumber);

                CreateRequest createServiceContractRequest = new CreateRequest()
                {
                    Target = serviceContract
                };
                reqExecTransaction.Requests.Add(createServiceContractRequest);
            }


            return(reqExecTransaction);
        }
        public ActionResult RetrieveOrcidProfile()
        {
            // if the user is anonymus or null, redirect them to the signin page

            if (!InitializeOrcidController())
            {
                // TODO give a better error around not already being signed in.
                return(Redirect("/SignIn/"));
            }
            if (string.IsNullOrEmpty(UserAuthorizationToken))
            {
                // user authorization token is not defined
            }

            record userRecord = OrcidClient.GetUserRecord();

            // Create the entity contact to update.
            Contact contact = new Contact();

            contact.Id = xrmUser.ContactId.Id;
            contact.rp2_OricdBiography = userRecord?.person?.biography?.content;

            service = HttpContext.GetOrganizationService();

            service.Update(contact);

            if (userRecord.activitiessummary == null)
            {
                return(Redirect("/profile/orcid/"));
            }
            ExecuteMultipleRequest mRequest = new ExecuteMultipleRequest();

            mRequest.Settings = new ExecuteMultipleSettings();
            mRequest.Settings.ContinueOnError = true;
            mRequest.Settings.ReturnResponses = false;
            mRequest.Requests = new OrganizationRequestCollection();

            employments userEmployments = OrcidClient.GetUserOrcidData <employments>(userRecord.activitiessummary.employments.path);

            if (userEmployments?.employmentsummary != null)
            {
                foreach (employmentsummary es in userEmployments.employmentsummary)
                {
                    rp2_employment employment = new rp2_employment("rp2_sourceidentifier", es.path);

                    employment.rp2_Person               = xrmUser.ContactId;
                    employment.rp2_Department           = es?.departmentname;
                    employment.rp2_OrganizationNameText = es?.organization?.name;
                    employment.rp2_RoleTitle            = es.roletitle;
                    employment.rp2_City          = es.organization?.address?.city;
                    employment.rp2_Country       = es.organization?.address?.country.ToString();
                    employment.rp2_StateProvince = es.organization?.address?.region;
                    employment.rp2_EndDate       = es.enddate?.ToDateTime();
                    employment.rp2_StartDate     = es.startdate?.ToDateTime();

                    //service.Create(employment);
                    UpsertRequest cRq = new UpsertRequest();
                    cRq.Target = employment;
                    mRequest.Requests.Add(cRq);
                }
            }
            if (mRequest.Requests.Count > 0)
            {
                ExecuteMultipleResponse response = service.Execute(mRequest) as ExecuteMultipleResponse;
                // TODO validate resonse
                var errorFaults = response.Responses.Where(r => r.Fault != null);
                if (errorFaults.Any())
                {
                    string errorMessages = "{" + string.Join("}, {", errorFaults.Select(f => f.Fault.Message)) + "}";
                    throw new Exception(errorMessages);
                }
            }
            return(Redirect("/profile/orcid/"));
        }
示例#27
0
        public void RegisterPluginsFromXml(string registrationXmlPath, string pluginsDllFilePath, IOrganizationService service)
        {
            RetrievePluginTypes retrievePluginTypes = new RetrievePluginTypes();
            string      strPluginDllName            = Path.GetFileName(pluginsDllFilePath);
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(registrationXmlPath);
            XmlNodeList xnList = xmlDoc.DocumentElement.SelectNodes("/Register/Solutions/Solution[@Assembly='" + strPluginDllName + "']");

            foreach (XmlElement node in xnList)
            {
                var id = node.GetAttribute("Id");
                UnRegisterPlugins unregisterPlugins = new UnRegisterPlugins();
                Console.WriteLine("Unregistering the plugin assembly: " + strPluginDllName);
                unregisterPlugins.UnRegisterPluginTypes(new Guid(id), service);
                var    sourceType     = Convert.ToInt32(node.GetAttribute("SourceType").ToString());
                var    isolationMode  = Convert.ToInt32(node.GetAttribute("IsolationMode").ToString());
                Entity pluginAssembly = new Entity("pluginassembly", new Guid(id));
                pluginAssembly["isolationmode"] = new OptionSetValue(isolationMode);
                pluginAssembly["sourcetype"]    = new OptionSetValue(sourceType);
                pluginAssembly["content"]       = Convert.ToBase64String(File.ReadAllBytes(pluginsDllFilePath));
                UpsertRequest upsertpluginAssemblyRequest = new UpsertRequest();
                upsertpluginAssemblyRequest.Target = pluginAssembly;
                UpsertResponse upsertPluginAssemblyResponse = (UpsertResponse)service.Execute(upsertpluginAssemblyRequest);
                node.Attributes["Id"].Value = upsertPluginAssemblyResponse.Target.Id.ToString();
                pluginAssembly.Id           = upsertPluginAssemblyResponse.Target.Id;
                XmlNodeList workflowTypeList = node.SelectNodes("WorkflowTypes/WorkflowType");
                foreach (XmlElement workflowType in workflowTypeList)
                {
                    Guid workflowTypeId = RegisterWorkflowTypes(new EntityReference(pluginAssembly.LogicalName, upsertPluginAssemblyResponse.Target.Id), workflowType, service);
                    workflowType.Attributes["Id"].Value = workflowTypeId.ToString();
                }

                XmlNodeList pluginTypeList = node.SelectNodes("PluginTypes/Plugin");
                foreach (XmlElement pluginType in pluginTypeList)
                {
                    Console.WriteLine("Registering the plugin type: " + pluginType.GetAttribute("TypeName"));
                    Entity pluginTypeEntity = new Entity("plugintype", new Guid(pluginType.GetAttribute("Id")));
                    pluginTypeEntity["typename"]         = pluginType.GetAttribute("TypeName");
                    pluginTypeEntity["friendlyname"]     = pluginType.GetAttribute("friendlyname");
                    pluginTypeEntity["name"]             = pluginType.GetAttribute("Name");
                    pluginTypeEntity["pluginassemblyid"] = new EntityReference(pluginAssembly.LogicalName, pluginAssembly.Id);
                    UpsertRequest upsertPluginTypeRequest = new UpsertRequest();
                    upsertPluginTypeRequest.Target = pluginTypeEntity;
                    UpsertResponse upsertPluginTypeResponse = (UpsertResponse)service.Execute(upsertPluginTypeRequest);
                    if (upsertPluginTypeResponse.RecordCreated)
                    {
                        pluginType.Attributes["Id"].Value = upsertPluginTypeResponse.Target.Id.ToString();
                    }

                    XmlNodeList sdksteps = pluginType.SelectNodes("Steps/Step");
                    foreach (XmlElement sdkmessageStepNode in sdksteps)
                    {
                        Console.WriteLine("Registering the sdk step: " + sdkmessageStepNode.GetAttribute("Name"));
                        Entity sdkmessageProcessingStep = new Entity("sdkmessageprocessingstep", new Guid(sdkmessageStepNode.GetAttribute("Id")));
                        sdkmessageProcessingStep["name"]        = sdkmessageStepNode.GetAttribute("Name");
                        sdkmessageProcessingStep["description"] = sdkmessageStepNode.GetAttribute("Description");
                        Guid messageId = retrievePluginTypes.GetSdkMessageId(sdkmessageStepNode.GetAttribute("MessageName"), service);
                        sdkmessageProcessingStep["sdkmessageid"]        = new EntityReference("sdkmessage", messageId);
                        sdkmessageProcessingStep["plugintypeid"]        = new EntityReference("plugintype", upsertPluginTypeResponse.Target.Id);
                        sdkmessageProcessingStep["mode"]                = new OptionSetValue(Convert.ToInt32(sdkmessageStepNode.GetAttribute("Mode")));  //0=sync,1=async
                        sdkmessageProcessingStep["rank"]                = Convert.ToInt32(sdkmessageStepNode.GetAttribute("Rank"));
                        sdkmessageProcessingStep["stage"]               = new OptionSetValue(Convert.ToInt32(sdkmessageStepNode.GetAttribute("Stage"))); //10-preValidation, 20-preOperation, 40-PostOperation
                        sdkmessageProcessingStep["supporteddeployment"] = new OptionSetValue(Convert.ToInt32(sdkmessageStepNode.GetAttribute("SupportedDeployment")));
                        Guid messageFitlerId = retrievePluginTypes.GetSdkMessageFilterId(sdkmessageStepNode.GetAttribute("PrimaryEntityName"), messageId, service);
                        sdkmessageProcessingStep["sdkmessagefilterid"] = new EntityReference("sdkmessagefilter", messageFitlerId);
                        UpsertRequest upsertPluginStepsRequest = new UpsertRequest();
                        upsertPluginStepsRequest.Target = sdkmessageProcessingStep;
                        UpsertResponse upsertPluginStepResponse = (UpsertResponse)service.Execute(upsertPluginStepsRequest);
                        if (upsertPluginStepResponse.RecordCreated)
                        {
                            sdkmessageStepNode.Attributes["Id"].Value = upsertPluginStepResponse.Target.Id.ToString();
                        }

                        string      messageName   = sdkmessageStepNode.GetAttribute("MessageName");
                        XmlNodeList sdkstepImages = sdkmessageStepNode.SelectNodes("Images/Image");
                        foreach (XmlElement sdkstepImageNode in sdkstepImages)
                        {
                            Guid createdImageId = CreateSdkImage(upsertPluginStepResponse.Target.Id, sdkstepImageNode, messageName, service);
                            if (createdImageId != Guid.Empty)
                            {
                                sdkstepImageNode.Attributes["Id"].Value = createdImageId.ToString();
                            }
                        }
                    }
                }
            }

            xmlDoc.Save(registrationXmlPath);
        }
示例#28
0
        static void Main(string[] args)
        {
            var       organizationServiceProxy             = new OrganizationServiceProxy(GetUri(), null, GetClientCredentials(), null);
            DataTable csvDataTable                         = GetCSVData();
            ExecuteMultipleRequest executeMultipleRequest1 = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings
                {
                    ContinueOnError = true,
                    ReturnResponses = true
                }
                ,
                Requests = new OrganizationRequestCollection()
            };
            ExecuteMultipleRequest executeMultipleRequest2 = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings
                {
                    ContinueOnError = true,
                    ReturnResponses = true
                }
                ,
                Requests = new OrganizationRequestCollection()
            };
            int counter = 0;

            for (int locIndexRow = 1; locIndexRow < csvDataTable.Rows.Count; locIndexRow++)
            {
                string          name            = csvDataTable.Rows[locIndexRow][0].ToString();
                string          primaryContact  = csvDataTable.Rows[locIndexRow][1].ToString();
                string          telephone1      = csvDataTable.Rows[locIndexRow][2].ToString();
                QueryExpression queryExpression = new QueryExpression("contact");
                queryExpression.ColumnSet = new ColumnSet(false);
                queryExpression.NoLock    = true;
                queryExpression.TopCount  = 1;
                queryExpression.Criteria.AddCondition("fullname", ConditionOperator.Equal, primaryContact);
                Entity queryResult = organizationServiceProxy.RetrieveMultiple(queryExpression).Entities.FirstOrDefault();
                if (queryResult != null)
                {
                    EntityReference primaryContactReference = queryResult.ToEntityReference();
                    Entity          customEntity            = CreateCustomEntity("account", name, primaryContactReference, telephone1);
                    UpsertRequest   upsertRequest           = new UpsertRequest()
                    {
                        Target = customEntity
                    };
                    if (locIndexRow % 2 == 0)
                    {
                        executeMultipleRequest1.Requests.Add(upsertRequest);
                    }
                    else
                    {
                        executeMultipleRequest2.Requests.Add(upsertRequest);
                    }
                    counter++;
                    Console.WriteLine($"Request {counter} added");
                }
            }
            Console.WriteLine("Started executing request.");
            Task.WaitAll(Task.Run(() =>
            {
                ExecuteMultipleResponse executeMultipleResponse = (ExecuteMultipleResponse)organizationServiceProxy.Execute(executeMultipleRequest1);
                foreach (var response in executeMultipleResponse.Responses)
                {
                    if (response.Fault != null)
                    {
                        Console.WriteLine(response.Fault.Message);
                    }
                    else
                    {
                        Console.WriteLine("Request1 executed done!");
                    }
                }
            }),
                         Task.Run(() =>
            {
                ExecuteMultipleResponse executeMultipleResponse = (ExecuteMultipleResponse)organizationServiceProxy.Execute(executeMultipleRequest2);
                foreach (var response in executeMultipleResponse.Responses)
                {
                    if (response.Fault != null)
                    {
                        Console.WriteLine(response.Fault.Message);
                    }
                    else
                    {
                        Console.WriteLine("Request2 executed done!");
                    }
                }
            }));
            executeMultipleRequest1.Requests.Clear();
            executeMultipleRequest2.Requests.Clear();
            Console.WriteLine("Requests have been executed");
            Console.ReadLine();
        }
 /// <summary>Performs a UPSERT (update-or-insert) request.</summary>
 /// <param name="upsertRequest">The upsert request.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <typeparam name="T">The class for object mapping.</typeparam>
 /// <returns>The <see cref="Task" /> with no data as result.</returns>
 public async Task UpsertAsync <T>(UpsertRequest <T> upsertRequest, CancellationToken cancellationToken)
 {
     await RequestAsync(upsertRequest, cancellationToken).ConfigureAwait(false);
 }
示例#30
0
        private void btnMigrateRecordBPF_Click(object sender, EventArgs evt)
        {
            if (!AllowMigrateButton())
            {
                return;
            }

            string        bpfSelectedEntityTarget = bpfSelected.GetAttributeValue <string>("uniquename");
            var           stageId             = stageList.FirstOrDefault(w => w.Attributes["stagename"] == cbTargetBPFStages.SelectedItem);
            List <string> traversedpath       = new List <string>();
            string        targetStage         = cbTargetBPFStages.SelectedItem.ToString();
            var           totalRecordMigrated = 0;

            totalRecordToMigrate = recordToMigrateList.Count;
            migrationErrors      = new List <MigrationError>();

            manageEnablingOfControls(false);
            DisplayStatsMiddle();

            // Init progressBar

            SendMessageToStatusBar(this, new StatusBarMessageEventArgs(0, "Starting migration ..."));

            WorkAsync(new WorkAsyncInfo
            {
                Message      = $"Migrating the Business Process flows for each records {Environment.NewLine}May take a moment ...",
                IsCancelable = true,
                Work         = (bw, e) =>
                {
                    List <Entity> retrieveExistingBPFInstances = null;
                    try
                    {
                        retrieveExistingBPFInstances = dm.GetExistingBPFInstances(bpfSelected.GetAttributeValue <string>("uniquename"),
                                                                                  recordToMigrateList.FirstOrDefault().LogicalName, recordToMigrateList.Select(x => x.Id).ToArray());
                    }
                    catch (Exception exception)
                    {
                        if (!continueOnPermissionError)
                        {
                            var result = MessageBox.Show(exception.Message, "Error during migration !",
                                                         MessageBoxButtons.YesNo, MessageBoxIcon.Error);

                            if (result == DialogResult.No)
                            {
                                return;
                            }
                            else if (result == DialogResult.Yes)
                            {
                                continueOnPermissionError = true;
                            }
                        }
                    }
                    int progress = ((totalRecordMigrated * 100) / totalRecordToMigrate);
                    var bpfSelectedEntityName = bpfSelected.GetAttributeValue <string>("uniquename");

                    // Get lookup field between record entity & bpf entity
                    var referencingAttributeEntityBpf = this.dm.RetrieveReferencingAttributeOfBpf(bpfSelectedEntityName, recordEntityToMigrate);

                    var numberOfRecordsToProceed = recordToMigrateList.Count;

                    var executeMultipleRequestSetBPF = new ExecuteMultipleRequest()
                    {
                        Settings = new ExecuteMultipleSettings()
                        {
                            ContinueOnError = false,
                            ReturnResponses = true
                        },
                        Requests = new OrganizationRequestCollection()
                    };

                    // for each record to migrate
                    foreach (var record in recordToMigrateList)
                    {
                        if (bw.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        var bpfInstanceExist = this.dm.GetExistingBpfInstance(bpfSelectedEntityName, referencingAttributeEntityBpf, record.Id);

                        var bpfToUpdate = new Entity(bpfSelectedEntityName);
                        if (bpfInstanceExist != null)
                        {
                            bpfToUpdate.Id = bpfInstanceExist.Id;
                        }
                        bpfToUpdate[referencingAttributeEntityBpf] = record.ToEntityReference();
                        bpfToUpdate["activestageid"] = stageId.ToEntityReference();
                        UpsertRequest upsertRequest  = new UpsertRequest()
                        {
                            Target = bpfToUpdate
                        };

                        executeMultipleRequestSetBPF.Requests.Add(upsertRequest);

                        totalRecordMigrated++;

                        if (totalRecordMigrated % this.settings.NumberOfRecordPerRound == 0 || numberOfRecordsToProceed == totalRecordMigrated)
                        {
                            ExecuteMultipleRequestBPF(ref executeMultipleRequestSetBPF, bw,
                                                      totalRecordMigrated, 0, "updated");
                            progress = ((totalRecordMigrated * 100) / totalRecordToMigrate);
                            SendMessageToStatusBar(this, new StatusBarMessageEventArgs(progress, $"Migration in progress {progress}%  ..."));
                            bw?.ReportProgress(0, $"Processing business process flows {totalRecordMigrated}/{totalRecordToMigrate} migrated ...");
                        }

                        Invoke(new Action(() =>
                        {
                            labelRecordsRemaining.Text = $@"{totalRecordToMigrate - totalRecordMigrated}";
                        }));
                    }

                    e.Result = totalRecordMigrated;
                },
                PostWorkCallBack = e =>
                {
                    if (e.Error != null)
                    {
                        MessageBox.Show(this, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.log.LogData(EventType.Exception, LogAction.RecordsMigrated, e.Error);
                        return;
                    }
                    else if (e.Cancelled)
                    {
                        this.log.LogData(EventType.Event, LogAction.MigrationCancelled);
                        MessageBox.Show(
                            $"The migration was successfully cancelled. {Environment.NewLine}{totalRecordMigrated} records were migrated.",
                            "Cancel", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        labelNumberOfRecordsToMigrate.Text = "The migration will handle : X records.";
                        labelRecordsRemaining.Text         = "X";
                        labelTimeEstimation.Text           = "This can take up to X time.";

                        SendMessageToStatusBar(this, new StatusBarMessageEventArgs(0, "Cancelled ..."));
                    }
                    else
                    {
                        MessageBox.Show($"You migrated {totalRecordMigrated} records !", "Migration done.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        SendMessageToStatusBar(this, new StatusBarMessageEventArgs("done!."));
                        this.log.LogData(EventType.Event, LogAction.RecordsMigrated);
                    }

                    manageEnablingOfControls(true);
                },
                ProgressChanged = e => { SetWorkingMessage(e.UserState.ToString()); }
            });
        }