Tuesday, 30 August 2016

alternativekeys and upsert in mscrm2016

UPser Functionality Using  in Mscrm 2015
===================================================================

if the record is  dere in database  it will update if record is not presented it will  create record in mscrm2016


Entity Accounts = new Entity("new_event");
     
        Accounts.KeyAttributes = new KeyAttributeCollection
        {
            {"new_valueb", "RAVIs" }
        };
        Accounts.Attributes["new_name"] = "DemoValues";
       // service.Update(Accounts);
        var request = new UpsertRequest() { Target = Accounts };
        var response = (UpsertResponse)service.Execute(request);

AlternativeKeys2015

AlternativeKeys in Mscrm Example Demo
=============================================

Entity Accounts = new Entity("new_event");
     
        Accounts.KeyAttributes = new KeyAttributeCollection
        {
            {"new_valueb", "RAVI" }
        };
        Accounts.Attributes["new_name"] = "DemoValues";
        service.Update(Accounts);

Saturday, 20 August 2016

Multiple Retrieve in MSCRM


Multiple retrieve Examples in MSCRM using WebAPPI
=====================================================================


function AccountOnLoad() {
    var Id = Xrm.Page.data.entity.getId().substring(1, 37); //remove braces
    var entity = "contacts";
    //note here we need to use _accounted_value instead of parentcustomerid
    var columnSet = "?$select=firstname&$filter=_accountid_value eq " + Id + "&$count=true";
    retrieveentityCollection(entity, columnSet);
}

function retrieveentityCollection(entity, options) {
    var serverURL = Xrm.Page.context.getClientUrl();
    var Query = entity + options;
    var req = new XMLHttpRequest();
    req.open("GET", serverURL + "/api/data/v8.0/" + Query, true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                var data = JSON.parse(this.response);
                if (data['@odata.count'] != null)
                    Xrm.Page.getAttribute("numberofemployees").setValue(data['@odata.count']); //we are displaying it in out of the box number o employee field
            } else {
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };
    req.send();
}

Passing Inputparameters to Actions in MSCRM using WebAPI


Actions Input parameters:Inpuparams, Inputparameters1 are single line Text Parameters in MSCRM
=======================================================================



function ActionsDemos() {
    debugger;
    var data = {
        "InputParams": "Welcome to Actons Practice",
        "Inputparams1": "SUCCessful Parameters Passed"
    };

    customaction(data);
}


function customaction( dt) {
    debugger;
    var Id = Xrm.Page.data.entity.getId().substring(1, 37);
    var serverURL = Xrm.Page.context.getClientUrl();

    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/api/data/v8.0/accounts(" + Id + ")/Microsoft.Dynamics.CRM.new_SampleActions", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                debugger;
                var data = JSON.parse(this.response);
            //    if (data['Inputparams1'] != null)  //output parameters
              //      alert(data['Inputparams1']);
            } else {
                debugger;
                //var error = JSON.parse(this.response).error; // error out Mssages
                //alert(error.message);
            }
        }
    };
    req.send(window.JSON.stringify(dt));
}

Actions Calling With WebApi EXamples

Calling Actions Using Java scripts:
=============================================================
Out parameter Approved Data Type Equals to Boolean Type  bounded with Event Enttiy and Output Response We will get.


function Callcustomaction() {
    debugger;
    var Id = Xrm.Page.data.entity.getId().substring(1, 37);
    var serverURL = Xrm.Page.context.getClientUrl();

    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/api/data/v8.0/new_events(" + Id + ")/Microsoft.Dynamics.CRM.new_DemActions", true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                debugger;
                var data = JSON.parse(this.response);
                if (data['Aprroved'] != null)
                    alert(data['Aprroved']);
            } else {
                debugger;
                var error = JSON.parse(this.response).error;
                alert(error.message);
            }
        }
    };
    req.send();
}

Action to Create Contact Records



Actions Demo



Monday, 8 August 2016

Odata Queries For Practices In MScrm


/MSCRM2013/xrmservices/2011/OrganizationData.svc/new_courseSet?$select=new_Amount,new_available,new_courseId,new_durations,new_Fee,new_name,new_Paymentdate,new_Test&$filter=new_courseId eq guid'5666666666666'



/MSCRM2013/xrmservices/2011/OrganizationData.svc/new_courseSet?$select=new_Amount,new_available,new_courseId,new_durations,new_Fee,new_name,new_Paymentdate,new_Test&$filter=new_Test/Id eq guid'7887777'-----lookupe



OrganizationData.svc/new_courseSet?$select=new_Amount,new_available,new_courseId,new_durations,new_Fee,new_name,new_Paymentdate,new_Test&$filter=new_durations/Value eq 100000001----optionset


http:///MSCRM2013/xrmservices/2011/OrganizationData.svc/new_courseSet?$select=new_Amount,new_available,new_courseId,new_durations,new_Fee,new_name,new_Paymentdate,new_Test&$filter=new_available eq true  twooptionsetvalus


/xrmservices/2011/OrganizationData.svc/new_courseSet?$select=new_Amount,new_available,new_courseId,new_durations,new_Fee,new_name,new_Paymentdate,new_Test&$filter=new_name eq 'rrrrrr'


/MSCRM2013/xrmservices/2011/OrganizationData.svc/new_courseSet?$select=new_Amount,new_available,new_courseId,new_durations,new_Fee,new_name,new_Paymentdate,new_Test&$filter=new_Amount/Value eq 6789----money




/MSCRM2013/xrmservices/2011/OrganizationData.svc/new_courseSet?$select=new_Amount,new_available,new_courseId,new_durations,new_Fee,new_name,new_Paymentdate,new_Test&$filter=new_Paymentdate eq datetime'2016-04-05T12:00:00'----date and


/MSCRM2013/xrmservices/2011/OrganizationData.svc/new_courseSet?$filter=new_Fee eq 6789

Sunday, 7 August 2016

SDK.Rest Examples Practices

SDK.Rest Examples Practices
______________________________________________________________________________


if (typeof (MscrmAplications) == "undefined") {
    MscrmAplications = { _namespace: true };
}
MscrmAplications.Studentonload =
{
    CreateRecord: function () {
        debugger;
        var student = {};
        student.new_name = "DemoExample";// string
        student.new_courseName = "MSCRMTechnologies";// string values
        student.new_CourseDuration = { Value: 100000001 }; // optionset values
        student.new_Gender = false;//Two OptionSetvalues
        student.new_Fee = { Value: "60000" }; // currency  field
        var dt = new Date(2015, 9, 8);
        student.new_startdate = dt; // date and time  field
        student.new_TotalSudents = 200;// whole numbers
        student.new_Amount = "6.2";// floating point
        student.new_Hieght = "9.9"; //decimal

        student.new_Student = { Id: "F3397DD5-1458-E611-80F1-C4346BDD3121", LogicalName: "new_students", Name: "StudentC" };//lookupvalues

        SDK.REST.createRecord(student, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage);
    },

    UpdateRecords: function () {

        debugger;
        if (Xrm.Page.data.entity.getId() != null) {

            var RecordId = Xrm.Page.data.entity.getId()

            if (Xrm.Page.getAttribute("new_demos").getValue() != null) {
                var Opts = Xrm.Page.getAttribute("new_demos").getValue()
                if (Opts == 100000000) {
                    var student = {};
                    student.new_name = "DemoExample";// string
                    student.new_courseName = "MSCRMTechnologies";// string values
                    student.new_CourseDuration = { Value: 100000002 }; // optionset values
                    student.new_Gender = false;//Two OptionSetvalues
                    student.new_Fee = { Value: "60000" }; // currency  field
                    var dt = new Date(2015, 9, 8);
                    student.new_startdate = dt; // date and time  field
                    student.new_TotalSudents = 900;// whole numbers
                    student.new_Amount = "1.1";// floating point
                    student.new_Hieght = "8.9"; //decimal

                    student.new_Student = { Id: "364010EF-1458-E611-80F1-C4346BDD3121", LogicalName: "new_students", Name: "StudentB" };//lookupvalues

                    SDK.REST.updateRecord(RecordId, student, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage);
                }

                else if (Opts == 100000002) {
                    debugger;
                    SDK.REST.deleteRecord(RecordId, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage)

                }
                else if (Opts == 100000003) {
                    debugger;

                }
            }

        }
    },
    sucessful: function () {
        alert("sucessfuly excuted");
    },
    errormessage: function () {
        alert("Error Occured here");
    },

    _namespace: true
};

create record using Javascript using SDK.Rest examples

///=================================================================================
// creation  records  using mscrm2016 application
// created  by Ravi Jaala on august 5th 2016
//===============================================================

if (typeof (MscrmAplications) == "undefined") {
    MscrmAplications = { _namespace: true };
}
MscrmAplications.Studentonload =
{
    CreateRecord: function () {
        debugger;
        var student = {};
        student.new_name = "DemoExample";// string
        student.new_courseName = "MSCRMTechnologies";// string values
        student.new_CourseDuration = { Value: 100000001 }; // optionset values
        student.new_Gender = false;//Two OptionSetvalues
        student.new_Fee = { Value: "60000" }; // currency  field
        var dt = new Date(2015, 9, 8);
        student.new_startdate = dt; // date and time  field
        student.new_TotalSudents = 200;// whole numbers
        student.new_Amount = "6.2";// floating point
        student.new_Hieght = "9.9"; //decimal

        student.new_Student = { Id: "F3397DD5-1458-E611-80F1-C4346BDD3121", LogicalName: "new_students", Name: "StudentC" };//lookupvalues

        SDK.REST.createRecord(student, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage);
    },

    UpdateRecords: function () {

        debugger;
        if (Xrm.Page.data.entity.getId() != null) {

            var RecordId = Xrm.Page.data.entity.getId()

            if (Xrm.Page.getAttribute("new_demos").getValue() != null) {
                var Opts = Xrm.Page.getAttribute("new_demos").getValue()
                if (Opts == 100000000) {
                    var student = {};
                    student.new_name = "DemoExample";// string
                    student.new_courseName = "MSCRMTechnologies";// string values
                    student.new_CourseDuration = { Value: 100000002 }; // optionset values
                    student.new_Gender = false;//Two OptionSetvalues
                    student.new_Fee = { Value: "60000" }; // currency  field
                    var dt = new Date(2015, 9, 8);
                    student.new_startdate = dt; // date and time  field
                    student.new_TotalSudents = 900;// whole numbers
                    student.new_Amount = "1.1";// floating point
                    student.new_Hieght = "8.9"; //decimal

                    student.new_Student = { Id: "364010EF-1458-E611-80F1-C4346BDD3121", LogicalName: "new_students", Name: "StudentB" };//lookupvalues

                    SDK.REST.updateRecord(RecordId, student, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage);
                }

                else if (Opts == 100000002) {
                    debugger;
                    SDK.REST.deleteRecord(RecordId, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage)

                }
                else if (Opts == 100000003) {
                    debugger;

                }
            }

        }
    },

    RetrievRecords: function () {

        debugger;
        if (Xrm.Page.data.entity.getId() != null) {
            var RecordId = Xrm.Page.data.entity.getId()

            if (Xrm.Page.getAttribute("new_course").getValue() != null) {

                var lookup = Xrm.Page.getAttribute("new_course").getValue();
                var Id = lookup[0].id;

                SDK.REST.retrieveRecord(Id, "new_course", null, null, MscrmAplications.Studentonload.sucessfulrestrieve, MscrmAplications.Studentonload.errormessage)

            }

        }
    },

    sucessful: function () {
        alert("sucessfuly excuted");
    },
    errormessage: function () {
        alert("Error Occured here");
    },

    sucessfulrestrieve: function (results) {
        debugger;
     
        alert(results.new_name + "" + results.new_Fee.Value + "" + results.new_courseName);
     
    },

    _namespace: true
};








create record using Javascript using SDK.Rest examples

//=================================================================================
// creation  records  using mscrm2016 application
// created  by Ravi Jaala on august 5th 2016
//===============================================================

if (typeof (MscrmAplications) == "undefined") {
    MscrmAplications = { _namespace: true };
}
MscrmAplications.Studentonload =
{
    CreateRecord: function () {
        debugger;
        var student = {};
        student.new_name = "DemoExample";// string
        student.new_courseName = "MSCRMTechnologies";// string values
        student.new_CourseDuration = { Value: 100000001 }; // optionset values
        student.new_Gender = false;//Two OptionSetvalues
        student.new_Fee = { Value: "60000" }; // currency  field
        var dt = new Date(2015, 9, 8);
        student.new_startdate = dt; // date and time  field
        student.new_TotalSudents = 200;// whole numbers
        student.new_Amount = "6.2";// floating point
        student.new_Hieght = "9.9"; //decimal

        student.new_Student = { Id: "F3397DD5-1458-E611-80F1-C4346BDD3121", LogicalName: "new_students", Name: "StudentC" };//lookupvalues

        SDK.REST.createRecord(student, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage);
    },
    sucessful: function () {
        alert("sucessfuly excuted");
    },
    errormessage: function () {
        alert("Error Occured here");
    },

    _namespace: true
};



create record using Javascript using SDK.Rest examples

//=================================================================================
// creation  records  using mscrm2016 application
// created  by Ravi Jaala on august 5th 2016
//===============================================================

if (typeof (MscrmAplications) == "undefined") {
    MscrmAplications = { _namespace: true };
}
MscrmAplications.Studentonload =
{
    CreateRecord: function () {
        debugger;
        var student = {};
        student.new_name = "DemoExample";// string
        student.new_courseName = "MSCRMTechnologies";// string values
        student.new_CourseDuration = { Value: 100000001 }; // optionset values
        student.new_Gender = false;//Two OptionSetvalues
        student.new_Fee = { Value: "60000" }; // currency  field
        var dt = new Date(2015, 9, 8);
        student.new_startdate = dt; // date and time  field
        student.new_TotalSudents = 200;// whole numbers
        student.new_Amount = "6.2";// floating point
        student.new_Hieght = "9.9"; //decimal

        student.new_Student = { Id: "F3397DD5-1458-E611-80F1-C4346BDD3121", LogicalName: "new_students", Name: "StudentC" };//lookupvalues

        SDK.REST.createRecord(student, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage);
    },
    sucessful: function () {
        alert("sucessfuly excuted");
    },
    errormessage: function () {
        alert("Error Occured here");
    },

    _namespace: true
};



create record using Javascript using SDK.Rest examples

//=================================================================================
// creation  records  using mscrm2016 application
// created  by Ravi Jaala on august 5th 2016
//===============================================================

if (typeof (MscrmAplications) == "undefined") {
    MscrmAplications = { _namespace: true };
}
MscrmAplications.Studentonload =
{
    CreateRecord: function () {
        debugger;
        var student = {};
        student.new_name = "DemoExample";// string
        student.new_courseName = "MSCRMTechnologies";// string values
        student.new_CourseDuration = { Value: 100000001 }; // optionset values
        student.new_Gender = false;//Two OptionSetvalues
        student.new_Fee = { Value: "60000" }; // currency  field
        var dt = new Date(2015, 9, 8);
        student.new_startdate = dt; // date and time  field
        student.new_TotalSudents = 200;// whole numbers
        student.new_Amount = "6.2";// floating point
        student.new_Hieght = "9.9"; //decimal

        student.new_Student = { Id: "F3397DD5-1458-E611-80F1-C4346BDD3121", LogicalName: "new_students", Name: "StudentC" };//lookupvalues

        SDK.REST.createRecord(student, "new_course", MscrmAplications.Studentonload.sucessful, MscrmAplications.Studentonload.errormessage);
    },
    sucessful: function () {
        alert("sucessfuly excuted");
    },
    errormessage: function () {
        alert("Error Occured here");
    },

    _namespace: true
};

Monday, 1 August 2016

QueryExpressions in MSCRM

QueryExpressions with MSCRM using multiple Condtions
_____________________________________________________________________________


public EntityCollection getAllContacts(IOrganizationService Service, Guid accountNumbers)
        {
            EntityCollection EntityResult = new EntityCollection();
            Entity contract = new Entity();
            QueryExpression Query = new QueryExpression()
            {
                ColumnSet = new ColumnSet("ownerid","new_fullname"),
                EntityName = "contract",
                Criteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression("customercode", ConditionOperator.Equal, accountNumbers),                                      
                        new ConditionExpression("statecode", ConditionOperator.Equal, 2),
                        new ConditionExpression("new_flag", ConditionOperator.Equal,false)
                    }
                }
            };

            EntityResult = Service.RetrieveMultiple(Query);
            return EntityResult;
        }

---------------------------------------------------------------------------------------------
single Condtion In QueryExpression in MSCRM



ColumnSet Columns = new ColumnSet("new_region", "new_country", "new_state", "name");
        QueryExpression parentAccounts = new QueryExpression()
               {
                   EntityName = "new_EntitySchemaName",
                   ColumnSet = Columns,
                   Criteria =
                   {
                       Conditions =
                    {
                        new ConditionExpression
                            {
                                 AttributeName = "new_accountnumber",
                                 Operator = ConditionOperator.Equal,
                                 Values = {"1EDH897"}
                            }
                    }
                   }
               };
        EntityCollection Results = service.RetrieveMultiple(parentAccounts);


--------------------------------------------------------------------------------------------------------
Muiltiple Conditions with QueryExpressions In MSCRM
-----------------------------------------------------------------------------------------------------------------
 public EntityCollection Contractdetails(IOrganizationService service, Entity entityname, ColumnSet colunms)
        {
            EntityCollection ContractDetals;
            //ColumnSet colunms = new ColumnSet("new_billtype");
            QueryExpression query = new QueryExpression()
            {
                EntityName = "entityname",
                ColumnSet = colunms,
                Criteria =
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression
                        {
                         
                            AttributeName = "new_opportunityid",
                            Operator = ConditionOperator.Equal,
                            Values = {((EntityReference)result.Attributes["new_opportunityid"]).Id}
                        },
                        new ConditionExpression
                        {
                         
                            AttributeName="statecode",
                            Operator = ConditionOperator.Equal,
                            Values={0}
                        },
                        new ConditionExpression
                        {
                         
                            AttributeName="new_Titlesubtype",
                            Operator = ConditionOperator.Equal,
                            Values={3}
                        }
                    }
                }
            };
            ContractDetals = service.RetrieveMultiple(query);
            return ContractDetals;
        }


QueryExpressions in MSCRM

QueryExpressions with MSCRM using multiple Condtions
_____________________________________________________________________________


public EntityCollection getAllContacts(IOrganizationService Service, Guid accountNumbers)
        {
            EntityCollection EntityResult = new EntityCollection();
            Entity contract = new Entity();
            QueryExpression Query = new QueryExpression()
            {
                ColumnSet = new ColumnSet("ownerid","new_fullname"),
                EntityName = "contract",
                Criteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression("customercode", ConditionOperator.Equal, accountNumbers),                                      
                        new ConditionExpression("statecode", ConditionOperator.Equal, 2),
                        new ConditionExpression("new_flag", ConditionOperator.Equal,false)
                    }
                }
            };

            EntityResult = Service.RetrieveMultiple(Query);
            return EntityResult;
        }

---------------------------------------------------------------------------------------------
single Condtion In QueryExpression in MSCRM



ColumnSet Columns = new ColumnSet("new_region", "new_country", "new_state", "name");
        QueryExpression parentAccounts = new QueryExpression()
               {
                   EntityName = "new_EntitySchemaName",
                   ColumnSet = Columns,
                   Criteria =
                   {
                       Conditions =
                    {
                        new ConditionExpression
                            {
                                 AttributeName = "new_accountnumber",
                                 Operator = ConditionOperator.Equal,
                                 Values = {"1EDH897"}
                            }
                    }
                   }
               };
        EntityCollection Results = service.RetrieveMultiple(parentAccounts);


--------------------------------------------------------------------------------------------------------
Muiltiple Conditions with QueryExpressions In MSCRM
-----------------------------------------------------------------------------------------------------------------
 public EntityCollection Contractdetails(IOrganizationService service, Entity entityname, ColumnSet colunms)
        {
            EntityCollection ContractDetals;
            //ColumnSet colunms = new ColumnSet("new_billtype");
            QueryExpression query = new QueryExpression()
            {
                EntityName = "entityname",
                ColumnSet = colunms,
                Criteria =
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions =
                    {
                        new ConditionExpression
                        {
                         
                            AttributeName = "new_opportunityid",
                            Operator = ConditionOperator.Equal,
                            Values = {((EntityReference)result.Attributes["new_opportunityid"]).Id}
                        },
                        new ConditionExpression
                        {
                         
                            AttributeName="statecode",
                            Operator = ConditionOperator.Equal,
                            Values={0}
                        },
                        new ConditionExpression
                        {
                         
                            AttributeName="new_Titlesubtype",
                            Operator = ConditionOperator.Equal,
                            Values={3}
                        }
                    }
                }
            };
            ContractDetals = service.RetrieveMultiple(query);
            return ContractDetals;
        }


Mscrm Plugin to call the WebService Using C#

Mscrm Plugin to call WCF Service Using Custom bindings
--------------------------------------------------------------------------------------------

BasicHttpBinding myBinding = new BasicHttpBinding();
                myBinding.Name = "BasicHttpBinding_GetOpportunityDetails";
                myBinding.Security.Mode = BasicHttpSecurityMode.None;
                myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                EndpointAddress endPointAddress = new EndpointAddress("http://10.1980.89/LoginPortal/Services/LoginPortal.svc?wsdl");
                ServiceReference1.ConTractDetailsClient Case = new ServiceReference1.ConTractDetailsClient(myBinding, endPointAddress);
                string str = Case.UpdateStatus(CaseNumber, UpdateStatus, Comments, ContactName,
PhoneNumber);

-------------------------------------------------------------------------------------------

Mscrm to connect C#

Mscrm to connect Specific Organization by passing UserId and Pwd
--------------------------------------------------------------------------------------

 public IOrganizationService ConnectMSCRM( string UserId,string Pwd,string Url)
    {
        ClientCredentials cre = new ClientCredentials();
        cre.UserName.UserName = UserId;
        cre.UserName.Password = Pwd;
        Uri serviceUri = new Uri(Url);
        OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, cre, null);
        IOrganizationService service = (IOrganizationService)proxy;
        return service;
    }

-----------------------------------------------------------------------------------------------
Retrieving Data From Mscrm using C#


 ColumnSet attributes = new ColumnSet(new string[] { "new_name", "new_education", "new_courseid", "new_gender", "new_joindate" });
        Entity obj = service.Retrieve("new_test_a", new Guid("8CFADFE4-46C7-E511-80E2-3863BB3DEF88"), attributes);
        bool gg = Convert.ToBoolean(obj.Attributes["new_gender"]);
        string edname = ((Microsoft.Xrm.Sdk.OptionSetValue)(obj.Attributes["new_education"])).Value.ToString();
        string cc = ((Microsoft.Xrm.Sdk.EntityReference)(obj.Attributes["new_courseid"])).Name.ToString();



--------------------------------------------------------------------------------------------------------------------

Sample Plugin in MSCRM

public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(null);
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "email")
                {

                           ColumnSet attributes = new ColumnSet(new string[] { "description", "subject", "from" });
                            Entity emailEntity = service.Retrieve(entity.LogicalName, entity.Id, attributes);
                            if (emailEntity.Contains("description") && emailEntity.Attributes["description"] != null)
                            {
                                String htmlEmailBody = emailEntity.Attributes["description"].ToString();
                                emailSubject = emailEntity.Attributes["subject"].ToString();

                                EntityCollection Recipients = emailEntity.GetAttributeValue<EntityCollection>("from");

                                foreach (var party in Recipients.Entities)
                                {
                                    senderAddress = party.Attributes["addressused"].ToString();
                                }

                            }

                }

            }

        }









Friday, 29 January 2016

setRecordStatus



public static void SetState(Entity record, int stateCode, int statusCode, ITracingService trace, IOrganizationService service)
{
trace.Trace("Entered SetState Method");
trace.Trace(string.Format("LogicalName:{0}, StatusCode:{1}, StateCode:{2}", record.LogicalName, statusCode, stateCode));

// Create SetState Request
SetStateRequest setStateRequest = new SetStateRequest()
{
EntityMoniker = new EntityReference
{
Id = record.Id,
LogicalName = record.LogicalName
},
State = new OptionSetValue(stateCode),
Status = new OptionSetValue(statusCode)
};

// Execute the request
service.Execute(setStateRequest);

trace.Trace("Exiting SetStatus Method");
}