Tuesday, 14 March 2017

MSCRM Plugin using early binding

1) Generate CRM proxy class using CSV UTIL using following config detail

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="url" value="https:///XRMServices/2011/Organization.svc"/>
    <add key="out" value="class.cs"/>
    <add key="namespace" value="MscrmOnlinePlugin"/>
    <add key="serviceContextName" value="XrmServiceContext"/>
    <add key="username" value="username"/>
    <add key="password" value="password "/>
  </appSettings>
</configuration>


2) Adding the generated proxy file in project

3) Create plugins.cs to project inheriting Iplugin interface

public class Plugins : IPlugin
 {
 protected class LocalPluginContext

 {
 internal IServiceProvider ServiceProvider

 {
 get;


private set;

 }
 internal IOrganizationService OrganizationService



 {
 get;


private set;
 }
 internal IPluginExecutionContext PluginExecutionContext

 {
 get;

private set;
 }
 internal ITracingService TracingService


 {
 get;
private set;

 }
 private LocalPluginContext()

 {
 }
 internal LocalPluginContext(IServiceProvider serviceProvider)

 {
 if (serviceProvider == null)

 {
 throw new ArgumentNullException("serviceProvider");

 }
 // Obtain the execution context service from the service provider.

this.PluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

// Obtain the tracing service from the service provider.

this.TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

// Obtain the Organization Service factory service from the service provider
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
// Use the factory to generate the Organization Service.

this.OrganizationService = factory.CreateOrganizationService(this.PluginExecutionContext.UserId);

 }
 internal void Trace(string message)

 {
 if (string.IsNullOrWhiteSpace(message) || this.TracingService == null)

 {
 return;


 }
 if (this.PluginExecutionContext == null)

 {
 this.TracingService.Trace(message);

 }
 else

 {
 this.TracingService.Trace(

"{0}, Correlation Id: {1}, Initiating User: {2}",

 message,
 this.PluginExecutionContext.CorrelationId,

this.PluginExecutionContext.InitiatingUserId);

 }

 }

 }
 private Collection<Tuple<int, string, string, Action<LocalPluginContext>>> registeredEvents;

/// <summary>



/// Gets the List of events that the plug-in should fire for. Each List



/// Item is a <see cref="System.Tuple"/> containing the Pipeline Stage, Message and (optionally) the Primary Entity.



/// In addition, the fourth parameter provide the delegate to invoke on a matching registration.



/// </summary>



protected Collection<Tuple<int, string, string, Action<LocalPluginContext>>> RegisteredEvents

 {
 get


 {
 if (this.registeredEvents == null)

 {
 this.registeredEvents = new Collection<Tuple<int, string, string, Action<LocalPluginContext>>>();
 }
 return this.registeredEvents;

 }

 }
 /// <summary>

/// Gets or sets the name of the child class.



/// </summary>



/// <value>The name of the child class.</value>

protected string ChildClassName




 {
 get;


private set;

 }
 /// <summary>


/// Initializes a new instance of the <see cref="Plugin"/> class.

/// </summary>

/// <param name="childClassName">The <see cref=" cred="Type"/> of the derived class.</param>

internal Plugin(Type childClassName)

 {
 this.ChildClassName = childClassName.ToString();



 }
 /// <summary>



/// Executes the plug-in.



/// </summary>



/// <param name="serviceProvider">The service provider.</param>



/// <remarks>



/// For improved performance, Microsoft Dynamics CRM caches plug-in instances.



/// The plug-in's Execute method should be written to be stateless as the constructor



/// is not called for every invocation of the plug-in. Also, multiple system threads



/// could execute the plug-in at the same time. All per invocation state information



/// is stored in the context. This means that you should not use global variables in plug-ins.



/// </remarks>



public void Execute(IServiceProvider serviceProvider)


 {
 if (serviceProvider == null)

 {
 throw new ArgumentNullException("serviceProvider");
 }
 // Construct the Local plug-in context.


LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);

localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", this.ChildClassName));


try

 {
 // Iterate over all of the expected registered events to ensure that the plugin


// has been invoked by an expected event

// For any given plug-in event at an instance in time, we would expect at most 1 result to match.
Action<LocalPluginContext> entityAction =
 (from a in this.RegisteredEvents


where (

 a.Item1 == localcontext.PluginExecutionContext.Stage &&

 a.Item2 == localcontext.PluginExecutionContext.MessageName &&
 (string.IsNullOrWhiteSpace(a.Item3) ? true : a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
 )
 select a.Item4).FirstOrDefault();

if (entityAction != null)

 {
 localcontext.Trace(string.Format(


CultureInfo.InvariantCulture,


"{0} is firing for Entity: {1}, Message: {2}",


this.ChildClassName,


localcontext.PluginExecutionContext.PrimaryEntityName,

localcontext.PluginExecutionContext.MessageName));

entityAction.Invoke(localcontext);
 // now exit - if the derived plug-in has incorrectly registered overlapping event registrations,



// guard against multiple executions.



return;

 }

 }
 catch (FaultException<OrganizationServiceFault> e)


 {
 localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString()));


// Handle the exception.

throw;


 }
 finally


 {
 localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));



 }

 }

 }
4) Create pluginsbase  abstract  class


public abstract class PluginsBase : IPlugin



 {
 public IPluginExecutionContext Context;


public IOrganizationServiceFactory Factory;


// public CrmOrganizationServiceContext CrmOrgService;



public XrmServiceContext ServiceContext;


public IOrganizationService _service;


protected abstract void OnExecute();


public void Execute(IServiceProvider serviceProvider)

 {
 // Obtain the execution context from the service provider.



 Context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));


//If ILMerged used for plug in , we can remove the below line of code



//InitiliazeEntityType(();

// Get a reference to the organization service.



 Factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));


// _service = (IOrganizationService)serviceProvider.GetService(typeof(IOrganizationService));



//CrmOrgService = new CrmOrganizationServiceContext(Factory.CreateOrganizationService(Context.UserId));



ServiceContext = new XrmServiceContext(Factory.CreateOrganizationService(Context.UserId));


OnExecute();

 }
 public PluginBase()


 {

 }

 }

 5)Add Account Update and create plugin code

public class AccountUpdate : PluginBase

 {
 protected override void OnExecute()



 {

 {
 Entity entity = (Entity)Context.InputParameters["Target"];

 if (entity.LogicalName != "account" )
return;
try
 {
 if (Context.MessageName.ToLower() == "create")
 {
 Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");

 Account acc = entity.ToEntity<Account>();
  ServiceContext.ClearChanges();
 acc.WebSiteURL = "google@gmail.com";
 acc.ParentAccountId = new EntityReference(Account.EntityLogicalName, parentAcc); ;
 acc.Address1_AddressTypeCode = new OptionSetValue(1);

 }
 if (Context.MessageName.ToLower() == "update")

 {

 Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");
 Account account = new Account();

 account.Id = entity.Id;

 account.LogicalName = entity.LogicalName;
 account["websiteurl"] = "google.com";
 account["parentaccountid"] = new EntityReference("account", parentAcc);
 account["address1_addresstypecode"] = new OptionSetValue(2);

ServiceContext.ClearChanges();

ServiceContext.Attach(account);

ServiceContext.UpdateObject(account);

ServiceContext.SaveChanges();

 }


 }
 catch (FaultException<OrganizationServiceFault> ex)

 {

 }
 catch (Exception ex)





 {


 throw;

 }

 }

 }





Friday, 10 March 2017

Accessing WCF Web API

Create WCF with the following web invoke method:

1) In interface add web invoke
  [WebInvoke(Method = "GET", UriTemplate = "/Lead/{LeadId}",
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json,
            BodyStyle= WebMessageBodyStyle.Wrapped)]
        CompositeType GetLeadData(string LeadId);

2)Add in service
 [AspNetCompatibilityRequirements(RequirementsMode  = AspNetCompatibilityRequirementsMode.Allowed)]

Add following detail in web config for webHttpBinding
    <serviceBehaviors >
        <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information,
          set the values below to false before deployment -->
          <serviceMetadata  httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <!-- To receive exception details in faults for debugging purposes,
          set the value below to true.  Set to false before deployment
          to avoid disclosing exception information -->
          <!--<serviceDebug includeExceptionDetailInFaults="True"/>-->
        </behavior>
      </serviceBehaviors>
 <endpoint address="" binding="webHttpBinding"  contract=".IService1" behaviorConfiguration="EndpBehavior">

   <endpointBehaviors>
        <behavior name="basichttp">
          <clientVia />
        </behavior>
    <behavior name="EndpBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>

3) Access from console application
string url = "http://service/" + "488C7C54-0EFF-E611-80E4-005056A93809";
            WebRequest req = WebRequest.Create(@url);
            req.Method = "GET";
            req.ContentType = @"application/json; charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            string jsonResponse = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                jsonResponse = sr.ReadToEnd();
                Console.WriteLine(jsonResponse);
            }

Tuesday, 7 March 2017

Generating Early Bound and MS CRM Proxy for MSCRM Online

1) First please Generate MSCRM proxy file by using below CRMSVCUTIL.EXE

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="url" value="https://.crm8.dynamics.com/XRMServices/2011/Organization.svc"/>
    <add key="out" value="TestAppXrmProxy.cs"/>
    <add key="namespace" value="TestMsApp"/>
    <add key="serviceContextName" value="XrmServiceContext"/>
    <add key="username" value="username"/>
    <add key="password" value="password"/>
  </appSettings>
</configuration>

2) Add helper class
#region Assembly Needed
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk;
#endregion

namespace TestMsApp
{
    public static class ServiceHelper
    {
        private static IOrganizationService _service = null;
        private static OrganizationServiceProxy _serviceProxy = null;
        private static XrmServiceContext _ServiceContext = null;
        //Check error to be logged in CRM
        static bool isErrorLogged = false;

        /// <summary>
        /// InitializeCRMService
        /// </summary>
        /// <returns></returns>
        private static IOrganizationService InitializeCRMService()
        {
            try
            {
                string url = "https://r/XRMServices/2011/Organization.svc";
                ClientCredentials Credentials = new ClientCredentials();
                //Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
                //Not using default credentials since we need WCF Service for IFD deployment
                Credentials.UserName.UserName = "user name";
                Credentials.UserName.Password = "password";
                Uri organizationUri = new Uri(url);
                _serviceProxy = new OrganizationServiceProxy(organizationUri, null, Credentials, null);
                _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                _serviceProxy.EnableProxyTypes();
                _service = (IOrganizationService)_serviceProxy;
            }
            catch (Exception ex)
            {
           
                    throw ex;
            }
            return _service;
        }

        /// <summary>
        /// GetXRMCRMServiceContext
        /// </summary>
        /// <returns></returns>
        public static XrmServiceContext GetXRMCRMServiceContext()
        {
            try
            {
                _service = InitializeCRMService();

                _ServiceContext = new XrmServiceContext(_service);
               
            }
            catch (Exception ex)
            {
               
                    throw ex;
            }
            return _ServiceContext;
        }
    }
}

3) Define proxy Object
   private static XrmServiceContext serviceContext;
   serviceContext = ServiceHelper.GetXRMCRMServiceContext();

Enjoy MSCRMING !


Monday, 6 March 2017

Web Api GET data using Java script MSCRM

// JavaScript source code


function WhoAmIRequest() {

    var qry = "accounts?$filter=startswith(name,'A') or startswith(name,'C')";
    var clientUrl = Xrm.Page.context.getClientUrl();

    var req = new XMLHttpRequest()

    req.open("GET", encodeURI(clientUrl + "/api/data/v8.0/" + qry  ), 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);
               
                for(var i = 0; i < data.value.length ; i++ )
                {
                    alert("Acc Num Id : "+ data.value[i].accountnumber);
                }
                }

            else {

                var error = JSON.parse(this.response).error;

                alert(error.message);

            }

        }

    };

    req.send();

}

sample plugin code MSCRM create and update

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.Crm.Sdk.Messages;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Client;

using System.ServiceModel.Description;

using Microsoft.Xrm.Sdk.Query;

using System.ServiceModel;

namespace MscrmOnlinePlugin



{

public class AccountUpdate : IPlugin



{

public void Execute(IServiceProvider serviceProvider)



{

// Extract the tracing service for use in debugging sandboxed plug-ins.

// If you are not registering the plug-in in the sandbox, then you do

// not have to add any tracing service related code.

ITracingService tracingService =

(ITracingService)serviceProvider.GetService(typeof(ITracingService));

// Obtain the execution context from the service provider.

IPluginExecutionContext context = (IPluginExecutionContext)

serviceProvider.GetService(typeof(IPluginExecutionContext));

// The InputParameters collection contains all the data passed in the message request.

if (context.InputParameters.Contains("Target") &&

context.InputParameters["Target"] is Entity)



{

// Obtain the target entity from the input parameters.

Entity entity = (Entity)context.InputParameters["Target"];

Entity entPost = (Entity)context.PostEntityImages["postImage"];

// Verify that the target entity represents an entity type you are expecting.

// For example, an account. If not, the plug-in was not registered correctly.

if (entity.LogicalName != "account" )

return;

// Obtain the organization service reference which you will need for

// web service calls.

IOrganizationServiceFactory serviceFactory =

(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

try



{

if (context.MessageName.ToLower() == "create")



{

Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");

entity["websiteurl"] = "google@gmail.com";

entity["parentaccountid"] = new EntityReference("account", parentAcc);

entity["address1_addresstypecode"] = new OptionSetValue(1);

// service.Update(entity);



}

if (context.MessageName.ToLower() == "update")



{

Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");

Entity account = new Entity();



account.Id = entity.Id;

account.LogicalName = entity.LogicalName;

account["websiteurl"] = "google@gmail.com";

account["parentaccountid"] = new EntityReference("account", parentAcc);

account["address1_addresstypecode"] = new OptionSetValue(1);



service.Update(account);

 

}

if (context.MessageName.ToLower() == "update")



{

if (entPost.Attributes.Contains("address1_addresstypecode"))



{

if (((OptionSetValue)entPost.Attributes["address1_addresstypecode"]).Value == 1)



{

Entity account = new Entity();



account.Id = entPost.Id;

account.LogicalName = entPost.LogicalName;

account["address1_addresstypecode"] = new OptionSetValue(2);



service.Update(account);

}

}

}

}

catch (FaultException<OrganizationServiceFault> ex)



{

throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex);



}

catch (Exception ex)



{

tracingService.Trace("MyPlugin: {0}", ex.ToString());

throw;



}

}

}

}

}


Console Application Connect to MSCRM online 2016

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

namespace TestMsApp



{
public class Program


{
static IOrganizationService _service ;

static void Main(string[] args)



{
// ConnectToMSCRM("rahuljim@rahuljim.onmicrosoft.com ", "password" "https://damics.com/XRMServices/2011/Discovery.svc");
ConnectToMSCRM("user id", "password", "https://***2011/Organization.svc");
        
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;




if (userid == Guid.Empty) return;//Check for CRM Connection Establishment. If Not return, other wise will proceed to next step
try


{
string queryString = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>




<entity name='account'>

<attribute name='name' />

<attribute name='primarycontactid' />

<attribute name='telephone1' />

<attribute name='accountid' />

<order attribute='name' descending='false' />

<filter type='and'>

<condition attribute='statecode' operator='eq' value='0' />

<condition attribute='statuscode' operator='eq' value='1' />

</filter>

</entity>
</fetch>";

string fetchAcccount = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>




<entity name='account'>

<all-attributes />

<order attribute='name' descending='false' />

<filter type='and'>

<condition attribute='accountnumber' operator='eq' value='{0}' />

</filter>

</entity>
</fetch>";

fetchAcccount = String.Format(fetchAcccount, "AF3HN2S4");

EntityCollection ec = _service.RetrieveMultiple(new FetchExpression(fetchAcccount));

if (ec.Entities.Count > 0)



{
string output = string.Empty;
foreach (var item in ec.Entities)



{
//String
if (item.Attributes.Contains("name")) //Check for fullname value exists or not in Entity Collection
output += "Full Name : " + item.Attributes["name"] + "\n";



}
Console.WriteLine(output);
Console.ReadKey();
// Update Account
Guid parentAcc = new Guid("C3390F45-D5FF-E611-8116-C4346BDCFDE1");
Entity account = new Entity();



account.Id = ec.Entities[0].Id;
account.LogicalName = "account";
account["websiteurl"] = "google@gmail.com";
account["parentaccountid"] = new EntityReference("account", parentAcc);
account["address1_addresstypecode"] = new OptionSetValue(1);



_service.Update(account);

 

}

 

}
catch (Exception ex)



{
Console.WriteLine(ex.Message);



}

}
public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)



{
try


{
ClientCredentials credentials = new ClientCredentials();



credentials.UserName.UserName = UserName;

credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);



proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;



}
catch (Exception ex)



{
Console.WriteLine("Error while connecting to CRM " + ex.Message);
Console.ReadKey();



}

}

}

}