public void When_Assigned_User_As_Owner_OwningUser_Is_Set() { var context = new XrmFakedContext(); var user1 = new SystemUser { Id = Guid.NewGuid(), FirstName = "User1" }; var team1 = new Team { Id = Guid.NewGuid(), Name = "Team1" }; var account1 = new Account { Id = Guid.NewGuid(), Name = "Acc1" }; context.Initialize(new List <Entity> { user1, team1, account1 }); var executor = new AssignRequestExecutor(); AssignRequest req = new AssignRequest() { Target = account1.ToEntityReference(), Assignee = user1.ToEntityReference() }; executor.Execute(req, context); var acc_Fresh = context.GetOrganizationService().Retrieve(account1.LogicalName, account1.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true)); Assert.Equal(user1.Id, acc_Fresh.GetAttributeValue <EntityReference>("owninguser").Id); Assert.Null(acc_Fresh.GetAttributeValue <EntityReference>("owningteam")); }
public string AssignBook([FromBody] AssignRequest request) { if (request == null) { return("Assign request is null"); } if (!ModelState.IsValid) { return(string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage))); } if (!_bookService.IsValidBook(request.BookId)) { return("The requested book is not available in the library!"); } if (!_studentsService.IsValidStudent(request.StudentId)) { return("Invalid Student Id!"); } if (!_booksAssignServie.CanAssignBook(request.BookId)) { return("Book is already assigned!"); } if (_booksAssignServie.AssignBook(request.StudentId, request.BookId)) { return("Book assigned successfully"); } return("Book could not be assigned"); }
protected override void Execute(CodeActivityContext executionContext) { #region Boilerplate IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); var tracing = executionContext.GetExtension <ITracingService>(); #endregion var entityIdString = EntityId.Get(executionContext); Guid entityId = Guid.Empty; if (!Guid.TryParse(entityIdString, out entityId)) { Succeeded.Set(executionContext, false); ErrorMessage.Set(executionContext, $"Guid {entityIdString} is not a valid GUID."); return; } var teamName = TeamName.Get(executionContext); using (var ctx = new XrmServiceContext(service)) { var team = (from t in ctx.CreateQuery <Team>() where t.Name == teamName select t).FirstOrDefault(); if (team == null) { Succeeded.Set(executionContext, false); ErrorMessage.Set(executionContext, $"Team {teamName} not found."); return; } var logicalName = EntityName.Get(executionContext); var reference = (from r in ctx.CreateQuery(logicalName) where (Guid)r[$"{logicalName}id"] == entityId select r).FirstOrDefault(); if (reference == null) { Succeeded.Set(executionContext, false); ErrorMessage.Set(executionContext, $"Entity Reference with logical name {logicalName} and id {entityIdString} wasn't found."); return; } //Assign otherwise var assignRequest = new AssignRequest() { Assignee = team.ToEntityReference(), Target = reference.ToEntityReference() }; service.Execute(assignRequest); } Succeeded.Set(executionContext, true); }
public void AssignWorkflowsToUser(EntityCollection workflows, Guid userId) { if (workflows == null) { throw new ArgumentNullException(nameof(workflows)); } if (userId == Guid.Empty) { throw new ArgumentNullException(nameof(userId), $"(Can't assign workflows to user if {nameof(userId)} is an empty guid."); } for (var i = 0; i < workflows.Entities.Count; i++) { var assign = new AssignRequest(); try { assign.Assignee = new EntityReference("systemuser", userId); assign.Target = workflows.Entities[i].ToEntityReference(); Service.Execute(assign); Console.WriteLine($"Assigned workflow {(i + 1)} with ID: {assign.Target.Id} to user with ID: {userId.ToString()}"); } catch (Exception) { Console.WriteLine($"Error assigning workflow {(i + 1)} with ID: {assign.Target.Id} to user. Continuing."); } } }
protected void Execute(LocalPluginContext localContext) { //assign the parent to the record owning team. var target = (Entity)localContext.PluginExecutionContext.InputParameters["Target"]; localContext.TracingService.Trace($"target logical name {target.LogicalName}"); //find the "record owner team" team var q = new QueryExpression("team"); q.Criteria.AddCondition("name", ConditionOperator.Equal, "* RECORD OWNER TEAM *"); var team = localContext.OrganizationService.RetrieveMultiple(q).Entities.Single(); localContext.TracingService.Trace($"found team"); //assign the target record to the team var req = new AssignRequest(); req.Assignee = team.ToEntityReference(); req.Target = target.ToEntityReference(); localContext.TracingService.Trace($"assigning"); var resp = (AssignResponse)localContext.OrganizationService.Execute(req); }
public bool Assign() { if (Id == Guid.Empty) { throw new ArgumentException($"Assign can only be called on entities with id, the entity is {entityName}"); } string ownerEntityName = GetOwnerEntityName(); ownerid.LogicalName = ownerEntityName; AssignRequest assignRequest = new AssignRequest() { Assignee = ownerid, Target = GetAsEntityReference(), }; try { Connection.Service.Execute(assignRequest); } catch (System.ServiceModel.FaultException <OrganizationServiceFault> ) { return(false); } return(true); }
protected void PostCreateExecution(IServiceProvider serviceProvider) { // Use a 'using' statement to dispose of the service context properly // To use a specific early bound entity replace the 'Entity' below with the appropriate class type using (var localContext = new LocalPluginContext <Entity>(serviceProvider)) { var targetEntity = (Entity)localContext.PluginExecutionContext.InputParameters["Target"]; var postImage = (Entity)localContext.PluginExecutionContext.PostEntityImages["PostImage"]; if (postImage.Contains("parentcustomerid") && postImage["parentcustomerid"] != null) { var owningAccountId = ((EntityReference)postImage["parentcustomerid"]).Id; var account = localContext.OrganizationService.Retrieve(ProxyClasses.Account.LogicalName, owningAccountId, new ColumnSet(new string[] { "ownerid" })); var assignRequest = new AssignRequest { Assignee = (EntityReference)account["ownerid"], Target = targetEntity.ToEntityReference() }; // Execute the Request localContext.OrganizationService.Execute(assignRequest); } } }
public void TestCascadeAssignParentToChildAndParent() { using (var context = new Xrm(orgAdminUIService)) { var fetchedAccount1 = context.AccountSet.FirstOrDefault(x => x.Id == acc1.Id); Assert.AreEqual(crm.AdminUser.Id, fetchedAccount1.OwnerId.Id); var fetchedAccount2 = context.AccountSet.FirstOrDefault(x => x.Id == acc2.Id); Assert.AreEqual(crm.AdminUser.Id, fetchedAccount2.OwnerId.Id); var fetchedContact = context.ContactSet.FirstOrDefault(x => x.Id == contact.Id); Assert.AreEqual(crm.AdminUser.Id, fetchedContact.OwnerId.Id); } var req = new AssignRequest() { Assignee = user1.ToEntityReference(), Target = acc2.ToEntityReference() }; orgAdminUIService.Execute(req); using (var context = new Xrm(orgAdminUIService)) { var fetchedAccount1 = context.AccountSet.FirstOrDefault(x => x.Id == acc1.Id); Assert.AreEqual(crm.AdminUser.Id, fetchedAccount1.OwnerId.Id); var fetchedAccount2 = context.AccountSet.FirstOrDefault(x => x.Id == acc2.Id); Assert.AreEqual(user1.Id, fetchedAccount2.OwnerId.Id); var fetchedContact = context.ContactSet.FirstOrDefault(x => x.Id == contact.Id); Assert.AreEqual(user1.Id, fetchedContact.OwnerId.Id); } }
public void When_Executing_Assign_Request_New_Owner_Should_Be_Assigned() { var oldOwner = new EntityReference("systemuser", Guid.NewGuid()); var newOwner = new EntityReference("systemuser", Guid.NewGuid()); var account = new Account { Id = Guid.NewGuid(), OwnerId = oldOwner }; var context = new XrmFakedContext(); var service = context.GetOrganizationService(); context.Initialize(new [] { account }); var assignRequest = new AssignRequest { Target = account.ToEntityReference(), Assignee = newOwner }; service.Execute(assignRequest); //retrieve account updated var updatedAccount = context.CreateQuery <Account>().FirstOrDefault(); Assert.Equal(newOwner.Id, updatedAccount.OwnerId.Id); }
protected void Execute(Context context, EntityReference ownerRef) { var fetchXml = FetchXml.Get(context); var entities = context.Service.RetrieveMultiple(fetchXml).Entities; var affectedEntities = 0; foreach (var entity in entities) { try { var request = new AssignRequest { Assignee = ownerRef, Target = entity.ToEntityReference() }; context.Service.Execute(request); affectedEntities++; } catch (Exception ex) { context.TracingService.Trace(ex); } } if (affectedEntities == 0) { SetError(context, "В процессе назначения записей произошли ошибки. Ни одна запись не назначена."); } else if (affectedEntities < entities.Count) { SetError(context, $"В процессе назначения записей произошли ошибки. Записей назначено: {affectedEntities}, записей не назначено: {entities.Count - affectedEntities}."); } AffectedEntities.Set(context, affectedEntities); }
public async Task AssignCategoryAsync(AssignRequest assignRequest) { switch (assignRequest.CategoryType) { case Project.LanguageCategory: var language = await context.Languages.FirstOrDefaultAsync(l => l.Name == assignRequest.Name); if (language == null) { language = new Language { Name = assignRequest.Name }; context.Languages.Add(language); await context.SaveChangesAsync(); } var lc = new ProjectLanguage { ProjectId = assignRequest.ProjectId, LanguageId = language.Id }; context.ProjectLanguages.Add(lc); await context.SaveChangesAsync(); break; default: break; } }
public void TestAssignSecurityTeam() { using (var context = new Xrm(orgAdminUIService)) { var businessunit = new BusinessUnit(); businessunit["name"] = "business unit name 3"; businessunit.Id = orgAdminUIService.Create(businessunit); var orgUser = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.SystemAdministrator); var service = crm.CreateOrganizationService(orgUser.Id); var contact = new Contact(); contact.Id = service.Create(contact); var team = crm.CreateTeam(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.Cannotreadcontact); FaultException faultException = null; var req = new AssignRequest(); try { req.Assignee = team.ToEntityReference(); req.Target = contact.ToEntityReference(); service.Execute(req); Assert.Fail(); } catch (FaultException e) { faultException = e; } var teamAdmin = crm.CreateTeam(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.SystemAdministrator); var adminContact = new Contact(); adminContact.Id = service.Create(adminContact); req.Assignee = teamAdmin.ToEntityReference(); req.Target = adminContact.ToEntityReference(); service.Execute(req); } }
public void When_execute_is_called_with_a_null_target_exception_is_thrown() { var context = new XrmFakedContext(); var executor = new AssignRequestExecutor(); AssignRequest req = new AssignRequest() { Target = null }; Assert.Throws<FaultException<OrganizationServiceFault>>(() => executor.Execute(req, context)); }
public void TestAssignSecurityUser() { using (var context = new Xrm(orgAdminUIService)) { var businessunit = new BusinessUnit(); businessunit["name"] = "business unit name 2"; businessunit.Id = orgAdminUIService.Create(businessunit); var orgUser = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.SystemAdministrator); var service = crm.CreateOrganizationService(orgUser.Id); var contact = new Contact(); contact.Id = service.Create(contact); var user = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.Scheduler); service = crm.CreateOrganizationService(user.Id); var req = new AssignRequest(); try { req.Assignee = user.ToEntityReference(); req.Target = contact.ToEntityReference(); service.Execute(req); throw new XunitException(); } catch (Exception e) { Assert.IsType <FaultException>(e); } var usersContact = new Contact(); usersContact.Id = service.Create(usersContact); req.Assignee = orgUser.ToEntityReference(); req.Target = usersContact.ToEntityReference(); service.Execute(req); } }
public void When_Executing_Assign_Request_New_Owner_Should_Be_Assigned() { var oldOwner = new EntityReference("systemuser", Guid.NewGuid()); var newOwner = new EntityReference("systemuser", Guid.NewGuid()); var account = new Account { Id = Guid.NewGuid(), OwnerId = oldOwner }; var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); context.Initialize(new [] { account }); var assignRequest = new AssignRequest { Target = account.ToEntityReference(), Assignee = newOwner }; service.Execute(assignRequest); Assert.Equal(newOwner, account.OwnerId); }
public AssignResponse AssignUser(EntityReference entityId, EntityReference ownerId) { AssignRequest req = new AssignRequest(); req.Assignee = ownerId; req.Target = entityId; return((AssignResponse)this.Service.Execute(req)); }
public async Task Then_Maps_StartMonthYear( AssignRequest request, AssignViewModelMapper mapper) { var viewModel = await mapper.Map(request); viewModel.StartMonthYear.Should().Be(request.StartMonthYear); }
public async Task Then_Maps_EmployerAccountLegalEntityPublicHashedId( AssignRequest request, AssignViewModelMapper mapper) { var viewModel = await mapper.Map(request); viewModel.AccountLegalEntityHashedId.Should().Be(request.AccountLegalEntityHashedId); }
public async Task Then_Maps_TransferSenderId( AssignRequest request, AssignViewModelMapper mapper) { var viewModel = await mapper.Map(request); viewModel.TransferSenderId.Should().Be(request.TransferSenderId); }
public async Task Then_Maps_UkPrn( AssignRequest request, AssignViewModelMapper mapper) { var viewModel = await mapper.Map(request); viewModel.ProviderId.Should().Be(request.ProviderId); }
public async Task Then_Maps_CourseCode( AssignRequest request, AssignViewModelMapper mapper) { var viewModel = await mapper.Map(request); viewModel.CourseCode.Should().Be(request.CourseCode); }
public static void Assign(this IOrganizationService service, EntityReference target, EntityReference assignee) { var req = new AssignRequest(); req.Assignee = assignee; req.Target = target; service.Execute(req); }
public async Task Then_Maps_ReservationId( AssignRequest request, AssignViewModelMapper mapper) { var viewModel = await mapper.Map(request); viewModel.ReservationId.Should().Be(request.ReservationId); }
public async Task Then_Maps_AccountHashedId( AssignRequest request, AssignViewModelMapper mapper) { var viewModel = await mapper.Map(request); viewModel.AccountHashedId.Should().Be(request.AccountHashedId); }
/// <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); }
internal override OrganizationResponse Execute(OrganizationRequest orgRequest, EntityReference userRef) { var request = MakeRequest <AssignRequest>(orgRequest); var casSelection = new CascadeSelection() { assign = true }; var dbEntity = core.GetDbEntityWithRelatedEntities(request.Target, EntityRole.Referenced, userRef, casSelection); security.CheckAssignPermission(dbEntity, request.Assignee, userRef); // Cascade foreach (var relatedEntities in dbEntity.RelatedEntities) { var relationshipMeta = metadata.EntityMetadata.GetMetadata(dbEntity.LogicalName).OneToManyRelationships.First(r => r.SchemaName == relatedEntities.Key.SchemaName); var req = new AssignRequest(); switch (relationshipMeta.CascadeConfiguration.Assign) { case CascadeType.Cascade: foreach (var relatedEntity in relatedEntities.Value.Entities) { req.Target = relatedEntity.ToEntityReference(); req.Assignee = request.Assignee; core.Execute(req, userRef, null); } break; case CascadeType.Active: foreach (var relatedEntity in relatedEntities.Value.Entities) { if (db.GetEntity(relatedEntity.ToEntityReference()).GetAttributeValue <OptionSetValue>("statecode")?.Value == 0) { req.Target = relatedEntity.ToEntityReference(); req.Assignee = request.Assignee; core.Execute(req, userRef, null); } } break; case CascadeType.UserOwned: foreach (var relatedEntity in relatedEntities.Value.Entities) { var currentOwner = dbEntity.Attributes["ownerid"] as EntityReference; if (db.GetEntity(relatedEntity.ToEntityReference()).GetAttributeValue <EntityReference>("ownerid")?.Id == currentOwner.Id) { req.Target = relatedEntity.ToEntityReference(); req.Assignee = request.Assignee; core.Execute(req, userRef, null); } } break; } } Utility.SetOwner(db, security, metadata, dbEntity, request.Assignee); Utility.Touch(dbEntity, metadata.EntityMetadata.GetMetadata(dbEntity.LogicalName), core.TimeOffset, userRef); db.Update(dbEntity); return(new AssignResponse()); }
public void UpdateStatus(ServiceRequest serviceRequest) { var idOfUpdatedItem = serviceRequest.SRID; //Login and connect to the server and create the context var connection = ConnectToDatabase(); var service = new OrganizationService(connection); var context = new CrmOrganizationServiceContext(connection); //Gather the components for the "Retrieve" function ColumnSet set = new ColumnSet(); set.AllColumns = true; Guid incidentGuid = GetGUIDByName(idOfUpdatedItem, service); //Retrieves the record that will be updated var incident = service.Retrieve("incident", incidentGuid, set); EventLog.saveMessage("Update Status of SRID:" + serviceRequest.SRID); try { // Actual UPDATE of the record. incident["description"] = serviceRequest.LongDescription; incident["statuscode"] = ReturnStatusCode(serviceRequest.ServiceRequestStatus); incident["subjectid"] = ReturnRequestType(serviceRequest.ServiceRequestType); incident["new_moduleoptionset"] = ReturnModuleCode("TS"); //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson,service)); incident["new_statushistory"] = serviceRequest.CommentsMatricia; incident["casetypecode"] = returnRequestKind(serviceRequest.ServiceRequestKind); incident["new_caseasignedto"] = serviceRequest.AssignedPerson; //incident["followupby"] = serviceRequest.DueDate; incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName; //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service)); incident["customerid"] = new EntityReference("account", findCustomerID(serviceRequest.companyName)); incident["new_statushistory"] = serviceRequest.ShortDescription; incident["new_assignedfrom"] = serviceRequest.CreatedBy; Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service); //Assign a case! service.Update(incident); EventLog.saveMessage("Start of Assignment! to :" + consultantID); AssignRequest assignRequest = new AssignRequest(); assignRequest.Assignee = new EntityReference("systemuser", consultantID); assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid); service.Execute(assignRequest); } catch (Exception) { EventLog.saveMessage("This record is unavailable for update right now!" + serviceRequest.SRID); return; } }
//ENDVERSIONCHECK public static AssignResponse Assign(this IOrganizationService service, EntityReference target, EntityReference owner) { var req = new AssignRequest() { Target = target, Assignee = owner }; return(service.Execute(req) as AssignResponse); }
public void AssignOwner(T entity, EntityReference owner) { var assignRequest = new AssignRequest() { Assignee = owner, Target = entity.ToEntityReference() }; service.Execute(assignRequest); }
public static void SetOwnerOfEntity(IOrganizationService service, string entityName, Guid entityId, string assigneeEntity, Guid assigneeId) { AssignRequest assignRequest = new AssignRequest(); assignRequest.Assignee = new EntityReference(assigneeEntity, assigneeId); assignRequest.Target = new EntityReference(entityName, entityId); service.Execute(assignRequest); }
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}"); } }
public void PublishInCRM(ServiceRequest serviceRequest) { //Connects to the database and Logs the User In var connection = ConnectToDatabase(); var service = new OrganizationService(connection); var context = new CrmOrganizationServiceContext(connection); //const int hour = 60; EventLog.saveMessage("PublishIssue SRID:" + serviceRequest.SRID); //Creating the new Case Entity incident = new Entity("incident"); try { //Filling the Data for the new case incident["createdon"] = serviceRequest.RegistrationDate; incident["description"] = serviceRequest.LongDescription; incident["statuscode"] = ReturnStatusCode(serviceRequest.ServiceRequestStatus); incident["subjectid"] = ReturnRequestType(serviceRequest.ServiceRequestType); incident["new_moduleoptionset"] = ReturnModuleCode("TS"); //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson, service)); incident["new_caseasignedto"] = serviceRequest.AssignedPerson; incident["new_statushistory"] = serviceRequest.CommentsMatricia; incident["casetypecode"] = returnRequestKind(serviceRequest.ServiceRequestKind); incident["followupby"] = serviceRequest.DueDate; incident["new_supportrequestid"] = serviceRequest.SRID; incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName; //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service)); incident["customerid"] = new EntityReference("account", findCustomerID(serviceRequest.companyName)); incident["new_statushistory"] = serviceRequest.ShortDescription; incident["new_assignedfrom"] = serviceRequest.CreatedBy; Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service); //Adding the created case to CRM; var incidentGuid = service.Create(incident); //Assign a case! EventLog.saveMessage("Start of Assignment! to :" + consultantID); AssignRequest assignRequest = new AssignRequest(); assignRequest.Assignee = new EntityReference("systemuser", consultantID); assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid); service.Execute(assignRequest); } catch (Exception) { EventLog.saveMessage("This case was not created in CRM " + serviceRequest.CreatedBy + "'" + serviceRequest.SRID); ; } }
/// <summary> /// This method first connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetBasicContextExamples1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery<SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery<UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery<UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery<Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Assigns the record. /// </summary> /// <param name="crmService">The CRM service.</param> /// <param name="owner">The owner.</param> /// <param name="entityName">Name of the entity.</param> /// <param name="id">The identifier.</param> public static void TryAssignRecord(IOrganizationService crmService, EntityReference owner, string entityName, Guid id) { try { "setting ownership for record with id {0}".Trace(id); var assignRequest = new AssignRequest { Assignee = owner, Target = new EntityReference(entityName, id) }; crmService.Execute(assignRequest); "ownership of the record with {0} successfully assigned.".Trace(id); } catch (FaultException<OrganizationServiceFault> orgFaultException) { orgFaultException.Message.TraceError(orgFaultException); } }
private AssignResponse ExecuteInternal(AssignRequest request) { InvokeStaticGenericMethod(request.Target.LogicalName, "Assign", this, request.Target, request.Assignee); return new AssignResponse(); }
public void Assign(Entity entity, Guid userId) { var request = new AssignRequest { Assignee = CreateLookup("systemuser", userId), Target = CreateLookup(entity) }; Execute(request); }
/// <summary> /// This method first retrieves the lead. Afterwards, it checks the value of /// the new_autoroute field, and if it is True, it retrieves all the users /// with 'Customer Service Representative' role, and assigns this lead to /// the user with the fewest lead records assigned. /// </summary> protected override void Execute(CodeActivityContext executionContext) { IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); #region Retrieve the lead // Get the lead ID Guid leadId = this.lead_input.Get(executionContext).Id; //Request for Entity RetrieveRequest request = new RetrieveRequest(); request.ColumnSet = new ColumnSet(true); request.Target = new EntityReference("lead", leadId); //Execute request Entity targetRequest = (Entity)((RetrieveResponse)service.Execute(request)).Entity; #endregion Retrieve the lead bool autoroute = false; autoroute = (bool)targetRequest.Attributes["new_autoroute"]; if (autoroute) { // Get user's BusinessUnit RetrieveRequest userrequest = new RetrieveRequest(); userrequest.ColumnSet = new ColumnSet("businessunitid"); userrequest.Target = new EntityReference("systemuser", context.UserId); Entity userEntity = (Entity)((RetrieveResponse)service.Execute(userrequest)).Entity; EntityReference bu = (EntityReference)userEntity["businessunitid"]; // Get roleid for 'Customer Service Representative' with that BU QueryExpression queryRole = new QueryExpression(); queryRole.ColumnSet = new ColumnSet("roleid"); queryRole.EntityName = "role"; queryRole.Criteria.AddCondition(new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { "Customer Service Representative" } }); queryRole.Criteria.AddCondition(new ConditionExpression { AttributeName = "businessunitid", Operator = ConditionOperator.Equal, Values = { bu.Id } }); var roles = service.RetrieveMultiple(queryRole); if (roles.Entities.Count > 0) { Guid roleId = (Guid)roles.Entities[0]["roleid"]; // Create the query to get all the users with that role QueryExpression queryUsers = new QueryExpression(); // Set the properties of the query. queryUsers.EntityName = "systemuserroles"; queryUsers.ColumnSet = new ColumnSet("systemuserid"); queryUsers.Criteria.AddCondition ("roleid", ConditionOperator.Equal, roleId); // Get the list of users. var users = service.RetrieveMultiple(queryUsers); if (users.Entities.Count > 0) { #region Get User with lowest number of leads assigned // Initialize variables int lowLeadCount = -1; int currentLeadCount = 0; Guid lowUserId = new Guid(); // Create the query to find out how many leads // each retrieved user has QueryExpression queryUsersLeads = new QueryExpression(); // Set the properties of the query. queryUsersLeads.EntityName = "lead"; queryUsersLeads.ColumnSet = new ColumnSet("leadid", "ownerid"); foreach (var user in users.Entities) { queryUsersLeads.Criteria.AddCondition ("ownerid", ConditionOperator.Equal, user["systemuserid"]); EntityCollection currentUserLeads = service.RetrieveMultiple(queryUsersLeads); currentLeadCount = currentUserLeads.Entities.Count; // If is the first time or the number of leads is lowest, // the current User is marked lowest. if ((lowLeadCount == -1) || (currentLeadCount < lowLeadCount)) { lowLeadCount = currentLeadCount; lowUserId = (Guid)user["systemuserid"]; } } #endregion Get User with Lowest Number of leads assigned #region Assign new lead to identified user // Assign the lead to the user // with the fewest lead records assigned AssignRequest assignRequest = new AssignRequest() { Target = new EntityReference("lead", leadId), Assignee = new EntityReference("systemuser", lowUserId) }; service.Execute(assignRequest); #endregion Assign new lead to identified user } } } }
/// <summary> /// Create and configure the organization service proxy. /// Retrieves new owner's details and creates an account record. /// Assign the account to new owner. /// Optionally delete any entity records that were created for this sample. // </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetAssign1> // Create the Request Object and Set the Request Object's Properties AssignRequest assign = new AssignRequest { Assignee = new EntityReference(SystemUser.EntityLogicalName, _otherUserId), Target = new EntityReference(Account.EntityLogicalName, _accountId) }; // Execute the Request _service.Execute(assign); //</snippetAssign1> Console.WriteLine("The account is owned by new owner."); DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
public void UpdateAssignedPerson(ServiceRequest serviceRequest) { var idOfUpdatedItem = serviceRequest.SRID; var connection = ConnectToDatabase(); var service = new OrganizationService(connection); var context = new CrmOrganizationServiceContext(connection); Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service); ColumnSet set = new ColumnSet(); set.AllColumns = true; //Gather the components for the "Retrieve" function Guid incidentGuid = GetGUIDByName(idOfUpdatedItem, service); //Retrieves the record that will be updated var incident = service.Retrieve("incident", incidentGuid, set); EventLog.saveMessage("Updating the consultant person of case: " + serviceRequest.SRID + "to " + serviceRequest.AssignedPerson); try { //Assign a case! AssignRequest assignRequest = new AssignRequest(); assignRequest.Assignee = new EntityReference("systemuser", consultantID); assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid); //sets the new User. //incident["ownerid"] = new EntityReference("systemuser", consultantID); service.Update(incident); service.Execute(assignRequest); } catch (Exception) { EventLog.saveMessage("Updating the consultant person of case: " + serviceRequest.SRID + "to " + serviceRequest.AssignedPerson + " failed!"); return; } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// a user dashbaord is assigned to another user. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetAssignDashboardToUser1> AssignRequest assignRequest = new AssignRequest { Assignee = new EntityReference { LogicalName = SystemUser.EntityLogicalName, // Here we could assign the visualization to the newly created user Id = _otherUserId }, Target = new EntityReference { LogicalName = UserForm.EntityLogicalName, Id = _userDashboardId } }; _serviceProxy.Execute(assignRequest); Console.WriteLine("The user dashboard has been assigned to Kevin Cook."); //</snippetAssignDashboardToUser1> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }