예제 #1
0
 internal void Open()
 {
      System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(indexPath);
      Directory directory = FSDirectory.Open(di);
      ireader = DirectoryReader.Open(directory, true);
      isearcher = new IndexSearcher(ireader);
 }
예제 #2
0
파일: Rm.cs 프로젝트: vuuvv/zecms
        public ElFinder.Connector.Responses.Response Execute()
        {
            var path = DirectoryUtils.GetFilePathByHash(Current, Configuration.Configuration.RootPath);

            foreach (var name in ToDelete)
            {
                var toDelete = DirectoryUtils.GetFilePathByHash(name, Configuration.Configuration.RootPath);

                try
                {
                    System.IO.File.Delete(toDelete);
                }
                catch
                {
                    var dir = new System.IO.DirectoryInfo(toDelete);
                    dir.DeleteWithFiles();
                }
            }

            var folder = new Utils.Folder(path);

            var response = new Responses.DirectoryResponse();

            response.cwd = folder.Cwd;

            response.cdc = folder.Contents;

            response.tree = folder.Tree;

            return response;
        }
예제 #3
0
        /*
           * Arguments:
           * First : Path to folder where the files must be renamed
           * Second: Search pattern to choose files (ex.: *.hdf5)
           * Third : AllDirectories or TopDirectoryOnly
           * Fourth: _1 or _2
          */
        static void Main(string[] args)
        {
            bool show_help = true;

             if (args.Length == 4)
             {
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(args[0]);
            string new_name;

            foreach (System.IO.FileInfo fileToRename in directory.GetFiles(args[1], (System.IO.SearchOption)Enum.Parse(typeof(System.IO.SearchOption), (string)args[2], true)))
            {
               Console.Write("Cheking file {0}", fileToRename.Name);
               if (System.IO.Path.GetFileNameWithoutExtension(fileToRename.Name).EndsWith(args[3]))
               {
                  new_name = fileToRename.FullName.Replace(args[3], "");
                  System.IO.File.Move(fileToRename.FullName, new_name);
                  Console.WriteLine("[ OK ]");
               }
               else
                  Console.WriteLine("[ SKIPPED ]");
            }
            show_help = false;
             }

             if (show_help)
             {
            Console.WriteLine("Usage: RenameMohidResultsFiles [path] [search_pattern] [recursion] [ends_with]");
            Console.WriteLine("       [path]           : Path to the folder where the files to rename are.");
            Console.WriteLine("       [search_pattern] : Pattern of files to rename. Ex.: *.hdf5");
            Console.WriteLine("       [recursion]      : AllDirectories to include sub-folders or TopDirectoryOnly");
            Console.WriteLine("       [ends_with]      : Ending of the name that must \"disappear\"");
            Console.WriteLine("                             Ex.: _1");
            Console.WriteLine("                             RunOff_1.hdf5 => RunOff.hdf5");
             }
        }
        public static PrefSound[] GetList(bool allowDefault)
        {
            List<PrefSound> list = new List<PrefSound>();
            if (allowDefault) list.Add(Default);
            list.Add(None);

            // read available sounds from C:\WINDOWS\Media
            string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
            string windowsPath = System.IO.Path.GetDirectoryName(systemPath);
            string mediaPath = System.IO.Path.Combine(windowsPath, "Media");
            if (System.IO.Directory.Exists(mediaPath))
            {
                System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(mediaPath);
                System.IO.FileInfo[] files = d.GetFiles("*.wav");
                foreach (System.IO.FileInfo file in files)
                {
                    PrefSound ps = new PrefSound(true, file.Name, file.FullName);
                    list.Add(ps);
                }
            }

            PrefSound[] arr = list.ToArray();
            list.Clear();
            list = null;
            return arr;
        }
예제 #5
0
		/// for an example:XCopy("c:\a\", "d:\b\");
		/// <summary>Copy source script to report folder</summary>
		/// <param name="sourceDir">sourceDir</param>
		/// <param name="targetDir">targetDir</param>
		public static void XCopy(string sourceDir, string targetDir)
		
    	{
		   //If the source directory exists.
		   if (System.IO.Directory.Exists(sourceDir))
		   {
		       //If the source directory does not exist, create it.
		       if (!System.IO.Directory.Exists(targetDir))
		       System.IO.Directory.CreateDirectory(targetDir);
		       //Get data from sourcedir.
		       System.IO.DirectoryInfo sourceInfo = new System.IO.DirectoryInfo(sourceDir);
		       //Copy the files.
		       System.IO.FileInfo[] files = sourceInfo.GetFiles();
		       foreach (System.IO.FileInfo file in files)
		       {
		           System.IO.File.Copy(sourceDir + "\\" + file.Name, targetDir + "\\" + file.Name, true);
		       }
		       //Copy the dir.
		       System.IO.DirectoryInfo[] dirs = sourceInfo.GetDirectories();
		       foreach (System.IO.DirectoryInfo dir in dirs)
		       {
		          string currentSource = dir.FullName;
		          string currentTarget = dir.FullName.Replace(sourceDir, targetDir);
		          System.IO.Directory.CreateDirectory(currentTarget);
		          //recursion
		          XCopy(currentSource, currentTarget);
		        }
		      }
		   }
 public JobContainerViewModel(ImageDownloaderContainer downloader)
 {
     ThumbDir = new System.IO.DirectoryInfo(string.Format("{0}\\{1}", System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()));
     ThumbDir.Create();
     _downloader = downloader;
     _downloader.AddedDownloadingImage += _downloader_DownloadingImageEvent;
 }
예제 #7
0
        public static string GetLargestFilePathFromDir(string startFolder)
        {
            // Take a snapshot of the file system.
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);

            // This method assumes that the application has discovery permissions
            // for all folders under the specified path.
            IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

            //Return the size of the largest file
            long maxSize =
                (from file in fileList
                 let len = GetFileLength(file)
                 select len)
                 .Max();

            Console.WriteLine("The length of the largest file under {0} is {1}", startFolder, maxSize);

            // Return the FileInfo object for the largest file
            // by sorting and selecting from beginning of list
            System.IO.FileInfo longestFile =
                (from file in fileList
                 let len = GetFileLength(file)
                 where len > 0
                 orderby len descending
                 select file)
                .First();

            Console.WriteLine("The largest file under {0} is {1} with a length of {2} bytes",
                                startFolder, longestFile.FullName, longestFile.Length);

            return longestFile.FullName;
        }
예제 #8
0
        internal Stat fstat(string path)
        {
            System.IO.FileSystemInfo fsi;
            if (System.IO.Directory.Exists(path))
                fsi = new System.IO.DirectoryInfo(path);
            else if (System.IO.File.Exists(path))
                fsi = new System.IO.FileInfo(path);
            else
                throw SystemCallError.rb_sys_fail(path, new System.IO.FileNotFoundException("", path), null).raise(null);

            Stat st = new Stat();
            st.fsi = fsi;
            st.st_dev = (int)fsi.FullName.ToCharArray(0,1)[0];  // drive letter as int, what to do for networked files?
            st.st_ino = 0; // no inode on win32
            st.st_mode = 0;
            st.st_nlink = 1; // no symbolic link support on win32
            st.st_uid = 0;  // no uid in win32
            st.st_gid = 0; // no gid in win32
            //st.st_rdev = 0; // no rdev in win32
            st.st_size = (fsi is System.IO.FileInfo) ? ((System.IO.FileInfo)fsi).Length : 0;
            //st.st_blksize = 0; // no blksize in win32
            //st.st_blocks = 0; // no blocks in win32
            st.st_atime = fsi.LastAccessTime;
            st.st_mtime = fsi.LastWriteTime;
            st.st_ctime = fsi.CreationTime;

            return st;
        }
예제 #9
0
        public xInfoElement()
        {
            g_Singleton = this;
            InitializeComponent();

            eCArchiveFile E = new eCArchiveFile(FileManager.GetFile("compiled_infos.bin"));
            E.Position = 14;
            eCDocArchive D = new eCDocArchive(E);

            foreach (bCAccessorPropertyObject o in D)
            {
                InfoWrapper w = new InfoWrapper(o.Class as gCInfo);
                m_pData.Add(w.Name.pString, w);
            }

            System.IO.DirectoryInfo m = new System.IO.DirectoryInfo(FileManager.g_pGamepath + "data\\raw\\infos");
            if (m.Exists)
            {
                foreach (System.IO.FileInfo fi in m.GetFiles("*.xinf"))
                {
                    InfoWrapper w = InfoWrapper.FromXml(System.Xml.Linq.XElement.Load(fi.FullName));
                    m_pData.Add(w.Name.pString, w);
                }
            }

            listView1.ItemsSource = m_pData.Values;
            setElement(m_pData["PANKRATZX2_00647"], 1, 0);
        }
예제 #10
0
        protected void Initialize()
        {
            System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(source);
            System.IO.FileInfo[] filesInfo = directoryInfo.GetFiles();
            var files = filesInfo.OrderBy(f => f.FullName);//sort alphabetically
            //foreach (System.IO.FileInfo info in filesInfo)
            foreach(System.IO.FileInfo info in files)
            {
                //System.Diagnostics.Debug.WriteLine("Reading " + info.Name + "...");

                SvgReader reader = new SvgReader(info.FullName);
                //HACK: At this moment only support one Path in a template file. Ideal case is get a group of graphic object.
                var elements = reader.GetXMLElements("path");
                foreach (XElement element in elements)
                {
                    Path path = new Path();
                    path.Fill = Brushes.Black;
                    XAttribute attribute = element.Attribute(XName.Get("d"));
                    path.Data = (Geometry)new GeometryConverter().ConvertFromString(attribute.Value);//key

                    //string name = info.Name.ToLower().TrimEnd(new char[] { 'g', 'v', 's', '.' });//caused some ended with 's' interpreted wrongly.
                    string name = info.Name.ToLower().Substring(0, info.Name.Length - 4);
                    string label = GetLabel(info.Name);
                    if (label.Length > 0) name = name.Replace(label, string.Empty);

                    PathViewModel item = new PathViewModel(name, path, label);
                    this.items.Add(item);
                    break;
                }
            }//end loops
        }
예제 #11
0
        private System.Collections.Generic.List<string> getFiles(string location, bool recursive)
        {
            System.Collections.Generic.List<string>  sc = new List<string>();

            System.IO.FileInfo fi = new System.IO.FileInfo(location);

            if(fi.Exists)
            {
                sc.Add(fi.FullName);
                return sc;
            }

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(location);

            if(di.Exists)
            {
                foreach(System.IO.FileInfo f in di.GetFiles())
                {
                    foreach(string s in getFiles(f.FullName,recursive))
                        sc.Add(s);
                }

                if(recursive)
                {
                    foreach(System.IO.DirectoryInfo d in di.GetDirectories())
                    {
                        foreach(string s in getFiles(d.FullName,recursive))
                            sc.Add(s);
                    }
                }
            }

            return sc;
        }
예제 #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            string katalognavn = tbxKatalognavn.Text.Trim();

            // Viser brugen af DirectoryInfo til at hente info for et katalog

            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(katalognavn);         // objekt med information for det angive katalognavn
            
            if (dir.Exists)                                                                 // tjek om katalog findes
            {
                textBox2.Text = dir.CreationTime.ToString() + Environment.NewLine;


                System.IO.DirectoryInfo[] subDirs = dir.GetDirectories();                   // Hent underliggende kataloginformationer for det angive katalog 

                foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                {
                    textBox2.Text = textBox2.Text + "Name:<" + dirInfo.Name + "> Extension:<" + dirInfo.Extension +">" + Environment.NewLine;
                }
                

                dataGridView1.DataSource = subDirs;     // vis elementerne i grid formatet for demo af alle properties
            }
            else
                textBox2.Text = "Katalog findes ikke";
        }
예제 #13
0
        private void DirectoryCheck(String userName)
        {
            var receiptImageDir = new System.IO.DirectoryInfo(Server.MapPath("~/IMG/"));

            if (!receiptImageDir.Exists)
            {
                var createReceiptImageDir = new System.IO.DirectoryInfo(Server.MapPath("~"));
                createReceiptImageDir.CreateSubdirectory("IMG/");
            }

            receiptImageDir = new System.IO.DirectoryInfo(Server.MapPath("~/IMG/receiptImage/"));

            if (!receiptImageDir.Exists)
            {
                var createReceiptImageDir = new System.IO.DirectoryInfo(Server.MapPath("~/IMG"));
                createReceiptImageDir.CreateSubdirectory("receiptImage/");
            }

            receiptImageDir = new System.IO.DirectoryInfo(Server.MapPath("~/IMG/receiptImage/"
                + userName + "/"));

            if (!receiptImageDir.Exists)
            {
                var createReceiptImageDir = new System.IO.DirectoryInfo(Server.MapPath("~/IMG/receiptImage/"));
                createReceiptImageDir.CreateSubdirectory(userName + "/");
            }
        }
예제 #14
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            string pathToFile = inputPath.Text; //pega o caminho do arquivo/programa do campo
            string nameApp = inputName.Text; //pega o nome do arquivo/programa do campo
            string[] files = {pathToFile, nameApp}; //seta o caminho e nome do arquivo/programa num array
            string path = @"C:\\Users\\" + System.Environment.UserName + "\\Documents\\CentralAtalhos"; //seta o caminho para o arquivo de configuração

            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(path); //classe de informações de diretório
            //verifica se diretório não existe
            if (!directory.Exists)
            {
                System.IO.Directory.CreateDirectory(path); //cria diretório caso não exista
            }

            //Classe para criar o arquivo de configuração caso não exista e escrita no mesmo
            using (System.IO.StreamWriter file =
            new System.IO.StreamWriter(path + "\\atalhos.txt", true))
            {
                for (int i = 0; i < files.Length; i++)
                {
                    file.WriteLine(files[i]); //escreve o array no arquivo de configuração
                }
            }

            MessageBox.Show("Cadastrado com sucesso!", "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }
예제 #15
0
        private void CleanUpTempFolder()
        {
            try {

                if (!Globals.IsTempCleanUpDone) {

                    Globals.IsTempCleanUpDone = true;
                    string baseReportPath = Server.MapPath("~/PDF");

                    //====================================================
                    // Clean up all old files in PDF folder
                    //====================================================
                    System.IO.DirectoryInfo pdfDir = new System.IO.DirectoryInfo(baseReportPath);
                    DateTime minDate = DateTime.Now.AddMinutes(-10);

                    System.IO.FileInfo[] pdfFiles = pdfDir.GetFiles("*.*");
                    foreach (System.IO.FileInfo fi in pdfFiles) {
                        if (fi.CreationTime < minDate) {
                            System.IO.File.Delete(fi.FullName);
                        }
                    }
                }
            }
            catch {
                // IGNORE ERRORS !
            }
        }
예제 #16
0
        // functions
        static void Main(string[] args)
        {
            if (args.Length < 6 )
            {
                Console.WriteLine("Error --  not enough parameters");
                Console.WriteLine("Usage : DataImporter.exe file[path], ip, port, catalog, id, passwd");
                Console.ReadKey();
                return;
            }
            DbManager.SetConnString(string.Format("Data Source={0},{1};Initial Catalog={2};USER ID={3};PASSWORD={4}", args[1], args[2], args[3], args[4], args[5]));
            // argument가 directory면 파일을 만들고
            string listFileName = "";
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(args[0]);
            if( dirInfo.Exists )
            {
                listFileName = args[0] + "\\data_table.lst";
                System.IO.StreamWriter listWriter = new System.IO.StreamWriter(listFileName);
                foreach ( System.IO.FileInfo fileInfo in dirInfo.GetFiles())
                {
                    if(fileInfo.Extension == ".csv" )
                    {
                        listWriter.WriteLine(fileInfo.FullName);
                    }
                }
                listWriter.Close();
            }
            else
            {
                listFileName = args[0];
            }

            // 시간 측정
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();

            string[] dataFiles = System.IO.File.ReadAllLines(listFileName, Encoding.Default);
            if( dataFiles.Length == 0)
            {
                Console.WriteLine("Error : invalid file or directory.!");
                Console.ReadLine();
                return;
            }

            // 파일이면 해당 파일의 리스트를 읽어서 사용한다.
            System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            FileManager.Init(string.Format("{0}\\{1}.log", System.IO.Directory.GetCurrentDirectory(), currentProcess.ProcessName));

            Parallel.For(0, dataFiles.Length, (i) =>
               {
               FileManager fileManager = new FileManager();
               fileManager.ImportToDb(dataFiles[i]);
               });

            FileManager.Release();

            sw.Stop();
            Console.WriteLine("수행시간 : {0}", sw.ElapsedMilliseconds / 1000.0f);
            Console.ReadLine();
        }
예제 #17
0
        private void button1_Click(object sender, EventArgs e)
        {
         System.IO.DirectoryInfo dropFolder = new System.IO.DirectoryInfo(@"\\cob-hds-1\compression\QC\");

         photographer.snapShot(dropFolder);

        }
예제 #18
0
 /// <summary>
 /// Return a listing of basic details for secret/hidden achievements, based upon XML files saved in a set directory.
 /// </summary>
 public static List<HiddenAchievement> ParseHiddenAchievementsXml(string xmlDirectory = null)
 {
     var hiddenAchievements = new List<HiddenAchievement>();
     if (string.IsNullOrWhiteSpace(xmlDirectory))
     {
         return hiddenAchievements;
     }
     var directory = new System.IO.DirectoryInfo(xmlDirectory);
     foreach (var file in directory.GetFiles("*.xml").Where(f => !f.Name.StartsWith("__")))
     {
         try
         {
             var xml = XDocument.Load(file.FullName);
             XNamespace ns = "http://media.jamesrskemp.com/ns/XblAchievements/201307";
             var gameId = xml.Root.Element(ns + "Game").Attribute("id").Value;
             var achievements = xml.Root.Elements(ns + "Achievement");
             foreach (var achievement in achievements)
             {
                 var hiddenAchievement = new HiddenAchievement();
                 hiddenAchievement.GameId = gameId;
                 hiddenAchievement.Id = achievement.Attribute("id").Value;
                 hiddenAchievement.Title = achievement.Element(ns + "Title").Value;
                 hiddenAchievement.Image = achievement.Element(ns + "Image").Value;
                 hiddenAchievement.Description = achievement.Element(ns + "Description").Value;
                 hiddenAchievements.Add(hiddenAchievement);
             }
         }
         catch (Exception)
         {
             // todo once I determine how things will be logged
         }
     }
     return hiddenAchievements;
 }
예제 #19
0
		public string GetTruncatedPath(string path)
		{
			System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
			if (dir != null)
			{
				string directParent = string.Empty;
				string parentParent = string.Empty;
				string rootDir = string.Empty;
				string ellipsis = "...";
				System.IO.DirectoryInfo p = dir.Parent;
				if ((p != null) && (p.Name != dir.Root.Name))
				{
					directParent = p.Name + @"\";
					System.IO.DirectoryInfo pp = p.Parent;
					if ((pp != null) && (pp.Name != dir.Root.Name))
					{
						parentParent = pp.Name + @"\";
					}
					else
					{
						ellipsis = string.Empty;
					}
				}
				else
				{
					ellipsis = string.Empty;
				}
				return dir.Root.Name + ellipsis + parentParent + directParent + dir.Name;
			}
			return path;
		}
예제 #20
0
        public static List<System.IO.DirectoryInfo> LoadCaptureFolder(string Path)
        {
            if(!System.IO.Directory.Exists(Path)) return null;

            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Path);
            return new List<System.IO.DirectoryInfo>(dir.GetDirectories());
        }
예제 #21
0
        /// <summary>
        /// This logs every file that we have ever gotten BEFORE we start our work on it. It then moves each file in the drop folder
        /// to be accessed by AutoQC
        /// </summary>
        /// <param name="dropFolder"></param>
        /// <returns></returns>
        public static bool snapShot(System.IO.DirectoryInfo dropFolder)
        {
            //get all of the files

            System.IO.FileInfo[] files = dropFolder.GetFiles();

            

            List<System.IO.FileInfo> cleanfileList = utility.checkForSystemFiles(files.ToList<System.IO.FileInfo>());

            List<System.IO.FileInfo> toMove = new List<System.IO.FileInfo>();

            foreach (System.IO.FileInfo file in cleanfileList)
            {
                if (utility.isFileWritable(file))
                {
                    // Use the logger to log this
                    
                    System.IO.DirectoryInfo logsDirectory = new System.IO.DirectoryInfo(@"\\cob-hds-1\compression\QC\QCing\otherFiles\logs\OverseerLogs\");
                    
                    //USED FOR TESTING
                    //System.IO.DirectoryInfo logsDirectory = new System.IO.DirectoryInfo(@"C:\Users\BagpipesJohnson\Desktop\testing\Target");
                    
                    logger.saveToTXT("FilesReceived", logsDirectory, file.Name + '\t' + file.FullName + '\t' + file.CreationTime + '\t' + DateTime.Now + '\t' + file.Length + "\r\n");
                    logger.saveToTabDilimited("FilesReceived", logsDirectory, file.Name + '\t' + file.FullName + '\t' + file.CreationTime + '\t' + DateTime.Now + '\t' + file.Length + "\r\n");

                    // Create the metaData for the AutoQC bot to use
                    toMove.Add(file);
                }
            }
            taskmaster.moveAfterSnapshot(toMove);

            return false;
        }
예제 #22
0
        public static void backupSSF()
        {
            //verifica se existe o diretório, caso não exista será criado
            string dirAnteriores = Library.appDir + "\\ssf\\anteriores\\";
            if (!System.IO.Directory.Exists(dirAnteriores))
            {
                System.IO.Directory.CreateDirectory(dirAnteriores);
            }

            //verifica se existe o diretório, caso não exista será criado
            string dirZipados = Library.appDir + "\\ssf\\zipados\\";
            if (!System.IO.Directory.Exists(dirZipados))
            {
                System.IO.Directory.CreateDirectory(dirZipados);
            }

            //backup ssf
            System.IO.DirectoryInfo dirSSF = new System.IO.DirectoryInfo(appDir + "\\ssf");

            string[] filePaths = System.IO.Directory.GetFiles(dirSSF.ToString(), "*.ssf");

            ZipFile zip =
                new ZipFile(dirZipados + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year +
                    DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".zip");
            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
            zip.AddFiles(filePaths);
            zip.Save();

            //move todos os arquivos
            foreach (string file in filePaths)
                System.IO.File.Move(file, dirAnteriores + System.IO.Path.GetFileName(file));
        }
예제 #23
0
        protected override void GetChildItems(string path, bool recurse)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new Exception("Path can't be empty");
            }

            path = NormalizePath(path);

            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(path);
            if (directory.Exists)
            {
                GetDirectoryContent(directory, recurse);
            }
            else
            {
                System.IO.FileInfo item = new System.IO.FileInfo(path);
                if (item.Exists)
                {
                    if ((item.Attributes & System.IO.FileAttributes.Hidden) == 0)
                    {
                        WriteItemObject(item, path, false);
                    }
                }
                else
                {
                    Exception exception = new System.IO.IOException("Path doesn't exist: " + path);
                    WriteError(new ErrorRecord(exception, "ItemDoesNotExist", ErrorCategory.ObjectNotFound, path));
                }
            }
        }
예제 #24
0
        public List<FileNames> GetFiles()
        {
            List<FileNames> listFiles = new List<FileNames>();
            System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(HostingEnvironment.MapPath("~/App_Data/UploadedFiles"));

            int i = 0;
            foreach (var item in directoryInfo.GetFiles())
            {
                FileNames file = new FileNames();
                file.FileID = i + 1;
                file.FileName = item.Name;
                file.FilePath = directoryInfo.FullName + @"\" + item.Name;
                string mimeType = "application/unknown";
                //string ext = System.IO.Path.GetExtension(item).ToLower();
                Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(item.Extension);
                //if (regKey != null && regKey.GetValue("Content Type") != null)
                mimeType = regKey.GetValue("Content Type").ToString();
                //return mimeType;
                file.FileContentType = mimeType;
                file.FileByte = System.IO.File.ReadAllBytes(file.FilePath);
                listFiles.Add(file);

                i = i + 1;
            }

            return listFiles;
        }
예제 #25
0
        public static List<string> GetSerialPorts()
        {
            List<string> result = new List<string>();
            try {
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("/dev");
                System.IO.FileInfo[] fi = di.GetFiles("ttyUSB*");

                foreach (System.IO.FileInfo f in fi) {
                    result.Add(f.FullName);
                }
            } catch (Exception) {
                //eh
            }

            try {
                String[] ports = SerialPort.GetPortNames();
                foreach (String p in ports) {
                    result.Add(p);
                }
            } catch (Exception) {
                //eh
            }

            return result;
        }
예제 #26
0
        public void CanQueryLuceneIndexCreatedOnDisk()
        {
            CanCreateLuceneIndexOnDisk();

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Path.GetTempPath());
            using (Lucene.Net.Store.Directory directory = Lucene.Net.Store.FSDirectory.Open(di))
            {
                Lucene.Net.Index.IndexReader ir = Lucene.Net.Index.IndexReader.Open(directory, true);
                Lucene.Net.Search.Searcher searcher = new Lucene.Net.Search.IndexSearcher(ir);
                using (Lucene.Net.Analysis.Analyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30))
                {
                    Lucene.Net.QueryParsers.QueryParser parser = new Lucene.Net.QueryParsers.QueryParser(Version.LUCENE_30, "content", analyzer);
                    Lucene.Net.Search.Query query = parser.Parse("lorem");
                    Lucene.Net.Search.TopScoreDocCollector collector = Lucene.Net.Search.TopScoreDocCollector.Create(100, true);
                    searcher.Search(query, collector);
                    Lucene.Net.Search.ScoreDoc[] docs = collector.TopDocs().ScoreDocs;

                    foreach (Lucene.Net.Search.ScoreDoc scoreDoc in docs)
                    {
                        //Get the document that represents the search result.
                        Document document = searcher.Doc(scoreDoc.Doc);

                        var id = document.Get("Id");
                        var content = document.Get("content");
                    }
                }
            }
        }
예제 #27
0
        private void BindData()
        {
            using(DataTable dt = new DataTable("Files"))
            {
                dt.Columns.Add("FileID",typeof(long));
                dt.Columns.Add("FileName",typeof(string));
                dt.Columns.Add("Description",typeof(string));
                DataRow dr = dt.NewRow();
                dr["FileID"] = 0;
                dr["FileName"] = "../spacer.gif"; // use blank.gif for Description Entry
                dr["Description"] = "Select Rank Image";
                dt.Rows.Add(dr);

                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Request.MapPath(String.Format("{0}images/ranks",Data.ForumRoot)));
                System.IO.FileInfo[] files = dir.GetFiles("*.*");
                long nFileID = 1;
                foreach(System.IO.FileInfo file in files)
                {
                    string sExt = file.Extension.ToLower();
                    if(sExt!=".gif" && sExt!=".gif" && sExt!=".jpg")
                        continue;

                    dr = dt.NewRow();
                    dr["FileID"] = nFileID++;
                    dr["FileName"] = file.Name;
                    dr["Description"] = file.Name;
                    dt.Rows.Add(dr);
                }

                RankImage.DataSource = dt;
                RankImage.DataValueField = "FileName";
                RankImage.DataTextField = "Description";
            }
            DataBind();
        }
예제 #28
0
        public static void backup()
        {
            //verificar se existem mais de 10 backups e deletar os mais antigos
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(appDir + "\\backup");

            while (dirInfo.GetFiles().Length > 5)
            {
                System.IO.FileInfo tmp = dirInfo.GetFiles()[0];
                foreach (System.IO.FileInfo file in dirInfo.GetFiles())
                {
                    if (tmp.CreationTime < file.CreationTime)
                    {
                        tmp = file;
                    }
                }
                tmp.Delete();
            }

            ZipFile zip =
                new ZipFile(Library.appDir + "\\backup\\" +
                    DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year +
                    DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second);
            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
            zip.AddFile(Library.appDir + "\\db\\cipdatabase.sdf");
            zip.Save();
        }
예제 #29
0
		private void BindData()
		{
			using ( DataTable dt = new DataTable( "Files" ) )
			{
				dt.Columns.Add( "FileID", typeof( long ) );
				dt.Columns.Add( "FileName", typeof( string ) );
				DataRow dr = dt.NewRow();
				dr ["FileID"] = 0;
				dr ["FileName"] = "Select File (*.pak)";
				dt.Rows.Add( dr );

				System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo( Request.MapPath( String.Format( "{0}images/emoticons", YafForumInfo.ForumFileRoot ) ) );
				System.IO.FileInfo [] files = dir.GetFiles( "*.pak" );
				long nFileID = 1;
				foreach ( System.IO.FileInfo file in files )
				{
					dr = dt.NewRow();
					dr ["FileID"] = nFileID++;
					dr ["FileName"] = file.Name;
					dt.Rows.Add( dr );
				}

				File.DataSource = dt;
				File.DataValueField = "FileID";
				File.DataTextField = "FileName";
			}
			DataBind();
		}
예제 #30
0
		private void BindData()
		{

			using ( DataTable dt = new DataTable( "Files" ) )
			{
				dt.Columns.Add( "FileID", typeof( long ) );
				dt.Columns.Add( "FileName", typeof( string ) );
				dt.Columns.Add( "Description", typeof( string ) );
				DataRow dr = dt.NewRow();
				dr ["FileID"] = 0;
				dr ["FileName"] = "../spacer.gif"; // use blank.gif for Description Entry
				dr ["Description"] = "Select Smiley Image";
				dt.Rows.Add( dr );

				System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo( Request.MapPath( String.Format( "{0}images/emoticons", YafForumInfo.ForumFileRoot ) ) );
				System.IO.FileInfo [] files = dir.GetFiles( "*.*" );
				long nFileID = 1;
				foreach ( System.IO.FileInfo file in files )
				{
					string sExt = file.Extension.ToLower();
					if ( sExt != ".png" && sExt != ".gif" && sExt != ".jpg" )
						continue;

					dr = dt.NewRow();
					dr ["FileID"] = nFileID++;
					dr ["FileName"] = file.Name;
					dr ["Description"] = file.Name;
					dt.Rows.Add( dr );
				}

				Icon.DataSource = dt;
				Icon.DataValueField = "FileName";
				Icon.DataTextField = "Description";
			}
			DataBind();

			if ( Request ["s"] != null )
			{
				using ( DataTable dt = YAF.Classes.Data.DB.smiley_list( PageContext.PageBoardID, Request.QueryString ["s"] ) )
				{
					if ( dt.Rows.Count > 0 )
					{
						Code.Text = dt.Rows [0] ["Code"].ToString();
						Emotion.Text = dt.Rows [0] ["Emoticon"].ToString();
						if ( Icon.Items.FindByText( dt.Rows [0] ["Icon"].ToString() ) != null ) Icon.Items.FindByText( dt.Rows [0] ["Icon"].ToString() ).Selected = true;
						Preview.Src = String.Format( "{0}images/emoticons/{1}", YafForumInfo.ForumRoot, dt.Rows [0] ["Icon"] );
						SortOrder.Text = dt.Rows [0] ["SortOrder"].ToString();		// Ederon : 9/4/2007
					}
				}
			}
			else
			{
				Preview.Src = String.Format( "{0}images/spacer.gif", YafForumInfo.ForumRoot );
			}
			Icon.Attributes ["onchange"] = String.Format(
				"getElementById('{1}').src='{0}images/emoticons/' + this.value",
				YafForumInfo.ForumRoot,
				Preview.ClientID
				);
		}
예제 #31
0
        /// <summary>Gets the absolute Railway folder for a given route file</summary>
        /// <returns>The absolute on-disk path of the railway folder</returns>
        private static string GetRailwayFolder(string RouteFile)
        {
            try {
                string Folder = System.IO.Path.GetDirectoryName(RouteFile);

                while (true)
                {
                    string Subfolder = OpenBveApi.Path.CombineDirectory(Folder, "Railway");
                    if (System.IO.Directory.Exists(Subfolder))
                    {
                        if (System.IO.Directory.EnumerateDirectories(Subfolder).Any() || System.IO.Directory.EnumerateFiles(Subfolder).Any())
                        {
                            //HACK: Ignore completely empty directories
                            //Doesn't handle wrong directories, or those with stuff missing, TODO.....
                            Program.AppendToLogFile(Subfolder + " : Railway folder found.");
                            return(Subfolder);
                        }
                        Program.AppendToLogFile(Subfolder + " : Railway folder candidate rejected- Directory empty.");
                    }
                    if (Folder == null)
                    {
                        continue;
                    }
                    System.IO.DirectoryInfo Info = System.IO.Directory.GetParent(Folder);
                    if (Info == null)
                    {
                        break;
                    }
                    Folder = Info.FullName;
                }
            } catch { }

            //If the Route, Object and Sound folders exist, but are not in a railway folder.....
            try
            {
                string Folder    = System.IO.Path.GetDirectoryName(RouteFile);
                string candidate = null;
                while (true)
                {
                    string RouteFolder  = OpenBveApi.Path.CombineDirectory(Folder, "Route");
                    string ObjectFolder = OpenBveApi.Path.CombineDirectory(Folder, "Object");
                    string SoundFolder  = OpenBveApi.Path.CombineDirectory(Folder, "Sound");
                    if (System.IO.Directory.Exists(RouteFolder) && System.IO.Directory.Exists(ObjectFolder) && System.IO.Directory.Exists(SoundFolder))
                    {
                        Program.AppendToLogFile(Folder + " : Railway folder found.");
                        return(Folder);
                    }
                    if (System.IO.Directory.Exists(RouteFolder) && System.IO.Directory.Exists(ObjectFolder))
                    {
                        candidate = Folder;
                    }
                    System.IO.DirectoryInfo Info = System.IO.Directory.GetParent(Folder);
                    if (Info == null)
                    {
                        if (candidate != null)
                        {
                            Program.AppendToLogFile(Folder + " : The best candidate for the Railway folder has been selected- Sound folder not detected.");
                            return(candidate);
                        }
                        break;
                    }
                    Folder = Info.FullName;
                }
            }
            catch { }
            Program.AppendToLogFile("No Railway folder found- Returning the openBVE startup path.");
            return(Application.StartupPath);
        }
예제 #32
0
        public void download(int count, string[] words, string delete, string[] calib3)
        {
            string pwd = Environment.CurrentDirectory;

            Console.WriteLine("Downloading...");
            PictureList picturelist = Program.lytronetclient.DownloadPictureList();
            int         c           = picturelist.Count;
            string      sn          = info.SerialNumber;

            string calib = calib3[0];

            // if creating new calibration data set, delete old sets if they exist
            if (calib.Equals("Y") || calib.Equals("y"))
            {
                string path = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Cameras/{1}/Calibration_dataset/01/", pwd);
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);

                foreach (System.IO.FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }
                foreach (System.IO.DirectoryInfo dir in di.GetDirectories())
                {
                    dir.Delete(true);
                }
            }

            int a = 0;

            foreach (PictureListEntry entry in picturelist) // download files
            {
                string str  = picturelist[a].ToString();
                string path = picturelist[a].Path.ToString();

                string[] detail = str.Split();
                string   ids    = detail[0];
                string   addres = detail[1];
                addres = addres.Replace("[", "");
                addres = addres.Replace("]", "");
                string[] splits = addres.Split('\\');

                string nameL     = String.Format(@"IMG_{0}.LFR", a);
                string datanameL = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}", pwd, nameL);
                string nameR     = String.Format(@"IMG_{0}.RAW", a);
                string datanameR = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}", pwd, nameR);
                string nameJ     = String.Format(@"IMG_{0}.JPG", a);
                string datanameJ = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}", pwd, nameJ);
                string nameT     = String.Format(@"IMG_{0}.TXT", a);
                string datanameT = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}", pwd, nameT);

                if (!System.IO.File.Exists(datanameL) && !System.IO.File.Exists(datanameR) &&
                    !System.IO.File.Exists(datanameT) && !System.IO.File.Exists(datanameJ))
                {
                    foreach (string word in words)
                    {
                        if (word.Equals("j"))
                        {
                            string[] details = str.Split();
                            string   id      = details[0];
                            string   address = details[1];
                            address = address.Replace("[", "");
                            address = address.Replace("]", "");
                            string[] split = address.Split('\\');
                            string   name  = split[3];
                            byte[]   data  = Program.lytronetclient.DownloadPicture(id, LoadPictureFormat.Jpeg);
                            if (calib.Equals("Y") || calib.Equals("y"))
                            {
                                string dataname = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Cameras/{1}/Calibration_dataset/01/{2}.jpg", pwd, sn, name);
                                System.IO.File.WriteAllBytes(dataname, data);
                            }
                            else
                            {
                                string dataname = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}.jpg", pwd, name);
                                System.IO.File.WriteAllBytes(dataname, data);
                            }
                        }
                        else if (word.Equals("r"))
                        {
                            string[] details = str.Split();
                            string   id      = details[0];
                            string   address = details[1];
                            address = address.Replace("[", "");
                            address = address.Replace("]", "");
                            string[] split = address.Split('\\');
                            string   name  = split[3];
                            name = name.Replace(".RAW", "");
                            byte[] data = Program.lytronetclient.DownloadPicture(id, LoadPictureFormat.Raw);
                            if (calib.Equals("Y") || calib.Equals("y"))
                            {
                                string dataname = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Cameras/{1}/Calibration_dataset/01/{2}.raw", pwd, sn, name);
                                System.IO.File.WriteAllBytes(dataname, data);
                            }
                            else
                            {
                                string dataname = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}.raw", pwd, name);
                                System.IO.File.WriteAllBytes(dataname, data);
                            }
                        }
                        else if (word.Equals("m"))
                        {
                            string[] details = str.Split();
                            string   id      = details[0];
                            string   address = details[1];
                            address = address.Replace("[", "");
                            address = address.Replace("]", "");
                            string[] split = address.Split('\\');
                            string   name  = split[3];
                            name = name.Replace(".RAW", "");
                            byte[] data = Program.lytronetclient.DownloadPicture(id, LoadPictureFormat.Metadata);
                            if (calib.Equals("Y") || calib.Equals("y"))
                            {
                                string dataname = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Cameras/{1}/Calibration_dataset/01/{2}.txt", pwd, sn, name);
                                System.IO.File.WriteAllBytes(dataname, data);
                            }
                            else
                            {
                                string dataname = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}.txt", pwd, name);
                                System.IO.File.WriteAllBytes(dataname, data);
                            }
                        }
                        else if (word.Equals("s"))
                        {
                            string[] details = str.Split();
                            string   id      = details[0];
                            string   address = details[1];
                            address = address.Replace("[", "");
                            address = address.Replace("]", "");
                            string[] split = address.Split('\\');
                            string   name  = split[3];
                            name = name.Replace(".RAW", "");
                            name = String.Format("{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}.raw", pwd, name);
                            int    offset = 0x1C;
                            byte[] data   = Program.lytronetclient.DownloadPicture(id, LoadPictureFormat.Stack);
                            string ext    = System.IO.Path.GetExtension(path);
                            int    index  = 1;

                            while (offset + 4 < data.Length)
                            {
                                int length = BitConverter.ToInt32(data, offset); offset += 4;
                                if (offset + length > data.Length)
                                {
                                    break;
                                }

                                string pathstack = System.IO.Path.ChangeExtension(name, index + ext);
                                using (System.IO.FileStream file = System.IO.File.Create(pathstack))
                                    file.Write(data, offset, length);

                                offset += length;
                                index++;
                            }
                        }
                        else if (word.Equals("L"))
                        {
                            byte[]    rawData  = Program.lytronetclient.DownloadFile(path);
                            string    npath    = System.IO.Path.ChangeExtension(path, "TXT");
                            byte[]    metaData = Program.lytronetclient.DownloadFile(npath);
                            Json.Root root     = new Json.Root();
                            root.LoadFromJson(Encoding.UTF8.GetString(metaData));
                            string name = String.Format(@"IMG_{0}.LFR", a);
                            if (calib.Equals("Y") || calib.Equals("y"))
                            {
                                string savepath = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Cameras/{1}/Calibration_dataset/01/{2}", pwd, sn, name);
                                using (System.IO.FileStream file = System.IO.File.Create(savepath))
                                    LightFieldPackage.FromCameraFiles(root, rawData).WriteTo(file);
                            }
                            else
                            {
                                string savepath = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}", pwd, name);
                                using (System.IO.FileStream file = System.IO.File.Create(savepath))
                                    LightFieldPackage.FromCameraFiles(root, rawData).WriteTo(file);
                            }
                        }
                        else if (word.Equals("J"))
                        {
                            string name    = System.IO.Path.ChangeExtension(path, "rawCompressed.jpg");
                            byte[] rawData = Program.lytronetclient.DownloadPictureRawJpeg(path);
                            if (calib.Equals("Y") || calib.Equals("y"))
                            {
                                string savepath = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Cameras/{1}/Calibration_dataset/01/{2}", pwd, sn, name);
                                System.IO.File.WriteAllBytes(savepath, rawData);
                            }
                            else
                            {
                                string savepath = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}", pwd, name);
                                System.IO.File.WriteAllBytes(savepath, rawData);
                            }
                        }
                        else if (word.Equals("R"))
                        {
                            byte[]   image     = Program.lytronetclient.DownloadFile(path);
                            string[] directory = path.Split('\\');
                            string   name      = directory[3];
                            if (calib.Equals("Y") || calib.Equals("y"))
                            {
                                string savepath = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Cameras/{1}/Calibration_dataset/01/{2}", pwd, sn, name);
                                System.IO.File.WriteAllBytes(savepath, image);
                            }
                            else
                            {
                                string savepath = String.Format(@"{0}/LFToolbox0.4/LFToolbox0.3_Samples1/Images/Lytro/{1}", pwd, name);
                                System.IO.File.WriteAllBytes(savepath, image);
                            }
                        }
                    }
                    int    b         = a + 1;
                    string timestamp = picturelist[a].DateTaken.ToString();
                    Console.WriteLine("timestamp: " + timestamp);
                    Console.WriteLine("Downloaded Photo " + b + "/" + c);

                    if (delete.Equals("Y") || delete.Equals("y"))
                    {
                        Program.lytronetclient.DeletePicture(picturelist[a]); // delete photo from camera
                    }
                }
                a = a + 1;
            }
            Console.WriteLine("Download Complete.");
        }
 /// <summary> Create a NativeFSLockFactory instance, storing lock
 /// files into the specified lockDir:
 ///
 /// </summary>
 /// <param name="lockDir">where lock files are created.
 /// </param>
 public NativeFSLockFactory(System.IO.DirectoryInfo lockDir)
 {
     SetLockDir(lockDir);
 }
 public NativeFSLock(System.IO.DirectoryInfo lockDir, System.String lockFileName)
 {
     this.lockDir = lockDir;
     path         = new System.IO.FileInfo(System.IO.Path.Combine(lockDir.FullName, lockFileName));
 }
예제 #35
0
            private void PublishChanges()
            {
                if (WorkshopUploadAppId == 0)
                {
                    throw new Exception("WorkshopUploadAppId should not be 0");
                }

                UpdateHandle = workshop.ugc.StartItemUpdate(WorkshopUploadAppId, Id);

                if (Title != null)
                {
                    workshop.ugc.SetItemTitle(UpdateHandle, Title);
                }

                if (Description != null)
                {
                    workshop.ugc.SetItemDescription(UpdateHandle, Description);
                }

                if (Folder != null)
                {
                    var info = new System.IO.DirectoryInfo(Folder);

                    if (!info.Exists)
                    {
                        throw new System.Exception($"Folder doesn't exist ({Folder})");
                    }

                    workshop.ugc.SetItemContent(UpdateHandle, Folder);
                }

                if (Tags != null && Tags.Count > 0)
                {
                    workshop.ugc.SetItemTags(UpdateHandle, Tags.ToArray());
                }

                if (Visibility.HasValue)
                {
                    workshop.ugc.SetItemVisibility(UpdateHandle, (SteamNative.RemoteStoragePublishedFileVisibility)(uint) Visibility.Value);
                }

                if (PreviewImage != null)
                {
                    var info = new System.IO.FileInfo(PreviewImage);

                    if (!info.Exists)
                    {
                        throw new System.Exception($"PreviewImage doesn't exist ({PreviewImage})");
                    }

                    if (info.Length >= 1024 * 1024)
                    {
                        throw new System.Exception($"PreviewImage should be under 1MB ({info.Length})");
                    }

                    workshop.ugc.SetItemPreview(UpdateHandle, PreviewImage);
                }

                if (MetaData != null)
                {
                    workshop.ugc.SetItemMetadata(UpdateHandle, MetaData);
                }

                if (KeyValues != null)
                {
                    foreach (var key in KeyValues)
                    {
                        foreach (var value in key.Value)
                        {
                            workshop.ugc.AddItemKeyValueTag(UpdateHandle, key.Key, value);
                        }
                    }
                }

                /*
                 *  workshop.ugc.SetItemUpdateLanguage( UpdateId, const char *pchLanguage ) = 0; // specify the language of the title or description that will be set
                 *  workshop.ugc.RemoveItemKeyValueTags( UpdateId, const char *pchKey ) = 0; // remove any existing key-value tags with the specified key
                 *  workshop.ugc.AddItemPreviewFile( UpdateId, const char *pszPreviewFile, EItemPreviewType type ) = 0; //  add preview file for this item. pszPreviewFile points to local file, which must be under 1MB in size
                 *  workshop.ugc.AddItemPreviewVideo( UpdateId, const char *pszVideoID ) = 0; //  add preview video for this item
                 *  workshop.ugc.UpdateItemPreviewFile( UpdateId, uint32 index, const char *pszPreviewFile ) = 0; //  updates an existing preview file for this item. pszPreviewFile points to local file, which must be under 1MB in size
                 *  workshop.ugc.UpdateItemPreviewVideo( UpdateId, uint32 index, const char *pszVideoID ) = 0; //  updates an existing preview video for this item
                 *  workshop.ugc.RemoveItemPreview( UpdateId, uint32 index ) = 0; // remove a preview by index starting at 0 (previews are sorted)
                 */

                SubmitItemUpdate = workshop.ugc.SubmitItemUpdate(UpdateHandle, ChangeNote, OnChangesSubmittedInternal);
            }
예제 #36
0
 public static bool DllHijackingAttempted(string path, string dllFileName)
 {
     System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
     return(System.IO.File.Exists(di.FullName + System.IO.Path.DirectorySeparatorChar + dllFileName));
 }
예제 #37
0
        public void WriteException(Exception ex, int maxFiles, string logsFolder, bool writeAsHtml)
        {
            var ev = WritingException;
            var le = new LogHelperEventArgs()
            {
                Exception = ex
            };

            if (ev != null)
            {
                ev(this, le);
            }
            if (le.Cancel)
            {
                return;
            }
            // Must wrap into lock so that process won't attempt to delete/write same file twice from different threads.
            lock (WriteLock)
            {
                var n    = DateTime.Now;
                var type = ex.GetType();
                if (exeptionTimes.ContainsKey(type))
                {
                    // Increase counter.
                    exeptionCount[type] = exeptionCount[type] + 1;
                    // Do not allow write if not enough time passed.
                    if (n.Subtract(exeptionTimes[type]).Milliseconds < 500)
                    {
                        return;
                    }
                }
                else
                {
                    exeptionTimes.Add(type, n);
                    exeptionCount.Add(type, 1);
                }
                var count = exeptionCount[type];
                // Reset count and update last write time.
                exeptionCount[type] = 0;
                exeptionTimes[type] = n;
                // Create file.
                var prefix = "FCE_" + ex.GetType().Name;
                var ext    = writeAsHtml ? "htm" : "txt";
                var di     = new System.IO.DirectoryInfo(logsFolder);
                if (di.Exists)
                {
                    var files = di.GetFiles(prefix + "*." + ext).OrderBy(x => x.CreationTime).ToArray();
                    if (maxFiles > 0 && files.Count() > 0 && files.Count() > maxFiles)
                    {
                        // Remove oldest file.
                        files[0].Delete();
                    }
                }
                else
                {
                    di.Create();
                }
                //var fileTime = JocysCom.ClassLibrary.HiResDateTime.Current.Now;
                var fileTime = HiResDateTime.Current.Now;
                var fileName = string.Format("{0}\\{1}_{2:yyyyMMdd_HHmmss.ffffff}{3}.{4}",
                                             di.FullName, prefix, fileTime, count == 1 ? "" : "." + count.ToString(), ext);
                var fi      = new System.IO.FileInfo(fileName);
                var content = writeAsHtml ? ExceptionInfo(ex, "") : ex.ToString();
                System.IO.File.AppendAllText(fileName, content);
            }
        }
        string OpenPlatformSpecificOutputSelector()
        {
            const string kTitle = "Select Output Path";
            string       path   = UBS.Helpers.GetAbsolutePathRelativeToProject(mEditedBuildProcess.mOutputPath);

            switch (mEditedBuildProcess.mPlatform)
            {
            case BuildTarget.Android:
                return(EditorUtility.SaveFilePanel(kTitle, path, "android", "apk"));

#if !UNITY_5
            case BuildTarget.iPhone:
                return(EditorUtility.SaveFolderPanel(kTitle, path, "iOSDeployment"));

            case BuildTarget.MetroPlayer:
                return(EditorUtility.SaveFolderPanel(kTitle, path, "MetroDeployment"));

            case BuildTarget.NaCl:
                return(EditorUtility.SaveFolderPanel(kTitle, path, "NativeClientDeployment"));
#else
            case BuildTarget.iOS:
                return(EditorUtility.SaveFolderPanel(kTitle, path, "iOSDeployment"));

            case BuildTarget.WSAPlayer:
                return(EditorUtility.SaveFolderPanel(kTitle, path, "MetroDeployment"));

            case BuildTarget.WebGL:
                return(EditorUtility.SaveFolderPanel(kTitle, path, "WebGLDeployment"));
#endif

#if UNITY_4_5 || UNITY_4_6 || UNITY_5
            case BuildTarget.BlackBerry:
#else
            case BuildTarget.BB10:
#endif
                return(EditorUtility.SaveFolderPanel(kTitle, path, "BlackBerryDeployment"));


            case BuildTarget.WebPlayer:
                return(EditorUtility.SaveFolderPanel(kTitle, path, "WebPlayerDeployment"));


            case BuildTarget.StandaloneOSXUniversal:
            case BuildTarget.StandaloneOSXIntel64:
            case BuildTarget.StandaloneOSXIntel:

                //
                // special handle .app folders for OSX
                //
                string suffix = "/" + PlayerSettings.productName + ".app";

                if (path.EndsWith(suffix))
                {
                    path = path.Substring(0, path.Length - 4);
                }
                System.IO.DirectoryInfo fi = new System.IO.DirectoryInfo(path);
                Debug.Log(fi.Parent.ToString());

                string outString = EditorUtility.SaveFolderPanel(kTitle, fi.Parent.ToString(), "");

                if (!string.IsNullOrEmpty(outString))
                {
                    if (!outString.EndsWith(suffix))
                    {
                        outString = outString + suffix;
                    }
                }

                return(outString);

            case BuildTarget.StandaloneLinux:
            case BuildTarget.StandaloneLinux64:
            case BuildTarget.StandaloneLinuxUniversal:

            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneWindows64:

                return(EditorUtility.SaveFilePanel(kTitle, path, "StandaloneDeployment", "exe"));
            }
            return("");
        }
예제 #39
0
        public void LoadCoupon()
        {
            OnStateChange?.Invoke(Enums.StateLogType.MoGuJieGetCouponStart, "开始加载蘑菇街优惠券");
            var cids     = MoGuJie.Method.AllCategory;
            var pageSize = 100;
            var models   = new List <Coupon>();

            foreach (var cid in cids)
            {
                if (!EnableRun)
                {
                    return;
                }

                try
                {
                    //获取第一页
                    var result = mgj.GetItemList(channels, cid, pageNo: 1, pageSize: pageSize);
                    //已经初始化过了,就不往下加载了
                    if (result.Total > 0)
                    {
                        models.AddRange(result.Items);
                        //获取
                        if (!onlyFirstPage)
                        {
                            for (int i = 2; i <= result.TotalPage; i++)
                            {
                                var result2 = mgj.GetItemList(channels, cid, pageNo: i, pageSize: pageSize);
                                models.AddRange(result2.Items);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    SystemBase.WriteLog(ex.Message, "MoGuJie");
                }
            }


            OnStateChange?.Invoke(Enums.StateLogType.MoGuJieGetCouponComplated, "加载蘑菇街优惠券加载完成");
            var dirInfo = new System.IO.DirectoryInfo($"{Config.RuningPath}\\temp");

            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }
            foreach (var item in channels)
            {
                var pModel   = models.Where(s => s.UserID == item.UserID).ToList();
                var path     = $"{Config.RuningPath}\\temp\\蘑菇街_{item.Name}_{DateTime.Now:yyyyMMddHHmm}.json";
                var fileInfo = new System.IO.FileInfo(path);
                System.IO.File.WriteAllText(path, JsonConvert.SerializeObject(pModel));


                try
                {
                    OnStateChange?.Invoke(Enums.StateLogType.MoGuJieCouponAddDbStart, $"蘑菇街 代理{item.Name} 提交开始");
                    var files = new Dictionary <string, string>();
                    files.Add("file", path);

                    var upload = new Api.BuyUploadApi(files).CreateRequestReturnUrls();
                    var update = new Api.BuyApi("ImportItems", "MoGuJie", new { Url = upload[0] }).CreateRequestReturnBuyResult <object>();

                    if (update.State == "Success")
                    {
                        OnStateChange?.Invoke(Enums.StateLogType.MoGuJieCouponAddDbComplated, $"蘑菇街 代理{item.Name} 提交完成");
                        try
                        {
                            System.IO.File.Delete(path);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        OnStateChange?.Invoke(Enums.StateLogType.MoGuJieCouponAddDbError, update.Message);
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        Bll.Buy.LoopCheckCouponUserTemps(item.UserID, Enums.Platform.MGJ);
                        OnStateChange?.Invoke(Enums.StateLogType.MoGuJieCouponAddDbComplated, $"蘑菇街 代理{item.Name} 提交完成");
                    }
                    catch (Exception)
                    {
                        OnStateChange?.Invoke(Enums.StateLogType.MoGuJieCouponAddDbError, $"蘑菇街 代理{item.Name} 提交超时");
                    }
                }
                finally
                {
                    try
                    {
                        System.IO.File.Delete(path);
                    }
                    catch (Exception ex)
                    {
                        OnStateChange?.Invoke(Enums.StateLogType.MoGuJieCouponDeleteTemp, $"蘑菇街 代理{item.Name} 提交有误");
                    }
                }
            }

            onlyFirstPage = true;

            var task = new Task(() =>
            {
                Thread.Sleep(5 * 60 * 1000);
                mgj.RefeashToken();
                LoadCoupon();
            });

            task.Start();
        }
        private void CompareDirectoryInfos(System.IO.DirectoryInfo expected, Alphaleonis.Win32.Filesystem.DirectoryInfo actual, bool exists)
        {
            if (expected == null || actual == null)
            {
                Assert.AreEqual(expected, actual, "The two DirectoryInfo instances are not the same, but are expected to be.");
            }

            UnitTestConstants.Dump(expected, -17);
            Console.WriteLine();
            UnitTestConstants.Dump(actual, -17);


            if (exists)
            {
                Assert.IsTrue(expected.Exists && actual.Exists, "The directory does not exist, but is expected to.");
            }
            else
            {
                Assert.IsFalse(expected.Exists && actual.Exists, "The directory exists, but is expected not to.");
            }


            var cnt = -1;

            while (cnt != 13)
            {
                cnt++;
                // Compare values of both instances.
                switch (cnt)
                {
                case 0:
                    Assert.AreEqual(expected.Attributes, actual.Attributes, "The property Attributes is not the same, but is expected to be.");
                    break;

                case 1:
                    Assert.AreEqual(expected.CreationTime, actual.CreationTime, "The property CreationTime is not the same, but is expected to be.");
                    break;

                case 2:
                    Assert.AreEqual(expected.CreationTimeUtc, actual.CreationTimeUtc, "The property CreationTimeUtc is not the same, but is expected to be.");
                    break;

                case 3:
                    Assert.AreEqual(expected.Exists, actual.Exists, "The property Exists is not the same, but is expected to be.");
                    break;

                case 4:
                    Assert.AreEqual(expected.Extension, actual.Extension, "The property Extension is not the same, but is expected to be.");
                    break;

                case 5:
                    Assert.AreEqual(expected.FullName, actual.FullName, "The property FullName is not the same, but is expected to be.");
                    break;

                case 6:
                    Assert.AreEqual(expected.LastAccessTime, actual.LastAccessTime, "The property LastAccessTime is not the same, but is expected to be.");
                    break;

                case 7:
                    Assert.AreEqual(expected.LastAccessTimeUtc, actual.LastAccessTimeUtc, "The property LastAccessTimeUtc is not the same, but is expected to be.");
                    break;

                case 8:
                    Assert.AreEqual(expected.LastWriteTime, actual.LastWriteTime, "The property LastWriteTime is not the same, but is expected to be.");
                    break;

                case 9:
                    Assert.AreEqual(expected.LastWriteTimeUtc, actual.LastWriteTimeUtc, "The property LastWriteTimeUtc is not the same, but is expected to be.");
                    break;

                case 10:
                    Assert.AreEqual(expected.Name, actual.Name, "The property Name is not the same, but is expected to be.");
                    break;

                // Need .ToString() here since the object types are obviously not the same.
                case 11: Assert.AreEqual(expected.Parent.ToString(), actual.Parent.ToString(), "The property Parent is not the same, but is expected to be.");
                    break;

                case 12: Assert.AreEqual(expected.Root.ToString(), actual.Root.ToString(), "The property Root is not the same, but is expected to be.");
                    break;
                }
            }
        }
예제 #41
0
        private void QueueThread()
        {
            //触发队列启动事件
            if (QueueStarted != null)
            {
                QueueStarted(this, new QueueEventArgs());
            }

            //初始化相关变量
            TransferedFileCount  = 0;
            TransferedDataLength = 0;
            TransferStartTime    = DateTime.Now;

            //开始传输队列
            while (QueueItemList.Count > 0)
            {
                if (QueueState == TransferQueueState.Stoped)
                {
                    break;
                }
                var item = QueueItemList[0];
                CurrentQueueItem = item;

                //处理队列对象
                item.State = TransferQueueItem.TransferQueueItemStateEnum.Transfering;

                CurrentSiteData = item.SiteData;
                var CurrentSite = CurrentSiteData.GetFtpSite();
                var CurrentGroupSiteDataList = new List <FtpSiteData>(CurrentSiteData.Group.Sites);

                if (item.Type == TransferQueueItem.TransferQueueItemTypeEnum.Download)
                {
                    var baseFile = item.RemoteBaseFile;

                    //如果是目录
                    if (baseFile.IsFolder)
                    {
                        var subLocalPath = System.IO.Path.Combine(item.LocalPath, item.Name);
                        if (!aaaSoft.Helpers.IoHelper.CreateMultiFolder(subLocalPath))
                        {
                            item.State = TransferQueueItem.TransferQueueItemStateEnum.Error;
                            item.Tip   = String.Format("创建目录 {0} 时失败。", subLocalPath);
                            RemoveFromQueue(item);
                            continue;
                        }
                        //列出目录
                        var subBaseFiles = CurrentSite.ListDirectory(baseFile.FullName);
                        if (subBaseFiles == null)
                        {
                            item.State = TransferQueueItem.TransferQueueItemStateEnum.Error;
                            item.Tip   = String.Format("列目录 {0} 时失败,原因:{1}。", baseFile.FullName, CurrentSite.ErrMsg);
                            RemoveFromQueue(item);
                            continue;
                        }
                        foreach (var subBaseFile in subBaseFiles)
                        {
                            var subItem = new TransferQueueItem(CurrentSiteData);
                            subItem.Type           = TransferQueueItem.TransferQueueItemTypeEnum.Download;
                            subItem.RemoteBaseFile = subBaseFile;
                            subItem.RemotePath     = subBaseFile.FullName;
                            subItem.LocalPath      = System.IO.Path.Combine(subLocalPath, subBaseFile.Name);
                            InsertIntoQueue(subItem);
                        }
                        item.State = TransferQueueItem.TransferQueueItemStateEnum.TransferComplete;
                    }
                    //如果是文件
                    else if (baseFile is FtpBaseFileInfo)
                    {
                        //如果当前目录不是要下载文件的目录,则改变工作目录
                        if (CurrentSite.CurrentDirectoryPath.ToUpper() != baseFile.ParentPath.ToUpper())
                        {
                            CurrentSite.ListDirectory(baseFile.ParentPath);
                        }
                        if (!CurrentSite.DownloadFile(baseFile as FtpBaseFileInfo, item.LocalPath))
                        {
                            item.Tip   = String.Format("下载文件 {0} 时失败,原因:{1}。", baseFile.FullName, CurrentSite.ErrMsg);
                            item.State = TransferQueueItem.TransferQueueItemStateEnum.Error;
                            RemoveFromQueue(item);
                            continue;
                        }
                        item.State = TransferQueueItem.TransferQueueItemStateEnum.TransferComplete;
                        TransferedFileCount++;
                        TransferedDataLength += CurrentSite.TransferedDataLength;
                    }
                }
                else if (item.Type == TransferQueueItem.TransferQueueItemTypeEnum.Upload)
                {
                    //如果是文件
                    if (System.IO.File.Exists(item.LocalPath))
                    {
                        //远端目录路径
                        var remoteFolderPath = aaaSoft.Helpers.IoHelper.GetParentPath(item.RemotePath, '/');
                        foreach (var siteData in CurrentGroupSiteDataList)
                        {
                            var site = siteData.GetFtpSite();
                            if (site.CurrentDirectoryPath != remoteFolderPath)
                            {
                                var baseFiles = site.ListDirectory(remoteFolderPath);
                                //如果列目录失败
                                if (baseFiles == null)
                                {
                                    item.State = TransferQueueItem.TransferQueueItemStateEnum.Error;
                                    item.Tip   = String.Format("列目录 {0} 时失败,原因:{1}。", remoteFolderPath, site.ErrMsg);
                                    RemoveFromQueue(item);
                                    continue;
                                }
                            }
                        }

                        //远端文件名
                        var remoteFileName = aaaSoft.Helpers.IoHelper.GetFileOrFolderName(item.RemotePath, '/');

                        //是否传输成功
                        bool IsTransferSuccess = true;
                        //已成功传输的站点数量
                        Int32 successedSiteCount = 0;

                        foreach (var siteData in CurrentGroupSiteDataList)
                        {
                            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(Object state)
                            {
                                var ositeData = state as FtpSiteData;
                                var osite     = ositeData.GetFtpSite();
                                if (!osite.UploadFile(remoteFileName, item.LocalPath))
                                {
                                    IsTransferSuccess = false;
                                    item.State        = TransferQueueItem.TransferQueueItemStateEnum.Error;
                                    item.Tip          = String.Format("上传文件 {0} 时失败,原因:{1}。", item.LocalPath, osite.ErrMsg);
                                    Debug.Print("TransferQueue.QueueThread():" + item.Tip);
                                }
                                lock (TransferedFileCountObj)
                                    TransferedFileCount++;
                                lock (TransferedDataLengthObj)
                                    TransferedDataLength += osite.TransferedDataLength;
                                successedSiteCount++;
                            }), siteData);
                        }

                        while (IsTransferSuccess && successedSiteCount < CurrentSiteData.Group.Sites.Count)
                        {
                            Thread.Sleep(ProgressUpdateTimeInterval);
                        }

                        if (!IsTransferSuccess)
                        {
                            RemoveFromQueue(item);
                            continue;
                        }

                        item.State = TransferQueueItem.TransferQueueItemStateEnum.TransferComplete;
                    }
                    //如果是目录
                    else if (System.IO.Directory.Exists(item.LocalPath))
                    {
                        //=====================
                        //检查远端目录是否存在
                        //=====================
                        foreach (var siteData in CurrentGroupSiteDataList)
                        {
                            var site      = siteData.GetFtpSite();
                            var baseFiles = site.ListDirectory(item.RemotePath);
                            //如果远端目录不存在
                            if (baseFiles == null)
                            {
                                if (!site.CreateDirectory(item.RemotePath))
                                {
                                    item.State = TransferQueueItem.TransferQueueItemStateEnum.Error;
                                    item.Tip   = String.Format("创建远端目录 {0} 时失败,原因:{0}。", item.LocalPath, site.ErrMsg);
                                    RemoveFromQueue(item);
                                    continue;
                                }
                            }
                        }

                        try
                        {
                            var localFolderInfo = new System.IO.DirectoryInfo(item.LocalPath);

                            List <String> PathList = new List <string>();
                            foreach (var subFileInfo in localFolderInfo.GetFiles())
                            {
                                PathList.Add(subFileInfo.FullName);
                            }
                            foreach (var subFolderInfo in localFolderInfo.GetDirectories())
                            {
                                PathList.Add(subFolderInfo.FullName);
                            }

                            foreach (var subPath in PathList)
                            {
                                var subItem = new TransferQueueItem(CurrentSiteData);
                                subItem.Type       = TransferQueueItem.TransferQueueItemTypeEnum.Upload;
                                subItem.LocalPath  = subPath;
                                subItem.RemotePath = (item.RemotePath + "/" + IoHelper.GetFileOrFolderName(subPath, System.IO.Path.DirectorySeparatorChar)).Replace("//", "/");
                                InsertIntoQueue(subItem);
                            }
                            item.State = TransferQueueItem.TransferQueueItemStateEnum.TransferComplete;
                        }
                        catch (Exception ex)
                        {
                            item.State = TransferQueueItem.TransferQueueItemStateEnum.Error;
                            item.Tip   = String.Format("上传目录 {0} 时失败,原因:{0}。", item.LocalPath, ex.Message);
                            RemoveFromQueue(item);
                            continue;
                        }
                    }
                }

                //如果处理成功则从队列中移除
                RemoveFromQueue(item);
            }
            TransferEndTime  = DateTime.Now;
            trdTransfer      = null;
            CurrentSiteData  = null;
            CurrentQueueItem = null;
            if (QueueItemList.Count == 0)
            {
                //触发队列完成事件
                if (QueueCompleted != null)
                {
                    QueueCompleted(this, new QueueEventArgs());
                }
            }
            else
            {
                //触发队列停止事件
                if (QueueStoped != null)
                {
                    QueueStoped(this, new QueueEventArgs());
                }
            }
        }
        protected override void BuildXml()
        {
            if (Request.Form["CKFinderCommand"] != "true")
            {
                ConnectorException.Throw(Errors.InvalidRequest);
            }

            if (!this.CurrentFolder.CheckAcl(AccessControlRules.FolderRename))
            {
                ConnectorException.Throw(Errors.Unauthorized);
            }

            // The root folder cannot be deleted.
            if (this.CurrentFolder.ClientPath == "/")
            {
                ConnectorException.Throw(Errors.InvalidRequest);
                return;
            }

            string newFileName = Request["NewFolderName"];

            if (!Connector.CheckFolderName(newFileName) || Config.Current.CheckIsHiddenFolder(newFileName))
            {
                ConnectorException.Throw(Errors.InvalidName);
                return;
            }

            // Get the current folder.
            System.IO.DirectoryInfo oDir = new System.IO.DirectoryInfo(this.CurrentFolder.ServerPath);

            bool bMoved = false;

            try
            {
                if (!oDir.Exists)
                {
                    ConnectorException.Throw(Errors.InvalidRequest);
                }
                else
                {
                    // Build the new folder path.
                    string newFolderPath = System.IO.Path.Combine(oDir.Parent.FullName, newFileName);

                    if (System.IO.Directory.Exists(newFolderPath) || System.IO.File.Exists(newFolderPath))
                    {
                        ConnectorException.Throw(Errors.AlreadyExist);
                    }

                    oDir.MoveTo(newFolderPath);
                    bMoved = true;
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                ConnectorException.Throw(Errors.AccessDenied);
            }
            catch (System.Security.SecurityException)
            {
                ConnectorException.Throw(Errors.AccessDenied);
            }
            catch (System.ArgumentException)
            {
                ConnectorException.Throw(Errors.InvalidName);
            }
            catch (System.NotSupportedException)
            {
                ConnectorException.Throw(Errors.InvalidName);
            }
            catch (System.IO.PathTooLongException)
            {
                ConnectorException.Throw(Errors.InvalidName);
            }
            catch (System.IO.IOException)
            {
                ConnectorException.Throw(Errors.Unknown);
            }
            catch (ConnectorException connectorException)
            {
                throw connectorException;
            }
            catch
            {
#if DEBUG
                throw;
#else
                ConnectorException.Throw(Errors.Unknown);
#endif
            }

            if (bMoved)
            {
                try
                {
                    // Get the thumbnails folder.
                    System.IO.DirectoryInfo oThumbsDir = new System.IO.DirectoryInfo(this.CurrentFolder.ThumbsServerPath);

                    // Build the new folder path.
                    string newThumbsFolderPath = System.IO.Path.Combine(oThumbsDir.Parent.FullName, newFileName);

                    if (System.IO.Directory.Exists(newThumbsFolderPath))
                    {
                        System.IO.File.Delete(this.CurrentFolder.ThumbsServerPath);
                    }
                    else
                    {
                        try
                        {
                            oThumbsDir.MoveTo(newThumbsFolderPath);
                        }
                        catch
                        {
                            System.IO.File.Delete(this.CurrentFolder.ThumbsServerPath);
                        }
                    }
                }
                catch { /* No errors if we are not able to delete the thumb. */ }

                string newFolderPath = Regex.Replace(this.CurrentFolder.ClientPath, "[^/]+/?$", newFileName) + "/";
                string newFolderUrl  = this.CurrentFolder.ResourceTypeInfo.Url + newFolderPath.TrimStart('/');

                XmlNode oRenamedNode = XmlUtil.AppendElement(this.ConnectorNode, "RenamedFolder");
                XmlUtil.SetAttribute(oRenamedNode, "newName", newFileName);
                XmlUtil.SetAttribute(oRenamedNode, "newPath", newFolderPath);
                XmlUtil.SetAttribute(oRenamedNode, "newUrl", newFolderUrl);
            }
        }
예제 #43
0
        public static int Main(string[] args)
        {
            /*
             * if(!CheckDeviceAvailable())
             * {
             * DialogResult dr = MessageBox.Show("Do you want to continue? Click Ok button to continue.", "Warning" , MessageBoxButtons.YesNo,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2);
             * if(dr == DialogResult.No)
             * {
             * return 0;
             * }
             * }
             *
             * var configs = GetConfigs ();
             * string CheckDevice = configs["CheckDevice_BeforeTesting"];
             * string RestoreDB = configs["RestoreDB_AfterEachTestCase"];
             */

            /*
             * Get size of database for SQL SERVER
             *  LxSQLDbOperation SQLOper = new LxSQLDbOperation();
             *  SqlConnection conn = new SqlConnection();
             *  conn.ConnectionString =@"Data Source=10.146.64.56\SQLEXPRESS;Initial Catalog=master;User ID=sa;Password=sa@2013;";
             *          SQLOper.OpenConnection(conn);
             *  string NformSize = SQLOper.GetDbSize(conn, "Nform");
             *  string NformAlmSize = SQLOper.GetDbSize(conn, "NformAlm");
             *  string NformLogSize = SQLOper.GetDbSize(conn, "NformLog");
             *  Console.WriteLine("The size of Nform is:"+NformSize);
             *  Console.WriteLine("The size of Nform is:"+NformAlmSize);
             *  Console.WriteLine("The size of Nform is:"+NformLogSize);
             */

            /*
             * Get size of database for SQL CE
             * LxCEDbOperation CEOper = new LxCEDbOperation();
             * double NformAlmSize = CEOper.GetAlarmDbSize();
             * double NformDataLogSize = CEOper.GetDataLogDbSize();
             *      Console.WriteLine("NformAlmSize is: " +NformAlmSize);
             * Console.WriteLine("NformDataLogSize is: " +NformDataLogSize);
             * */

            /*
             * Increase database for SQLCE
             * LxCEDbOperation CEOper = new LxCEDbOperation();
             *           CEOper.IncreaseAlarmDbSize();
             *           CEOper.IncreaseDatalogDbSize();
             * */

            /*
             * Increase database for SQL SERVER
             * LxSQLDbOperation SQLOper = new LxSQLDbOperation();
             *           SqlConnection conn = new SqlConnection();
             *   conn.ConnectionString =@"Data Source=10.146.64.56\SQLEXPRESS;Initial Catalog=master;User ID=sa;Password=sa@2013;";
             *           SQLOper.GetDbSize(conn,"NformAlm");
             *           SQLOper.GetDbSize(conn,"NformLog");
             *           SQLOper.IncreaseAlarmDbSize();
             *           SQLOper.IncreaseDatalogDbSize();
             *
             * */

            /*
             * Get table value for SQLCE database
             *
             * LxCEDbOperation CEOper = new LxCEDbOperation();
             * string dbNformName = @"Nform.sdf";
             * string dbNformAlmName = @"NformAlm.sdf";
             * string dbNformLogName = @"NformLog.sdf";
             * string cmdVersion = @"SELECT * FROM Version;";
             * string cmdAlarm = @"SELECT * FROM Alarm;";
             * string cmdLog = @"SELECT * FROM DataLog;";
             *       CEOper.GetTableValue(dbNformName,cmdVersion);
             *       CEOper.GetTableValue(dbNformAlmName,cmdAlarm);
             * CEOper.GetTableValue(dbNformLogName,cmdLog);
             *
             * */

            /*
             * Get table value for SQLServer database
             * LxSQLDbOperation SQLOper = new LxSQLDbOperation();
             *           SqlConnection conn = new SqlConnection();
             *   conn.ConnectionString =@"Data Source=10.146.64.56\SQLEXPRESS;Initial Catalog=master;User ID=sa;Password=sa@2013;";
             *   string cmdVersion = @"use Nform;SELECT * FROM Version;";
             *   string cmdAlarm = @"use NformAlm;SELECT * FROM Alarm;";
             *   string cmdLog = @"use NformLog;SELECT * FROM DataLog;";
             *   string cmdGrp = @"use Nform;SELECT * FROM UsrGrp;";
             *   SQLOper.GetTableValue(conn,cmdVersion);
             *   SQLOper.GetTableValue(conn,cmdGrp);
             * */

            string CheckDevice = AppConfigOper.getConfigValue("CheckDevice_BeforeTesting");
            string RestoreDB   = AppConfigOper.getConfigValue("RestoreDB_AfterEachTestCase");
            string runOnVM     = AppConfigOper.getConfigValue("RunOnVM");
            //Create Report folder
            string reportDir = System.IO.Directory.GetCurrentDirectory();

            System.IO.DirectoryInfo reportDirect = System.IO.Directory.CreateDirectory(reportDir + @"\Report\" + "Report_" + System.DateTime.Now.ToString("yyyyMMdd_HHmmss"));
            string ReportPath = reportDirect.FullName + @"\";

            setReport(ReportPath);

            // If CheckDevice is Y, program will check these ip addresses are available or not.
            if (CheckDevice.Equals("Y"))
            {
                //stop Nform service
                Console.WriteLine("Stop Nform service...");
                string strRst = RunCommand("sc stop Nform");
                //Be used to check devices are avalibale or not, which are configured in Device.ini
                LxDeviceAvailable myDeviceAvailable = new LxDeviceAvailable();
                myDeviceAvailable.CheckSnmpDevice();
                //myDeviceAvailable.CheckVelDevice();
                //start Nform service
                Console.WriteLine("Start Nform service...");
                strRst = RunCommand("sc start Nform");
            }

            if (CheckDevice.Equals("Y"))
            {
                Keyboard.Enabled  = false;
                Mouse.Enabled     = false;
                Keyboard.AbortKey = System.Windows.Forms.Keys.Pause;
                NformRepository.Instance.SearchTimeout = new Duration(50000);
            }

            Keyboard.AbortKey = System.Windows.Forms.Keys.Pause;
            int error = 0;

            /*
             * try
             * {
             *  error = TestSuiteRunner.Run(typeof(Program), Environment.CommandLine);
             * }
             * catch (Exception e)
             * {
             * MessageBox.Show("Unexpected exception occurred:");
             *  Report.Error("Unexpected exception occurred: " + e.ToString());
             *  error = -1;
             * }
             */
            error = TestSuiteRunner.Run(typeof(Program), Environment.CommandLine);

            return(error);
        }
예제 #44
0
        public void LoadType(bool reload)
        {
            Action <string, object> saveResult = (name, obj) =>
            {
                var p = $"{Config.RuningPath}\\temp\\{name}.json";
                System.IO.File.WriteAllText(p, JToken.FromObject(obj).ToString(Formatting.Indented));
            };
            Func <string, string> readResult = name =>
            {
                var p = $"{Config.RuningPath}\\temp\\{name}.json";
                return(System.IO.File.ReadAllText(p));
            };
            var d = new System.IO.DirectoryInfo($"{Config.RuningPath}\\temp");

            if (!d.Exists)
            {
                d.Create();
            }
            List <MoGuJie.Cid2> r = new List <MoGuJie.Cid2>();

            if (reload)
            {
                r = mgj.GetAllCategory2();
                var r2 = new List <MoGuJie.Cid2>();
                foreach (var item in r)
                {
                    var id = item.ID;
                    r2.AddRange(mgj.GetAllCategory2(id));
                }
                var r3 = new List <MoGuJie.Cid2>();
                foreach (var item in r2)
                {
                    var id = item.ID;
                    r3.AddRange(mgj.GetAllCategory2(id));
                }

                r.AddRange(r2);
                r.AddRange(r3);
                foreach (var item in r)
                {
                    var id = mgj.DecryptID(item.ID);
                    item.DID = id;
                }
                saveResult("cid", r);
            }
            else
            {
                r = JsonConvert.DeserializeObject <List <MoGuJie.Cid2> >(readResult("cid"));
            }
            var dNames = r.GroupBy(s => s.Name)
                         .Select(s => new
            {
                Name  = s.Key,
                Count = s.Count()
            }).Where(s => s.Count > 1)
                         .Select(s => s.Name).ToList();

            foreach (var item in dNames)
            {
                var rTemp = r.Where(s => s.Name == item).ToList();
                foreach (var temp in rTemp)
                {
                    var pName = r.FirstOrDefault(s => s.ID == temp.ParentId)?.Name;
                    pName     = pName == null ? "" : $"{pName}+";
                    temp.Name = $"{pName}{temp.Name}";
                }
            }
            foreach (var item in r)
            {
                item.Count = mgj.GetItemList(channels, item).Total;
            }
            saveResult("temp2", r);
        }
예제 #45
0
        private void VerificarArchivoImagen(StringBuilder htmlImagenes, Entidades.ImagenesAspNet_Users elementoImagenes)
        {
            string idImagen = elementoImagenes.IdImagen.ToString();

            string idCategoria = elementoImagenes.IdCategoria.ToString();

            string userId = elementoImagenes.UserId.ToString();

            string esAprobado = elementoImagenes.EsAprobado.ToString();

            string titulo = elementoImagenes.Titulo.ToString();

            string directorioRelativo = elementoImagenes.DirectorioRelativo.ToString();

            string rutaRelativa = elementoImagenes.RutaRelativa.ToString();

            string enlaceExterno = elementoImagenes.EnlaceExterno.ToString();

            string etiquetasBasicas = elementoImagenes.EtiquetasBasicas.ToString();

            string etiquetasOpcionales = elementoImagenes.EtiquetasOpcionales.ToString();

            string fechaSubida = elementoImagenes.FechaSubida.ToString();

            string fechaPublicacion = elementoImagenes.FechaPublicacion.ToString();

            string applicationId = elementoImagenes.ApplicationId.ToString();

            string userName = elementoImagenes.UserName;

            string loweredUserName = elementoImagenes.LoweredUserName;

            string mobileAlias = elementoImagenes.MobileAlias;

            string isAnonymous = elementoImagenes.IsAnonymous.ToString();

            string lastActivityDate = elementoImagenes.LastActivityDate.ToString();

            System.IO.DirectoryInfo directorio = new System.IO.DirectoryInfo(HttpContext.Current.Server.MapPath(directorioRelativo));

            if (directorio.Exists)
            {
                System.IO.FileInfo[] archivos = directorio.GetFiles();

                bool esArchivoEncontrado = false;

                foreach (System.IO.FileInfo archivo in archivos)
                {
                    string urlImagen = string.Format("{0}\\{1}", directorioRelativo, archivo);

                    if (rutaRelativa.Equals(urlImagen))
                    {
                        string tituloImagen = string.Format("<h2>{0}</h2>", titulo);

                        string nombreUsuario = string.Format("<h3>{0}{1}</h3>", "Aporte por: ", userName);

                        string fechaPublicacionImagen = string.Format("<h4>{0}</h4>", fechaPublicacion);

                        string archivoImagen = string.Format("<img src='{0}' alt='{1}'>", urlImagen, titulo);

                        string linkImagen = string.Format("<a class={0} href={1}{2} onmouseover={3}>{4}</a>", "iframe", "Individual/", idImagen, "InvocarFancybox('75%','100%','false','0.8')", archivoImagen);

                        string etiquetas = string.Format("<h4>{0} | {1}</h4>", etiquetasBasicas, etiquetasOpcionales);

                        string contenidoDivImagen = string.Format("{0}{1}{2}{3}{4}", tituloImagen, nombreUsuario, fechaPublicacionImagen, linkImagen, etiquetas);

                        string imagen = string.Format("<div class={0}>{1}</div>", "imagen", contenidoDivImagen);

                        htmlImagenes.AppendFormat(imagen);

                        esArchivoEncontrado = true;

                        break;
                    }
                }

                if (!esArchivoEncontrado)
                {
                    string imagenNoEncontrada = string.Format("<h2>{0}</br>{1}</h2>", "No se encontró la imagen:", rutaRelativa);

                    string imagen = string.Format("<div class={0}>{1}</div>", "imagen", imagenNoEncontrada);

                    htmlImagenes.AppendFormat(imagen);
                }
            }
            else if (!directorio.Exists)
            {
                htmlImagenes.Clear();

                htmlImagenes.AppendFormat(string.Format("<h2>{0}</h2>", "El directorio no existe."));
            }
        }
예제 #46
0
 public static int FilesInDirectory(string directory)
 {
     System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(directory);
     return(dir.GetFiles().Length);
 }
예제 #47
0
        static void WalkDirectoryTree(System.IO.DirectoryInfo root)
        {
            System.IO.FileInfo[]      files   = null;
            System.IO.DirectoryInfo[] subDirs = null;

            // First, process all the files directly under this folder
            try
            {
                files = root.GetFiles("*.*");
            }
            // This is thrown if even one of the files requires permissions greater
            // than the application provides.
            catch (UnauthorizedAccessException e)
            {
                // This code just writes out the message and continues to recurse.
                // You may decide to do something different here. For example, you
                // can try to elevate your privileges and access the file again.
                log.Add(e.Message);
            }

            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }

            if (files != null)
            {
                foreach (System.IO.FileInfo fi in files) //search for files within the directories
                {
                    // In this example, we only access the existing FileInfo object. If we
                    // want to open, delete or modify the file, then
                    // a try-catch block is required here to handle the case
                    // where the file has been deleted since the call to TraverseTree().
                    if (fi.Name.Contains(".mp3"))
                    {
                        Console.WriteLine(fi.Name); //<--Uncomment this to write individual files in directories to Console
                    }

                    /*
                     * String s = fi.FullName;
                     */
                }

                // Now find all the subdirectories under this directory.
                subDirs = root.GetDirectories(); //<------HERE!!!!!

                /**/
                foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                {
                    // Resursive call for each subdirectory.
                    //Console.WriteLine(dirInfo.FullName);

                    /*
                     * WHEN CALLING WalkDirectoryTree(dirInfo) BELOW:
                     * The specified path, file name, or both are too long.
                     * The fully qualified file name must be less than 260 characters,
                     * and the directory name must be less than 248 characters.
                     */
                    WalkDirectoryTree(dirInfo); //<--Uncomment this to recurse through the next level of subdirectories
                }
                /**/
            }
예제 #48
0
        protected override void ProtectedConvert(IProcess process)
        {
            base.ProtectedConvert(process);

            process.Percent = 0;
            using (var context = Repository.GetEntityContext())
            {
                using (var tranc = context.OpenTransaction())
                {
                    var mangas = context.Get <IManga>().OrderBy(m => m.Id).ToList();
                    foreach (var manga in mangas)
                    {
                        process.Percent += 100.0 / mangas.Count;
                        if (mangaCreated.Any(c => c.Id == manga.Id))
                        {
                            continue;
                        }

                        DateTime?min = null;
                        if (firstRun && manga.Histories.Any())
                        {
                            min = manga.Histories.Min(h => h.Date);
                        }
                        if (firstRun && min == null)
                        {
                            var folder = new System.IO.DirectoryInfo(manga.GetAbsoulteFolderPath());
                            if (folder.Exists)
                            {
                                min = folder.CreationTime;
                            }
                        }
                        if (!firstRun && min == null)
                        {
                            if (!mangaCreated.Any())
                            {
                                min = GetDefaultDate();
                            }
                            if (min == null)
                            {
                                var before = mangaCreated.TakeWhile(m => m.Id < manga.Id).LastOrDefault();
                                var after  = mangaCreated.SkipWhile(m => m.Id < manga.Id).FirstOrDefault();
                                if (before == null && after == null)
                                {
                                    min = GetDefaultDate();
                                }
                                else if (before == null)
                                {
                                    min = after.Created - TimeSpan.FromSeconds(after.Id - manga.Id);
                                }
                                else if (after == null)
                                {
                                    min = before.Created + TimeSpan.FromSeconds(manga.Id - before.Id);
                                }
                                else
                                {
                                    var allowedSeconds = (after.Created - before.Created).TotalSeconds;
                                    var hasIds         = after.Id - before.Id;
                                    var period         = allowedSeconds / hasIds;
                                    min = before.Created.AddSeconds(period * (manga.Id - before.Id));
                                }
                            }
                            Log.Add($"Манге {manga.Name} не удалось найти примерную дату добавления, проставлена {min}.");
                        }
                        if (min != null)
                        {
                            mangaCreated.Add(new MangaProxy(manga.Id, min.Value));
                        }
                        else
                        {
                            hasEmptyRecords = true;
                        }
                        if (manga.Created == null || manga.Created > min)
                        {
                            manga.Created = min;
                            context.SaveOrUpdate(manga);
                        }
                    }
                    tranc.Commit();
                }
            }

            if (hasEmptyRecords)
            {
                hasEmptyRecords = false;
                firstRun        = false;
                ProtectedConvert(process);
            }
        }
        public ResultOperation SaveFile(System.IO.Stream inputStream, string fileName, Guid?entityID, Guid?entityDefID, Guid documentDefID, string captionOF, bool replace)
        {
            ResultOperation resultOperation = new ResultOperation();

            if (inputStream == null || inputStream.Length <= 0)
            {
                return(resultOperation);
            }
            sysBpmsDocument    PostDocument = null;
            sysBpmsDocumentDef documentDef  = new DocumentDefService(base.UnitOfWork).GetInfo(documentDefID);

            try
            {
                Guid   Guid = System.Guid.NewGuid();
                string fe   = System.IO.Path.GetExtension(fileName).Trim('.').ToLower();
                if (!string.IsNullOrWhiteSpace(documentDef.ValidExtentions) &&
                    !documentDef.ValidExtentions.ToStringObj().Trim().ToLower().Split(',').Any(c => c.Trim('.') == fe))
                {
                    resultOperation.AddError(string.Format(LangUtility.Get("FileNotValid.Text", "Engine"), documentDef.DisplayName));
                    return(resultOperation);
                }
                if (documentDef.MaxSize > 0 && documentDef.MaxSize * 1024 < inputStream.Length)
                {
                    resultOperation.AddError(string.Format(LangUtility.Get("FileSizeError.Text", "Engine"), documentDef.DisplayName));
                    return(resultOperation);
                }
                if (!System.IO.Directory.Exists(BPMSResources.FilesRoot.Trim('\\')))
                {
                    System.IO.DirectoryInfo DirectoryInfoObject = System.IO.Directory.CreateDirectory(BPMSResources.FilesRoot.Trim('\\'));
                }

                using (System.IO.FileStream saveStream = System.IO.File.Create(BPMSResources.FilesRoot.Trim('\\') + "\\" + Guid))
                {
                    byte[] bytes  = new byte[1024];
                    int    lenght = 0;
                    while ((lenght = inputStream.Read(bytes, 0, bytes.Length)) > 0)
                    {
                        saveStream.Write(bytes, 0, lenght);
                    }
                }

                PostDocument = new sysBpmsDocument()
                {
                    IsDeleted     = false,
                    AtachDateOf   = DateTime.Now,
                    CaptionOf     = string.IsNullOrWhiteSpace(captionOF) ? documentDef.DisplayName : captionOF,
                    EntityID      = entityID,
                    EntityDefID   = entityDefID,
                    DocumentDefID = documentDefID,
                    FileExtention = fe,
                    GUID          = Guid,
                    ThreadID      = base.EngineSharedModel.CurrentThreadID,
                };

                if (replace)
                {
                    var _Document = this.DocumentService.GetList(documentDefID, entityDefID, entityID, "", false, null, null).FirstOrDefault();
                    if (_Document != null)
                    {
                        _Document.IsDeleted = true;
                        this.DocumentService.Update(_Document);
                    }
                }
                this.DocumentService.Add(PostDocument);
            }
            catch
            {
                resultOperation.AddError(LangUtility.Get("FileSaveError.Text", "Engine"));
            }
            resultOperation.CurrentObject = PostDocument;
            return(resultOperation);
        }
예제 #50
0
        /// <summary>
        /// Update the directory on disk with the current name and location of the album. A new directory is
        /// created for new albums, and the directory is moved to the location specified by FullPhysicalPath if
        /// that property is different than FullPhysicalPathOnDisk.
        /// </summary>
        /// <param name="album">The album to persist to disk.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="album" /> is null.</exception>
        private static void PersistToFileSystemStore(IAlbum album)
        {
            if (album == null)
            {
                throw new ArgumentNullException("album");
            }

            if (album.IsRootAlbum)
            {
                return;                 // The directory for the root album is the media objects path, whose existence has already been verified by other code.
            }

            if (album.IsNew)
            {
                System.IO.Directory.CreateDirectory(album.FullPhysicalPath);

                IGallerySettings gallerySetting = Factory.LoadGallerySetting(album.GalleryId);

                // Create directory for thumbnail cache, if needed.
                string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPath, gallerySetting.FullThumbnailPath, gallerySetting.FullMediaObjectPath);
                if (thumbnailPath != album.FullPhysicalPath)
                {
                    System.IO.Directory.CreateDirectory(thumbnailPath);
                }

                // Create directory for optimized image cache, if needed.
                string optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPath, gallerySetting.FullOptimizedPath, gallerySetting.FullMediaObjectPath);
                if (optimizedPath != album.FullPhysicalPath)
                {
                    System.IO.Directory.CreateDirectory(optimizedPath);
                }
            }
            else if (album.FullPhysicalPathOnDisk != album.FullPhysicalPath)
            {
                // We need to move the directory to its new location or change its name. Verify that the containing directory doesn't already
                // have a directory with the new name. If it does, alter it slightly to make it unique.
                System.IO.DirectoryInfo di = System.IO.Directory.GetParent(album.FullPhysicalPath);

                IGallerySettings gallerySetting = Factory.LoadGallerySetting(album.GalleryId);

                string newDirName = HelperFunctions.ValidateDirectoryName(di.FullName, album.DirectoryName, gallerySetting.DefaultAlbumDirectoryNameLength);
                if (album.DirectoryName != newDirName)
                {
                    album.DirectoryName = newDirName;
                }

                // Now we are guaranteed to have a "safe" directory name, so proceed with the move/rename.
                System.IO.Directory.Move(album.FullPhysicalPathOnDisk, album.FullPhysicalPath);

                // Rename directory for thumbnail cache, if needed.
                string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPath, gallerySetting.FullThumbnailPath, gallerySetting.FullMediaObjectPath);
                if (thumbnailPath != album.FullPhysicalPath)
                {
                    string currentThumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPathOnDisk, gallerySetting.FullThumbnailPath, gallerySetting.FullMediaObjectPath);

                    RenameDirectory(currentThumbnailPath, thumbnailPath);
                }

                // Rename directory for optimized image cache, if needed.
                string optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPath, gallerySetting.FullOptimizedPath, gallerySetting.FullMediaObjectPath);
                if (optimizedPath != album.FullPhysicalPath)
                {
                    string currentOptimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(album.FullPhysicalPathOnDisk, gallerySetting.FullOptimizedPath, gallerySetting.FullMediaObjectPath);

                    RenameDirectory(currentOptimizedPath, optimizedPath);
                }
            }
        }
 public PhysicalDirectoryInfo(System.IO.DirectoryInfo info)
 {
 }
        void OnGUI()
        {
            EditorGUILayout.HelpBox("The tool will serialize scene  generating a new cooked scene and label scene assets  automatically.Then, you can use SceneBuilder tool to build these assets!", MessageType.Info);

            if (GUILayout.Button("Serialize Scene"))
            {
                string SceneOriginalName = EditorSceneManager.GetActiveScene().name;
                #region Save As New Scene
                EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), "Assets/Res/Cooked/Scene/" + SceneOriginalName + "_Cooked.unity", true);
                EditorSceneManager.OpenScene("Assets/Res/Cooked/Scene/" + SceneOriginalName + "_Cooked.unity");
                #endregion

                GameObject[]      SceneObjects            = GameObject.FindObjectsOfType <GameObject>();
                List <GameObject> ScenePrefabsGameObjects = new List <GameObject>();

                int SerializedID = 0;

                foreach (GameObject sceneObject in SceneObjects)
                {
                    GameObject PrefabRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(sceneObject); //场景中物体父对象

                    if (PrefabRoot == null)
                    {
                        continue;
                    }

                    if (PrefabUtility.GetPrefabAssetType(PrefabRoot) != PrefabAssetType.NotAPrefab)
                    {
                        if (PrefabRoot.tag == "NotAllowBuild")
                        {
                            continue;
                        }

                        if (ScenePrefabsGameObjects.Contains(PrefabRoot))
                        {
                            Debug.Log(PrefabRoot.name + "Built");
                            continue;
                        }
                        SerializedID += 1;
                        #region Genrerate new ReplaceObject with SceneAssetPrefab.cs
                        GameObject ReplaceObject = new GameObject(PrefabRoot.name + "_CookedResource");

                        ReplaceObject.transform.position   = PrefabRoot.transform.position;
                        ReplaceObject.transform.rotation   = PrefabRoot.transform.rotation;
                        ReplaceObject.transform.localScale = PrefabRoot.transform.localScale;

                        ReplaceObject.transform.SetParent(PrefabRoot.transform.parent);

                        ReplaceObject.isStatic = PrefabRoot.isStatic;
                        //ReplaceObject.layer = PrefabRoot.layer;
                        //ReplaceObject.transform.tag = PrefabRoot.transform.tag;

                        #region SetUp SceneAssetPrefab
                        SceneAssetPrefab sceneAssetPrefab = ReplaceObject.AddComponent <SceneAssetPrefab>();
                        List <SceneAssetPrefab.MeshParameter> MeshParameters = new List <SceneAssetPrefab.MeshParameter>();
                        #region Save LightMap data
                        if (PrefabRoot.GetComponentsInChildren <ParticleSystem>().Length > 0)
                        {
                            sceneAssetPrefab.HasParticleSystem = true;
                        }

                        if (PrefabRoot.GetComponentsInChildren <MeshRenderer>().Length > 0)
                        {
                            foreach (MeshRenderer meshRender in PrefabRoot.GetComponentsInChildren <MeshRenderer>())
                            {
                                SceneAssetPrefab.MeshParameter MeshParameter = new SceneAssetPrefab.MeshParameter();
                                if (meshRender.transform == PrefabRoot.transform)
                                {
                                    MeshParameter.RendererPathinChild = false;
                                }
                                else
                                {
                                    MeshParameter.RendererPathinChild = true;
                                    Transform Current = meshRender.transform;

                                    string        ChildPath = "";
                                    List <string> Relation  = new List <string>();
                                    while (Current != PrefabRoot.transform)
                                    {
                                        Relation.Add(Current.name);
                                        Current = Current.parent;
                                    }
                                    for (int i = Relation.Count - 1; i >= 0; i--)
                                    {
                                        ChildPath += Relation[i] + "/";
                                    }
                                    MeshParameter.RendererPath = ChildPath;
                                }
                                MeshParameter.LightingMapIndex        = meshRender.lightmapIndex;
                                MeshParameter.LightingMapTilingOffset = meshRender.lightmapScaleOffset;
                                MeshParameter.reflectionusage         = meshRender.reflectionProbeUsage;
                                MeshParameters.Add(MeshParameter);
                            }
                        }
                        //if (PrefabUtility.GetCorrespondingObjectFromSource(PrefabRoot) == null)
                        //{
                        //    Debug.Log(PrefabRoot.name);
                        //}
                        sceneAssetPrefab.assetName          = PrefabUtility.GetCorrespondingObjectFromSource(PrefabRoot).name;
                        sceneAssetPrefab.meshParameters     = MeshParameters.ToArray();
                        sceneAssetPrefab.SerializedID       = SerializedID;
                        sceneAssetPrefab.assetBundleName    = AssetNameCorretor(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(PrefabRoot))));
                        sceneAssetPrefab.assetBundleVariant = "sceneobject";
                        #endregion
                        #endregion



                        #endregion

                        if (!ScenePrefabsGameObjects.Contains(PrefabRoot))
                        {
                            ScenePrefabsGameObjects.Add(PrefabRoot);
                        }
                    }
                }
                List <GameObject> GameObjectsInAsset = new List <GameObject>();
                foreach (GameObject scenePrefab in ScenePrefabsGameObjects)
                {
                    GameObject GameObjectInAsset = PrefabUtility.GetCorrespondingObjectFromSource(scenePrefab) as GameObject;
                    if (!GameObjectsInAsset.Contains(GameObjectInAsset))
                    {
                        GameObjectsInAsset.Add(GameObjectInAsset);
                    }
                }

                SceneData sceneData = ScriptableObject.CreateInstance <SceneData>();
                sceneData.SceneObjectReferences = GameObjectsInAsset.ToArray();
                System.IO.DirectoryInfo Dir = System.IO.Directory.CreateDirectory("Assets/Cooks/Map/");

                AssetDatabase.CreateAsset(sceneData, "Assets/Cooks/Map/" + SceneOriginalName + ".asset");
                AssetDatabase.SaveAssets();
                EditorUtility.FocusProjectWindow();
                Selection.activeObject = sceneData;

                foreach (GameObject scenePrefab in ScenePrefabsGameObjects)
                {
                    //if (scenePrefab != null && !Reimported.Contains(PrefabUtility.GetPrefabParent(scenePrefab)))
                    //{
                    //    Reimported.Add(PrefabUtility.GetPrefabParent(scenePrefab));

                    //    Debug.Log(scenePrefab.name + "Asset Reimported!");
                    //    AssetImporter assetImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(scenePrefab)));
                    //    string AssetPathToGUID = AssetNameCorretor(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(scenePrefab))));

                    //    assetImporter.assetBundleName = AssetPathToGUID;
                    //    assetImporter.assetBundleVariant = "sceneobject";


                    //}
                    DestroyImmediate(scenePrefab);
                }
                EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
                EditorSceneManager.SaveOpenScenes();
                string AllScenes = "\n Current Active Scenes:";
                bool   AddFlag   = true;

                for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
                {
                    AllScenes += "\n -" + EditorBuildSettings.scenes[i].path;
                    if (EditorBuildSettings.scenes[i].path == EditorSceneManager.GetActiveScene().path)
                    {
                        AddFlag = false;
                    }
                }
                if (AddFlag)
                {
                    if (EditorUtility.DisplayDialog("Add to BuildSetting", "Do you want to add this cooked scene to BuildSetting?" + AllScenes, "Yes", "No,Thanks"))
                    {
                        EditorBuildSettingsScene[] original    = EditorBuildSettings.scenes;
                        EditorBuildSettingsScene[] newSettings = new EditorBuildSettingsScene[original.Length + 1];
                        System.Array.Copy(original, newSettings, original.Length);
                        newSettings[newSettings.Length - 1] = new EditorBuildSettingsScene(EditorSceneManager.GetActiveScene().path, true);
                        EditorBuildSettings.scenes          = newSettings;
                    }
                }

                EditorUtility.ClearProgressBar();


                //EditorSceneManager.SaveOpenScenes ();
            }
        }
예제 #53
0
        private static void QueryFilesBySize()
        {
            string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\";

            // Take a snapshot of the file system.
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);

            // This method assumes that the application has discovery permissions
            // for all folders under the specified path.
            IEnumerable <System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

            //Return the size of the largest file
            long maxSize =
                (from file in fileList
                 let len = GetFileLength(file)
                           select len)
                .Max();

            Console.WriteLine("The length of the largest file under {0} is {1}",
                              startFolder, maxSize);

            // Return the FileInfo object for the largest file
            // by sorting and selecting from beginning of list
            System.IO.FileInfo longestFile =
                (from file in fileList
                 let len = GetFileLength(file)
                           where len > 0
                           orderby len descending
                           select file)
                .First();

            Console.WriteLine("The largest file under {0} is {1} with a length of {2} bytes",
                              startFolder, longestFile.FullName, longestFile.Length);

            //Return the FileInfo of the smallest file
            System.IO.FileInfo smallestFile =
                (from file in fileList
                 let len = GetFileLength(file)
                           where len > 0
                           orderby len ascending
                           select file).First();

            Console.WriteLine("The smallest file under {0} is {1} with a length of {2} bytes",
                              startFolder, smallestFile.FullName, smallestFile.Length);

            //Return the FileInfos for the 10 largest files
            // queryTenLargest is an IEnumerable<System.IO.FileInfo>
            var queryTenLargest =
                (from file in fileList
                 let len = GetFileLength(file)
                           orderby len descending
                           select file).Take(10);

            Console.WriteLine("The 10 largest files under {0} are:", startFolder);

            foreach (var v in queryTenLargest)
            {
                Console.WriteLine("{0}: {1} bytes", v.FullName, v.Length);
            }


            // Group the files according to their size, leaving out
            // files that are less than 200000 bytes.
            var querySizeGroups =
                from file in fileList
                let len = GetFileLength(file)
                          where len > 0
                          group file by(len / 100000) into fileGroup
                              where fileGroup.Key >= 2
                          orderby fileGroup.Key descending
                          select fileGroup;


            foreach (var filegroup in querySizeGroups)
            {
                Console.WriteLine(filegroup.Key.ToString() + "00000");
                foreach (var item in filegroup)
                {
                    Console.WriteLine("\t{0}: {1}", item.Name, item.Length);
                }
            }
        }
예제 #54
0
 public FileItemDirectory(System.IO.DirectoryInfo dir) : this(dir, new StorageConfig())
 {
 }
예제 #55
0
        public virtual void  TestLazyPerformance()
        {
            System.String           tmpIODir = AppSettings.Get("tempDir", "");
            System.String           userName = System.Environment.UserName;
            System.String           path     = tmpIODir + System.IO.Path.DirectorySeparatorChar.ToString() + "lazyDir" + userName;
            System.IO.DirectoryInfo file     = new System.IO.DirectoryInfo(path);
            _TestUtil.RmDir(file);
            FSDirectory tmpDir = FSDirectory.Open(file);

            Assert.IsTrue(tmpDir != null);

            IndexWriter writer = new IndexWriter(tmpDir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);

            writer.UseCompoundFile = false;
            writer.AddDocument(testDoc);
            writer.Close();

            Assert.IsTrue(fieldInfos != null);
            FieldsReader  reader;
            long          lazyTime       = 0;
            long          regularTime    = 0;
            int           length         = 50;
            ISet <string> lazyFieldNames = Support.Compatibility.SetFactory.CreateHashSet <string>();

            lazyFieldNames.Add(DocHelper.LARGE_LAZY_FIELD_KEY);
            SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(Support.Compatibility.SetFactory.CreateHashSet <string>(), lazyFieldNames);

            for (int i = 0; i < length; i++)
            {
                reader = new FieldsReader(tmpDir, TEST_SEGMENT_NAME, fieldInfos);
                Assert.IsTrue(reader != null);
                Assert.IsTrue(reader.Size() == 1);

                Document doc;
                doc = reader.Doc(0, null); //Load all of them
                Assert.IsTrue(doc != null, "doc is null and it shouldn't be");
                IFieldable field = doc.GetFieldable(DocHelper.LARGE_LAZY_FIELD_KEY);
                Assert.IsTrue(field.IsLazy == false, "field is lazy");
                System.String value_Renamed;
                long          start;
                long          finish;
                start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
                //On my machine this was always 0ms.
                value_Renamed = field.StringValue;
                finish        = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
                Assert.IsTrue(value_Renamed != null, "value is null and it shouldn't be");
                Assert.IsTrue(field != null, "field is null and it shouldn't be");
                regularTime += (finish - start);
                reader.Dispose();
                reader = null;
                doc    = null;
                //Hmmm, are we still in cache???
                System.GC.Collect();
                reader = new FieldsReader(tmpDir, TEST_SEGMENT_NAME, fieldInfos);
                doc    = reader.Doc(0, fieldSelector);
                field  = doc.GetFieldable(DocHelper.LARGE_LAZY_FIELD_KEY);
                Assert.IsTrue(field.IsLazy == true, "field is not lazy");
                start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
                //On my machine this took around 50 - 70ms
                value_Renamed = field.StringValue;
                finish        = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
                Assert.IsTrue(value_Renamed != null, "value is null and it shouldn't be");
                lazyTime += (finish - start);
                reader.Dispose();
            }
            System.Console.Out.WriteLine("Average Non-lazy time (should be very close to zero): " + regularTime / length + " ms for " + length + " reads");
            System.Console.Out.WriteLine("Average Lazy Time (should be greater than zero): " + lazyTime / length + " ms for " + length + " reads");
        }
예제 #56
0
            static void Main(string[] args)
            {
                // Create two identical or different temporary folders
                // on a local drive and change these file paths.
                string pathA = @"C:\TestDir";
                string pathB = @"C:\TestDir2";

                System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(pathA);
                System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(pathB);

                // Take a snapshot of the file system.
                IEnumerable <System.IO.FileInfo> list1 = dir1.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
                IEnumerable <System.IO.FileInfo> list2 = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

                //A custom file comparer defined below
                FileCompare myFileCompare = new FileCompare();

                // This query determines whether the two folders contain
                // identical file lists, based on the custom file comparer
                // that is defined in the FileCompare class.
                // The query executes immediately because it returns a bool.
                bool areIdentical = list1.SequenceEqual(list2, myFileCompare);

                if (areIdentical == true)
                {
                    Console.WriteLine("the two folders are the same");
                }
                else
                {
                    Console.WriteLine("The two folders are not the same");
                }

                // Find the common files. It produces a sequence and doesn't
                // execute until the foreach statement.
                var queryCommonFiles = list1.Intersect(list2, myFileCompare);

                if (queryCommonFiles.Count() > 0)
                {
                    Console.WriteLine("The following files are in both folders:");
                    foreach (var v in queryCommonFiles)
                    {
                        Console.WriteLine(v.FullName); //shows which items end up in result list
                    }
                }
                else
                {
                    Console.WriteLine("There are no common files in the two folders.");
                }

                // Find the set difference between the two folders.
                // For this example we only check one way.
                var queryList1Only = (from file in list1
                                      select file).Except(list2, myFileCompare);

                Console.WriteLine("The following files are in list1 but not list2:");
                foreach (var v in queryList1Only)
                {
                    Console.WriteLine(v.FullName);
                }

                // Keep the console window open in debug mode.
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
 internal static bool IsDirectoryMounted(System.IO.DirectoryInfo directory, System.Collections.Generic.IEnumerable <string> fstab)
 {
     throw null;
 }
예제 #58
0
 public FaultyFSDirectory(System.IO.DirectoryInfo dir)
 {
     fsDir = FSDirectory.Open(dir);
     interalLockFactory = fsDir.LockFactory;
 }
예제 #59
0
        protected override bool RunInternal(IRemoteClient client, RemoteCommandVerbOptions options)
        {
            CloneVerbOptions localOptions = options as CloneVerbOptions;

            if (localOptions.Path.Count > 1)
            {
                Printer.PrintError("#e#Error:## Clone path is invalid. Please specify a subfolder to clone in to or leave empty to clone into the current directory.");
                return(false);
            }

            // Choose target directory from server name or path
            if (localOptions.Path != null && localOptions.Path.Count == 1)
            {
                string subdir = localOptions.Path[0];
                if (!string.IsNullOrEmpty(subdir))
                {
                    System.IO.DirectoryInfo info;
                    try
                    {
                        info = new System.IO.DirectoryInfo(System.IO.Path.Combine(TargetDirectory.FullName, subdir));
                    }
                    catch
                    {
                        Printer.PrintError("#e#Error - invalid subdirectory \"{0}\"##", subdir);
                        return(false);
                    }
                    Printer.PrintMessage("Target directory: #b#{0}##.", info);
                    TargetDirectory = info;
                }
            }

            if (localOptions.QuietFail && new System.IO.DirectoryInfo(System.IO.Path.Combine(TargetDirectory.FullName, ".versionr")).Exists)
            {
                return(true);
            }

            try
            {
                var ws = Area.Load(TargetDirectory, Headless, localOptions.BreachContainment);
                if (ws != null)
                {
                    CloneVerbOptions cloneOptions = options as CloneVerbOptions;
                    if (cloneOptions != null && cloneOptions.QuietFail)
                    {
                        Printer.PrintMessage("Directory already contains a vault. Skipping.");
                        return(false);
                    }
                    Printer.PrintError("This command cannot function with an active Versionr vault.");
                    return(false);
                }
            }
            catch
            {
            }
            bool result = false;

            try
            {
                TargetDirectory.Create();
            }
            catch
            {
                Printer.PrintError("#e#Error - couldn't create subdirectory \"{0}\"##", TargetDirectory);
                return(false);
            }
            client.BaseDirectory = TargetDirectory;
            if (localOptions.Full.HasValue)
            {
                result = client.Clone(localOptions.Full.Value);
            }
            else
            {
                result = client.Clone(true);
                if (!result)
                {
                    result = client.Clone(false);
                }
            }
            if (result)
            {
                Printer.PrintMessage("Successfully cloned from remote vault. Initializing default remote.");
                string remoteName = "default";

                if (client.Workspace.SetRemote(client.URL, remoteName))
                {
                    Printer.PrintMessage("Configured remote \"#b#{0}##\" as: #b#{1}##", remoteName, client.URL);
                }

                if (localOptions.Partial != null)
                {
                    client.Workspace.SetPartialPath(localOptions.Partial);
                }

                if (localOptions.Update)
                {
                    client.Pull(false, string.IsNullOrEmpty(localOptions.Branch) ? client.Workspace.CurrentBranch.ID.ToString() : localOptions.Branch);
                    Area area = Area.Load(client.Workspace.Root);
                    area.Checkout(localOptions.Branch, false, false);
                }

                if (localOptions.Synchronize)
                {
                    return(client.SyncAllRecords());
                }
            }
            return(result);
        }
 public static bool IsVolumeMountedFolder(System.IO.DirectoryInfo directory)
 {
     throw null;
 }