/// <summary> /// Assigns ownership of a record to a new user or team /// </summary> /// <param name="entityname">The Name of the Entity</param> /// <param name="id">The unique Id of the record that is to be assigned</param> /// <param name="ownerid">The new owner of the record</param> /// <param name="ownertype">The type of owner of the record</param> public static void AssignOwnership(string entityname, Guid id, Guid ownerid, OwnerTypeCode ownertype) { AssignRequest request = new AssignRequest(); request.Target = new EntityReference(entityname, id); request.Assignee = new EntityReference(ownertype.ToString().ToLower(), ownerid); AssignResponse response = (AssignResponse)OrganizationService.Execute(request); }
private AssignResponse HandleAssign(OrganizationRequest orgRequest, EntityReference userRef) { var request = MakeRequest <AssignRequest>(orgRequest); var resp = new AssignResponse(); dataMethods.Assign(request.Target, request.Assignee, userRef); return(resp); }
protected override void Execute(System.Activities.CodeActivityContext context) { var workflowContext = context.GetExtension <IWorkflowContext>(); var service = this.RetrieveOrganizationService(context); QueryResult result = ExecuteQueryForRecords(context); if (!result.EntityName.Equals("systemuser", StringComparison.InvariantCultureIgnoreCase) && !result.EntityName.Equals("team", StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentException("Query must return a User or Team record"); } // Ensure the record has an owner field RetrieveEntityRequest request = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest() { EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity, LogicalName = workflowContext.PrimaryEntityName }; RetrieveEntityResponse metadataResponse = service.Execute(request) as RetrieveEntityResponse; if (metadataResponse.EntityMetadata.OwnershipType == null || metadataResponse.EntityMetadata.OwnershipType.Value != OwnershipTypes.UserOwned) { throw new ArgumentException("This activity is only available for User owned records"); } if (!result.RecordIds.Any()) { return; } var workflowRecord = new EntityReference(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId); var assignee = new EntityReference(result.EntityName, result.RecordIds.FirstOrDefault()); AssignRequest assignRequest = new AssignRequest() { Assignee = assignee, Target = workflowRecord }; try { AssignResponse response = service.Execute(assignRequest) as AssignResponse; if (assignee.LogicalName.Equals("team")) { this.NewOwner_Team.Set(context, assignee); } else { this.NewOwner_User.Set(context, assignee); } this.RecordReassigned.Set(context, true); } catch (Exception ex) { throw new Exception($"There was an error reassigning the record: {ex.Message}"); } }
private void UpdateEntityOwner(IOrganizationService service, string entityName, Guid entityId, Guid ownerId, string ownerIdType) { AssignRequest request = new AssignRequest() { Assignee = new EntityReference(ownerIdType, ownerId), Target = new EntityReference(entityName, entityId) }; try { AssignResponse response = (AssignResponse)service.Execute(request); } catch (FaultException <OrganizationServiceFault> ex) { throw new Exception("XrmWorkflowTools.AssignChildRecords.UpdateEntityOwner: " + ex.Message); } }
public void AssignEntityToUserTest() { Mock <IOrganizationService> orgSvc = null; Mock <MoqHttpMessagehander> fakHttpMethodHander = null; ServiceClient cli = null; testSupport.SetupMockAndSupport(out orgSvc, out fakHttpMethodHander, out cli); AssignResponse assignResponse = new AssignResponse(); orgSvc.Setup(f => f.Execute(It.IsAny <AssignRequest>())).Returns(assignResponse); bool result = cli.AssignEntityToUser(testSupport._DefaultId, "account", testSupport._DefaultId); Assert.True(result); }
public Respuesta Asignar(Guid ContactoID, Guid UsuarioID, IOrganizationService Servicio) { Respuesta resp = new Respuesta(); try { AssignRequest assign = new AssignRequest(); assign.Assignee = new EntityReference("systemuser", UsuarioID); assign.Target = new EntityReference(_nombreEntidad, ContactoID); AssignResponse response = (AssignResponse)Servicio.Execute(assign); var name = response.ResponseName; } catch (Exception ex) { resp.Error = ex.Message; } return(resp); }
static void ExecuteAssign(OrganizationServiceProxy serviceProxy) { Guid systemuserid = Guid.Empty; EntityReference alvo = new EntityReference(); QueryExpression queryExpression = new QueryExpression("systemuser"); queryExpression.Criteria.AddCondition("fullname", ConditionOperator.BeginsWith, "Marcos"); queryExpression.ColumnSet = new ColumnSet(true); EntityCollection colecaoEntidades = serviceProxy.RetrieveMultiple(queryExpression); if (colecaoEntidades.Entities != null && colecaoEntidades.Entities.Count > 0) { systemuserid = colecaoEntidades[0].Id; EntityReference dono = new EntityReference("systemuser", systemuserid); queryExpression = new QueryExpression("account"); queryExpression.Criteria.AddCondition("name", ConditionOperator.BeginsWith, "Alpine"); queryExpression.ColumnSet = new ColumnSet(true); colecaoEntidades = serviceProxy.RetrieveMultiple(queryExpression); if (colecaoEntidades.Entities != null && colecaoEntidades.Entities.Count > 0) { foreach (var item in colecaoEntidades.Entities) { try { alvo = new EntityReference("account", item.Id); AssignRequest assignRequest = new AssignRequest(); assignRequest.Assignee = dono; assignRequest.Target = alvo; AssignResponse response = (AssignResponse)serviceProxy.Execute(assignRequest); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } } } }
public String CreateContact(Guid contact_ID, Contact contact) { Guid contactid = contact_ID; try { contact cont = new contact(); CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); if (contact_ID == new Guid("{00000000-0000-0000-0000-000000000000}")) { contactid = crmService.Create(cont); } // Создаем экземпляр динамческого объекта и указываем его имя DynamicEntity myDEUpdate = new DynamicEntity(); myDEUpdate.Name = "contact"; // Создаем KeyProperty для хранения GUID’а обновляемой записи KeyProperty myContactGuid = new KeyProperty(); myContactGuid.Name = "contactid"; // Указываем GUID обновляемой записи Key myContactKey = new Key(); myContactKey.Value = contactid; myContactGuid.Value = myContactKey; myDEUpdate.Properties.Add(myContactGuid); if (contact.address1_city != null) { myDEUpdate.Properties.Add(new StringProperty("address1_city", contact.address1_city)); } if (contact.address1_country != null) { myDEUpdate.Properties.Add(new StringProperty("address1_country", contact.address1_country)); } if (contact.address1_line1 != null) { myDEUpdate.Properties.Add(new StringProperty("address1_line1", contact.address1_line1)); } if (contact.address1_name != null) { myDEUpdate.Properties.Add(new StringProperty("address1_name", contact.address1_name)); } if (contact.address1_postalcode != null) { myDEUpdate.Properties.Add(new StringProperty("address1_postalcode", contact.address1_postalcode)); } if (contact.emailaddress1 != null) { myDEUpdate.Properties.Add(new StringProperty("emailaddress1", contact.emailaddress1)); } if (contact.firstname != null) { myDEUpdate.Properties.Add(new StringProperty("firstname", contact.firstname)); } if (contact.lastname != null) { myDEUpdate.Properties.Add(new StringProperty("lastname", contact.lastname)); } if (contact.middlename != null) { myDEUpdate.Properties.Add(new StringProperty("middlename", contact.middlename)); } if (contact.mobilephone != null) { myDEUpdate.Properties.Add(new StringProperty("mobilephone", contact.mobilephone)); } if (contact.salutation != null) { myDEUpdate.Properties.Add(new StringProperty("salutation", contact.salutation)); } //Кем выдан if (contact.new_giveoutby != null) { myDEUpdate.Properties.Add(new StringProperty("new_giveoutby", contact.new_giveoutby)); } //Номер if (contact.new_nomer != null) { myDEUpdate.Properties.Add(new StringProperty("new_nomer", contact.new_nomer)); } //Серия if (contact.new_seria != null) { myDEUpdate.Properties.Add(new StringProperty("new_seria", contact.new_seria)); } //Пол if (contact.gendercode != 0) { myDEUpdate.Properties.Add(new PicklistProperty("gendercode", new Picklist(contact.gendercode))); } //Гражданство if (contact.new_nationality != 0) { myDEUpdate.Properties.Add(new PicklistProperty("new_nationality", new Picklist(contact.new_nationality))); } //Тип ФЛ if (contact.new_type != 0) { myDEUpdate.Properties.Add(new PicklistProperty("new_type", new Picklist(contact.new_type))); } //Семейное положение if (contact.familystatuscode != 0) { myDEUpdate.Properties.Add(new PicklistProperty("familystatuscode", new Picklist(contact.familystatuscode))); } //День рождения if (contact.birthdate != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("birthdate", CrmDateTime.FromUser(DateTime.ParseExact(contact.birthdate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } //Посетил открытый урок if (contact.new_openles != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_openles", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_openles, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } //Дата выдачи if (contact.new_dategiveout != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_dategiveout", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_dategiveout, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } crmService.Update(myDEUpdate); //поиск контакта для переназначения ответственного, если таковой меняется Owner ownerID = new Owner(); if (contact_ID != new Guid("{00000000-0000-0000-0000-000000000000}")) { try { string ln = ""; //фамилия BusinessEntityCollection fcontact = searchContact(contact_ID.ToString()); foreach (DynamicEntity cont1 in fcontact.BusinessEntities) { ln = cont1["lastname"].ToString(); if (cont1.Properties.Contains("ownerid")) { ownerID = (Owner)cont1["ownerid"]; } } logger.Info($"Нашли контакт {ln}. ownerid={ownerID.Value.ToString()}"); } catch (Exception ex) { logger.Error($"Ошибка: {ex.ToString()}"); } } if (contact.ownerid != new Guid("{00000000-0000-0000-0000-000000000000}")) { if (ownerID.Value != contact.ownerid) { TargetOwnedContact target = new TargetOwnedContact(); SecurityPrincipal assignee = new SecurityPrincipal(); assignee.Type = SecurityPrincipalType.User; assignee.PrincipalId = contact.ownerid; target.EntityId = contactid; AssignRequest assign = new AssignRequest(); assign.Assignee = assignee; assign.Target = target; AssignResponse res = (AssignResponse)crmService.Execute(assign); } } return(contactid.ToString()); } catch (SoapException ex) { logger.Error($"Ошибка: {ex.Detail.InnerText}"); return(ex.Detail.InnerText); } }