예제 #1
0
        private string CreateCommandArgs()
        {
            var command = new StringBuilder();

            if (arguments.SdkLogin.Length > 0 && arguments.SdkLogin.ToLower() == "yes")
            {
                command.Append("/interactivelogin ");
            }
            else
            {
                command.Append($"/connectionstring:\"{XrmHelper.BuildConnectionString(arguments.Connection)}\" ");
            }
            command.Append($"/nologo ");
            command.Append($"/SuppressGeneratedCodeAttribute ");
            command.Append($"/generateActions ");
            command.Append($"/namespace:\"{json.@namespace}\" ");
            if (json.entities != null && json.entities.Length > 0)
            {
                if (json.entities != "*" && json.entities.ToLower() != "all")
                {
                    command.Append($"/codewriterfilter:\"DynamicsCrm.DevKit.CrmSvcUtilExtensions.CodeWriterFilter,DynamicsCrm.DevKit.CrmSvcUtilExtensions\" ");
                }
            }
            command.Append($"/out:\"{json.output}\"");
            return(command.ToString());
        }
예제 #2
0
        private string CreateCommandArgs()
        {
            var command = new StringBuilder();

            command.Append($"/connectionstring:\"{XrmHelper.BuildConnectionString(arguments.Connection)}\" ");
            command.Append($"/nologo ");
            command.Append($"/namespace:{json.@namespace} ");
            if (json.entities != null && json.entities.Length > 0)
            {
                command.Append($"/codewriterfilter:DynamicsCrm.DevKit.CrmSvcUtilExtensions.CodeWriterFilter,DynamicsCrm.DevKit.CrmSvcUtilExtensions ");
            }
            command.Append($"/out:{json.output}");
            return(command.ToString());
        }
 private bool CanConnect(CrmConnection crmConnection)
 {
     try
     {
         var connectionString = XrmHelper.BuildConnectionString(crmConnection.Type, crmConnection.Url, crmConnection.UserName, crmConnection.Password);
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
         CrmServiceClient = new CrmServiceClient(connectionString);
         CrmServiceClient.Execute(new WhoAmIRequest());
         return(true);
     }
     catch
     {
         return(false);
     }
 }
예제 #4
0
 public static IOrganizationService IsConnection(CrmConnection crmConnection)
 {
     try
     {
         if (crmConnection.Type != "ClientSecret")
         {
             crmConnection.Password = EncryptDecrypt.DecryptString(crmConnection.Password);;
         }
         var connectionString = XrmHelper.BuildConnectionString(crmConnection);
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
         var crmServiceClient = new CrmServiceClient(connectionString);
         return(XrmHelper.GetIOrganizationService(crmServiceClient));
     }
     catch
     {
         return(null);
     }
 }
예제 #5
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }
            Cursor = Cursors.WaitCursor;
            EnabledControl(false);

            var connectionString = XrmHelper.BuildConnectionString(cboType.Text, txtUrl.Text, txtUserName.Text, txtPassword.Text);

            if (CanConnect(connectionString))
            {
                SaveConnection();
                ClearControl();
                LoadConnections();
            }
            else
            {
                MessageBox.Show(@"Something wrong with your connection. Please try it again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            EnabledControl(true);
            Cursor = Cursors.Default;
        }
예제 #6
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);
        }
예제 #9
0
        private static bool IsValid(CommandLineArgs arguments)
        {
            if (arguments.SdkLogin.Length > 0 && arguments.SdkLogin.ToLower() == "yes")
            {
                ;
            }
            else
            {
                if (arguments.Connection.Length == 0)
                {
                    CliLog.WriteLine(CliLog.ColorError, $"/conn: missing");
                    return(false);
                }
            }
            if (arguments.Json.Length == 0)
            {
                CliLog.WriteLine(CliLog.ColorError, $"/json: missing");
                return(false);
            }
            var jsonFile = Path.Combine(CurrentDirectory, arguments.Json);

            if (!File.Exists(jsonFile))
            {
                CliLog.WriteLine(CliLog.ColorError, $"/json: DynamicsCrm.DevKit json missing [{jsonFile}]");
                return(false);
            }
            if (arguments.Type.Length == 0)
            {
                CliLog.WriteLine(CliLog.ColorError, $"/type: missing");
                return(false);
            }
            if (arguments.Profile.Length == 0)
            {
                CliLog.WriteLine(CliLog.ColorError, $"/profile: missing");
                return(false);
            }
            if (arguments.SdkLogin.Length > 0 && arguments.SdkLogin.ToLower() == "yes")
            {
                if (arguments.Type.ToLower() != "proxytypes")
                {
                    if (!IsConnectedDynamics365BySdkLogin())
                    {
                        CliLog.WriteLine(CliLog.ColorError, $"SdkLogin failed !!!");
                        return(false);
                    }
                }
            }
            else
            {
                if (!IsConnectedDynamics365(XrmHelper.BuildConnectionString(arguments.Connection)))
                {
                    CliLog.WriteLine(CliLog.ColorError, $"/conn: Cannot connect to Dynamics 365 with your Connection String: {XrmHelper.BuildConnectionStringLog2(arguments.Connection)}");
                    return(false);
                }
            }
            if (CrmServiceClient != null)
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|");
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "Connected: ", CliLog.ColorWhite, XrmHelper.ConnectedUrl(CrmServiceClient));
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "Connection Timeout (seconds): ", CliLog.ColorWhite, CrmServiceClient.MaxConnectionTimeout.TotalSeconds.ToString("#,###"));
            }
            CliLog.WriteLine(CliLog.ColorWhite, "|");
            return(true);
        }