Beispiel #1
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();
        }
        /// <param name="path">删除的文件的路径</param>
        /// <param name="date">删除某一个时间点以前的文件</param>
        /// <param name="fileType">文件类型</param>
        public static void Delete_TempFile(string path,int datePoint,string fileType)
        {
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(path);
            //DateTime time = DateTime.Now.AddDays(-datePoint);
            //该目录存在且有临时文件则进行删除处理
            if (dirInfo.Exists && dirInfo.GetFiles().Length > 0)
            {
                System.IO.FileInfo[] files = dirInfo.GetFiles();
                for (int i = 0; i < files.Length; i++)
                {
                    if (files[i].Exists)
                    {
                        try
                        {
                            //将该文件设置为临时文件
                            System.IO.File.SetAttributes(path + "//" + files[i].Name, System.IO.FileAttributes.Temporary);
                            //删除指定的文件
                            System.IO.File.Delete(path + "//" + files[i].Name);

                        }catch(System.IO.IOException ex)
                        {
                            throw ex;
                        }
                    }
                }
            }
        }
        public AjaxControlToolkit.Slide[] GetHomeSlides()
        {

            string imageFolder = HttpContext.Current.Server.MapPath(@"~/images/PictureGallery/HomePic");
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(imageFolder);
            AjaxControlToolkit.Slide[] slides = null;

            if (directory.Exists)
            {
                System.IO.FileInfo[] images = directory.GetFiles("*.jpg");
                slides = new AjaxControlToolkit.Slide[images.Length];

                int i = 0;

                foreach (System.IO.FileInfo image in images)
                {
                    string title = image.Name;
                    string imagePath = "/images/PictureGallery/HomePic/" + title;

                    slides[i] = new AjaxControlToolkit.Slide(imagePath, title, title);
                    i++;
                }
                ShuffleList(slides);
            }
            return (slides);
        }
        /*Server pagination with server option like server filteration and server sorting i.e serverFiltering: true, serverSorting: true,*/
        public JsonResult GetAllWithServerOptions(int skip, int take, int page, int pageSize, string group)
        {
            var sorterCollection = KendoGridSorterCollection.BuildCollection(Request);
            var filterCollection = KendoGridFilterCollection.BuildCollection(Request);

            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
            IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

            IEnumerable<System.IO.FileInfo> fulllist = (from file in fileList select file);
            /*IEnumerable<System.IO.FileInfo> fullfileinfo =
                (from file in fileList select file).Skip(skip).Take(take);*/
            var list = fulllist.Select(x => new
            {
                text = x.Name,
                value = x.Name
            });

            var filteredItems = list.MultipleFilter(filterCollection.Filters);
            var sortedItems = filteredItems.MultipleSort(sorterCollection.Sorters).ToList();
            var count = sortedItems.Count();
            var data = (from v in sortedItems.Skip((page - 1) * pageSize)
                            .Take(pageSize)
                        select v).ToList();

            return Json(
                new
                {
                    File = data,
                    TotalCount = count
                },
                JsonRequestBehavior.AllowGet); //alow get while using server grid
        }
		/// 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);
		        }
		      }
		   }
 /// <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;
 }
Beispiel #7
0
        //this actually decrypts
        public static string decrypt(string passed_data_store, int key_used, string passed_data)
        {
            string return_data = "error";
            System.IO.DirectoryInfo Keys_Dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(passed_data_store, "keys"));
            string blob = "";
            System.Security.Cryptography.RSACryptoServiceProvider provider = new System.Security.Cryptography.RSACryptoServiceProvider();

            foreach(System.IO.FileInfo File in Keys_Dir.GetFiles())
            {
                if (File.Name.Split('.')[0] == key_used.ToString())
                {

                    using (System.IO.StreamReader reader = File.OpenText())
                    {
                        blob = reader.ReadToEnd();

                        String[] str_arr = blob.Split('-');
                        byte[] encrypted_array = new byte[str_arr.Length];
                        for(int i = 0; i < str_arr.Length; i++) encrypted_array[i]=Convert.ToByte(str_arr[i], 16);
                        provider.ImportCspBlob(encrypted_array);

                        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

                        byte[] science = StringToByteArray(passed_data);
                        byte[] decrtpyerd_array = provider.Decrypt(science, false);
                        return Encoding.UTF8.GetString(decrtpyerd_array);
                    }
                }
            }
            Console.WriteLine("Can not find decryption key");
            return return_data;
        }
Beispiel #8
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();
        }
		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();
		}
Beispiel #10
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();
        }
Beispiel #11
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
        }
        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;
        }
        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);
        }
Beispiel #14
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;
        }
Beispiel #15
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");
             }
        }
		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
				);
		}
Beispiel #17
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 !
            }
        }
Beispiel #18
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;
        }
Beispiel #19
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;
        }
Beispiel #20
0
        static void Main()
        {
            try
            {
                Impersonate.ImpersonateNow();
            }
            catch
            {
                MessageBox.Show("Error establishing Windows authentication.");
                return;
            }
            try
            {
                if (System.IO.File.Exists("\\\\cba1.bus.ucf.edu/apps/current/CBA_Special_Use/Updater/TRC Application Update Service.exe"))
                    System.IO.File.Copy("\\\\cba1.bus.ucf.edu/apps/current/CBA_Special_Use/Updater/TRC Application Update Service.exe", Application.StartupPath + "/TRC Application Update Service.exe", true);
            }
            catch
            {
                MessageBox.Show("Cannot reach update server.");
            }

            try
            {

                //Check to see if photos directory exists
                if (System.IO.Directory.Exists(Application.StartupPath + "/Photos/") == false)
                {
                    System.IO.Directory.CreateDirectory(Application.StartupPath + "/Photos/");
                }
                else
                {
                    //Refresh Cache
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Application.StartupPath + "/Photos/");
                    foreach (System.IO.FileInfo files in dir.GetFiles())
                    {
                        if (!files.FullName.Contains("Generic.jpg"))
                            files.Delete();
                    }
                }

            }
            catch
            {
                MessageBox.Show("Error creating photo cache. Check read/write permissions.");
            }

            if (Authenticate())
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmMain());
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmMain(true));
            }
        }
Beispiel #21
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     var browser = new System.Windows.Forms.FolderBrowserDialog();
     browser.ShowDialog();
     var selectedDirectory = new System.IO.DirectoryInfo(browser.SelectedPath);
     var files = selectedDirectory.GetFiles();
     //MessageBox.Show("You chose: " + selectedDirectory + " containing " + files.Length + " files.");
     dataGridPictures.ItemsSource = files;
 }
Beispiel #22
0
        //-------------------------------------------------------------------------
        // Start the Form and look for the files .Statistics.log in the root
        // the two Listview are configured
        //-------------------------------------------------------------------------
        public FrmMain()
        {
            InitializeComponent();

            System.IO.DirectoryInfo o = new System.IO.DirectoryInfo(LocalRuta);
            System.IO.FileInfo[] myfiles = null;

            myfiles = o.GetFiles("*.statistics.log");
            for (int y = 0; y <= myfiles.Length - 1; y++)
            {
                cmb1.Items.Add(myfiles[y].Name);
            }

            var _with1 = Lst1;
            _with1.View = View.Details;
            _with1.FullRowSelect = true;
            _with1.GridLines = true;
            _with1.LabelEdit = false;
            _with1.Columns.Clear();
            _with1.Items.Clear();

            _with1.Columns.Add("", 0, HorizontalAlignment.Right);
            _with1.Columns.Add("Date", 145, HorizontalAlignment.Left);
            _with1.Columns.Add("Mission", 190, HorizontalAlignment.Left);
            _with1.Columns.Add("Time", 50, HorizontalAlignment.Right);
            _with1.Columns.Add("Isk Bounty", 100, HorizontalAlignment.Right);
            _with1.Columns.Add("Bounty/Min", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Isk Loot", 100, HorizontalAlignment.Right);
            _with1.Columns.Add("Loot/Min", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("LP", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("LP/Min", 60, HorizontalAlignment.Right);
            _with1.Columns.Add("Total ISK/Min", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Lost Drones", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Ammo Consumption", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Ammo Value", 80, HorizontalAlignment.Right);

            var _with2 = LstMision;
            _with2.View = View.Details;
            _with2.FullRowSelect = true;
            _with2.GridLines = true;
            _with2.LabelEdit = false;
            _with2.Columns.Clear();
            _with2.Items.Clear();

            _with2.Columns.Add("", 0, HorizontalAlignment.Right);
            _with2.Columns.Add("Mission", 240, HorizontalAlignment.Left);
            _with2.Columns.Add("Repet %", 60, HorizontalAlignment.Right);
            _with2.Columns.Add("Time", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media Isk Bounty", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media Isk Loot", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media LP", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media ISK/Min", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Lost Drones", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media Ammo Consumption", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media Ammo Value", 100, HorizontalAlignment.Right);
            return;
        }
Beispiel #23
0
 void init()
 {
     _logs.Items.Clear();
     System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(PATH);
     System.IO.FileInfo [] fis = di.GetFiles(WILDEXT, System.IO.SearchOption.TopDirectoryOnly);
     foreach (System.IO.FileInfo fi in fis)
         addname(fi.Name);
     Invalidate();
 }
        private Terminals.Integration.Import.IImport FindImportType(string Extension)
        {
            Terminals.Integration.Import.IImport import = null;
            if(Importers == null)
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
                string[] patterns = new string[] { "*.dll", "*.exe"};
                foreach(string pattern in patterns)
                {
                    foreach(System.IO.FileInfo fi in dir.GetFiles(pattern))
                    {
                        try
                        {
                            System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFile(fi.FullName);
                            if(asm != null)
                            {
                                foreach(Type t in asm.GetTypes())
                                {
                                    try
                                    {
                                        if(typeof(Terminals.Integration.Import.IImport).IsAssignableFrom(t) && t.IsClass)
                                        {
                                            if(Importers == null) Importers = new List<Type>();
                                            Importers.Add(t);
                                        }
                                    }
                                    catch (Exception exc) { Terminals.Logging.Log.Info("", exc); }
                                }
                            }
                        }
                        catch(Exception exc)
                        {
                            Terminals.Logging.Log.Info("", exc);
                            //do nothing
                        }

                    }
                }
            }
            if(Importers != null)
            {
                foreach(Type t in Importers)
                {
                    Terminals.Integration.Import.IImport i = (t.Assembly.CreateInstance(t.FullName) as Terminals.Integration.Import.IImport);
                    if(i != null && i.KnownExtension!=null)
                    {
                        if(i.KnownExtension == Extension)
                        {
                            import = i;
                            break;
                        }
                    }
                }
            }
            return import;
        }
        public static long GetStorageUsed(string userId)
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Path.Combine(transcodeFolder, userId));

            if(di.Exists)
            {
                return di.GetFiles().Sum(f => f.Length);
            }
            return 0;
        }
Beispiel #26
0
 private bool checkUpdate()
 {
     System.IO.DirectoryInfo _directory = new System.IO.DirectoryInfo(System.AppDomain.CurrentDomain.BaseDirectory);
     foreach (System.IO.FileInfo _file in _directory.GetFiles("*.xml")) {
         if (string.Compare(_file.Name, "install", true) == 0) {
             return true;
         }
     }
     return false;
 }
Beispiel #27
0
        public static string[] GetPublicURLFromFolder(string path, string extension)
        {
            System.IO.DirectoryInfo dinfo = new System.IO.DirectoryInfo(path);
            System.IO.FileInfo[] files = extension == "" ? dinfo.GetFiles() : dinfo.GetFiles("*." + extension);
            List<string> urls = new List<string>();


            foreach (System.IO.FileInfo file in files)
            {
                string s = file.FullName.Replace('\\', '/');
                s = String.Format(@"{0}/{1}/{2}",
                 System.Configuration.ConfigurationManager.AppSettings.Get("HttpPath"),
                System.Configuration.ConfigurationManager.AppSettings.Get("UserID"),
                Uri.EscapeUriString(s.Substring(s.IndexOf(System.Configuration.ConfigurationManager.AppSettings.Get("SyncDirectory")) +
                System.Configuration.ConfigurationManager.AppSettings.Get("SyncDirectory").Length + 1)));
                urls.Add(s);
            }

            return urls.ToArray();
        }
        public new RelaxedBundle IncludeDirectory(string directoryVirtualPath, string searchPattern, bool searchSubdirectories)
        {
            var truePath = HostingEnvironment.MapPath(directoryVirtualPath);
            if (truePath == null) return this;

            var dir = new System.IO.DirectoryInfo(truePath);
            if (!dir.Exists || dir.GetFiles(searchPattern).Length < 1) return this;

            base.IncludeDirectory(directoryVirtualPath, searchPattern);
            return this;
        }
        private static void TraverseFiles(string pathDirectory, XElement rootElement)
        {
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(pathDirectory);
            System.IO.FileInfo[] files = directory.GetFiles();

            foreach (var file in files)
            {
                XElement fileElement = new XElement("file", new XAttribute("name", file.Name));
                rootElement.Add(fileElement);
            }
        }
        protected override void BuildXml()
        {
            if ( !this.CurrentFolder.CheckAcl( AccessControlRules.FileView ) )
            {
                ConnectorException.Throw( Errors.Unauthorized );
            }

            // Map the virtual path to the local server path.
            string sServerDir = this.CurrentFolder.ServerPath ;
            bool bShowThumbs = Request.QueryString["showThumbs"] != null && Request.QueryString["showThumbs"].ToString().Equals( "1" ) ;

            // Create the "Files" node.
            XmlNode oFilesNode = XmlUtil.AppendElement( this.ConnectorNode, "Files" ) ;

            System.IO.DirectoryInfo oDir = new System.IO.DirectoryInfo( sServerDir ) ;
            System.IO.FileInfo[] aFiles = oDir.GetFiles() ;

            for ( int i = 0 ; i < aFiles.Length ; i++ )
            {
                System.IO.FileInfo oFile = aFiles[ i ];
                string sExtension = System.IO.Path.GetExtension( oFile.Name ) ;

                if ( Config.Current.CheckIsHiddenFile( oFile.Name ) )
                    continue;

                if ( !this.CurrentFolder.ResourceTypeInfo.CheckExtension( sExtension ) )
                    continue;

                Decimal iFileSize = Math.Round( (Decimal)oFile.Length / 1024 ) ;
                if ( iFileSize < 1 && oFile.Length != 0 ) iFileSize = 1 ;

                // Create the "File" node.
                XmlNode oFileNode = XmlUtil.AppendElement( oFilesNode, "File" ) ;
                XmlUtil.SetAttribute( oFileNode, "name", oFile.Name );
                XmlUtil.SetAttribute( oFileNode, "date", oFile.LastWriteTime.ToString( "yyyyMMddHHmm" ) );
                if ( Config.Current.Thumbnails.Enabled
                    && ( Config.Current.Thumbnails.DirectAccess || bShowThumbs )
                    && ImageTools.IsImageExtension( sExtension.TrimStart( '.' ) ) )
                {
                    bool bFileExists = false;
                    try
                    {
                        bFileExists = System.IO.File.Exists(System.IO.Path.Combine(this.CurrentFolder.ThumbsServerPath, oFile.Name));
                    }
                    catch {}

                    if ( bFileExists )
                        XmlUtil.SetAttribute( oFileNode, "thumb", oFile.Name ) ;
                    else if ( bShowThumbs )
                        XmlUtil.SetAttribute( oFileNode, "thumb", "?" + oFile.Name ) ;
                }
                XmlUtil.SetAttribute( oFileNode, "size", iFileSize.ToString( CultureInfo.InvariantCulture ) );
            }
        }
Beispiel #31
0
        private void loop()
        {
            //loopthread:macro Thread;
            while (true)
            {
                if (!loop_thread)
                {
                    set_unlock();
                    Thread.Sleep(1500);
                    continue;
                }
                Thread.Sleep(1500);
                set_value();
                SetWindowPos(hwnd, 0, 0, 0, 1280, 750, 2);
                ShowWindowAsync(hwnd, 1);
                SetForegroundWindow(hwnd);

                //image search algorhtm

                string filePath = "*50 img\\";
                Thread.Sleep(40);
                if (in_battle)
                {
                    //전투화면
                    string[] search = null;
                    filePath += "battle/";
                    String FolderName          = "img/battle";
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(FolderName);
                    String FileNameOnly        = "";
                    foreach (System.IO.FileInfo File in di.GetFiles())
                    {
                        if (File.Extension.ToLower().CompareTo(".png") == 0 || File.Extension.ToLower().CompareTo(".jpg") == 0)
                        {
                            FileNameOnly = File.Name.Substring(0, File.Name.Length);
                            //String FullFileName = File.FullName;
                            string temp = filePath + FileNameOnly;
                            search = UseImageSearch(temp, hwnd);
                            if (search == null)
                            {
                                continue;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    if (search == null)
                    {
                        //new_drop_check

                        /*Bitmap cap = PrintWindow(hwnd);
                         * RECT brt;
                         * GetWindowRect(hwnd, out brt);
                         * Bitmap ship_cap = crop(cap, new Rectangle(200, 130, 30, 270));      //new ship
                         * var ocr = new TesseractEngine("./tessdata", "jpn", EngineMode.Default);
                         * var texts = ocr.Process(ship_cap);
                         * if(texts.GetText().Equals("&&"))
                         * {
                         *  set_new_drop();
                         * }*/
                        //auto clicking
                        RECT brt;
                        GetWindowRect(hwnd, out brt);
                        SetCursorPos(brt.Left + 1190, brt.Top + 700);
                        SendMessage(hwnd, 0x0201, (IntPtr)0x00000001, (IntPtr)0);
                        SendMessage(hwnd, 0x0202, (IntPtr)0x00000000, (IntPtr)0);
                    }
                    else
                    {
                        //auto Button,drop_ship_unlock button,end check button
                        if (FileNameOnly.Equals("end.PNG"))
                        {
                            in_battle = false;
                            continue;
                        }
                        else if (FileNameOnly.Equals("drop_ship_unlock.PNG") && drop_check)
                        {
                            set_new_drop();
                        }
                        int[] search_ = new int[search.Length];
                        for (int j = 0; j < search.Length; j++)
                        {
                            search_[j] = Convert.ToInt32(search[j]);
                        }
                        SetCursorPos(search_[1] + (search_[3] / 2), search_[2] + (search_[4] / 2));
                        SendMessage(hwnd, 0x0201, (IntPtr)0x00000001, (IntPtr)0);
                        SendMessage(hwnd, 0x0202, (IntPtr)0x00000000, (IntPtr)0);
                    }
                    continue;
                }
                //통상화면
                if (oil_check)
                {
                    //oil_check
                    if (oil_val.Equals(""))
                    {
                        loop_thread = false;
                        MessageBox.Show("최저연료가 입력되지 않았습니다.");
                        continue;
                    }
                    Bitmap cap = PrintWindow(hwnd);
                    RECT   brt;
                    GetWindowRect(hwnd, out brt);
                    cap = crop(cap, new Rectangle(770, 30, 80, 50));    //oil check
                    try
                    {
                        var ocr   = new TesseractEngine("./tessdata", "eng", EngineMode.TesseractAndCube);
                        var texts = ocr.Process(cap);
                        if (texts.GetText().Equals(""))
                        {
                            //nothing
                        }
                        else if (Int32.Parse(oil_val) > Int32.Parse(texts.GetText()))
                        {
                            loop_thread = false;
                            continue;
                        }
                    }
                    catch
                    {
                        //tessract error
                    }
                }
                if (drop_check)
                {
                    //drop_ship_check
                    if (drop_val.Equals("0"))
                    {
                        loop_thread = false;
                        continue;
                    }
                    else if (drop_val.Equals(""))
                    {
                        MessageBox.Show("드랍수를 입력하지 않았습니다.");
                        loop_thread = false;
                        continue;
                    }
                }
                try
                {
                    string[] search = null;
                    if (stage_val.Equals(""))
                    {
                        MessageBox.Show("해역이 선택되지 않았습니다.");
                        loop_thread = false;
                        continue;
                    }
                    filePath += "stage/";
                    string temp  = filePath + stage_val + ".png";   //stage select
                    string temp2 = filePath + "start.png";          //start button
                    search = UseImageSearch(temp, hwnd);
                    if (search == null)
                    {
                        search = UseImageSearch(temp2, hwnd);
                        if (search == null)
                        {
                            continue;
                        }
                        else
                        {
                            //temp2
                            in_battle = true;
                            int[] search_ = new int[search.Length];
                            for (int j = 0; j < search.Length; j++)
                            {
                                search_[j] = Convert.ToInt32(search[j]);
                            }
                            SetCursorPos(search_[1] + (search_[3] / 2), search_[2] + (search_[4] / 2));
                        }
                    }
                    else
                    {
                        //select stage
                        int[] search_ = new int[search.Length];
                        for (int j = 0; j < search.Length; j++)
                        {
                            search_[j] = Convert.ToInt32(search[j]);
                        }
                        SetCursorPos(search_[1] + (search_[3] / 2) - 100, search_[2] + (search_[4] / 2));
                    }
                    SendMessage(hwnd, 0x0201, (IntPtr)0x00000001, (IntPtr)0);
                    SendMessage(hwnd, 0x0202, (IntPtr)0x00000000, (IntPtr)0);
                }
                catch
                {
                }
                finally
                {
                }
            }
        }
Beispiel #32
0
        //public const string SAVE_DIR = "results/";

        public static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            int  gameMode, numGames, numThreads;
            bool parallel, saveCards;


            if (args.Length == 6)
            {
                //Assuming the input is correct
                gameMode   = Int16.Parse(args[0]);
                numGames   = Int16.Parse(args[1]);
                parallel   = Boolean.Parse(args[2]);
                numThreads = Int16.Parse(args[3]);
                saveCards  = Boolean.Parse(args[5]);
            }
            else
            {
                Console.WriteLine("Unspecified parameters. The program will use default parameters.");
                gameMode   = GAMEMODE;
                numGames   = NUMGAMES;
                parallel   = PARALLEL;
                numThreads = NUM_THREADS;
                saveCards  = SAVE_CARDS;
            }

            int firstTeamWins = 0, secondTeamWins = 0, draws = 0, nullGames = 0;

            //Shared data between threads!
            List <List <int>[]> cardsPerPlayer     = new List <List <int>[]>(numGames);
            List <int>          trumps             = new List <int>(numGames);
            List <int>          firstPlayers       = new List <int>(numGames);
            List <int>          finalBotTeamPoints = new List <int>(numGames);
            List <ulong[]>      timePerTrick       = new List <ulong[]>(numGames);
            Object allGamesLock                    = new Object();

            Console.WriteLine("");
            Console.WriteLine("|||||||||||||||||||| SUECA TEST WAR ||||||||||||||||||||");
            Console.WriteLine("");
            switch (gameMode)
            {
            case 1:
                Console.WriteLine("Mode 1 (1 RuleBased 3 Random)");
                break;

            case 2:
                Console.WriteLine("Mode 2 (1 TrickPlayer 3 RuleBased)");
                break;

            case 3:
                Console.WriteLine("Mode 3 (1 Smart 3 RuleBased)");
                break;

            case 4:
                Console.WriteLine("Mode 4 (1 TimeLimited 3 RuleBased)");
                break;

            case 5:
                Console.WriteLine("Mode 5 (1 RBO 3 RuleBased)");
                break;

            case 6:
                Console.WriteLine("Mode 6 (1 Hybrid 3 RuleBased)");
                break;

            default:
                break;
            }
            Console.WriteLine("#Games: " + numGames);


            if (parallel)
            {
                Parallel.For(0, numGames,
                             new ParallelOptions {
                    MaxDegreeOfParallelism = numThreads
                },
                             () => new int[4],

                             (int i, ParallelLoopState state, int[] localCount) =>
                {
                    return(processGames(i,
                                        localCount,
                                        gameMode,
                                        cardsPerPlayer,
                                        trumps,
                                        firstPlayers,
                                        finalBotTeamPoints,
                                        timePerTrick,
                                        allGamesLock));
                },

                             (int[] localCount) =>
                {
                    draws          += localCount[0];
                    firstTeamWins  += localCount[1];
                    secondTeamWins += localCount[2];
                    nullGames      += localCount[3];
                });
            }
            else
            {
                for (int i = 0; i < numGames; i++)
                {
                    int[] localCount = new int[14];
                    processGames(i,
                                 localCount,
                                 gameMode,
                                 cardsPerPlayer,
                                 trumps,
                                 firstPlayers,
                                 finalBotTeamPoints,
                                 timePerTrick,
                                 allGamesLock);
                    draws          += localCount[0];
                    firstTeamWins  += localCount[1];
                    secondTeamWins += localCount[2];
                    nullGames      += localCount[3];
                }
            }


            if (saveCards)
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(SAVE_DIR);
                int count = dir.GetFiles("log*.txt").Length;
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(SAVE_DIR + "log" + count + ".txt"))
                {
                    file.WriteLine("Mode: " + GAMEMODE + " #Games: " + numGames);

                    file.WriteLine("p0_0\tp0_1\tp0_2\tp0_3\tp0_4\tp0_5\tp0_6\tp0_7\tp0_8\tp0_9\t"
                                   + "p2_0\tp2_1\tp2_2\tp2_3\tp2_4\tp2_5\tp2_6\tp2_7\tp2_8\tp2_9\t"
                                   + "trump\tfirst\tfp\t"
                                   + "t_t0\tt_t1\tt_t2\tt_t3\tt_t4\tt_t5\tt_t6\tt_t7\tt_t8\tt_t9");
                    for (int i = 0; i < numGames; i++)
                    {
                        for (int k = 0; k < 4; k = k + 2)
                        {
                            for (int j = 0; j < 10; j++)
                            {
                                file.Write(cardsPerPlayer[i][k][j] + "\t");
                            }
                        }
                        file.Write(trumps[i] + "\t");
                        file.Write(firstPlayers[i] + "\t");
                        file.Write(finalBotTeamPoints[i] + "\t");
                        for (int l = 0; l < timePerTrick[i].Length; l++)
                        {
                            file.Write(timePerTrick[i][l] + "\t");
                        }
                        file.WriteLine("");
                    }
                }
            }


            Console.WriteLine("");
            Console.WriteLine("----------------- Summary -----------------");
            Console.WriteLine("FirstTeam won " + firstTeamWins + "/" + numGames);
            Console.WriteLine("SecondTeam 1 won " + secondTeamWins + "/" + numGames);
            Console.WriteLine("Draws " + draws + "/" + numGames);
            Console.WriteLine("Null Games " + nullGames);

            sw.Stop();
            Console.WriteLine("Total Time taken by functions is {0} seconds", sw.ElapsedMilliseconds / 1000);  //seconds
            Console.WriteLine("Total Time taken by functions is {0} minutes", sw.ElapsedMilliseconds / 60000); //minutes
            Console.ReadLine();
        }
Beispiel #33
0
        /// <summary>
        /// 获取配置图片
        /// </summary>
        /// <param name="requestParams"></param>
        /// <returns></returns>
        public object POST([FromBody] JObject requestParams)
        {
            var source   = requestParams.Property("source", true);
            var type     = requestParams.Property("type", true);
            var ratio    = requestParams.Property("ratio", true);
            var position = requestParams.Property("position", true);

            //var screenWidth = Request.Headers.GetCookies();
            if (source.IsNullOrEmpty())
            {
                throw new MessageException("来源不能为空!");
            }
            if (type.IsNullOrEmpty())
            {
                throw new MessageException("类型不能为空!");
            }
            if (position.IsNullOrEmpty())
            {
                throw new MessageException("位置不能为空!");
            }

            var list = new List <object>();
            var url  = Request.GetUrlHelper().Content("~/Images/app/");

            var version = Theme;

            if (string.Equals(source, "APP", StringComparison.CurrentCultureIgnoreCase))
            {
                string width = "", height = "";
                if (string.Equals(type, "Android", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (ratio.IsNullOrEmpty())
                    {
                        ratio = "640x960";
                    }
                    if (ratio.StartsWith("640x", StringComparison.CurrentCultureIgnoreCase))
                    {
                        type = "android640";
                    }
                }
                if (string.Equals(type, "IOS", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (ratio.IsNullOrEmpty())
                    {
                        ratio = "750x1334";
                    }
                    if (ratio.StartsWith("750x", StringComparison.CurrentCultureIgnoreCase))
                    {
                        type = "ios640";
                    }
                    else if (ratio.StartsWith("1080x", StringComparison.CurrentCultureIgnoreCase))
                    {
                        type = "ios960";
                    }
                }
                var path = GetImagePath(type);
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
                var bllset   = new SysWebSettingBLL();
                var set      = bllset.GetWebSetting();
                var sip      = Pharos.Utility.Config.GetAppSettings("ServerIP");
                var prefix   = type + "/" + version + "/";
                var filename = GetImageBySet(set, position, type);
                if (!filename.IsNullOrEmpty() && !sip.IsNullOrEmpty())
                {
                    url    = sip;
                    prefix = "SysImg/" + Sys.SysCommonRules.CompanyId + "/";
                }
                if (string.Equals(position, "sysLogo", StringComparison.CurrentCultureIgnoreCase))
                {
                    url += prefix + (filename.IsNullOrEmpty() ? "login_sysLogo.png" : filename) + "?t=" + DateTime.Now.ToLongTimeString();
                    list.Add(new { Url = url, Width = width, Height = height });
                }
                else if (string.Equals(position, "sysLogo2", StringComparison.CurrentCultureIgnoreCase))
                {
                    url += prefix + (filename.IsNullOrEmpty() ?"index_sysLogo.png":filename);
                    list.Add(new { Url = url, Width = width, Height = height });
                }
                else if (string.Equals(position, "sysLoginBj", StringComparison.CurrentCultureIgnoreCase))
                {
                    var    files  = dir.GetFiles("login_bg_*");
                    Random random = new Random();
                    var    idx    = random.Next(0, files.Count());
                    url += prefix + (files.Any() ? files[idx].Name : "");
                    list.Add(new { Url = url, Width = width, Height = height });
                }
                else if (string.Equals(position, "indexTop", StringComparison.CurrentCultureIgnoreCase))
                {
                    url += prefix + (filename.IsNullOrEmpty() ?"index_bg.png":filename) + "?t=" + DateTime.Now.ToLongTimeString();
                    list.Add(new { Url = url, Width = width, Height = height });
                }
                else if (string.Equals(position, "consumerLogo", StringComparison.CurrentCultureIgnoreCase))
                {
                    url += prefix + (filename.IsNullOrEmpty() ? "db_logo.png":filename);
                    list.Add(new { Url = url, Width = width, Height = height });
                }
                else if (string.Equals(position, "indexAdv", StringComparison.CurrentCultureIgnoreCase))
                {
                    var files = dir.GetFiles("index_slides_*");
                    foreach (var fs in files)
                    {
                        list.Add(new { Url = url + prefix + fs.Name, Width = width, Height = height });
                    }
                }
            }

            return(list);
        }
Beispiel #34
0
        public void Restore(string backupName)
        {
            string Carpeta = backupName + System.IO.Path.DirectorySeparatorChar;

            Lfx.Environment.Folders.EnsurePathExists(this.BackupPath);

            if (Carpeta != null && Carpeta.Length > 0 && System.IO.Directory.Exists(this.BackupPath + Carpeta))
            {
                bool UsandoArchivoComprimido = false;

                Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Restaurando copia de seguridad", "Este proceso va a demorar varios minutos. Por favor no lo interrumpa");
                Progreso.Modal = true;

                /* Progreso.ChangeStatus("Descomprimiendo");
                 * // Descomprimir backup si está comprimido
                 * if (System.IO.File.Exists(BackupPath + Carpeta + "backup.7z")) {
                 *      Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(BackupPath + Carpeta + "backup.7z");
                 *      ArchivoComprimido.ExtractAll(BackupPath + Carpeta);
                 *      UsandoArchivoComprimido = true;
                 * } */

                Progreso.ChangeStatus("Eliminando datos actuales");
                using (Lfx.Data.IConnection ConnRestaurar = Lfx.Workspace.Master.GetNewConnection("Restauración de copia de seguridad") as Lfx.Data.IConnection) {
                    Progreso.ChangeStatus("Acomodando estructuras");
                    Lfx.Workspace.Master.Structure.TagList.Clear();
                    Lfx.Workspace.Master.Structure.LoadFromFile(this.BackupPath + Carpeta + "dbstruct.xml");
                    Lfx.Workspace.Master.CheckAndUpdateDatabaseVersion(true, true);

                    using (BackupReader Lector = new BackupReader(this.BackupPath + Carpeta + "dbdata.lbd"))
                        using (IDbTransaction Trans = ConnRestaurar.BeginTransaction()) {
                            ConnRestaurar.EnableConstraints(false);

                            Progreso.ChangeStatus("Incorporando tablas de datos");

                            Progreso.Max = (int)(Lector.Length / 1024);
                            string           TablaActual   = null;
                            string[]         ListaCampos   = null;
                            object[]         ValoresCampos = null;
                            int              CampoActual   = 0;
                            bool             EndTable      = false;
                            qGen.BuilkInsert Insertador    = new qGen.BuilkInsert();
                            do
                            {
                                string Comando = Lector.ReadString(4);
                                switch (Comando)
                                {
                                case ":TBL":
                                    TablaActual = Lector.ReadPrefixedString4();
                                    string NombreTabla;
                                    if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(TablaActual) && Lfx.Workspace.Master.Structure.Tables[TablaActual].Label != null)
                                    {
                                        NombreTabla = Lfx.Workspace.Master.Structure.Tables[TablaActual].Label;
                                    }
                                    else
                                    {
                                        NombreTabla = TablaActual.ToTitleCase();
                                    }
                                    EndTable = false;
                                    Progreso.ChangeStatus("Cargando " + NombreTabla);

                                    qGen.Delete DelCmd = new qGen.Delete(TablaActual);
                                    DelCmd.EnableDeleleteWithoutWhere = true;
                                    ConnRestaurar.ExecuteNonQuery(DelCmd);
                                    break;

                                case ":FDL":
                                    ListaCampos   = Lector.ReadPrefixedString4().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    ValoresCampos = new object[ListaCampos.Length];
                                    CampoActual   = 0;
                                    break;

                                case ":FLD":
                                    ValoresCampos[CampoActual++] = Lector.ReadField();
                                    break;

                                case ".ROW":
                                    qGen.Insert Insertar = new qGen.Insert(TablaActual);
                                    for (int i = 0; i < ListaCampos.Length; i++)
                                    {
                                        Insertar.ColumnValues.AddWithValue(ListaCampos[i], ValoresCampos[i]);
                                    }
                                    Insertador.Add(Insertar);

                                    ValoresCampos = new object[ListaCampos.Length];
                                    CampoActual   = 0;
                                    break;

                                case ":REM":
                                    Lector.ReadPrefixedString4();
                                    break;

                                case ".TBL":
                                    EndTable = true;
                                    break;
                                }
                                if (EndTable || Insertador.Count >= 1000)
                                {
                                    if (Insertador.Count > 0)
                                    {
                                        ConnRestaurar.ExecuteNonQuery(Insertador);
                                    }
                                    Insertador.Clear();
                                    Progreso.Value = (int)(Lector.Position / 1024);
                                }
                            } while (Lector.Position < Lector.Length);
                            Lector.Close();

                            if (Lfx.Workspace.Master.MasterConnection.SqlMode == qGen.SqlModes.PostgreSql)
                            {
                                // PostgreSql: Tengo que actualizar las secuencias
                                Progreso.ChangeStatus("Actualizando secuencias");
                                string PatronSecuencia = @"nextval\(\'(.+)\'(.*)\)";
                                foreach (string Tabla in Lfx.Data.DatabaseCache.DefaultCache.GetTableNames())
                                {
                                    string OID = ConnRestaurar.FieldString("SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE pg_catalog.pg_table_is_visible(c.oid) AND c.relname ~ '^" + Tabla + "$'");
                                    System.Data.DataTable Campos = ConnRestaurar.Select("SELECT a.attname,pg_catalog.format_type(a.atttypid, a.atttypmod),(SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum FROM pg_catalog.pg_attribute a WHERE a.attrelid = '" + OID + "' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum");
                                    foreach (System.Data.DataRow Campo in Campos.Rows)
                                    {
                                        if (Campo[2] != DBNull.Value && Campo[2] != null)
                                        {
                                            string DefaultCampo = System.Convert.ToString(Campo[2]);
                                            if (Regex.IsMatch(DefaultCampo, PatronSecuencia))
                                            {
                                                string NombreCampo = System.Convert.ToString(Campo[0]);
                                                foreach (System.Text.RegularExpressions.Match Ocurrencia in Regex.Matches(DefaultCampo, PatronSecuencia))
                                                {
                                                    string Secuencia = Ocurrencia.Groups[1].ToString();
                                                    int    MaxId     = ConnRestaurar.FieldInt("SELECT MAX(" + NombreCampo + ") FROM " + Tabla) + 1;
                                                    ConnRestaurar.ExecuteNonQuery("ALTER SEQUENCE " + Secuencia + " RESTART WITH " + MaxId.ToString());
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (System.IO.File.Exists(this.BackupPath + Carpeta + "blobs.lst"))
                            {
                                // Incorporar Blobs
                                Progreso.ChangeStatus("Incorporando imágenes");
                                System.IO.StreamReader LectorBlobs = new System.IO.StreamReader(this.BackupPath + Carpeta + "blobs.lst", System.Text.Encoding.Default);
                                string InfoImagen = null;
                                do
                                {
                                    InfoImagen = LectorBlobs.ReadLine();
                                    if (InfoImagen != null && InfoImagen.Length > 0)
                                    {
                                        string Tabla               = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string Campo               = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string CampoId             = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string NombreArchivoImagen = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");

                                        // Guardar blob nuevo
                                        qGen.Update ActualizarBlob = new qGen.Update(Tabla);
                                        ActualizarBlob.WhereClause = new qGen.Where(Campo, CampoId);

                                        System.IO.FileStream ArchivoImagen = new System.IO.FileStream(this.BackupPath + Carpeta + NombreArchivoImagen, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                        byte[] Contenido = new byte[System.Convert.ToInt32(ArchivoImagen.Length) - 1 + 1];
                                        ArchivoImagen.Read(Contenido, 0, System.Convert.ToInt32(ArchivoImagen.Length));
                                        ArchivoImagen.Close();

                                        ActualizarBlob.ColumnValues.AddWithValue(Campo, Contenido);
                                        ConnRestaurar.ExecuteNonQuery(ActualizarBlob);
                                    }
                                }while (InfoImagen != null);
                                LectorBlobs.Close();
                            }

                            if (UsandoArchivoComprimido)
                            {
                                Progreso.ChangeStatus("Eliminando archivos temporales");
                                // Borrar los archivos que descomprim temporalmente
                                System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(this.BackupPath + Carpeta);
                                foreach (System.IO.FileInfo DirItem in Dir.GetFiles())
                                {
                                    if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt")
                                    {
                                        System.IO.File.Delete(this.BackupPath + Carpeta + DirItem.Name);
                                    }
                                }
                            }
                            Progreso.ChangeStatus("Terminando transacción");
                            Trans.Commit();
                        }
                    Progreso.End();
                }

                Lfx.Workspace.Master.RunTime.Toast("La copia de seguridad se restauró con éxito. A continuación se va a reiniciar la aplicación.", "Copia Restaurada");
            }
        }
        private void FileIterator(string inputFolder, string successFolder, string failureFolder, string toolPath, string subPath, string logPath)
        {
            var thisDirectory = new System.IO.DirectoryInfo(System.IO.Path.Combine(inputFolder, subPath));
            var inputPath     = System.IO.Path.Combine(inputFolder, subPath);
            var successPath   = System.IO.Path.Combine(successFolder, subPath);
            var failurePath   = ViolentlySanitizeUnicodedPath(System.IO.Path.Combine(failureFolder, subPath));

            CreateDirectoryIfNecessary(successPath);
            CreateDirectoryIfNecessary(failurePath);

            foreach (var file in thisDirectory.GetFiles())
            {
                if (file.Extension.ToLowerInvariant() == ".max")
                {
                    UpdateProgress(file.FullName);

                    var failureFilePath    = System.IO.Path.Combine(failurePath, ViolentlySanitizeUnicodedPath(file.Name));
                    var failureFilePdfPath = failureFilePath + ".pdf";
                    var successFilePdfPath = System.IO.Path.Combine(successPath, file.Name) + ".pdf";

                    file.CopyTo(failureFilePath, true);

                    var procInfo = new ProcessStartInfo(toolPath, "-o2 \"" + failureFilePath + "\"");
                    //var procInfo = new ProcessStartInfo(toolPath, "\"" + failureFilePath + "\"");
                    procInfo.RedirectStandardOutput = true;
                    procInfo.RedirectStandardError  = true;
                    procInfo.UseShellExecute        = false;
                    procInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                    procInfo.CreateNoWindow         = true;

                    bool killed            = false;
                    var  conversionAttempt = Process.Start(procInfo);
                    conversionAttempt.WaitForExit(300000);                     //time out at 5 mins
                    if (!conversionAttempt.HasExited)
                    {
                        conversionAttempt.Kill();
                        killed = true;
                    }
                    var output = conversionAttempt.StandardOutput.ReadToEnd();
                    var error  = conversionAttempt.StandardError.ReadToEnd();

                    System.IO.File.AppendAllText(logPath, string.Format(@"---
File: {0}
Ended: {1}
Killed: {2}
Result: {3}
StdError: {4}
StdOutput: {5}
", file.FullName, DateTime.Now, killed, conversionAttempt.ExitCode, error, output), Encoding.UTF8);

                    //System.Diagnostics.Debugger.Break();

                    bool allGood = false;
                    if (System.IO.File.Exists(failureFilePdfPath))
                    {
                        var targetPDFFile = new System.IO.FileInfo(failureFilePdfPath);
                        if (targetPDFFile.Length > 0)
                        {
                            //if success, delete this and move the PDF to its destination
                            System.IO.File.Copy(failureFilePdfPath, successFilePdfPath, true);
                            System.IO.File.SetCreationTimeUtc(successFilePdfPath, file.CreationTimeUtc);
                            System.IO.File.SetLastWriteTimeUtc(successFilePdfPath, file.LastWriteTimeUtc);
                            System.IO.File.Delete(failureFilePath);
                            System.IO.File.Delete(failureFilePdfPath);
                            allGood = true;
                        }
                    }

                    if (!allGood)
                    {
                        //if failure, re-copy in case the process messed up the file
                        file.CopyTo(failureFilePath, true);
                    }
                }
                else
                {
                    file.CopyTo(System.IO.Path.Combine(successPath, file.Name), true);
                }
            }
            foreach (var directory in thisDirectory.GetDirectories())
            {
                FileIterator(inputFolder, successFolder, failureFolder, toolPath, System.IO.Path.Combine(subPath, directory.Name), logPath);
            }
        }
        public virtual void StartImportPackage()
        {
            if (!ValidateInput())
            {
                return;
            }

            progressBar.Style = ProgressBarStyle.Marquee;

            if (importWorker != null && importWorker.WorkerSupportsCancellation)
            {
                importWorker.CancelAsync();
            }

            this.Cursor = Cursors.WaitCursor;

            string importTypeDescription = ImportExportSharedStrings.IMPORT_TYPE_UPDATE_AND_APPEND;

            if (cmbImportType.SelectedIndex == 0)
            {
                update = true;
                append = true;
            }
            else if (cmbImportType.SelectedIndex == 1)
            {
                update = true;
                append = false;
                importTypeDescription = ImportExportSharedStrings.IMPORT_TYPE_UPDATE_ONLY;
            }
            else
            {
                update = false;
                append = true;
                importTypeDescription = ImportExportSharedStrings.IMPORT_TYPE_APPEND_ONLY;
            }

            progressBar.Visible = true;
            progressBar.Style   = ProgressBarStyle.Marquee;

            lbxStatus.Items.Clear();

            //AddNotificationStatusMessage("Package creation initiated by user " + System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString() + ".");

            DisableControls();

            password     = txtPassword.Text;
            packagePaths = new List <string>();

            if (checkboxBatchImport.Checked)
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(txtPackageFile.Text);
                foreach (System.IO.FileInfo f in dir.GetFiles("*.edp7"))
                {
                    packagePaths.Add(f.FullName);
                }
                AddNotificationStatusMessage(string.Format(ImportExportSharedStrings.START_BATCH_IMPORT, packagePaths.Count.ToString(), txtPackageFile.Text));
            }
            else
            {
                packagePaths.Add(txtPackageFile.Text);
                AddNotificationStatusMessage(string.Format(ImportExportSharedStrings.START_SINGLE_IMPORT, txtPackageFile.Text));
            }

            AddNotificationStatusMessage(importTypeDescription);

            stopwatch = new Stopwatch();
            stopwatch.Start();

            importWorker = new BackgroundWorker();
            importWorker.WorkerSupportsCancellation = true;
            importWorker.DoWork             += new System.ComponentModel.DoWorkEventHandler(importWorker_DoWork);
            importWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(importWorker_WorkerCompleted);
            importWorker.RunWorkerAsync();
        }
Beispiel #37
0
    // Recursively copy a directory to its destination.
    public static bool RecursiveCopyDirectory(System.IO.DirectoryInfo srcDir, System.IO.DirectoryInfo destDir,
                                              System.Collections.Generic.List <string> excludeExtensions = null)
    {
        if (!srcDir.Exists)
        {
            UnityEngine.Debug.LogError(string.Format("WwiseUnity: Failed to copy. Source is missing: {0}.", srcDir));
            return(false);
        }

        if (!destDir.Exists)
        {
            destDir.Create();
        }

        // Copy all files.
        var files = srcDir.GetFiles();

        foreach (var file in files)
        {
            if (excludeExtensions != null)
            {
                var fileExt        = System.IO.Path.GetExtension(file.Name);
                var isFileExcluded = false;
                foreach (var ext in excludeExtensions)
                {
                    if (fileExt.ToLower() == ext)
                    {
                        isFileExcluded = true;
                        break;
                    }
                }

                if (isFileExcluded)
                {
                    continue;
                }
            }

            const bool IsToOverwrite = true;
            try
            {
                file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name), IsToOverwrite);
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError(string.Format("WwiseUnity: Error during installation: {0}.", ex.Message));
                return(false);
            }
        }

        // Process subdirectories.
        var dirs = srcDir.GetDirectories();

        foreach (var dir in dirs)
        {
            // Get destination directory.
            var destFullPath = System.IO.Path.Combine(destDir.FullName, dir.Name);

            // Recurse
            var isSuccess = RecursiveCopyDirectory(dir, new System.IO.DirectoryInfo(destFullPath), excludeExtensions);
            if (!isSuccess)
            {
                return(false);
            }
        }

        return(true);
    }
Beispiel #38
0
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                disp_usage();
                return;
            }
            libtysila5.libtysila.AssemblyLoader al = new libtysila5.libtysila.AssemblyLoader(
                new tysila4.FileSystemFileLoader());
            tysila4.Program.search_dirs.Add(args[0]);
            tysila4.Program.search_dirs.Add(new System.IO.FileInfo(args[2]).DirectoryName);

            /* Load up all types in corefx files */
            Dictionary <string, string> map = new Dictionary <string, string>();
            var indir = new System.IO.DirectoryInfo(args[0]);
            var files = indir.GetFiles(args[1]);

            foreach (var fi in files)
            {
                var m = al.GetAssembly(fi.FullName);

                for (int i = 1; i <= m.table_rows[metadata.MetadataStream.tid_TypeDef]; i++)
                {
                    var flags            = m.GetIntEntry(metadata.MetadataStream.tid_TypeDef, i, 0);
                    metadata.TypeSpec ts = new metadata.TypeSpec {
                        m = m, tdrow = i
                    };

                    if ((flags & 0x7) == 0x1 || (flags & 0x7) == 0x2)
                    {
                        // public
                        var nspace   = ts.Namespace;
                        var name     = ts.Name;
                        var fullname = nspace + "." + name;
                        map[fullname] = fi.Name;
                    }
                }
            }

            /* Generate a mapping from type name/namespaces to the files they are contained in */
            var infiledi = al.LoadAssembly(args[2]);
            var infile   = new metadata.PEFile().Parse(infiledi, al, false);
            var o        = new System.IO.StreamWriter(args[3]);

            for (int i = 1; i <= infile.table_rows[metadata.MetadataStream.tid_TypeDef]; i++)
            {
                var flags            = infile.GetIntEntry(metadata.MetadataStream.tid_TypeDef, i, 0);
                metadata.TypeSpec ts = new metadata.TypeSpec {
                    m = infile, tdrow = i
                };

                if ((flags & 0x7) == 0x1 || (flags & 0x7) == 0x2)
                {
                    // public
                    var nspace   = ts.Namespace;
                    var name     = ts.Name;
                    var fullname = nspace + "." + name;

                    if (map.ContainsKey(fullname))
                    {
                        o.WriteLine(infile.AssemblyName + "!" + fullname + "=" + map[fullname]);
                    }
                }
            }
            for (int i = 1; i <= infile.table_rows[metadata.MetadataStream.tid_ExportedType]; i++)
            {
                var nspace   = infile.GetStringEntry(metadata.MetadataStream.tid_ExportedType, i, 3);
                var name     = infile.GetStringEntry(metadata.MetadataStream.tid_ExportedType, i, 2);
                var fullname = nspace + "." + name;

                if (map.ContainsKey(fullname))
                {
                    o.WriteLine(infile.AssemblyName + "!" + fullname + "=" + map[fullname]);
                }
            }
            o.Close();
        }
Beispiel #39
0
            private static void aboutSystemDrive()
            {
                // You can also use System.Environment.GetLogicalDrives to
                // obtain names of all logical drives on the computer.
                System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\");
                Console.WriteLine(di.TotalFreeSpace);
                Console.WriteLine(di.VolumeLabel);

                // Get the root directory and print out some information about it.
                System.IO.DirectoryInfo dirInfo = di.RootDirectory;
                Console.WriteLine(dirInfo.Attributes.ToString());

                // Get the files in the directory and print out some information about them.
                System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");

                foreach (System.IO.FileInfo fi in fileNames)
                {
                    Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);
                }

                // Get the subdirectories directly that is under the root.
                // See "How to: Iterate Through a Directory Tree" for an example of how to
                // iterate through an entire tree.
                System.IO.DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*");

                foreach (System.IO.DirectoryInfo d in dirInfos)
                {
                    Console.WriteLine(d.Name);
                }

                // The Directory and File classes provide several static methods
                // for accessing files and directories.

                // Get the current application directory.
                string currentDirName = System.IO.Directory.GetCurrentDirectory();

                Console.WriteLine(currentDirName);

                // Get an array of file names as strings rather than FileInfo objects.
                // Use this method when storage space is an issue, and when you might
                // hold on to the file name reference for a while before you try to access
                // the file.
                string[] files = System.IO.Directory.GetFiles(currentDirName, "*.txt");

                foreach (string s in files)
                {
                    // Create the FileInfo object only when needed to ensure
                    // the information is as current as possible.
                    System.IO.FileInfo fi = null;
                    try
                    {
                        fi = new System.IO.FileInfo(s);
                    }
                    catch (System.IO.FileNotFoundException e)
                    {
                        // To inform the user and continue is
                        // sufficient for this demonstration.
                        // Your application may require different behavior.
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    Console.WriteLine("{0} : {1}", fi.Name, fi.Directory);
                }

                // Change the directory. In this case, first check to see
                // whether it already exists, and create it if it does not.
                // If this is not appropriate for your application, you can
                // handle the System.IO.IOException that will be raised if the
                // directory cannot be found.
                if (!System.IO.Directory.Exists(@"C:\Users\Public\TestFolder\"))
                {
                    System.IO.Directory.CreateDirectory(@"C:\Users\Public\TestFolder\");
                }

                System.IO.Directory.SetCurrentDirectory(@"C:\Users\Public\TestFolder\");

                currentDirName = System.IO.Directory.GetCurrentDirectory();
                Console.WriteLine(currentDirName);

                // Keep the console window open in debug mode.
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
Beispiel #40
0
        protected void uploadButtonClicked(String projectId, String name, String description, String tags, String draftAccessList, String attribution, String acquisitionTime, String maskType)
        {
            try
            {
                // create a new Processing Dialog
                Dialogs.Processing.ProgressDialog processingDialog = new Processing.ProgressDialog();

                // check to see if the layer is valid
                // and destination is configured correctly
                if (isLayerValidated &&
                    projectId != null && projectId.Length > 0 &&
                    name != null && name.Length > 0 &&
                    draftAccessList != null && draftAccessList.Length > 0 &&
                    uploadType.Equals("vector") || (uploadType.Equals("raster") && attribution != null && attribution.Length > 0))
                {
                    // show the processing dialog
                    processingDialog.Show();

                    // create a reference to the Google Maps Engine API
                    MapsEngine.API.GoogleMapsEngineAPI api = new MapsEngine.API.GoogleMapsEngineAPI(ref log);

                    // establish a reference to the running ArcMap instance
                    ESRI.ArcGIS.ArcMapUI.IMxDocument mxDoc = (ESRI.ArcGIS.ArcMapUI.IMxDocument)ArcMap.Application.Document;

                    // retrieve a reference to the selected layer
                    ESRI.ArcGIS.Carto.ILayer selectedLayer = mxDoc.SelectedLayer;

                    // create a temporary working directory
                    System.IO.DirectoryInfo tempDir
                        = System.IO.Directory.CreateDirectory(ext.getLocalWorkspaceDirectory() + "\\" + System.Guid.NewGuid());

                    // determine what type of layer is selected
                    if (selectedLayer is ESRI.ArcGIS.Carto.IFeatureLayer)
                    {
                        // export a copy of the feature class to a "uploadable" Shapefile
                        // raise a processing notification
                        ext.publishRaiseDownloadProgressChangeEvent(false, "Extracting a copy of '" + selectedLayer.Name + "' (feature class) for data upload.");
                        ExportLayerToShapefile(tempDir.FullName, selectedLayer.Name, selectedLayer);

                        processingDialog.Update();
                        processingDialog.Focus();

                        // create a list of files in the temp directory
                        List <String> filesNames = new List <String>();
                        for (int k = 0; k < tempDir.GetFiles().Count(); k++)
                        {
                            if (!tempDir.GetFiles()[k].Name.EndsWith(".lock"))
                            {
                                filesNames.Add(tempDir.GetFiles()[k].Name);
                            }
                        }

                        // create a Google Maps Engine asset record
                        ext.publishRaiseDownloadProgressChangeEvent(false, "Requesting a new Google Maps Engine asset be created.");
                        MapsEngine.DataModel.gme.UploadingAsset uploadingAsset
                            = api.createVectorTableAssetForUploading(ext.getToken(),
                                                                     MapsEngine.API.GoogleMapsEngineAPI.AssetType.table,
                                                                     projectId,
                                                                     name,
                                                                     draftAccessList,
                                                                     filesNames,
                                                                     description,
                                                                     tags.Split(",".ToCharArray()).ToList <String>(),
                                                                     "UTF-8");

                        // Initiate upload of file(s)
                        ext.publishRaiseDownloadProgressChangeEvent(false, "Starting to upload files...");
                        api.uploadFilesToAsset(ext.getToken(), uploadingAsset.id, "tables", tempDir.GetFiles());

                        // launch a web browser
                        ext.publishRaiseDownloadProgressChangeEvent(false, "Launching a web browser.");
                        System.Diagnostics.Process.Start("https://mapsengine.google.com/admin/#RepositoryPlace:cid=" + projectId + "&v=DETAIL_INFO&aid=" + uploadingAsset.id);
                    }
                    else if (selectedLayer is ESRI.ArcGIS.Carto.IRasterLayer)
                    {
                        // export a copy of the raster to a format that can be uploaded
                        // raise a processing notification
                        ext.publishRaiseDownloadProgressChangeEvent(false, "Extracting a copy of '" + selectedLayer.Name + "' (raster) for data upload.");
                        ExportLayerToUploadableRaster(tempDir.FullName, selectedLayer.Name, selectedLayer);

                        processingDialog.Update();
                        processingDialog.Focus();

                        // create a list of files in the temp directory
                        List <String> filesNames = new List <String>();
                        for (int k = 0; k < tempDir.GetFiles().Count(); k++)
                        {
                            if (!tempDir.GetFiles()[k].Name.EndsWith(".lock"))
                            {
                                filesNames.Add(tempDir.GetFiles()[k].Name);
                            }
                        }

                        // create a Google Maps Engine asset record
                        ext.publishRaiseDownloadProgressChangeEvent(false, "Requesting a new Google Maps Engine asset be created.");
                        MapsEngine.DataModel.gme.UploadingAsset uploadingAsset
                            = api.createRasterAssetForUploading(ext.getToken(),
                                                                projectId,
                                                                name,
                                                                draftAccessList,
                                                                attribution, // attribution
                                                                filesNames,
                                                                description,
                                                                tags.Split(",".ToCharArray()).ToList <String>(),
                                                                acquisitionTime,
                                                                maskType);

                        // Initiate upload of file(s)
                        ext.publishRaiseDownloadProgressChangeEvent(false, "Starting to upload files...");
                        api.uploadFilesToAsset(ext.getToken(), uploadingAsset.id, "rasters", tempDir.GetFiles());

                        // launch a web browser
                        ext.publishRaiseDownloadProgressChangeEvent(false, "Launching a web browser.");
                        System.Diagnostics.Process.Start("https://mapsengine.google.com/admin/#RepositoryPlace:cid=" + projectId + "&v=DETAIL_INFO&aid=" + uploadingAsset.id);
                    }

                    // Ask the user if the temporary files should be deleted
                    DialogResult dialogResult = MessageBox.Show(
                        String.Format(Properties.Resources.dialog_dataUpload_tempFileCleanupMessage,
                                      tempDir.GetFiles().Count(), tempDir.FullName),
                        ext.getAddinName() + " Temporary File Clean-up",
                        MessageBoxButtons.YesNo);

                    // if the user wishes to delete the temporary files, delete them
                    if (dialogResult == DialogResult.Yes)
                    {
                        try
                        {
                            // remove the temporary layer from the ArcMap session
                            ext.removeLayerByName((uploadType.Equals("vector") ? selectedLayer.Name : selectedLayer.Name + ".tif"), tempDir.FullName);

                            // Delete temporary directory and containing files
                            tempDir.Delete(true);
                        }
                        catch (Exception) { }
                    }

                    // close the processing dialog
                    ext.publishRaiseDownloadProgressChangeEvent(true, "Finished");
                    processingDialog.Close();
                }
                else
                {
                    // display an error dialog to the user
                    System.Windows.Forms.MessageBox.Show("The selected layer is invalid or the destination configuration has not been properly set.");
                }
            }
            catch (System.Exception ex)
            {
                // Ops.
                System.Windows.Forms.MessageBox.Show("An error occured. " + ex.Message);
            }

            // close the dialog
            this.Close();
        }
        private void _CompressTAR(string pathFileTAR, IDTSComponentEvents componentEvents, System.IO.Stream stream)
        {
            bool b = false;

            System.IO.DirectoryInfo di   = new System.IO.DirectoryInfo(_folderSource);
            System.IO.FileInfo[]    fi_s = di.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

            if (stream == null)
            {
                stream = System.IO.File.Create(pathFileTAR);
            }

            using (ICSharpCode.SharpZipLib.Tar.TarOutputStream tar = new ICSharpCode.SharpZipLib.Tar.TarOutputStream(stream))
            {
                foreach (System.IO.FileInfo fi in fi_s)
                {
                    if (!System.Text.RegularExpressions.Regex.Match(fi.FullName, _fileFilter).Success)
                    {
                        componentEvents.FireInformation(1, "UnZip SSIS", _typeCompression.ToString() + ": file " + fi.FullName + " doesn't match regex filter '" + _fileFilter + "'. File not processed.", null, 0, ref b);
                        continue;
                    }

                    componentEvents.FireInformation(1, "UnZip SSIS", _typeCompression.ToString() + ": Compress (with '" + _storePaths.ToString() + "') file: " + fi.FullName, null, 0, ref b);
                    string fileName = fi.FullName;

                    if (_storePaths == Store_Paths.Absolute_Paths)
                    {
                        //Absolute Path
                        fileName = fi.FullName.Replace("\\", "/").Substring(3);
                    }
                    else if (_storePaths == Store_Paths.Relative_Paths)
                    {
                        //Relative Path
                        fileName = fileName.Replace(_folderSource, "").Replace("\\", "/");
                        if (_addRootFolder)
                        {
                            fileName = (di.Name + "/" + fileName).Replace("//", "/");
                        }
                    }
                    else if (_storePaths == Store_Paths.No_Paths)
                    {
                        //No Path
                        fileName = fi.Name;
                    }
                    else
                    {
                        throw new Exception("Please select type Store Paths (No_Paths / Relative_Paths / Absolute_Paths).");
                    }

                    using (System.IO.FileStream fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        ICSharpCode.SharpZipLib.Tar.TarEntry te = ICSharpCode.SharpZipLib.Tar.TarEntry.CreateTarEntry(fileName);
                        te.Size = fs.Length;
                        tar.PutNextEntry(te);

                        fs.CopyTo(tar);

                        fs.Flush();
                        tar.Flush();

                        tar.CloseEntry();
                    }
                }

                tar.Flush();
                tar.Close();
            }
        }
Beispiel #42
0
        public override bool Execute()
        {
            base.Log.LogMessage(MessageImportance.High, "Copy from: {0} to {1}", new object[]
            {
                this.CopyFrom,
                this.CopyTo
            });
            bool result;

            if (!System.IO.Directory.Exists(this.CopyFrom))
            {
                base.Log.LogWarning("CopyFrom directory {0} not exists!", new object[]
                {
                    this.CopyFrom
                });
                result = true;
            }
            else
            {
                if (!string.IsNullOrEmpty(this.Filters))
                {
                    this.filters = this.Filters.Split(new char[]
                    {
                        ';'
                    });
                }
                System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(this.CopyFrom);
                System.IO.FileInfo[]    files         = directoryInfo.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
                System.IO.FileInfo[]    array         = files;
                int i = 0;
                while (i < array.Length)
                {
                    System.IO.FileInfo fileInfo = array[i];
                    if (this.ExcludeDirs == null)
                    {
                        goto IL_142;
                    }
                    bool     flag   = false;
                    string[] array2 = this.ExcludeDirs;
                    for (int j = 0; j < array2.Length; j++)
                    {
                        string str = array2[j];
                        if (fileInfo.DirectoryName.Contains("\\" + str))
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        goto IL_142;
                    }
IL_22B:
                    i++;
                    continue;
IL_142:
                    if (this.ExcludeFiles != null)
                    {
                        flag   = false;
                        array2 = this.ExcludeFiles;
                        for (int j = 0; j < array2.Length; j++)
                        {
                            string b = array2[j];
                            if (fileInfo.Extension == b)
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (flag)
                        {
                            goto IL_22B;
                        }
                    }
                    string text = this.CopyTo + fileInfo.FullName.Replace(this.CopyFrom, string.Empty);
                    if (this.filters != null)
                    {
                        if (!this.CheckFileForFilters(fileInfo))
                        {
                            goto IL_22B;
                        }
                        text = System.Text.RegularExpressions.Regex.Replace(text, "*", string.Empty);
                    }
                    string directoryName = System.IO.Path.GetDirectoryName(text);
                    if (!System.IO.Directory.Exists(directoryName))
                    {
                        System.IO.Directory.CreateDirectory(directoryName);
                    }
                    fileInfo.CopyTo(text, true);
                    goto IL_22B;
                }
                result = true;
            }
            return(result);
        }
Beispiel #43
0
        //Own Thread
        public void ThreadSave_GeneratePlaylistUpdates() // over TaskPlannerBase
        {
            try
            {
                old_PlaylistUpdatesItems   = playlistUpdatesModel.Items;
                playlistUpdatesModel.Items = new ObservableCollection <PlayListUpdatesViewModel>(); // Reset


                // Delete old Plalist Updates
                String TempPlaylistPath = TempPlaylistPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

                if (System.IO.Directory.Exists(TempPlaylistPath + "\\RoMoRDuP\\") == false)
                {
                    if (System.IO.Directory.CreateDirectory(TempPlaylistPath + "\\RoMoRDuP\\") == null)
                    {
                        MessageBox.Show("Cannot create Directory " + TempPlaylistPath + "\\RoMoRDuP\\");
                        return;
                    }
                }

                if (System.IO.Directory.Exists(TempPlaylistPath + "\\RoMoRDuP\\PlaylistUpdates\\") == true) // empty folder
                {
                    // delete
                    try
                    {
                        System.IO.DirectoryInfo downloadedMessageInfo = new System.IO.DirectoryInfo(TempPlaylistPath + "\\RoMoRDuP\\PlaylistUpdates\\");

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

                        //System.IO.Directory.Delete(TempPlaylistPath + "\\RoMoRDuP\\PlaylistUpdates\\");
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show("Can´t delete " + TempPlaylistPath + "\\RoMoRDuP\\PlaylistUpdates\\ ! " + ex.Message);
                    }
                }



                // Generate new Plalist Updates
                int iTempPlaylistIndex = 1;

                foreach (List <string> list in matrixListPlaylists)
                {
                    foreach (string PlaylistFilePath in list)
                    {
                        // load File into RAM
                        StringBuilder sb = new StringBuilder();
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(PlaylistFilePath, Encoding.Default))
                        {
                            String line;
                            // Read and display lines from the file until the end of
                            // the file is reached.
                            while ((line = sr.ReadLine()) != null)
                            {
                                sb.AppendLine(line);
                            }
                        }
                        string strFileListOrgContent = sb.ToString();

                        List <ValidPath> AllValidPaths = GetAllValidPathsFromString(strFileListOrgContent, PlaylistFilePath);

                        {
                            TempPlaylistPath = TempPlaylistPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

                            if (System.IO.Directory.Exists(TempPlaylistPath + "\\RoMoRDuP\\") == false)
                            {
                                if (System.IO.Directory.CreateDirectory(TempPlaylistPath + "\\RoMoRDuP\\") == null)
                                {
                                    MessageBox.Show("Cannot create Directory " + TempPlaylistPath + "\\RoMoRDuP\\");
                                    return;
                                }
                            }

                            if (System.IO.Directory.Exists(TempPlaylistPath + "\\RoMoRDuP\\PlaylistUpdates\\") == false)
                            {
                                if (System.IO.Directory.CreateDirectory(TempPlaylistPath + "\\RoMoRDuP\\PlaylistUpdates\\") == null)
                                {
                                    MessageBox.Show("Cannot create Directory " + TempPlaylistPath + "\\RoMoRDuP\\PlaylistUpdates\\");
                                    return;
                                }
                            }

                            System.IO.FileInfo fileInfo = new System.IO.FileInfo(PlaylistFilePath);
                            TempPlaylistPath = TempPlaylistPath + "\\RoMoRDuP\\PlaylistUpdates\\" + "Temp_" + iTempPlaylistIndex.ToString() + "_" + fileInfo.Name;
                            iTempPlaylistIndex++;
                        }

                        PlayListUpdatesViewModel PlaylistUpdatesEntry = null;

                        foreach (ValidPath validPath in AllValidPaths)
                        {
                            // regenerate all Before Actions already done in UCPartent

                            // check for changes
                            TaskPlanner.FileListEntry changingEntry = null;
                            changingEntry = CheckChangesValidPath(validPath, fileLists.SourceFileListBefore);

                            if (userOptions is UserInterface.UserOptionsMirror) // Only for Mirror
                            {
                                if (changingEntry == null)
                                {
                                    changingEntry = CheckChangesValidPath(validPath, fileLists.TargetFileListBefore);
                                }
                            }

                            // if changes create entry, set bool for create file in AppData/Playlist
                            if (changingEntry != null)
                            {
                                if (PlaylistUpdatesEntry == null)
                                {
                                    PlaylistUpdatesEntry = new PlayListUpdatesViewModel();
                                    PlaylistUpdatesEntry.PathOriginal = PlaylistFilePath;
                                    //PlaylistUpdatesEntry.PathRenameOrg = ;
                                    PlaylistUpdatesEntry.PathTemp = TempPlaylistPath;
                                }

                                PlaylistChange playlistChange = new PlaylistChange();

                                playlistChange.validPath     = validPath;
                                playlistChange.changingEntry = changingEntry;

                                PlaylistUpdatesEntry.PlaylistChanges.Add(playlistChange);
                            }
                        }

                        // create file if changes
                        if (PlaylistUpdatesEntry != null)
                        {
                            if (PlaylistUpdatesEntry.PlaylistChanges.Count > 0)
                            {
                                // check if LeaveCopy/UpdatePlaylist Option was changed before
                                if (old_PlaylistUpdatesItems != null)
                                {
                                    foreach (PlayListUpdatesViewModel oldvm in old_PlaylistUpdatesItems)
                                    {
                                        if (oldvm.PathOriginal == PlaylistUpdatesEntry.PathOriginal)
                                        {
                                            PlaylistUpdatesEntry.LeaveCopy      = oldvm.LeaveCopy;
                                            PlaylistUpdatesEntry.UpdatePlaylist = oldvm.UpdatePlaylist;
                                            break;
                                        }
                                    }
                                }


                                if (userOptions.mainWindow != null)
                                {
                                    userOptions.mainWindow.Dispatcher.Invoke(
                                        (Action)(() =>
                                    {
                                        playlistUpdatesModel.Items.Add(PlaylistUpdatesEntry);
                                        CreateNewPlaylistFile(PlaylistFilePath, strFileListOrgContent, PlaylistUpdatesEntry);
                                    }
                                                 ), null);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
Beispiel #44
0
        public static void AddScripts(this XmlNode parent, Project project, string version, string packageScriptsFolder)
        {
            if (string.IsNullOrEmpty(project.pathsAndFiles.pathToScripts))
            {
                return;
            }
            var folderName = packageScriptsFolder.EnsureEndsWith("/");

            folderName += project.packageName.NoSlashes() + "/";
            var scriptsFound = false;
            var newNode      = parent.AddChildElement("component").AddAttribute("type", "Script");
            var scripts      = newNode.AddChildElement("scripts");

            scripts.AddChildElement("basePath", "DesktopModules/" + project.folder + "/SqlScripts");
            var d = new System.IO.DirectoryInfo(project.pathsAndFiles.pathToScripts);

            Console.WriteLine("Looking for scripts in {0}", d.FullName);
            if (!d.Exists)
            {
                return;
            }

            foreach (var f in d.GetFiles("*.SqlDataProvider"))
            {
                Console.WriteLine("Adding {0}", f.Name);
                var m = Regex.Match(f.Name, @"(?i)^(\d+)\.(\d+)\.(\d+)\.SqlDataProvider(?-i)");
                if (m.Success)
                {
                    var script = scripts.AddChildElement("script").AddAttribute("type", "Install");
                    script.AddChildElement("name", f.Name);
                    script.AddChildElement("sourceFileName", folderName + f.Name);
                    script.AddChildElement("version", System.IO.Path.GetFileNameWithoutExtension(f.Name));
                    scriptsFound = true;
                }
                else
                {
                    m = Regex.Match(f.Name, @"(?i)Install\.(\d+)\.(\d+)\.(\d+)\.SqlDataProvider(?-i)");
                    if (m.Success)
                    {
                        var script = scripts.AddChildElement("script").AddAttribute("type", "Install");
                        script.AddChildElement("name", f.Name);
                        script.AddChildElement("sourceFileName", folderName + f.Name);
                        script.AddChildElement("version", string.Format("{0}.{1}.{2}", m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value));
                        scriptsFound = true;
                    }
                    else
                    {
                        m = Regex.Match(f.Name, @"(?i)(.+)\.SqlDataProvider(?-i)");
                        if (m.Success)
                        {
                            var scriptName = m.Groups[1].Value.ToLower();
                            if (scriptName == "uninstall")
                            {
                                var script = scripts.AddChildElement("script").AddAttribute("type", "UnInstall");
                                script.AddChildElement("name", f.Name);
                                script.AddChildElement("sourceFileName", folderName + f.Name);
                                script.AddChildElement("version", version.ToNormalizedVersion());
                                scriptsFound = true;
                            }
                            else if (scriptName.StartsWith("upgrade") || scriptName.StartsWith("schema"))
                            {
                                var script = scripts.AddChildElement("script").AddAttribute("type", "Install");
                                script.AddChildElement("name", f.Name);
                                script.AddChildElement("sourceFileName", folderName + f.Name);
                                script.AddChildElement("version", version.ToNormalizedVersion());
                                scriptsFound = true;
                            }
                        }
                    }
                }
            }
            if (scriptsFound)
            {
                parent.AppendChild(newNode);
            }
        }
        protected static void setupResources(string source, string sourceFolder, string target, string targetFolder, string metafile)
        {
            bool exists = false;

            try
            {
                if (System.IO.Directory.Exists(sourceFolder))
                {
                    exists = true;

                    if (!System.IO.Directory.Exists(targetFolder))
                    {
                        System.IO.Directory.CreateDirectory(targetFolder);
                    }

                    System.IO.DirectoryInfo dirSource = new System.IO.DirectoryInfo(sourceFolder);

                    foreach (System.IO.FileInfo file in dirSource.GetFiles("*"))
                    {
                        if (System.IO.File.Exists(targetFolder + file.Name))
                        {
                            if (Util.BaseConstants.DEV_DEBUG)
                            {
                                Debug.Log($"File exists: {file}");
                            }
                        }
                        else
                        {
                            AssetDatabase.MoveAsset(source + file.Name, target + file.Name);

                            if (Util.BaseConstants.DEV_DEBUG)
                            {
                                Debug.Log($"File moved: {file}");
                            }
                        }
                    }

                    //dirSource.Delete(true);
                    dirSource.Delete();

                    if (System.IO.File.Exists(metafile))
                    {
                        System.IO.File.Delete(metafile);
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (Util.BaseConstants.DEV_DEBUG)
                {
                    Debug.LogError($"Could not move all files: {ex}");
                }
            }
            finally
            {
                if (exists)
                {
                    EditorUtil.BaseEditorHelper.RefreshAssetDatabase();
                }
            }
        }
Beispiel #46
0
        //-------------------------------------------------------------------------
        // Start the Form and look for the files .Statistics.log in the root
        // the two Listview are configured
        //-------------------------------------------------------------------------

        public FrmMain()
        {
            InitializeComponent();

            System.IO.DirectoryInfo o       = new System.IO.DirectoryInfo(LocalRuta);
            System.IO.FileInfo[]    myfiles = null;

            myfiles = o.GetFiles("*.CustomDatedStatistics.log");
            for (int y = 0; y <= myfiles.Length - 1; y++)
            {
                cmb1.Items.Add(myfiles[y].Name);
            }

            var _with1 = Lst1;

            _with1.View          = View.Details;
            _with1.FullRowSelect = true;
            _with1.GridLines     = true;
            _with1.LabelEdit     = false;
            _with1.Columns.Clear();
            _with1.Items.Clear();

            _with1.Columns.Add("", 0, HorizontalAlignment.Right);
            _with1.Columns.Add("Date", 145, HorizontalAlignment.Left);
            _with1.Columns.Add("Mission", 190, HorizontalAlignment.Left);
            _with1.Columns.Add("Time", 40, HorizontalAlignment.Right);
            _with1.Columns.Add("Isk Bounty", 100, HorizontalAlignment.Right);
            _with1.Columns.Add("Bounty/Min", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Isk Loot", 100, HorizontalAlignment.Right);
            _with1.Columns.Add("Loot/Min", 60, HorizontalAlignment.Right);
            _with1.Columns.Add("LP", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("LP/Min", 60, HorizontalAlignment.Right);
            _with1.Columns.Add("Total ISK/Min", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Lost Drones", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Ammo Consumption", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Ammo Value", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Panics", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Lowest Shield", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Lowest Armor", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Lowest Cap", 80, HorizontalAlignment.Right);
            _with1.Columns.Add("Repair Cycles", 80, HorizontalAlignment.Right);


            var _with2 = LstMision;

            _with2.View          = View.Details;
            _with2.FullRowSelect = true;
            _with2.GridLines     = true;
            _with2.LabelEdit     = false;
            _with2.Columns.Clear();
            _with2.Items.Clear();

            _with2.Columns.Add("", 0, HorizontalAlignment.Right);
            _with2.Columns.Add("Mission", 240, HorizontalAlignment.Left);
            _with2.Columns.Add("Repet %", 60, HorizontalAlignment.Right);
            _with2.Columns.Add("Time", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media Isk Bounty", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media Isk Loot", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media LP", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media ISK/Min", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Lost Drones", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media Ammo Consumption", 100, HorizontalAlignment.Right);
            _with2.Columns.Add("Media Ammo Value", 100, HorizontalAlignment.Right);
            return;
        }
Beispiel #47
0
        public Lfx.Types.OperationResult Backup(BackupInfo backupInfo)
        {
            string WorkFolder = backupInfo.Name + System.IO.Path.DirectorySeparatorChar;

            Lfx.Environment.Folders.EnsurePathExists(this.BackupPath);

            if (!System.IO.Directory.Exists(Lfx.Environment.Folders.TemporaryFolder + WorkFolder))
            {
                System.IO.Directory.CreateDirectory(Lfx.Environment.Folders.TemporaryFolder + WorkFolder);
            }

            Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Creando copia de seguridad", "Se está creando un volcado completo del almacén de datos en una carpeta, para resguardar.");
            Progreso.Modal     = true;
            Progreso.Advertise = true;
            Progreso.Begin();
            Progreso.Max = Lfx.Workspace.Master.Structure.Tables.Count + 1;

            Progreso.ChangeStatus("Exportando estructura");
            Progreso.ChangeStatus(Progreso.Value + 1);
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.AppendChild(Lfx.Workspace.Master.Structure.ToXml(doc));
            doc.Save(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "dbstruct.xml");

            BackupWriter Writer = new BackupWriter(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "dbdata.lbd");

            Writer.Write(":BKP");

            IList <string> TableList = Lfx.Data.DatabaseCache.DefaultCache.GetTableNames();

            foreach (string Tabla in TableList)
            {
                string NombreTabla = Tabla;
                if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(Tabla))
                {
                    NombreTabla = Lfx.Workspace.Master.Structure.Tables[Tabla].Label;
                }

                Progreso.ChangeStatus("Volcando " + NombreTabla);
                Progreso.ChangeStatus(Progreso.Value + 1);
                ExportTableBin(Tabla, Writer);
            }
            Writer.Close();

            System.IO.FileStream Archivo = new System.IO.FileStream(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "info.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write);
            using (System.IO.StreamWriter Escribidor = new System.IO.StreamWriter(Archivo, System.Text.Encoding.Default)) {
                Escribidor.WriteLine("Copia de seguridad de Lázaro");
                Escribidor.WriteLine("");
                Escribidor.WriteLine("Empresa=" + backupInfo.CompanyName);
                Escribidor.WriteLine("EspacioTrabajo=" + Lfx.Workspace.Master.Name);
                Escribidor.WriteLine("FechaYHora=" + System.DateTime.Now.ToString("dd-MM-yyyy") + " a las " + System.DateTime.Now.ToString("HH:mm:ss"));
                Escribidor.WriteLine("Usuario=" + backupInfo.UserName);
                Escribidor.WriteLine("Estación=" + Lfx.Environment.SystemInformation.MachineName);
                Escribidor.WriteLine("VersiónLazaro=" + backupInfo.ProgramVersion);
                Escribidor.WriteLine("");
                Escribidor.WriteLine("Por favor no modifique ni elimine este archivo.");
                Escribidor.Close();
                Archivo.Close();
            }

            if (Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting <int>("Sistema.ComprimirCopiasDeSeguridad", 0) != 0)
            {
                Progreso.ChangeStatus("Comprimiendo los datos");
                Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "backup.7z");
                ArchivoComprimido.Add(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "*");
                if (System.IO.File.Exists(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "backup.7z"))
                {
                    Progreso.ChangeStatus("Eliminando archivos temporales");
                    // Borrar los archivos que acabo de comprimir
                    System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(Lfx.Environment.Folders.TemporaryFolder + WorkFolder);
                    foreach (System.IO.FileInfo DirItem in Dir.GetFiles())
                    {
                        if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt")
                        {
                            System.IO.File.Delete(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + DirItem.Name);
                        }
                    }
                }
            }

            Progreso.ChangeStatus("Almacenando");
            Progreso.ChangeStatus(Progreso.Value + 1);
            Lfx.Environment.Folders.MoveDirectory(Lfx.Environment.Folders.TemporaryFolder + WorkFolder, this.BackupPath + WorkFolder);

            int GuardarBackups = Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting <int>("Sisteam.Backup.CantMax", 14);

            if (GuardarBackups > 0)
            {
                List <BackupInfo> ListaDeBackups = this.GetBackups();
                if (ListaDeBackups.Count > GuardarBackups)
                {
                    Progreso.ChangeStatus("Eliminando copias de seguridad antiguas");
                    int BorrarBackups = ListaDeBackups.Count - GuardarBackups;
                    if (BorrarBackups < ListaDeBackups.Count)
                    {
                        for (int i = 1; i <= BorrarBackups; i++)
                        {
                            this.Delete(this.GetOldestBackupName());
                        }
                    }
                }
            }

            Progreso.End();

            return(new Lfx.Types.SuccessOperationResult());
        }
Beispiel #48
0
        public void InitCustomSetting()
        {
            //病历病程是否窗口显示
            ExtendApplicationContext.Current.CustomSettingContext.IsCheckInfoShowDialog = false;

            //检查结果是否窗口显示
            ExtendApplicationContext.Current.CustomSettingContext.IsHisCheckInfo = false;


            //文书中切换使用DEV日期控件
            ExtendApplicationContext.Current.CustomSettingContext.IsShowDevDateTimeEditor = true;

            //程序登入后是否弹出显示术中患者列表
            //ExtendApplicationContext.Current.CustomSettingContext.IsShowUnDonePatientListView = ApplicationConfiguration.IsShowUnDonePatientList;

            //文书中同步手术申请
            ExtendApplicationContext.Current.CustomSettingContext.IsSyncScheduleInfo = true;


            //加载自定义文书模板标识(模板管理-文书模板列表)
            XmlDocument xmlDoc = new XmlDocument();

            //if (System.IO.File.Exists(ExtendApplicationContext.Current.AppPath + @"\DocTemplate\客户化医院\CustomDocTempletFlags.xml"))
            //{
            //    xmlDoc.Load(ExtendApplicationContext.Current.AppPath + @"\DocTemplate\客户化医院\CustomDocTempletFlags.xml");
            //}
            //其他医院打版本需求,不写死医院文件夹
            System.IO.DirectoryInfo dir       = new System.IO.DirectoryInfo(ExtendApplicationContext.Current.AppPath + @"\DocTemplate\");
            System.IO.FileInfo[]    fileInfos = dir.GetFiles("CustomDocTempletFlags.xml", System.IO.SearchOption.AllDirectories);
            if (fileInfos != null && fileInfos.Length > 0)
            {
                xmlDoc.Load(fileInfos[0].FullName);
            }
            if (xmlDoc.ChildNodes.Count > 0)
            {
                foreach (XmlNode xmlNode in xmlDoc.ChildNodes[0].ChildNodes)
                {
                    if (xmlNode is XmlComment)
                    {
                        continue;
                    }
                    ExtendApplicationContext.Current.CustomSettingContext.CustomTempletFlagNames.Add(xmlNode.Name);
                }
            }



            // 获取上传PDF配置
            PostPDF_ServerURL = ApplicationConfiguration.PDFServerUrl;
            PostPDF_LocalURL  = ApplicationConfiguration.PDFLocalUrl;
            //  获取上传PDF配置
            if (!string.IsNullOrEmpty(ApplicationConfiguration.PostPDF_Names))
            {
                PostPDF_Names = ApplicationConfiguration.PostPDF_Names.Split(new char[] { ',' }, StringSplitOptions.None);
            }
            ExtendApplicationContext.Current.CustomSettingContext.IsCheckDocCompelete = true;

            // 获取检查的文书
            if (!string.IsNullOrEmpty(ApplicationConfiguration.DocNameCheckList))
            {
                DocNameCheckList = ApplicationConfiguration.DocNameCheckList.Split(new char[] { ',' }, StringSplitOptions.None);
            }

            //监测项目默认持续配置
            MedSheetContinue = System.Configuration.ConfigurationManager.AppSettings["MedSheetContinue"];
        }
Beispiel #49
0
        //------------------------------------------------------------------
        // Рекурсивная функция поиска файлов по указанным настройками поиска
        public void WalkDirectoryTree(System.IO.DirectoryInfo root)
        {
            System.IO.FileInfo[]      files   = null;
            System.IO.DirectoryInfo[] subDirs = null;

            try
            {
                files = root.GetFiles();
            }

            catch (UnauthorizedAccessException e)
            {
                //log.Add(e.Message);
            }

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

            if (files != null)
            {
                foreach (System.IO.FileInfo fi in files)
                {
                    // предварительная проверка расширения
                    FileInfoExt fiExt = new FileInfoExt(fi);

                    if ((fiExt.IsFileImage() == false) && (fiExt.IsFileVideo() == false))
                    {
                        continue;
                    }

                    // предварительная проверка размера
                    if (fi.Length < 30_000 || fi.Length > 4_000_000_000)
                    {
                        continue;
                    }



                    if (fiExt.level > 0)
                    {
                        AddFileToList(fi, level);
                    }
                }

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

                foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                {
                    // Глобально исключаем папки
                    // Windows "Program Files" "Program Files (x86)" ProgramData
                    // эти папки уже наверное поштучно будем исключать AppData Downloads Загрузки

                    if (dirInfo.Name == "Windows" ||
                        dirInfo.Name == "Program Files" ||
                        dirInfo.Name == "Program Files (x86)" ||
                        dirInfo.Name == "ProgramData" ||
                        dirInfo.Name == "AppData" // ||
                                                  //
                                                  // dirInfo.Name == "Adult"

                        )
                    {
                        continue;
                    }

                    WalkDirectoryTree(dirInfo);
                }
            }
        }
Beispiel #50
0
        private void OptionsDialog_Load(object sender, EventArgs e)
        {
            (new Microsoft.VisualBasic.Devices.Audio()).Stop(); //In case some long .wav file is still playing

            switch (GPS.Disp2)
            {
            case "age":
                this.boxText2.SelectedIndex = 1;
                break;

            case "hdop":
                this.boxText2.SelectedIndex = 2;
                break;

            case "vdop":
                this.boxText2.SelectedIndex = 3;
                break;

            case "pdop":
                this.boxText2.SelectedIndex = 4;
                break;

            case "elevation-feet":
                this.boxText2.SelectedIndex = 5;
                break;

            case "elevation-meters":
                this.boxText2.SelectedIndex = 6;
                break;

            case "speed-mph":
                this.boxText2.SelectedIndex = 7;
                break;

            case "speed-mph-smoothed":
                this.boxText2.SelectedIndex = 8;
                break;

            case "speed-kmh":
                this.boxText2.SelectedIndex = 9;
                break;

            case "speed-kmh-smoothed":
                this.boxText2.SelectedIndex = 10;
                break;

            case "heading":
                this.boxText2.SelectedIndex = 11;
                break;

            default:
                this.boxText2.SelectedIndex = 0;
                break;
            }

            switch (GPS.Disp3)
            {
            case "age":
                this.boxText3.SelectedIndex = 1;
                break;

            case "hdop":
                this.boxText3.SelectedIndex = 2;
                break;

            case "vdop":
                this.boxText3.SelectedIndex = 3;
                break;

            case "pdop":
                this.boxText3.SelectedIndex = 4;
                break;

            case "elevation-feet":
                this.boxText3.SelectedIndex = 5;
                break;

            case "elevation-meters":
                this.boxText3.SelectedIndex = 6;
                break;

            case "speed-mph":
                this.boxText3.SelectedIndex = 7;
                break;

            case "speed-mph-smoothed":
                this.boxText3.SelectedIndex = 8;
                break;

            case "speed-kmh":
                this.boxText3.SelectedIndex = 9;
                break;

            case "speed-kmh-smoothed":
                this.boxText3.SelectedIndex = 10;
                break;

            case "heading":
                this.boxText3.SelectedIndex = 11;
                break;

            default:
                this.boxText3.SelectedIndex = 0;
                break;
            }

            this.boxAudioFile.Items.Clear();
            this.boxAudioFile.Items.Add("None");
            this.boxAudioFile.SelectedIndex = 0;
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath);
            foreach (System.IO.FileInfo fi in di.GetFiles())
            {
                if (fi.Extension == ".wav")
                {
                    //MsgBox(fi.Name)
                    this.boxAudioFile.Items.Add(fi.Name);
                    if (fi.Name == this.NtripParam.AudioFile)
                    {
                        this.boxAudioFile.SelectedIndex = this.boxAudioFile.Items.Count - 1;
                    }
                }
            }

            if (NtripParam.WriteEventsToFile)
            {
                this.boxDoLogging.SelectedIndex = 1;
            }
            else
            {
                this.boxDoLogging.SelectedIndex = 0;
            }

            if (NtripParam.WriteNMEAToFile)
            {
                this.boxDoSaveNMEA.SelectedIndex = 1;
            }
            else
            {
                this.boxDoSaveNMEA.SelectedIndex = 0;
            }
        }
Beispiel #51
0
 public System.IO.FileInfo[] GetAllDocument()
 {
     return(_folder.GetFiles());
 }
        public ActionResult Index(SysAgent SysAgent)
        {
            if (this.BasicAgent.Tier != 1)
            {
                ViewBag.ErrorMsg = "抱歉!该功能只有一级代理可用.";
                return(View("Error"));
            }
            if (this.BasicAgent.IsTeiPai == 0)
            {
                ViewBag.ErrorMsg = "非贴牌用户无法使用该功能";
                return(View("Error"));
            }

            var APPModuleList = Entity.APPModule.Where(o => o.AgentId == this.BasicAgent.Id && o.Version == 0).OrderBy(o => o.Id).ToList();

            ViewBag.APPModuleList = APPModuleList;
            //加载类型选项
            string filename             = HttpContext.Server.MapPath("/ModuleTypeSelectList.json");
            string jsonstr              = System.IO.File.ReadAllText(filename);
            var    ModuleTypeSelectList = JsonConvert.DeserializeObject <SortedList <string, string> >(jsonstr);

            ViewBag.ModuleTypeSelectList = ModuleTypeSelectList;
            string Bottomfilename             = HttpContext.Server.MapPath("/ModuleTypeBottomSelectList.json");
            string Bottomjsonstr              = System.IO.File.ReadAllText(Bottomfilename);
            var    ModuleTypeBottomSelectList = JsonConvert.DeserializeObject <SortedList <string, string> >(Bottomjsonstr);

            ViewBag.ModuleTypeBottomSelectList = ModuleTypeBottomSelectList;
            //加载广告及标识
            AdTag scanCodeTag = Entity.AdTag.FirstOrDefault(o => o.Tag == "SaoBg" && o.State == 1);

            ViewBag.ScanCodeTag = scanCodeTag;
            AdTag bannerTag = Entity.AdTag.FirstOrDefault(o => o.Tag == "banner" && o.State == 1);

            ViewBag.BannerTag = bannerTag;
            if (scanCodeTag == null || bannerTag == null)
            {
                ViewBag.ErrorMsg = "无法找到广告标识";
                return(View("Error"));
            }
            var scanCodeInfo = Entity.AdInfo.FirstOrNew(o => o.TId == scanCodeTag.Id && o.State == 1 && o.AgentId == this.BasicAgent.Id);

            ViewBag.scanCodeInfo = scanCodeInfo;
            var bannerInfos = Entity.AdInfo.OrderBy(o => o.Sort).Where(o => o.TId == bannerTag.Id && o.State == 1 && o.AgentId == this.BasicAgent.Id).ToList();

            ViewBag.bannerInfos = bannerInfos;

            if (Request.UrlReferrer != null)
            {
                Session["Url"] = Request.UrlReferrer.ToString();
            }

            //取得系统图标
            string PhysicalApplicationPath = this.HttpContext.Request.PhysicalApplicationPath;
            string APPModelPath            = PhysicalApplicationPath + "UpLoadFiles\\APPModule\\";
            var    homeDir      = new System.IO.DirectoryInfo(APPModelPath + "home");
            var    bottomDefDir = new System.IO.DirectoryInfo(APPModelPath + "bottom\\default");
            var    bottomActDir = new System.IO.DirectoryInfo(APPModelPath + "bottom\\activate");

            var homeFiles      = homeDir.GetFiles();
            var bottomDefFiles = bottomDefDir.GetFiles();
            var bottomActFiles = bottomActDir.GetFiles();

            ViewBag.homeFiles          = homeFiles;
            ViewBag.bottomDefaultFiles = bottomDefFiles;
            ViewBag.bottomActFiles     = bottomActFiles;

            ViewBag.SysAgent      = this.BasicAgent;
            this.ViewBag.IsAdd    = this.checkPower("Add");
            this.ViewBag.IsSave   = this.checkPower("Save");
            this.ViewBag.IsDelete = this.checkPower("Delete");
            this.ViewBag.IsEdit   = this.checkPower("Edit");
            return(View());
        }
        protected override void BuildXml()
        {
            if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileView))
            {
                ConnectorException.Throw(Errors.Unauthorized);
            }

            // Map the virtual path to the local server path.
            string sServerDir  = this.CurrentFolder.ServerPath;
            bool   bShowThumbs = Request.QueryString["showThumbs"] != null && Request.QueryString["showThumbs"].ToString().Equals("1");

            // Create the "Files" node.
            XmlNode oFilesNode = XmlUtil.AppendElement(this.ConnectorNode, "Files");

            System.IO.DirectoryInfo oDir   = new System.IO.DirectoryInfo(sServerDir);
            System.IO.FileInfo[]    aFiles = oDir.GetFiles();

            for (int i = 0; i < aFiles.Length; i++)
            {
                System.IO.FileInfo oFile      = aFiles[i];
                string             sExtension = System.IO.Path.GetExtension(oFile.Name);

                if (Config.Current.CheckIsHiddenFile(oFile.Name))
                {
                    continue;
                }
                if (oFile.Name.Contains("_") && oFile.Name.Contains("x"))
                {
                    continue;
                }
                if (!this.CurrentFolder.ResourceTypeInfo.CheckExtension(sExtension))
                {
                    continue;
                }

                Decimal iFileSize = Math.Round((Decimal)oFile.Length / 1024);
                if (iFileSize < 1 && oFile.Length != 0)
                {
                    iFileSize = 1;
                }

                // Create the "File" node.
                XmlNode oFileNode = XmlUtil.AppendElement(oFilesNode, "File");
                XmlUtil.SetAttribute(oFileNode, "name", oFile.Name);
                XmlUtil.SetAttribute(oFileNode, "date", oFile.LastWriteTime.ToString("yyyyMMddHHmm"));
                if (Config.Current.Thumbnails.Enabled &&
                    (Config.Current.Thumbnails.DirectAccess || bShowThumbs) &&
                    ImageTools.IsImageExtension(sExtension.TrimStart('.')))
                {
                    bool bFileExists = false;
                    try
                    {
                        bFileExists = System.IO.File.Exists(System.IO.Path.Combine(this.CurrentFolder.ThumbsServerPath, oFile.Name));
                    }
                    catch {}

                    if (bFileExists)
                    {
                        XmlUtil.SetAttribute(oFileNode, "thumb", oFile.Name);
                    }
                    else if (bShowThumbs)
                    {
                        XmlUtil.SetAttribute(oFileNode, "thumb", "?" + oFile.Name);
                    }
                }
                XmlUtil.SetAttribute(oFileNode, "size", iFileSize.ToString(CultureInfo.InvariantCulture));
            }
        }
Beispiel #54
0
        /// <summary>
        /// 遍历文件夹
        /// </summary>
        /// <param name="dirPath">Dir path.</param>
        /// <param name="level">Level.</param>
        private void loopDirectoriesAndFiles(string dirPath, int level, IList <FileInfoModel> list)
        {
            List <Exception> dirExList  = new List <Exception>();
            List <Exception> fileExList = new List <Exception>();

            try
            {
                #region 若不是根目录, 在第一位加上目录 .. (返回)

                if (dirPath.Equals(this.ViewModel.BaseDirectory, StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    System.IO.DirectoryInfo di    = new System.IO.DirectoryInfo(dirPath);
                    FileInfoModel           toAdd = new FileInfoModel()
                    {
                        IsDirectory     = true,
                        IsDirectoryBack = true,

                        // 通用
                        Level = level - 1,

                        // 目录
                        DirectoryName = "..",
                        Directory     = di.Parent.FullName,

                        // 文件
                        Name      = string.Empty,
                        Extension = string.Empty,
                        FullName  = string.Empty,

                        // 图标
                        ModelIcon = ImageSource.FromResource("Client.Images.FileExplorer.record.png")
                    };

                    list.Add(toAdd);
                }

                #endregion

                foreach (var item in System.IO.Directory.GetDirectories(dirPath).OrderBy(i => i))
                {
                    try
                    {
                        string msg = "|{0}{1}".FormatWith("".PadLeft(level, '_'), item);
                        System.Diagnostics.Debug.WriteLine(msg);
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(item);

                        FileInfoModel toAdd = new FileInfoModel()
                        {
                            IsDirectory = true,

                            // 通用
                            Level         = level,
                            LastWriteTime = di.LastWriteTime,

                            // 目录
                            DirectoryName    = di.Name,
                            Directory        = di.FullName,
                            ContainFileCount = di.GetFiles().Length,

                            // 文件
                            Name      = di.Name,
                            Extension = di.Extension,
                            FullName  = di.FullName,

                            // 图标
                            ModelIcon = ImageSource.FromResource("Client.Images.FileExplorer.record.png")
                        };

                        list.Add(toAdd);
                    }
                    catch (Exception dirEx)
                    {
                        dirExList.Add(dirEx);
                    }
                }

                foreach (var item in System.IO.Directory.GetFiles(dirPath).OrderBy(i => i))
                {
                    try
                    {
                        string msg = "|{0}{1}".FormatWith("".PadLeft(level, '_'), item);
                        System.Diagnostics.Debug.WriteLine(msg);
                        System.IO.FileInfo di = new System.IO.FileInfo(item);

                        FileInfoModel toAdd = new FileInfoModel()
                        {
                            IsDirectory = false,

                            // 通用
                            Level         = level,
                            LastWriteTime = di.LastWriteTime,

                            // 目录
                            DirectoryName = di.DirectoryName,
                            Directory     = di.Directory.FullName,

                            // 文件
                            Name           = di.Name,
                            Extension      = di.Extension,
                            FullName       = di.FullName,
                            FileLength     = di.Length,
                            FileLengthInfo = Util.IO.FileUtils.GetFileLengthInfo(di.Length),

                            // 图标
                            // ModelIcon = ImageSource.FromResource("Client.Images.FileExplorer.file.svg")
                            ModelIcon = ImageSource.FromResource("Client.Images.FileExplorer.file.png")
                                        // ModelIcon = ImageSource.FromFile()
                        };

                        list.Add(toAdd);
                    }
                    catch (Exception fileEx)
                    {
                        fileExList.Add(fileEx);
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = ex.GetFullInfo();
                System.Diagnostics.Debug.WriteLine(msg);
                DisplayAlert("Error", msg, "确认");
            }
            finally
            {
                string msg = string.Empty;
                if (dirExList.Count > 0)
                {
                    msg += $"遍历文件夹时捕获到读取文件夹信息错误共 {dirExList.Count} 个;";
                }

                if (fileExList.Count > 0)
                {
                    msg += $"遍历文件夹时捕获到读取文件错误共 {fileExList.Count} 个;";
                }

                if (msg.IsNullOrWhiteSpace() == false)
                {
                    System.Diagnostics.Debug.WriteLine(msg);
                    DisplayAlert("Error", msg, "确认");
                }
            }
        }
Beispiel #55
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // Noget LINQ kode- LINQ står for Language Integrated Query
            var mappe = new System.IO.DirectoryInfo(@"c:\temp");
            var filer = mappe.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

            Console.WriteLine($"Antal filer i temp: {filer.Length:N0}");

            var res1 = from fil in filer
                       orderby fil.Length
                       group fil by fil.Extension into f
                       select f;

            var res2 = filer
                       .OrderBy(i => i.Length)
                       .GroupBy(i => i.Extension);

            Console.WriteLine($"Der findes {res1.Count()} forskellige extensions i mappen.");
            Console.WriteLine($"Der findes {res2.Count()} forskellige extensions i mappen.");

            var res3 = from fil in filer select fil;
            var res4 = filer;

            // Execution
            Console.WriteLine($"Der findes {res3.Count()} filer i mappen.");
            Console.WriteLine($"Der findes {res4.Count()} filer i mappen.");

            var res5 = (from fil in filer where fil.Extension == ".txt" select fil).ToList();
            var res6 = filer.Where(i => i.Extension == ".txt").ToList();

            Console.WriteLine($"Der findes {res5.Count()} .txt-filer i mappen.");
            Console.WriteLine($"Der findes {res6.Count()} .txt-filer i mappen.");

            var res7 = from fil in filer where fil.Extension == ".txt" select fil;
            var res8 = filer.Where(i => i.Extension == ".txt");

            Console.WriteLine($"Der findes {res7.Count()} .txt-filer i mappen.");
            Console.WriteLine($"Der findes {res8.Count()} .txt-filer i mappen.");

            // Execution
            var res9  = from fil in filer where fil.Extension == ".txt" orderby fil.FullName select fil;
            var res10 = filer.Where(i => i.Extension == ".txt").OrderBy(i => i.FullName);

            foreach (var item in res7)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"Der findes {res9} .txt-filer i mappen");

            foreach (var item in res9)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"Der findes {res10} .txt-filer i mappen");

            foreach (var item in res10)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            Console.WriteLine("Gruppering");

            var res11 = from fil in filer group fil by fil.Extension into gruppe select gruppe;
            var res12 = filer.GroupBy(x => x.Extension);

            // resultat er IGrouping<string, FileInfo> - kan ses ved at holde musen over var ovenfor
            foreach (var item in res11)
            {
                Console.WriteLine("Gruppe");
                foreach (var fil in item)
                {
                    Console.WriteLine(fil.FullName);
                }
            }

            Console.WriteLine();
            Console.WriteLine("Udfladning af lister");

            var res13 = from fil in filer group fil by fil.Extension into gruppe from r in gruppe select r;
            var res14 = filer.GroupBy(i => i.Extension).SelectMany(i => i);

            Console.WriteLine($"Res13 består af {res13.Count()} ting");
            Console.WriteLine($"Res14 består af {res14.Count()} ting");

            foreach (var item in res13)
            {
                Console.WriteLine(item.ToString());
            }

            Console.WriteLine();
            Console.WriteLine("Projecting");

            // En liste af strenge
            var res15 = from f in filer
                        select new
            {
                Navn      = f.Name,
                Størrelse = f.Length
            };
            var res16 = filer.Select(f => new { Navn = f.Name, Størrelse = f.Length });

            foreach (var item in res15)
            {
                Console.WriteLine(item);
                Console.WriteLine(item.GetType());
                Console.WriteLine(item.Navn);
                Console.WriteLine(item.Størrelse);
            }

            try
            {
                Console.WriteLine($"Res15 består af {res15.Count()} ting");
                Console.WriteLine($"Res16 består af {res16.Count()} ting");
            }
            catch (Exception)
            {
                throw;
            }

            //Joining
            Console.WriteLine();
            Console.WriteLine("Joining");

            var personer = opgave_LINQ.Person.HentPersoner();

            personer.Add(new Person()
            {
                Navn = "William", IdLand = 1
            });
            var lande = Land.HentLande();

            var res17 = from pers in personer
                        join land in lande
                        on pers.IdLand equals land.IdLand
                        select new
            {
                Navn = pers.Navn,
                Land = land.Navn
            };


            Console.WriteLine();
            Console.WriteLine("Experiments");

            var res18 = from land in lande
                        join pers in personer
                        on land.IdLand equals pers.IdLand
                        select land;

            //select new
            //{
            //    Navn = pers.Navn,
            //    Land = land.Navn
            //};

            foreach (var item in res18)
            {
                Console.WriteLine(item.Navn);
                Console.WriteLine(item.IdLand);
            }
        }
        private void VerificarArchivoImagen(Entidades.Imagenes 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();

            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))
                    {
                        Panel pnlImagen = CrearPanelImagen(idImagen);

                        pnlImagenes.Controls.Add(pnlImagen);

                        Image imgPendiente = CrearImagePendiente(urlImagen, titulo);

                        pnlImagen.Controls.Add(imgPendiente);

                        Panel pnlCalificar = CrearPanelCalificar(idImagen);

                        pnlImagen.Controls.Add(pnlCalificar);

                        Button btnAprobar = CrearButtonAprobar(idImagen);

                        pnlCalificar.Controls.Add(btnAprobar);

                        Button btnRechazar = CrearButtonRechazar(idImagen);

                        pnlCalificar.Controls.Add(btnRechazar);

                        esArchivoEncontrado = true;

                        break;
                    }
                }

                if (!esArchivoEncontrado)
                {
                    Panel pnlImagen = CrearPanelImagen(idImagen);

                    pnlImagenes.Controls.Add(pnlImagen);

                    Literal litImagenNoEncontrada = CrearLiteralImagenNoEncontrada(rutaRelativa);

                    pnlImagen.Controls.Add(litImagenNoEncontrada);
                }
            }
            else if (!directorio.Exists)
            {
                Label lblSinArchivos = CrearLabelDirectorioNoExistente();

                pnlImagenes.Controls.Add(lblSinArchivos);
            }
        }
        public ActionResult Index(SysAgent SysAgent, EFPagingInfo <APPModule> p, int SourceAgentId = 0)
        {
            var APPModuleList = Entity.APPModule.Where(o => o.AgentId == SysAgent.Id && o.Version == 1 && o.State == 1).OrderBy(o => o.Sort).ToList();

            ViewBag.APPModuleList = APPModuleList;
            var APPBlockList = Entity.APPBlock.Where(o => o.AgentId == SysAgent.Id && o.State == 1).OrderBy(o => o.Sort).ToList();

            ViewBag.APPBlockList = APPBlockList;
            //加载类型选项
            string filename             = HttpContext.Server.MapPath("/ModuleTypeSelectList.json");
            string jsonstr              = System.IO.File.ReadAllText(filename);
            var    ModuleTypeSelectList = JsonConvert.DeserializeObject <SortedList <string, string> >(jsonstr);

            ViewBag.ModuleTypeSelectList = ModuleTypeSelectList;
            string Bottomfilename             = HttpContext.Server.MapPath("/ModuleTypeBottomSelectList.json");
            string Bottomjsonstr              = System.IO.File.ReadAllText(Bottomfilename);
            var    ModuleTypeBottomSelectList = JsonConvert.DeserializeObject <SortedList <string, string> >(Bottomjsonstr);

            ViewBag.ModuleTypeBottomSelectList = ModuleTypeBottomSelectList;
            //加载广告及标识
            AdTag bannerTag = Entity.AdTag.FirstOrDefault(o => o.Tag == "newBanner" && o.State == 1);

            ViewBag.BannerTag = bannerTag;
            if (bannerTag == null)
            {
                ViewBag.ErrorMsg = "无法找到广告标识";
                return(View("Error"));
            }
            var bannerInfos = Entity.AdInfo.OrderBy(o => o.Sort).Where(o => o.TId == bannerTag.Id && o.State == 1 && o.AgentId == SysAgent.Id).ToList();

            ViewBag.bannerInfos = bannerInfos;
            //贴牌代理
            var SysAgentList  = Entity.SysAgent.Where(o => o.IsTeiPai == 1 && o.State == 1).ToList();
            var haofusysagent = new SysAgent()
            {
                Id           = 0,
                Name         = "好付",
                AppBtnNumber = BasicSet.AppBtnNumber,
                APPHasMore   = BasicSet.APPHasMore,
                APPName      = BasicSet.Name,
            };

            SysAgentList.Add(haofusysagent);
            SysAgentList          = SysAgentList.OrderBy(o => o.Id).ToList();
            ViewBag.SysAgentList  = SysAgentList;
            ViewBag.SysAgent      = SysAgentList.FirstOrNew(o => o.Id == SysAgent.Id);
            ViewBag.SourceAgentId = SourceAgentId;
            if (Request.UrlReferrer != null)
            {
                Session["Url"] = Request.UrlReferrer.ToString();
            }

            //取得系统图标
            string PhysicalApplicationPath = this.HttpContext.Request.PhysicalApplicationPath;
            string APPModelPath            = PhysicalApplicationPath + "UpLoadFiles\\APPModule\\";
            var    homeDir      = new System.IO.DirectoryInfo(APPModelPath + "home2");
            var    bottomDefDir = new System.IO.DirectoryInfo(APPModelPath + "bottom2\\default");
            var    bottomActDir = new System.IO.DirectoryInfo(APPModelPath + "bottom2\\activate");

            var homeFiles      = homeDir.GetFiles();
            var bottomDefFiles = bottomDefDir.GetFiles();
            var bottomActFiles = bottomActDir.GetFiles();

            ViewBag.homeFiles          = homeFiles;
            ViewBag.bottomDefaultFiles = bottomDefFiles;
            ViewBag.bottomActFiles     = bottomActFiles;

            //公告
            var Notice = this.Entity.MsgNotice.Where(o => (o.AgentId == 0 || o.AgentId == SysAgent.Id) && (o.NType == 0 || o.NType == 3) && o.State == 1).OrderByDescending(o => o.Id)
                         .Select(o => new { info = o.Info }).FirstOrDefault();
            var ninfo = string.Empty;

            if (Notice != null)
            {
                ninfo += Notice.info.IsNullOrEmpty() ? Notice.info : Utils.RemoveHtml(Notice.info) + "          ";
            }
            ViewBag.ninfo = ninfo;

            this.ViewBag.IsSave       = this.checkSignPower("Save");
            this.ViewBag.IsDelete     = this.checkSignPower("Delete");
            this.ViewBag.IsImportData = this.checkPower("ImportData");
            return(View());
        }
    private bool GatherModifiedFiles()
    {
        _WwiseObjectsToRemove.Clear();
        _WwiseObjectsToAdd.Clear();

        var bChanged     = false;
        var iBasePathLen = s_wwiseProjectPath.Length + 1;

        foreach (var scannedAsset in AssetType.ScannedAssets)
        {
            var dir          = scannedAsset.RootDirectoryName;
            var deleted      = new System.Collections.Generic.List <int>();
            var knownFiles   = AkWwiseProjectInfo.GetData().GetWwuListByString(dir);
            var cKnownBefore = knownFiles.Count;

            try
            {
                //Get all Wwus in this folder.
                var di    = new System.IO.DirectoryInfo(System.IO.Path.Combine(s_wwiseProjectPath, dir));
                var files = di.GetFiles("*.wwu", System.IO.SearchOption.AllDirectories);
                System.Array.Sort(files, s_FileInfo_CompareByPath);

                //Walk both arrays
                var iKnown = 0;
                var iFound = 0;

                while (iFound < files.Length && iKnown < knownFiles.Count)
                {
                    var workunit     = knownFiles[iKnown] as AkWwiseProjectData.WorkUnit;
                    var foundRelPath = files[iFound].FullName.Substring(iBasePathLen);
                    switch (workunit.PhysicalPath.CompareTo(foundRelPath))
                    {
                    case 0:
                        //File was there and is still there.  Check the FileTimes.
                        try
                        {
                            if (files[iFound].LastWriteTime > workunit.LastTime)
                            {
                                //File has been changed!
                                //If this file had a parent, parse recursively the parent itself
                                m_WwuToProcess.Add(files[iFound].FullName);
                                FlagForRemoval(scannedAsset.Type, iKnown);
                                bChanged = true;
                            }
                        }
                        catch
                        {
                            //Access denied probably (file does exists since it was picked up by GetFiles).
                            //Just ignore this file.
                        }

                        iFound++;
                        iKnown++;
                        break;

                    case 1:
                        m_WwuToProcess.Add(files[iFound].FullName);
                        iFound++;
                        break;

                    case -1:
                        //A file was deleted.  Can't process it now, it would change the array indices.
                        deleted.Add(iKnown);
                        iKnown++;
                        break;
                    }
                }

                //The remainder from the files found on disk are all new files.
                for (; iFound < files.Length; iFound++)
                {
                    m_WwuToProcess.Add(files[iFound].FullName);
                }

                //All the remainder is deleted.  From the end, of course.
                if (iKnown < knownFiles.Count)
                {
                    for (var i = iKnown; i < knownFiles.Count; ++i)
                    {
                        FlagForRemoval(scannedAsset.Type, i);
                    }

                    knownFiles.RemoveRange(iKnown, knownFiles.Count - iKnown);
                }

                //Delete those tagged.
                for (var i = deleted.Count - 1; i >= 0; i--)
                {
                    FlagForRemoval(scannedAsset.Type, deleted[i]);
                    knownFiles.RemoveAt(deleted[i]);
                }

                bChanged |= cKnownBefore != knownFiles.Count;
            }
            catch
            {
                return(false);
            }
        }

        return(bChanged || m_WwuToProcess.Count > 0);
    }
        private void _CompressZIP(string pathFileZip, IDTSComponentEvents componentEvents)
        {
            System.IO.DirectoryInfo di   = new System.IO.DirectoryInfo(_folderSource);
            System.IO.FileInfo[]    fi_s = di.GetFiles("*.*", (_recurse ? System.IO.SearchOption.AllDirectories : System.IO.SearchOption.TopDirectoryOnly));
            bool b = false;

            try
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream fz = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(pathFileZip)))
                {
                    fz.SetLevel(9);

                    if (!string.IsNullOrEmpty(_comment))
                    {
                        componentEvents.FireInformation(1, "UnZip SSIS", "Set Comment.", null, 0, ref b);
                        fz.SetComment(_comment);
                    }

                    if (!string.IsNullOrWhiteSpace(_password))
                    {
                        componentEvents.FireInformation(1, "UnZip SSIS", "Set Password.", null, 0, ref b);
                        fz.Password = _password;
                    }


                    foreach (System.IO.FileInfo fi in fi_s)
                    {
                        if (!System.Text.RegularExpressions.Regex.Match(fi.FullName, _fileFilter).Success)
                        {
                            componentEvents.FireInformation(1, "UnZip SSIS", _typeCompression.ToString() + ": file " + fi.FullName + " doesn't match regex filter '" + _fileFilter + "'. File not processed.", null, 0, ref b);
                            continue;
                        }

                        componentEvents.FireInformation(1, "UnZip SSIS", _typeCompression.ToString() + ": Compress (with '" + _storePaths.ToString() + "') file: " + fi.FullName, null, 0, ref b);

                        string file_name = "";
                        ICSharpCode.SharpZipLib.Zip.ZipEntry ze = null;

                        if (_storePaths == Store_Paths.Absolute_Paths)
                        {
                            //Absolute Path
                            file_name = ICSharpCode.SharpZipLib.Zip.ZipEntry.CleanName(fi.FullName);
                            ze        = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file_name);
                        }
                        else if (_storePaths == Store_Paths.Relative_Paths)
                        {
                            //Relative Path
                            ICSharpCode.SharpZipLib.Zip.ZipNameTransform zn = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(_folderSource);
                            file_name = zn.TransformFile(fi.FullName);
                            if (_addRootFolder)
                            {
                                file_name = (di.Name + "/" + file_name).Replace("//", "/");
                            }
                            ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file_name);
                        }
                        else if (_storePaths == Store_Paths.No_Paths)
                        {
                            //No Path
                            file_name = fi.Name;
                            ze        = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file_name);
                        }
                        else
                        {
                            throw new Exception("Please select type Store Paths (No_Paths / Relative_Paths / Absolute_Paths).");
                        }

                        using (System.IO.FileStream fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            ze.Size = fs.Length;
                            fz.PutNextEntry(ze);

                            fs.CopyTo(fz);

                            fs.Flush();
                            fz.Flush();

                            fz.CloseEntry();
                        }
                    }

                    fz.Flush();
                }

                _Check_ZIP(pathFileZip, componentEvents);
            }
            catch (Exception ex)
            {
                componentEvents.FireError(1000, "UnZip SSIS", ex.Message, null, 0);
                throw;
            }
            finally
            {
            }
        }
        public void Compare(List <string> lstFileType)
        {
            // Create two identical or different temporary folders
            // on a local drive and change these file paths.


            System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(_OldVcp);
            System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(_NewVcp);

            // 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);

            // 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)
            {
                foreach (var v in queryCommonFiles)
                {
                    if (lstFileType.Count > 0)
                    {
                        if (lstFileType.Contains(v.Extension.ToUpper()))
                        {
                            _lstSameResult.Add(v.FullName);
                        }
                    }
                    else
                    {
                        _lstSameResult.Add(v.FullName);
                    }
                }
            }

            // 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);

            foreach (var v in queryList1Only)
            {
                if (lstFileType.Count > 0)
                {
                    if (lstFileType.Contains(v.Extension.ToUpper()))
                    {
                        _lstDiffResult1.Add(v.FullName);
                    }
                }
                else
                {
                    _lstDiffResult1.Add(v.FullName);
                }
            }

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

            foreach (var v in queryList1Only1)
            {
                if (lstFileType.Count > 0)
                {
                    if (lstFileType.Contains(v.Extension.ToUpper()))
                    {
                        _lstDiffResult2.Add(v.FullName);
                    }
                }
                else
                {
                    _lstDiffResult2.Add(v.FullName);
                }
            }
        }