Monday, 7 May 2012

Code to Schedule a resource in CRM 2011


In this article , I am going to explain how to Schedule a resource

For Better Understanding I divided this article in multiple parts
(i)      Create the van resource
(ii)     Create the contraints for creating the plumber resource group
(iii)    Create the plumber resource group
(iv)    Create the resource specification
(v)     Create the plumber required resource object
(vi)    Create the service for the equipment
(vii)   Create the van required resource object
(viii)  Create the appointment request
(ix)    Verify that the resources have been scheduled

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;

Create the van resource
Equipment van = new Equipment
{
    Name = "Van 1",
    TimeZoneCode = 1,
    BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId)
};
Guid _vanId = _serviceProxy.Create(van);

Create the contraints for creating the plumber resource group
System.Text.StringBuilder builder = new System.Text.StringBuilder("<Constraints>");
builder.Append("<Constraint>");
builder.Append("<Expression>");
builder.Append("<Body>resource[\"Id\"] == ");
builder.Append(userResponse.UserId.ToString("B"));
builder.Append(" || resource[\"Id\"] == ");
builder.Append(_vanId.ToString("B"));
builder.Append("</Body>");
builder.Append("<Parameters>");
builder.Append("<Parameter name=\"resource\" />");
builder.Append("</Parameters>");
builder.Append("</Expression>");
builder.Append("</Constraint>");
builder.Append("</Constraints>");

Create the plumber resource group
ConstraintBasedGroup group = new ConstraintBasedGroup
{
    BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId),
    Name = "Plumber with Van 1",
    Constraints = builder.ToString(),
    GroupTypeCode = new OptionSetValue(ConstraintBasedGroupTypeCode.Static),
};
Guid _groupId = _serviceProxy.Create(group);

Create the resource specification
ResourceSpec spec = new ResourceSpec
{
    BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId),
    ObjectiveExpression = @"
<Expression>
<Body>udf ""Random""(factory,resource,appointment,request,leftoffset,rightoffset)</Body>
<Parameters>
<Parameter name=""factory"" />
<Parameter name=""resource"" />
<Parameter name=""appointment"" />
<Parameter name=""request"" />
<Parameter name=""leftoffset"" />
<Parameter name=""rightoffset"" />
</Parameters>
<Properties EvaluationInterval=""P0D"" evaluationcost=""0"" />
</Expression>",
    RequiredCount = 1,
    Name = "Test Spec",
    GroupObjectId = _groupId
};
Guid _specId = _serviceProxy.Create(spec);

Create the plumber required resource object
RequiredResource plumberReq = new RequiredResource
{
    ResourceId = userResponse.UserId,   // assume current user is the plumber
    ResourceSpecId = _specId
};

Create the service for the equipment
Service plumberService = new Service
{
    Name = "Plumber 1",
    Duration = 60,
    InitialStatusCode = new OptionSetValue(1),
    Granularity = "FREQ=MINUTELY;INTERVAL=15;",
    ResourceSpecId = new EntityReference(ResourceSpec.EntityLogicalName, _specId)
};
Guid _plumberServiceId = _serviceProxy.Create(plumberService);

Create the van required resource object
RequiredResource vanReq = new RequiredResource
{
    ResourceId = _vanId,
    ResourceSpecId = _specId
};

Create the appointment request
AppointmentRequest appointmentReq = new AppointmentRequest
{
    RequiredResources = new RequiredResource[] { vanReq },
    Direction = SearchDirection.Backward,
    Duration = 60,
    NumberOfResults = 10,
    ServiceId = _plumberServiceId,
    // The search window describes the time when the resouce can be scheduled.
    // It must be set.
    SearchWindowStart = DateTime.Now.ToUniversalTime(),
    SearchWindowEnd = DateTime.Now.AddDays(7).ToUniversalTime(),
    UserTimeZoneCode = 1
};

Verify that the resources have been scheduled
SearchRequest search = new SearchRequest
{
    AppointmentRequest = appointmentReq
};
SearchResponse searched = (SearchResponse)_serviceProxy.Execute(search);

Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

    // Get the current user's information.
    WhoAmIRequest userRequest = new WhoAmIRequest();
    WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);

    // Create the van resource.
    Equipment van = new Equipment
    {
        Name = "Van 1",
        TimeZoneCode = 1,
        BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId)
    };

    Guid _vanId = _serviceProxy.Create(van);


    // Create the contraints for creating the plumber resource group
    System.Text.StringBuilder builder = new System.Text.StringBuilder("<Constraints>");
    builder.Append("<Constraint>");
    builder.Append("<Expression>");
    builder.Append("<Body>resource[\"Id\"] == ");
    builder.Append(userResponse.UserId.ToString("B"));
    builder.Append(" || resource[\"Id\"] == ");
    builder.Append(_vanId.ToString("B"));
    builder.Append("</Body>");
    builder.Append("<Parameters>");
    builder.Append("<Parameter name=\"resource\" />");
    builder.Append("</Parameters>");
    builder.Append("</Expression>");
    builder.Append("</Constraint>");
    builder.Append("</Constraints>");

    // Define an anonymous type to define the possible constraint based group type code values.
    var ConstraintBasedGroupTypeCode = new
    {
        Static = 0,
        Dynamic = 1,
        Implicit = 2
    };
    // Create the plumber resource group.
    ConstraintBasedGroup group = new ConstraintBasedGroup
    {
        BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId),
        Name = "Plumber with Van 1",
        Constraints = builder.ToString(),
        GroupTypeCode = new OptionSetValue(ConstraintBasedGroupTypeCode.Static),
    };
    Guid _groupId = _serviceProxy.Create(group);


    // Create the resource specification.
    ResourceSpec spec = new ResourceSpec
    {
        BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, userResponse.BusinessUnitId),
        ObjectiveExpression = @"
    <Expression>
   <Body>udf ""Random""(factory,resource,appointment,request,leftoffset,rightoffset)</Body>
   <Parameters>
   <Parameter name=""factory"" />
   <Parameter name=""resource"" />
   <Parameter name=""appointment"" />
   <Parameter name=""request"" />
   <Parameter name=""leftoffset"" />
   <Parameter name=""rightoffset"" />
   </Parameters>
   <Properties EvaluationInterval=""P0D"" evaluationcost=""0"" />
    </Expression>",
        RequiredCount = 1,
        Name = "Test Spec",
        GroupObjectId = _groupId
    };
    Guid _specId = _serviceProxy.Create(spec);

    // Create the plumber required resource object.
    RequiredResource plumberReq = new RequiredResource
    {
        ResourceId = userResponse.UserId,   // assume current user is the plumber
        ResourceSpecId = _specId
    };

    // Create the service for the equipment.
    Service plumberService = new Service
    {
        Name = "Plumber 1",
        Duration = 60,
        InitialStatusCode = new OptionSetValue(1),
        Granularity = "FREQ=MINUTELY;INTERVAL=15;",
        ResourceSpecId = new EntityReference(ResourceSpec.EntityLogicalName, _specId)
    };

    Guid _plumberServiceId = _serviceProxy.Create(plumberService);

    // Create the van required resource object.
    RequiredResource vanReq = new RequiredResource
    {
        ResourceId = _vanId,
        ResourceSpecId = _specId
    };

    // Create the appointment request.
    AppointmentRequest appointmentReq = new AppointmentRequest
    {
        RequiredResources = new RequiredResource[] { vanReq },
        Direction = SearchDirection.Backward,
        Duration = 60,
        NumberOfResults = 10,
        ServiceId = _plumberServiceId,
        // The search window describes the time when the resouce can be scheduled.
        // It must be set.
        SearchWindowStart = DateTime.Now.ToUniversalTime(),
        SearchWindowEnd = DateTime.Now.AddDays(7).ToUniversalTime(),
        UserTimeZoneCode = 1
    };

    // Verify that the resources have been scheduled              
    SearchRequest search = new SearchRequest
    {
        AppointmentRequest = appointmentReq
    };
    SearchResponse searched = (SearchResponse)_serviceProxy.Execute(search);
}

Thursday, 3 May 2012

Code to create Letter Entity record in CRM 2011


In this article , I am going to explain how to create Letter entity record

For Better Understanding I divided this article in three parts
(i)      Retrieve the Contact records
(ii)     Create an Activity Party record for each Contact
(iii)    Create Letter Activity

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;

Retrieve the Contact records
List<Contact> contacts = (from c in orgContext.CreateQuery<Contact>()
                            where c.Address1_City == "chandigarh"
                            select new Contact
                            {
                                ContactId = c.ContactId,
                                FirstName = c.FirstName,
                                LastName = c.LastName
                            }).ToList<Contact>();

Create an Activity Party record for each Contact
var activityParty1 = new ActivityParty
{
    PartyId = new EntityReference(Contact.EntityLogicalName,
        contacts[0].ContactId.Value),
};

var activityParty2 = new ActivityParty
{
    PartyId = new EntityReference(Contact.EntityLogicalName,
        contacts[1].ContactId.Value),
};

var activityParty3 = new ActivityParty
{
    PartyId = new EntityReference(Contact.EntityLogicalName,
        contacts[2].ContactId.Value),
};

Create Letter Activity
var letter = new Letter
{
    RegardingObjectId = new EntityReference(Contact.EntityLogicalName,
        contacts[2].ContactId.Value),
    Subject = "Activity Letter ",
    ScheduledEnd = DateTime.Now + TimeSpan.FromDays(5),
    Description = @"Greetings, Mr. XYZ,

                    This is a sample letter activity .

                    Sincerely,
                    ABC Co.",
    From = new ActivityParty[] { activityParty1 },
    To = new ActivityParty[] { activityParty3, activityParty2 }
};
orgContext.AddObject(letter);
orgContext.SaveChanges();

Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());


    OrganizationServiceContext orgContext =
        new OrganizationServiceContext(_serviceProxy);

    // Retrieve the Contact records .
    List<Contact> contacts = (from c in orgContext.CreateQuery<Contact>()
                                where c.Address1_City == "chandigarh"
                                select new Contact
                                {
                                    ContactId = c.ContactId,
                                    FirstName = c.FirstName,
                                    LastName = c.LastName
                                }).ToList<Contact>();

    // Create an Activity Party record for each Contact.
    var activityParty1 = new ActivityParty
    {
        PartyId = new EntityReference(Contact.EntityLogicalName,
            contacts[0].ContactId.Value),
    };

    var activityParty2 = new ActivityParty
    {
        PartyId = new EntityReference(Contact.EntityLogicalName,
            contacts[1].ContactId.Value),
    };

    var activityParty3 = new ActivityParty
    {
        PartyId = new EntityReference(Contact.EntityLogicalName,
            contacts[2].ContactId.Value),
    };


    // Create Letter Activity and set From and To fields to the
    // respective Activity Party entities.
    var letter = new Letter
    {
        RegardingObjectId = new EntityReference(Contact.EntityLogicalName,
            contacts[2].ContactId.Value),
        Subject = "Activity Letter ",
        ScheduledEnd = DateTime.Now + TimeSpan.FromDays(5),
        Description = @"Greetings, Mr. XYZ,

                        This is a sample letter activity.

                        Sincerely,
                        ABC Co.",
        From = new ActivityParty[] { activityParty1 },
        To = new ActivityParty[] { activityParty3, activityParty2 }
    };
    orgContext.AddObject(letter);
    orgContext.SaveChanges();
}


Tuesday, 1 May 2012

Code to create Fax Entity record in CRM 2011


In this article , I am going to explain how to Create Fax Entity record

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Crm.Sdk.Messages;

Code to create Fax Entity

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

    // Get the current user.
    WhoAmIRequest userRequest = new WhoAmIRequest();
    WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
    Guid _userId = userResponse.UserId;

    // Create the activity party for sending and receiving the fax.
    ActivityParty party = new ActivityParty
    {
        PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
    };

    // Create the fax object.
    Fax fax = new Fax
    {
        Subject = "Sample Fax",
        From = new ActivityParty[] { party },
        To = new ActivityParty[] { party }
    };
    Guid _faxId = _serviceProxy.Create(fax);

}

Create and attach attachment to Email Template in CRM 2011


In this article , I am going to explain how to Create and attach attachment to Email Template


For Better Understanding I divided this article in two parts
(i)      Create Email Template
(ii)     Attach attachments to email Template


Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Crm.Sdk.Messages;
using System.Collections.Generic;

Create Email Template
Template emailTemplate = new Template
{
    Title = "An example email template",
    Subject = "This is an example email.",
    IsPersonal = false,
    TemplateTypeCode = "lead",

    //1033 is the code for US English - you may need to change this value
    //depending on your locale.
    LanguageCode = 1033

};
Guid _emailTemplateId = _serviceProxy.Create(emailTemplate);

Attach attachments to email Template
ActivityMimeAttachment attachment = new ActivityMimeAttachment
{
    Subject = String.Format("Attachment {0}", i),
    FileName = String.Format("ExampleAttachment{0}.txt", i),
    Body = "Some Text",
    ObjectId = new EntityReference(Template.EntityLogicalName, _emailTemplateId),
    ObjectTypeCode = Template.EntityLogicalName
};

_templateAttachmentIds.Add(_serviceProxy.Create(attachment));

Complete Source Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                serverConfig.HomeRealmUri,
                                                serverConfig.Credentials,
                                                serverConfig.DeviceCredentials))
{
    // This statement is required to enable early-bound type support.
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

    // Create Email Template.
    Template emailTemplate = new Template
    {
        Title = "An example email template",
        Subject = "This is an example email.",
        IsPersonal = false,
        TemplateTypeCode = "lead",

        //1033 is the code for US English - you may need to change this value
        //depending on your locale.
        LanguageCode = 1033

    };
    Guid _emailTemplateId = _serviceProxy.Create(emailTemplate);

    //Attach attachments to email Template
    List<Guid> _templateAttachmentIds = new List<Guid>();
    for (int i = 0; i < 3; i++)
    {
        ActivityMimeAttachment attachment = new ActivityMimeAttachment
        {
            Subject = String.Format("Attachment {0}", i),
            FileName = String.Format("ExampleAttachment{0}.txt", i),
            Body = "Some Text",
            ObjectId = new EntityReference(Template.EntityLogicalName, _emailTemplateId),
            ObjectTypeCode = Template.EntityLogicalName
        };

        _templateAttachmentIds.Add(_serviceProxy.Create(attachment));
    }

}



Code to Create Update , Retrieve and Delete Email Attachment in CRM 2011


In this article , I am going to explain how to Create Update , Retrieve and Delete Email Attachment


For Better Understanding I divided this article in multiple part
(i)      Create Email Activity
(ii)     Create an e-mail attachment
(iii)     Retrieve an attachment
(iv)     Update attachment
(v)      Retrieve all attachments associated with the email activity
(vi)     Delete Attachment


Namespace need to include 
using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;


Create Email Activity
Email email = new Email

{
    Subject = "This is an example email",
    ActivityId = Guid.NewGuid()
};
Guid _emailId = _serviceProxy.Create(email);


Create an e-mail attachment
ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment

{
    ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
    ObjectTypeCode = Email.EntityLogicalName,
    Subject = String.Format("Sample Attachment {0}", i),
    Body = System.Convert.ToBase64String(
            new ASCIIEncoding().GetBytes("Example Attachment")),
    FileName = String.Format("ExampleAttachment{0}.txt", i)
};

_emailAttachmentId[i] = _serviceProxy.Create(_sampleAttachment);


Retrieve an attachment
ActivityMimeAttachment _singleAttachment =

    (ActivityMimeAttachment)_serviceProxy.Retrieve(
                                ActivityMimeAttachment.EntityLogicalName,
                                _emailAttachmentId[0],
                                new ColumnSet("activitymimeattachmentid",
                                    "subject",
                                    "filename",
                                    "body"));


Update an attachment
_singleAttachment.FileName = "ExampleAttachmentUpdated.txt";

_serviceProxy.Update(_singleAttachment);


Retrieve all attachments associated with the email activity

QueryExpression _attachmentQuery = new QueryExpression
{
    EntityName = ActivityMimeAttachment.EntityLogicalName,
    ColumnSet = new ColumnSet("activitymimeattachmentid"),
    Criteria = new FilterExpression
    {
        Conditions =
        {
            new ConditionExpression
            {
                AttributeName = "objectid",
                Operator = ConditionOperator.Equal,
                Values = {_emailId}
            },
            new ConditionExpression
            {
                AttributeName = "objecttypecode",
                Operator = ConditionOperator.Equal,
                Values = {Email.EntityLogicalName}
            }
        }
    }
};

EntityCollection results = _serviceProxy.RetrieveMultiple(
    _attachmentQuery);


Delete an Attachment
_serviceProxy.Delete(ActivityMimeAttachment.EntityLogicalName, _emailAttachmentId[0]);

Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,

                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

    // Create Email Activity
    Email email = new Email
    {
        Subject = "This is an example email",
        ActivityId = Guid.NewGuid()
    };
    Guid _emailId = _serviceProxy.Create(email);


    Guid[] _emailAttachmentId = new Guid[3];
    // Create three e-mail attachments
    for (int i = 0; i < 3; i++)
    {
        ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment
        {
            ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
            ObjectTypeCode = Email.EntityLogicalName,
            Subject = String.Format("Sample Attachment {0}", i),
            Body = System.Convert.ToBase64String(
                    new ASCIIEncoding().GetBytes("Example Attachment")),
            FileName = String.Format("ExampleAttachment{0}.txt", i)
        };

        _emailAttachmentId[i] = _serviceProxy.Create(_sampleAttachment);
    }

                   

    // Retrieve an attachment including its id, subject, filename and body.
    ActivityMimeAttachment _singleAttachment =
        (ActivityMimeAttachment)_serviceProxy.Retrieve(
                                    ActivityMimeAttachment.EntityLogicalName,
                                    _emailAttachmentId[0],
                                    new ColumnSet("activitymimeattachmentid",
                                        "subject",
                                        "filename",
                                        "body"));


    // Update attachment
    _singleAttachment.FileName = "ExampleAttachmentUpdated.txt";
    _serviceProxy.Update(_singleAttachment);


    // Retrieve all attachments associated with the email activity.
    QueryExpression _attachmentQuery = new QueryExpression
    {
        EntityName = ActivityMimeAttachment.EntityLogicalName,
        ColumnSet = new ColumnSet("activitymimeattachmentid"),
        Criteria = new FilterExpression
        {
            Conditions =
            {
                new ConditionExpression
                {
                    AttributeName = "objectid",
                    Operator = ConditionOperator.Equal,
                    Values = {_emailId}
                },
                new ConditionExpression
                {
                    AttributeName = "objecttypecode",
                    Operator = ConditionOperator.Equal,
                    Values = {Email.EntityLogicalName}
                }
            }
        }
    };

    EntityCollection results = _serviceProxy.RetrieveMultiple(
        _attachmentQuery);

    // Delete an Attachment
    _serviceProxy.Delete(ActivityMimeAttachment.EntityLogicalName, _emailAttachmentId[0]);
}


Code to create Custom Activity and Attributes in CRM 2011



In this article , I am going to explain how to Create Custom Activity Entity and Attribute


For Better Understanding I divided this article in two part
(i)      Create the custom activity entity
(ii)     Add attributes to the custom activity entity


Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

Create the custom activity entity
CreateEntityRequest request = new CreateEntityRequest

{
    HasNotes = true,
    HasActivities = false,
    PrimaryAttribute = new StringAttributeMetadata
    {
        SchemaName = "Subject",
        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
        MaxLength = 100,
        DisplayName = new Label("Subject", 1033)
    },
    Entity = new EntityMetadata
    {
        IsActivity = true,
        SchemaName = customEntityName,
        DisplayName = new Label("Instant Message", 1033),
        DisplayCollectionName = new Label("Instant Messages", 1033),
        OwnershipType = OwnershipTypes.UserOwned,
        IsAvailableOffline = true,

    }
};

_serviceProxy.Execute(request);



Add an attribute to the custom activity entity
CreateAttributeRequest fontFamilyAttributeRequest =

    new CreateAttributeRequest
    {
        EntityName = customEntityName,
        Attribute = new StringAttributeMetadata
        {
            SchemaName = prefix + "fontfamily",
            DisplayName = new Label("Font Family", 1033),
            MaxLength = 100
        }
    };
CreateAttributeResponse fontFamilyAttributeResponse =
    (CreateAttributeResponse)_serviceProxy.Execute(
    fontFamilyAttributeRequest);

Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,

                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

                 
    String prefix = "new_";
    String customEntityName = prefix + "instantmessage";

    // Create the custom activity entity.
    CreateEntityRequest request = new CreateEntityRequest
    {
        HasNotes = true,
        HasActivities = false,
        PrimaryAttribute = new StringAttributeMetadata
        {
            SchemaName = "Subject",
            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
            MaxLength = 100,
            DisplayName = new Label("Subject", 1033)
        },
        Entity = new EntityMetadata
        {
            IsActivity = true,
            SchemaName = customEntityName,
            DisplayName = new Label("Instant Message", 1033),
            DisplayCollectionName = new Label("Instant Messages", 1033),
            OwnershipType = OwnershipTypes.UserOwned,
            IsAvailableOffline = true,

        }
    };

    _serviceProxy.Execute(request);

    //Entity must be published

    // Add few attributes to the custom activity entity.
    CreateAttributeRequest fontFamilyAttributeRequest =
        new CreateAttributeRequest
        {
            EntityName = customEntityName,
            Attribute = new StringAttributeMetadata
            {
                SchemaName = prefix + "fontfamily",
                DisplayName = new Label("Font Family", 1033),
                MaxLength = 100
            }
        };
    CreateAttributeResponse fontFamilyAttributeResponse =
        (CreateAttributeResponse)_serviceProxy.Execute(
        fontFamilyAttributeRequest);

    CreateAttributeRequest fontColorAttributeRequest =
        new CreateAttributeRequest
        {
            EntityName = customEntityName,
            Attribute = new StringAttributeMetadata
            {
                SchemaName = prefix + "fontcolor",
                DisplayName = new Label("Font Color", 1033),
                MaxLength = 50
            }
        };
    CreateAttributeResponse fontColorAttributeResponse =
        (CreateAttributeResponse)_serviceProxy.Execute(
        fontColorAttributeRequest);

    CreateAttributeRequest fontSizeAttributeRequest =
        new CreateAttributeRequest
        {
            EntityName = customEntityName,
            Attribute = new IntegerAttributeMetadata
            {
                SchemaName = prefix + "fontSize",
                DisplayName = new Label("Font Size", 1033)
            }
        };
    CreateAttributeResponse fontSizeAttributeResponse =
        (CreateAttributeResponse)_serviceProxy.Execute(
        fontSizeAttributeRequest);
}


Create , Validate and Close Incident and Appointment in CRM 2011


In this article , I am going to explain how to Create , Validate and Close Incident and Appointment.

For Better Understanding I divided this article in multiple part
(i)      Create an incident
(ii)     Create an appointment
(iii)    Validate the Appointment state transition
(iv)    Close the appointment
(v)     Validate the Incident state transition.
(vi)    Create the incident's resolution and Close the incident with the resolution.

Namespace need to include 

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;


Code to Create an incident

var incident = new Incident
{
    CustomerId = new EntityReference(Account.EntityLogicalName, _accountId),
    Title = "Sample Incident"
};
Guid _incidentId = _serviceProxy.Create(incident);


Code to  Create an appointment

var appointment = new Appointment
{
    ScheduledStart = DateTime.Now,
    ScheduledEnd = DateTime.Now.Add(new TimeSpan(0, 30, 0)),
    Subject = "Sample 30-minute Appointment",
    RegardingObjectId = new EntityReference(Incident.EntityLogicalName,
        _incidentId)
};
Guid _appointmentId = _serviceProxy.Create(appointment);


Code to Validate the Appointment state transition

var isAppointmentValidRequest = new IsValidStateTransitionRequest
{
    Entity = new EntityReference(Appointment.EntityLogicalName, _incidentId),
    NewState = "1", //Completed
    NewStatus = 3 //Completed
};
var isAppointmentValidResponse =
    (IsValidStateTransitionResponse)_serviceProxy.Execute(isAppointmentValidRequest);


Code to  Close the appointment

var setAppointmentStateReq = new SetStateRequest
{
    EntityMoniker = new EntityReference(Appointment.EntityLogicalName,
        _appointmentId),
    State = new OptionSetValue(1), //Completed
    Status = new OptionSetValue(3) //Completed
};

_serviceProxy.Execute(setAppointmentStateReq);


Code to Validate the Incident state transition.

var isIncidentValidRequest = new IsValidStateTransitionRequest
{
    Entity = new EntityReference(Incident.EntityLogicalName, _incidentId),
    NewState = "1", //Resolver
    NewStatus =5 //ProblemSolved
};
var isIncidentValidResponse =
    (IsValidStateTransitionResponse)_serviceProxy.Execute(isIncidentValidRequest);


Code to  Create the incident's resolution and Close the incident with the resolution

var incidentResolution = new IncidentResolution
{
    Subject = "Resolved Sample Incident",
    IncidentId = new EntityReference(Incident.EntityLogicalName, _incidentId)
};

// Close the incident with the resolution.
var closeIncidentRequest = new CloseIncidentRequest
{
    IncidentResolution = incidentResolution,
    Status = new OptionSetValue(5) //ProblemSolved
};
_serviceProxy.Execute(closeIncidentRequest);

Complete Source Code

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(
    serverConfig.OrganizationUri,
    serverConfig.HomeRealmUri,
    serverConfig.Credentials,
    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(
        new ProxyTypesBehavior());
    Guid _accountId = new Guid("ffbb6e3f-ccfe-4d84-90d9-421418b03a8e");

    // Create an incident.
    var incident = new Incident
    {
        CustomerId = new EntityReference(Account.EntityLogicalName, _accountId),
        Title = "Sample Incident"
    };
    Guid _incidentId = _serviceProxy.Create(incident);


    // Create a 30-minute appointment regarding the incident.
    var appointment = new Appointment
    {
        ScheduledStart = DateTime.Now,
        ScheduledEnd = DateTime.Now.Add(new TimeSpan(0, 30, 0)),
        Subject = "Sample 30-minute Appointment",
        RegardingObjectId = new EntityReference(Incident.EntityLogicalName,
            _incidentId)
    };
    Guid _appointmentId = _serviceProxy.Create(appointment);


    // Validate the Appointment state transition.
    var isAppointmentValidRequest = new IsValidStateTransitionRequest
    {
        Entity = new EntityReference(Appointment.EntityLogicalName, _incidentId),
        NewState = "1", //Completed
        NewStatus = 3 //Completed
    };
    var isAppointmentValidResponse =
        (IsValidStateTransitionResponse)_serviceProxy.Execute(isAppointmentValidRequest);


    if (isAppointmentValidResponse.IsValid)
    {
        // Close the appointment.
        var setAppointmentStateReq = new SetStateRequest
        {
            EntityMoniker = new EntityReference(Appointment.EntityLogicalName,
                _appointmentId),
            State = new OptionSetValue(1), //Completed
            Status = new OptionSetValue(3) //Completed
        };

        _serviceProxy.Execute(setAppointmentStateReq);
    }


    // Validate the Incident state transition.
    var isIncidentValidRequest = new IsValidStateTransitionRequest
    {
        Entity = new EntityReference(Incident.EntityLogicalName, _incidentId),
        NewState = "1", //Resolver
        NewStatus =5 //ProblemSolved
    };
    var isIncidentValidResponse =
        (IsValidStateTransitionResponse)_serviceProxy.Execute(isIncidentValidRequest);


    if (isIncidentValidResponse.IsValid)
    {
        // Create the incident's resolution.
        var incidentResolution = new IncidentResolution
        {
            Subject = "Resolved Sample Incident",
            IncidentId = new EntityReference(Incident.EntityLogicalName, _incidentId)
        };

        // Close the incident with the resolution.
        var closeIncidentRequest = new CloseIncidentRequest
        {
            IncidentResolution = incidentResolution,
            Status = new OptionSetValue(5) //ProblemSolved
        };
        _serviceProxy.Execute(closeIncidentRequest);
    }

}



Creating and Distributing Campaign with Dynamic and Static List in CRM 2011


In this Article, I am going to explain how to create Campaign and Associate Campaign with Static and Dynamic List

For Better Understanding I divided this article in four part
(i)    Code to create campaign
(ii)   Create and Associate Dynamics List to campaign
(iii)  Create and Associate Static List to campaign
(iv)   Distribute a campaign

Namespace need to Include

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;



Code to create campaign

     // Create a campaign.
     Campaign campaign = new Campaign()
     {
       Name = "Sample Campaign"
     };
     Guid _campaignId = _serviceProxy.Create(campaign);
     campaign.Id = _campaignId;



Code to create and Associate Dynamics List to campaign

     //Create Dynamic List

     String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                               <entity name='account'>
                               <attribute name='name' />
                               <attribute name='address1_city' />
                               <attribute name='primarycontactid' />
                               <attribute name='telephone1' />
                               <attribute name='accountid' />
                               <order attribute='name' descending='false' />
                               <filter type='and'>
                               <condition attribute='address1_city' operator='eq' value='chandigarh' />
                               </filter>
                               </entity>
                           </fetch>";

    // Create dynamic list. Set the type to true to declare a dynamic
    // list.
    List dynamicList = new List()
    {
       Type = true,
       ListName = "Dynamic List",
       CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account),
       Query = fetchXml
    };
    Guid _dynamicListId = _serviceProxy.Create(dynamicList);
    dynamicList.Id = _dynamicListId;

    //Associate dynamic list to campaign

    // Add the dynamic list to the campaign.
    AddItemCampaignRequest addListToCampaignRequest =
                        new AddItemCampaignRequest()
                        {
                            CampaignId = _campaignId,
                            EntityId = _dynamicListId,
                            EntityName = List.EntityLogicalName,
                        };
   _serviceProxy.Execute(addListToCampaignRequest);

   // Create a campaign activity to distribute fax to the list members.
   CampaignActivity campaignActivity = new CampaignActivity()
   {
       Subject = "Sample Campaign Activity",
       ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax),
       RegardingObjectId = campaign.ToEntityReference()
   };
   Guid _campaignActivityId = _serviceProxy.Create(campaignActivity);

   // Add dynamic list to campaign activity.
   AddItemCampaignActivityRequest addListToCampaignActivityRequest =
                new AddItemCampaignActivityRequest()
   {
      CampaignActivityId = _campaignActivityId,
      ItemId = _dynamicListId,
      EntityName = List.EntityLogicalName
   };
   _serviceProxy.Execute(addListToCampaignActivityRequest);



Code to create and Associate Static List to campaign

   // Add the static list to the campaign.
   AddItemCampaignRequest addStaticListToCampaignRequest =
                        new AddItemCampaignRequest()
   {
       CampaignId = _campaignId,
       EntityId = _staticListId,
       EntityName = List.EntityLogicalName
   };
   _serviceProxy.Execute(addStaticListToCampaignRequest);

   // Add the static list to the campaign activity.
   AddItemCampaignActivityRequest addStaticListToCampaignActivityRequest =
                        new AddItemCampaignActivityRequest()
   {
     CampaignActivityId = _campaignActivityId,
     ItemId = _staticListId,
     EntityName = List.EntityLogicalName
   };
   _serviceProxy.Execute(addStaticListToCampaignActivityRequest);



Code to Distribute a campaign

   // Create a fax.
   Fax fax = new Fax()
   {
     Subject = "Example Fax"
   };

   // Distribute the campaign activity to the marketing lists.
   DistributeCampaignActivityRequest distributeRequest =
                        new DistributeCampaignActivityRequest()
                        {
                            CampaignActivityId = _campaignActivityId,
                            Activity = fax,
                            Owner = new EntityReference("systemuser", _salesManagerId),
                            Propagate = true,
                            SendEmail = false,
                            PostWorkflowEvent = true
                        };
   _serviceProxy.Execute(distributeRequest);



Complete Code

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
              serverConfig.HomeRealmUri,
              serverConfig.Credentials,
              serverConfig.DeviceCredentials))
{
     _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

     // Retrieve a sales manager.
     Guid _salesManagerId = new Guid("ffbb6e3f-ccfe-4d84-90d9-421418b03a8e");
     Guid _accountId = new Guid("9fbb2e3f-ggfe-4d84-90d9-423245b03a8e");

     // Create a campaign.
     Campaign campaign = new Campaign()
     {
       Name = "Sample Campaign"
     };
     Guid _campaignId = _serviceProxy.Create(campaign);
     campaign.Id = _campaignId;

     //Create Dynamic List

     String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                               <entity name='account'>
                               <attribute name='name' />
                               <attribute name='address1_city' />
                               <attribute name='primarycontactid' />
                               <attribute name='telephone1' />
                               <attribute name='accountid' />
                               <order attribute='name' descending='false' />
                               <filter type='and'>
                               <condition attribute='address1_city' operator='eq' value='chandigarh' />
                               </filter>
                               </entity>
                           </fetch>";

    // Create dynamic list. Set the type to true to declare a dynamic
    // list.
    List dynamicList = new List()
    {
       Type = true,
       ListName = "Dynamic List",
       CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account),
       Query = fetchXml
    };
    Guid _dynamicListId = _serviceProxy.Create(dynamicList);
    dynamicList.Id = _dynamicListId;

    //Associate dynamic list to campaign

    // Add the dynamic list to the campaign.
    AddItemCampaignRequest addListToCampaignRequest =
                        new AddItemCampaignRequest()
                        {
                            CampaignId = _campaignId,
                            EntityId = _dynamicListId,
                            EntityName = List.EntityLogicalName,
                        };
   _serviceProxy.Execute(addListToCampaignRequest);

   // Create a campaign activity to distribute fax to the list members.
   CampaignActivity campaignActivity = new CampaignActivity()
   {
       Subject = "Sample Campaign Activity",
       ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax),
       RegardingObjectId = campaign.ToEntityReference()
   };
   Guid _campaignActivityId = _serviceProxy.Create(campaignActivity);

   // Add dynamic list to campaign activity.
   AddItemCampaignActivityRequest addListToCampaignActivityRequest =
                new AddItemCampaignActivityRequest()
   {
      CampaignActivityId = _campaignActivityId,
      ItemId = _dynamicListId,
      EntityName = List.EntityLogicalName
   };
   _serviceProxy.Execute(addListToCampaignActivityRequest);




  // Associate static list to campaign

  // Copy the dynamic list to a static list.
  CopyDynamicListToStaticRequest copyRequest =
                new CopyDynamicListToStaticRequest()
   {
        ListId = _dynamicListId
   };
   CopyDynamicListToStaticResponse copyResponse =
                        (CopyDynamicListToStaticResponse)_serviceProxy.Execute(copyRequest);
   Guid _staticListId = copyResponse.StaticListId;

   // Add the static list to the campaign.
   AddItemCampaignRequest addStaticListToCampaignRequest =
                        new AddItemCampaignRequest()
   {
       CampaignId = _campaignId,
       EntityId = _staticListId,
       EntityName = List.EntityLogicalName
   };
   _serviceProxy.Execute(addStaticListToCampaignRequest);

   // Add the static list to the campaign activity.
   AddItemCampaignActivityRequest addStaticListToCampaignActivityRequest =
                        new AddItemCampaignActivityRequest()
   {
     CampaignActivityId = _campaignActivityId,
     ItemId = _staticListId,
     EntityName = List.EntityLogicalName
   };
   _serviceProxy.Execute(addStaticListToCampaignActivityRequest);


   // Create a fax.
   Fax fax = new Fax()
   {
     Subject = "Example Fax"
   };

   // Distribute the campaign activity to the marketing lists.
   DistributeCampaignActivityRequest distributeRequest =
                        new DistributeCampaignActivityRequest()
                        {
                            CampaignActivityId = _campaignActivityId,
                            Activity = fax,
                            Owner = new EntityReference("systemuser", _salesManagerId),
                            Propagate = true,
                            SendEmail = false,
                            PostWorkflowEvent = true
                        };
   _serviceProxy.Execute(distributeRequest);
}

Creating and Distributing Quick Campaign in CRM 2011


In this article , I am going to explain , how to create and distribute Quick Campaign .

There are two method of Creating Campaign
(i)  Using List Class
(ii) Using Query Expression


First Method : Code to Create Quick Campaign with marketing list as input

   List newList = new List()
   {
     ListName = "TestList",
     CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account)
   };
   Guid _newListId = _serviceProxy.Create(newList);

   for (int j = 0; j < 5; j++)
   {
      AddMemberListRequest addMemberListRequest = new AddMemberListRequest();
      addMemberListRequest.EntityId = _accountIdArray[j];
      addMemberListRequest.ListId = _newListId;
      AddMemberListResponse addMemberListResponse =
      _serviceProxy.Execute(addMemberListRequest) as AddMemberListResponse;
   }

   //Create the request object from input parameters
   CreateActivitiesListRequest request = new CreateActivitiesListRequest()
   {
      Activity = new Letter()
      {
          Subject = "qcCreatedLetterActivity"
      },
      ListId = _newListId,
      OwnershipOptions = PropagationOwnershipOptions.ListMemberOwner,
      Propagate = true,
      TemplateId = Guid.Empty,
      FriendlyName = "Quick Campaign for My List",
      Owner = new EntityReference("systemuser", _currentUser),
      PostWorkflowEvent = true ;

   //Execute the request
   CreateActivitiesListResponse response = (CreateActivitiesListResponse)_serviceProxy.Execute(request);
   Guid BOId = response.BulkOperationId;



Second Method : Code to Create Quick Campaign with Query Expression as input

   QueryExpression query = new QueryExpression("account");
   query.ColumnSet = new ColumnSet("accountid");
   query.Criteria = new FilterExpression();
   FilterExpression filter = query.Criteria.AddFilter(LogicalOperator.Or);
   for (int j = 0; j < 5; j++)
   {
     filter.AddCondition("accountid", ConditionOperator.Equal, _accountIdArray[j]);
   }
                 
   // create the bulkoperation
   PropagateByExpressionRequest qrequest = new PropagateByExpressionRequest()
   {
       Activity = new Email()
            {
               Subject = "qcCreatedEmailActivity"
            },
       ExecuteImmediately = false, // Default value.
       FriendlyName = "Query Based Quick Campaign",
       OwnershipOptions = PropagationOwnershipOptions.ListMemberOwner,
       QueryExpression = query,
       Owner = new EntityReference("systemuser", _currentUser),
       PostWorkflowEvent = true,
       SendEmail = false,
       TemplateId = Guid.Empty
   };

   PropagateByExpressionResponse qresponse =
                        (PropagateByExpressionResponse)_serviceProxy.Execute(qrequest);

   Guid bulkOpId = response.BulkOperationId;



Complete Sample Code

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
              serverConfig.HomeRealmUri,
              serverConfig.Credentials,
              serverConfig.DeviceCredentials))
{
   _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

   WhoAmIRequest whoRequest = new WhoAmIRequest();
   Guid _currentUser = ((WhoAmIResponse)_serviceProxy.Execute(whoRequest)).UserId;

   // Create accounts on which we want to run Quick Campaign
   Guid[] _accountIdArray = new Guid[5];
   for (int i = 0; i < 5; i++)
   {
      Account acct = new Account()
      {
           Name = "Account For Quick Campaign " + i.ToString()
      };
      _accountIdArray[i] = _serviceProxy.Create(acct);
   }


   // Run a Quick Campaign with marketing list as input/
   List newList = new List()
   {
     ListName = "TestList",
     CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account)
   };
   Guid _newListId = _serviceProxy.Create(newList);

   for (int j = 0; j < 5; j++)
   {
      AddMemberListRequest addMemberListRequest = new AddMemberListRequest();
      addMemberListRequest.EntityId = _accountIdArray[j];
      addMemberListRequest.ListId = _newListId;
      AddMemberListResponse addMemberListResponse =
      _serviceProxy.Execute(addMemberListRequest) as AddMemberListResponse;
   }

   //Create the request object from input parameters
   CreateActivitiesListRequest request = new CreateActivitiesListRequest()
   {
      Activity = new Letter()
      {
          Subject = "qcCreatedLetterActivity"
      },
      ListId = _newListId,
      OwnershipOptions = PropagationOwnershipOptions.ListMemberOwner,
      Propagate = true,
      TemplateId = Guid.Empty,
      FriendlyName = "Quick Campaign for My List",
      Owner = new EntityReference("systemuser", _currentUser),
      PostWorkflowEvent = true
   ;

   //Execute the request
   CreateActivitiesListResponse response = (CreateActivitiesListResponse)_serviceProxy.Execute(request);
   Guid BOId = response.BulkOperationId;

                 

   // Run a Quick Campaign with a list of accounts as input

   // Construct a Query Expression(QE) which specifies which records QC should include              
   QueryExpression query = new QueryExpression("account");
   query.ColumnSet = new ColumnSet("accountid");
   query.Criteria = new FilterExpression();
   FilterExpression filter = query.Criteria.AddFilter(LogicalOperator.Or);
   for (int j = 0; j < 5; j++)
   {
     filter.AddCondition("accountid", ConditionOperator.Equal, _accountIdArray[j]);
   }
                 
   // create the bulkoperation
   PropagateByExpressionRequest qrequest = new PropagateByExpressionRequest()
   {
       Activity = new Email()
            {
               Subject = "qcCreatedEmailActivity"
            },
       ExecuteImmediately = false, // Default value.
       FriendlyName = "Query Based Quick Campaign",
       OwnershipOptions = PropagationOwnershipOptions.ListMemberOwner,
       QueryExpression = query,
       Owner = new EntityReference("systemuser", _currentUser),
       PostWorkflowEvent = true,
       SendEmail = false,
       TemplateId = Guid.Empty
   };

   PropagateByExpressionResponse qresponse =
                        (PropagateByExpressionResponse)_serviceProxy.Execute(qrequest);

   Guid bulkOpId = response.BulkOperationId;
}

Code to convert Opportunity to a Quote, then convert a Quote to a Sales Order and a Sales Order to an Invoice in CRM 2011

In this article , I am going to explain, how to convert Opportunity to a Quote, then convert a Quote to a Sales Order and a Sales Order to an Invoice

For better understanding , i divided code into three parts

(i)   Convert Opportunity to Quote
(ii)  Convert Quote to Sales Order
(iii) Convert Sales Order to Invoice 


Namespace need to include

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;



Convert Opportunity to Quote

 Guid _opportunityId = new Guid("ffbb6e3f-ccfe-4d84-90d9-421418b03a8e");

     // Close the opportunity as won
     var winOppRequest = new WinOpportunityRequest
     {
        OpportunityClose = new OpportunityClose
        {
           OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId)
        },
        Status = new OptionSetValue((int)opportunity_statuscode.Won),
     };
     _serviceProxy.Execute(winOppRequest);



     // Convert the opportunity to a quote
     var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest
     {
         OpportunityId = _opportunityId,
         ColumnSet = new ColumnSet("quoteid", "name")
     };
     var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse)
     _serviceProxy.Execute(genQuoteFromOppRequest);
     Quote quote = genQuoteFromOppResponse.Entity.ToEntity<Quote>();
     Guid _quoteId = quote.Id;

     // Set the quote's product
     Guid _productId = new Guid("eebb6e3f-ccfe-4d84-90d9-421418b03a8e");
     Guid _defaultUnitId = new Guid("mmbb6e3f-ccfe-4d84-90d9-421418b03a8e");

     QuoteDetail quoteDetail = new QuoteDetail()
     {
        ProductId = new EntityReference(Product.EntityLogicalName,
                            _productId),
        Quantity = 1,
        QuoteId = quote.ToEntityReference(),
        UoMId = new EntityReference(UoM.EntityLogicalName,
                            _defaultUnitId)
     };
     Guid _quoteDetailId = _serviceProxy.Create(quoteDetail);

     // Activate the quote
     SetStateRequest activateQuote = new SetStateRequest()
     {
        EntityMoniker = quote.ToEntityReference(),
        State = new OptionSetValue((int)QuoteState.Active),
        Status = new OptionSetValue((int)quote_statuscode.InProgress)
     };
     _serviceProxy.Execute(activateQuote);

     // Mark the quote as won
     // Note: this is necessary in order to convert a quote into a 
     // SalesOrder.
     WinQuoteRequest winQuoteRequest = new WinQuoteRequest()
     {
         QuoteClose = new QuoteClose()
         {
             Subject = "Quote Close" + DateTime.Now.ToString(),
             QuoteId = quote.ToEntityReference()
         },
         Status = new OptionSetValue(-1)
     };
     _serviceProxy.Execute(winQuoteRequest);




Convert Quote to Sales Order

     ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount");

     ConvertQuoteToSalesOrderRequest convertQuoteRequest =
                        new ConvertQuoteToSalesOrderRequest()
                        {
                            QuoteId = _quoteId,
                            ColumnSet = salesOrderColumns
                        };
     ConvertQuoteToSalesOrderResponse convertQuoteResponse =
                        (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest);
     SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity;
     Guid _salesOrderId = salesOrder.Id;


     Guid _priceListItemId = new Guid("eebb6e3f-ccfe-4d84-90d9-421418b03a8e");
     // Retrieve current price list
     ProductPriceLevel priceListItem =
                        (ProductPriceLevel)_serviceProxy.Retrieve(ProductPriceLevel.EntityLogicalName,
                            _priceListItemId, new ColumnSet("productpricelevelid", "amount"));

     // Update the price list
     priceListItem.Amount = new Money(30.0M);

     UpdateRequest updatePriceListItem = new UpdateRequest()
     {
          Target = priceListItem,
     };
     _serviceProxy.Execute(updatePriceListItem);

     // Retrieve the order
     SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve(
                            SalesOrder.EntityLogicalName,_salesOrderId,new ColumnSet("salesorderid", "totalamount")
                        );

     // Unlock the order pricing
     UnlockSalesOrderPricingRequest unlockOrderRequest =new UnlockSalesOrderPricingRequest()
                        {
                            SalesOrderId = _salesOrderId
                        };
     _serviceProxy.Execute(unlockOrderRequest);

     // Retrieve the order
     updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName,
                            _salesOrderId,  new ColumnSet("salesorderid", "totalamount") );

    // Relock the order pricing
    LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest()
                        {
                            SalesOrderId = _salesOrderId
                        };
    _serviceProxy.Execute(lockOrderRequest);




Convert Sales Order to Invoice  

ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount");

    // Convert the order to an invoice
    ConvertSalesOrderToInvoiceRequest convertOrderRequest =  new ConvertSalesOrderToInvoiceRequest()
                                {
                                  SalesOrderId = _salesOrderId,
                                  ColumnSet = invoiceColumns
                                 };
    ConvertSalesOrderToInvoiceResponse convertOrderResponse =
                        (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest);
    Invoice invoice = (Invoice)convertOrderResponse.Entity;
    Guid _invoiceId = invoice.Id;


    // Retrieve current price list
    priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve(ProductPriceLevel.EntityLogicalName,
                            _priceListItemId,new ColumnSet("productpricelevelid", "amount"));

    // Lock the invoice pricing
    LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest()
                               {
                                 InvoiceId = _invoiceId
                                };
    _serviceProxy.Execute(lockInvoiceRequest);


    // Update the price list
    priceListItem.Amount = new Money(40.0M);

    updatePriceListItem = new UpdateRequest()
    {
        Target = priceListItem
    };
    _serviceProxy.Execute(updatePriceListItem);


    // Retrieve the invoice
    Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve(
                            Invoice.EntityLogicalName,
                            _invoiceId, new ColumnSet("invoiceid", "totalamount"));

    // Unlock the invoice pricing
    UnlockInvoicePricingRequest unlockInvoiceRequest =  new UnlockInvoicePricingRequest()
                        {
                            InvoiceId = _invoiceId
                        };
    _serviceProxy.Execute(unlockInvoiceRequest);

    // Retrieve the invoice
    updatedInvoice = (Invoice)_serviceProxy.Retrieve(Invoice.EntityLogicalName,
                            _invoiceId,
                            new ColumnSet("invoiceid", "totalamount"));



Complete Code

using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
             serverConfig.HomeRealmUri,
             serverConfig.Credentials,
             serverConfig.DeviceCredentials))
{
     _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

     Guid _opportunityId = new Guid("ffbb6e3f-ccfe-4d84-90d9-421418b03a8e");

     // Close the opportunity as won
     var winOppRequest = new WinOpportunityRequest
     {
        OpportunityClose = new OpportunityClose
        {
           OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId)
        },
        Status = new OptionSetValue((int)opportunity_statuscode.Won),
     };
     _serviceProxy.Execute(winOppRequest);



     // Convert the opportunity to a quote
     var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest
     {
         OpportunityId = _opportunityId,
         ColumnSet = new ColumnSet("quoteid", "name")
     };
     var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse)
     _serviceProxy.Execute(genQuoteFromOppRequest);
     Quote quote = genQuoteFromOppResponse.Entity.ToEntity<Quote>();
     Guid _quoteId = quote.Id;

     // Set the quote's product
     Guid _productId = new Guid("eebb6e3f-ccfe-4d84-90d9-421418b03a8e");
     Guid _defaultUnitId = new Guid("mmbb6e3f-ccfe-4d84-90d9-421418b03a8e");

     QuoteDetail quoteDetail = new QuoteDetail()
     {
        ProductId = new EntityReference(Product.EntityLogicalName,
                            _productId),
        Quantity = 1,
        QuoteId = quote.ToEntityReference(),
        UoMId = new EntityReference(UoM.EntityLogicalName,
                            _defaultUnitId)
     };
     Guid _quoteDetailId = _serviceProxy.Create(quoteDetail);

     // Activate the quote
     SetStateRequest activateQuote = new SetStateRequest()
     {
        EntityMoniker = quote.ToEntityReference(),
        State = new OptionSetValue((int)QuoteState.Active),
        Status = new OptionSetValue((int)quote_statuscode.InProgress)
     };
     _serviceProxy.Execute(activateQuote);

     // Mark the quote as won
     // Note: this is necessary in order to convert a quote into a 
     // SalesOrder.
     WinQuoteRequest winQuoteRequest = new WinQuoteRequest()
     {
         QuoteClose = new QuoteClose()
         {
             Subject = "Quote Close" + DateTime.Now.ToString(),
             QuoteId = quote.ToEntityReference()
         },
         Status = new OptionSetValue(-1)
     };
     _serviceProxy.Execute(winQuoteRequest);




     // Define columns to be retrieved after creating the order
     ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount");

     ConvertQuoteToSalesOrderRequest convertQuoteRequest =
                        new ConvertQuoteToSalesOrderRequest()
                        {
                            QuoteId = _quoteId,
                            ColumnSet = salesOrderColumns
                        };
     ConvertQuoteToSalesOrderResponse convertQuoteResponse =
                        (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest);
     SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity;
     Guid _salesOrderId = salesOrder.Id;


     Guid _priceListItemId = new Guid("eebb6e3f-ccfe-4d84-90d9-421418b03a8e");
     // Retrieve current price list
     ProductPriceLevel priceListItem =
                        (ProductPriceLevel)_serviceProxy.Retrieve(ProductPriceLevel.EntityLogicalName,
                            _priceListItemId, new ColumnSet("productpricelevelid", "amount"));

     // Update the price list
     priceListItem.Amount = new Money(30.0M);

     UpdateRequest updatePriceListItem = new UpdateRequest()
     {
          Target = priceListItem,
     };
     _serviceProxy.Execute(updatePriceListItem);

     // Retrieve the order
     SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve(
                            SalesOrder.EntityLogicalName,_salesOrderId,new ColumnSet("salesorderid", "totalamount")
                        );

     // Unlock the order pricing
     UnlockSalesOrderPricingRequest unlockOrderRequest =new UnlockSalesOrderPricingRequest()
                        {
                            SalesOrderId = _salesOrderId
                        };
     _serviceProxy.Execute(unlockOrderRequest);

     // Retrieve the order
     updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName,
                            _salesOrderId,  new ColumnSet("salesorderid", "totalamount") );

    // Relock the order pricing
    LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest()
                        {
                            SalesOrderId = _salesOrderId
                        };
    _serviceProxy.Execute(lockOrderRequest);


    // Define columns to be retrieved after creating the invoice
    ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount");

    // Convert the order to an invoice
    ConvertSalesOrderToInvoiceRequest convertOrderRequest =  new ConvertSalesOrderToInvoiceRequest()
                                {
                                  SalesOrderId = _salesOrderId,
                                  ColumnSet = invoiceColumns
                                 };
    ConvertSalesOrderToInvoiceResponse convertOrderResponse =
                        (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest);
    Invoice invoice = (Invoice)convertOrderResponse.Entity;
    Guid _invoiceId = invoice.Id;


    // Retrieve current price list
    priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve(ProductPriceLevel.EntityLogicalName,
                            _priceListItemId,new ColumnSet("productpricelevelid", "amount"));

    // Lock the invoice pricing
    LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest()
                               {
                                 InvoiceId = _invoiceId
                                };
    _serviceProxy.Execute(lockInvoiceRequest);


    // Update the price list
    priceListItem.Amount = new Money(40.0M);

    updatePriceListItem = new UpdateRequest()
    {
        Target = priceListItem
    };
    _serviceProxy.Execute(updatePriceListItem);


    // Retrieve the invoice
    Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve(
                            Invoice.EntityLogicalName,
                            _invoiceId, new ColumnSet("invoiceid", "totalamount"));

    // Unlock the invoice pricing
    UnlockInvoicePricingRequest unlockInvoiceRequest =  new UnlockInvoicePricingRequest()
                        {
                            InvoiceId = _invoiceId
                        };
    _serviceProxy.Execute(unlockInvoiceRequest);

    // Retrieve the invoice
    updatedInvoice = (Invoice)_serviceProxy.Retrieve(Invoice.EntityLogicalName,
                            _invoiceId,
                            new ColumnSet("invoiceid", "totalamount"));
}