예제 #1
0
        private void loadMruFileProjects()
        {
            barSubRecentProjects.ItemLinks.Clear();

            var files = coreLoadMruProjectFiles();

            if (files.Length <= 0)
            {
                barSubRecentProjects.Visibility = BarItemVisibility.Never;
                barSubRecentProjects.Enabled    = false;
            }
            else
            {
                barSubRecentProjects.Visibility = BarItemVisibility.Always;
                barSubRecentProjects.Enabled    = true;

                var index = 0;
                foreach (var file in files)
                {
                    var bbi =
                        new BarButtonItem
                    {
                        Caption =
                            $@"{index + 1} {ZlpPathHelper.GetFileNameWithoutExtension(file)}",
                        //Description =
                        //    ZrePathHelper.ShortenPathName(
                        //        file,
                        //        MruMaxCharSize),
                        SuperTip        = createToolTip(file),
                        Tag             = file,
                        Enabled         = true,
                        Visibility      = BarItemVisibility.Always,
                        LargeImageIndex = 40
                    };

                    bbi.ItemClick += bbi_ItemClick2;

                    barSubRecentProjects.ItemLinks.Add(bbi);

                    index++;
                }

                // --

                if (barSubRecentProjects.ItemLinks.Count > 0)
                {
                    var bbi =
                        new BarButtonItem
                    {
                        Caption =
                            Resources.SR_MainFormNew_loadMruFileProjects_ClearRecentProjectsList,
                        Description = Resources.SR_MainFormNew_loadMruFileProjects_RemovesAllItemsFromTheListAbove,
                        Enabled     = true,
                        Visibility  = BarItemVisibility.Always
                    };

                    bbi.ItemClick +=
                        delegate
                    {
                        coreStoreMruProjectFiles(new string[] { });
                        UpdateUI();
                        loadMruFileProjects();
                        checkShowApplicationMenuButton();
                    };

                    barSubRecentProjects.ItemLinks.Add(bbi, true);
                }
            }
        }
예제 #2
0
        public void TestCompareWithFrameworkFunctions()
        {
            string s1;
            string s2;

            // --

            s1 = ZlpPathHelper.GetFileNameFromFilePath(@"/suchen.html");
            s2 = Path.GetFileName(@"/suchen.html");

            Assert.AreEqual(s1, s2);

            // --

            s1 = ZlpPathHelper.GetDirectoryPathNameFromFilePath(@"sitemap.xml");
            s2 = Path.GetDirectoryName(@"sitemap.xml");

            Assert.AreEqual(s1, s2);

            //s1 = ZlpPathHelper.GetDirectoryPathNameFromFilePath(@"");
            //s2 = Path.GetDirectoryName(@"");

            //Assert.AreEqual(s1, s2);

            s1 = ZlpPathHelper.GetDirectoryPathNameFromFilePath(@"c:\ablage\sitemap.xml");
            s2 = Path.GetDirectoryName(@"c:\ablage\sitemap.xml");

            Assert.AreEqual(s1, s2);

            s1 = ZlpPathHelper.GetDirectoryPathNameFromFilePath(@"c:\ablage\");
            s2 = Path.GetDirectoryName(@"c:\ablage\");

            Assert.AreEqual(s1, s2);

            s1 = ZlpPathHelper.GetDirectoryPathNameFromFilePath(@"c:\ablage");
            s2 = Path.GetDirectoryName(@"c:\ablage");

            Assert.AreEqual(s1, s2);

            s1 = ZlpPathHelper.GetDirectoryPathNameFromFilePath(@"c:/ablage/sitemap.xml");
            s2 = Path.GetDirectoryName(@"c:/ablage/sitemap.xml");

            Assert.AreEqual(s1, s2);

            // --

            s1 = @"c:\folder1\folder2\folder3\file1.txt";

            var s3 = ZlpPathHelper.GetFileNameFromFilePath(s1);
            var s4 = Path.GetFileName(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"c:\folder1\folder2\folder3\file1";

            s3 = ZlpPathHelper.GetFileNameFromFilePath(s1);
            s4 = Path.GetFileName(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"c:\folder1\folder2\folder3\file1.";

            s3 = ZlpPathHelper.GetFileNameFromFilePath(s1);
            s4 = Path.GetFileName(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"file1.txt";

            s3 = ZlpPathHelper.GetFileNameFromFilePath(s1);
            s4 = Path.GetFileName(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"file1";

            s3 = ZlpPathHelper.GetFileNameFromFilePath(s1);
            s4 = Path.GetFileName(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"file1.";

            s3 = ZlpPathHelper.GetFileNameFromFilePath(s1);
            s4 = Path.GetFileName(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"c:\folder1\folder2\folder3\file1.txt";

            s3 = ZlpPathHelper.GetFileNameWithoutExtension(s1);
            s4 = Path.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"c:\folder1\folder2\folder3\file1";

            s3 = ZlpPathHelper.GetFileNameWithoutExtension(s1);
            s4 = Path.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"c:\folder1\folder2\folder3\file1.";

            s3 = ZlpPathHelper.GetFileNameWithoutExtension(s1);
            s4 = Path.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"file1.txt";

            s3 = ZlpPathHelper.GetFileNameWithoutExtension(s1);
            s4 = Path.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"file1";

            s3 = ZlpPathHelper.GetFileNameWithoutExtension(s1);
            s4 = Path.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"file1.";

            s3 = ZlpPathHelper.GetFileNameWithoutExtension(s1);
            s4 = Path.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(s3, s4);
        }
예제 #3
0
        public void TestGeneral()
        {
            var s1 =
                @"C:\Users\ukeim\Documents\Visual Studio 2008\Projects\Zeta Producer 9\Zeta Producer Main\Deploy\Origin\Enterprise\C-Allgaier\Windows\Packaging\Stationary\DEU\FirstStart\StandardProject";
            var s2 = ZlpPathHelper.GetFullPath(s1);

            Assert.AreEqual(
                @"C:\Users\ukeim\Documents\Visual Studio 2008\Projects\Zeta Producer 9\Zeta Producer Main\Deploy\Origin\Enterprise\C-Allgaier\Windows\Packaging\Stationary\DEU\FirstStart\StandardProject",
                s2);

            // --

            s1 = @"c:\ablage\..\windows\notepad.exe";
            s2 = ZlpPathHelper.GetFullPath(s1);

            Assert.AreEqual(@"c:\windows\notepad.exe", s2);

            //--

            s1 = @"lalala-123";
            s2 = ZlpPathHelper.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(@"lalala-123", s2);

            //--

            s1 = @"lalala-123.txt";
            s2 = ZlpPathHelper.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(@"lalala-123", s2);

            //--

            s1 = @"C:\Ablage\lalala-123.txt";
            s2 = ZlpPathHelper.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(@"lalala-123", s2);

            //--

            s1 = @"\\nas001\data\folder\lalala-123.txt";
            s2 = ZlpPathHelper.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(@"lalala-123", s2);

            //--

            s1 = @"c:\ablage\..\windows\notepad.exe";
            s2 = ZlpPathHelper.GetFileNameWithoutExtension(s1);

            Assert.AreEqual(@"notepad", s2);

            //--

            s1 = @"c:\ablage\..\windows\notepad.exe";
            s2 = ZlpPathHelper.GetExtension(s1);

            Assert.AreEqual(@".exe", s2);

            //--

            s1 = @"c:\ablage\..\windows\notepad.exe";
            s2 = ZlpPathHelper.ChangeExtension(s1, @".com");

            Assert.AreEqual(@"c:\ablage\..\windows\notepad.com", s2);

            // --

            s1 = @"file.ext";
            s2 = @"c:\ablage\path1\path2";
            var s3 = @"c:\ablage\path1\path2\file.ext";
            var s4 = ZlpPathHelper.GetAbsolutePath(s1, s2);

            Assert.AreEqual(s3, s4);

            // --

            s1 = @"c:\folder1\folder2\folder4\";
            s2 = @"c:\folder1\folder2\folder3\file1.txt";
            s3 = ZlpPathHelper.GetRelativePath(s1, s2);

            s4 = @"..\folder3\file1.txt";

            Assert.AreEqual(s3, s4);
        }
예제 #4
0
        public bool CreateAndAddNewFile(
            string sourceFilePath,
            string newFileName,
            string sourceLanguageCode,
            string newLanguageCode,
            bool copyTextsFromSource,
            bool automaticallyTranslateTexts,
            string prefix)
        {
            if (newFileName.StartsWith(BaseName, StringComparison.InvariantCultureIgnoreCase) &&
                newFileName.EndsWith(BaseExtension, StringComparison.InvariantCultureIgnoreCase))
            {
                var newFilePath =
                    ZlpPathHelper.Combine(
                        ZlpPathHelper.GetDirectoryPathNameFromFilePath(sourceFilePath),
                        newFileName);

                bool didCopy;

                if (ZlpIOHelper.FileExists(newFilePath))
                {
                    // Simply ignore and add.

                    didCopy = false;

                    // File may already exist but was not yet added
                    // to the file group.

                    /*
                     * throw new Exception(
                     *      string.Format(
                     *              "New file '{0}' already exists.",
                     *              newFileName));
                     */
                }
                else
                {
                    // Copy only if not exists.

                    ZlpIOHelper.CopyFile(sourceFilePath, newFilePath, false);
                    didCopy = true;
                }

                // Add to myself.
                var ffi =
                    new FileInformation(this)
                {
                    File = new ZlpFileInfo(newFilePath)
                };
                Add(ffi);

                // --
                // Further process.

                if (!copyTextsFromSource /*&& !automaticallyTranslateTexts*/)
                {
                    if (didCopy)
                    {
                        clearAllTexts(ffi);
                    }
                }

                if (automaticallyTranslateTexts)
                {
                    if (didCopy)
                    {
                        translateTexts(
                            _project,
                            ffi,
                            sourceLanguageCode,
                            newLanguageCode,
                            prefix);
                    }
                }

                return(didCopy);
            }
            else
            {
                throw new Exception(
                          string.Format(
                              Resources.SR_FileGroup_CreateAndAddNewFile_New_file_name_does_not_match,
                              BaseName,
                              BaseExtension));
            }
        }
예제 #5
0
        public void TestGeneral()
        {
            // Ordner mit Punkt am Ende.
            var dir = $@"C:\Ablage\{Guid.NewGuid():N}.";

            Assert.IsFalse(new ZlpDirectoryInfo(dir).Exists);
            new ZlpDirectoryInfo(dir).CheckCreate();
            Assert.IsTrue(new ZlpDirectoryInfo(dir).Exists);
            new ZlpDirectoryInfo(dir).Delete(true);
            Assert.IsFalse(new ZlpDirectoryInfo(dir).Exists);


            //Assert.IsTrue(new ZlpDirectoryInfo(Path.GetTempPath()).CreationTime>DateTime.MinValue);
            //Assert.IsTrue(new ZlpDirectoryInfo(Path.GetTempPath()).Exists);
            //Assert.IsFalse(new ZlpDirectoryInfo(@"C:\Ablage\doesnotexistjdlkfjsdlkfj").Exists);
            //Assert.IsTrue(new ZlpDirectoryInfo(Path.GetTempPath()).Exists);
            //Assert.IsFalse(new ZlpDirectoryInfo(@"C:\Ablage\doesnotexistjdlkfjsdlkfj2").Exists);
            //Assert.IsFalse(new ZlpDirectoryInfo(@"\\zetac11\C$\Ablage").Exists);
            //Assert.IsFalse(new ZlpDirectoryInfo(@"\\zetac11\C$\Ablage\doesnotexistjdlkfjsdlkfj2").Exists);

            const string s1 =
                @"C:\Users\Chris\Documents\Development\ADC\InterStore.NET\Visual Studio 2008\6.4.2\Zeta Resource Editor";
            const string s2 =
                @"C:\Users\Chris\Documents\Development\ADC\InterStore.NET\Visual Studio 2008\6.4.2\Web\central\Controls\App_LocalResources\ItemSearch";

            var s3 = ZlpPathHelper.GetRelativePath(s1, s2);

            Assert.AreEqual(s3, @"..\Web\central\Controls\App_LocalResources\ItemSearch");

            var ext = ZlpPathHelper.GetExtension(s3);

            Assert.IsEmpty(ext ?? string.Empty);

            ext = ZlpPathHelper.GetExtension(@"C:\Ablage\Uwe.txt");
            Assert.AreEqual(ext, @".txt");

            const string path = @"C:\Ablage\Test";

            Assert.AreEqual(
                new DirectoryInfo(path).Name,
                new ZlpDirectoryInfo(path).Name);

            Assert.AreEqual(
                new DirectoryInfo(path).FullName,
                new ZlpDirectoryInfo(path).FullName);

            const string filePath = @"C:\Ablage\Test\file.txt";
            var          fn1      = new FileInfo(filePath).Directory?.FullName;
            var          fn2      = new ZlpFileInfo(filePath).Directory.FullName;

            var fn1A = new FileInfo(filePath).DirectoryName;
            var fn2A = new ZlpFileInfo(filePath).DirectoryName;

            Assert.AreEqual(fn1, fn2);
            Assert.AreEqual(fn1A, fn2A);

            var fn = new ZlpDirectoryInfo(@"\\zetac11\C$\Ablage\doesnotexistjdlkfjsdlkfj2").Parent.FullName;

            Assert.AreEqual(fn, @"\\zetac11\C$\Ablage");

            fn = new ZlpDirectoryInfo(@"\\zetac11\C$\Ablage\doesnotexistjdlkfjsdlkfj2\").Parent.FullName;

            Assert.AreEqual(fn, @"\\zetac11\C$\Ablage");
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            _result = null;

            using (new WaitCursor(this, WaitCursorOption.ShortSleep))
            {
                var cultures = getCultures();

                var baseFolderPath = baseFolderTextEdit.Text.Trim();
                var baseFileName   = baseFileNameTextEdit.Text.Trim();

                var extension = @"." + extensionComboBoxEdit.Text.Trim('.');

                var created = 0;

                using (new BackgroundWorkerLongProgressGui(
                           delegate(object snd, DoWorkEventArgs args)
                {
                    try
                    {
                        var bw = (BackgroundWorker)snd;

                        // --
                        // First pass, add all in-memory to check for same file group.

                        var fg = new FileGroup(_project);

                        if (cultures != null)
                        {
                            foreach (var culture in cultures)
                            {
                                var fileName =
                                    _project.IsNeutralLanguage(culture)
                                                                                        ? baseFileName + extension
                                                                                        : generateFileName(fg, culture);

                                fg.Add(new FileInformation(fg)
                                {
                                    File = new ZlpFileInfo(fileName)
                                });
                            }

                            // Look for same entries.
                            if (_project.FileGroups.HasFileGroupWithChecksum(
                                    fg.GetChecksum(_project)))
                            {
                                throw new MessageBoxException(
                                    this,
                                    Resources.SR_ProjectFilesUserControl_AddResourceFilesWithDialog_ExistsInTheProject,
                                    MessageBoxIcon.Information);
                            }
                            else
                            {
                                // --
                                // Second pass, add all existing.

                                fg = new FileGroup(_project);

                                foreach (var culture in cultures)
                                {
                                    if (bw.CancellationPending)
                                    {
                                        throw new OperationCanceledException();
                                    }

                                    var fileName =
                                        _project.IsNeutralLanguage(culture)
                                                                                                ? baseFileName + extension
                                                                                                : generateFileName(fg, culture);

                                    FileInformation ffi;

                                    if (_project.IsNeutralLanguage(culture))
                                    {
                                        ffi = new FileInformation(fg)
                                        {
                                            File = new ZlpFileInfo(ZlpPathHelper.Combine(baseFolderPath, fileName))
                                        };
                                        fg.Add(ffi);
                                    }
                                    else
                                    {
                                        ffi =
                                            fg.CreateAndAddNewFile(
                                                baseFolderPath,
                                                fileName,
                                                culture.Name);
                                    }

                                    // Must create real file.
                                    ZlpIOHelper.WriteAllText(ffi.File.FullName, Resources.SR_EmptyResourceFile);

                                    created++;
                                }
                            }
                        }

                        if (_projectFolder != null)
                        {
                            fg.ProjectFolder = _projectFolder;
                        }

                        _project.FileGroups.Add(fg);
                        _project.MarkAsModified();

                        _result = fg;
                    }
                    catch (OperationCanceledException)
                    {
                        // Ignore.
                    }
                },
                           Resources.SR_CreateNewFilesForm_Creating,
                           BackgroundWorkerLongProgressGui.CancellationMode.Cancelable,
                           this))
                {
                }

                // --

                XtraMessageBox.Show(
                    this,
                    string.Format(
                        Resources.SR_CreateNewFilesForm_Finished03,
                        created),
                    @"Zeta Resource Editor",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
        }
        private void doAutomaticallyAddResourceFilesFromVSSolution(
            BackgroundWorker backgroundWorker,
            ProjectFolder parentProjectFolder,
            ref int fileGroupCount,
            ref int fileCount,
            ZlpFileInfo vsSolutionPath)
        {
            if (vsSolutionPath != null && vsSolutionPath.Exists)
            {
                string solutionText;
                //using (var sr = vsSolutionPath.OpenText())
                {
                    //we can read it line by line to reduce memory usage, but solution files are not very big
                    solutionText = ZlpIOHelper.ReadAllText(vsSolutionPath.FullName); // sr.ReadToEnd();
                }
                //solution files looks like:
                //Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZetaResourceEditor", "Main\ZetaResourceEditor.csproj", "{367758E7-0435-440A-AC76-1F30ABBA3ED8}"
                //EndProject
                //known projectTypes:
                //c#: FAE04EC0-301F-11D3-BF4B-00C04F79EFBC, VB: F184B08F-C81C-45F6-A57F-5ABD9991F28F
                //@see http://msdn.microsoft.com/en-us/library/hb23x61k%28VS.80%29.aspx
                //TODO: support virtual folders
                var supportedProjectTypes =
                    new[]
                {
                    @"FAE04EC0-301F-11D3-BF4B-00C04F79EFBC",
                    @"F184B08F-C81C-45F6-A57F-5ABD9991F28F"
                };

                //we need some regular expression to find required info:
                const string pattern =
                    @"Project\(""{(?<projectType>[^}]*)}""\)\s*=\s*""(?<projectName>[^""]*)"",\s*""(?<projectRelPath>[^""]*)"",\s*""{(?<projectID>[^}]*)}""";

                foreach (Match m in Regex.Matches(solutionText, pattern))
                {
                    if (!m.Success)
                    {
                        continue;
                    }

                    var g = m.Groups[@"projectType"];
                    if (g == null || !g.Success)
                    {
                        continue;
                    }
                    var projectType = g.Value;

                    //compare with known project types.
                    // Currently only CS Projects are supported.
                    // But other types like VB can be simply added.
                    if (!Array.Exists(supportedProjectTypes, a => a == projectType))
                    {
                        continue;
                    }

                    var projectRelPath = m.Groups[@"projectRelPath"].Value;
                    var projectFile    =
                        new ZlpFileInfo(ZlpPathHelper.Combine(vsSolutionPath.Directory.FullName, projectRelPath));

                    //add all files from project
                    //we can add each using separate sub folder
                    var projectName = m.Groups[@"projectName"].Value;
                    //look in subfolders only
                    var subFolders = Project.ProjectFolders;
                    if (parentProjectFolder != null)
                    {
                        subFolders = parentProjectFolder.ChildProjectFolders;
                    }
                    var pf = subFolders.Find(f => f.Name == projectName);
                    if (pf == null)
                    {
                        pf =
                            new ProjectFolder(Project)
                        {
                            Name   = projectName,
                            Parent = parentProjectFolder
                        };
                        Project.ProjectFolders.Add(pf);
                    }

                    Project.MarkAsModified();

                    DoAutomaticallyAddResourceFilesFromVsProject(
                        backgroundWorker,
                        pf,
                        ref fileGroupCount,
                        ref fileCount,
                        projectFile);
                }
            }
        }
예제 #8
0
 private void DoWork()
 {
     try
     {
         CurrentAction = "Discovery";
         DoStatus(true);
         //var sources = sourcefolders.SelectMany(s => GetFiles(s, Path.GetDirectoryName(s), target)).ToList();
         var sources = sourcefolders.SelectMany(s => GetFiles(s, ZlpPathHelper.GetDirectoryPathNameFromFilePath(s), target)).ToList();
         {
             //var files = sources.Select(item => item.Source).OfType<FileInfo>().Count();
             var files = sources.Select(item => item.Source).OfType <ZlpFileInfo>().Count();
             this.TotalItems    = files;
             this.TotalProgress = files;
         }
         DoStatus(true);
         if (CheckCancel())
         {
             return;
         }
         foreach (var item in sources)
         {
             //if (item.Source is FileInfo sourcefile && item.Target is FileInfo targetfile)
             if (item.Source is ZlpFileInfo sourcefile && item.Target is ZlpFileInfo targetfile)
             {
                 var same = false;
                 while (!same && !IsCancelled)
                 {
                     if (CheckCancel())
                     {
                         return;
                     }
                     try
                     {
                         CurrentAction = "Linking";
                         CurrentName   = sourcefile.Name;
                         DoStatus(false);
                         targetfile.Refresh();
                         if (targetfile.Exists)
                         {
                             targetfile.Delete();
                         }
                         same = CreateHardLink(IOHelper.CheckAddLongPathPrefix(targetfile.FullName), IOHelper.CheckAddLongPathPrefix(sourcefile.FullName), IntPtr.Zero);
                         if (same)
                         {
                             CurrentItems++;
                             CurrentProgress++;
                             DoStatus(false);
                         }
                         else
                         {
                         }
                     }
                     catch (Exception e)
                     {
                         CurrentAction = "Errored";
                         CurrentName   = $"{sourcefile.Name}:{e.GetType().Name}: {e.Message}";
                         DoStatus(true);
                         Thread.Sleep(5000);
                     }
                 }
             }
             //else if (item.Target is DirectoryInfo td)
             else if (item.Target is ZlpDirectoryInfo td)
             {
                 td.Create();
             }
         }
예제 #9
0
        private static void Main()
        {
            try
            {
                //Zeta.EnterpriseLibrary.Common.Configuration.
                //    LibraryConfiguration.Current.Initialize();
                //Zeta.EnterpriseLibrary.Windows.Configuration.
                //    LibraryConfiguration.Current.Initialize();

                LogCentral.Current.ConfigureLogging();

                // --
                // Register extension.

                try
                {
                    var info =
                        new FileExtensionRegistration.RegistrationInformation
                    {
                        ApplicationFilePath = typeof(Host).Assembly.Location,
                        Extension           = Project.ProjectFileExtension,
                        ClassName           = @"ZetaResourceEditorDocument",
                        Description         = Resources.SR_Host_Main_ZetaResourceEditorProjectFile
                    };

                    FileExtensionRegistration.Register(info);
                }
                catch (Exception x)
                {
                    // May fail if no permissions, silently eat.
                    LogCentral.Current.LogError(x);
                }

                // --

                var persistentStorage =
                    new PersistentXmlFilePairStorage
                {
                    FilePath =
                        ZlpPathHelper.Combine(
                            CurrentUserStorageBaseFolderPath.FullName,
                            @"zeta-resource-editor-settings.xml")
                };
                persistentStorage.Error += storageError;

                PersistanceHelper.Storage = persistentStorage;

                // --

                // http://community.devexpress.com/forums/t/80133.aspx

                // http://www.devexpress.com/Support/Center/p/B155647.aspx
                //DevExpress.UserSkins.OfficeSkins.Register();
                //DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = @"Office 2010 Silver";

                DevExpress.Skins.SkinManager.EnableFormSkins();

                // --

                // Manually turn off.
                //Zeta.EnterpriseLibrary.Windows.Configuration.
                //    LibraryConfiguration.Current.IsDesignMode = false;

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                AppDomain.CurrentDomain.UnhandledException +=
                    currentDomainUnhandledException;
                Application.ThreadException +=
                    applicationThreadException;

                test();

                initializeLanguage();

                Application.Run(new MainForm());
            }
            catch (Exception x)
            {
                doHandleException(x);
            }
        }
        public void DoAutomaticallyAddResourceFilesFromVsProject(
            BackgroundWorker backgroundWorker,
            ProjectFolder parentProjectFolder,
            ref int fileGroupCount,
            ref int fileCount,
            ZlpFileInfo vsProjectPath)
        {
            if (backgroundWorker.CancellationPending)
            {
                throw new OperationCanceledException();
            }
            else if (vsProjectPath != null && vsProjectPath.Exists)
            {
                if (@".sln" == vsProjectPath.Extension.ToLowerInvariant())
                {
                    //file is solution, so add all projects from solution
                    doAutomaticallyAddResourceFilesFromVSSolution(
                        backgroundWorker,
                        parentProjectFolder,
                        ref fileGroupCount,
                        ref fileCount,
                        vsProjectPath);
                }
                else
                {
                    //load fom solution
                    var pdoc = new XmlDocument();
                    //using (var fs = vsProjectPath.OpenRead())
                    {
                        pdoc.LoadXml(ZlpIOHelper.ReadAllText(vsProjectPath.FullName));
                    }

                    var nameMgr = new XmlNamespaceManager(pdoc.NameTable);
                    nameMgr.AddNamespace(@"mb", @"http://schemas.microsoft.com/developer/msbuild/2003");
                    const string xpath    = @"/mb:Project/mb:ItemGroup/mb:EmbeddedResource/@Include";
                    var          resNodes = pdoc.SelectNodes(xpath, nameMgr);

                    var filePaths = new List <ZlpFileInfo>();                    //get all files
                    if (resNodes != null)
                    {
                        // ReSharper disable LoopCanBeConvertedToQuery
                        foreach (XmlNode node in resNodes)
                        // ReSharper restore LoopCanBeConvertedToQuery
                        {
                            var include = node.Value;

                            if (!string.IsNullOrEmpty(include) &&
                                (include.ToLowerInvariant().EndsWith(@".resx") ||
                                 include.ToLowerInvariant().EndsWith(@".resw")))
                            {
                                var fullPath = ZlpPathHelper.Combine(vsProjectPath.DirectoryName, include);
                                filePaths.Add(new ZlpFileInfo(fullPath));
                            }
                        }
                    }

                    //add all files from list
                    DoAutomaticallyAddResourceFilesFromList(
                        backgroundWorker,
                        parentProjectFolder,
                        ref fileGroupCount,
                        ref fileCount,
                        filePaths);
                }
            }
        }
예제 #11
0
        public void TransferSetupFile(
            string apiKey,
            string fileName,
            byte[] fileContent)
        {
            try
            {
                LogCentral.Current.LogInfo(
                    $@"About to receive file with name '{fileContent}' and size {fileContent?.Length ?? 0:#,#} bytes");

                var requiredApiKey =
                    ConfigurationManager.AppSettings[@"setupUploadService.apiKey"];

                if (string.Compare(apiKey, requiredApiKey, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    var baseFolderPath =
                        ConfigurationManager.AppSettings[@"setupUploadService.baseFolderPath"];

                    var destinationFilePath =
                        ZlpPathHelper.Combine(
                            baseFolderPath,
                            fileName);

                    destinationFilePath += @"." + Guid.NewGuid().ToString(@"N");

                    var tempDestinationFilePath = destinationFilePath + @".temporary";

                    // --

                    using (var fs = new FileStream(
                               tempDestinationFilePath,
                               FileMode.Create,
                               FileAccess.Write,
                               FileShare.None))
                    {
                        if (fileContent != null)
                        {
                            fs.Write(fileContent, 0, fileContent.Length);
                        }
                    }

                    // --

                    File.Move(tempDestinationFilePath, destinationFilePath);

                    // --
                    // Delete any older files, if  currently not in use.

                    var files =
                        new List <FileInfo>(
                            new DirectoryInfo(baseFolderPath).
                            GetFiles(fileName + @"*"));

                    files.RemoveAll(x => x.FullName.ToLowerInvariant().EndsWith(@".temporary"));
                    files.Sort((x, y) => - x.LastWriteTime.CompareTo(y.LastWriteTime));

                    if (files.Count > 1)
                    {
                        for (var index = 1; index < files.Count; ++index)
                        {
                            var file = files[index];

                            try
                            {
                                LogCentral.Current.LogInfo(
                                    $@"About to delete old file '{file.Name}'.");

                                // Try to delete but if failing (usually when in use),
                                // do not fail.
                                file.Delete();
                            }
                            catch (Exception x)
                            {
                                LogCentral.Current.LogError(
                                    $@"Ignoring error while deleting file '{file.Name}'.",
                                    x);
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception(
                              $"Invalid API key '{apiKey}'.");
                }
            }
            catch (Exception x)
            {
                LogCentral.Current.LogError(
                    $@"Exception during upload of file '{fileName}' with API key '{apiKey}' and {fileContent?.Length ?? 0:#,#} bytes file size.",
                    x);

                throw;
            }
        }
예제 #12
0
        private static void Main()
        {
            try
            {
                LogCentral.Current.ConfigureLogging();

                // --
                // Register extension.

                try
                {
                    var info =
                        new FileExtensionRegistration.RegistrationInformation
                    {
                        ApplicationFilePath = typeof(Host).Assembly.Location,
                        Extension           = Project.ProjectFileExtension,
                        ClassName           = @"ZetaResourceEditorDocument",
                        Description         = Resources.SR_Host_Main_ZetaResourceEditorProjectFile
                    };

                    FileExtensionRegistration.Register(info);
                }
                catch (Exception x)
                {
                    // May fail if no permissions, silently eat.
                    LogCentral.Current.LogError(x);
                }

                // --

                var persistentStorage =
                    new PersistentXmlFilePairStorage
                {
                    FilePath =
                        ZlpPathHelper.Combine(
                            CurrentUserStorageBaseFolderPath.FullName,
                            @"zeta-resource-editor-settings.xml")
                };
                persistentStorage.Error += storageError;

                PersistanceHelper.Storage = persistentStorage;

                // --

                // http://community.devexpress.com/forums/t/80133.aspx

                SkinHelper.InitializeAll();

                // --

                AppDomain.CurrentDomain.UnhandledException += currentDomainUnhandledException;
                Application.ThreadException += applicationThreadException;

                // --
                // http://stackoverflow.com/a/9180843/107625

                var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                foreach (var assemblyName in Directory.GetFiles(dir, @"*.dll"))
                {
                    try
                    {
                        var assembly = Assembly.LoadFile(assemblyName);
                        _additional.Add(assembly.GetName().Name, assembly);
                    }
                    catch (BadImageFormatException)
                    {
                        // Ignorieren.
                    }
                }

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ResolveAssembly;
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_ResolveAssembly;

                // --

                test();

                initializeLanguage();

                Application.Run(new MainForm());
            }
            catch (Exception x)
            {
                doHandleException(x);
            }
        }
        private static string doSendFilesWithZetaUploader(
            BackgroundWorker bw,
            SendProjectInformation information,
            string[] filePathsToSend)
        {
            if (filePathsToSend.Length > 0)
            {
                bw.ReportProgress(
                    0,
                    new ExcelProgressInformation
                {
                    TemporaryProgressMessage =
                        string.Format(
                            Resources.ExcelExportController_doSendFilesWithZetaUploader_Sending__0__files_through_Zeta_Uploader___,
                            filePathsToSend.Length)
                });

                var sendInfo =
                    new ZetaUploaderCommunicationClientTransferInformation2
                {
                    EMailReceiverAddresses =
                        splitEMailAddresses(
                            information.SendFilesEMailReceivers),
                    EMailSubject =
                        replaceEMailPlaceholders(
                            information.SendFilesEMailSubject, information),
                    AdditionalRemarks =
                        replaceEMailPlaceholders(
                            information.SendFilesEMailBody, information),
                    Language =
                        CultureHelper.GetSupportedUICultureFromThreeLetterWindowsLanguageName(
                            CultureInfo.CurrentUICulture.ThreeLetterWindowsLanguageName).TwoLetterISOLanguageName,
                    UserStates = new[] { new ZulPair {
                                             Name = @"allow-browse", Value = bool.TrueString
                                         } },
                };

                // --

                if (filePathsToSend.Length == 1)
                {
                    sendInfo.FileName    = ZlpPathHelper.GetFileNameFromFilePath(filePathsToSend[0]);
                    sendInfo.FileContent = ZlpIOHelper.ReadAllBytes(filePathsToSend[0]);
                }
                else
                {
                    sendInfo.FileName = replaceEMailPlaceholders(@"ZRE-Sent-Project-{SafeProjectName}.zip", information);

                    var compressInfos = new CompressHeterogeneousInfos();

                    compressInfos.AddFiles(filePathsToSend);

                    sendInfo.FileContent =
                        CompressionHelper.CompressHeterogeneous(
                            compressInfos);
                }

                if (bw.CancellationPending)
                {
                    throw new OperationCanceledException();
                }

                var ws     = WebServiceManager.Current.ZetaUploaderWS;
                var result = ws.SendFile2(sendInfo);

                return(result.DownloadUrl);
            }
            else
            {
                throw new Exception(Resources.SendProjectController_doSendFilesWithZetaUploader_No_files_to_send_);
            }
        }
예제 #14
0
        public string GetNameIntelligent(
            Project project)
        {
            lock (_fileInfos)
            {
                if (string.IsNullOrEmpty(_name) && _fileInfos.Count > 0)
                {
                    // Try guessing several names.

                    var filePath   = _fileInfos[0].File;
                    var folderPath = filePath.Directory;

                    //CHANGED: use base name instead
                    var baseName = LanguageCodeDetection.GetBaseName(project, filePath.Name);
                    filePath = new ZlpFileInfo(ZlpPathHelper.Combine(folderPath.FullName, baseName));

                    if ((string.Equals(@"Properties", folderPath.Name,
                                       StringComparison.InvariantCultureIgnoreCase) ||
                         string.Equals(@"App_GlobalResources", folderPath.Name,
                                       StringComparison.InvariantCultureIgnoreCase)) &&
                        filePath.Name.StartsWith(
                            @"Resources.", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var parentFolderPath = folderPath.Parent;
                        if (parentFolderPath == null)
                        {
                            return(_name);
                        }
                        else
                        {
                            //CHANGED: append fileName, otherwise name is not complete.
                            var pathToMakeRelative = ZlpPathHelper.Combine(parentFolderPath.FullName, filePath.Name);
                            return
                                (shortenFilePath(
                                     ZlpPathHelper.GetRelativePath(
                                         project == null
                                                                                        ? string.Empty
                                                                                        : project.ProjectConfigurationFilePath.DirectoryName,
                                         pathToMakeRelative)));
                        }
                    }
                    else if (string.Equals(@"App_LocalResources", folderPath.Name,
                                           StringComparison.InvariantCultureIgnoreCase))
                    {
                        var name =
                            ZlpPathHelper.GetRelativePath(
                                project == null
                                                                        ? string.Empty
                                                                        : project.ProjectConfigurationFilePath.DirectoryName,
                                filePath.FullName);

                        var ext    = ZlpPathHelper.GetExtension(name);
                        var result = name.Substring(0, name.Length - ext.Length);

                        return(shortenFilePath(result));
                    }
                    else
                    {
                        return
                            (shortenFilePath(
                                 ZlpPathHelper.GetRelativePath(
                                     project == null
                                                                                ? string.Empty
                                                                                : project.ProjectConfigurationFilePath.DirectoryName,
                                     filePath.FullName)));
                    }
                }
                else
                {
                    return(_name);
                }
            }
        }
        private void doUpdateUI(BaseWizardPage selectedPage)
        {
            if (selectedPage == fileGroupSelectionWizardPage)
            {
                invertFileGroupsButton.Enabled =
                    fileGroupsListBox.Items.Count > 0;
                selectNoFileGroupsButton.Enabled =
                    fileGroupsListBox.CheckedItems.Count > 0;
                selectAllFileGroupsButton.Enabled =
                    fileGroupsListBox.Items.Count > 0 &&
                    fileGroupsListBox.CheckedItems.Count <
                    fileGroupsListBox.Items.Count;

                selectedPage.AllowNext =
                    fileGroupsListBox.CheckedItems.Count > 0;
            }
            else if (selectedPage == languagesWizardPage)
            {
                invertLanguagesToExportButton.Enabled =
                    languagesToExportCheckListBox.Items.Count > 0;
                selectNoLanguagesToExportButton.Enabled =
                    languagesToExportCheckListBox.CheckedItems.Count > 0;
                selectAllLanguagesToExportButton.Enabled =
                    languagesToExportCheckListBox.Items.Count > 0 &&
                    languagesToExportCheckListBox.CheckedItems.Count <
                    languagesToExportCheckListBox.Items.Count;

                selectedPage.AllowNext =
                    referenceLanguageGroupBox.SelectedIndex >= 0 &&
                    languagesToExportCheckListBox.CheckedItems.Count > 0;
            }
            else if (selectedPage == optionsWizardPage)
            {
                buttonResetOptions.Enabled = _canResetOptions;

                multipleFilesGroupControl.Visible =
                    exportEachLanguageIntoSeparateExcelFileCheckEdit.Checked ||
                    exportGroupsAsExcelFilesCheckEdit.Checked;

                buttonDecorateSimpleAutomatically.Visible =
                    !(exportEachLanguageIntoSeparateExcelFileCheckEdit.Checked ||
                      exportGroupsAsExcelFilesCheckEdit.Checked);

                selectedPage.AllowNext = true;
            }
            else if (selectedPage == advancedOptionsWizardPage)
            {
                buttonResetOptions.Enabled = _canResetAdvancedOptions;

                // Must at least have one of those two.
                selectedPage.AllowNext =
                    exportNameColumnCheckEdit.Checked ||
                    exportReferenceLanguageColumnCheckEdit.Checked;
            }
            else if (selectedPage == destinationFileWizardPage)
            {
                selectedPage.AllowNext =
                    destinationFileTextEdit.Text.Trim().Length > 0 &&
                    ZlpPathHelper.GetExtension(destinationFileTextEdit.Text.Trim().ToLowerInvariant()) == @".xlsx";
            }
            else if (selectedPage == sendWithZetaUploaderWizardPage)
            {
                zulReceiversTextEdit.Enabled           =
                    labelControl10.Visible             =
                        zulSubjectTextEdit.Visible     =
                            zulBodyTextEdit.Visible    =
                                buttonZulReset.Visible =
                                    sendFilesToEMailReceiversCheckEdit.Checked;

                selectedPage.AllowNext =
                    !sendFilesToEMailReceiversCheckEdit.Checked ||
                    StringHelper.IsValidEMailAddress(zulReceiversTextEdit.Text.Trim());
            }
            else if (selectedPage == progressWizardPage)
            {
            }
            else if (selectedPage == errorOccurredWizardPage)
            {
            }
            else if (selectedPage == successWizardPage)
            {
            }
            else
            {
                throw new Exception();
            }
        }
예제 #16
0
        public void TestGeneral()
        {
            var tempFolder = Environment.ExpandEnvironmentVariables("%temp%");

            Assert.True(ZlpIOHelper.DirectoryExists(tempFolder));

            var tempPath = ZlpPathHelper.Combine(tempFolder, "ZlpTest");

            try
            {
                ZlpIOHelper.CreateDirectory(tempPath);
                Assert.IsTrue(ZlpIOHelper.DirectoryExists(tempPath));

                var filePath = ZlpPathHelper.Combine(tempPath, "text.zlp");
                using (var fileHandle = ZlpIOHelper.CreateFileHandle(
                           filePath,
                           CreationDisposition.CreateAlways,
                           FileAccess.GenericWrite | FileAccess.GenericRead,
                           FileShare.None))
                    using (var textStream = new StreamWriter(new FileStream(fileHandle, System.IO.FileAccess.Write)))
                    {
                        textStream.WriteLine("Zeta Long Paths Extended testing...");
                        textStream.Flush();
                        //textStream.Close();
                        //fileHandle.Close();
                    }

                Assert.IsTrue(ZlpIOHelper.FileExists(filePath));


                var m = ZlpIOHelper.GetFileLength(filePath);
                Assert.IsTrue(m > 0);
                Assert.IsTrue(m == new FileInfo(filePath).Length);


                Assert.IsTrue(ZlpIOHelper.FileExists(@"c:\Windows\notepad.exe"));
                Assert.IsFalse(ZlpIOHelper.FileExists(@"c:\dslfsdjklfhsd\kjsaklfjd.exe"));
                Assert.IsFalse(ZlpIOHelper.FileExists(@"c:\ablage"));

                Assert.IsFalse(ZlpIOHelper.DirectoryExists(@"c:\Windows\notepad.exe"));
                Assert.IsTrue(ZlpIOHelper.DirectoryExists(@"c:\Windows"));
                Assert.IsTrue(ZlpIOHelper.DirectoryExists(@"c:\Windows\"));
                Assert.IsFalse(ZlpIOHelper.DirectoryExists(@"c:\fkjhskfsdhfjkhsdjkfhsdkjfh"));
                Assert.IsFalse(ZlpIOHelper.DirectoryExists(@"c:\fkjhskfsdhfjkhsdjkfhsdkjfh\"));

                // --

                Assert.DoesNotThrow(() => ZlpIOHelper.SetFileLastWriteTime(filePath, new DateTime(1986, 1, 1)));
                Assert.DoesNotThrow(() => ZlpIOHelper.SetFileLastAccessTime(filePath, new DateTime(1987, 1, 1)));
                Assert.DoesNotThrow(() => ZlpIOHelper.SetFileCreationTime(filePath, new DateTime(1988, 1, 1)));

                Assert.DoesNotThrow(() => ZlpIOHelper.SetFileLastWriteTime(tempPath, new DateTime(1986, 1, 1)));
                Assert.DoesNotThrow(() => ZlpIOHelper.SetFileLastAccessTime(tempPath, new DateTime(1987, 1, 1)));
                Assert.DoesNotThrow(() => ZlpIOHelper.SetFileCreationTime(tempPath, new DateTime(1988, 1, 1)));

                var anotherFile = ZlpPathHelper.Combine(tempPath, "test2.zpl");
                ZlpIOHelper.WriteAllText(anotherFile, @"äöü.");
                Assert.IsTrue(ZlpIOHelper.FileExists(anotherFile));

                var time = ZlpIOHelper.GetFileLastWriteTime(filePath);
                Assert.Greater(time, DateTime.MinValue);

                var owner = ZlpIOHelper.GetFileOwner(@"c:\Windows\notepad.exe");
                Assert.IsNotEmpty(owner ?? string.Empty);

                var l = ZlpIOHelper.GetFileLength(anotherFile);
                Assert.IsTrue(l > 0);
            }
            finally
            {
                ZlpIOHelper.DeleteDirectory(tempPath, true);
            }
        }
예제 #17
0
        private static CacheItem doHasDictionariesForCulture(
            CultureInfo culture)
        {
            var fileNames        = getAllCompleteCultureFileNames();
            var cultureName      = culture.Name;
            var cultureNameShort = culture.Name.Substring(0, 2);

            // --
            // First pass: direct match.

            foreach (var fileName in fileNames)
            {
                var normalizedFileName = fileName.Replace(@"_", @"-");

                if (string.Equals(
                        cultureName,
                        normalizedFileName,
                        StringComparison.InvariantCultureIgnoreCase))
                {
                    return
                        (new CacheItem
                    {
                        Available = true,
                        DictionaryFilePath = ZlpPathHelper.Combine(dictionaryBaseFolderPath.FullName, fileName + @".dic"),
                        GrammarFilePath = ZlpPathHelper.Combine(dictionaryBaseFolderPath.FullName, fileName + @".aff")
                    });
                }
            }

            // --
            // Second pass: base match.

            foreach (var fileName in fileNames)
            {
                if (fileName.Length >= 2)
                {
                    var normalizedFileName = fileName.Substring(0, 2);

                    if (string.Equals(
                            cultureNameShort,
                            normalizedFileName,
                            StringComparison.InvariantCultureIgnoreCase))
                    {
                        return
                            (new CacheItem
                        {
                            Available = true,
                            DictionaryFilePath = ZlpPathHelper.Combine(dictionaryBaseFolderPath.FullName, fileName + @".dic"),
                            GrammarFilePath = ZlpPathHelper.Combine(dictionaryBaseFolderPath.FullName, fileName + @".aff")
                        });
                    }
                }
            }

            // --
            // Not found.

            return
                (new CacheItem
            {
                Available = false
            });
        }
예제 #18
0
        private static void Main()
        {
            try
            {
                LogCentral.Current.ConfigureLogging();

                // --
                // Register extension.

                try
                {
                    var info =
                        new FileExtensionRegistration.RegistrationInformation
                    {
                        ApplicationFilePath = typeof(Host).Assembly.Location,
                        Extension           = Project.ProjectFileExtension,
                        ClassName           = @"ZetaResourceEditorDocument",
                        Description         = Resources.SR_Host_Main_ZetaResourceEditorProjectFile
                    };

                    FileExtensionRegistration.Register(info);
                }
                catch (Exception x)
                {
                    // May fail if no permissions, silently eat.
                    LogCentral.Current.LogError(x);
                }

                // --

                var persistentStorage =
                    new PersistentXmlFilePairStorage
                {
                    FilePath =
                        ZlpPathHelper.Combine(
                            CurrentUserStorageBaseFolderPath.FullName,
                            @"zeta-resource-editor-settings.xml")
                };
                persistentStorage.Error += storageError;

                PersistanceHelper.Storage = persistentStorage;

                // --

                // http://community.devexpress.com/forums/t/80133.aspx

                SkinHelper.InitializeAll();

                // --

                AppDomain.CurrentDomain.UnhandledException += currentDomainUnhandledException;
                Application.ThreadException += applicationThreadException;

                test();

                initializeLanguage();

                Application.Run(new MainForm());
            }
            catch (Exception x)
            {
                doHandleException(x);
            }
        }
        private static void doProcess(
            PreparedInformation preparedInformation,
            BackgroundWorker bw,
            int fileGroupsLength,
            ICollection <string> savedFiles)
        {
            var ssc = new SnapshotController(preparedInformation.Project, @"XLS");

            ssc.Initialize();

            // --

            var exportedReferenceLanguageValues = new HashSet <string>();

            var dataSet = new DataSet();

            dataSet.Tables.Clear();

            DataTable dataTable       = null;
            var       currentRowIndex = 0;

            var suggestedWorkSheetNamesToRemove = new List <string>();

            var fileGroupIndex = 0;

            foreach (var fileGroup in preparedInformation.FileGroups)
            {
                if (bw.CancellationPending)
                {
                    throw new OperationCanceledException();
                }

                var isFirstFileGroup = fileGroupIndex == 0;
                var isLastFileGroup  = fileGroupIndex == preparedInformation.FileGroups.Length - 1;

                var worksheetIndex = -1;

                if (preparedInformation.ExportAllGroups)
                {
                    if (dataTable == null)
                    {
                        dataSet.Tables.Add();
                        worksheetIndex      = dataSet.Tables.Count - 1;
                        dataTable           = dataSet.Tables[worksheetIndex];
                        dataTable.TableName = Resources.SR_CommandProcessorSend_Process_ZRE_Export;
                    }
                }
                else
                {
                    dataSet.Tables.Add();
                    worksheetIndex      = dataSet.Tables.Count - 1;
                    dataTable           = dataSet.Tables[worksheetIndex];
                    dataTable.TableName = generateWorksheetName(preparedInformation, fileGroup, preparedInformation.Project);
                }

                var rows = dataTable.Rows;

                var wantNewSheet = !preparedInformation.ExportAllGroups || isFirstFileGroup;

                // --
                // Header.

                const int headerStartRowIndex = 0;
                const int columnStartIndex    = 0;

                if (wantNewSheet)
                {
                    if (preparedInformation.ExportFileGroupColumn)
                    {
                        // Checksum.
                        // 2014-06-25 Krickbaum - Corrected type to double
                        dataTable.Columns.Add(Resources.SR_CommandProcessorSend_Process_Group, typeof(double));
                    }
                    if (preparedInformation.ExportNameColumn)
                    {
                        // String name.
                        dataTable.Columns.Add(Resources.SR_CommandProcessorSend_Process_Name, typeof(string));
                    }
                    if (preparedInformation.ExportReferenceLanguageColumn)
                    {
                        // Reference language.
                        dataTable.Columns.Add(preparedInformation.ReferenceLanguageCode, typeof(string));
                    }

                    // Destination languages.
                    // ReSharper disable ForCanBeConvertedToForeach
                    for (var runningColIndex = 0;
                         // ReSharper restore ForCanBeConvertedToForeach
                         runningColIndex < preparedInformation.DestinationLanguageCodes.Length;
                         ++runningColIndex)
                    {
                        var destinationLanguageCode =
                            preparedInformation.DestinationLanguageCodes[runningColIndex];

                        if (string.Compare(preparedInformation.ReferenceLanguageCode, destinationLanguageCode,
                                           StringComparison.OrdinalIgnoreCase) != 0)
                        {
                            dataTable.Columns.Add(destinationLanguageCode, typeof(string));
                        }
                    }

                    if (preparedInformation.ExportCommentColumn)
                    {
                        // String name.
                        dataTable.Columns.Add(Resources.SR_CommandProcessorSend_Process_Comment, typeof(string));
                    }

                    currentRowIndex = headerStartRowIndex;
                }

                // --
                // Content.

                var dp    = new DataProcessing(fileGroup);
                var table =
                    dp.GetDataTableFromResxFiles(preparedInformation.Project, preparedInformation.ExportCommentColumn);
                table =
                    removeUnusedColumns(
                        preparedInformation,
                        fileGroup.ParentSettings,
                        table);

                var rowIndex = 0;

                foreach (DataRow row in table.Rows)
                {
                    if ((rowIndex + 1) % 20 == 0)
                    {
                        bw.ReportProgress(
                            0,
                            new ExcelProgressInformation
                        {
                            TemporaryProgressMessage =
                                string.Format(
                                    Resources.SR_CommandProcessorSend_Process_ProcessingFileGroupOfRowOf,
                                    fileGroupIndex + 1,
                                    fileGroupsLength,
                                    rowIndex + 1,
                                    table.Rows.Count,
                                    (int)((rowIndex + 1.0) /
                                          table.Rows.Count *
                                          ((fileGroupIndex + 1.0) /
                                           fileGroupsLength) * 100))
                        });

                        if (bw.CancellationPending)
                        {
                            throw new OperationCanceledException();
                        }
                    }

                    if (wantExportRow(
                            ssc,
                            preparedInformation,
                            fileGroup.ParentSettings,
                            row,
                            CommentVisibilityScope.InMemory))
                    {
                        if (!wasAlreadyExported(
                                exportedReferenceLanguageValues,
                                preparedInformation,
                                fileGroup.ParentSettings,
                                row))
                        {
                            var offset = 0;

                            if (preparedInformation.ExportFileGroupColumn)
                            {
                                // Checksum.
                                checkEnsureRowPresent(dataTable, currentRowIndex);
                                rows[currentRowIndex][columnStartIndex] = fileGroup.GetChecksum(preparedInformation.Project);
                                makeCellReadOnly(dataTable.Columns[columnStartIndex]);
                                offset++;
                            }
                            if (preparedInformation.ExportNameColumn)
                            {
                                // String name.
                                checkEnsureRowPresent(dataTable, currentRowIndex);
                                rows[currentRowIndex][columnStartIndex + offset] = row[1]; // Column 0=FileGroup checksum, column 1=Tag name.
                                makeCellReadOnly(dataTable.Columns[columnStartIndex + offset]);

                                offset++;
                            }

                            var effectiveDestinationColumnIndex = 1;
                            // Column 0=FileGroup checksum, column 1=Tag name.
                            for (var sourceColumnIndex = 2;
                                 sourceColumnIndex < table.Columns.Count - (preparedInformation.ExportCommentColumn ? 1 : 0); // Subtract 1, because last column is ALWAYS the comment.
                                 ++sourceColumnIndex)
                            {
                                var languageValue = row[sourceColumnIndex] as string;
                                var languageCode  =
                                    IsFileName(table.Columns[sourceColumnIndex].ColumnName)
                                        ? new LanguageCodeDetection(preparedInformation.Project)
                                    .DetectLanguageCodeFromFileName(
                                        fileGroup.ParentSettings,
                                        table.Columns[sourceColumnIndex].ColumnName)
                                        : table.Columns[sourceColumnIndex].ColumnName;
                                var isReferenceLanguage =
                                    string.Compare(preparedInformation.ReferenceLanguageCode, languageCode,
                                                   StringComparison.OrdinalIgnoreCase) == 0;

                                if (isReferenceLanguage && preparedInformation.ExportReferenceLanguageColumn ||
                                    !isReferenceLanguage)
                                {
                                    checkEnsureRowPresent(dataTable, currentRowIndex);
                                    var columnIndex = columnStartIndex - 1 + effectiveDestinationColumnIndex + offset;
                                    rows[currentRowIndex][columnIndex] = languageValue;

                                    if (isReferenceLanguage)
                                    {
                                        makeCellReadOnly(dataTable.Columns[columnIndex]);

                                        exportedReferenceLanguageValues.Add(
                                            string.IsNullOrEmpty(languageValue)
                                                ? string.Empty
                                                : languageValue);
                                    }

                                    effectiveDestinationColumnIndex++;
                                }
                            }

                            if (preparedInformation.ExportCommentColumn)
                            {
                                // Comment.
                                checkEnsureRowPresent(dataTable, currentRowIndex);
                                rows[currentRowIndex][columnStartIndex - 1 + effectiveDestinationColumnIndex + offset]
                                    = DataProcessing.GetComment(preparedInformation.Project, row);

                                /*offset++;*/
                            }

                            currentRowIndex++;
                        }
                    }

                    // In every loop, check again.
                    suggestedWorkSheetNamesToRemove.Remove(dataTable.TableName);

                    //CHANGED if worksheet empty: remove it)
                    if (currentRowIndex == headerStartRowIndex + 1 &&
                        !preparedInformation.ExportAllGroups)
                    {
                        // http://www.codeproject.com/Messages/3539004/Export-to-Excel-bug.aspx
                        if (worksheetIndex < dataSet.Tables.Count)
                        {
                            suggestedWorkSheetNamesToRemove.Add(dataTable.TableName);
                        }
                    }

                    rowIndex++;
                }

                //dataTable.AutoFitRow(currentRowIndex - 1);

                if (bw.CancellationPending)
                {
                    throw new OperationCanceledException();
                }

                // --

                if (!preparedInformation.ExportAllGroups ||
                    isLastFileGroup)
                {
                    var offset = 0;

                    if (preparedInformation.ExportFileGroupColumn)
                    {
                        // Checksum.
                        //dataTable.AutoFitColumn(
                        //    columnStartIndex,
                        //    headerStartRowIndex,
                        //    currentRowIndex);
                        offset++;
                    }
                    if (preparedInformation.ExportNameColumn)
                    {
                        // String name.
                        //dataTable.AutoFitColumn(
                        //    columnStartIndex + offset,
                        //    headerStartRowIndex,
                        //    currentRowIndex);
                        offset++;
                    }
                    if (preparedInformation.ExportReferenceLanguageColumn)
                    {
                        // Reference language.
                        //dataTable.AutoFitColumn(
                        //    columnStartIndex + offset,
                        //    headerStartRowIndex,
                        //    currentRowIndex);
                        offset++;
                    }

                    // Destination languages.
                    int runningColIndex;
                    for (runningColIndex = 0;
                         runningColIndex < preparedInformation.DestinationLanguageCodes.Length;
                         ++runningColIndex)
                    {
                        //dataTable.AutoFitColumn(
                        //    columnStartIndex + runningColIndex + offset,
                        //    headerStartRowIndex,
                        //    currentRowIndex);
                    }

                    if (preparedInformation.ExportCommentColumn)
                    {
                        // Comment.
                        //dataTable.AutoFitColumn(
                        //    columnStartIndex + offset + runningColIndex,
                        //    headerStartRowIndex,
                        //    currentRowIndex);
                        /*offset++;*/
                    }
                }

                // --

                fileGroupIndex++;
            }

            // --

            // 2011-01-31, Uwe Keim.
            // http://www.codeproject.com/Messages/3559812/Export-error.aspx
            foreach (var name in suggestedWorkSheetNamesToRemove)
            {
                dataSet.Tables.Remove(name);
            }

            // --

            if (dataSet.Tables.Count > 0)
            {
                bw.ReportProgress(
                    0,
                    new ExcelProgressInformation
                {
                    TemporaryProgressMessage =
                        string.Format(
                            Resources.SR_CommandProcessorSend_Process_SavingMicrosoftOfficeExcelDocument)
                });

                savedFiles.Add(preparedInformation.DestinationFilePath);
                CoreExcelExporter.ExportToExcelFile(dataSet, preparedInformation.DestinationFilePath);
            }
            else
            {
                bw.ReportProgress(
                    0,
                    new ExcelProgressInformation
                {
                    TemporaryProgressMessage =
                        Resources.ExcelExportController_doProcess_Skipping_Microsoft_Office_Excel_document_,
                    WarningMessage =
                        string.Format(
                            Resources.ExcelExportController_doProcess_Skipping_Excel_document___0___because_it_contains_no_work_sheets_,
                            ZlpPathHelper.GetFileNameFromFilePath(preparedInformation.DestinationFilePath))
                });
            }

            // --

            // At very last, to not overwrite before comparing.
            if (preparedInformation.Project.EnableExcelExportSnapshots)
            {
                ssc.TakeFullSnapshot(
                    preparedInformation.FileGroups,
                    new[] { preparedInformation.ReferenceLanguageCode },
                    bw);
            }
        }
        public void DownloadAndRunSetup(
            IWin32Window owner,
            UpdateCheckInfo2 info,
            string downloadWebsiteUrl)
        {
            var    error     = false;
            string localPath = null;

            using (new BackgroundWorkerLongProgressGui(
                       delegate
            {
                try
                {
                    var res = _ws.DownloadUpdate2(info);

                    localPath =
                        ZlpPathHelper.Combine(
                            getTempPathIntelligent(),
                            Path.GetFileNameWithoutExtension(res.FileName) +
                            Guid.NewGuid() +
                            Path.GetExtension(res.FileName));

                    File.WriteAllBytes(localPath, res.FileContent);
                }
                catch (Exception x)
                {
                    LogCentral.Current.LogError(
                        @"Error downloading setup of new version.",
                        x);

                    error = true;
                }
            },
                       Resources.SetupDownloadController_DownloadAndRunSetup_Downloading_update__please_wait___,
                       BackgroundWorkerLongProgressGui.CancellationMode.NotCancelable,
                       owner))
            {
            }

            // --

            if (error)
            {
                // Failed, simply redirect.

                var url = downloadWebsiteUrl;

                LogCentral.Current.LogInfo(
                    $@"About to redirect to update-web page at '{url}' for client with version '{info.VersionNumber}'.");

                var si =
                    new ProcessStartInfo
                {
                    FileName = url,
                    //Arguments = @" /S",
                    UseShellExecute = true
                };

                Process.Start(si);
            }
            else
            {
                // Succeeded, run setup, from outside the background thread.

                var si =
                    new ProcessStartInfo
                {
                    FileName        = localPath,
                    Arguments       = @"/S",
                    UseShellExecute = true
                };

                Process.Start(si);

                // TODO: Some day, cleanup the downloaded file.
            }
        }
        public void DoAutomaticallyAddResourceFilesFromVsProject(
            BackgroundWorker backgroundWorker,
            ProjectFolder parentProjectFolder,
            ref int fileGroupCount,
            ref int fileCount,
            ZlpFileInfo vsProjectPath)
        {
            if (backgroundWorker.CancellationPending)
            {
                throw new OperationCanceledException();
            }
            else if (vsProjectPath != null && vsProjectPath.Exists)
            {
                if (@".sln" == vsProjectPath.Extension.ToLowerInvariant())
                {
                    //file is solution, so add all projects from solution
                    doAutomaticallyAddResourceFilesFromVSSolution(
                        backgroundWorker,
                        parentProjectFolder,
                        ref fileGroupCount,
                        ref fileCount,
                        vsProjectPath);
                }
                else
                {
                    //load fom solution
                    var pdoc = new XmlDocument();
                    //using (var fs = vsProjectPath.OpenRead())
                    {
                        pdoc.LoadXml(ZlpIOHelper.ReadAllText(vsProjectPath.FullName));
                    }

                    var nameMgr = new XmlNamespaceManager(pdoc.NameTable);
                    nameMgr.AddNamespace(@"mb", @"http://schemas.microsoft.com/developer/msbuild/2003");

                    //Update 16.16.2016 Christian Abele: Resourcen können unter EmbeddedResource und Content vorkommen! => Content ergänzt
                    var xpaths = new[]
                    {
                        @"/mb:Project/mb:ItemGroup/mb:EmbeddedResource/@Include",
                        @"/mb:Project/mb:ItemGroup/mb:Content/@Include",
                        @"/mb:Project/mb:ItemGroup/mb:EmbeddedResource/@Update",
                        @"/Project/ItemGroup/EmbeddedResource/@Update"
                    };

                    var resNodes = new List <XmlNode>();

                    foreach (var xpath in xpaths)
                    {
                        var r = pdoc.SelectNodes(xpath, nameMgr);
                        if (r != null)
                        {
                            resNodes.AddRange(r.Cast <XmlNode>().ToArray());
                        }
                    }

                    var filePaths = new List <ZlpFileInfo>(); //get all files
                    foreach (var node in resNodes)
                    {
                        var include = node.Value;

                        if (!string.IsNullOrEmpty(include) &&
                            (include.ToLowerInvariant().EndsWith(@".resx") ||
                             include.ToLowerInvariant().EndsWith(@".resw")))
                        {
                            var fullPath = ZlpPathHelper.Combine(vsProjectPath.DirectoryName, include);
                            filePaths.Add(new ZlpFileInfo(fullPath));
                        }
                    }

                    //add all files from list
                    DoAutomaticallyAddResourceFilesFromList(
                        backgroundWorker,
                        parentProjectFolder,
                        ref fileGroupCount,
                        ref fileCount,
                        filePaths);
                }
            }
        }
예제 #22
0
        public bool LoadFromXml(Project project, XmlNode parentNode)
        {
            if (parentNode.Attributes != null)
            {
                XmlHelper.ReadAttribute(
                    out _uniqueID,
                    parentNode.Attributes[@"uniqueID"]);
            }

            if (_uniqueID == Guid.Empty)
            {
                _uniqueID = Guid.NewGuid();
            }

            // --

            string filePath = null;

            if (parentNode.Attributes != null)
            {
                XmlHelper.ReadAttribute(
                    out filePath,
                    parentNode.Attributes[@"filePath"]);
            }

            filePath = project.MakeAbsoluteFilePath(filePath);

            if (!string.IsNullOrEmpty(filePath) && ZlpIOHelper.FileExists(filePath))
            {
                File = new ZlpFileInfo(filePath);
                return(true);
            }
            else
            {
                // Try absolute file path if relative one fails.
                filePath = null;
                if (parentNode.Attributes != null)
                {
                    XmlHelper.ReadAttribute(
                        out filePath,
                        parentNode.Attributes[@"absoluteFilePath"]);
                }

                if (!string.IsNullOrEmpty(filePath) && ZlpIOHelper.FileExists(filePath))
                {
                    File = new ZlpFileInfo(filePath);
                    return(true);
                }
                else
                {
                    // Try in same folder as project file, if both above failed.

                    filePath = null;
                    if (parentNode.Attributes != null)
                    {
                        XmlHelper.ReadAttribute(
                            out filePath,
                            parentNode.Attributes[@"filePath"]);
                    }
                    if (string.IsNullOrEmpty(filePath) && parentNode.Attributes != null)
                    {
                        XmlHelper.ReadAttribute(
                            out filePath,
                            parentNode.Attributes[@"absoluteFilePath"]);
                    }

                    if (string.IsNullOrEmpty(filePath))
                    {
                        File = null;
                        return(false);
                    }
                    else
                    {
                        filePath = ZlpPathHelper.GetFileNameFromFilePath(filePath);
                        filePath = project.MakeAbsoluteFilePath(filePath);

                        if (!string.IsNullOrEmpty(filePath) && ZlpIOHelper.FileExists(filePath))
                        {
                            File = new ZlpFileInfo(filePath);
                            return(true);
                        }
                        else
                        {
                            File = null;
                            return(false);
                        }
                    }
                }
            }
        }