Quantcast
Channel: Microsoft Dynamics CRM Forum - Recent Threads
Viewing all articles
Browse latest Browse all 79901

Registering a plug in with c# code for Online CRM

$
0
0

Hello Developers, 

I'm working with Dynamics CRM sdk 4.0. I'm trying to register a plugin in my code for a particular account on CRM online . When I try to run the Execute method of CRMService class by passing the request as a parameter then it shows the error of "Request failed with empty response". I am using Active Directory Authentication. May be this is causing that problem but I'm not pretty much sure. RegisterSolution() throws exception. I supply all the credentials of my CRM account i.e user name, password, domain, crm server and organisation name. Following is the link I have used as a reference to write code for that . 

https://www.microsoftpressstore.com/articles/article.aspx?p=2233321&seqNum=6

I can also provide you complete source code so that you may easily find the problem if required. Following is snippet of my code. it's not having 

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web.Services.Protocols;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using ProgrammingWithDynamicsCrm4.Plugins;
using ProgrammingWithDynamicsCrm4.Plugins.Attributes;

namespace ProgrammingWithDynamicsCrm4.PluginDeploy
{
    public class Program
    {
        static void Main(string[] args)
        {
            string path = @"D:\Sukhdeep\Others\TestProject\ProgrammingWithDynamicsCrm4\ProgrammingWithDynamicsCrm4.Plugins\bin\Debug\ProgrammingWithDynamicsCrm4.Plugins.dll";
          
          

            try
            {
                string pluginAssemblyPath = path;
                string crmServer = "disco.crm5.dynamics.com";
                string organizationName = "<orgName>"; 

                DeployPlugin(pluginAssemblyPath, crmServer, organizationName);
            }
            catch (SoapException e)
            {
                Console.WriteLine(e.Detail.InnerText);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private static void DeployPlugin(string pluginAssemblyPath, string crmServer, string organizationName)
        {
            Console.Write("Initializing CrmService... ");
            CrmService crmService = CreateCrmService(crmServer, organizationName);
            Console.WriteLine("Complete");

            pluginassembly pluginAssembly = LoadPluginAssembly(pluginAssemblyPath);

            // UnregisterExistingSolution(crmService, pluginAssembly.name);

            SdkMessageProcessingStepRegistration[] steps = LoadPluginSteps(pluginAssemblyPath);

            RegisterSolution(crmService, pluginAssembly, steps);
        }

        private static CrmService CreateCrmService(string crmServer, string organizationName)
        {
            UriBuilder crmServerUri = new UriBuilder(crmServer);
            crmServerUri.Path = "/MSCRMServices/2007/CrmService.asmx";

            string userName = <UserName>;
            string password = <Password>;
            string domain =<Domain>;

            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.AuthenticationType =  AuthenticationType.AD;
            token.OrganizationName = organizationName;

            CrmService crmService = new CrmService();
            crmService.CrmAuthenticationTokenValue = token;
            if (String.IsNullOrEmpty(userName))
            {
                crmService.UseDefaultCredentials = true;
            }
            else
            {
                crmService.Credentials = new NetworkCredential(userName, password, domain);
            }

           // crmService.Url = @"disco.crm5.dynamics.com/.../CrmService.asmx";
            crmService.Url = crmServerUri.ToString();
      

            return crmService;
        }

        private static pluginassembly LoadPluginAssembly(string pluginAssemblyPath)
        {
            Assembly assembly = Assembly.LoadFile(pluginAssemblyPath);
            pluginassembly pluginAssembly = new pluginassembly();
            pluginAssembly.name = assembly.GetName().Name;
            pluginAssembly.sourcetype = new Picklist(AssemblySourceType.Database);
            pluginAssembly.culture = assembly.GetName().CultureInfo.ToString();
            pluginAssembly.version = assembly.GetName().Version.ToString();

            if (String.IsNullOrEmpty(pluginAssembly.culture))
            {
                pluginAssembly.culture = "neutral";
            }

            byte[] publicKeyToken = assembly.GetName().GetPublicKeyToken();
            StringBuilder tokenBuilder = new StringBuilder();
            foreach (byte b in publicKeyToken)
            {
                tokenBuilder.Append(b.ToString("x").PadLeft(2, '0'));
            }
            pluginAssembly.publickeytoken = tokenBuilder.ToString();

            pluginAssembly.content = Convert.ToBase64String(
                File.ReadAllBytes(pluginAssemblyPath));

            return pluginAssembly;
        }

        private static void UnregisterExistingSolution(CrmService crmService, string assemblyName)
        {
            QueryByAttribute query = new QueryByAttribute();
            query.EntityName = EntityName.pluginassembly.ToString();
            query.ColumnSet = new ColumnSet(new string[] { "pluginassemblyid" });
            query.Attributes = new string[] { "name" };
            query.Values = new object[] { assemblyName };

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;

            RetrieveMultipleResponse response;
            Console.Write("Searching for existing solution... ");
            response = (RetrieveMultipleResponse)crmService.Execute(request);
            Console.WriteLine("Complete");

            if (response.BusinessEntityCollection.BusinessEntities.Count > 0)
            {
                pluginassembly pluginAssembly = (pluginassembly)
                    response.BusinessEntityCollection.BusinessEntities[0];
                Console.Write("Unregistering existing solution {0}... ",
                    pluginAssembly.pluginassemblyid.Value);

                UnregisterSolutionRequest unregisterRequest =
                    new UnregisterSolutionRequest();
                unregisterRequest.PluginAssemblyId = pluginAssembly.pluginassemblyid.Value;

                crmService.Execute(unregisterRequest);
                Console.WriteLine("Complete");
            }
        }

        private static SdkMessageProcessingStepRegistration[] LoadPluginSteps(string pluginAssemblyPath)
        {
            List<SdkMessageProcessingStepRegistration> steps =
                new List<SdkMessageProcessingStepRegistration>();

            Assembly assembly = Assembly.LoadFile(pluginAssemblyPath);
            foreach (Type pluginType in assembly.GetTypes())
            {
                if (typeof(IPlugin).IsAssignableFrom(pluginType) && !pluginType.IsAbstract)
                {
                    object[] stepAttributes =
                        pluginType.GetCustomAttributes(typeof(PluginStepAttribute), false);

                    foreach (PluginStepAttribute stepAttribute in stepAttributes)
                    {
                        steps.Add(CreateStepFromAttribute(pluginType, stepAttribute));
                    }
                }
            }

            return steps.ToArray();
        }

        private static SdkMessageProcessingStepRegistration CreateStepFromAttribute(Type pluginType, PluginStepAttribute stepAttribute)
        {
            SdkMessageProcessingStepRegistration step =
                new SdkMessageProcessingStepRegistration();
            step.Description = stepAttribute.Description;
            step.FilteringAttributes = stepAttribute.FilteringAttributes;
            step.InvocationSource = (int)stepAttribute.InvocationSource;
            step.MessageName = stepAttribute.Message;
            step.Mode = (int)stepAttribute.Mode;
            step.PluginTypeName = pluginType.FullName;
            step.PluginTypeFriendlyName = pluginType.FullName;
            step.PrimaryEntityName = stepAttribute.PrimaryEntityName;
            step.SecondaryEntityName = stepAttribute.SecondaryEntityName;
            step.Stage = (int)stepAttribute.Stage;
            step.SupportedDeployment = (int)stepAttribute.SupportedDeployment;

            if (String.IsNullOrEmpty(step.Description))
            {
                step.Description = String.Format("{0} {1} {2}",
                    step.PrimaryEntityName, step.MessageName, stepAttribute.Stage);
            }

            return step;
        }

        private static void RegisterSolution(CrmService crmService, pluginassembly pluginAssembly, SdkMessageProcessingStepRegistration[] steps)
        {
            RegisterSolutionRequest registerRequest = new RegisterSolutionRequest();
            registerRequest.PluginAssembly = pluginAssembly;
            registerRequest.Steps = steps;
            Console.Write("Registering solution... ");
            RegisterSolutionResponse response = (RegisterSolutionResponse)crmService.Execute(registerRequest);
            Console.WriteLine("Complete");


            //AddMembersTeamRequest addRequest = new AddMembersTeamRequest();

            ////Set the AddTeamMembersRequest TeamID property to the Object ID of 
            ////an existing team.
            //addRequest.TeamId = new Guid("A2EBD47D-1D14-DA11-A847-000874DE7397");

            ////Set the AddTeamMembersRequest MemberIds property to an 
            ////array of GUIDs that contain the Object IDs of systemusers.
            //addRequest.MemberIds = new Guid[] {
            //new Guid("C0165813-008E-4ADB-96A8-E4C5253D35E5"),
            //new Guid("F127938A-A2E8-4C76-994B-1F981B6D11CA"),
            //new Guid("A7847F46-3E3A-404F-B496-C6B2D8EC113B")};
                               
            //    AddMembersTeamResponse addResponse = (AddMembersTeamResponse)crmService.Execute(addRequest);
           
         


        }

    }

    
}

Looking forward to hear from you.

Thanks 


Viewing all articles
Browse latest Browse all 79901

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>