Ejemplo n.º 1
0
        internal void AddEntityFromFolders()
        {
            if (RestrictManualAdd() == false)
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                dialog.SelectedPath = Properties.Settings.Default.LastSelectedFolder;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Properties.Settings.Default.LastSelectedFolder = dialog.SelectedPath;
                    Properties.Settings.Default.Save();
                    List <string> Dirs = Directory.GetDirectories(dialog.SelectedPath, "*", SearchOption.AllDirectories).ToList();
                    Dirs.Add(dialog.SelectedPath);

                    foreach (string s in Dirs)
                    {
                        Node nodetoadd = new Node(ActiveFolder, "Node" + GlobalClass.GetRandomString(), OpenedNode.Name, new DirectoryInfo(s).Name);
                        AddTask(new TaskInfo(OpenedNode, nodetoadd, ActiveFolder));
                        List <FileInfo> files = new DirectoryInfo(s).GetFiles("*.jpg").ToList();
                        files.AddRange(new DirectoryInfo(s).GetFiles("*.png"));
                        foreach (FileInfo f in files)
                        {
                            AddTask(new TaskInfo(nodetoadd, f.FullName, ActiveFolder));
                        }
                    }
                }

                tasks.Execute();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Loads the assemblies.
        /// </summary>
        /// <returns>The list of assemblies that the system has loaded</returns>
        private static ConcurrentBag <Assembly> LoadAssemblies()
        {
            List <FileInfo> Files = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).GetFiles("*.dll", SearchOption.TopDirectoryOnly)
                                    .Where(x => !x.Name.Equals("CULGeneratedTypes.dll", StringComparison.InvariantCultureIgnoreCase))
                                    .ToList();

            if (!new DirectoryInfo(".").FullName.Contains(System.Environment.GetFolderPath(Environment.SpecialFolder.SystemX86)) &&
                !new DirectoryInfo(".").FullName.Contains(System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)) &&
                !new DirectoryInfo(".").FullName.Contains(System.Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)) &&
                !new DirectoryInfo(".").FullName.Contains(System.Environment.GetFolderPath(Environment.SpecialFolder.System)))
            {
                Files.AddRange(new DirectoryInfo(".").GetFiles("*.dll", SearchOption.TopDirectoryOnly)
                               .Where(x => !x.Name.Equals("CULGeneratedTypes.dll", StringComparison.InvariantCultureIgnoreCase)));
            }
            Files = Files.Distinct().ToList();
            var LoadedAssemblies = new List <Assembly>(AppDomain.CurrentDomain.GetAssemblies());

            LoadAssemblies(LoadedAssemblies, Files.Select(x => AssemblyName.GetAssemblyName(x.FullName)).ToArray());
            var GeneratedFile = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\CULGeneratedTypes.dll");

            if (GeneratedFile.Exists &&
                !LoadedAssemblies.Any(x => !x.FullName.Contains("vshost32") &&
                                      !x.IsDynamic &&
                                      new System.IO.FileInfo(x.Location).LastWriteTime > GeneratedFile.LastWriteTime))
            {
                LoadAssemblies(LoadedAssemblies, AssemblyName.GetAssemblyName(GeneratedFile.FullName));
            }
            return(new ConcurrentBag <Assembly>(LoadedAssemblies.Distinct(new AssemblyComparer())));
        }
Ejemplo n.º 3
0
        private List <string> GetScripts(string path)
        {
            var scripts = new DirectoryInfo(path).EnumerateFiles(_filter).Select(f => File.ReadAllText(f.FullName)).ToList();

            foreach (var d in new DirectoryInfo(path).EnumerateDirectories())
            {
                scripts.AddRange(GetScripts(d.FullName));
            }

            return(scripts);
        }
        /// <summary>
        ///     Method responsible for configuring module catalog
        /// </summary>
        /// <param name="catalog">module catalog</param>
        public virtual void ConfigureModuleCatalog(IModuleCatalog catalog)
        {
            var modulesPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules");

            var modules = new DirectoryInfo(modulesPath).GetDirectories();
            var dlls    = new DirectoryInfo(modulesPath).GetFiles("*.dll").ToList();

            foreach (var directoryInfo in modules)
            {
                var sub = directoryInfo.GetFiles("*.dll");
                dlls.AddRange(sub);
            }
            LoadModule(catalog, dlls);
        }
Ejemplo n.º 5
0
        public void StartMonitoring(string directory, params string[] fileExtensions)
        {
            AddToMonitoring(fileExtensions);
            _pathToDirectory = directory ?? _pathToDirectory;
            InitWatcher(_pathToDirectory);

            List <FileInfo> fInfos = new DirectoryInfo(directory).GetFiles("*.xml").ToList();

            fInfos.AddRange(new DirectoryInfo(directory).GetFiles("*.csv"));

            foreach (var fInfo in fInfos)
            {
                OnNewFileAdded(this, new FileInfoEventArgs(fInfo.FullName, fInfo.Extension));
            }
        }
Ejemplo n.º 6
0
        public MainWindow()
        {
            InitializeComponent();

            this.Activated      += new EventHandler(CommandTb_GotFocus);
            this.Deactivated    += new EventHandler(CommandTb_LostFocus);
            CommandTb.GotFocus  += new RoutedEventHandler(CommandTb_GotFocus);
            CommandTb.LostFocus += new RoutedEventHandler(CommandTb_LostFocus);

            var settings = new JsonSerializerSettings();



            FSettings = JsonConvert.DeserializeObject <Settings>(System.IO.File.ReadAllText(Properties.Settings.Default.SettingsPath + "settings.json"));

            ValidCommands = new Dictionary <string, Command>();
            foreach (Command cmd in FSettings.Commands)
            {
                ValidCommands.Add(cmd.Name, cmd);
                AutocompleteList.Add(cmd.Name);
            }

            string UserStartMenuPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs";
            string StartMenuPath     = System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"ProgramData\Microsoft\Windows\Start Menu\Programs";

            ProgramList.AddRange(Directory.GetFiles(StartMenuPath).Where(x => x.EndsWith("lnk")).ToList <string>());
            ProgramList.AddRange(Directory.GetFiles(UserStartMenuPath).Where(x => x.EndsWith("lnk")).ToList <string>());

            List <DirectoryInfo> StartMenuDirs = new DirectoryInfo(StartMenuPath).GetDirectories().Where(x => (x.Attributes & FileAttributes.Hidden) == 0).ToList <DirectoryInfo>();

            StartMenuDirs.AddRange(new DirectoryInfo(UserStartMenuPath).GetDirectories().Where(x => (x.Attributes & FileAttributes.Hidden) == 0).ToList <DirectoryInfo>());

            foreach (DirectoryInfo dir in StartMenuDirs)
            {
                ProgramList.AddRange(Directory.GetFiles(dir.FullName).Where(x => (x.Split(' ').Length < 5 && x.EndsWith("lnk"))));    // Short-named program shortcuts to make sure the autocomplete isn't too long
            }



            foreach (string prog in ProgramList)
            {
                ProgramPaths[System.IO.Path.GetFileNameWithoutExtension(prog).ToString().Trim()] = prog; // Add file name (without extension) and file path to dict
                AutocompleteList.Add(System.IO.Path.GetFileNameWithoutExtension(prog).ToString().Trim());
            }
        }
Ejemplo n.º 7
0
        private void buttonLoad2_Click(object sender, EventArgs e)
        {
            //Check if all directories exist
            foreach (DirectoryClassDescription myDir in multipleDirectorySelector1.MyDirectoryDescriptionDictionary)
            {
                if (!Directory.Exists(myDir.MyDirectoryFullName))
                {
                    MessageBox.Show("I cant find directory: " + myDir.MyDirectoryFullName);
                    return;
                }

                //and make sure we have at least one Sepro file in each directory
                List <FileInfo> fileInfo = new DirectoryInfo(myDir.MyDirectoryFullName).GetFiles("*.sepr", SearchOption.AllDirectories).ToList();
                fileInfo.AddRange(new DirectoryInfo(myDir.MyDirectoryFullName).GetFiles("*.mpex", SearchOption.AllDirectories).ToList());

                if (fileInfo.Count == 0)
                {
                    MessageBox.Show("There are no SEPro or mpex files in the directory : " + myDir.MyDirectoryFullName);
                    return;
                }
            }

            //Test if there are cells with no descriptions
            bool notVerified = true;

            foreach (DirectoryClassDescription myDir in multipleDirectorySelector1.MyDirectoryDescriptionDictionary)
            {
                if (myDir.Description.Equals(""))
                {
                    if (notVerified)
                    {
                        notVerified = false;
                        if (MessageBox.Show("There are still classes with no description.  Do you wish to proceed anyway?", "Class description", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                        {
                            return;
                        }
                    }
                }
            }
            splitContainerSpecCount.Enabled = true;
            parametersXQuant.Enabled        = true;
            groupBoxDominomics.Enabled      = true;
            buttonProcessXIC.Enabled        = true;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Loads all assemblies from folder where target .halcyon file is
        /// </summary>
        public static void LoadAssemblies()
        {
            string ignoredFilesPath = Path.Combine(Folder, "ignore");

            List <string> ignoredFiles = new List <string>();

            if (File.Exists(ignoredFilesPath))
            {
                ignoredFiles.AddRange(File.ReadAllLines(ignoredFilesPath));
            }

            List <FileInfo> fileInfos = new DirectoryInfo(Folder).GetFiles("*.dll").ToList();

            fileInfos.AddRange(new DirectoryInfo(Folder).GetFiles("*.exe"));

            foreach (FileInfo fileInfo in fileInfos)
            {
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
                try
                {
                    Assembly assembly;
                    // The plugin assembly might have been resolved by another plugin assembly already, so checking is required
                    if (!LoadedAssemblies.TryGetValue(fileNameWithoutExtension, out assembly))
                    {
                        try
                        {
                            assembly = Assembly.Load(File.ReadAllBytes(fileInfo.FullName));
                        }
                        catch (BadImageFormatException)
                        {
                            continue;
                        }
                        LoadedAssemblies.Add(fileNameWithoutExtension, assembly);
                    }
                }
                catch (Exception ex)
                {
                    // Broken assemblies better stop the entire referencer init.
                    Logger.Log(string.Format("Failed to load assembly \"{0}\".", fileInfo.Name) + ex);
                }
            }
            RegisterAssemblies();
        }
Ejemplo n.º 9
0
        internal static void LoadPlugins()
        {
            string ignoredPluginsFilePath = Path.Combine(ServerPluginsDirectoryPath, "ignoredplugins.txt");

            List <string> ignoredFiles = new List <string>();

            if (File.Exists(ignoredPluginsFilePath))
            {
                ignoredFiles.AddRange(File.ReadAllLines(ignoredPluginsFilePath));
            }

            List <FileInfo> fileInfos = new DirectoryInfo(ServerPluginsDirectoryPath).GetFiles("*.dll").ToList();

            fileInfos.AddRange(new DirectoryInfo(ServerPluginsDirectoryPath).GetFiles("*.dll-plugin"));

            Dictionary <TerrariaPlugin, Stopwatch> pluginInitWatches = new Dictionary <TerrariaPlugin, Stopwatch>();

            foreach (FileInfo fileInfo in fileInfos)
            {
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
                if (ignoredFiles.Contains(fileNameWithoutExtension))
                {
                    LogWriter.ServerWriteLine(
                        string.Format("{0} was ignored from being loaded.", fileNameWithoutExtension), TraceLevel.Verbose);

                    continue;
                }

                try
                {
                    Assembly assembly;
                    // The plugin assembly might have been resolved by another plugin assembly already, so no use to
                    // load it again, but we do still have to verify it and create plugin instances.
                    if (!loadedAssemblies.TryGetValue(fileNameWithoutExtension, out assembly))
                    {
                        try
                        {
                            assembly = Assembly.Load(File.ReadAllBytes(fileInfo.FullName));
                        }
                        catch (BadImageFormatException)
                        {
                            continue;
                        }
                        loadedAssemblies.Add(fileNameWithoutExtension, assembly);
                    }

                    if (!InvalidateAssembly(assembly, fileInfo.Name))
                    {
                        continue;
                    }

                    foreach (Type type in assembly.GetExportedTypes())
                    {
                        if (!type.IsSubclassOf(typeof(TerrariaPlugin)) || !type.IsPublic || type.IsAbstract)
                        {
                            continue;
                        }
                        object[] customAttributes = type.GetCustomAttributes(typeof(ApiVersionAttribute), false);
                        if (customAttributes.Length == 0)
                        {
                            continue;
                        }

                        if (!IgnoreVersion)
                        {
                            var     apiVersionAttribute = (ApiVersionAttribute)customAttributes[0];
                            Version apiVersion          = apiVersionAttribute.ApiVersion;
                            if (apiVersion.Major != ApiVersion.Major || apiVersion.Minor != ApiVersion.Minor)
                            {
                                LogWriter.ServerWriteLine(
                                    string.Format("Plugin \"{0}\" is designed for a different Server API version ({1}) and was ignored.",
                                                  type.FullName, apiVersion.ToString(2)), TraceLevel.Warning);

                                continue;
                            }
                        }

                        TerrariaPlugin pluginInstance;
                        try
                        {
                            Stopwatch initTimeWatch = new Stopwatch();
                            initTimeWatch.Start();

                            pluginInstance = (TerrariaPlugin)Activator.CreateInstance(type, game);

                            initTimeWatch.Stop();
                            pluginInitWatches.Add(pluginInstance, initTimeWatch);
                        }
                        catch (Exception ex)
                        {
                            // Broken plugins better stop the entire server init.
                            throw new InvalidOperationException(
                                      string.Format("Could not create an instance of plugin class \"{0}\".", type.FullName), ex);
                        }
                        plugins.Add(new PluginContainer(pluginInstance));
                    }
                }
                catch (Exception ex)
                {
                    // Broken assemblies / plugins better stop the entire server init.
                    throw new InvalidOperationException(
                              string.Format("Failed to load assembly \"{0}\".", fileInfo.Name), ex);
                }
            }
            IOrderedEnumerable <PluginContainer> orderedPluginSelector =
                from x in Plugins
                orderby x.Plugin.Order, x.Plugin.Name
            select x;

            foreach (PluginContainer current in orderedPluginSelector)
            {
                Stopwatch initTimeWatch = pluginInitWatches[current.Plugin];
                initTimeWatch.Start();

                try
                {
                    current.Initialize();
                }
                catch (Exception ex)
                {
                    // Broken plugins better stop the entire server init.
                    throw new InvalidOperationException(string.Format(
                                                            "Plugin \"{0}\" has thrown an exception during initialization.", current.Plugin.Name), ex);
                }

                initTimeWatch.Stop();
                LogWriter.ServerWriteLine(string.Format(
                                              "Plugin {0} v{1} (by {2}) initiated.", current.Plugin.Name, current.Plugin.Version, current.Plugin.Author),
                                          TraceLevel.Info);
            }

            if (Profiler.WrappedProfiler != null)
            {
                foreach (var pluginWatchPair in pluginInitWatches)
                {
                    TerrariaPlugin plugin        = pluginWatchPair.Key;
                    Stopwatch      initTimeWatch = pluginWatchPair.Value;

                    Profiler.InputPluginInitTime(plugin, initTimeWatch.Elapsed);
                }
            }
        }
Ejemplo n.º 10
0
        internal static void LoadExtensions()
        {
            List <FileInfo> fileInfos = new DirectoryInfo(ExtensionsDirectoryPath).GetFiles("*.dll").ToList();

            fileInfos.AddRange(new DirectoryInfo(ExtensionsDirectoryPath).GetFiles("*.extension"));
            foreach (FileInfo fileInfo in fileInfos)
            {
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
                try
                {
                    Assembly assembly;
                    if (!loadedAssemblies.TryGetValue(fileNameWithoutExtension, out assembly))
                    {
                        try
                        {
                            assembly = Assembly.Load(File.ReadAllBytes(fileInfo.FullName));
                        }
                        catch (BadImageFormatException)
                        {
                            continue;
                        }
                        loadedAssemblies.Add(fileNameWithoutExtension, assembly);
                    }
                    foreach (Type type in assembly.GetExportedTypes())
                    {
                        if (!type.IsSubclassOf(typeof(HalcyonExtension)) || !type.IsPublic || type.IsAbstract)
                        {
                            continue;
                        }
                        object[] customAttributes = type.GetCustomAttributes(typeof(ApiVersionAttribute), false);
                        if (customAttributes.Length == 0)
                        {
                            continue;
                        }
                        var     apiVersionAttribute = (ApiVersionAttribute)customAttributes[0];
                        Version apiVersion          = apiVersionAttribute.ApiVersion;
                        if (apiVersion.Major != ApiVersion.Major || apiVersion.Minor != ApiVersion.Minor)
                        {
                            Logger.Log(
                                string.Format("Extension \"{0}\" is designed for a different Halcyon API version ({1}) and was ignored.",
                                              type.FullName, apiVersion.ToString(2)));
                            continue;
                        }
                        HalcyonExtension extensionInstance;
                        extensionInstance = (HalcyonExtension)Activator.CreateInstance(type);
                        try
                        {
                            extensionInstance = (HalcyonExtension)Activator.CreateInstance(type);
                        }
                        catch (Exception ex)
                        {
                            Logger.Log(String.Format("Could not create an instance of extension class \"{0}\""), type.FullName + "\n" + ex);
                        }
                        extensions.Add(new ExtensionContainer(extensionInstance));
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(string.Format("Failed to load assembly \"{0}\".", fileInfo.Name) + ex);
                }
            }
            IOrderedEnumerable <ExtensionContainer> orderedExtensionSelector =
                from x in Extensions
                orderby x.Extension.Order, x.Extension.Name
            select x;

            try
            {
                int count = 0;
                foreach (ExtensionContainer current in orderedExtensionSelector)
                {
                    count++;
                }
                foreach (ExtensionContainer current in orderedExtensionSelector)
                {
                    try
                    {
                        current.Initialize();
                    }
                    catch (Exception ex)
                    {
                        Logger.LogNoTrace(ex.Message);
                        Logger.LogNoTrace(ex.Source);
                        Logger.LogNoTrace(ex.HelpLink);
                        Logger.LogNoTrace(ex.StackTrace);
                        // Broken extensions better stop the entire server init.
                        break;
                    }
                    Logger.Log(string.Format(
                                   "Extension {0} v{1} (by {2}) initiated.", current.Extension.Name, current.Extension.Version, current.Extension.Author));
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 11
0
        private void loadDir()
        {
            lock (this)
            {
                tableFile.Clear();
                fileTables.Clear();
                listMods.Items.Clear();
                listWorkShop.Items.Clear();
                listTables.Items.Clear();
                fileFields.Clear();
                fieldFiles.Clear();

                if (currentDir == null || currentDir.Length == 0 || !Directory.Exists(currentDir))
                {
                    return;
                }

                //读取所有pack文件
                List <FileInfo> files = new DirectoryInfo(currentDir).GetFiles("*.pack").ToList();

                List <WorkshopInfo> workShopInfos = new List <WorkshopInfo>();

                //加载创意工坊配置
                if (workShopConfigFile != null && workShopConfigFile.Length > 0 && File.Exists(workShopConfigFile))
                {
                    try
                    {
                        using (StreamReader sr = new StreamReader(workShopConfigFile))
                        {
                            workShopInfos = JsonConvert.DeserializeObject <List <WorkshopInfo> >(sr.ReadToEnd());
                        }
                    }
                    catch
                    {
                    }
                }

                //加载创意工坊pack文件
                if (workshopDir != null && workshopDir.Length > 0)
                {
                    string tmp = workshopDir + @"\workshop\content\779340";
                    if (Directory.Exists(tmp))
                    {
                        foreach (DirectoryInfo dir in new DirectoryInfo(tmp).GetDirectories())
                        {
                            files.AddRange(dir.GetFiles("*.pack").ToList());;
                        }
                    }
                }

                //文件排除列表
                List <string> exp = new List <string>();

                //读取manifest.txt文件筛选系统mod
                string[] mainfests = Directory.GetFiles(currentDir, "manifest.txt");
                if (mainfests.Length > 0)
                {
                    using (StreamReader sr = new StreamReader(mainfests[0]))
                    {
                        string line = null;
                        while ((line = sr.ReadLine()) != null)
                        {
                            int idx = line.ToLower().IndexOf(".pack");
                            if (idx > 0)
                            {
                                exp.Add(line.Substring(0, idx + 5));
                            }
                        }
                    }
                }

                files = files.Where(p => !exp.Contains(p.Name)).OrderBy(p => p.Name).ToList();
                files.ForEach(file =>
                {
                    WorkshopInfo wk = null;
                    try
                    {
                        wk = workShopInfos.Find(p => pathEquals(p.Packfile, file.FullName));
                    }
                    catch (Exception e)
                    {
                    }

                    if (wk == null || wk.Active || !tsmiIgnoreUnActive.Checked)
                    {
                        List <PackedFile> packageFile = ReadPackageFile(file.FullName);
                        //填充文件-目录数据
                        fileTables.Add(file.FullName, packageFile.Select(pkg => pkg.FullPath).ToList());
                        fileFields[file.FullName] = new List <ModLine>();


                        packageFile.ForEach(p =>
                        {
                            //填充目录-文件数据
                            if (!tableFile.ContainsKey(p.FullPath))
                            {
                                tableFile[p.FullPath] = new List <string>();
                            }

                            List <string> list = tableFile[p.FullPath];
                            list.Add(file.FullName);

                            if (tsmiCheckLine.Checked)
                            {
                                //填充文件-词条数据
                                List <ModLine> lines = ReadPackedField(p, file.FullName);

                                List <ModLine> fields = fileFields[file.FullName];
                                fields.AddRange(lines);

                                //填充词条-文件数据
                                lines.ForEach(line =>
                                {
                                    string key = line.TableName + "." + string.Join(".", line.FieldKeyValue);
                                    if (!fieldFiles.ContainsKey(key))
                                    {
                                        fieldFiles[key] = new List <string>();
                                    }
                                    List <string> fs = fieldFiles[key];
                                    fs.Add(file.FullName);
                                });
                            }
                        });
                    }
                    else
                    {
                        //填充文件-目录数据
                        fileTables.Add(file.FullName, new List <string>());
                        fileFields[file.FullName] = new List <ModLine>();
                    }
                });

                //填充左侧Mod目录
                foreach (FileInfo file in files)
                {
                    ModFile mod = new ModFile();
                    mod.FileName = file.FullName;
                    mod.Name     = Path.GetFileNameWithoutExtension(file.FullName);

                    //判断是否为创意工坊
                    mod.WorkshopInfo = workShopInfos.Find(p => pathEquals(p.Packfile, file.FullName));

                    if (mod.WorkshopInfo == null || mod.WorkshopInfo.Active || !tsmiIgnoreUnActive.Checked)
                    {
                        //判断是否冲突
                        foreach (string table in fileTables[file.FullName])
                        {
                            if (tableFile[table].Count(p => p != file.FullName) > 0)
                            {
                                mod.ConflictTable = true;
                                break;
                            }
                        }
                        if (tsmiCheckLine.Checked)
                        {
                            //如果目录无冲突,则判断词条冲突情况
                            List <ModLine> lines = fileFields[mod.FileName];
                            foreach (ModLine l in lines)
                            {
                                if (fieldFiles[l.TableName + "." + string.Join(".", l.FieldKeyValue)].Count(p => p != file.FullName) > 0)
                                {
                                    mod.ConflictField = true;
                                    break;
                                }
                            }
                        }
                    }


                    if (mod.WorkshopInfo != null)
                    {
                        listWorkShop.Items.Add(mod);
                    }
                    else
                    {
                        listMods.Items.Add(mod);
                    }
                }

                watcher.Path = currentDir;
                watcher.EnableRaisingEvents = true;

                if (workshopDir != null && workshopDir.Length > 0)
                {
                    string tmp = workshopDir + @"\workshop\content\779340";
                    if (Directory.Exists(tmp))
                    {
                        workshopWatcher.Path = tmp;
                        workshopWatcher.EnableRaisingEvents = true;
                    }
                }

                if (Directory.Exists(launchDir))
                {
                    workshopConfigWatcher.Path = launchDir;
                    workshopConfigWatcher.EnableRaisingEvents = true;
                }
            }
        }
Ejemplo n.º 12
0
        public Object GenerarVersion(FormCollection form)
        {
            try
            {
                int idVersion = int.Parse(form["idVersion"]);
                var version   = ProcessMsg.Version.GetVersiones(null).SingleOrDefault(x => x.IdVersion == idVersion);
                if (version == null)
                {
                    return(Json(new { Version = idVersion, CodErr = 2, MsgErr = "Version no existe", Output = "" }));
                }

                string sRuta = ProcessMsg.Utils.GetPathSetting(Server.MapPath("~/Uploads/")) + version.Release;
                if (!sRuta.EndsWith("\\"))
                {
                    sRuta += @"\";
                }
                string sFile      = "WP" + version.Release.Replace(".", "") + string.Format("{0:yyyyMMddhhhhmmss}", DateTime.Now);
                string dirN1      = ProcessMsg.Utils.GetPathSetting(Server.MapPath("~/VersionOficial/")) + "N+1";
                string dirFuentes = Path.Combine(ProcessMsg.Utils.GetPathSetting(Server.MapPath("~/Fuentes")));
                if (!Directory.Exists(dirFuentes))
                {
                    Directory.CreateDirectory(dirFuentes);
                }
                if (ProcessMsg.Version.GenerarInstalador(idVersion, sFile, sRuta, dirN1, dirFuentes) > 0)
                {
                    string Command  = ConfigurationManager.AppSettings["pathGenSetup"];
                    string argument = "\"" + sRuta + sFile + ".iss\"";


                    if (!version.IsVersionInicial)
                    {
                        if (ProcessMsg.Version.GenerarControlCambios(idVersion, dirN1))
                        {
                            //Proceso de copia de N+1 a N

                            string dirN        = ProcessMsg.Utils.GetPathSetting(Server.MapPath("~/VersionOficial/")) + "N";
                            var    componentes = ProcessMsg.Componente.GetComponenteConDirectorio(idVersion);

                            var files = new DirectoryInfo(sRuta).GetFiles().ToList();
                            if (Directory.Exists(Path.Combine(sRuta, "Scripts")))
                            {
                                files.AddRange(new DirectoryInfo(Path.Combine(sRuta, "Scripts")).GetFiles().ToList());
                            }
                            foreach (var x in files)
                            {
                                var comps = componentes.Where(y => y.Name.Equals(x.Name)).ToList();
                                foreach (var comp in comps)
                                {
                                    if (comp.Tipo == '*')
                                    {
                                        var oPath = Path.Combine(dirN1, comp.Directorio, comp.Name);
                                        var dPath = Path.Combine(dirN, comp.Directorio, comp.Name);
                                        System.IO.File.Copy(oPath, dPath, true);
                                        x.CopyTo(oPath, true);
                                    }
                                    else//Copiando scripts
                                    {
                                        var oPath = Path.Combine(dirN1, "Scripts", comp.TipoByNameFmt, comp.MotorSql);
                                        if (!Directory.Exists(oPath))
                                        {
                                            Directory.CreateDirectory(oPath);
                                        }
                                        oPath = Path.Combine(oPath, comp.Directorio);
                                        if (!Directory.Exists(oPath))
                                        {
                                            Directory.CreateDirectory(oPath);
                                        }
                                        //
                                        var dPath = Path.Combine(dirN, "Scripts", comp.TipoByNameFmt, comp.MotorSql);
                                        if (!Directory.Exists(dPath))
                                        {
                                            Directory.CreateDirectory(dPath);
                                        }
                                        dPath = Path.Combine(dPath, comp.Directorio);
                                        if (!Directory.Exists(dPath))
                                        {
                                            Directory.CreateDirectory(dPath);
                                        }
                                        //
                                        oPath = Path.Combine(oPath, x.Name);
                                        if (System.IO.File.Exists(oPath))
                                        {
                                            dPath = Path.Combine(dPath, x.Name);
                                            System.IO.File.Copy(oPath, dPath, true);
                                        }

                                        x.CopyTo(oPath, true);
                                    }
                                }
                            }
                        }
                        else
                        {
                            return(Json(new { Version = idVersion, CodErr = 4, MsgErr = "No pudo generar el control de cambios.", Output = "" }));
                        }
                    }

                    System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(Command, argument);
                    // Indicamos que la salida del proceso se redireccione en un Stream
                    procStartInfo.RedirectStandardOutput = true;
                    procStartInfo.UseShellExecute        = false;
                    //Indica que el proceso no despliegue una pantalla negra (El proceso se ejecuta en background)
                    procStartInfo.CreateNoWindow = false;
                    //Inicializa el proceso
                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.StartInfo = procStartInfo;
                    proc.Start();
                    //Consigue la salida de la Consola(Stream) y devuelve una cadena de texto
                    string result = proc.StandardOutput.ReadToEnd();
                    if (!System.IO.File.Exists(Path.Combine(sRuta, "Output", sFile + ".exe")))
                    {
                        return(Json(new { Version = idVersion, CodErr = 4, MsgErr = "No pudo generar instalador", Output = "" }));
                    }
                    return(Json(new { Version = idVersion, CodErr = 0, MsgErr = result, Output = sFile + ".exe" }));
                }
                return(Json(new { Version = idVersion, CodErr = 1, MsgErr = "No pudo generar archivo script de setup", Output = "" }));
            }
            catch (Exception ex)
            {
                return(Json(new { Version = 0, CodErr = 3, MsgErr = ex.Message, Output = "" }));
            }
        }
Ejemplo n.º 13
0
        public static void Initialize(Main main)
        {
            if (!Directory.Exists("ServerPlugins"))
            {
                Directory.CreateDirectory("ServerPlugins");
            }
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            List <FileInfo> files = new DirectoryInfo("ServerPlugins").GetFiles("*.dll").ToList();

            files.AddRange(new DirectoryInfo("ServerPlugins").GetFiles("*.dll-plugin"));
            for (int i = 0; i < files.Count; i++)
            {
                FileInfo fileInfo = files[i];
                try
                {
                    string   fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
                    Assembly assembly;
                    if (!LoadedAssemblies.TryGetValue(fileNameWithoutExtension, out assembly))
                    {
                        assembly = Assembly.Load(File.ReadAllBytes(fileInfo.FullName));
                        LoadedAssemblies.Add(fileNameWithoutExtension, assembly);
                    }
                    Type[] types = assembly.GetTypes();
                    for (int j = 0; j < types.Length; j++)
                    {
                        Type type = types[j];
                        if (type.BaseType == typeof(TerrariaPlugin))                          // Mono has this as a TODO.
                        {
                            if (Compatible(type))
                            {
                                Plugins.Add(new PluginContainer((TerrariaPlugin)Activator.CreateInstance(type, new object[]
                                {
                                    main
                                })));
                            }
                            else
                            {
                                Console.WriteLine("Outdated plugin: {0} ({1})", fileInfo.Name, type);
                                File.AppendAllText("ErrorLog.txt", string.Format("Outdated plugin: {0} ({1})\n", fileInfo.Name, type));
                            }
                        }
                    }
                }
                catch (Exception innerException)
                {
                    if (innerException is TargetInvocationException)
                    {
                        innerException = (innerException).InnerException;
                    }
                    else if (innerException is ReflectionTypeLoadException)
                    {
                        var exception = (ReflectionTypeLoadException)innerException;
                    }
                    AppendLog(fileInfo.Name, innerException);
                    Console.WriteLine("Plugin {0} failed to load", fileInfo.Name);
                }
            }
            IOrderedEnumerable <PluginContainer> orderedEnumerable =
                from x in Plugins
                orderby x.Plugin.Order, x.Plugin.Name
            select x;

            foreach (PluginContainer current in orderedEnumerable)
            {
                current.Initialize();
                Console.WriteLine("{0} v{1} ({2}) initiated.", current.Plugin.Name, current.Plugin.Version, current.Plugin.Author);
            }
        }
Ejemplo n.º 14
0
        public MainWindow()
        {
            RefreshSettings();
            RefreshStyle();

            this.DataContext = ViewModel;


            InitializeComponent();
            this.Activated      += new EventHandler(CommandTb_GotFocus);
            this.Deactivated    += new EventHandler(CommandTb_LostFocus);
            CommandTb.GotFocus  += new RoutedEventHandler(CommandTb_GotFocus);
            CommandTb.LostFocus += new RoutedEventHandler(CommandTb_LostFocus);


            foreach (string folder in FSettings.AppFolders)
            {
                string[] files;
                try
                {
                    files = Directory.GetFiles(folder);
                } catch
                {
                    CommandTb.Text = "Couldn't load folder: " + folder;
                    CommandError();
                    files = new string[0];
                }

                foreach (string file in files)   // Add all the programs in their folders to the autocomplete & valid commands list.
                {
                    Command toAdd = new Command();
                    toAdd.Name    = System.IO.Path.GetFileNameWithoutExtension(file);
                    toAdd.Actions = new List <Dictionary <String, String> >();
                    toAdd.Actions.Add(new Dictionary <string, string> {
                        { "PROCESS", file }
                    });
                    toAdd.Icon = "Apps";
                    ValidCommands.Add(toAdd.Name, toAdd);
                    AutocompleteList.Add(toAdd.Name);
                }
            }


            foreach (Command cmd in FSettings.Commands)
            {
                ValidCommands.Add(cmd.Name, cmd);
                AutocompleteList.Add(cmd.Name);
            }

            string UserStartMenuPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs"; // Also automatically add all startmenu programs
            string StartMenuPath     = System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"ProgramData\Microsoft\Windows\Start Menu\Programs";

            ProgramList.AddRange(Directory.GetFiles(StartMenuPath).Where(x => x.EndsWith("lnk")).ToList <string>());
            ProgramList.AddRange(Directory.GetFiles(UserStartMenuPath).Where(x => x.EndsWith("lnk")).ToList <string>());

            List <DirectoryInfo> StartMenuDirs = new DirectoryInfo(StartMenuPath).GetDirectories().Where(x => (x.Attributes & FileAttributes.Hidden) == 0).ToList <DirectoryInfo>();

            StartMenuDirs.AddRange(new DirectoryInfo(UserStartMenuPath).GetDirectories().Where(x => (x.Attributes & FileAttributes.Hidden) == 0).ToList <DirectoryInfo>());

            foreach (DirectoryInfo dir in StartMenuDirs)
            {
                ProgramList.AddRange(Directory.GetFiles(dir.FullName).Where(x => (x.Split(' ').Length < 5 && x.EndsWith("lnk"))));    // Short-named program shortcuts to make sure the autocomplete isn't too long
            }



            foreach (string prog in ProgramList)
            {
                ProgramPaths[System.IO.Path.GetFileNameWithoutExtension(prog).ToString().Trim()] = prog; // Add file name (without extension) and file path to dict
                AutocompleteList.Add(System.IO.Path.GetFileNameWithoutExtension(prog).ToString().Trim());
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            var opts = CmdLineOptions.Parse(args);

            var config = BuildConfiguration.Read(
                Path.Combine(opts.ConfigDir, MagicStrings.Files.ConfigYaml));

            Directory.CreateDirectory(opts.PackageOutDir);

            if (!ArtifactPackage.FromFilename(opts.PackageName, out var ap))
            {
                throw new Exception("Unable to parse file name: " + opts.PackageName);
            }

            var pc = config.GetProductConfig(ap.TargetName);

            var companyName    = MagicStrings.Elastic;
            var productSetName = MagicStrings.Beats.Name;
            var displayName    = MagicStrings.Beats.Name + " " + ap.TargetName;
            var exeName        = ap.CanonicalTargetName + MagicStrings.Ext.DotExe;

            // Generate UUID v5 from product properties.
            // This UUID *must* be stable and unique between Beats.
            var upgradeCode = Uuid5.FromString(ap.CanonicalTargetName);

            var project = new Project(displayName)
            {
                InstallerVersion = 500,

                GUID = upgradeCode,

                Name = $"{displayName} {ap.SemVer} ({ap.Architecture})",

                Description = pc.Description,

                OutFileName = Path.Combine(opts.PackageOutDir, opts.PackageName),
                Version     = new Version(ap.Version),

                // We massage LICENSE.txt into .rtf below
                LicenceFile = Path.Combine(
                    opts.PackageOutDir,
                    MagicStrings.Files.PackageLicenseRtf(opts.PackageName)),

                Platform = ap.Is32Bit ? Platform.x86 : Platform.x64,

                InstallScope = InstallScope.perMachine,

                UI = WUI.WixUI_Minimal,

                // TODO: Custom images?
                BannerImage     = Path.Combine(opts.ResDir, MagicStrings.Files.TopBannerBmp),
                BackgroundImage = Path.Combine(opts.ResDir, MagicStrings.Files.LeftBannerBmp),

                MajorUpgrade = new MajorUpgrade
                {
                    AllowDowngrades          = false,
                    AllowSameVersionUpgrades = false,
                    DowngradeErrorMessage    = MagicStrings.Errors.NewerVersionInstalled,
                },
            };

            project.Include(WixExtension.UI);
            project.Include(WixExtension.Util);

            project.ControlPanelInfo = new ProductInfo
            {
                Contact      = companyName,
                Manufacturer = companyName,
                UrlInfoAbout = "https://www.elastic.co",

                Comments = pc.Description + ". " + MagicStrings.Beats.Description,

                ProductIcon = Path.Combine(
                    opts.ResDir,
                    Path.GetFileNameWithoutExtension(exeName) + MagicStrings.Ext.DotIco),

                NoRepair = true,
            };

            // Convert LICENSE.txt to something richedit control can render
            System.IO.File.WriteAllText(
                Path.Combine(
                    opts.PackageOutDir,
                    MagicStrings.Files.PackageLicenseRtf(opts.PackageName)),
                MagicStrings.Content.WrapWithRtf(
                    System.IO.File.ReadAllText(
                        Path.Combine(opts.PackageInDir, MagicStrings.Files.LicenseTxt))));

            var beatConfigPath = "[CommonAppDataFolder]" + Path.Combine(companyName, productSetName, ap.CanonicalTargetName);
            var beatDataPath   = Path.Combine(beatConfigPath, "data");
            var beatLogsPath   = Path.Combine(beatConfigPath, "logs");

            var textInfo           = new CultureInfo("en-US", false).TextInfo;
            var serviceDisplayName = $"{companyName} {textInfo.ToTitleCase(ap.TargetName)} {ap.SemVer}";

            WixSharp.File service = null;
            if (pc.IsWindowsService)
            {
                service = new WixSharp.File(Path.Combine(opts.PackageInDir, exeName));

                // TODO: CNDL1150 : ServiceConfig functionality is documented in the Windows Installer SDK to
                //                  "not [work] as expected." Consider replacing ServiceConfig with the
                //                  WixUtilExtension ServiceConfig element.

                service.ServiceInstaller = new ServiceInstaller
                {
                    Interactive = false,

                    Name        = ap.CanonicalTargetName,
                    DisplayName = serviceDisplayName,
                    Description = pc.Description,

                    DependsOn = new[]
                    {
                        new ServiceDependency(MagicStrings.Services.Tcpip),
                        new ServiceDependency(MagicStrings.Services.Dnscache),
                    },

                    Arguments =
                        " --path.home " + ("[INSTALLDIR]" + Path.Combine(ap.Version, ap.CanonicalTargetName)).Quote() +
                        " --path.config " + beatConfigPath.Quote() +
                        " --path.data " + beatDataPath.Quote() +
                        " --path.logs " + beatLogsPath.Quote() +
                        " -E logging.files.redirect_stderr=true",

                    DelayedAutoStart = false,
                    Start            = SvcStartType.auto,

                    // Don't start on install, config file is likely not ready yet
                    //StartOn = SvcEvent.Install,

                    StopOn   = SvcEvent.InstallUninstall_Wait,
                    RemoveOn = SvcEvent.InstallUninstall_Wait,
                };
            }

            var packageContents = new List <WixEntity>
            {
                new DirFiles(Path.Combine(opts.PackageInDir, MagicStrings.Files.All), path =>
                {
                    var itm = path.ToLower();

                    bool exclude =

                        // configuration will go into mutable location
                        itm.EndsWith(MagicStrings.Ext.DotYml, StringComparison.OrdinalIgnoreCase) ||

                        // we install/remove service ourselves
                        itm.EndsWith(MagicStrings.Ext.DotPs1, StringComparison.OrdinalIgnoreCase) ||

                        // .exe must be excluded for service configuration to work
                        (pc.IsWindowsService && itm.EndsWith(exeName, StringComparison.OrdinalIgnoreCase))
                    ;

                    // this is an "include" filter
                    return(!exclude);
                })
            };

            packageContents.AddRange(
                new DirectoryInfo(opts.PackageInDir)
                .GetDirectories()
                .Select(dir => dir.Name)
                .Except(pc.MutableDirs)
                .Select(dirName =>
                        new Dir(
                            dirName,
                            new Files(Path.Combine(
                                          opts.PackageInDir,
                                          dirName,
                                          MagicStrings.Files.All)))));

            packageContents.Add(pc.IsWindowsService ? service : null);

            // Add a note to the final screen and a checkbox to open the directory of .example.yml file
            var beatConfigExampleFileName = ap.CanonicalTargetName + ".example" + MagicStrings.Ext.DotYml;
            var beatConfigExampleFileId   = beatConfigExampleFileName + "_" + (uint)beatConfigExampleFileName.GetHashCode32();

            project.AddProperty(new Property("WIXUI_EXITDIALOGOPTIONALTEXT",
                                             $"NOTE: Only Administrators can modify configuration files! We put an example configuration file " +
                                             $"in the data directory caled {ap.CanonicalTargetName}.example.yml. Please copy this example file to " +
                                             $"{ap.CanonicalTargetName}.yml and make changes according to your environment. Once {ap.CanonicalTargetName}.yml " +
                                             $"is created, you can configure {ap.CanonicalTargetName} from your favorite shell (in an elevated prompt) " +
                                             $"and then start {serviceDisplayName} Windows service.\r\n"));

            project.AddProperty(new Property("WIXUI_EXITDIALOGOPTIONALCHECKBOX", "1"));
            project.AddProperty(new Property("WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT",
                                             $"Open {ap.CanonicalTargetName} data directory in Windows Explorer"));

            // We'll open the folder for now
            // TODO: select file in explorer window
            project.AddProperty(new Property(
                                    "WixShellExecTarget",
                                    $"[$Component.{beatConfigExampleFileId}]"));

            project.AddWixFragment("Wix/Product",
                                   XElement.Parse(@"
<CustomAction
    Id=""CA_SelectExampleYamlInExplorer""
    BinaryKey = ""WixCA""
    DllEntry = ""WixShellExec""
    Impersonate = ""yes""
/>"),
                                   XElement.Parse(@"
<UI>
    <Publish
        Dialog=""ExitDialog""
        Control=""Finish""
        Event=""DoAction"" 
        Value=""CA_SelectExampleYamlInExplorer"">WIXUI_EXITDIALOGOPTIONALCHECKBOX=1 and NOT Installed
    </Publish>
</UI>"));

            var dataContents = new DirectoryInfo(opts.PackageInDir)
                               .GetFiles(MagicStrings.Files.AllDotYml, SearchOption.TopDirectoryOnly)
                               .Select(fi =>
            {
                var wf = new WixSharp.File(fi.FullName);

                // rename main config file to hide it from MSI engine and keep customizations
                if (string.Compare(
                        fi.Name,
                        ap.CanonicalTargetName + MagicStrings.Ext.DotYml,
                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    wf.Attributes.Add("Name", beatConfigExampleFileName);
                    wf.Id = new Id(beatConfigExampleFileId);
                }

                return(wf);
            })
                               .ToList <WixEntity>();

            dataContents.AddRange(
                pc.MutableDirs
                .Select(dirName =>
            {
                var dirPath = Path.Combine(opts.PackageInDir, dirName);

                return(Directory.Exists(dirPath)
                            ? new Dir(dirName, new Files(Path.Combine(dirPath, MagicStrings.Files.All)))
                            : null);
            })
                .Where(dir => dir != null));

            // Drop CLI shim on disk
            var cliShimScriptPath = Path.Combine(
                opts.PackageOutDir,
                MagicStrings.Files.ProductCliShim(ap.CanonicalTargetName));

            System.IO.File.WriteAllText(cliShimScriptPath, Resources.GenericCliShim);

            var beatsInstallPath =
                $"[ProgramFiles{(ap.Is64Bit ? "64" : string.Empty)}Folder]" +
                Path.Combine(companyName, productSetName);

            project.Dirs = new[]
            {
                // Binaries
                new InstallDir(
                    // Wix# directory parsing needs forward slash
                    beatsInstallPath.Replace("Folder]", "Folder]\\"),
                    new Dir(
                        ap.Version,
                        new Dir(ap.CanonicalTargetName, packageContents.ToArray()),
                        new WixSharp.File(cliShimScriptPath))),

                // Configration and logs
                new Dir("[CommonAppDataFolder]",
                        new Dir(companyName,
                                new Dir(productSetName,
                                        new Dir(ap.CanonicalTargetName, dataContents.ToArray())
                {
                    GenericItems = new []
                    {
                        /*
                         * This will *replace* ACL on the {beatname} directory:
                         *
                         * Directory tree:
                         *  NT AUTHORITY\SYSTEM:(OI)(CI)F
                         *  BUILTIN\Administrators:(OI)(CI)F
                         *  BUILTIN\Users:(CI)R
                         *
                         * Files:
                         *  NT AUTHORITY\SYSTEM:(ID)F
                         *  BUILTIN\Administrators:(ID)F
                         */

                        new MsiLockPermissionEx(
                            "D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;CI;0x1200a9;;;BU)",
                            ap.Is64Bit)
                    }
                })))
            };

            // CLI Shim path
            project.Add(new EnvironmentVariable("PATH", Path.Combine(beatsInstallPath, ap.Version))
            {
                Part = EnvVarPart.last
            });

            // We hard-link Wix Toolset to a known location
            Compiler.WixLocation = Path.Combine(opts.BinDir, "WixToolset", "bin");

#if !DEBUG
            if (opts.KeepTempFiles)
#endif
            {
                Compiler.PreserveTempFiles = true;
            }

            if (opts.Verbose)
            {
                Compiler.CandleOptions += " -v";
                Compiler.LightOptions  += " -v";
            }

            project.ResolveWildCards();

            if (opts.WxsOnly)
            {
                project.BuildWxs();
            }
            else if (opts.CmdOnly)
            {
                Compiler.BuildMsiCmd(project, Path.Combine(opts.SrcDir, opts.PackageName) + ".cmd");
            }
            else
            {
                Compiler.BuildMsi(project);
            }
        }