public void SetActive(bool isActive) { SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = Id, LogicalName = entityName, }, //State = new OptionSetValue(1), //Status = new OptionSetValue(2), }; if (isActive == true) { setStateRequest.State = new OptionSetValue((int)StateEnum.Active); setStateRequest.Status = new OptionSetValue((int)StatusEnum.Active); } else { setStateRequest.State = new OptionSetValue((int)StateEnum.Inactive); setStateRequest.Status = new OptionSetValue((int)StatusEnum.Inactive); } Connection.Service.Execute(setStateRequest); }
private static Entity CreateInvoiceFromOrder(OrganizationServiceContext context, Guid salesOrderId) { ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); var convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = salesOrderId, ColumnSet = invoiceColumns }; var convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)context.Execute(convertOrderRequest); var invoice = convertOrderResponse.Entity; var setStateRequest = new SetStateRequest() { EntityMoniker = invoice.ToEntityReference(), State = new OptionSetValue(2), Status = new OptionSetValue(100001) }; var setStateResponse = (SetStateResponse)context.Execute(setStateRequest); invoice = context.CreateQuery("invoice").Where(i => i.GetAttributeValue <Guid>("invoiceid") == convertOrderResponse.Entity.Id).FirstOrDefault(); return(invoice); }
/// <summary> /// Deletes the custom entity record that was created for this sample. /// <param name="prompt">Indicates whether to prompt the user /// to delete the entity created in this sample.</param> /// </summary> public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt) { bool deleteRecords = true; if (prompt) { Console.WriteLine("\nDo you want the system user record enabled? (y/n)"); String answer = Console.ReadLine(); deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); } if (deleteRecords) { SetStateRequest request = new SetStateRequest() { EntityMoniker = new EntityReference(SystemUser.EntityLogicalName, _userId), //sets the user to enabled State = new OptionSetValue(0), // required by request but always valued at -1 in this context Status = new OptionSetValue(-1) }; service.Execute(request); Console.WriteLine("System user has been enabled."); } }
internal void DeactivateTask(string requestId, string taskId, IOrganizationService service) { try { QueryExpression query = new QueryExpression("pp_signicatdocurl"); query.ColumnSet = new ColumnSet(false); query.Criteria.AddCondition("new_name", ConditionOperator.Equal, taskId); query.Criteria.AddCondition("pp_sdsurl", ConditionOperator.Contains, requestId); var result = service.RetrieveMultiple(query); if (result.Entities.Count == 1) { var task = result.Entities[0].ToEntityReference(); SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = task.Id, LogicalName = task.LogicalName, }, State = new OptionSetValue(1), Status = new OptionSetValue(2) }; service.Execute(setStateRequest); } } catch (Exception ex) { throw new Exception(ex.Message); } }
public void PerformTestSetup() { MessageName = "Close"; var quoteEntity = EntityFactory.CreateQuote(); var quoteClose = new Entity("quoteclose"); quoteClose["subject"] = "DummyQuoteClose"; quoteClose["quoteid"] = quoteEntity.ToEntityReference(); var setStateRequest = new SetStateRequest { EntityMoniker = quoteEntity.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(2) }; OrganizationService.Execute(setStateRequest); CloseQuoteRequest = new CloseQuoteRequest { QuoteClose = quoteClose, Status = new OptionSetValue(5), }; }
public void When_set_state_request_is_called_an_entity_is_updated() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var service = context.GetFakedOrganizationService(); var c = new Contact() { Id = Guid.NewGuid() }; context.Initialize(new[] { c }); var request = new SetStateRequest { EntityMoniker = c.ToEntityReference(), State = new OptionSetValue(69), Status = new OptionSetValue(6969), }; var response = service.Execute(request); //Retrieve record after update var contact = (from con in context.CreateQuery <Contact>() where con.Id == c.Id select con).FirstOrDefault(); Assert.Equal((int)contact.StateCode.Value, 69); Assert.Equal((int)contact.StatusCode.Value, 6969); }
private SetStateRequest GerarRequestInativacao(Entity entity, int status) { int stateCode; if (status == 0) { //Ativar stateCode = 0; status = 1; } else { //Inativar stateCode = 1; status = 2; } SetStateRequest state = new SetStateRequest(); state.State = new OptionSetValue(stateCode); state.Status = new OptionSetValue(status); state.EntityMoniker = new EntityReference(entity.LogicalName, entity.Id); return(state); }
public void updateAllProductToActive() { IOrganizationService service = CRMHelper.ConnectToMSCRM(); QueryExpression query = new QueryExpression("product"); query.ColumnSet = new ColumnSet(new string[] { "name" }); query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 2); query.Criteria.AddCondition("createdon", ConditionOperator.Yesterday); EntityCollection productentityList = service.RetrieveMultiple(query); Console.WriteLine("Total Product to be Procceed are : " + productentityList.Entities.Count); int counter = 0; foreach (Entity Item in productentityList.Entities) { SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = new EntityReference(Item.LogicalName, Item.Id), State = new OptionSetValue(0), Status = new OptionSetValue(1) }; service.Execute(publishRequest); counter++; if (counter % 100 == 0) { Console.WriteLine("Total Product Updated are : " + counter); } } }
protected override void Execute(CodeActivityContext context) { IWorkflowContext workFlowContext = context.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory factory = context.GetExtension <IOrganizationServiceFactory>(); _crmService = factory.CreateOrganizationService(null); Guid contractId = workFlowContext.PrimaryEntityId; RenewContractRequest contractReq = new RenewContractRequest(); contractReq.ContractId = contractId; contractReq.IncludeCanceledLines = false; contractReq.Status = 1; RenewContractResponse contractResp = (RenewContractResponse)_crmService.Execute(contractReq); if (contractResp != null) { Entity contract = contractResp.Entity; if (contract.Contains(CrmFields.UpdateContractLine)) { Boolean updateContractAfterRenewal = contract.GetAttributeValue <bool>(CrmFields.UpdateContractLine); if (updateContractAfterRenewal != true) { SetStateRequest req = new SetStateRequest(); req.EntityMoniker = contract.ToEntityReference(); req.State = new OptionSetValue(1); req.Status = new OptionSetValue(2); _crmService.Execute(req); } } } }
/// <summary> /// Deletes the custom entity record that was created for this sample. /// <param name="prompt">Indicates whether to prompt the user /// to delete the entity created in this sample.</param> /// </summary> public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt) { bool deleteRecords = true; if (prompt) { Console.WriteLine("\nDo you want these entity records deleted? (y/n)"); String answer = Console.ReadLine(); deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); } if (deleteRecords) { // Deactivate, and then delete the workflow. SetStateRequest deactivateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue((int)workflow_statuscode.Draft) }; service.Execute(deactivateRequest); service.Delete(Workflow.EntityLogicalName, _workflowId); Console.WriteLine("The workflow has been deactivated, and deleted."); } }
/// <summary> /// Sets the state. /// </summary> /// <param name="state">The state.</param> /// <param name="status">The status.</param> /// <param name="entityId">The entity identifier.</param> /// <param name="entityType">Type of the entity.</param> /// <returns>Result.</returns> public Result SetState(int state, int status, Guid entityId, string entityType) { try { logSystem.CreateLog("SetState Rrequest: Type: " + entityType + ", ID : " + entityId + ", State :" + state + ", Status :" + status , System.Diagnostics.EventLogEntryType.Information); // Create the Request Object SetStateRequest stateRequest = new SetStateRequest(); // Set the Request Object's Properties stateRequest.State = new OptionSetValue(state); stateRequest.Status = new OptionSetValue(status); // Point the Request to the case whose state is being changed stateRequest.EntityMoniker = new EntityReference(entityType, entityId); // Execute the Request SetStateResponse stateSet = (SetStateResponse)xrmService.Execute(stateRequest); return(Execute <SetStateRequest, SetStateResponse>(stateRequest)); } catch (Exception ex) { return(new Result(true, MethodBase.GetCurrentMethod().ToString() + " : " + ExceptionHandler.HandleException(ex), null, logSystem)); } }
private bool FindAndDeactivateEntity(DateTime date) { using (var orgContext = new OrganizationServiceContext(this.service)) { var currencyFromCrm = (from i in orgContext.CreateQuery <new_exchangerates>() where i.new_date < date && i.statecode == new_exchangeratesState.Active select i).ToList(); if (currencyFromCrm.Count == 0) { return(false); } // деактивация устаревших курсов State = Close foreach (var item in currencyFromCrm) { SetStateRequest deactivateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(new_exchangerates.EntityLogicalName, item.Id), State = new OptionSetValue(1), Status = new OptionSetValue(-1) }; orgContext.Execute(deactivateRequest); } return(true); } }
/// <summary> /// Deletes any entity records that were created for this sample. /// <param name="prompt">Indicates whether to prompt the user /// to delete the records created in this sample.</param> /// </summary> public void DeleteRequiredRecords(bool prompt) { bool toBeDeleted = true; if (prompt) { // Ask the user if the created entities should be deleted. Console.Write("\nDo you want these entity records deleted? (y/n) [y]: "); String answer = Console.ReadLine(); if (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty) { toBeDeleted = true; } else { toBeDeleted = false; } } if (toBeDeleted) { // Deactivate and delete workflow SetStateRequest deactivateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue((int)workflow_statuscode.Draft) }; _serviceProxy.Execute(deactivateRequest); _serviceProxy.Delete(Workflow.EntityLogicalName, _workflowId); Console.WriteLine("Workflow has been deactivated and deleted."); } }
/// <summary> /// Deletes any entity records that were created for this sample. /// <param name="prompt">Indicates whether to prompt the user /// to delete the records created in this sample.</param> /// </summary> public void DeleteRequiredRecords(bool prompt) { bool deleteRecords = true; if (prompt) { Console.WriteLine("\nDo you want these entity records deleted? (y/n) [y]: "); String answer = Console.ReadLine(); deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty); } if (deleteRecords) { // Deactivate the dialog, and then delete it. SetStateRequest deactivateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _dialogId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue(1), }; _serviceProxy.Execute(deactivateRequest); _serviceProxy.Delete(Workflow.EntityLogicalName, _dialogId); Console.WriteLine("Entity records have been deleted."); } }
public Boolean AlterarStatus(Guid itbc_mensagemid, int status) { int stateCode; if (status == 0) { //Ativar stateCode = 0; status = 1; } else { //Inativar stateCode = 1; status = 2; } SetStateRequest request = new SetStateRequest { EntityMoniker = new EntityReference("itbc_mensagem", itbc_mensagemid), State = new OptionSetValue(stateCode), Status = new OptionSetValue(status) }; SetStateResponse resp = (SetStateResponse)this.Execute(request); if (resp != null) { return(true); } return(false); }
/// <summary> /// Deletes/reverts any entity records that were created for this sample. /// <param name="prompt">Indicates whether to prompt the user /// to delete/revert the records created in this sample.</param> /// </summary> public void DeleteRequiredRecords(bool prompt) { bool deleteRecords = true; if (prompt) { Console.Write("\nDo you want these entity records deleted/reverted? (y/n) [y]: "); String answer = Console.ReadLine(); deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty); } if (deleteRecords) { SetStateRequest request = new SetStateRequest() { EntityMoniker = new EntityReference(SystemUser.EntityLogicalName, _userId), //sets the user to enabled State = new OptionSetValue(0), // required by request but always valued at -1 in this context Status = new OptionSetValue(-1) }; _serviceProxy.Execute(request); Console.WriteLine("User account is enabled back again."); } }
private static void SetState(CrmServiceClient service, EntityReference caseReference) { // Create the Request Object var state = new SetStateRequest(); // Set the Request Object's Properties state.State = new OptionSetValue((int)IncidentState.Active); state.Status = new OptionSetValue((int)incident_statuscode.WaitingforDetails); // Point the Request to the case whose state is being changed state.EntityMoniker = caseReference; // Execute the Request var stateSet = (SetStateResponse)service.Execute(state); // Check if the state was successfully set Incident incident = service.Retrieve(Incident.EntityLogicalName, _caseIncidentId, new ColumnSet(allColumns: true)).ToEntity <Incident>(); if (incident.StatusCode.Value == (int)incident_statuscode.WaitingforDetails) { Console.WriteLine("Record state set successfully."); } else { Console.WriteLine("The request to set the record state failed."); } }
//Created By : Raphael Herrera, Created On : 1/11/2017 /*Purpose: Cancel Vehicle Adjustment record. Delete all adjusted vehicle details records. Set inventory record to available and adjust product quantity count for each adjusted vehicle records. * Registration Details: * Event/Message: * Pre-Validate/Delete: * Post/Update: gsc_adjustmentvariancestatus * Post/Create: * Primary Entity: Vehicle Adjustment/Variance Entry Detail */ public Entity CancelAdjustedVehicle(Entity vehicleAdjustmentEntity) { _tracingService.Trace("Started CancelAdjustedVehicle Method..."); EntityCollection adjustedDetailsCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_adjustmentvariancedetail", "gsc_vehicleadjustmentvarianceentryid", vehicleAdjustmentEntity.Id, _organizationService, null, OrderType.Ascending, "gsc_inventoryid", "gsc_quantity"); _tracingService.Trace("Adjusted Details Records retrieved: " + adjustedDetailsCollection.Entities.Count); if (adjustedDetailsCollection.Entities.Count > 0) { foreach (Entity adjustedDetails in adjustedDetailsCollection.Entities) { UnallocateVehicleAdjustment(adjustedDetails, vehicleAdjustmentEntity, "Cancel"); } } SetStateRequest request = new SetStateRequest { EntityMoniker = new EntityReference("gsc_sls_vehicleadjustmentvarianceentry", vehicleAdjustmentEntity.Id), State = new OptionSetValue(1), Status = new OptionSetValue(2) }; _organizationService.Execute(request); _tracingService.Trace("Started CancelAdjustedVehicle Method..."); return(vehicleAdjustmentEntity); }
private void UpdateSupplementalExpenses(List <Entity> supplementalExpenses) { //Update Expense Records with reference to payment record var stateCode = new OptionSetValue(); var statusCode = new OptionSetValue(); foreach (var expense in supplementalExpenses) { SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = expense.Id, LogicalName = "educ_exoense", }, State = new OptionSetValue(1), Status = new OptionSetValue(610410006) }; organizationService.Execute(setStateRequest); //If not suplemental, set statuscode to Suplemental Recorded //if (expense.GetAttributeValue<OptionSetValue>("educ_supplementalexpense").Value == 610410000) // expense["statuscode"] = new OptionSetValue(610410006); //organizationService.Update(expense); } }
private bool FindAndDeactivateEntity(DateTime date) { using (var orgContext = new OrganizationServiceContext(this.service)) { var currencyFromCrm = (from i in orgContext.CreateQuery <sl_ExchangeRate>() where i.sl_RelevanceDate < date.ToUniversalTime().AddHours(_ToCrmUTCDate) && i.statecode == sl_ExchangeRateState.Active select i).ToList(); if (currencyFromCrm.Count == 0) { return(true); } // деактивация устаревших курсов State = Close foreach (var item in currencyFromCrm) { SetStateRequest deactivateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(sl_ExchangeRate.EntityLogicalName, item.Id), State = new OptionSetValue(1), Status = new OptionSetValue(-1) }; orgContext.Execute(deactivateRequest); } return(true); } }
public Entity CreateContract() { var contactEntity = CreateContact(); var entity = new Entity("contract") { Id = Guid.NewGuid() }; entity["title"] = "DummyContract"; entity["contracttemplateid"] = crmReader.GetContractTemplateId(); entity["billingcustomerid"] = contactEntity.ToEntityReference(); entity["customerid"] = contactEntity.ToEntityReference(); entity["billingstarton"] = DateTime.Now; entity["billingendon"] = DateTime.Now.AddYears(1); entity["activeon"] = DateTime.Now; entity["expireson"] = DateTime.Now.AddYears(1); organizationService.Create(entity); CreateContractLine(entity.ToEntityReference()); var setStateRequest = new SetStateRequest { EntityMoniker = entity.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(2) }; organizationService.Execute(setStateRequest); return(entity); }
/// <summary> /// Deletes the custom entity record that was created for this sample. /// <param name="prompt">Indicates whether to prompt the user /// to delete the entity created in this sample.</param> /// </summary> public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt) { bool deleteRecords = true; if (prompt) { Console.WriteLine("\nDo you want these entity records deleted? (y/n)"); String answer = Console.ReadLine(); deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y")); } if (deleteRecords) { SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue(1) }; service.Execute(setStateRequest); service.Delete(Workflow.EntityLogicalName, _workflowId); service.Delete(Lead.EntityLogicalName, _leadId); service.Delete(AsyncOperation.EntityLogicalName, _asyncOperationId); Console.WriteLine("Entity records have been deleted."); } }
public Boolean AlterarSituacao(Guid ArquivoDeSelloutId, int status) { int stateCode; if (status == 0) { //Ativar stateCode = 0; status = 1; } else { //Inativar stateCode = 1; status = 2; } SetStateRequest request = new SetStateRequest { EntityMoniker = new EntityReference("itbc_arquivodesellout", ArquivoDeSelloutId), State = new OptionSetValue(stateCode), Status = new OptionSetValue(status) }; SetStateResponse resp = (SetStateResponse)this.Execute(request); if (resp != null) { return(true); } return(false); }
public void UpdateEntityState(IEnumerable <EditableGridModel> records) { ExecuteMultipleRequest requestWithoutResults = XrmMultipleRequestHelper.CreateRequest(); foreach (EditableGridModel item in records) { SetStateRequest request = new SetStateRequest { EntityMoniker = new EntityReference(item.Entity, item.Id), // Sets the record to disabled. State = new OptionSetValue(0), // Required by request but always valued at -1 in this context. Status = new OptionSetValue(-1) }; if (item.Records.FirstOrDefault().Value == "disable") { request.State = new OptionSetValue(1); } request.Status = new OptionSetValue(-1); _service.ServiceContext.Execute(request); } }
public Boolean AlterarStatus(Guid acessoKonvivaId, int status) { int stateCode; if (status == (int)Domain.Enum.AcessoKonviva.StateCode.Ativo) { //Ativar stateCode = (int)Domain.Enum.AcessoKonviva.StateCode.Ativo; status = (int)Domain.Enum.AcessoKonviva.StatusCode.Ativo; } else { //Inativar stateCode = (int)Domain.Enum.AcessoKonviva.StateCode.Inativo; status = (int)Domain.Enum.AcessoKonviva.StatusCode.Inativo; } SetStateRequest request = new SetStateRequest { EntityMoniker = new EntityReference("itbc_acessoaokonviva", acessoKonvivaId), State = new OptionSetValue(stateCode), Status = new OptionSetValue(status) }; SetStateResponse resp = (SetStateResponse)this.Execute(request); if (resp != null) { return(true); } return(false); }
private void SetState(Entity target, RecordStateAndStatus sourceStateAndStatus, Entity currentStateAndStatusEntity = null) { // Don't update state when it's not available if (sourceStateAndStatus.State == null) { return; } if (currentStateAndStatusEntity != null) { var currentStateAndStatus = RemoveStateAndStatus(currentStateAndStatusEntity); // If the entity has no state: return if (currentStateAndStatus.State == null || (sourceStateAndStatus.State.Value == currentStateAndStatus.State.Value && sourceStateAndStatus.Status.Value == currentStateAndStatus.Status.Value)) { return; } } SetStateRequest setState = new SetStateRequest() { EntityMoniker = target.ToEntityReference(), State = sourceStateAndStatus.State, Status = sourceStateAndStatus.Status }; targetService.Execute(setState); }
public override void Execute() { EntityReference crmRecord = _crmContext.RecordCache[_alias]; SetStateRequest request = ObjectConverter.ToSetStateRequest(crmRecord, _statusCodeText, _crmContext); GlobalTestingContext.ConnectionManager.CurrentConnection.Execute <SetStateResponse>(request); }
private SetStateResponse ExecuteInternal(SetStateRequest request) { var entity = Service.Retrieve(request.EntityMoniker.LogicalName, request.EntityMoniker.Id, new ColumnSet()); var info = new LateBoundActivePropertyInfo(request.EntityMoniker.LogicalName); switch (info.ActiveAttribute) { case ActiveAttributeType.IsDisabled: entity["isdisabled"] = request.State.GetValueOrDefault() == 1; break; case ActiveAttributeType.None: case ActiveAttributeType.StateCode: entity["statecode"] = request.State; entity["statuscode"] = request.Status; break; default: throw new ArgumentOutOfRangeException(); } Service.Update(entity); return(new SetStateResponse()); }
public HttpResponseMessage Post(Guid taskId) { CrmConnection connection = CrmConnection.Parse(Strings.urlCreds); var ctx = new CrmServiceContext(new OrganizationService(connection)); var taskReference = new EntityReference("task", taskId); try { var req = new SetStateRequest(); req.State = new OptionSetValue(1); req.Status = new OptionSetValue(5); req.EntityMoniker = taskReference; var res = (SetStateResponse)ctx.Execute(req); } catch (Exception e) { return this.Request.CreateResponse( HttpStatusCode.InternalServerError, e); } return this.Request.CreateResponse( HttpStatusCode.Created); }
internal void DeactivateSignicatResults(IOrderedEnumerable <IGrouping <string, ResultObject> > groups, IOrganizationService service) { foreach (var group in groups) { var tempList = group.ToList(); if (tempList.Count > 1) { foreach (var resultObject in tempList) { SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = resultObject.Id, LogicalName = "pp_signicatresulturl", }, State = new OptionSetValue(1), Status = new OptionSetValue(2) }; service.Execute(setStateRequest); } } } }
public void When_set_state_request_is_called_an_entity_is_updated() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var service = context.GetFakedOrganizationService(); var c = new Contact() { Id = Guid.NewGuid() }; context.Initialize(new[] { c }); var request = new SetStateRequest { EntityMoniker = c.ToEntityReference(), State = new OptionSetValue(69), Status = new OptionSetValue(6969), }; var response = service.Execute(request); //Retrieve record after update var contact = (from con in context.CreateQuery<Contact>() where con.Id == c.Id select con).FirstOrDefault(); Assert.Equal((int) contact.StateCode.Value, 69); Assert.Equal((int) contact.StatusCode.Value, 6969); }
internal override OrganizationResponse Execute(OrganizationRequest orgRequest, EntityReference userRef) { var request = MakeRequest <MergeRequest>(orgRequest); var mainEntity = db.GetEntity(request.Target); var casSelection = new CascadeSelection() { merge = true }; var subordinateReference = new EntityReference { LogicalName = mainEntity.LogicalName, Id = request.SubordinateId }; var subordinateEntity = core.GetDbEntityWithRelatedEntities(subordinateReference, EntityRole.Referencing, userRef, casSelection); foreach (var attr in request.UpdateContent.Attributes) { if (attr.Value != null) { mainEntity[attr.Key] = attr.Value; } } foreach (var relatedEntities in subordinateEntity.RelatedEntities) { var relationshipMeta = metadata.EntityMetadata.GetMetadata(subordinateEntity.LogicalName).ManyToOneRelationships.First(r => r.SchemaName == relatedEntities.Key.SchemaName); if (relationshipMeta.CascadeConfiguration.Merge == CascadeType.Cascade) { var entitiesToSwap = relatedEntities.Value.Entities.Select(e => e.ToEntityReference()).ToList(); var disassocHandler = core.RequestHandlers.Find(x => x is DisassociateRequestHandler); disassocHandler.Execute(new DisassociateRequest { RelatedEntities = new EntityReferenceCollection(entitiesToSwap), Relationship = relatedEntities.Key, Target = subordinateEntity.ToEntityReference() }, userRef); var assocHandler = core.RequestHandlers.Find(x => x is AssociateRequestHandler); assocHandler.Execute(new AssociateRequest { RelatedEntities = new EntityReferenceCollection(entitiesToSwap), Relationship = relatedEntities.Key, Target = mainEntity.ToEntityReference() }, userRef); } } subordinateEntity["merged"] = true; db.Update(subordinateEntity); db.Update(mainEntity); var setStateHandler = core.RequestHandlers.Find(x => x is SetStateRequestHandler); var req = new SetStateRequest() { EntityMoniker = subordinateReference, State = new OptionSetValue(1), Status = new OptionSetValue(2) }; setStateHandler.Execute(req, userRef); return(new MergeResponse()); }
/// <summary> /// Деактиврует запись record /// </summary> /// <param name="xrmServiceContext"></param> /// <param name="record"></param> /// <returns></returns> public static SetStateResponse DeactivateEntityRecord(this XrmServiceContext xrmServiceContext, Entity record) { IOrganizationService service = xrmServiceContext; //State represents the field with schema name “state code” and display name “status”. //Suppose we are working on the account entity in which the state code field has to be 1 so that the record be inactive. //Status represents the field with schema name “Status code” and display name “Status Reason”. // set this value to -1 to let the system automatically set the appropriate corresponding status value. SetStateRequest setStateRequest = new SetStateRequest { EntityMoniker = new EntityReference(record.LogicalName, record.Id), State = new OptionSetValue(1), Status = new OptionSetValue(-1) }; // Execute the request var response = (SetStateResponse)service.Execute(setStateRequest); return response; }
private static bool? ChangeStateCode(Guid id) { var service = new OrganizationService(connection); SetStateRequest state = new SetStateRequest(); state.State = new OptionSetValue((int)TaskState.Completed); state.Status = new OptionSetValue(5); state.EntityMoniker = new EntityReference() { Id = id, LogicalName = SoftLine.Models.Task.EntityLogicalName }; SetStateResponse stateSet = (SetStateResponse)service.Execute(state); SoftLine.Models.Task task = service.Retrieve(SoftLine.Models.Task.EntityLogicalName, id, new ColumnSet("statecode")).ToEntity<SoftLine.Models.Task>(); if (task.StateCode == TaskState.Completed) { return true; } return null; }
public static MsCrmResult CloseFriendship(Guid friendshipId, IOrganizationService service) { MsCrmResult returnValue = new MsCrmResult(); try { SetStateRequest setStateReq = new SetStateRequest(); setStateReq.EntityMoniker = new EntityReference("new_friendship", friendshipId); setStateReq.State = new OptionSetValue(1); setStateReq.Status = new OptionSetValue(2); SetStateResponse response = (SetStateResponse)service.Execute(setStateReq); returnValue.Success = true; returnValue.Result = "M044"; //"Arkadaşlığınız iptal edilmiştir."; } catch (Exception ex) { returnValue.Success = false; returnValue.Result = ex.Message; } return returnValue; }
/// <summary> /// Активировать карточку /// </summary> /// <param name="organizationService"></param> /// <param name="record"></param> public static void ActivateRecord(this IOrganizationService organizationService, Entity record) { var cols = new ColumnSet("statecode", "statuscode"); //Check if it is Inactive or not var entity = organizationService.Retrieve(record.LogicalName, record.Id, cols); if (entity != null && entity.GetAttributeValue<OptionSetValue>("statecode").Value != 0) { //StateCode = 0 and StatusCode = 1 for activating Account or Contact SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = record.Id, LogicalName = record.LogicalName, }, State = new OptionSetValue(0), Status = new OptionSetValue(1) }; organizationService.Execute(setStateRequest); } }
private void DeactivateProductById(Guid Id) { var setStateProductRequest = new SetStateRequest { State = new OptionSetValue(1), Status = new OptionSetValue(2), EntityMoniker = new EntityReference(Product.EntityLogicalName, Id) }; _service.Execute(setStateProductRequest); }
/// <summary> /// This method first creates XAML to define the custom workflow. Afterwards, /// it creates the workflow record with this XAML and then activates it. Finally /// it checks if it is activated and, if so, deactivates it. /// </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(); CreateRequiredRecords(); // Activate the workflow. Console.WriteLine("\nActivating the workflow..."); //<snippetSetStateWorkflow1> var activateRequest = new SetStateRequest { EntityMoniker = new EntityReference (Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue((int)workflow_statuscode.Activated) }; _serviceProxy.Execute(activateRequest); //</snippetSetStateWorkflow1> // Verify that the workflow is activated. Workflow retrievedWorkflow = (Workflow)_serviceProxy.Retrieve("workflow", _workflowId, new ColumnSet("statecode", "name")); Console.WriteLine("The state of workflow {0} is: {1}.", retrievedWorkflow.Name, retrievedWorkflow.StateCode); // Deactivate the workflow. if (retrievedWorkflow.StateCode == WorkflowState.Activated) { Console.WriteLine("\nDeactivating the workflow..."); //<snippetSetStateWorkflow2> SetStateRequest deactivateRequest = new SetStateRequest { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue((int)workflow_statuscode.Draft) }; _serviceProxy.Execute(deactivateRequest); //</snippetSetStateWorkflow2> } // Verify that the workflow is deactivated (in a draft state). retrievedWorkflow = (Workflow)_serviceProxy.Retrieve("workflow", _workflowId, new ColumnSet("statecode", "name")); Console.WriteLine("The state of workflow {0} is: {1}.", retrievedWorkflow.Name, retrievedWorkflow.StateCode); 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; } }
private void UpdateConfirm(string incidentid) { SetStateRequest _request = new SetStateRequest(); _request.EntityMoniker = new EntityReference("incident", new Guid(incidentid)); _request.State = new OptionSetValue(0); _request.Status = new OptionSetValue(522040002); SetStateResponse _SetStateResponse = (SetStateResponse)crmService.Execute(_request); Entity _incident = crmService.Retrieve("incident", new Guid(incidentid), new ColumnSet("incidentid", "helpdesk_statusdescription")); _incident["helpdesk_statusdescription"] = new OptionSetValue(11); crmService.Update(_incident); FillRequestList(); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a Lead record on which we will execute the Workflow. Lead lead = new Lead() { FirstName = "Diogo", LastName = "Andrade" }; _leadId = _serviceProxy.Create(lead); Console.WriteLine("Created Lead for workflow request."); // Define an anonymous type to define the possible values for // process type var ProcessType = new { Definition = 1, Activation = 2, Template = 3 }; // Define an anonymous type to define the possible values for // process category var ProcessCategory = new { Workflow = 0, Dialog = 1, }; // Define an anonymous type to define the possible values for // process scope var ProcessScope = new { User = 1, BusinessUnit = 2, Deep = 3, Global = 4 }; // Create the Workflow that we will execute. Workflow workflow = new Workflow() { Name = "Sample Workflow", // friendly name of the record Type = new OptionSetValue(ProcessType.Definition), Category = new OptionSetValue(ProcessCategory.Workflow), Scope = new OptionSetValue(ProcessScope.User), OnDemand = true, PrimaryEntity = Lead.EntityLogicalName, Xaml = @"<?xml version=""1.0"" encoding=""utf-16""?> <Activity x:Class=""ExecuteWorkflowSample"" xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities"" xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:this=""clr-namespace:"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <x:Members> <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> </x:Members> <this:ExecuteWorkflowSample.InputEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:ExecuteWorkflowSample.InputEntities> <this:ExecuteWorkflowSample.CreatedEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:ExecuteWorkflowSample.CreatedEntities> <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings> <mxswa:Workflow> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" Value=""[New Entity("phonecall")]"" /> <Sequence DisplayName=""CreateStep1: Set first activity for lead.""> <Sequence.Variables> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_1"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_2"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_3"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_4"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_5"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_6"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_7"" /> <Variable x:TypeArguments=""x:Object"" Name=""CreateStep1_8"" /> </Sequence.Variables> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.Boolean, ""True"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:Boolean"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_1]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""directioncode"" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" Value=""[CreateStep1_1]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:Boolean"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.String, ""First call to "", ""String"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_3]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:GetEntityProperty Attribute=""fullname"" Entity=""[InputEntities("primaryEntity")]"" EntityName=""lead"" Value=""[CreateStep1_5]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_5 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_4]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">Add</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_3, CreateStep1_4 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_2]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""subject"" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" Value=""[CreateStep1_2]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""x:String"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:GetEntityProperty Attribute=""leadid"" Entity=""[InputEntities("primaryEntity")]"" EntityName=""lead"" Value=""[CreateStep1_7]""> <mxswa:GetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> </mxswa:GetEntityProperty.TargetType> </mxswa:GetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">SelectFirstNonNull</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { CreateStep1_7 }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_6]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""regardingobjectid"" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" Value=""[CreateStep1_6]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:EntityReference"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:ActivityReference AssemblyQualifiedName=""Microsoft.Crm.Workflow.Activities.EvaluateExpression, Microsoft.Crm.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" DisplayName=""EvaluateExpression""> <mxswa:ActivityReference.Arguments> <InArgument x:TypeArguments=""x:String"" x:Key=""ExpressionOperator"">CreateCrmType</InArgument> <InArgument x:TypeArguments=""s:Object[]"" x:Key=""Parameters"">[New Object() { Microsoft.Xrm.Sdk.Workflow.WorkflowPropertyType.OptionSetValue, ""1"", ""Picklist"" }]</InArgument> <InArgument x:TypeArguments=""s:Type"" x:Key=""TargetType""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" /> </InArgument> <OutArgument x:TypeArguments=""x:Object"" x:Key=""Result"">[CreateStep1_8]</OutArgument> </mxswa:ActivityReference.Arguments> </mxswa:ActivityReference> <mxswa:SetEntityProperty Attribute=""prioritycode"" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" Value=""[CreateStep1_8]""> <mxswa:SetEntityProperty.TargetType> <InArgument x:TypeArguments=""s:Type""> <mxswa:ReferenceLiteral x:TypeArguments=""s:Type"" Value=""mxs:OptionSetValue"" /> </InArgument> </mxswa:SetEntityProperty.TargetType> </mxswa:SetEntityProperty> <mxswa:CreateEntity EntityId=""{x:Null}"" DisplayName=""CreateStep1: Set first activity for lead."" Entity=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" EntityName=""phonecall"" /> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntities("CreateStep1_localParameter")]"" Value=""[CreatedEntities("CreateStep1_localParameter#Temp")]"" /> <Persist /> </Sequence> </mxswa:Workflow> </Activity>" }; _workflowId = _serviceProxy.Create(workflow); Console.Write("Created workflow to call in Execute Workflow request, "); SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue(2) }; _serviceProxy.Execute(setStateRequest); Console.WriteLine("and activated."); }
private void UpdateState(bool touch, bool onlychange, OptionSetValue statusvalue, OptionSetValue statevalue, Entity record) { var currentstate = record.Contains("statecode") ? record["statecode"] : new OptionSetValue(-1); var currentstatus = record.Contains("statuscode") ? record["statuscode"] : new OptionSetValue(-1); if (touch) { statevalue = (OptionSetValue)currentstate; statusvalue = (OptionSetValue)currentstatus; } if (!onlychange || !ValuesEqual(currentstate, statevalue) || !ValuesEqual(currentstatus, statusvalue)) { var req = new SetStateRequest() { EntityMoniker = record.ToEntityReference(), State = statevalue, Status = statusvalue }; var resp = Service.Execute(req); if (record.Contains("statecode")) { record["statecode"] = statevalue; } else { record.Attributes.Add("statecode", statevalue); } if (record.Contains("statuscode")) { record["statuscode"] = statusvalue; } else { record.Attributes.Add("statuscode", statusvalue); } } }
public void SetState(string entityType, Guid id, int state) { var setStateReq = new SetStateRequest { EntityMoniker = new EntityReference(entityType, id), State = new OptionSetValue(state), Status = new OptionSetValue(-1) }; Execute(setStateReq); }
public static MsCrmResult CloseFriendshipRequest(Guid requestId, FriendshipRequestStatus statusCode, IOrganizationService service) { MsCrmResult returnValue = new MsCrmResult(); try { SetStateRequest setStateReq = new SetStateRequest(); setStateReq.EntityMoniker = new EntityReference("new_friendshiprequest", requestId); setStateReq.State = new OptionSetValue(1); setStateReq.Status = new OptionSetValue((int)statusCode); SetStateResponse response = (SetStateResponse)service.Execute(setStateReq); returnValue.Success = true; returnValue.Result = "M041"; //"Arkadaşlık talebiniz durumu güncellendi."; } catch (Exception ex) { returnValue.Success = false; returnValue.Result = ex.Message; } return returnValue; }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Reschedule an instance of the recurring appointment series. /// Cancel another instance of the recurring appointment series. /// 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(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetRescheduleandCancelRecurringAppointmentInstance1> // Retrieve the individual appointment instance that falls on or after // 10 days from today. Basically this will be the second instance in the // recurring appointment series. QueryExpression instanceQuery = new QueryExpression { EntityName = Appointment.EntityLogicalName, ColumnSet = new ColumnSet { Columns = { "activityid", "scheduledstart", "scheduledend" } }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "seriesid", Operator = ConditionOperator.Equal, Values = { _recurringAppointmentMasterId } }, new ConditionExpression { AttributeName = "scheduledstart", Operator = ConditionOperator.OnOrAfter, Values = { DateTime.Today.AddDays(10) } } } } }; EntityCollection individualAppointments = _serviceProxy.RetrieveMultiple(instanceQuery); //<snippetRescheduleandCancelRecurringAppointmentInstance2> #region Reschedule an instance of recurring appointment // Update the scheduled start and end dates of the appointment // to reschedule it. Appointment updateAppointment = new Appointment { ActivityId = individualAppointments.Entities.Select(x => (Appointment)x).First().ActivityId, ScheduledStart = individualAppointments.Entities.Select(x => (Appointment)x).First().ScheduledStart.Value.AddHours(1), ScheduledEnd = individualAppointments.Entities.Select(x => (Appointment)x).First().ScheduledEnd.Value.AddHours(2) }; RescheduleRequest reschedule = new RescheduleRequest { Target = updateAppointment }; RescheduleResponse rescheduled = (RescheduleResponse)_serviceProxy.Execute(reschedule); Console.WriteLine("Rescheduled the second instance of the recurring appointment."); #endregion Reschedule an instance of recurring appointment //</snippetRescheduleandCancelRecurringAppointmentInstance2> //<snippetRescheduleandCancelRecurringAppointmentInstance3> #region Cancel an instance of recurring appointment // Cancel the last instance of the appointment. The status of this appointment // instance is set to 'Canceled'. You can view this appoinyment instance under // the 'All Activities' view. SetStateRequest appointmentRequest = new SetStateRequest { State = new OptionSetValue((int)AppointmentState.Canceled), Status = new OptionSetValue(4), EntityMoniker = new EntityReference(Appointment.EntityLogicalName, new Guid(individualAppointments.Entities.Select(x => (Appointment)x).Last().ActivityId.ToString())) }; _serviceProxy.Execute(appointmentRequest); Console.WriteLine("Canceled the last instance of the recurring appointment."); #endregion Cancel an instance of recurring appointment //</snippetRescheduleandCancelRecurringAppointmentInstance3> //</snippetRescheduleandCancelRecurringAppointmentInstance1> 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; } }
private void SetState(EntityReference caseReference) { //<snippetSetState> // Create the Request Object SetStateRequest state = new SetStateRequest(); // Set the Request Object's Properties state.State = new OptionSetValue((int)IncidentState.Active); state.Status = new OptionSetValue((int)incident_statuscode.WaitingforDetails); // Point the Request to the case whose state is being changed state.EntityMoniker = caseReference; // Execute the Request SetStateResponse stateSet = (SetStateResponse)_serviceProxy.Execute(state); // Check if the state was successfully set Incident incident = _serviceProxy.Retrieve(Incident.EntityLogicalName, _caseIncidentId, new ColumnSet(allColumns: true)).ToEntity<Incident>(); if (incident.StatusCode.Value == (int)incident_statuscode.WaitingforDetails) { Console.WriteLine("Record state set successfully."); } else { Console.WriteLine("The request to set the record state failed."); } //</snippetSetState> }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// a Contract Template and several Contracts are created, demonstrating how to /// create and work with the Contract entity. /// </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 { //<snippetWorkingWithContracts1> // 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(); CreateRequiredRecords(); #region Create Contract Template // First, attempt to retrieve the Contract Template. Otherwise, // create the template. QueryExpression templateQuery = new QueryExpression() { EntityName = ContractTemplate.EntityLogicalName, ColumnSet = new ColumnSet("contracttemplateid"), Criteria = { Conditions = { new ConditionExpression("abbreviation", ConditionOperator.Equal, "SCT") } } }; EntityCollection ec = _serviceProxy.RetrieveMultiple(templateQuery); if (ec.Entities.Count > 0) { _contractTemplateId = ec.Entities[0].Id; Console.Write("Template retrieved, "); } else { ContractTemplate contractTemplate = new ContractTemplate() { Name = "Sample Contract Template", BillingFrequencyCode = new OptionSetValue((int)ContractTemplateBillingFrequencyCode.Monthly), Abbreviation = "SCT", AllotmentTypeCode = new OptionSetValue((int)ContractTemplateAllotmentTypeCode.NumberofCases), EffectivityCalendar = "--------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++-------------------------------------------------------" }; _contractTemplateId = _serviceProxy.Create(contractTemplate); Console.Write("Template created, "); } #endregion #region Create Contract // Create a Contract from the Contract Template. Contract contract = new Contract() { Title = "Sample Contract", ContractTemplateId = new EntityReference { Id = _contractTemplateId, LogicalName = ContractTemplate.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = Account.EntityLogicalName }, BillingCustomerId = new EntityReference { Id = _accountId, LogicalName = Account.EntityLogicalName }, ActiveOn = new DateTime(2015, 1, 1), ExpiresOn = new DateTime(2020, 1, 1), BillingStartOn = new DateTime(2015, 1, 1), BillingEndOn = new DateTime(2020, 1, 1) }; _contractId = _serviceProxy.Create(contract); Console.Write("parent contract created, "); // Create a contract line item. ContractDetail contractLineItem = new ContractDetail() { Title = "Sample Contract Line Item", ContractId = new EntityReference { Id = _contractId, LogicalName = Contract.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = Account.EntityLogicalName }, ActiveOn = new DateTime(2015, 1, 1), ExpiresOn = new DateTime(2020, 1, 1), Price = new Money(20.0M), TotalAllotments = 20 }; _serviceProxy.Create(contractLineItem); Console.Write("contract line attached, "); #endregion #region Clone contract twice //<snippetCloneContract> // Create the first clone of the contract. CloneContractRequest cloneRequest = new CloneContractRequest() { ContractId = _contractId, IncludeCanceledLines = false }; CloneContractResponse cloneResponse = (CloneContractResponse)_serviceProxy.Execute(cloneRequest); _firstCloneId = ((Contract)cloneResponse.Entity).ContractId.Value; //</snippetCloneContract> Console.Write("first clone created, "); // Create the second clone of the contract. cloneRequest = new CloneContractRequest() { ContractId = _contractId, IncludeCanceledLines = true }; cloneResponse = (CloneContractResponse)_serviceProxy.Execute(cloneRequest); _secondCloneId = ((Contract)cloneResponse.Entity).ContractId.Value; Console.Write("second clone created. \n"); // Retrieve all Contracts. QueryExpression contractQuery = new QueryExpression() { EntityName = Contract.EntityLogicalName, ColumnSet = new ColumnSet("contractid"), Criteria = { Conditions = { new ConditionExpression("customerid", ConditionOperator.Equal, _accountId) } } }; EntityCollection contracts = _serviceProxy.RetrieveMultiple(contractQuery); // Display the retrieved Contract Ids. for (int i = 0; i < contracts.Entities.Count; i++) { Console.WriteLine("Retrieved contract with Id: {0}", ((Contract)contracts.Entities[i]).ContractId); } #endregion #region Deactivate a cloned contract // In order to deactivate a contract (put it on hold), it is first // necessary to invoice the contract. SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _firstCloneId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.Invoiced), Status = new OptionSetValue(2) }; _serviceProxy.Execute(setStateRequest); Console.Write("Contract invoiced, "); // Now that the contract has been invoiced, it is possible to put // the contract on hold. setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _firstCloneId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.OnHold), Status = new OptionSetValue(4) }; _serviceProxy.Execute(setStateRequest); Console.Write("and put on hold.\n"); #endregion #region Renew an invoiced contract // In order to renew a contract, it must be invoiced first, and // then canceled. //<snippetSetStateForContract> // Invoice the contract. setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _contractId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.Invoiced), Status = new OptionSetValue(3) }; _serviceProxy.Execute(setStateRequest); //</snippetSetStateForContract> Console.Write("Contract invoiced, "); //<snippetCancelContract> // Cancel the contract. setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _contractId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.Canceled), Status = new OptionSetValue(5) }; _serviceProxy.Execute(setStateRequest); //</snippetCancelContract> Console.Write("canceled, "); //<snippetRenewContract> // Renew the canceled contract. RenewContractRequest renewRequest = new RenewContractRequest() { ContractId = _contractId, IncludeCanceledLines = true, Status = 1 }; RenewContractResponse renewResponse = (RenewContractResponse)_serviceProxy.Execute(renewRequest); // Retrieve Id of renewed contract. _renewedId = ((Contract)renewResponse.Entity).ContractId.Value; //</snippetRenewContract> // Display the Id of the renewed contract. Console.WriteLine("and renewed."); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithContracts1> } // 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> /// Deletes any entity records that were created for this sample. /// <param name="prompt">Indicates whether to prompt the user /// to delete the records created in this sample.</param> /// </summary> public void DeleteRequiredRecords(bool prompt) { // Two of the contracts, their associated account and the contract template // records that were created and used in this sample will continue to exist // on your system because contracts that have been invoiced cannot be deleted // in Microsoft Dynamics CRM. They can only be put on hold or canceled. bool toBeDeleted = true; if (prompt) { // Ask the user if the created entities should be deleted. Console.Write("\nDo you want these entity records deleted? (y/n) [y]: "); String answer = Console.ReadLine(); if (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty) { toBeDeleted = true; } else { toBeDeleted = false; } } if (toBeDeleted) { _serviceProxy.Delete(Contract.EntityLogicalName, _secondCloneId); _serviceProxy.Delete(Contract.EntityLogicalName, _renewedId); _serviceProxy.Delete(Contract.EntityLogicalName, _contractId); SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _firstCloneId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.Invoiced), Status = new OptionSetValue(3) }; _serviceProxy.Execute(setStateRequest); setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _firstCloneId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.Canceled), Status = new OptionSetValue(5) }; _serviceProxy.Execute(setStateRequest); _serviceProxy.Delete(Contract.EntityLogicalName, _firstCloneId); _serviceProxy.Delete(Account.EntityLogicalName, _accountId); Console.WriteLine("Entity record(s) have been deleted."); } }
public void EnableRule(Guid ruleId) { var setStateRequest = new SetStateRequest { EntityMoniker = new EntityReference(entityName, ruleId), State = new OptionSetValue(0), Status = new OptionSetValue(-1) }; service.Execute(setStateRequest); }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// a goal is created specifying the target count. The goal is then /// rolled up, the actual and in-progress values are overridden and finally the /// goal is closed. /// </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 { //<snippetOverrideGoalTotalCount1> // 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(); CreateRequiredRecords(); // Create the count metric, setting the Metric Type to 'Count' by // setting IsAmount to false. Metric sampleMetric = new Metric() { Name = "Sample Count Metric", IsAmount = false, }; _metricId = _serviceProxy.Create(sampleMetric); sampleMetric.Id = _metricId; Console.Write("Created phone call metric, "); #region Create RollupFields // Create RollupField which targets completed (received) phone calls. RollupField actual = new RollupField() { SourceEntity = PhoneCall.EntityLogicalName, GoalAttribute = "actualinteger", SourceState = 1, SourceStatus = 4, EntityForDateAttribute = PhoneCall.EntityLogicalName, DateAttribute = "actualend", MetricId = sampleMetric.ToEntityReference() }; _actualId = _serviceProxy.Create(actual); Console.Write("created actual revenue RollupField, "); // Create RollupField which targets open (in-progress) phone calls. RollupField inprogress = new RollupField() { SourceEntity = PhoneCall.EntityLogicalName, GoalAttribute = "inprogressinteger", SourceState = 0, EntityForDateAttribute = PhoneCall.EntityLogicalName, DateAttribute = "createdon", MetricId = sampleMetric.ToEntityReference() }; _inprogressId = _serviceProxy.Create(inprogress); Console.Write("created in-progress revenue RollupField, "); #endregion #region Create the goal rollup queries // Note: Formatting the FetchXml onto multiple lines in the following // rollup queries causes the length property to be greater than 1,000 // chars and will cause an exception. // The following query locates closed incoming phone calls. GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "Example Goal Rollup Query - Actual", QueryEntityType = PhoneCall.EntityLogicalName, FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery)); goalRollupQuery.Id = _rollupQueryIds[0]; // The following query locates open incoming phone calls. GoalRollupQuery inProgressGoalRollupQuery = new GoalRollupQuery() { Name = "Example Goal Rollup Query - InProgress", QueryEntityType = PhoneCall.EntityLogicalName, FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='0' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(inProgressGoalRollupQuery)); inProgressGoalRollupQuery.Id = _rollupQueryIds[1]; Console.Write("created rollup queries for incoming phone calls.\n"); Console.WriteLine(); #endregion #region Create a goal to track the open incoming phone calls. // Create the goal. Goal goal = new Goal() { Title = "Sample Goal", RollupOnlyFromChildGoals = false, ConsiderOnlyGoalOwnersRecords = false, TargetInteger = 5, RollupQueryActualIntegerId = goalRollupQuery.ToEntityReference(), RollUpQueryInprogressIntegerId = inProgressGoalRollupQuery.ToEntityReference(), IsFiscalPeriodGoal = false, MetricId = sampleMetric.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _goalId = _serviceProxy.Create(goal); goal.Id = _goalId; Console.WriteLine("Created goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", goal.TargetInteger.Value); Console.WriteLine("Goal owner: {0}", goal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", goal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", goal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); #endregion #region Calculate rollup and display result // Calculate roll-up of the goal. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = goal.ToEntityReference() }; _serviceProxy.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goal."); Console.WriteLine(); // Retrieve and report 3 different computed values for the goal // - Percentage // - Actual (Integer) // - In-Progress (Integer) QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "actualinteger", "inprogressinteger") }; EntityCollection ec = _serviceProxy.RetrieveMultiple(retrieveValues); // Compute and display the results. for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("Percentage Achieved: {0}", temp.Percentage); Console.WriteLine("Actual (Integer): {0}", temp.ActualInteger.Value); Console.WriteLine("In-Progress (Integer): {0}", temp.InProgressInteger.Value); Console.WriteLine("<End of Listing>"); } Console.WriteLine(); #endregion #region Update goal to override the actual rollup value // Override the actual and in-progress values of the goal. // To prevent rollup values to be overwritten during next Recalculate operation, // set: goal.IsOverridden = true; goal.IsOverride = true; goal.ActualInteger = 10; goal.InProgressInteger = 5; // Update the goal. UpdateRequest update = new UpdateRequest() { Target = goal }; _serviceProxy.Execute(update); Console.WriteLine("Goal actual and in-progress values overridden."); Console.WriteLine(); #endregion #region Retrieve result of manual override // Retrieve and report 3 different computed values for the goal // - Percentage // - Actual (Integer) // - In-Progress (Integer) retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "actualinteger", "inprogressinteger") }; ec = _serviceProxy.RetrieveMultiple(retrieveValues); // Compute and display the results. for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("Percentage Achieved: {0}", temp.Percentage); Console.WriteLine("Actual (Integer): {0}", temp.ActualInteger.Value); Console.WriteLine("In-Progress (Integer): {0}", temp.InProgressInteger.Value); Console.WriteLine("<End of Listing>"); } Console.WriteLine(); #endregion #region Close the goal // Close the goal. SetStateRequest closeGoal = new SetStateRequest() { EntityMoniker = goal.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(1) }; Console.WriteLine("Goal closed."); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetOverrideGoalTotalCount1> } // 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> /// This method first creates XAML to define the custom workflow. Afterwards, /// it creates the workflow record with this XAML and then activates it. /// </summary> /// <remarks> /// Visit http://msdn.microsoft.com/en-us/library/gg309458.aspx /// for instructions on enabling XAML workflows on the Microsoft Dynamics CRM server. /// </remarks> /// <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(); CreateRequiredRecords(); #region Create XAML // Define the workflow XAML. string xamlWF; xamlWF = @"<?xml version=""1.0"" encoding=""utf-16""?> <Activity x:Class=""SampleWF"" xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities"" xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:this=""clr-namespace:"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <x:Members> <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> </x:Members> <this:SampleWF.InputEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:SampleWF.InputEntities> <this:SampleWF.CreatedEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:SampleWF.CreatedEntities> <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings> <mxswa:Workflow> <Sequence> <Sequence.Variables> <Variable x:TypeArguments=""x:Int32"" Default=""[40]"" Name=""probability_value"" /> <Variable x:TypeArguments=""mxs:Entity"" Default=""[CreatedEntities("primaryEntity#Temp")]"" Name=""CreatedEntity"" /> </Sequence.Variables> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntity]"" Value=""[New Entity("opportunity")]"" /> <Assign x:TypeArguments=""s:Guid"" To=""[CreatedEntity.Id]"" Value=""[InputEntities("primaryEntity").Id]"" /> <mxswa:SetEntityProperty Attribute=""closeprobability"" Entity=""[CreatedEntity]"" EntityName=""opportunity"" TargetType=""[Type.GetType("probability_value")]"" Value=""[probability_value]""> </mxswa:SetEntityProperty> <mxswa:UpdateEntity Entity=""[CreatedEntity]"" EntityName=""opportunity"" /> <Assign x:TypeArguments=""mxs:Entity"" To=""[InputEntities("primaryEntity")]"" Value=""[CreatedEntity]"" /> <Persist /> </Sequence> </mxswa:Workflow> </Activity>"; #endregion Create XAML #region Create Workflow //<snippetCreateAWorkflow1> // Create an asynchronous workflow. // The workflow should execute after a new opportunity is created. Workflow workflow = new Workflow() { // These properties map to the New Process form settings in the web application. Name = "Set closeprobability on opportunity create (async)", Type = new OptionSetValue((int)WorkflowType.Definition), Category = new OptionSetValue((int)WorkflowCategory.Workflow), PrimaryEntity = Opportunity.EntityLogicalName, Mode = new OptionSetValue((int)WorkflowMode.Background), // Additional settings from the second New Process form. Description = @"When an opportunity is created, this workflow" + " sets the closeprobability field of the opportunity record to 40%.", OnDemand = false, Subprocess = false, Scope = new OptionSetValue((int)WorkflowScope.User), TriggerOnCreate = true, AsyncAutoDelete = true, Xaml = xamlWF, // Other properties not in the web forms. LanguageCode = 1033, // U.S. English }; _workflowId = _serviceProxy.Create(workflow); //</snippetCreateAWorkflow1> Console.WriteLine("Created Workflow: " + workflow.Name); #endregion Create Workflow #region Activate Workflow // Activate the workflow. var activateRequest = new SetStateRequest { EntityMoniker = new EntityReference (Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue((int)workflow_statuscode.Activated) }; _serviceProxy.Execute(activateRequest); Console.WriteLine("Activated Workflow: " + workflow.Name); #endregion Activate Workflow 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; } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve a sales manager. _salesManagerId = SystemUserProvider.RetrieveMarketingManager(_serviceProxy); #endregion #region Create PhoneCall record and supporting account Account newAccount = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(newAccount)); newAccount.Id = _accountId; // Create Guids for PhoneCalls _phoneCallId = Guid.NewGuid(); _phoneCall2Id = Guid.NewGuid(); // Create ActivityPartys for the phone calls' "From" field. ActivityParty activityParty = new ActivityParty() { PartyId = newAccount.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; ActivityParty activityPartyClosed = new ActivityParty() { PartyId = newAccount.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCall2Id, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create an open phone call. PhoneCall phoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Sample Phone Call", DirectionCode = false, To = new ActivityParty[] { activityParty } }; _serviceProxy.Create(phoneCall); // Create a second phone call to close phoneCall = new PhoneCall() { Id = _phoneCall2Id, Subject = "Sample Phone Call 2", DirectionCode = false, To = new ActivityParty[] { activityParty }, ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the second phone call. SetStateRequest closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); #endregion }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a unit group. /// Retrieve the default unit. /// Create few products. /// Create new discount list and discount. /// Create new price list and few price list items. /// Create an account record. /// Create a new opportunity and few opportunity products. /// </summary> public void CreateRequiredRecords() { // Create a unit group UoMSchedule newUnitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _serviceProxy.Create(newUnitGroup); Console.WriteLine("Created {0}", newUnitGroup.Name); // Retrieve the default unit id that was automatically created // when we created the Unit Group QueryExpression unitQuery = new QueryExpression { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "uomscheduleid", Operator = ConditionOperator.Equal, Values = { _unitGroupId } } } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; // Retrieve the unit. UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0]; _defaultUnitId = unit.UoMId.Value; Console.WriteLine("Retrieved {0}", unit.Name); // Create a few products Product newProduct1 = new Product { ProductNumber = "1", Name = "Example Product 1", ProductStructure = new OptionSetValue(1), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("Created {0}", newProduct1.Name); Product newProduct2 = new Product { ProductNumber = "2", Name = "Example Product 2", ProductStructure = new OptionSetValue(1), QuantityDecimal = 3, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created {0}", newProduct2.Name); // Create a new discount list DiscountType newDiscountType = new DiscountType { Name = "Example Discount List", IsAmountType = false }; _discountTypeId = _serviceProxy.Create(newDiscountType); Console.WriteLine("Created {0}", newDiscountType.Name); // Create a new discount Discount newDiscount = new Discount { DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName, _discountTypeId), LowQuantity = 5, HighQuantity = 10, Percentage = 3 }; _discountId = _serviceProxy.Create(newDiscount); Console.WriteLine("Created new discount for the {0}.", newDiscountType.Name); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); Console.WriteLine("Created {0}", newPriceList.Name); // Create a price list item for the first product and apply volume discount ProductPriceLevel newPriceListItem1 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20), DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName, _discountTypeId) }; _priceListItem1Id = _serviceProxy.Create(newPriceListItem1); Console.WriteLine(@"Created price list item for the {0} and applied volume discount.", newProduct1.Name); // Create a price list item for the second product ProductPriceLevel newPriceListItem2 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product2Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20) }; _priceListItem2Id = _serviceProxy.Create(newPriceListItem2); Console.WriteLine("Created price list item for the {0}.", newProduct1.Name); //Publish Product1 SetStateRequest publishRequest1 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest1); //Publish Product2 SetStateRequest publishRequest2 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest2); Console.WriteLine("Published both the products"); // Create an account record for the opporutnity's potential customerid Account newAccount = new Account { Name = "Example Account" }; _accountId = _serviceProxy.Create(newAccount); Console.WriteLine("Created {0}", newAccount.Name); // Create a new opportunity Opportunity newOpportunity = new Opportunity { Name = "Example Opportunity", CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(newOpportunity); Console.WriteLine("Created {0}.", newOpportunity.Name); // Create some opportunity products OpportunityProduct newOpportunityProduct1 = new OpportunityProduct { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 8 }; _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1); OpportunityProduct newOpportunityProduct2 = new OpportunityProduct { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId), ProductId = new EntityReference(Product.EntityLogicalName, _product2Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 1 }; _opportunityProduct2Id = _serviceProxy.Create( newOpportunityProduct2); Console.WriteLine("Created few opportunity products."); return; }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve the ldapPath String ldapPath = String.Empty; // Retrieve the sales team - 1 sales manager and 2 sales representatives. _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath); _salesRepresentativeId = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath)[0]; #endregion #region Create records to support SalesOrder records // Create a unit group UoMSchedule newUnitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _serviceProxy.Create(newUnitGroup); // Retrieve the default unit id that was automatically created // when we created the Unit Group QueryExpression unitQuery = new QueryExpression { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "uomscheduleid", Operator = ConditionOperator.Equal, Values = { _unitGroupId } } } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; // Retrieve the unit. UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0]; _defaultUnitId = unit.UoMId.Value; // Create a few products Product newProduct = new Product { ProductNumber = "1", Name = "Example Product", ProductStructure = new OptionSetValue(1), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _productId = _serviceProxy.Create(newProduct); newProduct.Id = _productId; Console.WriteLine("Created {0}", newProduct.Name); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); // Create a price list item for the first product and apply volume discount ProductPriceLevel newPriceListItem = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _productId), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20), }; _priceListItemId = _serviceProxy.Create(newPriceListItem); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _productId), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("Published {0}", newProduct.Name); // Create an account record for the sales order's potential customerid Account newAccount = new Account { Name = "Litware, Inc.", Address1_PostalCode = "60661" }; _accountId = _serviceProxy.Create(newAccount); newAccount.Id = _accountId; #endregion Create records to support SalesOrder #region Create SalesOrder record // Create the sales order. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), FreightAmount = new Money(20.0M) }; _orderId = _serviceProxy.Create(order); order.Id = _orderId; // Add the product to the order with the price overriden with a // negative value. SalesOrderDetail orderDetail = new SalesOrderDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 4, SalesOrderId = order.ToEntityReference(), IsPriceOverridden = true, PricePerUnit = new Money(1000.0M), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _orderDetailId = _serviceProxy.Create(orderDetail); #endregion Create SalesOrder record }
private bool FindAndDeactivateEntity(DateTime date) { using (var orgContext = new OrganizationServiceContext(this.service)) { var currencyFromCrm = (from i in orgContext.CreateQuery<sl_ExchangeRate>() where i.sl_RelevanceDate < date.ToUniversalTime().AddHours(_ToCrmUTCDate) && i.statecode == sl_ExchangeRateState.Active select i).ToList(); if (currencyFromCrm.Count == 0) { return true; } // деактивация устаревших курсов State = Close foreach (var item in currencyFromCrm) { SetStateRequest deactivateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(sl_ExchangeRate.EntityLogicalName, item.Id), State = new OptionSetValue(1), Status = new OptionSetValue(-1) }; orgContext.Execute(deactivateRequest); } return true; } }
public static MsCrmResult PassiveCode(Guid pointCodeId, IOrganizationService service) { MsCrmResult returnValue = new MsCrmResult(); try { SetStateRequest setStateReq = new SetStateRequest(); setStateReq.EntityMoniker = new EntityReference("new_pointcode", pointCodeId); setStateReq.State = new OptionSetValue(1); setStateReq.Status = new OptionSetValue(2); SetStateResponse response = (SetStateResponse)service.Execute(setStateReq); returnValue.Success = true; returnValue.Result = "Kod kullanıldı"; } catch (Exception ex) { returnValue.Success = false; returnValue.Result = ex.Message; } return returnValue; }
/// <summary> /// Deletes any entity records that were created for this sample. /// <param name="prompt">Indicates whether to prompt the user /// to delete the records created in this sample.</param> /// </summary> public void DeleteRequiredRecords(bool prompt) { bool deleteRecords = true; if (prompt) { Console.WriteLine("\nDo you want these entity records deleted? (y/n) [y]: "); String answer = Console.ReadLine(); deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty); } if (deleteRecords) { SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Draft), Status = new OptionSetValue(1) }; _serviceProxy.Execute(setStateRequest); _serviceProxy.Delete(Workflow.EntityLogicalName, _workflowId); _serviceProxy.Delete(Lead.EntityLogicalName, _leadId); _serviceProxy.Delete(AsyncOperation.EntityLogicalName, _asyncOperationId); Console.WriteLine("Entity records have been deleted."); } }
protected void RequestView_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Confirm") { UpdateConfirm(e.CommandArgument.ToString()); } if (e.CommandName == "Cancel") { Entity _req = new Entity("incident"); _req["incidentid"] = new Guid(e.CommandArgument.ToString()); _req["helpdesk_statusdescription"] = null; crmService.Update(_req); SetStateRequest _request = new SetStateRequest(); _request.EntityMoniker = new EntityReference("incident", new Guid(e.CommandArgument.ToString())); _request.State = new OptionSetValue(2); _request.Status = new OptionSetValue(6); SetStateResponse _SetStateResponse = (SetStateResponse)crmService.Execute(_request); FillRequestList(); } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve the ldapPath String ldapPath = String.Empty; // Retrieve the sales team - 1 sales manager and 2 sales representatives. _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath); _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); #endregion #region Create records to support Opportunity records // Create a unit group UoMSchedule newUnitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _serviceProxy.Create(newUnitGroup); // Retrieve the default unit id that was automatically created // when we created the Unit Group QueryExpression unitQuery = new QueryExpression { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "uomscheduleid", Operator = ConditionOperator.Equal, Values = { _unitGroupId } } } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; // Retrieve the unit. UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0]; _defaultUnitId = unit.UoMId.Value; // Create a few products Product newProduct1 = new Product { ProductNumber = "1", Name = "Example Product 1", ProductStructure = new OptionSetValue(1), QuantityDecimal = 2, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _product1Id = _serviceProxy.Create(newProduct1); Console.WriteLine("Created {0}", newProduct1.Name); Product newProduct2 = new Product { ProductNumber = "2", Name = "Example Product 2", ProductStructure = new OptionSetValue(1), QuantityDecimal = 3, DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, _unitGroupId), DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _product2Id = _serviceProxy.Create(newProduct2); Console.WriteLine("Created {0}", newProduct2.Name); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); // Create a price list item for the first product and apply volume discount ProductPriceLevel newPriceListItem1 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(20) }; _priceListItem1Id = _serviceProxy.Create(newPriceListItem1); // Create a price list item for the second product ProductPriceLevel newPriceListItem2 = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), ProductId = new EntityReference(Product.EntityLogicalName, _product2Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Amount = new Money(15) }; _priceListItem2Id = _serviceProxy.Create(newPriceListItem2); //Publish Product1 SetStateRequest publishRequest1 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest1); //Publish Product2 SetStateRequest publishRequest2 = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest2); Console.WriteLine("Published both the products"); // Create an account record for the opportunity's potential customerid Account newAccount = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(newAccount)); #endregion Create records to support Opportunity records }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region create kb articles Console.WriteLine(" Creating KB Articles"); _subjectId = ( from subject in _context.SubjectSet where subject.Title == "Default Subject" select subject.Id ).First(); var kbArticleTemplateId = ( from articleTemplate in _context.KbArticleTemplateSet where articleTemplate.Title == "Standard KB Article" select articleTemplate.Id ).FirstOrDefault(); if (kbArticleTemplateId != Guid.Empty) { // create a KB article _articles[0] = new KbArticle() { // set the article properties Title = "Searching the knowledge base", ArticleXml = @" <articledata> <section id='0'> <content><![CDATA[This is a sample article about searching the knowledge base.]]></content> </section> <section id='1'> <content><![CDATA[Knowledge bases contain information useful for various people.]]></content> </section> </articledata>", // use the built-in "Standard KB Article" template KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName, kbArticleTemplateId), // use the default subject SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId), KeyWords = "Searching Knowledge base" }; _context.AddObject(_articles[0]); _articles[1] = new KbArticle() { Title = "What's in a knowledge base", ArticleXml = @" <articledata> <section id='0'> <content><![CDATA[This is a sample article about what would be in a knowledge base.]]></content> </section> <section id='1'> <content><![CDATA[This section contains more information.]]></content> </section> </articledata>", KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName, kbArticleTemplateId), SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId), KeyWords = "Knowledge base" }; _context.AddObject(_articles[1]); _articles[2] = new KbArticle() { Title = "Searching the knowledge base from code", ArticleXml = @" <articledata> <section id='0'> <content><![CDATA[This article covers searching the knowledge base from code.]]></content> </section> <section id='1'> <content><![CDATA[This section contains more information.]]></content> </section> </articledata>", KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName, kbArticleTemplateId), SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId), KeyWords = "Knowledge base code" }; _context.AddObject(_articles[2]); _context.SaveChanges(); } else { throw new ArgumentException("Standard Article Templates are missing"); } #endregion #region Submit the articles Console.WriteLine(" Submitting the articles"); foreach (var article in _articles) { _context.Execute(new SetStateRequest { EntityMoniker = article.ToEntityReference(), State = new OptionSetValue((int)KbArticleState.Unapproved), Status = new OptionSetValue((int)kbarticle_statuscode.Unapproved) }); } #endregion #region Approve and Publish the article Console.WriteLine(" Publishing articles"); foreach (var article in _articles) { _context.Execute(new SetStateRequest { EntityMoniker = article.ToEntityReference(), State = new OptionSetValue((int)KbArticleState.Published), Status = new OptionSetValue((int)kbarticle_statuscode.Published) }); } #endregion #region Waiting for publishing to finish // Wait 20 seconds to ensure that data will be available // Full-text indexing Console.WriteLine(" Waiting 20 seconds to ensure indexing has completed on the new records."); System.Threading.Thread.Sleep(20000); Console.WriteLine(); #endregion #region Add cases to KbArticles // Create UoM _uomSchedule = new UoMSchedule() { Name = "Sample unit group", BaseUoMName = "Sample base unit" }; _context.AddObject(_uomSchedule); _context.SaveChanges(); _uom = (from uom in _context.UoMSet where uom.Name == _uomSchedule.BaseUoMName select uom).First(); Console.WriteLine(" Creating an account and incidents for the KB articles"); var whoami = (WhoAmIResponse)_context.Execute(new WhoAmIRequest()); _account = new Account() { Name = "Coho Winery", }; _context.AddObject(_account); _context.SaveChanges(); _product = new Product() { Name = "Sample Product", ProductNumber = "0", ProductStructure = new OptionSetValue(1), DefaultUoMScheduleId = _uomSchedule.ToEntityReference(), DefaultUoMId = _uom.ToEntityReference() }; _context.AddObject(_product); _context.SaveChanges(); // Publish Product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product.Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _context.Execute(publishRequest); _incident = new Incident() { Title = "A sample incident", OwnerId = new EntityReference(SystemUser.EntityLogicalName, whoami.UserId), KbArticleId = _articles[0].ToEntityReference(), CustomerId = _account.ToEntityReference(), SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId), ProductId = _product.ToEntityReference() }; _context.AddObject(_incident); _context.SaveChanges(); #endregion }