Friday, October 30, 2015

Sample CRUD Operations Using C# in MSCRM

Steps to Achieve:


  1. Create a console Application in Visual Studio and add (Microsoft.Crm.Sdk.Proxy.dll, Microsoft.Xrm.Sdk.dll) in references section.
  2. Download this C# Class files to get crm service ,If you have this files just skip this step https://www.dropbox.com/s/pyj6zym6u9ea7wp/deviceidmanager.cs?dl=0 https://www.dropbox.com/s/q82xp39jn0nqi0j/OnlineService.cs?dl=0
  3. Open OnlineService.cs file and enter your crm credentials as shown below
           ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = "Username@Domain.onmicrosoft.com";//Username
            credentials.UserName.Password = "yourpasswordhere";//Password
            var _servproxy = new OrganizationServiceProxy(new     Uri("https://Domain.api.crm5.dynamics.com/XRMServices/2011/Organization.svc"), null,   credentials, GetDeviceCredentials());//ServerUrl

Code Snippet:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;

namespace SampleCrudOperations
{
    class CrudOperations
    {
        public void CreateRecord()
        {
            IOrganizationService service = OnlineService.servproxy;//To get CRM Service
            if (service != null)
            {
                Entity myentity = new Entity("new_employee");
                myentity.Attributes["new_name"] = "Rahul";
                myentity.Attributes["new_ename"] = "Veldandi";
                myentity.Attributes["new_employeesalary"] = new Money(23000);//Currency
                myentity.Attributes["new_employeelocation"] = new OptionSetValue(100000003);//optionset
                myentity.Attributes["new_employeehobbies"] = "TV \n Playing Cricket";//MultiLineText
                myentity.Attributes["new_employeegender"] = false;//Two Options                myentity.Attributes["new_employeeaccount"] = new EntityReference("account", new Guid("A478321B-E44C-E511-8102-C4346BADA644"));//Lookup
                myentity.Attributes["new_department"] = new EntityReference("new_department", new Guid("E07CB8D2-6C50-E511-810E-C4346BAD5740"));//Lookup
                myentity.Attributes["createdon"] = new DateTime(2015, 09, 11);//Date Time
                service.Create(myentity);
                Console.WriteLine("Record Created Successfully");
            }
        }
        public void RetrieveRecord()
        {
            Entity et = OnlineService.servproxy.Retrieve("new_employee", new Guid("BF18416B-2E58-E511-810E-C4346BAD3768"), new ColumnSet(true));
            string name = et["new_name"].ToString();
            string hobbies = et["new_employeehobbies"].ToString();
            string account = et.GetAttributeValue<EntityReference>("new_employeeaccount").Name;
            string gender = et.FormattedValues["new_employeegender"].ToString();
            string location = et.FormattedValues["new_employeelocation"].ToString();
            string dept = et.GetAttributeValue<EntityReference>("new_department").Name;
            decimal sal = et.GetAttributeValue<Money>("new_employeesalary").Value;
            Console.WriteLine("employee Name:" + name);
            Console.WriteLine("employee hobbies:" + hobbies);
            Console.WriteLine("employee account" + account);
            Console.WriteLine("employee gender" + gender);
            Console.WriteLine("employee location" + location);
            Console.WriteLine("employee department" + dept);
            Console.WriteLine("employee salary" + sal);
        }
        public void UpdateRecord()
        {
            Entity myet = OnlineService.servproxy.Retrieve("new_employee", new Guid("BF18416B-2E58-E511-810E-C4346BAD3768"), new ColumnSet("new_employeesalary", "new_employeelocation", "new_employeeaccount", "new_employeehobbies"));
            Console.WriteLine("Enter Employee salary");
            decimal sal = Convert.ToDecimal(Console.ReadLine());
            myet["new_employeesalary"] = new Money(sal); ;
            myet["new_employeelocation"] = new OptionSetValue(100000002);
            myet["new_employeeaccount"] = new EntityReference("account", new Guid("9C78321B-E44C-E511-8102-C4346BADA644"));
            myet["new_employeehobbies"] = "Watching TV";
            OnlineService.servproxy.Update(myet);
            Console.WriteLine("Record Updated Successfully");
        }
        public void delete()
        {
            OnlineService.servproxy.Delete("new_employee", new Guid("24E6B2EF-7B57-E511-810A-C4346BADB280"));
            Console.WriteLine("Record Deleted Sucessfully");
        }
        public void multiretrive()
        {
            QueryExpression query = new QueryExpression();
            query.EntityName = "new_employee";
            query.ColumnSet = new ColumnSet(true);
            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            RetrieveMultipleResponse responce = (RetrieveMultipleResponse)OnlineService.servproxy.Execute(request);
            foreach (Entity emp in responce.EntityCollection.Entities)
            {
                string name = emp["new_name"].ToString();
                string hobbies = emp["new_employeehobbies"].ToString();
                string account = emp.GetAttributeValue<EntityReference>("new_employeeaccount").Name;
                string gender = emp.FormattedValues["new_employeegender"].ToString();
                string location = emp.FormattedValues["new_employeelocation"].ToString();
                string dept = string.Empty;
                if (emp.Attributes.Contains("new_department"))
                {
                    dept = emp.GetAttributeValue<EntityReference>("new_department").Name;
                }
                decimal sal = emp.GetAttributeValue<Money>("new_employeesalary").Value;
                Console.WriteLine("employee Name : " + name);
                Console.WriteLine("employee hobbies : " + hobbies);
                Console.WriteLine("employee account : " + account);
                Console.WriteLine("employee gender : " + gender);
                Console.WriteLine("employee location : " + location);
                Console.WriteLine("employee department : " + dept);
                Console.WriteLine("employee salary : " + sal);
            }
        }
    }
}

Finally Call all the methods in Program.cs file..Like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
namespace SampleCrudOperations
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Your Choice: C for Create , U for update  , D for delete");
            char ch =char.Parse(Console.ReadLine());
            switch (ch)
            {
                case 'c':
                    CrudOperations c = new CrudOperations();
                    c.create();
                    break;
                case 'u':
                    CrudOperations u = new CrudOperations();
                    u.update();
                    break;
                case 'd':
                    CrudOperations d = new CrudOperations();
                    d.delete();
                    break;
                default:
                    Console.WriteLine("Please Choose any one from given choices");
                    break;
            }
            Console.ReadLine();
        }
    }
}

Thank you.......

Sample CRUD Operations Using Javascript in MSCRM

function CreateRecords()
{
    XrmSvcToolkit.createRecord({
        entityName: "Contact",
        entity: { 
   FirstName: "Rahul", 
   LastName: "Veldandi", 
   Address1_City: "Hyderabad",
   new_AccountName:{Id:"A478321B-E44C-E511-8102-C4346BADA644",LogicalName:"account",Name:"A. Datum Corporation (sample)"},//Lookup
   PreferredContactMethodCode:{Value:1},//Optionset
   AnnualIncome:{Value:"15000"},//Currency
   ExchangeRate:"50.600",//Decimal
   new_Gender:false,//Two Options
   BirthDate:new Date(1995,02,08),//DateTime
   Address1_Telephone2:"9876543210"
},
        async: false,
        successCallback: function (result) {
            var contactId = result.ContactId;
            // Do here want you want with the result
            alert("record created");
        },
        errorCallback: function (error) {
alert(error.message)
            alert("Unable to create record");
        }
    });
}

function UpdateRecords()
{
    XrmSvcToolkit.updateRecord({
        entityName: "Contact",
id:"32A1B4ED-D95D-E511-810E-C4346BAD3768",
        entity: { 
Address1_City: "Hyderabad",
Address1_Telephone2:"9876543210",
AnnualIncome:{Value:"2,20,000"},
PreferredContactMethodCode:{Value:2}
},
        async: false,
        successCallback: function (result) {
            //Do here want you want with the result
            alert("record updated");
        },
        errorCallback: function (error) {
            alert("Failed to update record");
        }
    });
}

function DeleteRecords()
{
XrmSvcToolkit.deleteRecord({
        entityName: "Contact",
id:"FD6EC9BA-5E5B-E511-8110-C4346BAD26CC",
        async: false,
        successCallback: function (result) {
            //Do here want to want with the result
            alert("record deleted");
        },
        errorCallback: function (error) {
            alert("Failed to delete record");
        }
    });
}

function Retrieve()

var lookup;
var name;
var curencyfield;
var curency;
var decimal;
var phonnmbr;
var DOB;
var id = "32A1B4ED-D95D-E511-810E-C4346BAD3768"
XrmSvcToolkit.retrieve({
        entityName: "Contact",
id:id,
/*select:["FirstName","LastName", "Address1_City", "Address1_Telephone2"],*/
        async: false,
        successCallback: function (result) {
lookup= Xrm.Page.getAttribute("new_accountname").getValue();
name= lookup[0].name;
            curency=Xrm.Page.getAttribute("annualincome").getValue();
             decimal=Xrm.Page.getAttribute("exchangerate").getValue();
           DOB=Xrm.Page.getAttribute("birthdate").getValue();
             alert("FirstName : "+result.FirstName+"\nLastName : "+result.LastName+"\ncity : "+result.Address1_City+"\nTeliphone number : "+result.Address1_Telephone2+"\nAccountname : "+name+"\nAnnual Income : "+curency+"\nExchange Rate : "+decimal+"\nDate Of Borth : "+DOB) 
        },
        errorCallback: function (error) {
            alert("Unable to retrieve record");
        }
    });
}

function multiretrieve()
{
    XrmSvcToolkit.retrieveMultiple({
        entityName: "Contact",
       odataQuery:"?$select=FirstName,LastName,Address1_City,new_AccountName,PreferredContactMethodCode,AnnualIncome,ExchangeRate,new_Gender,BirthDate,Address1_Telephone2&$filter=new_AccountName/Id eq guid'A478321B-E44C-E511-8102-C4346BADA644'",
        async: false,
        successCallback: function (results) {
alert("records retrieved");
var str = "";
            for (var i = 0;i<results.length; i++) 
            {
                str += "Name: "+results[i].FirstName+ "\n\n";
            }
            alert(str);
        },
        errorCallback: function (error) {
            alert("Unable to retrieve records..Please Try Again");
        }
    });
}

function multiretrievel()
{
    XrmSvcToolkit.retrieveMultiple({
        entityName: "Contact",
       odataQuery:"?$select=FirstName,LastName&$filter=new_AccountName/Id eq guid'A478321B-E44C-E511-8102-C4346BADA644'",
        async: false,
        successCallback: function (results) {
alert("records retrieved");
var str = "";
            for (var i = 0;i<results.length; i++) 
            {
                str += "Full Name :"+results[i].FirstName+"  "+results[i].LastName+"\n";
            }
            alert(str);
        },
        errorCallback: function (error) {
            alert("There was an error when retrieving the AccountSubgrid records\n"+error);
        }
    });
}

Export, prepare to edit, and import the ribbon in MSCRM

Dynamics CRM 2015

Applies To: CRM 2015 on-prem, CRM Online

To edit the ribbon, you must perform the following steps:
  1. Export the ribbon
  2. Prepare to edit the XML
  3. Edit the <RibbonDiffXml> (RibbonDiffXml)
  4. Import the ribbon

Export the ribbon


You export the ribbon by including it in a solution and then exporting the solution. You can choose to export all the customizations, but that can represent a large amount of data. We recommend that you use an existing unmanaged solution or create a new solution.

Create a new solution

  1. On the nav bar, choose Microsoft Dynamics CRM > Settings.
  2. Go to Settings > Customizations(How do I get there?)
  3. Go to Settings > Solutions(How do I get there?)
  4. Click or tap New.
  5. Type a meaningful Display NameUnique Name and enter a Publisher and type a Version number.
    noteNote
    You can usually use the default publisher for the organization.
  6. Click the Save icon.
  7. If you want to edit the ribbon for specific entities:
    1. Click Add Existing and then click Entity.
    2. Select the entities you want to include in the Solution and then click OK.
      noteNote
      For the purpose of editing entity ribbons, you do not have to include required components. If you intend to export this solution and apply it to another system, you should include required components.
  8. If you want to edit global ribbons or add a custom group to all entities, click Add Existing and then clickApplication Ribbons.
  9. Click Save and Close.

Use an existing solution

  1. On the nav bar, choose Microsoft Dynamics CRM > Settings.
  2. Go to Settings > Customizations(How do I get there?)
  3. Go to Settings > Solutions(How do I get there?)
  4. Double-click a solution to open it.
  5. If you want to edit the ribbon for specific entities:
    1. Click Add Existing and then click Entity.
    2. Select the entities you want to include in the Solution and then click OK.
      noteNote
      For the purpose of editing entity ribbons, you do not have to include required components. If you intend to export this solution and apply it to another system, you should include required components.
  6. If you want to edit global ribbons, such as to add custom button to all entities: click Add Existing and then click Application Ribbons.
  7. Click Save and Close.

Export the ribbon

  1. On the nav bar, choose Microsoft Dynamics CRM > Settings.
  2. Go to Settings > Customizations(How do I get there?)
  3. Go to Settings > Solutions(How do I get there?)
  4. Select the solution you want and then click Export.
  5. If you have made recent changes that have not yet been published, click Publish All Customizations. Otherwise, click Next.
  6. With the Unmanaged option selected, click Export.
  7. Click Save in the File Download dialog box and then click Open Folder in the Download complete dialog box.
  8. Right-click the compressed .zip file that you downloaded and select Extract All... .
  9. Select a location to extract the files and then click Extract.
  10. The customizations.xml file is the file that you will edit.

Prepare to edit the XML

For a better experience, edit the customizations.xml file with an application that can use schema validation to provide IntelliSense support. For more information, see Edit the customizations XML file with schema validation.

Import the ribbon

  1. After you have edited the customization.xml file, from Visual Studio or Microsoft Visual Web Developer 2010 Express, right-click the customization.xml tab and select Open Containing Folder.
  2. Select all of the files or folders that were included when you extracted the solution. Right-click the selected files, select Send To, and then select Compressed (zipped) folder.
    noteNote
    This creates a compressed .zip file in the same folder. The name of the file may vary, but it will be the same as one of the other files in the folder - except with a .zip file name extension.
  3. On the nav bar, choose Microsoft Dynamics CRM > Settings.
  4. Go to Settings > Customizations(How do I get there?)
  5. Go to Settings > Solutions(How do I get there?)
  6. Click Import.
  7. Click Browse and locate the compressed .zip file that you created in step 2 of this procedure.
  8. Click Next and then click Import.
  9. After the import has finished, you will see the message indicating that the import completed successfully. Click Close.
  10. After you have successfully imported your solution, you must publish customizations before you can see the changes. In the Solutions list, click Publish All Customizations.

Dealing with errors on import

  1. If you receive a notification that there were errors that caused the import to fail, click Export Log.
  2. Save the export log file. Select the file and right-click it. Choose Open With and then select Microsoft Office Excel.
  3. Select the Components worksheet and note any messages in the ErrorText column.
    TipTip
    The most common type of failure is an error when referencing a dependent element in the RibbonDiffXml. Perhaps you forgot to include a LocLabel that was referenced somewhere. Perhaps there is an extra blank character included at the end of an XML attribute referencing another element. All references must match exactly.
  4. After you have corrected the error, complete the steps to import the Ribbon again

Group by Using FetchXml in MSCRM


In Microsoft Dynamics CRM 2011 FetchXML includes grouping and aggregation features which let us to use aggregate functions like sum, count etc.

Using Group by we can calculate sum, avg, min, max, count. But, Group by clause is not supported through LINQ in CRM.
You can only specify one aggregate attribute in a query and you cannot use the distinct keyword. To create an aggregate attribute, set the keyword aggregate to true, then specify valid entity name, attribute name and alias(variable name). You must also specify the type of aggregation you want to perform.
<fetch distinct=’false’ mapping=’logical’ aggregate=’true’>
<entity name=’entity name’>
<attribute name=’attribute name’ aggregate=’count’ alias=’alias name’/>
</entity>
</fetch>”
Below is the example to get sum of total amount of all won quotes:
string quotes = @”
<fetch distinct=’false’ mapping=’logical’ aggregate=’true’>
<entity name=’quote’>
<attribute name=’totalamount’ alias=’totalamount_sum’ aggregate=’sum’/>
<attribute name=’statecode’ groupby=’true’ alias=’state’ />
<filter type=’and’>
<condition attribute=’ statecode ‘ operator=’eq’ value=’won’ />”+
“</filter> “+
“</entity> “+
“</fetch>”;
EntityCollection quotes_result = _service.RetrieveMultiple(new FetchExpression(quotes));
foreach (var q in quotes_result.Entities)
{
Decimal wonQuoteAmount = ((Money)((AliasedValue)q["totalamount_sum"]).Value).Value;
}

Thursday, October 29, 2015

Set PartyList using JavaScript in MSCRM

Here is the code to set the party list values using java script. 


Party List is a data type in CRM, using which you can set more than one records of 
an entity for a single field.
Part List type field, renders as Lookup on the form, but it works as multi select lookup

   var partyRequired = Xrm.Page.getAttribute("to");
    // Create new array
    var partlist = new Array();
    partlist[0] = new Object();
    partlist[0].id = Id; //Guid (i.e., Guid of User or Contact etc)
    partlist[0].name = "Name"//Name (i.e., Name of User or Contact etc)
    partlist[0].entityType = "systemuser"//entity schema name of account or contact
    // Set array value    partyRequired.setValue(partlist);

Thank you...