private static void cleanRecursive(String targetDirectory, bool logDetailedErrors)
        {
            if (String.IsNullOrWhiteSpace(targetDirectory))
            {
                return;
            }

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

            try
            {
                var currentDir = new System.IO.DirectoryInfo(targetDirectory);
                if (!currentDir.Exists)
                {
                    return;
                }

                cleanTypeScriptOutput(currentDir, logDetailedErrors);
                foreach (var subfolder in currentDir.EnumerateDirectories())
                {
                    cleanRecursive(subfolder.FullName, logDetailedErrors);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error opening directory for cleaning: " + targetDirectory);
                if (logDetailedErrors)
                {
                    Console.WriteLine("Error: " + ex.Message);
                }
            }
        }
Esempio n. 2
0
        private void ScanFolder(string folder, bool recurse, string[] extensions)
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(folder);


            foreach (var fi in di.EnumerateFiles())
            {
                String fileext = (fi.Extension != null && fi.Extension != String.Empty) ? fi.Extension.ToLower() : "";
                if (fileext.Length > 0 && fileext[0] == '.')
                {
                    fileext = fileext.Substring(1);
                }

                if (extensions.Length == 0 || extensions.Contains(fileext))
                {
                    if (!audioFiles.ContainsFile(fi.FullName))
                    {
                        audioFiles.Add(new AudioFile(fi.FullName));
                    }
                }
            }

            if (!recurse)
            {
                return;
            }

            foreach (var fi in di.EnumerateDirectories())
            {
                ScanFolder(fi.FullName, recurse, extensions);
            }
        }
Esempio n. 3
0
        public ReplayServer(MFroReplay replay)
        {
            this.replay = replay;
              this.alive = true;

              try {
            server = new HttpListener();
            server.Prefixes.Add("http://127.0.0.1:" + port + "/observer-mode/rest/consumer/");
            server.Start();
              } catch {
            try { AddAddress("http://127.0.0.1:" + port + "/"); } catch { return; }
            server = new HttpListener();
            server.Prefixes.Add("http://127.0.0.1:" + port + "/observer-mode/rest/consumer/");
            server.Start();
              }
              new Thread(this.Stopper) { IsBackground = true, Name = "Server Stopper" }.Start();
              new Thread(() => {
            Logger.WriteLine("Starting Spectator Server [ID: {0}]... ".Format(replay.GameId));
            try {
              while (alive) { Handle(server.GetContext()); }
            } catch { }
            server.Close();
            Logger.WriteLine("Closing Spectator Server");
              }) { IsBackground = true, Name = "ServerHandler" }.Start();

              var dir = new System.IO.DirectoryInfo(@"C:\Riot Games\League of Legends\RADS\"
            + @"solutions\lol_game_client_sln\releases\");
              var versions = dir.EnumerateDirectories().ToList();
              versions.Sort((a, b) => b.Name.CompareTo(a.Name));

              ProcessStartInfo info = new ProcessStartInfo(versions[0].FullName + @"\deploy\League of Legends.exe",
            String.Join(" ", SpectateArgs).Format(replay.MetaData["encryptionKey"], replay.GameId));
              info.WorkingDirectory = versions[0].FullName + @"\deploy";
              Process.Start(info);
        }
Esempio n. 4
0
        public static Node Generate(System.IO.DirectoryInfo directory, bool recursive)
        {
            Node node = new Node();

            foreach (var subdirectory in directory.EnumerateDirectories())
            {
                Entry dirEntry = new Entry(subdirectory);
                node.Nodes.Add(dirEntry);
                if (recursive)
                {
                    dirEntry.Node = Generate(subdirectory, recursive);
                    dirEntry.UpdateSize();
                }
            }
            foreach (var file in directory.EnumerateFiles())
            {
                Entry fileEntry = new Entry(file, IsZipFile(file));
                node.Nodes.Add(fileEntry);
                if ((fileEntry.Kind == EntryKind.ZipFile) && recursive)
                {
                    fileEntry.Node = ZipFileGenerator.Generate(file);
                    fileEntry.UpdateSize();
                }
            }
            return(node);
        }
Esempio n. 5
0
        /// <summary>
        ///
        /// </summary>
        public void Load()
        {
            if (mIsLoaded)
            {
                return;
            }
            mIsLoaded = true;

            var data = new System.IO.DirectoryInfo(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "Data"));

            if (data.Exists)
            {
                foreach (var vv in data.EnumerateDirectories())
                {
                    mMachines.Add(vv.Name, new MachineDocument()
                    {
                        Name = vv.Name
                    });
                }
            }
            else
            {
                var local = new MachineDocument()
                {
                    Name = "local"
                };
                local.New();
                mMachines.Add("local", local);
            }
        }
Esempio n. 6
0
        // re-scal the experiment folder and update the list of experiments
        private void ScanExperimentFolder(int selectIndex = 0)
        {
            if (!System.IO.Directory.Exists(PathOutputFolder))
            {
                lblStatus.Text = $"Directory does not exist: {PathOutputFolder}";
                return;
            }

            var di          = new System.IO.DirectoryInfo(PathOutputFolder);
            var folderNames = di.EnumerateDirectories()
                              .OrderBy(d => d.CreationTime)
                              .Select(d => d.Name)
                              .ToList();

            folderNames.Reverse();
            for (int i = 0; i < folderNames.Count; i++)
            {
                folderNames[i] = System.IO.Path.GetFileName(folderNames[i]);
            }

            lbFolderNames.Items.Clear();
            lbFolderNames.Items.AddRange(folderNames.ToArray());

            if (selectIndex >= 0 && selectIndex < lbFolderNames.Items.Count)
            {
                lbFolderNames.SelectedIndex = selectIndex;
                lbFolderNames_SelectedIndexChanged(null, null);
            }

            lblStatus.Text = ($"Scanned experiment folder: {PathOutputFolder}");
        }
Esempio n. 7
0
        public static async Task CreateZipFileFromDirectoryAsync(string sourcePath, string destionationFile)
        {
            if (!System.IO.Directory.Exists(sourcePath))
            {
                throw new System.IO.DirectoryNotFoundException(sourcePath);
            }

            Queue <string> folderQueue = new Queue <string>();

            folderQueue.Enqueue(sourcePath);

            using (System.IO.FileStream fs = new System.IO.FileStream(destionationFile, System.IO.FileMode.Create))
                using (System.IO.Compression.ZipArchive zipArchive = new System.IO.Compression.ZipArchive(fs, System.IO.Compression.ZipArchiveMode.Create, false))
                {
                    while (folderQueue.Count != 0)
                    {
                        System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo(folderQueue.Dequeue());

                        foreach (var subDir in folderInfo.EnumerateDirectories("*.*", System.IO.SearchOption.TopDirectoryOnly))
                        {
                            folderQueue.Enqueue(subDir.FullName);
                        }

                        foreach (var file in folderInfo.GetFiles("*.*", System.IO.SearchOption.TopDirectoryOnly))
                        {
                            string entryPath = System.IO.Path.GetRelativePath(sourcePath, file.FullName);
                            var    e         = zipArchive.CreateEntry(entryPath);

                            using (var entry = e.Open())
                                using (System.IO.FileStream fi = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open))
                                    await fi.CopyToAsync(entry);
                        }
                    }
                }
        }
Esempio n. 8
0
        static StackObject *EnumerateDirectories_26(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.SearchOption @searchOption = (System.IO.SearchOption) typeof(System.IO.SearchOption).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String @searchPattern = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.IO.DirectoryInfo instance_of_this_method = (System.IO.DirectoryInfo) typeof(System.IO.DirectoryInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.EnumerateDirectories(@searchPattern, @searchOption);

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Esempio n. 9
0
        public WorldLoaderState(DwarfGame Game, GameStateManager StateManager) :
            base(Game, StateManager)
        {
            this.ProceedButtonText = "Load";
            this.NoItemsText       = "No worlds found.";

            this.InvalidItemText = "This world was saved by an earlier version of DwarfCorp and is not compatible.";
            this.ValidateItem    = (item) =>
            {
                return(NewOverworldFile.CheckCompatibility(item) ? "" : "Incompatible save file.");
            };
            this.GetItemName = (item) =>
            {
                return(NewOverworldFile.GetOverworldName(item));
            };

            this.ItemSource = () =>
            {
                System.IO.DirectoryInfo worldDirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetWorldDirectory());
                var dirs = worldDirectory.EnumerateDirectories().ToList();
                dirs.Sort((a, b) => b.LastWriteTime.CompareTo(a.LastWriteTime));
                return(dirs);
            };

            this.ScreenshotSource = (path) =>
            {
                try
                {
                    return(AssetManager.LoadUnbuiltTextureFromAbsolutePath(path + ProgramData.DirChar + "screenshot.png"));
                }
                catch (Exception exception)
                {
                    Console.Error.WriteLine(exception.ToString());
                    return(null);
                }
            };

            this.OnProceedClicked = (path) =>
            {
                var file = new NewOverworldFile(path);
                Overworld.Map            = file.Data.CreateMap();
                Overworld.Name           = file.Data.Name;
                Overworld.NativeFactions = new List <Faction>();
                foreach (var faction in file.Data.FactionList)
                {
                    Overworld.NativeFactions.Add(new Faction(faction));
                }
                var settings = new WorldGenerationSettings();
                settings.Width  = Overworld.Map.GetLength(1);
                settings.Height = Overworld.Map.GetLength(0);
                settings.Name   = System.IO.Path.GetFileName(path);
                StateManager.PopState();
                settings.Natives = Overworld.NativeFactions;
                var genState = new WorldGeneratorState(Game, Game.StateManager, settings, false);
                StateManager.PushState(genState);
            };
        }
Esempio n. 10
0
        private int CountDirectory(System.IO.DirectoryInfo DirInfo)
        {
            int i = 0;

            foreach (System.IO.DirectoryInfo DI in DirInfo.EnumerateDirectories())
            {
                i++;
            }
            return(i);
        }
Esempio n. 11
0
        public static long DirectorySize(System.IO.DirectoryInfo dInfo, bool includeSubDir)
        {
            long totalSize = dInfo.EnumerateFiles()
                             .Sum(file => file.Length);

            if (includeSubDir)
            {
                totalSize += dInfo.EnumerateDirectories()
                             .Sum(dir => DirectorySize(dir, true));
            }
            return(totalSize);
        }
Esempio n. 12
0
        static void PrintMapper(string sti, int dybde = 0)
        {
            System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(sti);
            int l = d.GetFiles().Length;

            Console.WriteLine(new String('-', (dybde + 1) * 2) + " " + d.Name + $" - {l} filer");

            foreach (var subfolder in d.EnumerateDirectories())
            {
                PrintMapper(subfolder.FullName, dybde: dybde + 1);
            }
        }
Esempio n. 13
0
        private static void RecursiveDirectoryDelete(System.IO.DirectoryInfo baseDir)
        {
            if (!baseDir.Exists)
            {
                return;
            }

            foreach (var dir in baseDir.EnumerateDirectories())
            {
                RecursiveDirectoryDelete(dir);
            }
            baseDir.Delete(true);
        }
Esempio n. 14
0
        public LoadSaveGameState(DwarfGame Game, GameStateManager StateManager) :
            base(Game, StateManager)
        {
            this.ProceedButtonText = "Load";
            this.NoItemsText       = "No saves found.";

            this.ItemSource = () =>
            {
                System.IO.DirectoryInfo savedirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetSaveDirectory());
                return(savedirectory.EnumerateDirectories().Select(d => d.FullName).ToList());
            };

            this.ScreenshotSource = (path) =>
            {
                var screenshots = System.IO.Directory.GetFiles(path, "*.png");
                if (screenshots.Length == 0)
                {
                    return(null);
                }
                else
                {
                    return(TextureManager.LoadInstanceTexture(screenshots[0], false));
                }
            };

            this.OnProceedClicked = (path) =>
            {
                StateManager.ClearState();
                StateManager.PushState(new LoadState(Game, Game.StateManager,
                                                     new WorldGenerationSettings
                {
                    ExistingFile = path,
                    Name         = path
                }));
            };

            this.ValidateItem = (path) =>
            {
                try
                {
                    var saveGame = SaveGame.CreateFromDirectory(path);
                    return(Program.CompatibleVersions.Contains(saveGame.Metadata.Version));
                }
                catch (Exception)
                {
                    return(false);
                }
            };

            this.InvalidItemText = "This save was created with a different version of DwarfCorp and cannot be loaded.";
        }
        private static string GetFolderPath(string IISid)
        {
            string folderpath = "";

            Helper.Log($"Finding IIS Log folder for IIS Site {IISid}");

            System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(Program.IISLogsFolder);

            var Alldirs = DI.EnumerateDirectories().Where(d => d.Name.Contains(IISid)).First();

            folderpath = $"{Alldirs.FullName}\\*.log";

            Helper.Log($"IIS logs found at {folderpath}");

            return(folderpath);
        }
Esempio n. 16
0
        public ActionResult Index(string id)
        {
            string path = GetRepoServerPath();

            ViewBag.SearchTerm = id;



            RepoList rl = new RepoList();

            System.IO.DirectoryInfo dirinf = new System.IO.DirectoryInfo(path);

            foreach (System.IO.DirectoryInfo di in dirinf.EnumerateDirectories())
            {
                GitManager.GitRepository repo = GitManager.GitRepository.CreateInstance(di);
                if (!repo.IsGitRepo)
                {
                    continue;
                }

                int pos = 1;

                if (!string.IsNullOrWhiteSpace(id))
                {
                    pos = System.Globalization.CultureInfo.InvariantCulture
                          .CompareInfo.IndexOf(repo.Name, id, System.Globalization.CompareOptions.IgnoreCase);
                }

                if (pos != -1)
                {
                    rl.Repositories.Add(repo);
                }
            }             // Next di

            rl.Repositories.Sort(
                delegate(GitManager.GitRepository g1, GitManager.GitRepository g2)
            {
                //return g1.Name.CompareTo(g2.Name); // ASC
                // return g1.LastModified.CompareTo(g2.LastModified);// ASC

                return(g2.LastModified.CompareTo(g1.LastModified));    // DESC
            }
                );

            return(View(rl));
        } // End Action Index
Esempio n. 17
0
        public static void Update(System.IO.DirectoryInfo directory, Node node)
        {
            IDictionary <string, Entry> entries = new Dictionary <string, Entry>(node.Nodes.Count);

            foreach (var entry in node.Nodes)
            {
                entries.Add(entry.Name, entry);
            }
            foreach (var subdirectory in directory.EnumerateDirectories())
            {
                if (entries.ContainsKey(subdirectory.Name))
                {
                    entries.Remove(subdirectory.Name);
                }

                else
                {
                    Entry dirEntry = new Entry(subdirectory);
                    node.Nodes.Add(dirEntry);
                }
            }
            foreach (var file in directory.EnumerateFiles())
            {
                if (entries.ContainsKey(file.Name))
                {
                    Entry fileEntry = entries[file.Name];
                    entries.Remove(file.Name);
                    if (fileEntry.LastWriteTime < file.LastWriteTime)
                    {
                        node.Nodes.Remove(fileEntry);
                        node.Nodes.Add(new Entry(file, IsZipFile(file)));
                    }
                }

                else
                {
                    node.Nodes.Add(new Entry(file, IsZipFile(file)));
                }
            }
            foreach (var entryPair in entries)
            {
                node.Nodes.Remove(entryPair.Value);
            }
        }
Esempio n. 18
0
 public void LoadWorlds()
 {
     ExitThreads = false;
     try
     {
         System.IO.DirectoryInfo savedirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetGameDirectory() + ProgramData.DirChar + SaveDirectory);
         foreach (System.IO.DirectoryInfo file in savedirectory.EnumerateDirectories())
         {
             GameLoadDescriptor descriptor = new GameLoadDescriptor
             {
                 FileName = file.FullName
             };
             Games.Add(descriptor);
         }
     }
     catch (System.IO.IOException exception)
     {
         Console.Error.WriteLine(exception.Message);
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Returns a list of theme folders from the file system for selection
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        public static IEnumerable <SelectListItem> ThemeFolderList(this HtmlHelper htmlHelper)
        {
            HttpServerUtilityBase server = htmlHelper.ViewContext.HttpContext.Server;

            string virtualPath = "~/Content/Server/Themes/";

            if (!System.IO.Directory.Exists(server.MapPath(virtualPath)))
            {
                throw new ApplicationException("Themes folder does not exist in file system at '" + virtualPath + "'");
            }
            System.IO.DirectoryInfo themesFolder = new System.IO.DirectoryInfo(server.MapPath(virtualPath));
            IEnumerable <System.IO.DirectoryInfo> themeFolders = themesFolder.EnumerateDirectories("*", System.IO.SearchOption.TopDirectoryOnly);

            string selectedName = htmlHelper.ViewData.Model as string;

            return(themeFolders.Select(t => new SelectListItem
            {
                Value = t.Name,
                Text = t.Name + " [" + (System.IO.File.Exists(t.FullName + "\\bootstrap.min.css") ? "bootstrap.min.css OK" : "WARNING: no bootstrap.min.css") + "]",
                Selected = t.Name == selectedName
            }));
        }
Esempio n. 20
0
        private void AddFolder(PackageHeirarchyItem parent, string filePath)
        {
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(filePath);
            if (parent != null && !Contains(parent, dir.Name))
            {
                var newItem = new PackageHeirarchyItem(filePath);
                newItem.Name   = dir.Name;
                newItem.Parent = parent;

                parent.Children.Add(newItem);

                foreach (System.IO.FileInfo file in dir.EnumerateFiles())
                {
                    AddFile(newItem, file.FullName);
                }

                foreach (System.IO.DirectoryInfo subDir in dir.EnumerateDirectories())
                {
                    AddFolder(newItem, subDir.FullName);
                }
            }
        }
Esempio n. 21
0
        public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
        {
            var layoutDirectory = new System.IO.DirectoryInfo(HostingEnvironment.MapPath("~/Views/Shared/Layouts"));

            if(!layoutDirectory.Exists)
            {
                yield return new SelectItem() { Text = "No layouts available.", Value = "" };

                yield break;
            }

            var layouts = layoutDirectory.EnumerateDirectories("*", System.IO.SearchOption.TopDirectoryOnly);
            var siteroot = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

            foreach(var s in layouts)
            {
                yield return new SelectItem()
                {
                    Text = s.Name,
                    Value = s.FullName.Replace(siteroot, string.Empty).Replace("\\", "/").Insert(0,"~/")
                };
            }
        }
Esempio n. 22
0
        private PackageFileSourceInfo AddFolder(PackageHeirarchyItem parent, string filePath)
        {
            PackageHeirarchyItem newItem = null;

            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(filePath);
            if (parent != null && !Contains(parent, dir.Name))
            {
                newItem        = new PackageHeirarchyItem(filePath);
                newItem.Name   = dir.Name;
                newItem.Parent = parent;

                parent.Children.Add(newItem);

                // EnumerateFiles is not working on mono for some reason, therefore use GetFiles instead,
                IEnumerable <System.IO.FileInfo> files;
                if (TraceLabSDK.RuntimeInfo.IsRunInMono)
                {
                    files = dir.GetFiles();
                }
                else
                {
                    files = dir.EnumerateFiles();
                }

                foreach (System.IO.FileInfo file in files)
                {
                    AddFile(newItem, file.FullName);
                }

                foreach (System.IO.DirectoryInfo subDir in dir.EnumerateDirectories())
                {
                    AddFolder(newItem, subDir.FullName);
                }
            }

            return(newItem);
        }
Esempio n. 23
0
 private void GatherFSInfo(Context context)
 {
     if (!context.Request.Arguments.ContainsKey("directory"))
     {
         context.Response.Content["info.fs"] = System.IO.DriveInfo.GetDrives().Where(x => x.IsReady).Select(x => x.RootDirectory.FullName).ToArray();
     }
     else
     {
         try
         {
             var dir = new System.IO.DirectoryInfo(context.Request.Arguments["directory"]);
             context.Response.Content["info.fs"] = new DirectoryInfo()
             {
                 Path        = dir.FullName,
                 Directories = dir.EnumerateDirectories().Select(x => x.Name).ToArray(),
                 Files       = dir.EnumerateFiles().Select(x => x.Name).ToArray()
             };
         }
         catch
         {
             context.Response.Content["info.fs"] = null;
         }
     }
 }
Esempio n. 24
0
 public void LoadWorlds()
 {
     ExitThreads = false;
     try
     {
         System.IO.DirectoryInfo worldDirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetGameDirectory() + ProgramData.DirChar + OverworldDirectory);
         foreach (System.IO.DirectoryInfo file in worldDirectory.EnumerateDirectories())
         {
             WorldLoadDescriptor descriptor = new WorldLoadDescriptor
             {
                 DirectoryName  = file.FullName,
                 WorldName      = file.FullName.Split(ProgramData.DirChar).Last(),
                 ScreenshotName = file.FullName + ProgramData.DirChar + "screenshot.png",
                 FileName       = file.FullName + ProgramData.DirChar + "world." + OverworldFile.CompressedExtension,
             };
             Worlds.Add(descriptor);
         }
     }
     catch (System.IO.IOException exception)
     {
         Console.Error.WriteLine(exception.Message);
         Dialog.Popup(GUI, "Error.", "Error loading worlds:\n" + exception.Message, Dialog.ButtonType.OK);
     }
 }
Esempio n. 25
0
        private PackageFileSourceInfo AddFolder(PackageHeirarchyItem parent, string filePath)
        {
            PackageHeirarchyItem newItem = null;

            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(filePath);
            if (parent != null && !Contains(parent, dir.Name))
            {
                newItem = new PackageHeirarchyItem(filePath);
                newItem.Name = dir.Name;
                newItem.Parent = parent;

                parent.Children.Add(newItem);

                // EnumerateFiles is not working on mono for some reason, therefore use GetFiles instead,
                IEnumerable<System.IO.FileInfo> files;
                if(TraceLabSDK.RuntimeInfo.IsRunInMono) 
                {
                    files = dir.GetFiles();
                } 
                else 
                {
                    files = dir.EnumerateFiles();
                }

                foreach (System.IO.FileInfo file in files)
                {
                    AddFile(newItem, file.FullName);
                }

                foreach (System.IO.DirectoryInfo subDir in dir.EnumerateDirectories())
                {
                    AddFolder(newItem, subDir.FullName);
                }
            }

            return newItem;
        }
Esempio n. 26
0
        public LoadSaveGameState(DwarfGame Game, GameStateManager StateManager) :
            base(Game, StateManager)
        {
            this.ProceedButtonText = "Load";
            this.NoItemsText       = "No saves found.";

            this.ItemSource = () =>
            {
                System.IO.DirectoryInfo savedirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetSaveDirectory());
                var dirs = savedirectory.EnumerateDirectories().ToList();
                dirs.Sort((a, b) => b.LastWriteTime.CompareTo(a.LastWriteTime));
                return(dirs.ToList());
            };

            this.ScreenshotSource = (path) =>
            {
                var screenshots = System.IO.Directory.GetFiles(path, "*.png");
                if (screenshots.Length == 0)
                {
                    return(null);
                }
                else
                {
                    return(AssetManager.LoadUnbuiltTextureFromAbsolutePath(screenshots[0]));
                }
            };

            this.OnProceedClicked = (path) =>
            {
                StateManager.ClearState();
                StateManager.PushState(new LoadState(Game, Game.StateManager,
                                                     new WorldGenerationSettings
                {
                    ExistingFile = path,
                    Name         = path
                }));
            };

            this.ValidateItem = (path) =>
            {
                try
                {
                    var saveGame = SaveGame.CreateFromDirectory(path);
                    if (!Program.CompatibleVersions.Contains(saveGame.Metadata.Version))
                    {
                        return(String.Format("Incompatible version {0}", saveGame.Metadata.Version));
                    }
                    var overworld = saveGame.Metadata.OverworldFile;
                    if (!System.IO.Directory.Exists(DwarfGame.GetWorldDirectory() + Program.DirChar + overworld))
                    {
                        return(String.Format("Overworld \"{0}\" does not exist.", overworld));
                    }
                    return("");
                }
                catch (Exception e)
                {
                    return(String.Format("Error while loading {0}", e.Message));
                }
            };

            this.GetItemName = (path) =>
            {
                try
                {
                    var saveGame = SaveGame.CreateFromDirectory(path);
                    return(saveGame.Metadata.OverworldFile);
                }
                catch (Exception)
                {
                    return("?");
                }
            };

            this.InvalidItemText = "This save was created with a different version of DwarfCorp and cannot be loaded.";
        }
Esempio n. 27
0
        public async Task Execute()
        {
            _Logger.LogInformation($"Version: {Core.Config.App.Version}");
            _Logger.LogInformation($"Start Html conversion: {_Options.SourcePath} - {_Options.TargetPath}");

            foreach (var teamPath in System.IO.Directory.EnumerateDirectories(_Options.SourcePath))
            {
                var teamDir = new System.IO.DirectoryInfo(teamPath);
                _Logger.LogInformation($"Team: {teamDir.Name}");

                var htmlTeamDocument = new HtmlDocument();

                var htmlTeam = new HtmlTeam(_LoggerHtmlTeam, _Options, teamDir.Name);
                await htmlTeam.Load();

                var teamHead = await htmlTeam.GetHtml(htmlTeamDocument);


                _Logger.LogInformation($"Team: {htmlTeam.Team.Id} - {htmlTeam.Team.DisplayName}");

                foreach (var channelDir in teamDir.EnumerateDirectories())
                {
                    _Logger.LogInformation($"Channel: {channelDir.Name}");

                    var htmlChannel = new HtmlTeamChannel(_LoggerHtmlTeamChannel, _Options, htmlTeam.Team.Id, channelDir.Name);
                    await htmlChannel.Load();

                    var htmlChannelDocument = new HtmlDocument();
                    htmlChannelDocument.Load(_Options.TemplateFile);

                    var channelBodyNode = htmlChannelDocument.DocumentNode.SelectSingleNode(".//body");
                    channelBodyNode.AppendChild(teamHead);

                    var channelHead = await htmlChannel.GetHtml(htmlChannelDocument);

                    channelBodyNode.AppendChild(channelHead);

                    _Logger.LogInformation($"Channel: {htmlChannel.Channel.Id} - {htmlChannel.Channel.DisplayName} - {htmlChannel.Channel.MembershipType}");

                    foreach (var messageDir in channelDir.EnumerateDirectories().OrderBy(d => Convert.ToInt64(d.Name))) //Just a hack! Load all messages and reply and oder by last reply of a thread
                    {
                        _Logger.LogInformation($"Message: {messageDir.Name}");

                        var htmlMessage = new HtmlTeamChannelMessage(_LoggerHtmlTeamChannelMessage, _Options, htmlTeam.Team.Id, htmlChannel.Channel.Id, messageDir.Name);
                        await htmlMessage.Load();

                        _Logger.LogInformation($"Message: {htmlMessage.Message.Id}");

                        var htmlMessageDocument = new HtmlDocument();
                        htmlMessageDocument.Load(_Options.TemplateFile);
                        var messageBodyNode = htmlMessageDocument.DocumentNode.SelectSingleNode(".//body");

                        var thread = await htmlMessage.GetHtml(htmlMessageDocument);

                        messageBodyNode.AppendChild(thread);

                        if (_Options.CreateSingleHtmlForMessage)
                        {
                            htmlMessageDocument.Save(HtmlTeamChannelMessage.GetOutputMessageFile(_Options.TargetPath, htmlTeam.Team.Id, htmlChannel.Channel.Id, htmlMessage.Message.Id));
                        }
                        //add to channel
                        channelBodyNode.AppendChild(thread);
                    }
                    htmlChannelDocument.Save(HtmlTeamChannel.GetOutputChannelFile(_Options.TargetPath, htmlTeam.Team.Id, htmlChannel.Channel.Id));
                }
            }
        }
Esempio n. 28
0
        private static string CheckPath(string path, string name)
        {
            string ret="";
            try
            {
                var di = new System.IO.DirectoryInfo(path);

                di.EnumerateDirectories();
            } catch(Exception e)
            {
                ret += name + " can't enumerate, error "+e.Message+"<br />";
            }
            if (!System.IO.Directory.Exists(path))
                ret += name + " doesn't exist<br />";
            if (!(path.EndsWith("/") || path.EndsWith("\\")))
                ret += name + " should end with / or \\<br />";
            return ret;
        }
Esempio n. 29
0
 public IEnumerable <IDirectoryInfo> EnumerateDirectories()
 {
     return(inner.EnumerateDirectories().Select(Wrap));
 }
Esempio n. 30
0
        /// <summary>
        /// Dupe-safe uses theme.FolderName to prevent dupes
        /// </summary>
        private static List<Theme> CreateSeedThemes(this IGstoreDb storeDb, string virtualPath, Client client)
        {
            string path = string.Empty;
            if (HttpContext.Current == null)
            {
                string assemblyPath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).AbsolutePath;
                string directoryName = System.IO.Path.GetDirectoryName(assemblyPath).Replace("GStore\\GStoreData\\", "GStore\\GStoreWeb\\");
                path = System.IO.Path.Combine(directoryName, "..\\.." + virtualPath.TrimStart('~').Replace('/', '\\')).Replace("%20", " ");
                if (!System.IO.Directory.Exists(path))
                {
                    throw new ApplicationException("Themes folder could not be found in file system at path: " + path + ". Please run the web site first to populate the database.");
                }
            }
            else
            {
                path = HttpContext.Current.Server.MapPath(virtualPath);
            }

            if (!System.IO.Directory.Exists(path))
            {
                throw new ApplicationException("Themes folder could not be found in file system web server at path: " + path + ".");
            }
            System.IO.DirectoryInfo themesFolder = new System.IO.DirectoryInfo(path);
            IEnumerable<System.IO.DirectoryInfo> themeFolders = themesFolder.EnumerateDirectories();
            int counter = 0;
            List<Theme> newThemes = new List<Theme>();
            foreach (System.IO.DirectoryInfo themeFolder in themeFolders)
            {
                if (!client.Themes.Any(t => t.FolderName.ToLower() == themeFolder.Name.ToLower()))
                {
                    counter++;
                    Theme theme = storeDb.Themes.Create();
                    theme.Name = themeFolder.Name;
                    theme.Order = 2000 + counter;
                    theme.FolderName = themeFolder.Name;
                    theme.Description = themeFolder.Name + " theme";
                    theme.IsPending = false;
                    theme.StartDateTimeUtc = DateTime.UtcNow.AddMinutes(-1);
                    theme.EndDateTimeUtc = DateTime.UtcNow.AddYears(100);
                    theme.Client = client;
                    theme.ClientId = client.ClientId;

                    storeDb.Themes.Add(theme);
                    newThemes.Add(theme);
                }
            }
            storeDb.SaveChangesEx(true, false, false, false);

            return newThemes;
        }
Esempio n. 31
0
        /// <summary>
        /// Returns a list of theme folders from the file system for selection
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        public static IEnumerable<SelectListItem> ThemeFolderList(this HtmlHelper htmlHelper)
        {
            HttpServerUtilityBase server = htmlHelper.ViewContext.HttpContext.Server;

            string virtualPath = "~/Content/Server/Themes/";
            if (!System.IO.Directory.Exists(server.MapPath(virtualPath)))
            {
                throw new ApplicationException("Themes folder does not exist in file system at '" + virtualPath + "'");
            }
            System.IO.DirectoryInfo themesFolder = new System.IO.DirectoryInfo(server.MapPath(virtualPath));
            IEnumerable<System.IO.DirectoryInfo> themeFolders = themesFolder.EnumerateDirectories("*", System.IO.SearchOption.TopDirectoryOnly);

            string selectedName = htmlHelper.ViewData.Model as string;
            return themeFolders.Select(t => new SelectListItem
            {
                Value = t.Name,
                Text = t.Name + " [" + (System.IO.File.Exists(t.FullName + "\\bootstrap.min.css") ? "bootstrap.min.css OK" : "WARNING: no bootstrap.min.css") + "]",
                Selected = t.Name == selectedName
            });
        }
        /// <summary>
        /// Recursively calls the folder creation method for the folder
        /// </summary>
        /// <param name="parentFolder">Set the Folder equal to the absolute path of the SharePoint destination</param>
        /// <param name="directoryPath">The directory path which includes the fullFolderUrl</param>
        /// <param name="fullFolderUrl"></param>
        /// <returns></returns>
        private bool PopulateSharePointFolderWithFiles(Folder parentFolder, string directoryPath, string fullFolderUrl)
        {
            var subStatus = false;

            try
            {
                //Set the FolderRelativePath by removing the path of the folder supplied by the operator from the fullname of the folder
                var folderInfo         = new System.IO.DirectoryInfo(fullFolderUrl);
                var folderRelativePath = folderInfo.FullName.Substring(directoryPath.Length); // should filter out the parent folder
                if (folderRelativePath.StartsWith(@"\"))
                {
                    folderRelativePath = folderRelativePath.Substring(1);
                }

                string trimmedFolder = folderRelativePath.Trim().Replace("_", " "); // clean the folder name for SharePoint purposes

                // setup processing of folder in the parent folder
                var currentFolder = parentFolder;
                this.ClientContext.Load(parentFolder, pf => pf.Name, pf => pf.Folders, pf => pf.Files);
                this.ClientContext.ExecuteQuery();

                if (!parentFolder.FolderExists(trimmedFolder))
                {
                    currentFolder = parentFolder.EnsureFolder(trimmedFolder);
                    //this.ClientContext.Load(curFolder);
                    this.ClientContext.ExecuteQuery();
                    LogVerbose(".......... successfully created folder {0}....", folderRelativePath);
                }
                else
                {
                    currentFolder = parentFolder.Folders.FirstOrDefault(f => f.Name == trimmedFolder);
                    LogVerbose(".......... reading folder {0}....", folderRelativePath);
                }

                // Powershell parameter switch
                if (this.UploadFiles)
                {
                    UploadFileToSharePointFolder(currentFolder, folderInfo.FullName);
                }


                // retrieve any subdirectories for the child folder
                var firstLevelFolders = folderInfo.EnumerateDirectories().ToList();
                if (firstLevelFolders.Count() > 0)
                {
                    LogVerbose("Creating folders for {0}.....discovering folders {1}", folderRelativePath, firstLevelFolders.Count());

                    foreach (var subFolderUrl in firstLevelFolders)
                    {
                        subStatus = PopulateSharePointFolderWithFiles(currentFolder, fullFolderUrl, subFolderUrl.FullName);
                    }

                    LogVerbose("Leaving folder {0}.....", folderRelativePath);
                }
                return(true);
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed to provision SPFolders in SPFolder:{0}", fullFolderUrl);
            }
            return(false);
        }
Esempio n. 33
0
 public IEnumerable <System.IO.DirectoryInfo> EnumerateDirectories(System.IO.DirectoryInfo dir)
 {
     return(dir.EnumerateDirectories());
 }