Esempio n. 1
0
 private bool IsValid()
 {
     if (json == null)
     {
         throw new Exception($"{LOG} 'profile' not found: '{arguments.Profile}'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.solution.Length == 0 || json.solution == "???")
     {
         throw new Exception($"{LOG} 'solution' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (!XrmHelper.IsExistSolution(crmServiceClient, json.solution, out var solutionId, out var prefix))
     {
         throw new Exception($"{LOG} solution '{json.solution}' not exist");
     }
     SolutionId = solutionId;
     Prefix     = prefix;
     if (IsSupportWebResourceDependency)
     {
         foreach (var dependency in Dependencies)
         {
             var check = dependency.dependencies.Where(x => x.StartsWith("???_/")).Any();
             if (check)
             {
                 throw new Exception($"{LOG} Found ???_/ in webresource dependencies. Please check DynamicsCrm.DevKit.Cli.json file !!!");
             }
             var check2 = dependency.webresources.Where(x => x.StartsWith("???_/")).Any();
             if (check2)
             {
                 throw new Exception($"{LOG} Found ???_/ in webresource dependencies. Please check DynamicsCrm.DevKit.Cli.json file !!!");
             }
         }
     }
     return(true);
 }
        private void GeneratorLateBound(string entity, int i, int count)
        {
            var lateBound       = new CSharpLateBound();
            var rootNameSpace   = json.rootnamespace;
            var sharedNameSpace = GetSharedNameSpace(json.rootnamespace);
            var crmVersionName  = (CrmVersionName)int.Parse(json.crmversion);
            var generated       = lateBound.Go(XrmHelper.GetIOrganizationService(crmServiceClient), crmVersionName, entity, rootNameSpace, sharedNameSpace);
            var file            = $"{currentDirectory}\\{json.rootfolder}\\{entity}.generated.cs";
            var old             = string.Empty;

            if (File.Exists(file))
            {
                old = File.ReadAllText(file).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
            }
            var @new = generated.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);

            if (old != @new)
            {
                File.WriteAllText(file, generated, System.Text.Encoding.UTF8);
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Processing ", CliLog.ColorGreen, entity, ".generated.cs");
            }
            else
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "No change ", CliLog.ColorGreen, entity, ".generated.cs");
            }
        }
        private string CreateCommandArgsLog()
        {
            var command = new StringBuilder();

            if (arguments.SdkLogin.Length > 0 && arguments.SdkLogin.ToLower() == "yes")
            {
                command.Append("/interactivelogin ");
            }
            else
            {
                command.Append($"/connectionstring:\"{XrmHelper.BuildConnectionStringLog2(arguments.Connection)}\" ");
            }
            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($"/nologo ");
            command.Append($"/SuppressGeneratedCodeAttribute ");
            command.Append($"/generateActions ");
            command.Append($"/namespace:\"{json.@namespace}\" ");
            command.Append($"/out:\"{json.output}\"");
            return(command.ToString());
        }
Esempio n. 4
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);
        }
Esempio n. 5
0
        internal static void ClickNew(DTE dte)
        {
            try
            {
                dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                if (UtilityPackage.GetCrmServiceClient(dte))
                {
                    var crmServiceClient = (CrmServiceClient)UtilityPackage.GetGlobal("CrmServiceClient", dte);
                    var crmUrl           = (string)UtilityPackage.GetGlobal("CrmUrl", dte);

                    UtilityPackage.SetDTEStatusBar(dte, $"[{crmUrl}] Connected");

                    var fullFileName = dte.SelectedItems.Item(1).ProjectItem.FileNames[0];
                    var fileName     = Path.GetFileName(fullFileName);
                    var solutions    = XrmHelper.GetAllSolutions(crmServiceClient);
                    var formItems    = new FormItems(CrmItemType.NewWebResource, solutions, fullFileName, crmUrl);
                    formItems.SetWebResourceName(Utility.GetCurrentProjectDirectoryName(dte));
                    if (formItems.ShowDialog() == DialogResult.OK)
                    {
                        var solutionUniqueName = formItems.SolutionUniqueName;
                        var resourceName       = formItems.ResourceName;
                        var resourceId         = DeployNewWebResource(dte, crmServiceClient, crmUrl, fullFileName, resourceName, solutionUniqueName);
                        AddToCache(dte, fullFileName, resourceId, resourceName);
                    }
                }
                dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
            }
            catch
            {
                UtilityPackage.SetDTEStatusBarAndStopAnimate(dte, "Deploy WebResource failed");
            }
        }
Esempio n. 6
0
        private bool IsOkForRegisterDataProvider(List <DataProviderEvent> dataProviderEvents)
        {
            var count = dataProviderEvents.Count(x => x.Message == "Retrieve");

            if (count != 0 && count != 1)
            {
                throw new Exception($"{LOG} multiple message VirtualTablePlugin.Retrieve found");
            }
            count = dataProviderEvents.Count(x => x.Message == "RetrieveMultiple");
            if (count != 0 && count != 1)
            {
                throw new Exception($"{LOG} multiple message VirtualTablePlugin.RetrieveMultiple found");
            }
            if (XrmHelper.IsVirtualTableSupportCRUD(crmServiceClient))
            {
                count = dataProviderEvents.Count(x => x.Message == "Create");
                if (count != 0 && count != 1)
                {
                    throw new Exception($"{LOG} multiple message VirtualTablePlugin.Create found");
                }
                count = dataProviderEvents.Count(x => x.Message == "Update");
                if (count != 0 && count != 1)
                {
                    throw new Exception($"{LOG} multiple message VirtualTablePlugin.Update found");
                }
                count = dataProviderEvents.Count(x => x.Message == "Delete");
                if (count != 0 && count != 1)
                {
                    throw new Exception($"{LOG} multiple message VirtualTablePlugin.Delete found");
                }
            }
            return(true);
        }
Esempio n. 7
0
 private bool IsValid()
 {
     if (json == null)
     {
         throw new Exception($"{LOG} 'profile' not found: '{arguments.Profile}'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.solution.Length == 0 || json.solution == "???")
     {
         throw new Exception($"{LOG} 'solution' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.datasource == null || json.datasource.Length == 0 || json.datasource == "???")
     {
         throw new Exception($"{LOG} 'datasource' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (!XrmHelper.IsExistSolution(crmServiceClient, json.solution, out var solutionId, out var prefix))
     {
         throw new Exception($"{LOG} solution '{json.solution}' not exist");
     }
     SolutionId     = solutionId;
     Prefix         = prefix;
     DataSourceName = json.datasource.ToLower().StartsWith(prefix.ToLower()) ? json.datasource : $"{Prefix}{json.datasource}";
     if (!XrmHelper.IsExistDataSource(crmServiceClient, $"{DataSourceName}"))
     {
         throw new Exception($"{LOG} name '{json.datasource}' not exist with prefix: {Prefix}");
     }
     return(true);
 }
        private static void CrmCli(CommandLineArgs arguments)
        {
#if DEBUG
            CliLog.WriteLine(CliLog.ColorRed, new string('█', CliLog.StarLength + 2));
            CliLog.WriteLine(CliLog.ColorRed, " DEBUG MODE");
            CliLog.WriteLine(CliLog.ColorRed, new string('█', CliLog.StarLength + 2));
#endif
            CliLog.WriteLine(CliLog.ColorGreen, " ____                              _           ____                  ____             _  ___ _     ____ _ _ ");
            CliLog.WriteLine(CliLog.ColorGreen, "|  _ \\ _   _ _ __   __ _ _ __ ___ (_) ___ ___ / ___|_ __ _ __ ___   |  _ \\  _____   _| |/ (_) |_  / ___| (_)");
            CliLog.WriteLine(CliLog.ColorGreen, "| | | | | | | '_ \\ / _` | '_ ` _ \\| |/ __/ __| |   | '__| '_ ` _ \\  | | | |/ _ \\ \\ / / ' /| | __|| |   | | |");
            CliLog.WriteLine(CliLog.ColorGreen, "| |_| | |_| | | | | (_| | | | | | | | (__\\__ \\ |___| |  | | | | | |_| |_| |  __/\\ V /| . \\| | |_ | |___| | |");
            CliLog.WriteLine(CliLog.ColorGreen, "|____/ \\__, |_| |_|\\__,_|_| |_| |_|_|\\___|___/\\____|_|  |_| |_| |_(_)____/ \\___| \\_/ |_|\\_\\_|\\__(_)____|_|_|");
            CliLog.WriteLine(CliLog.ColorGreen, "       |___/                                          ", CliLog.ColorWhite, "https://github.com/phuocle/Dynamics-Crm-DevKit", CliLog.ColorBlue, $" {Const.Version}");
            CliLog.WriteLine();
            CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "Current Directory path: ", CliLog.ColorWhite, CurrentDirectory);
            CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "DynamicsCrm.DevKit.Cli.exe path: ", CliLog.ColorWhite, Assembly.GetExecutingAssembly().Location);
#if !DEBUG
            try
            {
#endif
            var jsonFile     = Path.Combine(CurrentDirectory, arguments.Json);
            var jsonFileInfo = new FileInfo(jsonFile);
            CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "DynamicsCrm.DevKit.Cli.json path: ", CliLog.ColorWhite, jsonFileInfo.FullName);
            if (arguments.SdkLogin.Length > 0 && arguments.SdkLogin.ToLower() == "yes")
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "Arguments: ",
                                 CliLog.ColorMagenta, "/sdklogin:"******"yes", " ",
                                 CliLog.ColorMagenta, "/json:", CliLog.ColorWhite, arguments.Json, " ",
                                 CliLog.ColorMagenta, "/type:", CliLog.ColorWhite, arguments.Type, " ",
                                 CliLog.ColorMagenta, "/profile:", CliLog.ColorWhite, arguments.Profile
                                 );
            }
            else
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "Arguments: ",
                                 CliLog.ColorMagenta, "/conn:", CliLog.ColorWhite, XrmHelper.BuildConnectionStringLog(arguments.Connection), " ",
                                 CliLog.ColorMagenta, "/json:", CliLog.ColorWhite, arguments.Json, " ",
                                 CliLog.ColorMagenta, "/type:", CliLog.ColorWhite, arguments.Type, " ",
                                 CliLog.ColorMagenta, "/profile:", CliLog.ColorWhite, arguments.Profile
                                 );
            }

            Run(arguments);
#if DEBUG
            CliLog.WriteLine(CliLog.ColorRed, "!!! FINISHED !!!");
            Console.ReadKey();
#endif
#if !DEBUG
        }

        catch (Exception e)
        {
            CliLog.WriteLine(CliLog.ColorError, $"{e.Message}");
            Console.ReadKey();
        }
#endif
        }
        private bool IsValid()
        {
            if (json == null)
            {
                throw new Exception($"{LOG} 'profile' not found: '{arguments.Profile}'. Please check DynamicsCrm.DevKit.Cli.json file.");
            }
            if (json.solution.Length == 0 || json.solution == "???")
            {
                throw new Exception($"{LOG} 'solution' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
            }
            if (json.displayname.Length == 0 || json.displayname == "???")
            {
                throw new Exception($"{LOG} 'displayname' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
            }
            if (json.pluralname.Length == 0 || json.pluralname == "???")
            {
                throw new Exception($"{LOG} 'pluralname' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
            }
            if (json.name.Length == 0 || json.name == "???")
            {
                throw new Exception($"{LOG} 'name' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
            }
            var regex = new Regex("^[a-zA-Z][_a-zA-Z0-9\\s,]*$");

            if (!regex.IsMatch(json.displayname))
            {
                throw new Exception($"{LOG} 'displayname' can only contain alpha-numeric and underscore characters.");
            }
            if (!regex.IsMatch(json.pluralname))
            {
                throw new Exception($"{LOG} 'pluralname' can only contain alpha-numeric and underscore characters.");
            }
            if (!regex.IsMatch(json.name))
            {
                throw new Exception($"{LOG} 'name' can only contain alpha-numeric and underscore characters.");
            }
            if (json.name.Contains(" "))
            {
                throw new Exception($"{LOG} 'name' can cannot contain space character.");
            }
            if (!XrmHelper.IsExistSolution(crmServiceClient, json.solution, out var solutionId, out var prefix))
            {
                throw new Exception($"{LOG} solution '{json.solution}' not exist");
            }
            //SolutionId = solutionId;
            Prefix         = prefix;
            DataSourceName = json.name.ToLower().StartsWith(prefix.ToLower()) ? json.name : $"{Prefix}{json.name}";
            if (XrmHelper.IsExistDataSource(crmServiceClient, DataSourceName))
            {
                throw new Exception($"{LOG} name '{DataSourceName}' exist");
            }
            return(true);
        }
Esempio n. 10
0
        private string CreateCommandArgsLog()
        {
            var command = new StringBuilder();

            command.Append($"/connectionstring:\"{XrmHelper.BuildConnectionStringLog(arguments.Connection)}\" ");
            if (json.entities != null && json.entities.Length > 0)
            {
                command.Append($"/codewriterfilter:DynamicsCrm.DevKit.CrmSvcUtilExtensions.CodeWriterFilter,DynamicsCrm.DevKit.CrmSvcUtilExtensions ");
            }
            command.Append($"/nologo ");
            command.Append($"/namespace:{json.@namespace} ");
            command.Append($"/out:{json.output}");
            return(command.ToString());
        }
Esempio n. 11
0
 private bool CanConnect(string connectionString)
 {
     try
     {
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
         var crmServiceClient = new CrmServiceClient(connectionString);
         CrmService = XrmHelper.GetIOrganizationService(crmServiceClient);
         CrmService.Execute(new WhoAmIRequest());
         return(true);
     }
     catch
     {
         return(false);
     }
 }
 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);
     }
 }
Esempio n. 13
0
 private bool IsValid()
 {
     if (json == null)
     {
         throw new Exception($"{LOG} 'profile' not found: '{arguments.Profile}'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.solution == "???" || (json.solution != null && json?.solution?.Trim().Length == 0))
     {
         throw new Exception($"{LOG} 'solution' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (!XrmHelper.IsExistSolution(crmServiceClient, json.solution, out var solutionId, out var prefix))
     {
         throw new Exception($"{LOG} solution '{json.solution}' not exist");
     }
     return(true);
 }
 private bool IsValid()
 {
     if (json == null)
     {
         throw new Exception($"{LOG} 'profile' not found: '{arguments.Profile}'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.solution.Length == 0 || json.solution == "???")
     {
         throw new Exception($"{LOG} 'solution' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.solutiontype.Length == 0 || json.solutiontype == "???")
     {
         throw new Exception($"{LOG} 'solutiontype' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.solutiontype.ToLower() != "Managed".ToLower() &&
         json.solutiontype.ToLower() != "Unmanaged".ToLower() &&
         json.solutiontype.ToLower() != "Both".ToLower())
     {
         throw new Exception($"{LOG} 'solutiontype' should be: 'Managed' or 'Unmanaged' or 'Both'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.folder.Length == 0 || json.folder == "???")
     {
         throw new Exception($"{LOG} 'folder' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.type.Length == 0 || json.type == "???")
     {
         throw new Exception($"{LOG} 'type' 'empty' or '???'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (json.type.ToLower() != "Extract".ToLower() && json.type.ToLower() != "Pack".ToLower())
     {
         throw new Exception($"{LOG} 'type' should be: 'Extract' or 'Pack'. Please check DynamicsCrm.DevKit.Cli.json file.");
     }
     if (!XrmHelper.IsExistSolution(crmServiceClient, json.solution, out var solutionId, out var prefix))
     {
         throw new Exception($"{LOG} solution '{json.solution}' not exist");
     }
     if (json.mapfile != null && json.mapfile.Length > 0)
     {
         var map = $"{currentDirectory}\\{json.mapfile}";
         if (!File.Exists(map))
         {
             throw new Exception($"{LOG} mapfile '{map}' not exist");
         }
     }
     return(true);
 }
        private void ButtonCheckConnection_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!IsValid())
            {
                return;
            }
            var crmConnection = new CrmConnection
            {
                Name     = textboxName.Text,
                Password = comboBoxType.Text == "ClientSecret" ? textboxPassword.Password : EncryptDecrypt.EncryptString(textboxPassword.Password),
                Type     = comboBoxType.Text,
                Url      = textboxUrl.Text,
                UserName = textboxUser.Text
            };

            stackPanelForm.IsEnabled = false;
            progressBar.Visibility   = System.Windows.Visibility.Visible;
            _ = Task.Factory.StartNew(() =>
            {
                var crmServiceClient = XrmHelper.IsConnected(crmConnection);
                ThreadHelper.JoinableTaskFactory.Run(async delegate
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                    stackPanelForm.IsEnabled = true;
                    progressBar.Visibility   = System.Windows.Visibility.Hidden;
                });
                if (crmServiceClient != null)
                {
                    var devKitConnections = VsixHelper.GetDevKitConnections();
                    devKitConnections.DefaultCrmConnection = crmConnection.Name;
                    devKitConnections.CrmConnections.Add(crmConnection);
                    VsixHelper.SaveDevKitConnections(devKitConnections);
                    LoadConnections();
                    ClearData();
                }
                else
                {
                    ThreadHelper.JoinableTaskFactory.Run(async delegate
                    {
                        await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                        await VS.MessageBox.ShowErrorAsync(@"Something wrong with your connection. Please try it again");
                    });
                }
            }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
        }
Esempio n. 16
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);
     }
 }
        private void GeneratorLateBound(string entity, int i, int count)
        {
            var lateBound       = new CSharpLateBound();
            var rootNameSpace   = json.rootnamespace;
            var sharedNameSpace = GetSharedNameSpace(json.rootnamespace);
            var crmVersionName  = (CrmVersionName)int.Parse(json.crmversion);
            var generated       = lateBound.Go(XrmHelper.GetIOrganizationService(crmServiceClient), crmVersionName, entity, rootNameSpace, sharedNameSpace);
            var file            = $"{currentDirectory}\\{json.rootfolder}\\{entity}.generated.cs";
            var old             = string.Empty;

            if (File.Exists(file))
            {
                old = File.ReadAllText(file);
            }
            var @new = generated;

            if (RemoveForCompare(old) != RemoveForCompare(@new))
            {
                if (File.Exists(file))
                {
                    File.WriteAllText(file, generated, System.Text.Encoding.UTF8);
                    CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Updated ", CliLog.ColorGreen, entity, ".generated.cs");
                }
                else
                {
                    var latebound = Utility.ReadEmbeddedResource("DynamicsCrm.DevKit.Resources.Generator.LateBound.cs");
                    latebound = latebound.Replace("$NameSpace$", json.rootnamespace).Replace("$class$", entity);
                    var fileLateBound = $"{currentDirectory}\\{json.rootfolder}\\{entity}.cs";

                    File.WriteAllText(fileLateBound, latebound, System.Text.Encoding.UTF8);
                    CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Created ", CliLog.ColorGreen, entity, ".cs");

                    File.WriteAllText(file, generated, System.Text.Encoding.UTF8);
                    CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Created ", CliLog.ColorGreen, entity, ".generated.cs");
                }
            }
            else
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorGreen, entity, ".generated.cs");
            }
        }
        private void btnConnection_Click(object sender, EventArgs e)
        {
            var form = new FormConnection(DTE);

            if (form.ShowDialog() == DialogResult.OK)
            {
                Cursor    = Cursors.WaitCursor;
                xrmHelper = new XrmHelper(form.CrmService);
                if (FormType == FormType.PluginItem)
                {
                    ddlMessage.DataSource = xrmHelper.GetSdkMessages(LogicalName);
                }
                else if (FormType == FormType.CustomActionItem)
                {
                    ddlMessage.DisplayMember = "LogicalName";
                    ddlMessage.ValueMember   = "Name";
                    ddlMessage.DataSource    = xrmHelper.GetAllCustomActions();
                }
                btnOk.Enabled = ddlMessage.Items.Count > 0;
                Cursor        = Cursors.Default;
            }
        }
Esempio n. 19
0
        private static void CrmCli(CommandLineArgs arguments)
        {
            CliLog.WriteLine(CliLog.ColorGreen, "╔", new string('═', CliLog.StarLength), "╗");
            CliLog.WriteLine(CliLog.ColorGreen, "║", new string(' ', CliLog.StarLength), "║");
            CliLog.WriteLine(CliLog.ColorGreen, "║", CliLog.ColorCyan, $"              DynamicsCrm.DevKit.Cli - {Const.Version}               ", CliLog.ColorGreen, "║");
            CliLog.WriteLine(CliLog.ColorGreen, "║", new string(' ', CliLog.StarLength), "║");
            CliLog.WriteLine(CliLog.ColorGreen, "╚", new string('═', CliLog.StarLength), "╝");
            CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "Path: ", CliLog.ColorWhite, Assembly.GetExecutingAssembly().Location);
#if DEBUG
            CliLog.WriteLine(CliLog.ColorRed, new string('█', CliLog.StarLength + 2));
            CliLog.WriteLine(CliLog.ColorRed, " DEBUG MODE");
            CliLog.WriteLine(CliLog.ColorRed, new string('█', CliLog.StarLength + 2));
#endif
#if !DEBUG
            try
            {
#endif
            var jsonFile = Path.Combine(CurrentDirectory, arguments.Json);
            CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "DynamicsCrm.DevKit.Cli.json path: ", CliLog.ColorWhite, jsonFile);
            CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "Arguments: ",
                             CliLog.ColorMagenta, "/conn:", CliLog.ColorWhite, XrmHelper.BuildConnectionStringLog(arguments.Connection), " ",
                             CliLog.ColorMagenta, "/json:", CliLog.ColorWhite, arguments.Json, " ",
                             CliLog.ColorMagenta, "/type:", CliLog.ColorWhite, arguments.Type, " ",
                             CliLog.ColorMagenta, "/profile:", CliLog.ColorWhite, arguments.Profile
                             );
            Run(arguments);
#if DEBUG
            CliLog.WriteLine(CliLog.ColorRed, "!!! FINISHED !!!");
            Console.ReadKey();
#endif
#if !DEBUG
        }
        catch (Exception e)
        {
            CliLog.WriteLine(CliLog.ColorError, $"{e.Message}");
            Console.ReadKey();
        }
#endif
        }
 private void ButtonOK_Click(object sender, System.Windows.RoutedEventArgs e)
 {
     if (IsOOBConnection)
     {
         DialogResult = true;
         Close();
     }
     else
     {
         stackPanelForm.IsEnabled = false;
         progressBar.Visibility   = System.Windows.Visibility.Visible;
         var selectedCrmConnection = comboBoxSavedConnection.SelectedItem as CrmConnection;
         _ = Task.Factory.StartNew(() => {
             CrmServiceClient = XrmHelper.IsConnected(selectedCrmConnection);
             ThreadHelper.JoinableTaskFactory.Run(async delegate
             {
                 await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                 DialogResult = true;
                 Close();
             });
         }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
     }
 }
        private void btnConnection_Click(object sender, System.EventArgs e)
        {
            var form = new FormConnection(DTE);

            if (form.ShowDialog() == DialogResult.OK)
            {
                Cursor        = Cursors.WaitCursor;
                CrmConnection = form.CrmConnection;
                CrmService    = form.CrmService;
                var xrmHelper = new XrmHelper(CrmService);
                if (FormType == FormType.Plugin || FormType == FormType.LateBoundClass || FormType == FormType.JsWebApiItem || FormType == FormType.Workflow)
                {
                    cboEntity.DataSource = xrmHelper.GetAllEntities();
                    btnOk.Enabled        = cboEntity.Items.Count > 0;
                    txtName_TextChanged(null, null);
                    cboEntity_SelectedIndexChanged(null, null);
                }
                if (FormType == FormType.ProxyTypes || FormType == FormType.WebResource || FormType == FormType.Console || FormType == FormType.CustomAction)
                {
                    btnOk.Enabled = true;
                }
                Cursor = Cursors.Default;
            }
        }
Esempio n. 22
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;
        }
Esempio n. 23
0
        private void RegisterDataProvider(List <DataProviderEvent> dataProviderEvents, string dataProviderName)
        {
            var entity = new Entity("entitydataprovider");

            entity.Attributes.Add("name", dataProviderName);
            entity.Attributes.Add("datasourcelogicalname", $"{DataSourceName.ToLower()}");
            entity.Attributes.Add("solutionid", SolutionId);

            var retrieve = dataProviderEvents.Where(x => x.Message == "Retrieve").FirstOrDefault();

            if (retrieve == null)
            {
                entity.Attributes.Add("retrieveplugin", new Guid("{c1919979-0021-4f11-a587-a8f904bdfdf9}"));
            }
            else
            {
                entity.Attributes.Add("retrieveplugin", retrieve.PluginTypeId);
            }

            var retrievemultiple = dataProviderEvents.Where(x => x.Message == "RetrieveMultiple").FirstOrDefault();

            if (retrievemultiple == null)
            {
                entity.Attributes.Add("retrievemultipleplugin", new Guid("{c1919979-0021-4f11-a587-a8f904bdfdf9}"));
            }
            else
            {
                entity.Attributes.Add("retrievemultipleplugin", retrievemultiple.PluginTypeId);
            }
            if (XrmHelper.IsVirtualTableSupportCRUD(crmServiceClient))
            {
                var create = dataProviderEvents.Where(x => x.Message == "Create").FirstOrDefault();
                if (create == null)
                {
                    entity.Attributes.Add("createplugin", new Guid("{c1919979-0021-4f11-a587-a8f904bdfdf9}"));
                }
                else
                {
                    entity.Attributes.Add("createplugin", create.PluginTypeId);
                }

                var update = dataProviderEvents.Where(x => x.Message == "Update").FirstOrDefault();
                if (update == null)
                {
                    entity.Attributes.Add("updateplugin", new Guid("{c1919979-0021-4f11-a587-a8f904bdfdf9}"));
                }
                else
                {
                    entity.Attributes.Add("updateplugin", update.PluginTypeId);
                }

                var delete = dataProviderEvents.Where(x => x.Message == "Delete").FirstOrDefault();
                if (delete == null)
                {
                    entity.Attributes.Add("deleteplugin", new Guid("{c1919979-0021-4f11-a587-a8f904bdfdf9}"));
                }
                else
                {
                    entity.Attributes.Add("deleteplugin", delete.PluginTypeId);
                }
            }

            var entityDataProvider = GetEntityDataProviderId(dataProviderName);

            if (entityDataProvider == null)
            {
                var request = new CreateRequest();
                if (request.Parameters == null)
                {
                    request.Parameters = new ParameterCollection();
                }
                request.Target = entity;
                request.Parameters.Add("SuppressDuplicateDetection", true);
                request.Parameters.Add("SolutionUniqueName", json.solution);
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorRed, " Registering", CliLog.ColorGreen, " Data Provider: ", CliLog.ColorCyan, $"{dataProviderName}");
                crmServiceClient.Execute(request);
            }
            else
            {
                var entitydataproviderid   = entityDataProvider.GetAttributeValue <Guid?>("entitydataproviderid");
                var retrieveplugin         = entityDataProvider.GetAttributeValue <Guid?>("retrieveplugin");
                var retrievemultipleplugin = entityDataProvider.GetAttributeValue <Guid?>("retrievemultipleplugin");
                var createplugin           = entityDataProvider.GetAttributeValue <Guid?>("createplugin");
                var deleteplugin           = entityDataProvider.GetAttributeValue <Guid?>("deleteplugin");
                var updateplugin           = entityDataProvider.GetAttributeValue <Guid?>("updateplugin");
                if (retrievemultipleplugin != entity.GetAttributeValue <Guid>("retrievemultipleplugin") ||
                    retrieveplugin != entity.GetAttributeValue <Guid>("retrieveplugin") ||
                    createplugin != entity.GetAttributeValue <Guid>("createplugin") ||
                    deleteplugin != entity.GetAttributeValue <Guid>("deleteplugin") ||
                    updateplugin != entity.GetAttributeValue <Guid>("updateplugin")
                    )
                {
                    entity.Attributes.Add("entitydataproviderid", entitydataproviderid.Value);
                    var request = new UpdateRequest
                    {
                        Target = entity
                    };
                    CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorRed, " Updating", CliLog.ColorGreen, " Data Provider: ", CliLog.ColorCyan, $"{dataProviderName}");
                    crmServiceClient.Execute(request);
                }
            }
        }
Esempio n. 24
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);
        }
Esempio n. 27
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);
        }
        private void btnConnection_Click(object sender, EventArgs e)
        {
            var form = new FormConnection(Dte);

            if (form.ShowDialog() == DialogResult.OK)
            {
                progressBar.Visible   = true;
                btnConnection.Enabled = false;
                btnCancel.Enabled     = false;
                List <string>    list  = null;
                List <XrmEntity> list2 = null;
                _xrmHelper = new XrmHelper(form.CrmService);
                var  failed = false;
                Task task   = Task.Factory.StartNew(() =>
                {
                    if (FormType == FormType.PluginItem)
                    {
                        try
                        {
                            list = _xrmHelper.GetSdkMessages(LogicalName);
                        }
                        catch
                        {
                            failed = true;
                        }
                    }
                    else if (FormType == FormType.CustomActionItem)
                    {
                        list2 = _xrmHelper.GetAllCustomActions();
                    }
                });
                while (!task.IsCompleted)
                {
                    Application.DoEvents();
                }
                if (failed)
                {
                    var form2 = new FormProject(FormType.SelectEntity, Dte);
                    form2.LoadSelectEntity(_xrmHelper.GetAllEntities());
                    if (form2.ShowDialog() == DialogResult.OK)
                    {
                        list        = _xrmHelper.GetSdkMessages(form2.SelectedEntity.ToLower());
                        EntityName  = form2.SelectedEntity;
                        LogicalName = form2.SelectedEntity.ToLower();
                    }
                }
                btnConnection.Enabled = true;
                progressBar.Visible   = false;
                if (FormType == FormType.PluginItem)
                {
                    ddlMessage.DataSource = list;
                }
                else if (FormType == FormType.CustomActionItem)
                {
                    ddlMessage.DisplayMember = "LogicalName";
                    ddlMessage.ValueMember   = "Name";
                    ddlMessage.DataSource    = list2;
                }
                btnOk.Enabled        = ddlMessage.Items.Count > 0;
                ddlMessage.Enabled   = btnOk.Enabled;
                ddlStage.Enabled     = btnOk.Enabled;
                ddlExecution.Enabled = btnOk.Enabled;
                btnCancel.Enabled    = true;
                btnOk.Focus();
            }
        }
        private void GeneratorJsWebApi(string entity, int i, int count)
        {
            var jsForm        = new List <string>();
            var isDebugForm   = false;
            var isDebugWebApi = false;
            var jsFormVersion = string.Empty;

            if (!File.Exists($"{currentDirectory}\\{json.rootfolder}\\{entity}.js"))
            {
                var text = string.Empty;
                text += "//@ts-check\r\n";
                text += $"///<reference path=\"{entity}.d.ts\" />\r\n";
                Utility.ForceWriteAllText($"{currentDirectory}\\{json.rootfolder}\\{entity}.js", text);
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Created ", CliLog.ColorGreen, entity, ".js");
            }
            var fileTypeScriptDeclaration = $"{currentDirectory}\\{json.rootfolder}\\{entity}.d.ts";

            if (File.Exists(fileTypeScriptDeclaration))
            {
                var lines = File.ReadAllLines(fileTypeScriptDeclaration);
                if (lines.Count() != 0)
                {
                    var json    = lines[lines.Length - 1];
                    var comment = SimpleJson.DeserializeObject <CommentTypeScriptDeclaration>(json.Substring("//".Length).Replace("'", "\""));
                    isDebugWebApi = comment.IsDebugWebApi;
                    jsForm        = comment.JsForm;
                    isDebugForm   = comment.IsDebugForm;
                    jsFormVersion = comment.JsFormVersion;
                }
            }
            var parts       = json.rootnamespace.Split(".".ToCharArray());
            var projectName = parts.Length > 1 ? parts[1] : parts[0];

            if (json.debug.Length > 0)
            {
                isDebugWebApi = json.debug == "yes" ? true : false;
            }
            var jsWebApi = new JsWebApi(XrmHelper.GetIOrganizationService(crmServiceClient), projectName, entity, isDebugWebApi, jsForm, isDebugForm, jsFormVersion);

            jsWebApi.GeneratorCode();
            var old = string.Empty;

            if (File.Exists(fileTypeScriptDeclaration))
            {
                old = File.ReadAllText(fileTypeScriptDeclaration); //.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
            }
            var @new = jsWebApi.WebApiCodeTypeScriptDeclaration;   //.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);

            if (RemoveForCompare(old) != RemoveForCompare(@new))
            {
                if (File.Exists(fileTypeScriptDeclaration))
                {
                    CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Updated ", CliLog.ColorGreen, entity, ".d.ts");
                }
                else
                {
                    CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Created ", CliLog.ColorGreen, entity, ".d.ts");
                }
                Utility.ForceWriteAllText(fileTypeScriptDeclaration, jsWebApi.WebApiCodeTypeScriptDeclaration);
            }
            else
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorGreen, entity, ".d.ts");
            }
            var fileWebApi = $"{currentDirectory}\\{json.rootfolder}\\{entity}.webapi.js";

            old = string.Empty;
            if (File.Exists(fileWebApi))
            {
                old = File.ReadAllText(fileWebApi); //.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
            }
            @new = jsWebApi.WebApiCode;             //.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
            if (RemoveForCompare(old) != RemoveForCompare(@new))
            {
                if (File.Exists(fileWebApi))
                {
                    CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Updated ", CliLog.ColorGreen, entity, ".webapi.js");
                }
                else
                {
                    CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Created ", CliLog.ColorGreen, entity, ".webapi.js");
                }
                Utility.ForceWriteAllText(fileWebApi, jsWebApi.WebApiCode);
            }
            else
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorBlue, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorGreen, entity, ".webapi.js");
            }
        }
        private void GeneratorJsForm(string entity, int i, int count)
        {
            var forms                     = new List <string>();
            var isDebugForm               = true;
            var webApi                    = true;
            var isDebugWebApi             = true;
            var fileTypeScriptDeclaration = $"{currentDirectory}\\{json.rootfolder}\\{entity}.d.ts";

            if (File.Exists(fileTypeScriptDeclaration))
            {
                var lines = File.ReadAllLines(fileTypeScriptDeclaration);
                if (lines.Count() != 0)
                {
                    var json    = lines[lines.Length - 1];
                    var comment = SimpleJson.DeserializeObject <CommentTypeScriptDeclaration>(json.Substring("//".Length).Replace("'", "\""));
                    forms         = comment.JsForm;
                    isDebugForm   = comment.IsDebugForm;
                    webApi        = comment.JsWebApi;
                    isDebugWebApi = comment.IsDebugWebApi;
                }
            }
            if (forms.Count == 0)
            {
                var parts2       = json.rootnamespace.Split(".".ToCharArray());
                var projectName2 = parts2.Length > 1 ? parts2[1] : parts2[0];
                var jsForm2      = new JsForm(XrmHelper.GetIOrganizationService(crmServiceClient), projectName2, entity);
                forms = GetAllForms(entity, jsForm2);
            }
            if (forms.Count == 0)
            {
                return;
            }
            if (File.Exists($"{currentDirectory}\\{json.rootfolder}\\{entity}.js"))
            {
                var text = File.ReadAllText($"{currentDirectory}\\{json.rootfolder}\\{entity}.js");
                text = text.Replace("\r\n", string.Empty);
                if (text.Length == 0 || text == $"//@ts-check///<reference path=\"{entity}.d.ts\" />")
                {
                    Utility.TryDeleteFile($"{currentDirectory}\\{json.rootfolder}\\{entity}.js");
                }
            }
            var parts       = json.rootnamespace.Split(".".ToCharArray());
            var projectName = parts.Length > 1 ? parts[1] : parts[0];
            var jsForm      = new JsForm(XrmHelper.GetIOrganizationService(crmServiceClient), projectName, entity);

            if (json.debug.Length > 0)
            {
                isDebugForm = json.debug == "yes" ? true : false;
            }
            jsForm.GeneratorCode(forms, isDebugForm, webApi, isDebugWebApi);
            if (!File.Exists($"{currentDirectory}\\{json.rootfolder}\\{entity}.js"))
            {
                var text = jsForm.Form;
                text = text.Replace($"[[{entity}]]", $"{entity}.d.ts");
                Utility.ForceWriteAllText($"{currentDirectory}\\{json.rootfolder}\\{entity}.js", text);
            }
            var old = string.Empty;

            if (File.Exists(fileTypeScriptDeclaration))
            {
                old = File.ReadAllText(fileTypeScriptDeclaration).Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
            }
            var @new = jsForm.FormCodeTypeScriptDeclaration.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);

            if (old != @new)
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Processing ", CliLog.ColorGreen, entity, ".d.ts");
                Utility.ForceWriteAllText(fileTypeScriptDeclaration, jsForm.FormCodeTypeScriptDeclaration);
            }
            else
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "No change ", CliLog.ColorGreen, entity, ".d.ts");
            }
            var fileForm = $"{currentDirectory}\\{json.rootfolder}\\{entity}.form.js";

            old = string.Empty;
            if (File.Exists(fileForm))
            {
                old = File.ReadAllText(fileForm).Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
            }
            @new = jsForm.FormCode.Replace(" ", string.Empty).Replace("\r\n", string.Empty).Replace("\t", string.Empty);
            if (old != @new)
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "Processing ", CliLog.ColorGreen, entity, ".form.js");
                Utility.ForceWriteAllText(fileForm, jsForm.FormCode);
            }
            else
            {
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, string.Format("{0,0}{1," + count.ToString().Length + "}", "", i) + ": ", CliLog.ColorMagenta, "No change ", CliLog.ColorGreen, entity, ".form.js");
            }
        }