Sonal B
Sonal B

Reputation: 11

Set and change the OptionSetValue of crm in C#

I am working on mvc-5 with dynamic-crm. In crm i have a optionsetValue for state-code with the value (publish,deactivate,draft). Now my first question is how do i set these value in my C# code,by default it should be draft. The second is how do i change the state-code value on button click(say when i click on publish button the state should change to publish from draft). below is the code that i have in my model

[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statuscode")]
public Microsoft.Xrm.Sdk.OptionSetValue statuscode
{
    get
    {
        return this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("statuscode");
    }
    set
    {

        this.SetAttributeValue("statuscode", value);

    }
}

[DisplayName("Status")]
[Display(Name = "Status")]
public string Status
{
    get
    {
        if(statuscode == null)
        {
            OptionSetValue setValue = new OptionSetValue();
            setValue.Value = 1;
            return Status = "Draft";          
        }

        return Status = statuscode.Value.ToString() == "1" ? "Publish" : "Draft";
    }
    set
    {

    }
}

Thanks in advance!!

Upvotes: 0

Views: 2586

Answers (1)

Dot_NET Pro
Dot_NET Pro

Reputation: 2123

In Dynamics CRM when we create a new record, the if we specify or not. The default value for the StateCode and StatusCode is set.

So we have to set Status(statecode) and Status Reason(statuscode) explicitly. Below is the function i am using in my code:

public static void SetStatus(string EntityName, Guid Id, int StateCode, int StatusCode)
    {
        try
        {
            if (Service == null)
                throw GRID.CRM.ExceptionHandler.ExceptionUtil.GetException("Connection with CRM is Lost", typeof(Common), "SetStatus");
            SetStateRequest StateRequest = new SetStateRequest();
            StateRequest.EntityMoniker = new EntityReference(EntityName, Id);
            StateRequest.State = new OptionSetValue(StateCode);
            StateRequest.Status = new OptionSetValue(StatusCode);
            SetStateResponse StateResponse = (SetStateResponse)Service.Execute(StateRequest);
        }
        catch (Exception ex)
        {
            throw GRID.CRM.ExceptionHandler.ExceptionUtil.GetException(ex, typeof(Common), "SetStatus");
        }
    }

Upvotes: 1

Related Questions