Tuesday, 1 March 2016

How to get current user Business Unit Details in CRM 2015 using C# plugin








Description:-

In this example we explain that how to get current user Business Unit Details in CRM 2015 using C# plugin. Or how to get details of the Business Unit in CRM plugin using C#.or how to get Business unit from Dynamic CRM 2015 plugin.

That is live issue that I have faced the requirement was that like when we create Lead in CRM then that’s Lead data are Insert/transferred into Dynamics AX automatically. For that requirements we have create one plugin that is called when new Lead is created and in which plugin we define the logic that will fetch the Last inserted Lead data and insert/transfer into Dynamic AX database.
But the finally problem was that we cannot get the Business Unit (Company name) of the current logged in user in CRM that we want to transfer in AX because requirement was that if current logged in users business unit is suppose “CRMAhmedabad” then in AX databases Lead Table Company field have value “CRMAhmedabad” when new Lead is insert same like if business unit is “CRMRajkot” then company field of the Lead table in AX Database have value “CRMRajkot”.



So finally we found solution like how to get the details of Business Unit of the current Logged in user in dynamic CRM using C# plugin are as below.

IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = factory.CreateOrganizationService(context.UserId);

Guid userId = context.InitiatingUserId;
                    ColumnSet allFields = new ColumnSet() { AllColumns = true };
                    Entity user = service.Retrieve("systemuser", userId, allFields);

All plugin code that will transfer or insert Dynamic CRM Lead data to AX Lead table using C# plugin are as below.

Plugin Code:-

namespace Leadtoanotherdomain.Plugins
{
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Leadtoanotherdomain.Plugins.ServiceReference1;
    using Microsoft.Xrm.Sdk.Query;

    public class leadtoanotherdomain: IPlugin
    {
        public void Execute(IServiceProvider serviceprovider)
        {
            try
            {
                ITracingService tracingService =
                  (ITracingService)serviceprovider.GetService(typeof(ITracingService));

                                IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));

                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {

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

                    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));

                    //Service = access to data for modification
                    IOrganizationService service = factory.CreateOrganizationService(context.UserId);

                    // Adding Basic Http Binding and its properties.
                    BasicHttpBinding myBinding = new BasicHttpBinding();
                    myBinding.Name = "BasicHttpBinding_Service";
                    myBinding.Security.Mode = BasicHttpSecurityMode.None;
                    myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                    myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                    myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;


                    myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                    myBinding.OpenTimeout = new TimeSpan(0, 10, 0);
                    myBinding.SendTimeout = new TimeSpan(0, 10, 0);
                    myBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);

                    EndpointAddress endPointAddress = new EndpointAddress(@"http://capella:7093");
                    WebServiceSoapClient my = new WebServiceSoapClient(myBinding, endPointAddress);

                    my.Open();

                    //retrieve user record
                    Guid userId = context.InitiatingUserId;
                    ColumnSet allFields = new ColumnSet() { AllColumns = true };
                    Entity user = service.Retrieve("systemuser", userId, allFields);

                    //get business unit lookup
                    Guid businessUnitId = ((EntityReference)user.Attributes["businessunitid"]).Id;
//here InsertLeadToDifferantDomain is the Webservice Method that we have created to transfer or insert CRM Lead data to AX Lead table Database.for that you have to define your web service that will insert CRM data to AX data.just sumple create insert method in your webservice and call here.
                    string ab = my.InsertLeadToDifferantDomain(entity.GetAttributeValue<string>("subject").ToString(), entity.GetAttributeValue<string>("lastname").ToString(), entity.GetAttributeValue<string>("firstname").ToString(), entity.GetAttributeValue<string>("emailaddress1").ToString(),Convert.ToString(businessUnitId));//
                    if (ab != null)
                    {
                        throw new InvalidPluginExecutionException("Success");
                    }
                    my.Close();
                    //var ab = myClient.GetGrants();
                }
            }
            catch (CommunicationException ex)
            {
                throw new InvalidPluginExecutionException(ex.ToString());

            }


            //            Sandboxed Plug-ins can access network through the HTTP and HTTPS protocols. This capability provides support for accessing popular Web resources like Social Sites, News Feeds, Web services, and more.
            //The following Web access restrictions apply to this Sandbox capability.

            //    Only the HTTP and HTTPS protocols are allowed.
            //    Access to localhost (loopback) is not permitted.
            //    IP addresses cannot be used. You must use a named Web address that requires DNS name resolution.


        }
    }
}



This entry was posted in : ,

0 comments:

Post a Comment