Exemple #1
0
        public static bool GetCrmServiceClient(DTE dte)
        {
            var check = UtilityPackage.GetGlobal("CrmServiceClient", dte);

            if (check == null)
            {
                var form = new FormConnection2(dte);
                if (form.ShowDialog() == DialogResult.Cancel)
                {
                    return(false);
                }
                if (form.Check == "1")
                {
                    var loginForm = new FormLogin();
                    loginForm.ConnectionToCrmCompleted += loginForm_ConnectionToCrmCompleted;
                    loginForm.ShowDialog();
                    if (loginForm.CrmConnectionMgr != null && loginForm.CrmConnectionMgr.CrmSvc != null && loginForm.CrmConnectionMgr.CrmSvc.IsReady)
                    {
                        UtilityPackage.SetGlobal("CrmUrl", XrmHelper.ConnectedUrl(loginForm.CrmConnectionMgr.CrmSvc), dte);
                        UtilityPackage.SetGlobal("CrmServiceClient", loginForm.CrmConnectionMgr.CrmSvc, dte);
                    }
                    else
                    {
                        UtilityPackage.SetDTEStatusBar(dte, "Connection failed");
                        return(false);
                    }
                }
                else
                {
                    UtilityPackage.SetGlobal("CrmUrl", XrmHelper.ConnectedUrl(form.CrmServiceClient), dte);
                    UtilityPackage.SetGlobal("CrmServiceClient", form.CrmServiceClient, dte);
                }
            }
            return(true);
        }
Exemple #2
0
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            try
            {
                DTE = (DTE)automationObject;
                var projects = (object[])DTE.ActiveSolutionProjects;
                var project  = (Project)projects[0];
                if (project == null)
                {
                    return;
                }
                var dir          = Path.GetDirectoryName(project.FullName);
                var downloadFile = Path.Combine(dir, "download.webresources.bat");
                if (File.Exists(downloadFile))
                {
                    MessageBox.Show("You added this file: download.webresources.bat to your active project", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                var form = new FormConnection2(DTE);
                if (form.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                //var crmConnectionString = CrmConnectionString(form.CrmConnection);
                var crmConnectionString = XrmHelper.BuildConnectionString(form.CrmConnection);
                var file = Utility.GetDevKitCliJsonFile(DTE);
                if (!File.Exists(file))
                {
                    var solutionName = Utility.GetSolutionName(DTE);
                    var json         = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.DynamicsCrm.DevKit.Cli.json");
                    json = json
                           .Replace("???.Plugin.*.dll", $"{solutionName}.Plugin.*.dll")
                           .Replace("???.CustomAction.*.dll", $"{solutionName}.CustomAction.*.dll")
                           .Replace("???.Workflow.*.dll", $"{solutionName}.Workflow.*.dll")
                           .Replace("???.DataProvider.*.dll", $"{solutionName}.DataProvider.*.dll")
                           .Replace("???.*.Test.dll", $"{solutionName}.*.Test.dll")
                    ;
                    Utility.ForceWriteAllText(file, json);
                }

                var downloadContent = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.webresource.download.webresources.bat");
                downloadContent = downloadContent.Replace("$CrmConnectionString$", crmConnectionString);
                Utility.ForceWriteAllTextWithoutUTF8(downloadFile, downloadContent);
                project.ProjectItems.AddFromFile(downloadFile);

                var deployFile = Path.Combine(dir, "deploy.debug.bat");
                if (!File.Exists(deployFile))
                {
                    var deployContent = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.webresource.deploy.debug.bat");
                    deployContent = deployContent.Replace("$CrmConnectionString$", crmConnectionString);
                    Utility.ForceWriteAllTextWithoutUTF8(deployFile, deployContent);
                    project.ProjectItems.AddFromFile(deployFile);
                }
                var packagesFile = Path.Combine(dir, "packages.config");
#if DEBUG
                var cliVersion = Const.Version;
#else
                var cliVersion = NugetHelper.GetLatestPackageVersion(Const.DynamicsCrmDevKitCli);
#endif
                if (!File.Exists(packagesFile))
                {
                    var packagesContent = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.webresource.packages.config");
                    packagesContent = packagesContent.Replace("$DynamicsCrm.DevKit.Cli.Version$", cliVersion);
                    Utility.ForceWriteAllText(packagesFile, packagesContent);
                    project.ProjectItems.AddFromFile(packagesFile);
                }
                else
                {
                    var packagesContent = File.ReadAllText(packagesFile);
                    if (packagesContent.IndexOf("DynamicsCrm.DevKit.Cli") < 0)
                    {
                        var packageLine = "\t<package id=\"DynamicsCrm.DevKit.Cli\" version=\"$DynamicsCrm.DevKit.Cli.Version$\" />\r\n";
                        packageLine     = packageLine.Replace("$DynamicsCrm.DevKit.Cli.Version$", cliVersion);
                        packagesContent = packagesContent.Replace("</packages>", packageLine + "</packages>");
                        Utility.ForceWriteAllText(packagesFile, packagesContent);
                    }
                }
                project.Save();
            }
            catch
            {
                throw;
            }
        }
        private static List <string> CrmPluginRegistrationDataForPlugin(DTE dte, string fullName)
        {
            IOrganizationService CrmService = null;

            Shared.Models.CrmConnection CrmConnection = null;
            var list = new List <string>();
            var form = new FormConnection2(dte);

            if (form.ShowDialog() == DialogResult.Cancel)
            {
                return(list);
            }
            if (form.Check == "1")
            {
                var loginForm = new FormLogin();
                loginForm.ConnectionToCrmCompleted += loginForm_ConnectionToCrmCompleted;
                loginForm.ShowDialog();
                if (loginForm.CrmConnectionMgr != null && loginForm.CrmConnectionMgr.CrmSvc != null && loginForm.CrmConnectionMgr.CrmSvc.IsReady)
                {
                    if (loginForm.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy != null)
                    {
                        CrmService = (IOrganizationService)loginForm.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy;
                    }
                    else if (loginForm.CrmConnectionMgr.CrmSvc.OrganizationWebProxyClient != null)
                    {
                        CrmService = (IOrganizationService)loginForm.CrmConnectionMgr.CrmSvc.OrganizationWebProxyClient;
                    }
                    else
                    {
                        return(list);
                    }
                }
                else
                {
                    return(list);
                }
            }
            else
            {
                CrmConnection = form.CrmConnection;
                CrmService    = form.CrmService;
            }
            if (form.Check == "1")
            {
                var deployText = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.plugin.deploy.debug.bat");
                deployText = deployText
                             .Replace("set CrmConnection=\"$CrmConnectionString$\"\r\n", string.Empty)
                             .Replace("/conn:%CrmConnection%", "/sdklogin:\"yes\"")
                             .Replace("$ProjectName$", Path.GetFileNameWithoutExtension(dte.ActiveDocument.ProjectItem.ContainingProject.FullName));
                AddDeployBatIfNeed(dte, deployText);
            }
            else
            {
                var crmConnectionString = XrmHelper.BuildConnectionString(CrmConnection);
                var deployText          = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.plugin.deploy.debug.bat");
                deployText = deployText
                             .Replace("$CrmConnectionString$", crmConnectionString)
                             .Replace("$ProjectName$", Path.GetFileNameWithoutExtension(dte.ActiveDocument.ProjectItem.ContainingProject.FullName));
                AddDeployBatIfNeed(dte, deployText);
            }

            var fetchData = new
            {
                ismanaged      = "0",
                iscustomizable = "1",
                typename       = fullName
            };
            var fetchXml = $@"
<fetch>
  <entity name='sdkmessageprocessingstep'>
    <attribute name='filteringattributes' />
    <attribute name='name' />
    <attribute name='impersonatinguserid' />
    <attribute name='rank' />
    <attribute name='description' />
    <attribute name='stage' />
    <attribute name='supporteddeployment' />
    <attribute name='componentstate' />
    <attribute name='asyncautodelete' />
    <attribute name='mode' />
    <attribute name='configuration' />
    <attribute name='statecode' />
    <filter type='and'>
      <condition attribute='ismanaged' operator='eq' value='{fetchData.ismanaged/*0*/}'/>
      <condition attribute='iscustomizable' operator='eq' value='{fetchData.iscustomizable/*1*/}'/>
    </filter>
    <link-entity name='sdkmessage' from='sdkmessageid' to='sdkmessageid' alias='m'>
      <attribute name='name' />
    </link-entity>
    <link-entity name='plugintype' from='plugintypeid' to='plugintypeid' link-type='inner' alias='t'>
      <filter type='and'>
        <condition attribute='typename' operator='eq' value='{fetchData.typename/*AccountPlugin.PostDeleteAccount*/}'/>
      </filter>
      <link-entity name='pluginassembly' from='pluginassemblyid' to='pluginassemblyid' link-type='inner' alias='p'>
        <attribute name='isolationmode' />
      </link-entity>
    </link-entity>
    <link-entity name='sdkmessagefilter' from='sdkmessagefilterid' to='sdkmessagefilterid' link-type='inner' alias='f'>
      <attribute name='primaryobjecttypecode' />
    </link-entity>
    <link-entity name='sdkmessageprocessingstepsecureconfig' from='sdkmessageprocessingstepsecureconfigid' to='sdkmessageprocessingstepsecureconfigid' link-type='outer' alias='s'>
      <attribute name='secureconfig' />
    </link-entity>
  </entity>
</fetch>";

            var rows = CrmService.RetrieveMultiple(new FetchExpression(fetchXml));

            if (rows.Entities.Count == 0)
            {
                return(list);
            }
            foreach (var row in rows.Entities)
            {
                var message             = GetAliasedValue <string>(row, "m.name");
                var entity              = GetAliasedValue <string>(row, "f.primaryobjecttypecode");
                var stage               = row.GetAttributeValue <OptionSetValue>("stage").Value;
                var stageName           = stage == 10 ? "StageEnum.PreValidation" : (stage == 20 ? "StageEnum.PreOperation" : "StageEnum.PostOperation");
                var mode                = row.GetAttributeValue <OptionSetValue>("mode").Value;
                var modeName            = mode == 0 ? "ExecutionModeEnum.Synchronous" : "ExecutionModeEnum.Asynchronous";
                var filteringAttributes = row.GetAttributeValue <string>("filteringattributes");
                var name                = row.GetAttributeValue <string>("name");
                var rank                = row.GetAttributeValue <int>("rank");
                var isolationMode       = GetAliasedValue <OptionSetValue>(row, "p.isolationmode").Value;
                var isolationModeName   = isolationMode == 0 ? "IsolationModeEnum.None" : "IsolationModeEnum.Sandbox";
                var asyncautodelete     = row.GetAttributeValue <bool>("asyncautodelete");
                var description         = row.GetAttributeValue <string>("description");
                var supportedDeployment = row.GetAttributeValue <OptionSetValue>("supporteddeployment").Value;
                var status              = row.GetAttributeValue <OptionSetValue>("statecode").Value;
                var configuration       = row.GetAttributeValue <string>("configuration");
                var secureconfig        = GetAliasedValue <string>(row, "s.secureconfig");
                var impersonatinguserid = row.GetAttributeValue <EntityReference>("impersonatinguserid");

                var attribute = string.Empty;
                attribute += $"\"{message}\"";
                attribute += $", \"{entity}\"";
                attribute += $", {stageName}";
                attribute += $", {modeName}";
                attribute += $", \"{filteringAttributes}\",\r\n\t";
                attribute += $"\"{name}\"";
                attribute += $", {rank}";
                attribute += $", {isolationModeName},\r\n\t";
                if (asyncautodelete)
                {
                    attribute += $"DeleteAsyncOperation = true, ";
                }
                if (description != null)
                {
                    attribute += $"Description = \"{description}\", ";
                }
                if (supportedDeployment == 2)
                {
                    attribute += $"Server = true, Offline = true, ";
                }
                else if (supportedDeployment == 1)
                {
                    attribute += $"Server = false, Offline = true, ";
                }
                if (status == 1)
                {
                    attribute += $"Action = PluginStepOperationEnum.Deactivate, ";
                }
                if (configuration != null)
                {
                    attribute += $"UnSecureConfiguration = \"{configuration}\", ";
                }
                if (secureconfig != null)
                {
                    attribute += $"SecureConfiguration = \"{secureconfig}\", ";
                }
                if (impersonatinguserid != null)
                {
                    attribute += $"RunAs = \"{impersonatinguserid.Name}\", ";
                }
                if (attribute.EndsWith(", "))
                {
                    attribute  = attribute.TrimEnd();
                    attribute += "\r\n\t";
                }
                var images = GetPluginImages(CrmService, fullName, row.Id);
                var image  = "Image{0}Name = \"{1}\", Image{0}Alias = \"{2}\", Image{0}Type = ImageTypeEnum.{3}, Image{0}Attributes = \"{4}\",\r\n\t";
                if (images.Count > 0)
                {
                    var i = 1;
                    foreach (var item in images)
                    {
                        attribute += string.Format(image, i, item.Name, item.Alias, item.Type.ToString(), item.Attributes);
                        i++;
                        if (i == 5)
                        {
                            break;
                        }
                    }
                    attribute = attribute.TrimEnd(",\r\n\t".ToCharArray());
                }
                else
                {
                    attribute += string.Format(image, 1, string.Empty, string.Empty, "PreImage", string.Empty);
                    attribute  = attribute.TrimEnd(",\r\n\t".ToCharArray());
                }
                list.Add(attribute);
            }
            return(list);
        }
        private static List <string> CrmPluginRegistrationDataForWorkflow(DTE dte, string fullName)
        {
            IOrganizationService CrmService = null;

            Shared.Models.CrmConnection CrmConnection = null;
            var list = new List <string>();
            var form = new FormConnection2(dte);

            if (form.ShowDialog() == DialogResult.Cancel)
            {
                return(list);
            }
            if (form.Check == "1")
            {
                var loginForm = new FormLogin();
                loginForm.ConnectionToCrmCompleted += loginForm_ConnectionToCrmCompleted;
                loginForm.ShowDialog();
                if (loginForm.CrmConnectionMgr != null && loginForm.CrmConnectionMgr.CrmSvc != null && loginForm.CrmConnectionMgr.CrmSvc.IsReady)
                {
                    if (loginForm.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy != null)
                    {
                        CrmService = (IOrganizationService)loginForm.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy;
                    }
                    else if (loginForm.CrmConnectionMgr.CrmSvc.OrganizationWebProxyClient != null)
                    {
                        CrmService = (IOrganizationService)loginForm.CrmConnectionMgr.CrmSvc.OrganizationWebProxyClient;
                    }
                    else
                    {
                        return(list);
                    }
                }
                else
                {
                    return(list);
                }
            }
            else
            {
                CrmConnection = form.CrmConnection;
                CrmService    = form.CrmService;
            }

            if (form.Check == "1")
            {
                var deployText = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.workflow.deploy.debug.bat");
                deployText = deployText
                             .Replace("set CrmConnection=\"$CrmConnectionString$\"\r\n", string.Empty)
                             .Replace("/conn:%CrmConnection%", "/sdklogin:\"yes\"")
                             .Replace("$ProjectName$", Path.GetFileNameWithoutExtension(dte.ActiveDocument.ProjectItem.ContainingProject.FullName));
                AddDeployBatIfNeed(dte, deployText);
            }
            else
            {
                var crmConnectionString = XrmHelper.BuildConnectionString(CrmConnection);
                var deployText          = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.workflow.deploy.debug.bat");
                deployText = deployText
                             .Replace("$CrmConnectionString$", crmConnectionString)
                             .Replace("$ProjectName$", Path.GetFileNameWithoutExtension(dte.ActiveDocument.ProjectItem.ContainingProject.FullName));
                AddDeployBatIfNeed(dte, deployText);
            }
            var fetchData = new
            {
                ismanaged          = "0",
                isworkflowactivity = "1",
                typename           = fullName
            };
            var fetchXml = $@"
<fetch>
  <entity name='plugintype'>
    <attribute name='name' />
    <attribute name='workflowactivitygroupname' />
    <attribute name='description' />
    <attribute name='typename' />
    <attribute name='assemblyname' />
    <attribute name='friendlyname' />
    <filter type='and'>
      <condition attribute='ismanaged' operator='eq' value='{fetchData.ismanaged/*0*/}'/>
      <condition attribute='isworkflowactivity' operator='eq' value='{fetchData.isworkflowactivity/*1*/}'/>
      <condition attribute='typename' operator='eq' value='{fetchData.typename/*CustomWorkflow.RetrieveUsers*/}'/>
    </filter>
    <link-entity name='pluginassembly' from='pluginassemblyid' to='pluginassemblyid' alias='a'>
      <attribute name='isolationmode' />
    </link-entity>
  </entity>
</fetch>";

            var rows = CrmService.RetrieveMultiple(new FetchExpression(fetchXml));

            if (rows.Entities.Count == 0)
            {
                return(list);
            }
            foreach (var row in rows.Entities)
            {
                var name         = row.GetAttributeValue <string>("name");
                var friendlyname = row.GetAttributeValue <string>("friendlyname");
                var description  = row.GetAttributeValue <string>("description");
                var workflowactivitygroupname = row.GetAttributeValue <string>("workflowactivitygroupname");
                var isolationMode             = GetAliasedValue <OptionSetValue>(row, "a.isolationmode").Value;
                var isolationModeName         = isolationMode == 0 ? "IsolationModeEnum.None" : "IsolationModeEnum.Sandbox";
                var attribute = string.Empty;
                attribute += $"\"{name}\"";
                attribute += $", \"{friendlyname}\"";
                attribute += $", \"{description}\"";
                attribute += $", \"{workflowactivitygroupname}\"";
                attribute += $", {isolationModeName}";
                list.Add(attribute);
            }
            return(list);
        }
        internal static void Click(DTE dte)
        {
            try
            {
                dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                var config = UtilityPackage.IsValid(dte);
                if (config == null)
                {
                    return;
                }
                UtilityPackage.SetDTEStatusBar(dte, " !!! Read DynamicsCrm.DevKit.Cli.json config !!! ");
                var check = UtilityPackage.GetGlobal("CrmService", dte);
                if (check == null)
                {
                    var form = new FormConnection2(dte);
                    if (form.ShowDialog() == DialogResult.Cancel)
                    {
                        return;
                    }
                    if (form.Check == "1")
                    {
                        var loginForm = new FormLogin();
                        loginForm.ConnectionToCrmCompleted += loginForm_ConnectionToCrmCompleted;
                        loginForm.ShowDialog();
                        if (loginForm.CrmConnectionMgr != null && loginForm.CrmConnectionMgr.CrmSvc != null && loginForm.CrmConnectionMgr.CrmSvc.IsReady)
                        {
                            if (loginForm.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy != null)
                            {
                                var CrmService = (IOrganizationService)loginForm.CrmConnectionMgr.CrmSvc.OrganizationServiceProxy;
                                UtilityPackage.SetGlobal("CrmService", CrmService, dte);
                            }
                            else if (loginForm.CrmConnectionMgr.CrmSvc.OrganizationWebProxyClient != null)
                            {
                                var CrmService = (IOrganizationService)loginForm.CrmConnectionMgr.CrmSvc.OrganizationWebProxyClient;
                                UtilityPackage.SetGlobal("CrmService", CrmService, dte);
                            }
                            else
                            {
                                UtilityPackage.SetDTEStatusBar(dte, " !!! Connection Dynamics CRM  failed !!! ", true);
                                return;
                            }
                        }
                        else
                        {
                            UtilityPackage.SetDTEStatusBar(dte, " !!! Connection Dynamics CRM  failed !!! ", true);
                            return;
                        }
                    }
                    else
                    {
                        var CrmConnection = form.CrmConnection;
                        var CrmService    = form.CrmService;
                        UtilityPackage.SetGlobal("CrmService", CrmService, dte);
                    }
                }
                var crmService = (IOrganizationService)UtilityPackage.GetGlobal("CrmService", dte);
                UtilityPackage.SetDTEStatusBar(dte, " !!! Connected Dynamics CRM !!! ");
                var webResourceId = IsFoundWebResource(dte, crmService, config.JsonWebResource.prefix);
                if (webResourceId == Guid.Empty)
                {
                    UtilityPackage.SetDTEStatusBar(dte, " !!! WebResource not found !!! ", true);
                    return;
                }
                var requests = new OrganizationRequestCollection();

                var webResource = new Entity("webresource")
                {
                    Id = webResourceId
                };
                var content = File.ReadAllText(dte.ActiveDocument.FullName);
                webResource["content"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(content));
                var request = new UpdateRequest {
                    Target = webResource
                };
                requests.Add(request);

                var publishXml = $"<importexportxml><webresources><webresource>{webResource.Id}</webresource></webresources></importexportxml>";
                var pubRequest = new PublishXmlRequest {
                    ParameterXml = publishXml
                };
                requests.Add(pubRequest);

                var multipleRequest = new ExecuteMultipleRequest
                {
                    Requests = requests,
                    Settings = new ExecuteMultipleSettings
                    {
                        ContinueOnError = false,
                        ReturnResponses = true
                    }
                };
                UtilityPackage.SetDTEStatusBar(dte, " !!! Updating & publishing WebResource !!! ");
                var multipleResponse = (ExecuteMultipleResponse)crmService.Execute(multipleRequest);
                foreach (var response in multipleResponse.Responses)
                {
                    if (response.Fault == null)
                    {
                        continue;
                    }
                    UtilityPackage.SetDTEStatusBar(dte, " !!! Deploy WebResource failed !!! ", true);
                    return;
                }
                UtilityPackage.SetDTEStatusBar(dte, " !!! Deploy WebResource succeeded !!! ", true);
            }
            catch
            {
                UtilityPackage.SetDTEStatusBar(dte, " !!! Deploy WebResource failed !!! ", true);
            }
        }