Monday, 26 September 2016

REST SOAP

SOAP
Simple Object Access Protocol (SOAP) standard an XML language defining a message architecture and message formats, is used by Web services it contain a description of the operations. WSDL is an XML-based language for describing Web services and how to access them. will run on SMTP,HTTP,FTP etc. Requires middleware support, well defined mechanisam to define services like WSDL+XSD, WS-Policy SOAP will return XML based data
REST Representational State Transfer (RESTful) web services. they are second generation Web Services. RESTful web services, communicate via HTTP than SOAP-based services and do not require XML messages or WSDL service-API definitions. for REST no middleware is required only HTTP support is needed.WADL Standard, REST can return XML, plain text, JSON, HTML etc

In general, When you're publishing an API to the outside world that is either complex or likely to change, SOAP will be more useful. Other than that, REST is usually the better option.
Rest VS SOAP
SOAP:
► SOAP is simple object access protocol that run on TCP/UDP/SMTP.
► SOAP read and write request response messages in XML format.
► SOAP uses interface in order to define the services.
► SOAP is more secure as it has its own security and well defined standards.
► SOAP follows RPC and Document style to define web services.
► SOAP uses SOAP-UI as client tools for testing.
REST
► REST is representational state transfer that uses underlying HTTP protocols.
► REST is stateless.
► REST is an architectural style that is used to describe and define web services.
► REST can read and write request response messages in JSON/XML/Plain HTML.
► REST uses URI for each resource that is used in web service.A resource can be image text method etc.
► REST uses set of VERBs like HTTP's GET, POST, PUT, DELETE.
► REST is easy to develop and easy to manage as compared to SOAP UI.
► REST has light weight client tools or plugins that can easily be integrated inside browser.
► REST services are cache able. 

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

Wednesday, 14 September 2016