Sample CRUD Operations Using C# in MSCRM

Sample CRUD Operations Using C# in MSCRM
Steps to Achieve:

Create a console Application in Visual Studio and add (Microsoft.Crm.Sdk.Proxy.dll, Microsoft.Xrm.Sdk.dll) in references section.
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
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;


public class SampleCurdOperations
{
         public void Createemp()
        {
            OrganizationServiceProxy service = OnlineService.getonlineservice();
            if (service != null)
            {
                Entity ent = new Entity();
                ent.LogicalName = "new_employee";
                ent.Attributes["new_name"] = "Purushotham";//string
ent.Attributes["new_employeehobbies"] = "TV \n Playing Cricket";//MultiLineText
                ent.Attributes["new_gender"] = false;//Two Optionset
                ent.Attributes["new_dateofjoining"] = Convert.ToDateTime("1/12/12");//date time
ent.Attributes["createdon"] = new DateTime(2015, 09, 11);//Date Time
                ent.Attributes["new_contacttype"] = new OptionSetValue(100000000);//optionset
                ent.Attributes["new_parentaccount"] = new EntityReference("Account", new Guid("16E18CD4-DBC9-E311-991D-D89D6765A2D0"));//lookup
                ent.Attributes["new_salary"] = Convert.ToDecimal(50000);//decimal
                ent.Attributes["new_package"] = new Money(300000);//currency

                for (int i = 0; i < 5000; i++)
                {
                    ent.LogicalName = "account";
                    ent.Attributes["name"] = "Purushotham"+i;

                    Guid empid = service.Create(ent);
                    Console.WriteLine(ent.Attributes["name"]);
                }
                Console.ReadLine();
            }
        }
public void RetrieveRecord()
        {
OrganizationServiceProxy service = OnlineService.getonlineservice();
            if (service != null)
            {// Entity ent = service.Retrieve("new_employee", new Guid("D9711698-E6C9-E311-8781-D89D6765A2E4"), new ColumnSet(true));
            string name = ent["new_name"].ToString();
            string hobbies = ent["new_employeehobbies"].ToString();
            string account = ent.GetAttributeValue<EntityReference>("new_employeeaccount").Name;
            string gender = ent.FormattedValues["new_employeegender"].ToString();
            string location = ent.FormattedValues["new_employeelocation"].ToString();
            string dept = ent.GetAttributeValue<EntityReference>("new_department").Name;
            decimal sal = ent.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);
        }
        }

//retrieve multiple for records
        public void retrieveMultiple()
        {
            OrganizationServiceProxy service = OnlineService.getonlineservice();
            {
                if (service != null)
                {
                    QueryExpression query = new QueryExpression("new_employee");
                    query.ColumnSet = new ColumnSet(new string[] { "new_empid", "new_name", "new_parentaccount", "new_dateofjoining", "new_salary", "new_package" ,"new_contacttype"});
                    FilterExpression filter = new FilterExpression();
                    ConditionExpression cond = new ConditionExpression();
                    cond.AttributeName = "new_name";
                    cond.Operator = ConditionOperator.Equal;
                    cond.Values.Add("laxmi");
                    filter.AddCondition(cond);
                    query.Criteria = filter;
                    EntityCollection col = service.RetrieveMultiple(query);
                    int count = 0, i = 1;
                    foreach (Entity emp in col.Entities)
                    {
                       Console.WriteLine(" recordno: " + i);
                       Console.WriteLine(" recordid: " + emp.Id);
                        Console.WriteLine("empid:" + emp.Attributes["new_empid"]);
                   
                        string empname = emp.GetAttributeValue<string>("new_name");
                        Console.Write("emp_name:" + empname);
                     
                        DateTime dateofjoin = emp.GetAttributeValue<DateTime>("new_dateofjoining").Date;
                        Console.WriteLine("emp_datefojoining" + dateofjoin);
                        bool s = Convert.ToBoolean(emp.GetAttributeValue<bool>("new_gender"));
                       Console.WriteLine("gender :" + s);
                        OptionSetValue contacttype= emp.GetAttributeValue<OptionSetValue>("new_contacttype");
                        string str = emp.FormattedValues["new_contacttype"].ToString();
                        Console.WriteLine("contacttype is:" + str);
                        EntityReference empac = emp.GetAttributeValue<EntityReference>("new_parentaccount.a");
                        Console.WriteLine("lookup logicalname" + empac.LogicalName);
                        Console.WriteLine("lookup id" + empac.Id);
                        Console.WriteLine("lookup name:" + empac.Name);
                        i++;
                        count++;
                    }

                    Console.Read();
                }
            }
        }

    //retrieve multiple for records
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);
        }
    }

//update record
        public void updateemp()
        {
            OrganizationServiceProxy service = OnlineService.getonlineservice();


            if (service != null)
            {
//Entity ent = OnlineService.servproxy.Retrieve("new_employee", new Guid("D9711698-E6C9-E311-8781-D89D6765A2E4"), new ColumnSet("new_employeesalary", "new_employeelocation", "new_employeeaccount", "new_employeehobbies"));
                Entity ent = new Entity();
                ent.LogicalName = "new_employee";
                ent.Id = new Guid("D9711698-E6C9-E311-8781-D89D6765A2E4");
                ent.Attributes["new_name"] = "lakshmi";

                ent.Attributes["new_salary"] = Convert.ToDecimal(75000);
                ent.Attributes["new_package"] = new Money(500000);
decimal sal = Convert.ToDecimal(Console.ReadLine());
                ent["new_employeesalary"] = new Money(sal);
ent["new_employeelocation"] = new OptionSetValue(100000002);
ent["new_employeeaccount"] = new EntityReference("account", new Guid("9C78321B-E44C-E511-8102-C4346BADA644"));
                ent.Attributes["new_gender"] = true;
                service.Update(ent);
                Console.WriteLine("Record Updated Successfully");
            }
        }

 public void delete()
        {
            OrganizationServiceProxy service = OnlineService.getonlineservice();
            {
                string name = string.Empty;
                Guid guid = Guid.Empty;
                if (service != null)
                {
                    QueryExpression query = new QueryExpression("new_employee");
                    query.ColumnSet = new ColumnSet(true);
                    FilterExpression filter = new FilterExpression();
                    ConditionExpression cond = new ConditionExpression();
                    cond.AttributeName = "new_name";
                    cond.Operator = ConditionOperator.Equal;
                    cond.Values.Add("laxmi");
                    filter.AddCondition(cond);
                    query.Criteria = filter;
                    EntityCollection col = service.RetrieveMultiple(query);
                    foreach (Entity emp in col.Entities)
                    {
                        if (emp.Attributes.Contains("new_parentaccount"))
                        {
                            guid = emp.Id;
                        }
                        if ( guid!=null)
                        {
                            service.Delete("new_employee", guid);
                            Console.WriteLine("record deleted");
                        }
                        Console.Read();
                      }

                }
            }
        }
}

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.......



Comments

Popular posts from this blog

Basic Plugin Code in D365 using C#

CURD (Create, Update, Retrieve and Delete) Operation in D365 using Power Shell Script

Meta Data Using WebApiRequest