Monday, 26 September 2016

Sample Codes

1. create WCF Services

Iservice,cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfServiceCrm
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        Account [] getAccountDetails();  
    }
    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class Account
    {
     
        string fullNmae ;
        string companyName;
        string telephone ;

        [DataMember]
        public string FullName
        {
            get { return fullNmae; }
            set { fullNmae = value; }
        }

        [DataMember]
        public string CompanyName
        {
            get { return companyName; }
            set { companyName = value; }
        }

        [DataMember]
        public string Telephone
        {
            get { return telephone; }
            set { telephone = value; }
        }
    }
}


Service.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Client;

namespace WcfServiceCrm
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        OrganizationService _orgservice = new OrganizationService(CrmConnection.Parse("Url=https://rangkothi.crm8.dynamics.com; Username=mukush@rangkothi.onmicrosoft.com;PASSWORD=XXXX;"));
        Account[] IService1.getAccountDetails()
        {
            string fetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' >
                                 <entity name='lead'>
                                 <attribute name='fullname' />  
                                <attribute name='companyname' />
                                 <attribute name='telephone1' />
                                 <attribute name='leadid'   />
                                 <attribute name='statecode' />
                                 <order attribute='fullname' descending='false' />
                                  <filter type='and' >
                                         <condition attribute='statecode' operator='in' >
                                            <value>0</value>
                                            <value>1 </value>
                                         </condition>
                                </filter>
                                </entity>
                               </fetch>";

            EntityCollection result = _orgservice.RetrieveMultiple(new FetchExpression(fetchXML));
            int i = 0;
            int Rcount = result.Entities.Count;
            Account[] arrAccount = new Account[Rcount];
            foreach (var c in result.Entities)
            {
                arrAccount[i] = new Account();
                arrAccount[i].FullName = c.Attributes["fullname"].ToString();

                if (c.Attributes.Contains("companyname"))
                { arrAccount[i].CompanyName = c.Attributes["companyname"].ToString (); }


                if (c.Attributes.Contains("telephone1"))
                { arrAccount[i].Telephone = c.Attributes["telephone1"].ToString(); }

                if (c.Attributes.Contains("companyname"))
                { arrAccount[i].CompanyName = c.Attributes["companyname"].ToString(); }

                i++;
      
            }
            return arrAccount;
   
        }
       
    }
}

Points To be Note- In writing fetch xml   <attribute dont write <   attribute > it will give error
2.To test wcf service debug it you will get method name then you can click to invoke it.
3.You need to include the dll of wcf sevices in refrence of aspx page.
4,Give space between url and username

To Create a Portal 

In a web config file
<connectionStrings>
     <add name="CRM" connectionString="URL=https://rangkothi.crm8.dynamics.com;Username=mukush@rangkothi.onmicrosoft.com;PASSWORD=xxxx;"/>
   </connectionStrings>

Create a Helper class - This class helps to create connection with crm.Also include 3 dll Microsoft.XRM.Sdk, Microsoft.XRM.Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Client;

namespace CRMPrortal
{
    public static class CRMHelper
    {
        public static OrganizationService GetCRMService()
        {
            CrmConnection crmconnection = new CrmConnection("CRM");
            return new OrganizationService(crmconnection);
        }
    }
}

Create a Model Class Account which will have simple get set
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace CRMPrortal
{
    public class Account
    {
        public Guid Id { get; set; }
        public string  AccountName { get; set; }
        public string EmailAddress { get; set; }
        public string PhoneAddress { get; set; }

    }
}

Finally create Aspx page  and include 3 dll in .cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Xrm.Sdk;


namespace CRMPrortal
{
    public partial class HomePage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
           var crmService = CRMHelper.GetCRMService();
           Entity e_Account = new Entity("account");
           e_Account.Attributes.Add("name", textAccountName.Text);
           e_Account.Attributes.Add("emailaddress1",txtEmailAddress.Text  );
           e_Account.Attributes.Add("telephone1", txtPhoneNumber.Text);
           var accountId = crmService.Create(e_Account);
           Response.Write("Record Inserted Successfully");
        }
    }
}


Create relation between entites

Console.WriteLine("Entering:RetrieveMultipleWithRelatedEntityColumns");
    //Create multiple accounts with primary contacts
    Entity contact = new Entity("contact");
    contact.Attributes["firstname"] = "ContactFirstName";
    contact.Attributes["lastname"] = "ContactLastName";
    Guid contactId = _orgService.Create(contact, null);

    Entity account = new Entity("account");
    account["name"] = "Test Account1";
    EntityReference primaryContactId = new EntityReference("contact", contactId);
    account["primarycontactid"] = primaryContactId;

    Guid accountId1 = _orgService.Create(account, null);
    account["name"] = "Test Account2";
    Guid accountId2 = _orgService.Create(account, null);
    account["name"] = "Test Account3";
    Guid accountId3 = _orgService.Create(account, null);


Retrive Multiple and Linked Enties

   //Create a query expression specifying the link entity alias and the columns of the link entity that you want to return
    QueryExpression qe = new QueryExpression();
    qe.EntityName = "account";
    qe.ColumnSet = new ColumnSet();
    qe.ColumnSet.Columns.Add("name");

    qe.LinkEntities.Add(new LinkEntity("account", "contact", "primarycontactid", "contactid", JoinOperator.Inner));
    qe.LinkEntities[0].Columns.AddColumns("firstname", "lastname");
    qe.LinkEntities[0].EntityAlias = "primarycontact";

    EntityCollection ec = _orgService.RetrieveMultiple(qe);

    Console.WriteLine("Retrieved {0} entities", ec.Entities.Count);
    foreach (Entity act in ec.Entities)
    {
       Console.WriteLine("account name:" + act["name"]);
       Console.WriteLine("primary contact first name:" + act["primarycontact.firstname"]);
       Console.WriteLine("primary contact last name:" + act["primarycontact.lastname"]);
    }

Sample code links

No comments:

Post a Comment