Ejemplo n.º 1
0
        void btnSaveDatabaseSettings_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btnSaveDatabaseSettings.IsEnabled   = false;
                cboDatabaseType.IsEnabled           = false;
                btnRefreshMSSQLServerList.IsEnabled = false;

                if (ServerState.Instance.DatabaseIsSQLite)
                {
                    ServerSettings.Instance.Database.Type = Server.Databases.DatabaseTypes.Sqlite;
                }
                else if (ServerState.Instance.DatabaseIsSQLServer)
                {
                    if (string.IsNullOrEmpty(txtMSSQL_DatabaseName.Text) ||
                        string.IsNullOrEmpty(txtMSSQL_Password.Password) ||
                        string.IsNullOrEmpty(cboMSSQLServerList.Text) ||
                        string.IsNullOrEmpty(txtMSSQL_Username.Text))
                    {
                        MessageBox.Show(Commons.Properties.Resources.Server_FillOutSettings,
                                        Commons.Properties.Resources.Error,
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        txtMSSQL_DatabaseName.Focus();
                        return;
                    }

                    ServerSettings.Instance.Database.Type     = Server.Databases.DatabaseTypes.SqlServer;
                    ServerSettings.Instance.Database.Schema   = txtMSSQL_DatabaseName.Text;
                    ServerSettings.Instance.Database.Password = txtMSSQL_Password.Password;
                    ServerSettings.Instance.Database.Hostname = cboMSSQLServerList.Text;
                    ServerSettings.Instance.Database.Username = txtMSSQL_Username.Text;
                }
                else if (ServerState.Instance.DatabaseIsMySQL)
                {
                    if (string.IsNullOrEmpty(txtMySQL_DatabaseName.Text) ||
                        string.IsNullOrEmpty(txtMySQL_Password.Password) ||
                        string.IsNullOrEmpty(txtMySQL_ServerAddress.Text) ||
                        string.IsNullOrEmpty(txtMySQL_Username.Text))
                    {
                        MessageBox.Show(Commons.Properties.Resources.Server_FillOutSettings,
                                        Commons.Properties.Resources.Error,
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        txtMySQL_DatabaseName.Focus();
                        return;
                    }

                    ServerSettings.Instance.Database.Type     = Server.Databases.DatabaseTypes.MySql;
                    ServerSettings.Instance.Database.Schema   = txtMySQL_DatabaseName.Text;
                    ServerSettings.Instance.Database.Password = txtMySQL_Password.Password;
                    ServerSettings.Instance.Database.Hostname = txtMySQL_ServerAddress.Text;
                    ServerSettings.Instance.Database.Username = txtMySQL_Username.Text;
                }

                logger.Info("Initializing DB...");

                ShokoServer.RunWorkSetupDB();
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.ToString());
                MessageBox.Show(Commons.Properties.Resources.Server_FailedToStart + ex.Message,
                                Commons.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 2
0
 private async void DataFilterBtn_Click(object sender, RoutedEventArgs e)
 {
     MessageBox.Show("Feature coming soon!", "Can't have everything, y'know", MessageBoxButton.OK, MessageBoxImage.Warning);
 }
Ejemplo n.º 3
0
        public string Column_Change(UIApplication uiapp, Document doc)
        {
            string result = "S";

            try
            {
                if (element_Changes.Count() > 0)
                {
                    foreach (Element_Change change in element_Changes)
                    {
                        if (change.element == null)
                        {
                            ElementTransformUtils.CopyElements(doc_link, new List <ElementId>()
                            {
                                change.element_link.Id
                            }, doc, Transform.Identity, new CopyPasteOptions()).First();
                        }
                        else if (change.element_link == null)
                        {
                            if (change.element.Pinned)
                            {
                                change.element.Pinned = false;
                            }
                            doc.Delete(change.element.Id);
                        }
                        else
                        {
                            if (change.element.Pinned)
                            {
                                change.element.Pinned = false;
                            }
                            if (change.type_change == "Profile")
                            {
                                var eles = ElementTransformUtils.CopyElements(doc_link, new List <ElementId>()
                                {
                                    change.element_link.Id
                                }, doc, Transform.Identity, new CopyPasteOptions());
                                // Change host
                                //................
                                ElementMulticategoryFilter filter = new ElementMulticategoryFilter(new List <BuiltInCategory>()
                                {
                                    BuiltInCategory.OST_Windows, BuiltInCategory.OST_Doors
                                });
                                List <Element_Group> support_all = new List <Element_Group>();
                                foreach (FamilyInstance familyInstance in new FilteredElementCollector(doc).WherePasses(filter).WhereElementIsNotElementType().Where(x => (x as FamilyInstance).Host.Id == change.element_link.Id).Cast <FamilyInstance>().ToList())
                                {
                                    support_all.Add(new Element_Group()
                                    {
                                        element       = familyInstance,
                                        element_text2 = familyInstance.LookupParameter("Text2").AsString(),
                                        link          = false
                                    });
                                }
                                foreach (FamilyInstance familyInstance in new FilteredElementCollector(doc).WherePasses(filter).WhereElementIsNotElementType().Where(x => (x as FamilyInstance).Host.Id == eles.First()).Cast <FamilyInstance>().ToList())
                                {
                                    support_all.Add(new Element_Group()
                                    {
                                        element       = familyInstance,
                                        element_text2 = familyInstance.LookupParameter("Text2").AsString(),
                                        link          = true
                                    });
                                }

                                List <List <Element_Group> > support_group = new List <List <Element_Group> >(support_all
                                                                                                              .GroupBy(x => new { x.element_text2 })
                                                                                                              .Select(y => new List <Element_Group>(y)));

                                foreach (List <Element_Group> familyInstances in support_group)
                                {
                                    if (familyInstances.Count() == 2)
                                    {
                                        familyInstances[1].element.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).Set(familyInstances[0].element.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).AsElementId());
                                    }
                                }

                                doc.Delete(change.element.Id);
                                doc.GetElement(eles.First()).Pinned = true;
                            }
                            else
                            {
                                if (change.type_change == "Location")
                                {
                                    if (change.parameter_category_name == Source.Category_Check[1].name)
                                    {
                                        LocationPoint columnPoint = change.element.Location as LocationPoint;
                                        columnPoint.Point = (change.element_link.Location as LocationPoint).Point;
                                    }
                                    else if (change.parameter_category_name == Source.Category_Check[2].name)
                                    {
                                        LocationCurve columnPoint = change.element.Location as LocationCurve;
                                        columnPoint.Curve = (change.element_link.Location as LocationCurve).Curve;
                                    }
                                    else if (change.parameter_category_name == Source.Category_Check[4].name)
                                    {
                                        Wall          wall        = change.element as Wall;
                                        Wall          wall_change = change.element_link as Wall;
                                        LocationCurve columnPoint = wall.Location as LocationCurve;
                                        columnPoint.Curve = (wall_change.Location as LocationCurve).Curve;
                                    }
                                    else if (change.parameter_category_name == Source.Category_Check[5].name)
                                    {
                                        LocationPoint columnPoint = change.element.Location as LocationPoint;
                                        columnPoint.Point = (change.element_link.Location as LocationPoint).Point;
                                    }
                                    else if (change.parameter_category_name == Source.Category_Check[6].name)
                                    {
                                        LocationPoint columnPoint = change.element.Location as LocationPoint;
                                        columnPoint.Point = (change.element_link.Location as LocationPoint).Point;
                                    }
                                    else if (change.parameter_category_name == Source.Category_Check[7].name)
                                    {
                                        LocationPoint columnPoint = change.element.Location as LocationPoint;
                                        columnPoint.Point = (change.element_link.Location as LocationPoint).Point;
                                    }
                                }
                                foreach (Parameter_Change para in change.parameter_change)
                                {
                                    if (para.parameter.Definition.Name == "Type")
                                    {
                                        if (change.parameter_category_name != Source.Category_Check[5].name && change.parameter_category_name != Source.Category_Check[6].name)
                                        {
                                            ElementId   type_id     = new ElementId(-1);
                                            ElementType link_symbol = doc_link.GetElement(change.element_link.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).AsElementId()) as ElementType;
                                            foreach (data_category data in Source.Category_Check)
                                            {
                                                if (change.parameter_category_name == data.name)
                                                {
                                                    var type = new FilteredElementCollector(doc).OfCategory(data.code).WhereElementIsElementType().Where(x => x.Name == link_symbol.Name).ToList();
                                                    if (type.Count() > 0)
                                                    {
                                                        type_id = type.First().Id;
                                                    }
                                                    else
                                                    {
                                                        var elment_copy = ElementTransformUtils.CopyElements(doc_link, new List <ElementId>()
                                                        {
                                                            link_symbol.Id
                                                        }, doc, Transform.Identity, new CopyPasteOptions());
                                                        type_id = elment_copy.First();
                                                    }
                                                    break;
                                                }
                                            }
                                            change.element.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).Set(type_id);
                                        }
                                    }
                                    else
                                    {
                                        Support.GetParameterValue(para.parameter, para.parameter_link);
                                    }
                                }
                                if (!change.element.Pinned)
                                {
                                    change.element.Pinned = true;
                                }
                            }
                        }
                        change.color = Source.color_used_change;
                        data_update.Items.Refresh();
                    }
                }
                F_ListBox.Save_Data_Check(my_element_change, link_file, uiapp, doc_link);
            }
            catch (Exception ex)
            {
                result = "F";
                MessageBox.Show(ex.Message);
            }
            return(result);
        }
        private void TreeViewItem_OnItemSelected(object sender, RoutedEventArgs e)
        {
            var item = myTreeItem.SelectedItem as TreeViewItem;

            if (item == null)
            {
                return;
            }
            AliasesText.Text = "You select " + item.Header;
            string nodePath = MakePathFromSelected(item, "", out string aliasname);

            try
            {
                if (nodePath == "\\")
                {
                    nodePath = "";
                }

                nodeImport = client.GetNode(nodePath, aliasname);
            }
            catch (FaultException <InvalidUserIPFault> )
            {
                MessageBox.Show("Your IP adress is in Black List. Program will be closed. ");
                Application.Current.Shutdown();
            }

            catch (FaultException <AliasNotExistFault> )
            {
                AliasesText.Text = "This alias is now not available.";
                RemoveAlias(aliasname);
                return;
            }
            catch (FaultException <ItemNotExcistFault> ex)
            {
                AliasesText.Text = "Access to selected item is now not available." + "\n\r" + ex.Message;

                if (sender is Button)
                {
                    item.Items.Remove(sender);
                }
                else
                {
                    if (item.Parent as TreeViewItem != null)
                    {
                        var parent = (myTreeItem.SelectedItem as TreeViewItem).Parent as TreeViewItem;
                        parent.Items.Remove(myTreeItem.SelectedItem);
                    }
                    else
                    {
                        myTreeItem.Items.Remove(item);
                    }
                }

                return;
            }

            catch (Exception ex)
            {
                AliasesText.Text = "Something wrong.. " + ex.Message;
                return;
            }

            var newChild = myTreeItem.SelectedItem as TreeViewItem;

            newChild.Items.Clear();
            foreach (AliasNode nodeItem in nodeImport.NodeArray)
            {
                if (nodeItem.IsDirectory)
                {
                    newChild.Items.Add(new TreeViewItem {
                        Header = nodeItem.ItemName
                    });
                }
                else
                {
                    var button = new Button
                    {
                        Content = nodeItem.ItemName
                    };
                    button.Click += Button_Click;
                    newChild.Items.Add(button);
                }
            }
        }
Ejemplo n.º 5
0
        public MainWindow()
        {
            InitializeComponent();
            var dialog = new FolderBrowserDialog();

            dialog.ShowNewFolderButton = false;
            dialog.Description         = "Select the folder which contains the resource files you wish to strip of newlines";
            var dialogResult = dialog.ShowDialog();

            if (dialogResult == System.Windows.Forms.DialogResult.OK)
            {
                var path = dialog.SelectedPath;
                try
                {
                    var filePaths = Directory.GetFiles(path, "*.resx");
                    if (filePaths.Count() > 0)
                    {
                        var mbResult = MessageBox.Show("The following resx files' values will be stripped of newlines:\n\n" +
                                                       filePaths.Aggregate((current, next) => current + "\n" + next) +
                                                       "\n\nDo you want to proceed?",
                                                       "Confirm files to be stripped",
                                                       MessageBoxButton.YesNo,
                                                       MessageBoxImage.Warning);

                        if (mbResult == MessageBoxResult.Yes)
                        {
                            foreach (var filePath in filePaths)
                            {
                                bool          currentlyReadingMultiLineValue = false;
                                StringBuilder result      = new StringBuilder();
                                StringBuilder innerResult = null;
                                var           lines       = File.ReadAllLines(filePath);
                                for (var i = 0; i < lines.Length; i++)
                                {
                                    if (Regex.IsMatch(lines[i], @"<value>.*<\/value>"))
                                    {
                                        result.AppendLine(lines[i]);
                                    }
                                    else if (Regex.IsMatch(lines[i], @"<value>"))
                                    {
                                        currentlyReadingMultiLineValue = true;
                                        innerResult = new StringBuilder();
                                        if (!lines[i].EndsWith(@"<value>") && !lines[i].EndsWith(" "))
                                        {
                                            innerResult.Append(lines[i] + " ");
                                        }
                                        else
                                        {
                                            innerResult.Append(lines[i]);
                                        }
                                    }
                                    else if (Regex.IsMatch(lines[i], @"<\/value>"))
                                    {
                                        currentlyReadingMultiLineValue = false;
                                        result.AppendLine(innerResult.ToString().TrimEnd(' ') + lines[i]);
                                    }
                                    else if (currentlyReadingMultiLineValue)
                                    {
                                        if (lines[i].EndsWith(" "))
                                        {
                                            innerResult.Append(lines[i]);
                                        }
                                        else
                                        {
                                            innerResult.Append(lines[i] + " ");
                                        }
                                    }
                                    else if (i != lines.Length - 1)
                                    {
                                        result.AppendLine(lines[i]);
                                    }
                                    else
                                    {
                                        result.Append(lines[i]);
                                    }
                                }
                                File.WriteAllText(filePath, result.ToString());
                            }
                            MessageBox.Show("Resx values successfully stripped of newlines.", "Success",
                                            MessageBoxButton.OK);
                        }
                        else
                        {
                            MessageBox.Show("Operation cancelled. No files were modified.", "Cancelled",
                                            MessageBoxButton.OK);
                        }
                    }
                    else
                    {
                        MessageBox.Show("No resx files were found in the specified directory.", "No files found",
                                        MessageBoxButton.OK);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occurred while attempting to load the file. The error is:"
                                    + Environment.NewLine + ex + Environment.NewLine);
                }
            }
            Application.Current.Shutdown();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Import(object sender, EventArgs e)
        {
            DTE2 dte = Package.GetGlobalService(typeof(DTE)) as DTE2;

            try
            {
                bool closed = SolutionSaveService.SaveAndCloseSolution(dte.Solution);
                if (!closed)
                {
                    return;
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show($"Project import could not be started:\n{exception.Message}", "Import failed");
                return;
            }

            ThreadHelper.JoinableTaskFactory.Run(
                "Importing project",
                async(progress) =>
            {
                if (_plcncliCommunication == null)
                {
                    MessageBox.Show("Could not import project because no plcncli communication found.");
                }
                string projectFilePath = string.Empty;
                if (OpenImportWizard())
                {
                    string projectDirectory = Path.GetDirectoryName(projectFilePath);

                    progress.Report(new ThreadedWaitDialogProgressData("Fetching project information."));
                    ProjectInformationCommandResult projectInformation = await GetProjectInformation();
                    if (projectInformation == null)
                    {
                        return;
                    }
                    string projectName = projectInformation.Name;
                    string projectType = projectInformation.Type;
                    IEnumerable <TargetResult> projectTargets = projectInformation.Targets;

                    await CreateVSProject(projectType, projectDirectory, projectName, projectTargets);

                    MessageBox.Show("If the imported project has source folders different from the standard 'src', they have to be set manually in the project properties.",
                                    "Successfully imported project", MessageBoxButton.OK, MessageBoxImage.Information);
                }

                bool OpenImportWizard()
                {
                    ImportDialogModel model         = new ImportDialogModel();
                    ImportDialogViewModel viewModel = new ImportDialogViewModel(model);
                    ImportDialogView view           = new ImportDialogView(viewModel);

                    view.ShowModal();
                    if (view.DialogResult == true)
                    {
                        projectFilePath = model.ProjectFilePath;
                        return(true);
                    }
                    return(false);
                }

                async Task <ProjectInformationCommandResult> GetProjectInformation()
                {
                    ProjectInformationCommandResult result = null;
                    await Task.Run(() =>
                    {
                        try
                        {
                            result = _plcncliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                          typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project,
                                                                          $"\"{projectFilePath}\"") as ProjectInformationCommandResult;
                        }
                        catch (PlcncliException ex)
                        {
                            result = _plcncliCommunication.ConvertToTypedCommandResult <ProjectInformationCommandResult>(ex.InfoMessages);
                            throw ex;
                        }
                    });
                    return(result);
                }

                async Task CreateVSProject(string projectType, string projectDirectory, string projectName, IEnumerable <TargetResult> projectTargets)
                {
                    progress.Report(new ThreadedWaitDialogProgressData("Creating project files."));
                    bool projectFileCreated = await CreateVSProjectFile();
                    if (!projectFileCreated)
                    {
                        return;
                    }

                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    dte.Solution.Create(projectDirectory, projectName);
                    dte.Solution.AddFromFile($"{Path.Combine(projectDirectory, projectName)}.vcxproj");

                    Project project = null;
                    foreach (Project proj in dte.Solution.Projects)
                    {
                        if (proj.Name.Equals(projectName))
                        {
                            project = proj;
                            break;
                        }
                    }
                    if (project == null)
                    {
                        MessageBox.Show("Something went wrong during creation of new project. Project was not found in solution.");
                        return;
                    }

                    progress.Report(new ThreadedWaitDialogProgressData("Creating project configurations."));
                    ProjectConfigurationManager.CreateConfigurationsForAllProjectTargets
                        (projectTargets.Select(t => t.GetNameFormattedForCommandLine()), project);

                    //**********delete intermediate**********
                    string intermediateFolder = Path.Combine(projectDirectory, "intermediate");
                    if (Directory.Exists(intermediateFolder))
                    {
                        Directory.Delete(intermediateFolder, true);
                    }

                    //**********add project items to project**********

                    IEnumerable <string> directories = Directory.GetDirectories(projectDirectory).Where(d => !d.EndsWith("bin"));

                    IEnumerable <string> projectFiles =
                        Directory.GetFiles(projectDirectory, "*.*pp", SearchOption.TopDirectoryOnly)
                        .Concat(Directory.GetFiles(projectDirectory, "*.txt", SearchOption.TopDirectoryOnly))
                        .Where(f => !f.EndsWith("UndefClang.hpp"))
                        .Concat(directories.SelectMany(d => Directory.GetFiles(d, "*.*pp", SearchOption.AllDirectories)
                                                       .Concat(Directory.GetFiles(d, "*.txt", SearchOption.AllDirectories)))
                                .Where(f => !f.EndsWith("UndefClang.hpp"))
                                );

                    foreach (string file in projectFiles)
                    {
                        project.ProjectItems.AddFromFile(file);
                    }

                    progress.Report(new ThreadedWaitDialogProgressData("Generating intermediate code."));
                    GenerateCode();

                    progress.Report(new ThreadedWaitDialogProgressData("Setting includes and macros."));
                    SetIncludesAndMacros();

                    project.Save();

                    async Task <bool> CreateVSProjectFile()
                    {
                        string filePath = Path.Combine(projectDirectory, $"{projectName}.vcxproj");
                        if (File.Exists(filePath))
                        {
                            MessageBox.Show($"Project creation failed because the file {filePath} already exists.");
                            return(false);
                        }

                        string additionalPropertiesKey = "additionalproperties";
                        string projectTypeKey          = "projecttype";
                        string targetsFileNameKey      = "targetsfilename";

                        Dictionary <string, string> replacementDictionary = new Dictionary <string, string>
                        {
                            { additionalPropertiesKey, string.Empty },
                            { projectTypeKey, projectType }
                        };
                        if (projectType == Resources.ProjectType_PLM)
                        {
                            replacementDictionary[additionalPropertiesKey] = "<PLCnCLIGenerateDT>true</PLCnCLIGenerateDT>";
                        }

                        if (projectType == Resources.ProjectType_ConsumableLibrary)
                        {
                            replacementDictionary.Add(targetsFileNameKey, "PLCnCLIBuild.targets");
                        }
                        else
                        {
                            replacementDictionary.Add(targetsFileNameKey, "PLCnCLI.targets");
                        }

                        string fileContent          = await GetProjectFileTemplate();
                        Match replaceParameterMatch = ReplaceParameterRegex.Match(fileContent);

                        while (replaceParameterMatch.Success)
                        {
                            string parameter = replaceParameterMatch.Groups["parameter"].Value;
                            if (!replacementDictionary.ContainsKey(parameter))
                            {
                                MessageBox.Show($"The parameter {parameter} could not be replaced in the project file.");
                                replaceParameterMatch = replaceParameterMatch.NextMatch();
                                continue;
                            }
                            fileContent = fileContent.Replace(replaceParameterMatch.Value, replacementDictionary[parameter]);

                            replaceParameterMatch = replaceParameterMatch.NextMatch();
                        }


                        try
                        {
                            File.WriteAllText(filePath, fileContent);
                            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PlcNextVSExtension.PlcNextProject.Import.ProjectTemplate.UndefClang.hpp"))
                                using (StreamReader reader = new StreamReader(stream))
                                {
                                    string content = await reader.ReadToEndAsync();
                                    File.WriteAllText(Path.Combine(projectDirectory, "UndefClang.hpp"), content);
                                }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message + ex.StackTrace ?? string.Empty, $"Exception during writing of {filePath}");
                            return(false);
                        }

                        return(true);

                        async Task <string> GetProjectFileTemplate()
                        {
                            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PlcNextVSExtension.PlcNextProject.Import.ProjectTemplate.PLCnextImportTemplate.vcxproj"))
                                using (StreamReader reader = new StreamReader(stream))
                                {
                                    return(await reader.ReadToEndAsync());
                                }
                        }
                    }

                    void GenerateCode()
                    {
                        _plcncliCommunication.ExecuteCommand(Resources.Command_generate_code, null, null, Resources.Option_generate_code_project, $"\"{projectDirectory}\"");
                    }

                    void SetIncludesAndMacros()
                    {
                        ProjectInformationCommandResult projectInformation = _plcncliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                                                  typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project, $"\"{projectDirectory}\"") as ProjectInformationCommandResult;

                        CompilerSpecificationCommandResult compilerSpecsCommandResult =
                            _plcncliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                                 typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project, $"\"{projectDirectory}\"") as
                            CompilerSpecificationCommandResult;

                        VCProject vcProject = project.Object as VCProject;
                        ProjectIncludesManager.SetIncludesForNewProject(vcProject, compilerSpecsCommandResult, projectInformation);
                    }
                }
            });
        }
Ejemplo n.º 7
0
 private void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     MessageBox.Show("Work Done");
     pbStatus.Visibility      = Visibility.Hidden;
     pbStatusLabel.Visibility = Visibility.Hidden;
 }
        private async Task <bool> ExtractPackage(string unmanagedPath, string managedPath, CrmSolution selectedSolution, Project project, bool?downloadManaged)
        {
            //https://msdn.microsoft.com/en-us/library/jj602987.aspx#arguments
            try
            {
                CommandWindow cw = _dte2.ToolWindows.CommandWindow;

                var    props  = _dte.Properties["CRM Developer Extensions", "Solution Packager"];
                string spPath = (string)props.Item("SolutionPackagerPath").Value;

                if (string.IsNullOrEmpty(spPath))
                {
                    MessageBox.Show("Set SDK bin folder unmanagedPath under Tools -> Options -> CRM Developer Extensions");
                    return(false);
                }

                if (!spPath.EndsWith("\\"))
                {
                    spPath += "\\";
                }

                string toolPath = @"""" + spPath + "SolutionPackager.exe" + @"""";

                if (!File.Exists(spPath + "SolutionPackager.exe"))
                {
                    MessageBox.Show("SolutionPackager.exe not found at: " + spPath);
                    return(false);
                }

                string tempDirectory = Path.GetDirectoryName(unmanagedPath);
                if (Directory.Exists(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(unmanagedPath)))
                {
                    Directory.Delete(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(unmanagedPath), true);
                }
                DirectoryInfo extractedFolder =
                    Directory.CreateDirectory(tempDirectory + "\\" + Path.GetFileNameWithoutExtension(unmanagedPath));

                string command = toolPath + " /action: Extract";
                command += " /zipfile:" + "\"" + unmanagedPath + "\"";
                command += " /folder: " + "\"" + extractedFolder.FullName + "\"";
                command += " /clobber";

                // Add a mapping file which should be in the root folder of the project and be named mapping.xml
                if (File.Exists(Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\mapping.xml"))
                {
                    command += " /map:" + "\"" + Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\mapping.xml\"";
                }

                // Write Solution Package output to a log file named SolutionPackager.log in the root folder of the project
                command += " /log:" + "\"" + Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\SolutionPackager.log\"";

                // Unpack managed solution as well.
                if (downloadManaged == true)
                {
                    command += " /packagetype:Both";
                }

                cw.SendInput("shell " + command, true);

                //Need this. Extend to allow bigger solutions to unpack
                System.Threading.Thread.Sleep(10000);

                bool solutionFileDelete    = RemoveDeletedItems(extractedFolder.FullName, ConnPane.SelectedProject.ProjectItems);
                bool solutionFileAddChange = ProcessDownloadedSolution(extractedFolder, Path.GetDirectoryName(ConnPane.SelectedProject.FullName),
                                                                       ConnPane.SelectedProject.ProjectItems);

                Directory.Delete(extractedFolder.FullName, true);

                //Solution change or file not present
                bool solutionChange = solutionFileDelete || solutionFileAddChange;
                StoreSolutionFile(unmanagedPath, project, solutionChange);
                if (downloadManaged == true && !string.IsNullOrEmpty(managedPath))
                {
                    StoreSolutionFile(managedPath, project, solutionChange);
                }

                return(solutionChange);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error launching Solution Packager: " + Environment.NewLine + Environment.NewLine + ex.Message, Logger.MessageType.Error);
                return(false);
            }
        }
        private async void Package_OnClick(object sender, RoutedEventArgs e)
        {
            CrmSolution selectedSolution = (CrmSolution)SolutionToPackage.SelectedItem;

            if (selectedSolution == null || selectedSolution.SolutionId == Guid.Empty)
            {
                return;
            }

            string solutionXmlPath = Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\Other\\Solution.xml";

            if (!File.Exists(solutionXmlPath))
            {
                MessageBox.Show("Solution.xml does not exist at: " +
                                Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\Other");
                return;
            }

            XmlDocument doc = new XmlDocument();

            doc.Load(solutionXmlPath);

            XmlNodeList versionNodes = doc.GetElementsByTagName("Version");

            if (versionNodes.Count != 1)
            {
                MessageBox.Show("Invalid Solutions.xml: could not locate Versions node");
                return;
            }

            Version version;
            bool    validVersion = Version.TryParse(versionNodes[0].InnerText, out version);

            if (!validVersion)
            {
                MessageBox.Show("Invalid Solutions.xml: invalid version");
                return;
            }

            var selectedProject = ConnPane.SelectedProject;

            if (selectedProject == null)
            {
                return;
            }

            bool?downloadManaged = DownloadManaged.IsChecked;

            string savePath;
            var    props             = _dte.Properties["CRM Developer Extensions", "Solution Packager"];
            bool   saveSolutionFiles = (bool)props.Item("SaveSolutionFiles").Value;

            if (saveSolutionFiles)
            {
                savePath = Path.GetDirectoryName(selectedProject.FullName) + "\\_Solutions";
            }
            else
            {
                FolderBrowserDialog folderDialog = new FolderBrowserDialog();
                DialogResult        result       = folderDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    savePath = folderDialog.SelectedPath;
                }
                else
                {
                    return;
                }
            }

            string overwriteMessage = null;

            if (File.Exists(savePath + "\\" + selectedSolution.UniqueName + "_" +
                            FormatVersionString(version) + ".zip"))
            {
                overwriteMessage = "Overwrite unmanaged solution version: " + version + "?";
            }

            if (downloadManaged == true)
            {
                if (File.Exists(savePath + "\\" + selectedSolution.UniqueName + "_" +
                                FormatVersionString(version) + "_managed.zip"))
                {
                    overwriteMessage += Environment.NewLine + "and/or" + Environment.NewLine + "Overwrite managed solution version: " + version + "?";
                }
            }

            if (!string.IsNullOrEmpty(overwriteMessage))
            {
                MessageBoxResult result = MessageBox.Show(overwriteMessage, "Overwrite?", MessageBoxButton.YesNo);
                if (result != MessageBoxResult.Yes)
                {
                    return;
                }
            }

            await Task.Run(() => CreatePackage(selectedSolution, version, savePath, selectedProject, downloadManaged));
        }
        private async Task <bool> GetSolutions(string connString)
        {
            _dte.StatusBar.Text = "Connecting to CRM and getting solutions...";
            _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync);
            LockMessage.Content    = "Working...";
            LockOverlay.Visibility = Visibility.Visible;

            EntityCollection results = await Task.Run(() => GetSolutionsFromCrm(connString));

            if (results == null)
            {
                _dte.StatusBar.Clear();
                _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync);
                LockOverlay.Visibility = Visibility.Hidden;
                MessageBox.Show("Error Retrieving Solutions. See the Output Window for additional details.");
                return(false);
            }

            _logger.WriteToOutputWindow("Retrieved Solutions From CRM", Logger.MessageType.Info);

            ObservableCollection <CrmSolution> solutions = new ObservableCollection <CrmSolution>();

            CrmSolution emptyItem = new CrmSolution
            {
                SolutionId = Guid.Empty,
                Name       = String.Empty
            };

            solutions.Add(emptyItem);

            foreach (Entity entity in results.Entities)
            {
                CrmSolution solution = new CrmSolution
                {
                    SolutionId = entity.Id,
                    Name       = entity.GetAttributeValue <string>("friendlyname"),
                    Prefix     = entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix").Value.ToString(),
                    UniqueName = entity.GetAttributeValue <string>("uniquename"),
                    Version    = Version.Parse(entity.GetAttributeValue <string>("version"))
                };

                solutions.Add(solution);
            }

            //Empty on top
            var i =
                solutions.IndexOf(
                    solutions.FirstOrDefault(s => s.SolutionId == new Guid("00000000-0000-0000-0000-000000000000")));

            var item = solutions[i];

            solutions.RemoveAt(i);
            solutions.Insert(0, item);

            //Default second
            i =
                solutions.IndexOf(
                    solutions.FirstOrDefault(s => s.SolutionId == new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238")));
            item = solutions[i];
            solutions.RemoveAt(i);
            solutions.Insert(1, item);

            solutions = HandleMappings(solutions);
            SolutionToPackage.ItemsSource = solutions;
            if (solutions.Count(s => !string.IsNullOrEmpty(s.BoundProject)) > 0)
            {
                SolutionToPackage.SelectedItem = solutions.First(s => !string.IsNullOrEmpty(s.BoundProject));
                var selectedProject = ConnPane.SelectedProject;
                if (selectedProject != null)
                {
                    SolutionToPackage.IsEnabled = !File.Exists(Path.GetDirectoryName(selectedProject.FullName) + "\\Other\\Solution.xml");
                }
            }
            else
            {
                SolutionToPackage.IsEnabled = true;
            }

            CrmSolution crmSolution = solutions.FirstOrDefault(s => !string.IsNullOrEmpty(s.BoundProject));

            DownloadManaged.IsChecked = crmSolution != null && solutions.First(s => !string.IsNullOrEmpty(s.BoundProject)).DownloadManagedSolution;

            _dte.StatusBar.Clear();
            _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync);
            LockOverlay.Visibility = Visibility.Hidden;

            return(true);
        }
        private async void Unpackage_OnClick(object sender, RoutedEventArgs e)
        {
            SolutionToPackage.IsEnabled = false;

            _dte.StatusBar.Text = "Connecting to CRM and getting unmanaged solution...";
            _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationSync);
            LockMessage.Content    = "Working...";
            LockOverlay.Visibility = Visibility.Visible;

            if (SolutionToPackage.SelectedItem == null)
            {
                return;
            }

            CrmSolution selectedSolution = (CrmSolution)SolutionToPackage.SelectedItem;
            bool?       downloadManaged  = DownloadManaged.IsChecked;

            // Export the unmanaged solution archive from CRM
            _logger.WriteToOutputWindow("Started Download of Unmanaged Solution From CRM", Logger.MessageType.Info);
            string unmanagedPath = await Task.Run(() => GetSolutionFromCrm(ConnPane.SelectedConnection.ConnectionString, selectedSolution, false));

            if (string.IsNullOrEmpty(unmanagedPath))
            {
                _dte.StatusBar.Clear();
                LockOverlay.Visibility = Visibility.Hidden;
                MessageBox.Show("Error Retrieving Unmanaged Solution. See the Output Window for additional details.");
                return;
            }

            _logger.WriteToOutputWindow("Retrieved Unmanaged Solution From CRM", Logger.MessageType.Info);
            _dte.StatusBar.Text = "Extracting solution...";

            Project project = ConnPane.SelectedProject;

            // If the managed flag was set, export the managed solution archive from CRM
            string managedPath = null;

            if (downloadManaged == true)
            {
                _dte.StatusBar.Text = "Connecting to CRM and getting managed solution...";
                _logger.WriteToOutputWindow("Started Download of Managed Solution From CRM", Logger.MessageType.Info);
                managedPath =
                    await
                    Task.Run(
                        () =>
                        GetSolutionFromCrm(ConnPane.SelectedConnection.ConnectionString, selectedSolution, true));

                if (string.IsNullOrEmpty(managedPath))
                {
                    _dte.StatusBar.Clear();
                    LockOverlay.Visibility = Visibility.Hidden;
                    MessageBox.Show("Error Retrieving Managed Solution. See the Output Window for additional details.");
                    return;
                }

                _logger.WriteToOutputWindow("Retrieved Managed Solution From CRM", Logger.MessageType.Info);
            }

            // Upack the solution(s) using the Solution Packager
            bool solutionChange = await Task.Run(() => ExtractPackage(unmanagedPath, managedPath, selectedSolution, project, downloadManaged));

            _dte.StatusBar.Clear();
            _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationSync);
            LockOverlay.Visibility = Visibility.Hidden;

            Package.IsEnabled = true;
        }
Ejemplo n.º 12
0
        public void Save()
        {
            var canClose = false;

            IsBusy = true;
            var bgWorker = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };

            bgWorker.DoWork += (sender, args) =>
            {
                try
                {
                    AllGames = GameRepository.Get(null);

                    if (SelectedGame == null && AllGames.Any(w => w.Month.Equals(Month) && w.Theme.Equals(Theme)))
                    {
                        MessageBox.Show($"Er bestaat reeds een wedstrijd met id {Month} - {Theme}.", "Fout",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        IsBusy = false;
                        return;
                    }
                    if (string.IsNullOrEmpty(Resolution))
                    {
                        MessageBox.Show("Gelieve een resolutie in te geven.", "Fout",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        IsBusy = false;
                        return;
                    }
                    if (!MaxToUpload.HasValue)
                    {
                        MessageBox.Show("Gelieve een max in te geven.", "Fout",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        IsBusy = false;
                        return;
                    }
                    var gameToSave = SelectedGame != null
                        ? AllGames.FirstOrDefault(w =>
                                                  w.Month.Equals(SelectedGame.Month) && w.Theme.Equals(SelectedGame.Theme))
                        : new GameItem();

                    if (gameToSave != null)
                    {
                        gameToSave.Club        = OrganisationName;
                        gameToSave.Month       = Month;
                        gameToSave.Theme       = Theme;
                        gameToSave.GameDate    = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        gameToSave.Resolution  = Resolution;
                        gameToSave.MaxToUpload = MaxToUpload.Value;
                        if (SelectedGame == null)
                        {
                            AllGames.Add(gameToSave);
                        }
                    }

                    XmlFactory.WriteXml(FolderFactory.MemberFolder, "Games", AllGames);
                    LogFactory.WriteToLog("De wedstrijd is met succes aangepast.", "GameDetailViewModel.Save",
                                          ActivityLogTypes.Success, App.ActivityLogFileName);
                    IsBusy = false;
                    MessageBox.Show("De gegevens zijn met succes bewaard.", "Informatie",
                                    MessageBoxButton.OK, MessageBoxImage.Information);
                    canClose = true;
                }
                catch (Exception ex)
                {
                    LogFactory.WriteToLog(ex.Message, "GameDetailViewModel.Save", ActivityLogTypes.Error,
                                          App.ActivityLogFileName);
                    IsBusy = false;
                    MessageBox.Show("Er is een fout opgetreden tijdens het bewaren van het lid.", "Fout",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
            };

            bgWorker.RunWorkerCompleted += (sender, args) => CloseWindow(canClose);
            bgWorker.RunWorkerAsync();
        }
Ejemplo n.º 13
0
        private void InitApplication()
        {
            // prevent some application crash
            //WpfCommands.DisableWpfTabletSupport();

            Dispatcher.Invoke(new Action(ServiceProvider.Configure));


            ServiceProvider.Settings = new Settings();
            ServiceProvider.Settings = ServiceProvider.Settings.Load();
            ServiceProvider.Branding = Branding.LoadBranding();

            ServiceProvider.ActionManager.Actions = new AsyncObservableCollection <IMenuAction>
            {
                //new CmdFocusStackingCombineZP(),
                //new CmdEnfuse(),
                // new CmdToJpg(),
                //new CmdExpJpg()
            };

            if (ServiceProvider.Settings.DisableNativeDrivers &&
                MessageBox.Show(TranslationStrings.MsgDisabledDrivers, "", MessageBoxButton.YesNo) ==
                MessageBoxResult.Yes)
            {
                ServiceProvider.Settings.DisableNativeDrivers = false;
            }
            ServiceProvider.Settings.LoadSessionData();
            TranslationManager.LoadLanguage(ServiceProvider.Settings.SelectedLanguage);

            ServiceProvider.PluginManager.CopyPlugins();
            Dispatcher.Invoke(new Action(InitWindowManager));


            ServiceProvider.Trigger.Start();
            ServiceProvider.Analytics.Start();

            Dispatcher.Invoke(new Action(delegate
            {
                try
                {
                    // event handlers
                    ServiceProvider.Settings.SessionSelected += Settings_SessionSelected;

                    ServiceProvider.DeviceManager.CameraConnected    += DeviceManager_CameraConnected;
                    ServiceProvider.DeviceManager.CameraSelected     += DeviceManager_CameraSelected;
                    ServiceProvider.DeviceManager.CameraDisconnected += DeviceManager_CameraDisconnected;
                    //-------------------
                    ServiceProvider.DeviceManager.DisableNativeDrivers = ServiceProvider.Settings.DisableNativeDrivers;
                    if (ServiceProvider.Settings.AddFakeCamera)
                    {
                        ServiceProvider.DeviceManager.AddFakeCamera();
                    }
                    ServiceProvider.DeviceManager.ConnectToCamera();
                }
                catch (Exception exception)
                {
                    Log.Error("Unable to initialize device manager", exception);
                    if (exception.Message.Contains("0AF10CEC-2ECD-4B92-9581-34F6AE0637F3"))
                    {
                        MessageBox.Show(
                            "Unable to initialize device manager !\nMissing some components! Please install latest Windows Media Player! ");
                        Application.Current.Shutdown(1);
                    }
                }
                StartApplication();
                if (_startUpWindow != null)
                {
                    _startUpWindow.Close();
                }
            }));
        }
Ejemplo n.º 14
0
        //----------------------------------------------------------
        public string Them_Hoac_Xoa_Parameter_Trong_Project(UIApplication uiapp, Document doc)
        {
            string result = "F";

            try
            {
                Transaction transaction = new Transaction(doc);
                transaction.Start("Parameters");
                var enums      = Enum.GetValues(typeof(BuiltInCategory));
                var enums1     = Enum.GetValues(typeof(BuiltInParameterGroup));
                var categories = doc.Settings.Categories;
                foreach (data_group_share_parameter item in my_group_share_parameter)
                {
                    DefinitionFile parafile = uiapp.Application.OpenSharedParameterFile();
                    if (parafile != null)
                    {
                        DefinitionGroup myGroup = parafile.Groups.get_Item(item.ten_group_parameter);

                        foreach (data_item_share_parameter subitem in item.Children)
                        {
                            if (subitem.exist_parameter == true)
                            {
                                //BuiltInParameterGroup builtInParameterGroup = BuiltInParameterGroup.PG_TEXT;
                                //foreach (BuiltInParameterGroup builtIn in enums1)
                                //{
                                //    if (builtIn.ToString().Split('_')[0] == subitem.ten_parameter && builtIn != BuiltInParameterGroup.INVALID) builtInParameterGroup = builtIn;
                                //}

                                Definition  myDefinition_ProductDate = myGroup.Definitions.get_Item(subitem.ten_parameter);
                                CategorySet myCategories             = uiapp.Application.Create.NewCategorySet();
                                foreach (BuiltInCategory buildCategory in enums)
                                {
                                    try
                                    {
                                        Category cate = categories.get_Item(buildCategory);
                                        if (cate.AllowsBoundParameters == true && cate.CategoryType.ToString() == "Model")
                                        {
                                            myCategories.Insert(cate);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }

                                try
                                {
                                    BindingMap bindingMap = doc.ParameterBindings;
                                    if (subitem.ten_parameter != "Chiều dày hoàn thiện")
                                    {
                                        InstanceBinding instanceBinding = uiapp.Application.Create.NewInstanceBinding(myCategories);
                                        bindingMap.Insert(myDefinition_ProductDate, instanceBinding);
                                    }
                                    else
                                    {
                                        TypeBinding instanceBinding = uiapp.Application.Create.NewTypeBinding(myCategories);
                                        bindingMap.Insert(myDefinition_ProductDate, instanceBinding);
                                    }
                                    if (my_data_parameter_current.Any(x => x.ten_parameter == subitem.ten_parameter) == false)
                                    {
                                        my_data_parameter_current.Add(new data_parameter()
                                        {
                                            ten_parameter = subitem.ten_parameter
                                        });
                                    }
                                }
                                catch (Exception)
                                {
                                }
                            }
                            else
                            {
                                try
                                {
                                    Definition myDefinition_ProductDate = myGroup.Definitions.get_Item(subitem.ten_parameter);
                                    BindingMap bindingMap = doc.ParameterBindings;
                                    bindingMap.Remove(myDefinition_ProductDate);
                                    data_parameter item_remove = my_data_parameter_current.First(x => x.ten_parameter == subitem.ten_parameter);
                                    if (item_remove != null)
                                    {
                                        my_data_parameter_current.Remove(item_remove);
                                    }
                                }
                                catch (Exception)
                                {
                                }
                            }
                            try
                            {
                                if (my_data_parameter_current.Any(x => x.ten_parameter == subitem.ten_parameter) == false)
                                {
                                    my_data_parameter_need.First(x => x.ten_parameter == subitem.ten_parameter).color = Source.color_error;
                                }
                                else
                                {
                                    my_data_parameter_need.First(x => x.ten_parameter == subitem.ten_parameter).color = Source.color;
                                }
                                thong_tin_parameter.Items.Refresh();
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Not found share parameter file!!!", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                result = "S";
                transaction.Commit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return(result);
        }
Ejemplo n.º 15
0
        private void BRedInside_Click(object sender, RoutedEventArgs e)
        {
            double dis  = Convert.ToDouble(Discount.Text) / 100;
            int    time = Convert.ToInt32(Duration.Text) * 60;
            int    cost = Convert.ToInt32(Cost.Text);
            string tit  = title.Text;
            int    idi  = Convert.ToInt32(id.Text);
            string desc = Description.Text;
            string pat  = Path.Text;

            switch (doID)
            {
            case 0:
                try
                {
                    DialogResult dialogResult = (DialogResult)MessageBox.Show("Изменить запись?", "Предупреждение!!!", (MessageBoxButton)MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        if (time <= 240 * 60)
                        {
                            Service obj = new Service()
                            {
                                ID                = idi,
                                Title             = tit,
                                Cost              = cost,
                                DurationInSeconds = time,
                                Description       = desc,
                                Discount          = dis,
                                MainImagePath     = pat
                            };
                            Classes.Base.DBD.Service.AddOrUpdate(obj);
                            Classes.Base.DBD.SaveChanges();
                            MessageBox.Show("Запись изменена");
                            i                      = -1;
                            ServiswList            = Classes.Base.DBD.Service.ToList();
                            DGServises.ItemsSource = ServiswList;
                            RedGrid.Visibility     = Visibility.Collapsed;
                            MainStack.Visibility   = Visibility.Visible;
                            BNewService.Visibility = Visibility.Visible;
                        }
                        if (time >= 240 * 60)
                        {
                            MessageBox.Show("Более 4 часов нельзя");
                        }
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        MessageBox.Show("Запись не изменена");
                    }
                }
                catch
                {
                    MessageBox.Show("Неверный формат");
                }
                break;

            case 1:
                BRedInside.Content = "Добавить";
                try
                {
                    DialogResult dialogResult = (DialogResult)MessageBox.Show("Вы хотите добавить новую услугу?", "Предупреждение!!!", (MessageBoxButton)MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        if (time <= 240 * 60)
                        {
                            Service obj = new Service()
                            {
                                ID                = idi,
                                Title             = tit,
                                Cost              = cost,
                                DurationInSeconds = time,
                                Description       = desc,
                                Discount          = dis,
                                MainImagePath     = pat
                            };
                            Classes.Base.DBD.Service.Add(obj);
                            Classes.Base.DBD.SaveChanges();
                            MessageBox.Show("Запись добавлена");

                            i                      = -1;
                            ServiswList            = Classes.Base.DBD.Service.ToList();
                            DGServises.ItemsSource = ServiswList;
                            RedGrid.Visibility     = Visibility.Collapsed;
                            MainStack.Visibility   = Visibility.Visible;
                            BNewService.Visibility = Visibility.Visible;
                        }
                        if (time >= 240 * 60)
                        {
                            MessageBox.Show("Более 4 часов нельзя");
                        }
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        MessageBox.Show("Запись не добавлена");
                    }
                }
                catch
                {
                }
                break;
            }
        }
        private void CreatePackage(CrmSolution selectedSolution, Version version, string savePath, Project project, bool?downloadManaged)
        {
            try
            {
                //https://msdn.microsoft.com/en-us/library/jj602987.aspx#arguments

                CommandWindow cw = _dte2.ToolWindows.CommandWindow;

                var    props  = _dte.Properties["CRM Developer Extensions", "Solution Packager"];
                string spPath = (string)props.Item("SolutionPackagerPath").Value;

                if (string.IsNullOrEmpty(spPath))
                {
                    MessageBox.Show("Set SDK bin folder unmanagedPath under Tools -> Options -> CRM Developer Extensions");
                    return;
                }

                if (!spPath.EndsWith("\\"))
                {
                    spPath += "\\";
                }

                string toolPath = @"""" + spPath + "SolutionPackager.exe" + @"""";

                if (!File.Exists(spPath + "SolutionPackager.exe"))
                {
                    MessageBox.Show("SolutionPackager.exe not found at: " + spPath);
                    return;
                }

                string filename = selectedSolution.UniqueName + "_" +
                                  FormatVersionString(version) + ".zip";

                string command = toolPath + " /action: Pack";
                command += " /zipfile:" + "\"" + savePath + "\\" + filename + "\"";
                command += " /folder: " + "\"" + Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\"";

                if (downloadManaged == true)
                {
                    command += " /packagetype:Both";
                }

                // Use a mapping file if one exists in the root folder of the project and be named mapping.xml
                if (File.Exists(Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\mapping.xml"))
                {
                    command += " /map:" + "\"" + Path.GetDirectoryName(ConnPane.SelectedProject.FullName) + "\\mapping.xml\"";
                }

                cw.SendInput("shell " + command, true);

                AddNewSolutionToProject(savePath, project, filename);
                if (downloadManaged == true)
                {
                    AddNewSolutionToProject(savePath, project, filename.Replace(".zip", "_managed.zip"));
                }
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error launching Solution Packager: " + Environment.NewLine + Environment.NewLine + ex.Message, Logger.MessageType.Error);
            }
        }
Ejemplo n.º 17
0
        private void csCBc_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int x = Convert.ToInt32(csCBc.SelectedValue);

            MessageBox.Show(x + "");
        }
        private void OnLearnColorModelButtonClick(object sender, RoutedEventArgs e)
        {
            if (this.backgroundImagesListBox.SelectedIndex != -1)
            {
                ImageInfo currentImageInfo = this.imageInfos[this.backgroundImagesListBox.SelectedIndex];
                currentImageInfo.ColorModelMask = this.colorMaskEditor.GetMask(currentImageInfo.Image.PixelWidth, currentImageInfo.Image.PixelHeight);
            }

            List <Color> objectColors     = new List <Color>();
            List <Color> backgroundColors = new List <Color>();

            for (int i = 0; i < this.imageInfos.Count; ++i)
            {
                if (this.imageInfos[i].ColorModelMask == null)
                {
                    continue;
                }

                Image2D <Color> image = ImageHelper.BitmapSourceToImage2D(this.imageInfos[i].Image);
                ExtractObjectBackgroundColorsByMask(
                    image,
                    this.imageInfos[i].ColorModelMask,
                    objectColors,
                    backgroundColors);

                Image2D.SaveToFile(image, string.Format("image_{0}.png", i));
                Image2D.SaveToFile(this.imageInfos[i].ColorModelMask, string.Format("mask_{0}.png", i));
            }

            if (objectColors.Count == 0)
            {
                MessageBox.Show("No object pixels specified.");
                return;
            }

            if (backgroundColors.Count == 0)
            {
                MessageBox.Show("No background pixels specified.");
                return;
            }

            Helper.Subsample(objectColors, this.algorithmProperties.MaxPixelsToLearnFrom);
            Helper.Subsample(backgroundColors, this.algorithmProperties.MaxPixelsToLearnFrom);

            try
            {
                GaussianMixtureColorModel objectModel = GaussianMixtureColorModel.Fit(
                    objectColors.Take(this.algorithmProperties.MaxPixelsToLearnFrom),
                    this.algorithmProperties.MixtureComponentCount,
                    this.algorithmProperties.StopTolerance);
                GaussianMixtureColorModel backgroundModel = GaussianMixtureColorModel.Fit(
                    backgroundColors.Take(this.algorithmProperties.MaxPixelsToLearnFrom),
                    this.algorithmProperties.MixtureComponentCount,
                    this.algorithmProperties.StopTolerance);
                this.colorModels = new ObjectBackgroundColorModels(objectModel, backgroundModel);

                this.UpdateControlsAccordingToCurrentState();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 19
0
        public Main()
        {
            Ioc.Container.RegisterSingleton <Main>(() => this);
            this.InitializeComponent();

            this.sourceRow.Height = new GridLength(Config.SourcePaneHeightStar, GridUnitType.Star);
            this.queueRow.Height  = new GridLength(Config.QueuePaneHeightStar, GridUnitType.Star);

            this.Activated += (sender, args) =>
            {
                DispatchUtilities.BeginInvoke(async() =>
                {
                    // Need to yield here for some reason, otherwise the activation is blocked.
                    await Task.Yield();
                    this.toastNotificationService.Clear();
                });
            };

            this.notifyIcon = new NotifyIcon
            {
                Visible = false
            };
            this.notifyIcon.Click       += (sender, args) => { this.RestoreWindow(); };
            this.notifyIcon.DoubleClick += (sender, args) => { this.RestoreWindow(); };

            StreamResourceInfo streamResourceInfo = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/VidCoder_icon.ico"));

            if (streamResourceInfo != null)
            {
                Stream iconStream = streamResourceInfo.Stream;
                this.notifyIcon.Icon = new Icon(iconStream);
            }

            this.RefreshQueueColumns();
            this.LoadCompletedColumnWidths();

#if DEBUG
            var debugDropDown = new DropDownButton {
                Header = "Debug"
            };

            var loadScanFromJsonItem = new Fluent.MenuItem {
                Header = "Load scan from JSON..."
            };
            loadScanFromJsonItem.Click += (sender, args) =>
            {
                DebugJsonDialog dialog = new DebugJsonDialog("Debug Scan JSON");
                dialog.ShowDialog();
                if (!string.IsNullOrWhiteSpace(dialog.Json))
                {
                    try
                    {
                        var scanObject = JsonConvert.DeserializeObject <JsonScanObject>(dialog.Json);
                        this.viewModel.UpdateFromNewVideoSource(new VideoSource {
                            Titles = scanObject.TitleList, FeatureTitle = scanObject.MainFeature
                        });
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(this, "Could not parse scan JSON:" + Environment.NewLine + Environment.NewLine + exception.ToString());
                    }
                }
            };
            debugDropDown.Items.Add(loadScanFromJsonItem);

            var queueFromJsonItem = new Fluent.MenuItem {
                Header = "Queue job from JSON..."
            };
            queueFromJsonItem.Click += (sender, args) =>
            {
                if (!this.viewModel.HasVideoSource)
                {
                    StaticResolver.Resolve <IMessageBoxService>().Show("Must open source before adding queue job from JSON");
                    return;
                }

                EncodeJobViewModel jobViewModel = this.viewModel.CreateEncodeJobVM();
                DebugJsonDialog    dialog       = new DebugJsonDialog("Debug Encode JSON");
                dialog.ShowDialog();

                if (!string.IsNullOrWhiteSpace(dialog.Json))
                {
                    try
                    {
                        JsonEncodeObject encodeObject = JsonConvert.DeserializeObject <JsonEncodeObject>(dialog.Json);

                        jobViewModel.DebugEncodeJsonOverride = dialog.Json;
                        jobViewModel.Job.FinalOutputPath     = encodeObject.Destination.File;
                        jobViewModel.Job.SourcePath          = encodeObject.Source.Path;

                        this.processingService.Queue(jobViewModel);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(this, "Could not parse encode JSON:" + Environment.NewLine + Environment.NewLine + exception.ToString());
                    }
                }
            };
            debugDropDown.Items.Add(queueFromJsonItem);

            var throwExceptionItem = new Fluent.MenuItem {
                Header = "Throw exception"
            };
            throwExceptionItem.Click += (sender, args) =>
            {
                throw new InvalidOperationException("Rats.");
            };
            debugDropDown.Items.Add(throwExceptionItem);

            var addLogItem = new Fluent.MenuItem {
                Header = "Add 1 log item"
            };
            addLogItem.Click += (sender, args) =>
            {
                StaticResolver.Resolve <IAppLogger>().Log("This is a log item");
            };
            debugDropDown.Items.Add(addLogItem);

            var addTenLogItems = new Fluent.MenuItem {
                Header = "Add 10 log items"
            };
            addTenLogItems.Click += (sender, args) =>
            {
                for (int i = 0; i < 10; i++)
                {
                    StaticResolver.Resolve <IAppLogger>().Log("This is a log item");
                }
            };
            debugDropDown.Items.Add(addTenLogItems);

            var addLongLogItem = new Fluent.MenuItem {
                Header = "Add long log item"
            };
            addLongLogItem.Click += (sender, args) =>
            {
                StaticResolver.Resolve <IAppLogger>().Log("This is a log item\r\nthat is split into multiple lines\r\nOh yes indeed");
            };
            debugDropDown.Items.Add(addLongLogItem);

            var doAnActionItem = new Fluent.MenuItem {
                Header = "Perform action"
            };
            doAnActionItem.Click += (sender, args) =>
            {
                var app = (App)System.Windows.Application.Current;
                app.ChangeTheme(new Uri("/Themes/Dark.xaml", UriKind.Relative));
            };
            debugDropDown.Items.Add(doAnActionItem);

            this.toolsRibbonGroupBox.Items.Add(debugDropDown);
#endif

            this.DataContextChanged += this.OnDataContextChanged;
            TheDispatcher            = this.Dispatcher;

            this.statusText.Opacity = 0.0;

            NameScope.SetNameScope(this, new NameScope());
            this.RegisterName("StatusText", this.statusText);

            var storyboard = (Storyboard)this.FindResource("StatusTextStoryboard");
            storyboard.Completed += (sender, args) =>
            {
                this.statusText.Visibility = Visibility.Collapsed;
            };

            this.presetTreeViewContainer.PresetTreeView.OnHierarchyMouseUp += (sender, args) =>
            {
                this.presetButton.IsDropDownOpen = false;
            };

            this.presetButton.DropDownOpened += (sender, args) =>
            {
                var item = UIUtilities.FindDescendant <TreeViewItem>(this.presetTreeViewContainer.PresetTreeView, viewItem =>
                {
                    return(viewItem.Header == this.viewModel.PresetsService.SelectedPreset);
                });

                if (item != null)
                {
                    UIUtilities.BringIntoView(item);
                }
            };

            this.Loaded += (e, o) =>
            {
                this.RestoredWindowState = this.WindowState;
            };

            this.statusService.MessageShown += (o, e) =>
            {
                this.ShowStatusMessage(e.Value);
            };

            this.queueView.SelectionChanged += this.QueueView_SelectionChanged;
        }
        private async void  InstallReleaseButton(object sender, RoutedEventArgs e)
        {
            var dcScriptsPath = dcsScriptsPath.Text;

            if ((bool)!InstallScriptsCheckbox.IsChecked)
            {
                dcScriptsPath = null;
            }
            else
            {
                var paths = FindValidDCSFolders(dcScriptsPath);

                if (paths.Count == 0)
                {
                    MessageBox.Show(
                        "Unable to find DCS Folder in Saved Games!\n\nPlease check the path to the \"Saved Games\" folder\n\nMake sure you are selecting the \"Saved Games\" folder - NOT the DCS folder inside \"Saved Games\" and NOT the DCS installation directory",
                        "SR Standalone Installer",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (IsDCSRunning())
                {
                    ShowDCSWarning();
                    return;
                }
            }

            InstallButton.IsEnabled = false;
            RemoveButton.IsEnabled  = false;

            InstallButton.Content = "Installing...";

            _progressBarDialog       = new ProgressBarDialog();
            _progressBarDialog.Owner = this;
            _progressBarDialog.Show();

            var srsPath = srPath.Text;

            var shortcut = CreateStartMenuShortcut.IsChecked ?? true;

            new Action(async() =>
            {
                int result = await Task.Run <int>(() => InstallRelease(srsPath, dcScriptsPath, shortcut));
                if (result == 0)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        InstallButton.IsEnabled = true;
                        RemoveButton.IsEnabled  = true;
                        InstallButton.Content   = "Install";
                    }
                                                          ); //end-invoke
                    _progressBarDialog.UpdateProgress(true, "Error");
                }
                else if (result == 1)
                {
                    _progressBarDialog.UpdateProgress(true, "Installed SRS Successfully!");

                    Logger.Info($"Installed SRS Successfully!");

                    //open to installation location
                    // Process.Start("explorer.exe", srPath.Text);
                    Environment.Exit(0);
                }
                else
                {
                    _progressBarDialog.UpdateProgress(true, "Error with Installation");

                    MessageBox.Show(
                        "Error with installation - please post your installer-log.txt on the SRS Discord for Support",
                        "Installation Error",
                        MessageBoxButton.OK, MessageBoxImage.Error);

                    Process.Start("https://discord.gg/vqxAw7H");
                    Process.Start("explorer.exe", GetWorkingDirectory());
                    Environment.Exit(0);
                }
            }).Invoke();
        }
Ejemplo n.º 21
0
        private void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (_mOWorker.CancellationPending)
            {
                e.Cancel = true;
                _mOWorker.ReportProgress(0);
                Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
                {
                    pbStatus.Value           = 0;
                    pbStatus.Visibility      = Visibility.Hidden;
                    pbStatusLabel.Visibility = Visibility.Hidden;
                });
                return;
            }
            string        outputFolder   = null;
            List <string> itemList       = null;
            string        rTargetContent = null;
            RadioButton   rTarget;
            RadioButton   rViewTarget;

            string[] isMobile = null;
            Dispatcher.Invoke(() => //Use Dispather to Update UI Immediately
            {
                outputFolder             = tbxFolder.Text;
                pbStatus.Visibility      = Visibility.Visible;
                pbStatusLabel.Visibility = Visibility.Visible;

                var buttons    = FormatGrid.Children.OfType <RadioButton>().ToList();
                rTarget        = buttons.Single(r => r.GroupName == "FormatSelection" && r.IsChecked == true);
                rTargetContent = rTarget.Content.ToString();

                var viewPortButtons = ViewPortGrid.Children.OfType <RadioButton>().ToList();
                rViewTarget         = viewPortButtons.Single(r => r.GroupName == "ViewPortSelection" && r.IsChecked == true);
                if (rTargetContent == "PDF" && rViewTarget.Content.ToString() != "MobileView")
                {
                    isMobile = new[] { "--page-size A4 --viewport-size 1280x1024 --disable-smart-shrinking" };
                }
                itemList = (from ListViewData lvc in urlListView.Items where lvc.Col1 != "" select lvc.Col1).ToList();
            });
            var indexer = 1;

            foreach (var item in itemList)
            {
                int percentage;
                var generatorFactory = new GeneratorFactory();
                var generatorType    = (GeneratorType)Enum.Parse(typeof(GeneratorType), rTargetContent);
                var generator        = generatorFactory.GetGenerator(generatorType);
                _tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
                var token        = _tokenSource.Token;
                var QueryTimeOut = 5000;
                var task         = Task.Factory.StartNew(() =>
                {
                    generator.GenerateDocument(outputFolder, "Tx", new[] { item }, isMobile);
                    percentage = indexer * 100 / itemList.Count;
                    _mOWorker.ReportProgress(percentage);
                    indexer += 1;
                }, token);
                if (!task.Wait(QueryTimeOut, token))
                {
                    MessageBox.Show($"Url is taking more than 5 seconds to Load -- Please Check the url: {item}");
                    _tokenSource.Cancel();
                }
                if (task.IsCanceled)
                {
                    MessageBox.Show($"Url not Valid: {item}");
                }
            }
            _mOWorker.ReportProgress(100);
        }
        private int InstallRelease(string srPath, string dcsScriptsPath, bool shortcut)
        {
            try
            {
                QuitSimpleRadio();

                var paths = new List <string>();
                if (dcsScriptsPath != null)
                {
                    paths = FindValidDCSFolders(dcsScriptsPath);

                    if (paths.Count == 0)
                    {
                        MessageBox.Show(
                            "Unable to find DCS Folder in Saved Games!\n\nPlease check the path to the \"Saved Games\" folder\n\nMake sure you are selecting the \"Saved Games\" folder - NOT the DCS folder inside \"Saved Games\" and NOT the DCS installation directory",
                            "SR Standalone Installer",
                            MessageBoxButton.OK, MessageBoxImage.Error);
                        return(0);
                    }

                    if (IsDCSRunning())
                    {
                        MessageBox.Show(
                            "DCS must now be closed before continuing the installation!\n\nClose DCS and please try again.",
                            "Please Close DCS",
                            MessageBoxButton.OK, MessageBoxImage.Error);

                        Logger.Warn("DCS is Running - Installer stopped");

                        return(0);
                    }

                    Logger.Info($"Installing - Paths: \nProgram:{srPath} \nDCS:{dcsScriptsPath} ");

                    ClearVersionPreModsTechDCS(srPath, dcsScriptsPath);
                    ClearVersionPostModsTechDCS(srPath, dcsScriptsPath);
                    ClearVersionPostModsServicesDCS(srPath, dcsScriptsPath);

                    foreach (var path in paths)
                    {
                        InstallScripts(path);
                    }
                }
                else
                {
                    Logger.Info($"Installing - Paths: \nProgram:{srPath} DCS: NO PATH - NO SCRIPTS");
                }

                //install program
                InstallProgram(srPath);

                WritePath(srPath, "SRPathStandalone");

                if (dcsScriptsPath != null)
                {
                    WritePath(dcsScriptsPath, "ScriptsPath");
                }

                if (shortcut)
                {
                    InstallShortcuts(srPath);
                }

                InstallVCRedist();

                if (dcsScriptsPath != null)
                {
                    string message = "Installation / Update Completed Successfully!\nInstalled DCS Scripts to: \n";

                    foreach (var path in paths)
                    {
                        message += ("\n" + path);
                    }

                    MessageBox.Show(message, "SR Standalone Installer",
                                    MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    if (IsSilentServer())
                    {
                        if (ShouldRestart())
                        {
                            StartServer(srPath);
                            return(1);
                        }
                    }
                    else
                    {
                        string message = "Installation / Update Completed Successfully!";

                        MessageBox.Show(message, "SR Standalone Installer",
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }


                return(1);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error Running Installer");


                return(-1);
            }
        }
Ejemplo n.º 23
0
 private void mnuHelpAbout_Click(object sender, RoutedEventArgs e)
 {
     MessageBox.Show("File System Watcher, watches the selected file directory an outputs to a database located next to where the app was launched, \nBased on the .Net Framework and developed using WPF \nConstructed by Ryan Cranston");
 }
        public MainWindow()
        {
            SetupLogging();
            InitializeComponent();

            var assembly = Assembly.GetExecutingAssembly();
            var fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            var version  = fvi.FileVersion;

            intro.Content = intro.Content + " v" + version;

            //allows click and drag anywhere on the window
            containerPanel.MouseLeftButtonDown += GridPanel_MouseLeftButtonDown;

            var srPathStr = ReadPath("SRPathStandalone");

            if (srPathStr != "")
            {
                srPath.Text = srPathStr;
            }

            var scriptsPath = ReadPath("ScriptsPath");

            if (scriptsPath != "")
            {
                dcsScriptsPath.Text = scriptsPath;
            }
            else
            {
                dcsScriptsPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                                      "\\Saved Games\\";
            }

            //To get the location the assembly normally resides on disk or the install directory
            var currentPath = GetWorkingDirectory();

            if (currentPath.StartsWith("file:\\"))
            {
                currentPath = currentPath.Replace("file:\\", "");
            }

            _currentDirectory = currentPath;

            Logger.Info("Listing Files / Directories for: " + _currentDirectory);
            ListFiles(_currentDirectory);
            Logger.Info("Finished Listing Files / Directories");

            if (!CheckExtracted())
            {
                MessageBox.Show(
                    "Please extract the entire installation zip into a folder and then run the installer from the extracted folder.\n\nDo not run the installer from the zip as it wont work!",
                    "Please Extract Installation zip",
                    MessageBoxButton.OK, MessageBoxImage.Error);

                Logger.Warn("Files missing from Installation Directory");

                Environment.Exit(0);

                return;
            }

            new Action(async() =>
            {
                await Task.Delay(1).ConfigureAwait(false);

                if (((App)Application.Current).Arguments.Length > 0)
                {
                    if (IsAutoUpdate() && !IsSilentServer())
                    {
                        Application.Current.Dispatcher?.Invoke(() =>
                        {
                            Logger.Info("Silent Installer Running");
                            var result = MessageBox.Show(
                                "Do you want to make changes? \n\nYes - Pause install and make changes\n\nNo - Run with previous install path and install scripts as default. \n\nIf unsure - hit Yes!",
                                "Change Installer Settings?",
                                MessageBoxButton.YesNo, MessageBoxImage.Information);

                            if (result == MessageBoxResult.Yes)
                            {
                            }
                            else
                            {
                                InstallScriptsCheckbox.IsChecked = true;
                                InstallReleaseButton(null, null);
                            }
                        }
                                                               ); //end-invoke
                    }
                    else if (IsAutoUpdate() && IsSilentServer())
                    {
                        Application.Current.Dispatcher?.Invoke(() =>
                        {
                            var path = ServerPath();
                            Logger.Info("Silent Server Installer Running - " + path);

                            srPath.Text = path;
                            InstallScriptsCheckbox.IsChecked = false;
                            InstallReleaseButton(null, null);
                        }
                                                               ); //end-invoke
                    }
                }
            }).Invoke();
        }
Ejemplo n.º 25
0
 private MessageBoxResult ShowUnsavedChangesWarning()
 {
     return(MessageBox.Show("There are unsaved changes. Would you like to continue?", "Warning - Unsaved Changes", MessageBoxButton.YesNo, MessageBoxImage.Warning));
 }
        private void InstallScripts(string path)
        {
            Logger.Info($"Installing Scripts to {path}");
            _progressBarDialog.UpdateProgress(false, $"Creating Script folders @ {path}");
            //Scripts Path
            CreateDirectory(path + "\\Scripts");
            CreateDirectory(path + "\\Scripts\\Hooks");

            //Make Tech Path
            CreateDirectory(path + "\\Mods");
            CreateDirectory(path + "\\Mods\\Services");
            CreateDirectory(path + "\\Mods\\Services\\DCS-SRS");

            Task.Delay(TimeSpan.FromMilliseconds(100)).Wait();

            _progressBarDialog.UpdateProgress(false, $"Updating / Creating Export.lua @ {path}");
            Logger.Info($"Handling Export.lua");
            //does it contain an export.lua?
            if (File.Exists(path + "\\Scripts\\Export.lua"))
            {
                var contents = File.ReadAllText(path + "\\Scripts\\Export.lua");

                contents.Split('\n');

                if (contents.Contains("SimpleRadioStandalone.lua"))
                {
                    Logger.Info($"Updating existing Export.lua with existing SRS install");
                    var lines = contents.Split('\n');

                    StringBuilder sb = new StringBuilder();

                    foreach (var line in lines)
                    {
                        if (line.Contains("SimpleRadioStandalone.lua"))
                        {
                            sb.Append("\n");
                            sb.Append(EXPORT_SRS_LUA);
                            sb.Append("\n");
                        }
                        else if (line.Trim().Length > 0)
                        {
                            sb.Append(line);
                            sb.Append("\n");
                        }
                    }
                    File.WriteAllText(path + "\\Scripts\\Export.lua", sb.ToString());
                }
                else
                {
                    Logger.Info($"Appending to existing Export.lua");
                    var writer = File.AppendText(path + "\\Scripts\\Export.lua");

                    writer.WriteLine("\n" + EXPORT_SRS_LUA + "\n");
                    writer.Close();
                }
            }
            else
            {
                Logger.Info($"Creating new Export.lua");
                var writer = File.CreateText(path + "\\Scripts\\Export.lua");

                writer.WriteLine("\n" + EXPORT_SRS_LUA + "\n");
                writer.Close();
            }


            //Now sort out Scripts//Hooks folder contents
            Logger.Info($"Creating / installing Hooks & Mods / Services");
            _progressBarDialog.UpdateProgress(false, $"Creating / installing Hooks & Mods/Services @ {path}");
            try
            {
                File.Copy(_currentDirectory + "\\Scripts\\Hooks\\DCS-SRS-hook.lua", path + "\\Scripts\\Hooks\\DCS-SRS-hook.lua",
                          true);

                DirectoryCopy(_currentDirectory + "\\Scripts\\DCS-SRS", path + "\\Mods\\Services\\DCS-SRS");
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(
                    "Install files not found - Unable to install! \n\nMake sure you extract all the files in the zip then run the Installer",
                    "Not Unzipped", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }
            Logger.Info($"Scripts installed to {path}");

            _progressBarDialog.UpdateProgress(false, $"Installed Hooks & Mods/Services @ {path}");
        }
Ejemplo n.º 27
0
        public void StartVidyoChatForAgent()
        {
            using (Trace.Main.scope())
            {
                try
                {
                    Trace.Main.status("Requesting new vidyo interaction for user {}", _session.UserId);

                    /* True if:
                     *  - An interaction is selected
                     *  - It's a chat or callback
                     *  - There's not already a video conversation attached to the interaction
                     */
                    if (_interactionSelector.SelectedInteraction != null &&
                        (_interactionSelector.SelectedInteraction.GetAttribute(InteractionAttributeName.InteractionType)
                         .Equals(InteractionAttributeValues.InteractionType.Chat,
                                 StringComparison.InvariantCultureIgnoreCase) ||
                         _interactionSelector.SelectedInteraction.GetAttribute(InteractionAttributeName.InteractionType)
                         .Equals(InteractionAttributeValues.InteractionType.Callback,
                                 StringComparison.InvariantCultureIgnoreCase)) &&
                        string.IsNullOrEmpty(
                            _interactionSelector.SelectedInteraction.GetAttribute(
                                VideoIntegrationAttributeNames.VideoConversationId)))
                    {
                        var interactionId =
                            _interactionSelector.SelectedInteraction.GetAttribute(InteractionAttributeName.InteractionId);

                        // Ask to attach, create new, or cancel
                        var result =
                            MessageBox.Show(
                                "Attach a new video chat for the selected interaction \"" +
                                _interactionSelector.SelectedInteraction.GetAttribute(
                                    InteractionAttributeName.RemoteName) + "\" (" + interactionId + ")?" +
                                Environment.NewLine + Environment.NewLine +
                                "[Yes] to attach a video chat to this interaction" + Environment.NewLine +
                                "[No] to start a new video interaction", "Attach or create a video conversation?",
                                MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Cancel);

                        switch (result)
                        {
                        case MessageBoxResult.Yes:
                            // Send with interaction ID
                            SendCustomNotification(CustomMessageType.ApplicationRequest,
                                                   VidyoNewConversationRequestOid,
                                                   VidyoNewConversationRequestEid, _session.UserId, interactionId);
                            return;

                        case MessageBoxResult.No:
                            // Send without interaction ID
                            SendCustomNotification(CustomMessageType.ApplicationRequest,
                                                   VidyoNewConversationRequestOid,
                                                   VidyoNewConversationRequestEid, _session.UserId);
                            return;

                        default:
                            // Canceled
                            return;
                        }
                    }

                    // Ask to create or cancel
                    var mboxResult = MessageBox.Show("Create a new video conversation?",
                                                     "Create a new video conversation?", MessageBoxButton.YesNo, MessageBoxImage.Question,
                                                     MessageBoxResult.No);

                    if (mboxResult == MessageBoxResult.Yes)
                    {
                        // Send without interaction ID
                        SendCustomNotification(CustomMessageType.ApplicationRequest, VidyoNewConversationRequestOid,
                                               VidyoNewConversationRequestEid, _session.UserId);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Trace.Main.exception(ex, ex.Message);
                }
            }
        }
Ejemplo n.º 28
0
        public void Copy()
        {
            byte[] buffer = new byte[1024 * 1024]; // 1MB buffer

            bool isCopy = true;

            while (isCopy)
            {
                try
                {
                    using (FileStream source = new FileStream(SourceFilePath, FileMode.Open, FileAccess.Read))
                    {
                        long fileLength = source.Length;

                        using (FileStream dest = new FileStream(DestFilePath, FileMode.CreateNew, FileAccess.Write))
                        {
                            long totalBytes = 0;

                            int currentBlockSize = 0;



                            while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                totalBytes += currentBlockSize;

                                double persentage = (double)totalBytes * 100.0 / fileLength;



                                dest.Write(buffer, 0, currentBlockSize);



                                OnProgressChanged(persentage, ref cancelFlag, _panel);

                                if (CancelFlag == true)
                                {
                                    File.Delete(DestFilePath);
                                    // Delete dest file here
                                    isCopy = false;
                                    break;
                                }

                                CancelFlag = false;
                                pauseFlag.WaitOne(Timeout.Infinite);
                            }
                        }
                    }
                    isCopy = false;
                }
                catch (IOException e)
                {
                    if (!cancelFlag)
                    {
                        var res = MessageBox.Show(e.Message + " Replace?", "Replace?", MessageBoxButton.YesNo,
                                                  MessageBoxImage.Question);
                        if (res == MessageBoxResult.Yes)
                        {
                            isCopy = true;
                            File.Delete(DestFilePath);
                        }
                        else
                        {
                            isCopy = false;
                        }
                    }
                    else
                    {
                        var res = MessageBox.Show(" Copying was canceled!", "Cancel", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                        isCopy = false;
                        File.Delete(DestFilePath);
                    }
                }
                catch (Exception e)
                {
                    var res = MessageBox.Show(e.Message, "Oooops", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }



            OnComplete(_panel);
        }
Ejemplo n.º 29
0
        private void InitApplication()
        {
            try
            {
                // prevent some application crash
                //WpfCommands.DisableWpfTabletSupport();

                Dispatcher.Invoke(new Action(ServiceProvider.Configure));


                ServiceProvider.Settings = new Settings();
                ServiceProvider.Settings = ServiceProvider.Settings.Load();
                ServiceProvider.Branding = Branding.LoadBranding();

                if (ServiceProvider.Settings.DisableNativeDrivers &&
                    MessageBox.Show(TranslationStrings.MsgDisabledDrivers, "", MessageBoxButton.YesNo) ==
                    MessageBoxResult.Yes)
                {
                    ServiceProvider.Settings.DisableNativeDrivers = false;
                }
                ServiceProvider.Settings.LoadSessionData();
                TranslationManager.LoadLanguage(ServiceProvider.Settings.SelectedLanguage);

                ServiceProvider.PluginManager.CopyPlugins();
                Dispatcher.Invoke(new Action(InitWindowManager));


                ServiceProvider.Trigger.Start();
                ServiceProvider.Analytics.Start();
                BitmapLoader.Instance.MetaDataUpdated += Instance_MetaDataUpdated;


                Dispatcher.Invoke(new Action(delegate
                {
                    try
                    {
                        // event handlers
                        ServiceProvider.Settings.SessionSelected += Settings_SessionSelected;

                        ServiceProvider.DeviceManager.CameraConnected    += DeviceManager_CameraConnected;
                        ServiceProvider.DeviceManager.CameraSelected     += DeviceManager_CameraSelected;
                        ServiceProvider.DeviceManager.CameraDisconnected += DeviceManager_CameraDisconnected;
                        //-------------------
                        ServiceProvider.DeviceManager.DisableNativeDrivers = ServiceProvider.Settings.DisableNativeDrivers;
                        if (ServiceProvider.Settings.AddFakeCamera)
                        {
                            ServiceProvider.DeviceManager.AddFakeCamera();
                        }
                        ServiceProvider.DeviceManager.DetectWebcams = ServiceProvider.Settings.WebcamSupport;
                        ServiceProvider.DeviceManager.ConnectToCamera();
                        if (ServiceProvider.Settings.DisableHardwareAccelerationNew)
                        {
                            OpenCL.IsEnabled = false;
                        }
                    }
                    catch (Exception exception)
                    {
                        Log.Error("Unable to initialize device manager", exception);
                        if (exception.Message.Contains("0AF10CEC-2ECD-4B92-9581-34F6AE0637F3"))
                        {
                            MessageBox.Show(
                                "Unable to initialize device manager !\nMissing some components! Please install latest Windows Media Player! ");
                            Application.Current.Shutdown(1);
                        }
                    }
                    StartApplication();
                    if (_startUpWindow != null)
                    {
                        _startUpWindow.Close();
                    }
                }));
                ServiceProvider.Database.StartEvent(EventType.App);
            }
            catch (Exception ex)
            {
                Log.Error("Fatal error ", ex);
            }
        }
Ejemplo n.º 30
0
        public MainWindow()
        {
            InitializeComponent();

            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Instance.Culture);
            ShokoServer.Instance.OAuthProvider    = new AuthProvider(this);
            if (!ShokoServer.Instance.StartUpServer())
            {
                MessageBox.Show(Commons.Properties.Resources.Server_Running,
                                Commons.Properties.Resources.ShokoServer, MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }

            //Create an instance of the NotifyIcon Class
            TippuTrayNotify = new NotifyIcon();

            // This icon file needs to be in the bin folder of the application
            TippuTrayNotify = new NotifyIcon();
            Stream iconStream =
                Application.GetResourceStream(new Uri("pack://application:,,,/ShokoServer;component/db.ico")).Stream;

            TippuTrayNotify.Icon = new Icon(iconStream);
            iconStream.Dispose();

            //show the Tray Notify IconbtnRemoveMissingFiles.Click
            TippuTrayNotify.Visible = true;

            //-- for winforms applications
            System.Windows.Forms.Application.ThreadException -= UnhandledExceptionManager.ThreadExceptionHandler;
            System.Windows.Forms.Application.ThreadException += UnhandledExceptionManager.ThreadExceptionHandler;

            CreateMenus();

            ServerState.Instance.DatabaseAvailable = false;
            ServerState.Instance.ServerOnline      = false;
            ServerState.Instance.BaseImagePath     = ImageUtils.GetBaseImagesPath();

            Closing      += MainWindow_Closing;
            StateChanged += MainWindow_StateChanged;
            TippuTrayNotify.MouseDoubleClick += TippuTrayNotify_MouseDoubleClick;

            btnToolbarShutdown.Click += btnToolbarShutdown_Click;
            btnHasherPause.Click     += btnHasherPause_Click;
            btnHasherResume.Click    += btnHasherResume_Click;
            btnGeneralPause.Click    += btnGeneralPause_Click;
            btnGeneralResume.Click   += btnGeneralResume_Click;
            btnImagesPause.Click     += btnImagesPause_Click;
            btnImagesResume.Click    += btnImagesResume_Click;
            btnAdminMessages.Click   += btnAdminMessages_Click;

            btnRemoveMissingFiles.Click += btnRemoveMissingFiles_Click;
            btnRunImport.Click          += btnRunImport_Click;
            btnSyncHashes.Click         += BtnSyncHashes_Click;
            btnSyncMedias.Click         += BtnSyncMedias_Click;
            btnSyncMyList.Click         += btnSyncMyList_Click;
            btnSyncVotes.Click          += btnSyncVotes_Click;
            btnUpdateTvDBInfo.Click     += btnUpdateTvDBInfo_Click;
            btnUpdateAllStats.Click     += btnUpdateAllStats_Click;
            btnSyncTrakt.Click          += btnSyncTrakt_Click;
            btnImportManualLinks.Click  += btnImportManualLinks_Click;
            btnUpdateAniDBInfo.Click    += btnUpdateAniDBInfo_Click;
            btnLaunchWebUI.Click        += btnLaunchWebUI_Click;
            btnUpdateImages.Click       += btnUpdateImages_Click;
            btnUploadAzureCache.Click   += btnUploadAzureCache_Click;
            btnUpdateTraktInfo.Click    += BtnUpdateTraktInfo_Click;
            btnSyncPlex.Click           += BtnSyncPlexOn_Click;
            btnValidateImages.Click     += BtnValidateAllImages_Click;

            Loaded += MainWindow_Loaded;

            txtServerPort.Text = ServerSettings.Instance.ServerPort.ToString(CultureInfo.InvariantCulture);

            btnToolbarHelp.Click     += btnToolbarHelp_Click;
            btnApplyServerPort.Click += btnApplyServerPort_Click;
            btnUpdateMediaInfo.Click += btnUpdateMediaInfo_Click;

            //StartUp();

            cboDatabaseType.Items.Clear();
            ShokoServer.Instance.GetSupportedDatabases().ForEach(s => cboDatabaseType.Items.Add(s));
            cboDatabaseType.SelectionChanged +=
                cboDatabaseType_SelectionChanged;

            btnChooseImagesFolder.Click += btnChooseImagesFolder_Click;
            btnSetDefault.Click         += BtnSetDefault_Click;


            btnSaveDatabaseSettings.Click   += btnSaveDatabaseSettings_Click;
            btnRefreshMSSQLServerList.Click += btnRefreshMSSQLServerList_Click;
            // btnInstallMSSQLServer.Click += new RoutedEventHandler(btnInstallMSSQLServer_Click);
            btnMaxOnStartup.Click               += toggleMinimizeOnStartup;
            btnMinOnStartup.Click               += toggleMinimizeOnStartup;
            btnLogs.Click                       += btnLogs_Click;
            btnChooseVLCLocation.Click          += btnChooseVLCLocation_Click;
            btnJMMEnableStartWithWindows.Click  += btnJMMEnableStartWithWindows_Click;
            btnJMMDisableStartWithWindows.Click += btnJMMDisableStartWithWindows_Click;
            btnUpdateAniDBLogin.Click           += btnUpdateAniDBLogin_Click;

            btnHasherClear.Click  += btnHasherClear_Click;
            btnGeneralClear.Click += btnGeneralClear_Click;
            btnImagesClear.Click  += btnImagesClear_Click;

            //automaticUpdater.MenuItem = mnuCheckForUpdates;

            ServerState.Instance.LoadSettings();

            cboLanguages.SelectionChanged += cboLanguages_SelectionChanged;

            InitCulture();
            Instance = this;

            if (!ServerSettings.Instance.FirstRun && ShokoService.AnidbProcessor.ValidAniDBCredentials())
            {
                logger.Info("Already been set up... Initializing DB...");
                ShokoServer.RunWorkSetupDB();
                cboLanguages.IsEnabled = true;
            }

            SubscribeEvents();
        }