Exemple #1
0
        //构造函数(略缩图数量, 略缩图路径, DIY略缩图路径)
        public PicLoader(int capacity, string icoPath, string diyIcoPath)
        {
            DB2Config config = DB2Config.GetInstance();

            if (!string.Equals(config.GetSetting("NotShowIco"), "True", StringComparison.OrdinalIgnoreCase))
            {
                //读取参数
                refreshinterval = MyTools.Config.GetIntValue(config.GetSetting("RefreshInterval"), 200);
                loadpicinterval = MyTools.Config.GetIntValue(config.GetSetting("LoadPicInterval"), 20);
                loadoncenum     = MyTools.Config.GetIntValue(config.GetSetting("LoadPicOnceNum"), 10);

                //初始化
                Global.loadPicEnd = false;
                Capacity          = capacity;
                IcoPath           = FileTools.DirToPath(FileTools.RelativeToAbsolutePath(icoPath));
                DIYIcoPath        = FileTools.DirToPath(FileTools.RelativeToAbsolutePath(diyIcoPath));
                NeedShow          = new Stack <PicInfo>();
                IndexMapper       = new Hashtable(capacity + 1);

                //将所有载入略缩图请求压栈
                for (int i = capacity - 1; i >= 0; i--)
                {
                    NeedShow.Push(new PicInfo(i, false));
                }

                //在新线程载入略缩图
                Thread WorkThread = new Thread(new ThreadStart(LoadPic));
                WorkThread.IsBackground = true;
                WorkThread.Priority     = ThreadPriority.BelowNormal;
                WorkThread.Start();
            }
            else
            {
                DoLoadEnd();
            }
        }
Exemple #2
0
        private static IEnumerable <byte[]> DecompressedParts(string nameOfCompressedFile)
        {
            var dynamicPartConfiguration = new DynamicPartConfiguration
            {
                PartSize = BitConverter.GetBytes(default(int)).Length
            };

            var enumerable = FileTools.ReadFileByDynamicParts(nameOfCompressedFile, dynamicPartConfiguration);

            using var enumerator = enumerable.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var lengthBytes  = enumerator.Current;
                var lengthOfPart = BitConverter.ToInt32(lengthBytes, 0);
                dynamicPartConfiguration.PartSize = lengthOfPart;

                enumerator.MoveNext();
                var compressed   = enumerator.Current;
                var decompressed = compressed.DecompressPart();
                dynamicPartConfiguration.PartSize = lengthBytes.Length;

                yield return(decompressed);
            }
        }
Exemple #3
0
        private void RemoveFromFile(string word)
        {
            try
            {
                FileStream fstream = new FileStream(this.m_dictionaryFileName, FileMode.Open, FileAccess.ReadWrite);

                long offset = FileTools.GetWordStartPositionInFile(fstream, word);

                if (offset == -1)
                {
                    //throw new Exception("Word was in the dictionary, but not in the file.");
                    return;
                }

                FileTools.RemoveLineFromPosition(fstream, offset);

                fstream.Close();
                fstream.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #4
0
        public void PutAudioFile(string file)
        {
            string ext = Path.GetExtension(file);

            if (Regex.IsMatch(ext, @"^\.[0-9A-Za-z]+$") == false)
            {
                throw new Exception("Bad (audio) ext: " + ext);
            }

            if (this.MFile != null)
            {
                FileTools.Delete(this.MFile);
                this.MFile = null;
                this.MInfo = null;
            }

            {
                string wFile = this.WD.GetPath("audio" + ext);

                File.Copy(file, wFile);

                this.MFile = wFile;
            }
        }
Exemple #5
0
        public static RecogReply PredictionFunc(Guid id, int timeBudgetInMS, RecogRequest req)
        {
            byte[] imgBuf      = req.Data;
            byte[] imgType     = System.Text.Encoding.UTF8.GetBytes("jpg");
            Guid   imgID       = BufferCache.HashBufferAndType(imgBuf, imgType);
            string imgFileName = imgID.ToString() + ".jpg";

            string filename = Path.Combine(saveImageDir, imgFileName);

            if (!File.Exists(filename))
            {
                FileTools.WriteBytesToFileConcurrent(filename, imgBuf);
            }

            string result_words   = wordDetector.DetectWords(filename);
            string result_feature = wordDetector.ExtractFeature(filename);

            string resultString = result_words + "\n" + result_feature;

            File.Delete(filename);
            numImageRecognized++;
            Console.WriteLine("Image {0}: {1}", numImageRecognized, resultString);
            return(VHubRecogResultHelper.FixedClassificationResult(resultString, resultString));
        }
Exemple #6
0
        }        // -----------------------------------------

        /// <summary>
        /// Check if path exists and create it
        /// If it exists, rename it to a new safe name, then return the new name
        /// </summary>
        /// <returns></returns>
        public static string checkCreateUniqueOutput(string partA, string partB = "")
        {
            string path;

            // -
            try{
                path = Path.Combine(partA, partB);
            }catch (ArgumentException) {
                return(null);
            }

            // Get unique path
            while (Directory.Exists(path))
            {
                path = path + "_";
            }
            // Path now is unique
            if (!FileTools.createDirectory(path))
            {
                return(null);
            }
            // Path is created OK
            return(path);
        } // -----------------------------------------
Exemple #7
0
        public static void AddSunRiseSetLinesToImage(Image <Rgb24> image, FileInfo sunriseSetData, int startdayOfYear, int endDayOfYear, int pixelStep)
        {
            List <string> lines    = FileTools.ReadTextFile(sunriseSetData.FullName);
            int           imageRow = 0;

            for (int i = startdayOfYear; i <= endDayOfYear; i++) // skip header
            {
                string[] fields = lines[i].Split(',');

                // the sunrise data hasthe below line format
                // DayOfyear    Date    Astro start Astro end   Naut start  Naut end    Civil start Civil end   Sunrise   Sunset
                //    1       1-Jan-13  3:24 AM      8:19 PM    3:58 AM      7:45 PM    4:30 AM     7:13 PM     4:56 AM   6:47 PM

                int      dayOfYear    = int.Parse(fields[0]);
                string[] sunriseArray = fields[6].Split(' ');
                string[] sunsetArray  = fields[7].Split(' ');
                sunriseArray = sunriseArray[0].Split(':');
                sunsetArray  = sunsetArray[0].Split(':');
                int sunriseMinute = (int.Parse(sunriseArray[0]) * 60) + int.Parse(sunriseArray[1]);
                int sunsetMinute  = (int.Parse(sunsetArray[0]) * 60) + int.Parse(sunsetArray[1]) + 720;
                for (int px = 0; px < pixelStep; px++)
                {
                    image[sunriseMinute, imageRow] = Color.White;
                    image[sunsetMinute, imageRow]  = Color.White;
                    imageRow++;
                }

                // this is a hack to deal with inserting weekly gridlines rather than overwriting the image.
                // This was done for EASY images but not for 3D!!
                // ONE DAY THIS WILL HAVE TO BE FIXED!
                if (dayOfYear % 7 == 0 || dayOfYear % 30 == 0)
                {
                    imageRow++;
                }
            }
        }
Exemple #8
0
        // < conf items

        public void loadConf()
        {
            try
            {
                List <string> lines = new List <string>();

                foreach (string line in FileTools.readAllLines(getConfFile(), StringTools.ENCODING_SJIS))
                {
                    if (line != "" && line[0] != ';')
                    {
                        lines.Add(line);
                    }
                }

                int c = 0;

                if (int.Parse(lines[c++]) != lines.Count)
                {
                    throw new Exception("Bad item count");
                }

                // conf items >

                consoleWinStyle          = (ProcessTools.WindowStyle_e) int.Parse(lines[c++]);
                passphraseSuffix         = lines[c++];
                disconnectAndShiftKeysUp = StringTools.toFlag(lines[c++]);
                clearLogCycle            = long.Parse(lines[c++]);
                antiScreenSaver          = StringTools.toFlag(lines[c++]);

                // < conf items
            }
            catch (Exception e)
            {
                Utils.WriteLog(e);
            }
        }
Exemple #9
0
        Coordinate[] GetCoordinates(BinaryReader binReader, Detail detail)
        {
            UInt32 size;

            Coordinate[] coordinate;
            switch (detail)
            {
            case Detail.Simple:
            case Detail.Extended:
                size       = binReader.ReadUInt32() / (uint)Marshal.SizeOf(typeof(Coordinate));
                coordinate = new Coordinate[size];
                FileTools.BinaryToArray <Coordinate>(binReader, coordinate);
                return(coordinate);

            case Detail.Full:
                size       = binReader.ReadUInt32() / (uint)Marshal.SizeOf(typeof(Extended));
                coordinate = new Extended[size];
                FileTools.BinaryToArray <Extended>(binReader, (Extended[])coordinate);
                return(coordinate);

            default:
                return(null);
            }
        }
Exemple #10
0
        private void SerializePart(WorkshopItemType part, NetStream stream)
        {
            byte[] array = null;
            RagdollPresetPartMetadata part2 = GetPart(part);

            if (part2 != null)
            {
                array = part2.bytes;
                if (array == null && !string.IsNullOrEmpty(folder))
                {
                    string path = FileTools.Combine(folder, part.ToString() + ".png");
                    array = FileTools.ReadAllBytes(path);
                }
            }
            if (array != null)
            {
                stream.Write(v: true);
                stream.WriteArray(array, 32);
            }
            else
            {
                stream.Write(v: false);
            }
        }
Exemple #11
0
        public StringsFile(byte[] buffer, String filePath)
        {
            IsStringsFile = true;

            FilePath = filePath;
            StringId = _GetStringId(filePath);
            if (StringId == null)
            {
                throw new Exceptions.DataFileStringIdNotFound(filePath);
            }
            Attributes = DataFileMap[StringId];

            // create field delegators
            FieldInfo[] dataFileFields = Attributes.RowType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            dataFileFields = dataFileFields.OrderBy(f => f.MetadataToken).ToArray(); // order by defined order - GetFields does not guarantee ordering
            Delegator      = new ObjectDelegator(dataFileFields);

            Rows = new List <Object>();

            int  peek  = FileTools.ByteArrayToInt32(buffer, 0);
            bool isCSV = (peek != Token.Header);

            HasIntegrity = ((isCSV)) ? ParseCSV(buffer) : ParseData(buffer);
        }
Exemple #12
0
        private void AddPath(string path)
        {
            if (Directory.Exists(path))
            {
                path = FileTools.MakeFullPath(path);

                string dropRootDir = path;

                if (CommonUtils.IsRootDir(dropRootDir) == false)
                {
                    dropRootDir = Path.GetDirectoryName(dropRootDir);
                    dropRootDir = FileTools.MakeFullPath(dropRootDir);
                }

                foreach (string file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
                {
                    this.AddFile(file, dropRootDir);
                }
            }
            else
            {
                this.AddFile(path);
            }
        }
Exemple #13
0
    private static void SetAtlasAdvancedProps(string atlasPngPath)
    {
        AssetDatabase.StartAssetEditing();
        string                  assetPath = FileTools.getRelativePath(atlasPngPath);
        TextureImporter         ti        = AssetImporter.GetAtPath(assetPath) as TextureImporter;
        TextureImporterSettings tis       = new TextureImporterSettings();

        tis.spriteMeshType      = SpriteMeshType.FullRect;
        tis.alphaIsTransparency = true;
        tis.spriteExtrude       = 1;
        tis.spritePixelsPerUnit = 100f;
        ti.SetTextureSettings(tis);
        ti.wrapMode         = TextureWrapMode.Clamp;
        ti.filterMode       = FilterMode.Bilinear;
        ti.textureType      = TextureImporterType.Advanced;
        ti.spriteImportMode = SpriteImportMode.Multiple;
        ti.mipmapEnabled    = MIPMAP_ENABLED;
        ti.maxTextureSize   = 2048;
        ti.textureFormat    = TextureImporterFormat.AutomaticCompressed;
        ti.anisoLevel       = 16;
        AssetDatabase.WriteImportSettingsIfDirty(assetPath);
        AssetDatabase.StopAssetEditing();
        AssetDatabase.Refresh();
    }
Exemple #14
0
        private static T FromConfigFile <T>(string ConfigFileNameWithoutPath, bool IsCheckParent) where T : class, new()
        {
            //查找文件
            FileInfo file = FileTools.FindFile(ConfigFileNameWithoutPath);

            if (file == null || file.Exists == false)
            {
                if (IsCheckParent == true && FileTools.CurrentDirectory.Parent.Exists)//没有文件, 有父目录, 默认放到父目录下
                {
                    file = new FileInfo(Path.Combine(FileTools.CurrentDirectory.Parent.FullName, ConfigFileNameWithoutPath));
                }
                else//没有文件, 没有父目录, 默认放到当前目录下
                {
                    file = new FileInfo(Path.Combine(FileTools.CurrentDirectory.FullName, ConfigFileNameWithoutPath));
                }
            }

            if (file.Exists)
            {
                return(FromConfigFile <T>(file.FullName));
            }

            return(null);
        }
        public override void Initialize()
        {
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/version", getVersion, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/ConsoleInfo", ConsoleInfo, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/Broadcast", Broadcast, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/getPlayerData", getPlayerData, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/GroupList", GroupList, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/PlayerList", PlayerList, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/BanList", BanList, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/WorldInfo", WorldInfo, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/GroupInfo", GroupInfo, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/serverInfo", serverInfo, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/getLog", getLog, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/updateMOTD", updateMOTD, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/getConfig", getConfig, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/getConfigDescription", getConfigDescription, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/updateConfig", updateConfig, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/searchusers", searchUsers, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/updateInventory", updateInventory, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/userlist", UserList, "AdminRest.allow"));
            TShock.RestApi.Register(new SecureRestCommand("/AdminREST/getInventory", getInventory, "AdminRest.allow"));

            FileTools.SetupConfig();
        }
Exemple #16
0
        /// <summary>
        /// This method reads a single file containg a single day of index values.
        /// The method assumes that the file name has following structure:  XXXXX_YYYYMMDD.SpectralIndices.PivotTable.csv
        /// </summary>
        public static List <string> GetDaySlice(DirectoryInfo dataTableDir, int year, int dayOfYear)
        {
            string key = KeyDayOfYear;

            LoggedConsole.WriteLine("GetDataSlice() for DayOfYear=" + dayOfYear + ": ");

            //get structure of the first file name in the directory
            FileInfo[] fileList = dataTableDir.GetFiles();
            FileInfo   file     = fileList[0];

            // split the file name into component parts
            string[] nameParts = file.Name.Split('.');
            string[] stemParts = nameParts[0].Split('_');

            var date = new DateTime(year, 1, 1).AddDays(dayOfYear - 1);

            //string stem = stemParts[0] + "_" + date.Year + date.Month + date.Day + "." + nameParts[1] + "." + nameParts[2] + nameParts[3];
            string stem =
                $"{stemParts[0]}_{date.Year:d4}{date.Month:d2}{date.Day:d2}.{nameParts[1]}.{nameParts[2]}.{nameParts[3]}";

            string path = Path.Combine(dataTableDir.FullName, stem);

            if (!File.Exists(path))
            {
                return(new List <string>());
            }

            List <string> list = FileTools.ReadSelectedLinesOfCsvFile(path, key, dayOfYear);

            if (list == null)
            {
                return(new List <string>());
            }

            return(list);
        }
Exemple #17
0
    /// <summary>
    /// 检查单个文件
    /// </summary>
    /// <param name="path"></param>
    void GetOneLuaTextList(string path)
    {
        string filename = FileTools.GetFilename(path, false);

        string[] lines = FileTools.ReadAllLines(path);
        for (int j = 0; j < lines.Length; j++)
        {
            string content = lines[j];
            if (string.IsNullOrEmpty(content) == true)
            {
                continue;
            }
            if (StringTools.isContainCN(content) == false)
            {
                continue;
            }
            if (content.Contains("error") || content.Contains("print") || content.Contains("--"))
            {
                continue;
            }
            int index = content.IndexOf('"');
            if (index == -1)
            {
                continue;
            }
            string[]      arr      = content.Split('"');
            int           len      = arr.Length;
            List <string> lineList = new List <string>();
            for (int m = 0; m < len; m++)
            {
                lineList.Add(arr[m]);
            }
            lines[j] = ReplaceSingleLine(lines[j], lineList, filename);
        }
        FileTools.SaveAllLines(path, lines);
    }
Exemple #18
0
        private void SaveOutputBtn_Click(object sender, EventArgs e)
        {
            List <double> outp = GetOutput();

            if (outp.Count == 0)
            {
                MessageBox.Show("нет данных", "Error");
                return;
            }
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    FileTools file = new FileTools(saveFileDialog.FileName);
                    file.BinWriterOpen();
                    file.WriteBinList(outp);
                    file.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
        }
Exemple #19
0
        private void _PropertiesScriptToByteArray(ref byte[] buffer, ref int offset)
        {
            foreach (ExcelFunction excelScript in ExcelFunctions)
            {
                foreach (ExcelFunction.Parameter paramater in excelScript.Parameters)
                {
                    FileTools.WriteToBuffer(ref buffer, ref offset, Token.mysh);
                    FileTools.WriteToBuffer(ref buffer, ref offset, Token.MyshVersion);

                    FileTools.WriteToBuffer(ref buffer, ref offset, (Int32)paramater.Name.Length);
                    FileTools.WriteToBuffer(ref buffer, ref offset, paramater.Name);
                    FileTools.WriteToBuffer(ref buffer, ref offset, paramater.Unknown);
                    FileTools.WriteToBuffer(ref buffer, ref offset, paramater.TypeId);
                    FileTools.WriteToBuffer(ref buffer, ref offset, paramater.TypeValues.ToByteArray());
                }

                if (excelScript.ScriptByteCode == null)
                {
                    continue;
                }
                FileTools.WriteToBuffer(ref buffer, ref offset, (Int32)excelScript.ScriptByteCode.Length);
                FileTools.WriteToBuffer(ref buffer, ref offset, excelScript.ScriptByteCode);
            }
        }
 public static void SetAssetName(ResourceInfo resInfo, string rootName, List <string> assetNames)
 {
     string[] Dirs = Directory.GetDirectories(RootPath + rootName);
     for (int i = 0; i < Dirs.Length; i++)
     {
         string path = Dirs[i].Replace("\\", "/");
         string name = FileTools.GetFullName(path);
         //Debug.LogWarning (path);
         //Debug.LogWarning (name);
         ResourceItemInfo item = new ResourceItemInfo();
         item.Path = name;
         item.Name = name;
         if (name == "resident")
         {
             item.IsResident = true;
         }
         GetResItemInfo(resInfo, item.Path, item.IsResident, assetNames);
         //item.Dependencies = GetResItemInfo (item.Path, item.IsResident);
         item.ResNames = new List <string> ();
         resInfo.ResList.Add(item);
         assetNames.Add(item.Name);
         item.IsAsset = AssetHeplerEditor.SetAssetBundleName(path, item.Name, item.ResNames);
     }
 }
Exemple #21
0
        public void Main01()
        {
            FileTools.Delete(W_DIR);
            FileTools.CreateDir(W_DIR);

            this.SpData = new SpectrumData(Path.Combine(R_DIR, "Spectrum.csv"));

            while (this.Frame < this.SpData.Rows.Length)
            {
                double[] row = this.SpData.Rows[this.Frame];

                DDCurtain.DrawCurtain();
                DDPrint.SetPrint(0, 20, 23);

                for (int index = 0; index < 45; index++)
                {
                    double lv = 0.0;

                    for (int c = 0; c < 2; c++)
                    {
                        lv += row[index * 2 + c];
                    }

                    int iLv = DoubleTools.ToInt(lv * 145.0);

                    for (int c = 0; c < iLv; c++)
                    {
                        DDPrint.Print("*");
                    }

                    DDPrint.PrintRet();
                }

                this.MG_EachFrame();
            }
        }
Exemple #22
0
        private string GetFileText(string path)
        {
            /*
             * Check the file isn't already open.
             */

            foreach (QuickSharp.Core.Document document in
                     _mainForm.ClientWindow.Documents)
            {
                ScintillaEditForm editor =
                    document as ScintillaEditForm;

                if (editor != null && FileTools.MatchPaths(path, editor.FilePath))
                {
                    return(editor.Editor.Text);
                }
            }

            /*
             * Read the content from the disk.
             */

            return(FileTools.ReadFile(path));
        }
    public static void SetDependencies(ResourceInfo itemInfo, string outPath)
    {
        //string info = File.ReadAllText (Path.Combine (AssetOutPath, ResInfoName));
        //ResourceInfo itemInfo = JsonUtility.FromJson<ResourceInfo> (info);

        AssetBundle         ab = AssetBundle.LoadFromFile(FileTools.CombinePath(outPath, AssetHeplerEditor.GetPlatformName()));
        AssetBundleManifest m  = ab.LoadAsset <AssetBundleManifest> ("AssetBundleManifest");

        //Debug.Log (m.GetAllDependencies("10001")[0]);
        for (int i = 0; i < itemInfo.ResList.Count; i++)
        {
            if (itemInfo.ResList [i].IsAsset)
            {
                itemInfo.ResList [i].Dependencies = m.GetAllDependencies(itemInfo.ResList [i].Name);
            }
        }
        ab.Unload(true);
//		string infoPath = Path.Combine (AssetOutPath, ResInfoName);
//		using (StreamWriter streamWriter = new StreamWriter(infoPath, false)) {
//			streamWriter.WriteLine(JsonUtility.ToJson(itemInfo));
//			streamWriter.Flush();
//		}
//		Debug.LogWarning (JsonUtility.ToJson(itemInfo));
    }
 private void btnExportExcel_Click(object sender, EventArgs e)
 {
     try
     {
         string FilenameDefault = "BaoCao_DSDiaChi_MoiGioi.xls";
         saveFileDialog1.FileName = FilenameDefault;
         if (saveFileDialog1.ShowDialog() == DialogResult.OK)
         {
             FileStream objFile = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate);
             // gridEXExporter1.GridEX = grdDSDiaChiMoiGioi;
             gridEXExporter1.Export((Stream)objFile);
             // objFile.Close();
             if (MessageBox.Show(this, "Tạo file Excel thành công. Bạn có muốn mở file?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
             {
                 FileTools.OpenFileExcel(saveFileDialog1.FileName);
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Có lỗi tạo file excel", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     btnExportExcel.Enabled = false;
 }
        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            try
            {
                string FilenameDefault = "BaoCao_CSKH_TongHop.xls";
                saveFileDialog1.FileName = FilenameDefault;
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    using (FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    {
                        gridEXExporter1.Export(fs);
                    }

                    if (new MessageBox.MessageBoxBA().Show(this, "Tạo file Excel thành công. Bạn có muốn mở file?", "Thông báo", MessageBox.MessageBoxButtonsBA.YesNoCancel, MessageBox.MessageBoxIconBA.Question) == DialogResult.Yes.ToString())
                    {
                        FileTools.OpenFileExcel(saveFileDialog1.FileName);
                    }
                }
            }
            catch
            {
                new MessageBox.MessageBoxBA().Show("Có lỗi tạo file Excel.", "Thông báo");
            }
        }
    private void CaptureThumbnail(Camera camera, string thumbPath)
    {
        RenderTexture renderTexture = null;

        renderTexture = new RenderTexture(256, 256, 16, RenderTextureFormat.ARGB32);
        RenderTexture renderTexture2 = null;
        RenderTexture renderTexture3 = null;

        renderTexture2 = new RenderTexture(512, 512, 16, RenderTextureFormat.ARGB32);
        renderTexture3 = (camera.targetTexture = renderTexture2);
        camera.Render();
        Graphics.Blit(renderTexture2, renderTexture);
        RenderTexture.active = null;
        camera.targetTexture = null;
        UnityEngine.Object.DestroyImmediate(renderTexture2);
        RenderTexture.active = renderTexture;
        Texture2D texture2D = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, mipmap: false);

        texture2D.ReadPixels(new Rect(0f, 0f, renderTexture.width, renderTexture.height), 0, 0);
        RenderTexture.active = null;
        camera.targetTexture = null;
        UnityEngine.Object.DestroyImmediate(renderTexture);
        FileTools.WriteTexture(thumbPath, texture2D);
    }
        public void OpenFileThrowsRightException(string missingFile, string errorMessage)
        {
            string missingFileExt = Path.GetExtension(missingFile);

            List <string> extensions = new List <string>()
            {
                ".shp", ".shx", ".dbf", ".prj"
            };

            extensions.Remove(missingFileExt);

            var source         = Path.Combine(_shapefiles, missingFile);
            var tmpFile        = FileTools.GetTempFileName(".shp");
            var missingTmpFile = Path.ChangeExtension(tmpFile, missingFileExt);

            foreach (var ext in extensions)
            {
                var sourceName  = Path.ChangeExtension(source, ext);
                var tmpFileName = Path.ChangeExtension(tmpFile, ext);

                Assert.NotNull(tmpFileName, "tmpFileName != null");
                File.Copy(sourceName, tmpFileName);
            }

            if (errorMessage != string.Empty)
            {
                var e = Assert.Throws <FileNotFoundException>(() => FeatureSet.OpenFile(tmpFile));
                Assert.AreEqual(string.Format(errorMessage, missingTmpFile), e.Message);
            }
            else
            {
                Assert.DoesNotThrow(() => FeatureSet.OpenFile(tmpFile));
            }

            FileTools.DeleteShapeFile(tmpFile);
        }
        public static void EnsureIntranetLibraryExists(string db_base_path, string db_title, string db_description, string id = null)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            try
            {
                string base_path = db_base_path;

                if (!Directory.Exists(base_path))
                {
                    DirectoryTools.CreateDirectory(base_path);
                }

                EnsureWarningFilesArePresent(base_path);

                // If the file exists, check that we don't need to update its details
                string library_detail_path = IntranetLibraryTools.GetLibraryDetailPath(base_path);
                if (File.Exists(library_detail_path))
                {
                    try
                    {
                        IntranetLibraryDetail library_detail = IntranetLibraryDetail.Read(library_detail_path);
                        if (library_detail.Title != db_title || library_detail.Description != db_description)
                        {
                            library_detail.Title       = db_title;
                            library_detail.Description = db_description;
                            IntranetLibraryDetail.Write(library_detail_path, library_detail);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.Error(ex, "There was an error while updating an Intranet Library path, so will try to delete and recreate... (path: {0})", base_path);
                        FileTools.Delete(library_detail_path);
                    }
                }

                // If the file does not exist, create it from scratch
                if (!File.Exists(library_detail_path))
                {
                    IntranetLibraryDetail library_detail = new IntranetLibraryDetail();
                    library_detail.Id          = String.IsNullOrEmpty(id) ? IntranetLibraryDetail.GetRandomId() : id;
                    library_detail.Title       = db_title;
                    library_detail.Description = db_description;
                    IntranetLibraryDetail.Write(library_detail_path, library_detail);
                }

                // If the sync database does not exist, put one in place.
                IntranetLibraryDB db = new IntranetLibraryDB(base_path);

                // Notify the WebLibraryManager
                WebLibraryManager.Instance.UpdateKnownWebLibraryFromIntranet(base_path, suppress_flush_to_disk: false, extra_info_message_on_skip: String.Format("as specified in file {0}", library_detail_path));

                // make sure the PDF/documents database is loaded into memory:
                WebLibraryManager.Instance.InitAllLoadedLibraries();
            }
            catch (Exception ex)
            {
                Logging.Error(ex, $"Problem accessing Intranet Library for the first time. (Id: {id}, path: '{db_base_path}', DB title: '{db_title}', Description: '{db_description}'");

                throw;
            }
        }
        public void SaveFeatureToShapefileWithMandZ(CoordinateType c, FeatureType ft)
        {
            var fileName = FileTools.GetTempFileName(".shp");

            try
            {
                List <Coordinate> coords = new List <Coordinate>
                {
                    new Coordinate(1, 2, 7, 4),
                    new Coordinate(3, 4, 5, 6),
                    new Coordinate(5, 6, 3, 8),
                    new Coordinate(7, 8, 9, 10),
                    new Coordinate(1, 2, 7, 4)
                };

                var fs = new FeatureSet(ft)
                {
                    Projection     = KnownCoordinateSystems.Geographic.World.WGS1984,
                    CoordinateType = c
                };

                switch (ft)
                {
                case FeatureType.Line:
                    fs.AddFeature(new LineString(coords.ToArray()));
                    break;

                case FeatureType.Polygon:
                    fs.AddFeature(new Polygon(new LinearRing(coords.ToArray())));
                    break;

                case FeatureType.MultiPoint:
                    coords.RemoveAt(4);
                    fs.AddFeature(new MultiPoint(coords.CastToPointArray()));
                    break;
                }

                Assert.DoesNotThrow(() => fs.SaveAs(fileName, true));

                var loaded = FeatureSet.Open(fileName);

                if (c == CoordinateType.Regular)
                {
                    // regular coordinates don't have m values
                    Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.Coordinates[0].M);
                    Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.M);
                    Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.M);
                }
                else
                {
                    // m or z coordinates have m values
                    Assert.AreEqual(4, loaded.Features[0].Geometry.Coordinates[0].M);
                    Assert.AreEqual(4, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.M);
                    Assert.AreEqual(10, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.M);
                }

                if (c == CoordinateType.Z)
                {
                    // z coordinates have z values
                    Assert.AreEqual(7, loaded.Features[0].Geometry.Coordinates[0].Z);
                    Assert.AreEqual(3, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.Z);
                    Assert.AreEqual(9, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.Z);
                }
                else
                {
                    // regular and m coordinates don't have z values
                    Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.Coordinates[0].Z);
                    Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Minimum.Z);
                    Assert.AreEqual(double.NaN, loaded.Features[0].Geometry.EnvelopeInternal.Maximum.Z);
                }
            }
            finally
            {
                FileTools.DeleteShapeFile(fileName);
            }
        }
		// TODO: write a generic method for each Primitive type, in order to avoid boxing to object.
		internal Object ReadPrimitiveObjectFromBinaryStream(FileTools.BinaryReader2 binaryReader, L3TypeManager typeManager, bool CompressIntsAs7Bits)
		{
			TypeCode tc = (TypeCode)typeManager.TypeIndex;
#if DEBUG
			if ((int)tc < (int)TypeCode.Boolean)
				throw new ArgumentException("data is not a Primitive type");
#endif
			switch (tc)
			{
				case TypeCode.Boolean:
					return binaryReader.ReadBoolean();
				case TypeCode.Byte:
					return binaryReader.ReadByte();
				case TypeCode.Char:
					return binaryReader.ReadChar();
				case TypeCode.DateTime:
					return new DateTime(binaryReader.ReadInt64());
				case TypeCode.Decimal:
					return binaryReader.ReadDecimal();
				case TypeCode.Double:
					return binaryReader.ReadDouble();
				case TypeCode.SByte:
					return binaryReader.ReadSByte();
				case TypeCode.Single:
					return binaryReader.ReadSingle();
				case TypeCode.String:
					return binaryReader.ReadString();

				case TypeCode.Int16:
					if (CompressIntsAs7Bits)
						return binaryReader.ReadSpecial7BitEncodedShort();
					else
						return binaryReader.ReadInt16();
				case TypeCode.Int32:
					if (CompressIntsAs7Bits)
						return binaryReader.ReadSpecial7BitEncodedInt();
					else
						return binaryReader.ReadInt32();
				case TypeCode.Int64:
					if (CompressIntsAs7Bits)
						return binaryReader.ReadSpecial7BitEncodedLong();
					else
						return binaryReader.ReadInt64();
				case TypeCode.UInt16:
					if (CompressIntsAs7Bits)
						return binaryReader.Read7BitEncodedUShort();
					else
						return binaryReader.ReadUInt16();
				case TypeCode.UInt32:
					if (CompressIntsAs7Bits)
						return binaryReader.Read7BitEncodedUInt();
					else
						return binaryReader.ReadUInt32();
				case TypeCode.UInt64:
					if (CompressIntsAs7Bits)
						return binaryReader.Read7BitEncodedULong();
					else
						return binaryReader.ReadUInt64();

				default:
#if DEBUG
					throw new Exception();
#else
					return null;
#endif
			}
		}
        public void SaveShapeFileCustomFieldMappings(bool customFieldMapper)
        {
            if (customFieldMapper)
            {
                FieldTypeCharacterMapperManager.Mapper = new CustomTestFieldMapper();
            }

            var featureType    = FeatureType.Line;
            var coordinateType = CoordinateType.Regular;
            var fileName       = FileTools.GetTempFileName(".shp");

            try
            {
                var coords = new List <Coordinate>
                {
                    new Coordinate(1, 2),
                    new Coordinate(3, 4),
                    new Coordinate(5, 6),
                    new Coordinate(7, 8),
                    new Coordinate(1, 2)
                };

                var fs = new FeatureSet(featureType)
                {
                    Projection     = KnownCoordinateSystems.Geographic.World.WGS1984,
                    CoordinateType = coordinateType
                };

                fs.DataTable.Columns.Add(new DataColumn("doublefield", typeof(double)));
                fs.DataTable.Columns.Add(new DataColumn("decimalfield", typeof(decimal)));
                fs.DataTable.Columns.Add(new DataColumn("floatfield", typeof(float)));
                fs.DataTable.Columns.Add(new DataColumn("stringfield", typeof(string)));

                var feature = fs.AddFeature(new LineString(coords.ToArray()));
                feature.DataRow.BeginEdit();
                feature.DataRow["doublefield"]  = 0.05d;
                feature.DataRow["decimalfield"] = 0.05m;
                feature.DataRow["floatfield"]   = 0.05f;
                feature.DataRow["stringfield"]  = "hello world";
                feature.DataRow.EndEdit();

                Assert.DoesNotThrow(() => fs.SaveAs(fileName, true));

                var loaded = FeatureSet.Open(fileName);
                if (customFieldMapper)
                {
                    Assert.True(new Field(loaded.DataTable.Columns[0]).TypeCharacter == FieldTypeCharacters.Double);
                    Assert.True(new Field(loaded.DataTable.Columns[1]).TypeCharacter == FieldTypeCharacters.Double);
                    Assert.True(new Field(loaded.DataTable.Columns[2]).TypeCharacter == FieldTypeCharacters.Double);
                }
                else
                {
                    Assert.True(new Field(loaded.DataTable.Columns[0]).TypeCharacter == FieldTypeCharacters.Number);
                    Assert.True(new Field(loaded.DataTable.Columns[1]).TypeCharacter == FieldTypeCharacters.Number);
                    Assert.True(new Field(loaded.DataTable.Columns[2]).TypeCharacter == FieldTypeCharacters.Number);
                }

                Assert.True(((Field)loaded.DataTable.Columns[3]).TypeCharacter == FieldTypeCharacters.Text);
            }
            finally
            {
                FileTools.DeleteShapeFile(fileName);
                FieldTypeCharacterMapperManager.Mapper = new FieldTypeCharacterMapper();
            }
        }
		// ----------------------------------------------------------------------

		//[System.Runtime.CompilerServices.MethodImpl((System.Runtime.CompilerServices.MethodImplOptions)256)] // AggressiveInlining
		static protected void WriteValueToBinaryWriter(
			FileTools.BinaryWriter2 bw, object data, bool CompressIntsAs7Bits, TypeCode typeCode)
		{
#if DEBUG
			if ((int)typeCode < (int)TypeCode.Boolean)
				throw new ArgumentException("data is not a Primitive type");
#endif
			switch (typeCode)
			{
				case TypeCode.Boolean:
					bw.Write((bool)data);
					break;
				case TypeCode.Byte:
					bw.Write((byte)data);
					break;
				case TypeCode.Char:
					bw.Write((char)data);
					break;
				case TypeCode.DateTime:
					bw.Write(((DateTime)data).Ticks);
					break;
				case TypeCode.Decimal:
#if (SILVERLIGHT || PORTABLE) && !WINDOWS_PHONE8
						bw.WriteDecimal((Decimal)data);
#else
					bw.Write((Decimal)data);
#endif
					break;
				case TypeCode.Double:
					bw.Write((double)data);
					break;
				case TypeCode.SByte:
					bw.Write((SByte)data);
					break;
				case TypeCode.Single:
					bw.Write((Single)data);
					break;
				case TypeCode.String:
					bw.Write((string)data);
					break;
				case TypeCode.Int16:
					if (CompressIntsAs7Bits)
						bw.WriteSpecial7BitEncodedShort((Int16)data);
					else
						bw.Write((Int16)data);
					break;
				case TypeCode.Int32:
					if (CompressIntsAs7Bits)
						bw.WriteSpecial7BitEncodedInt((Int32)data);
					else
						bw.Write((Int32)data);
					break;
				case TypeCode.Int64:
					if (CompressIntsAs7Bits)
						bw.WriteSpecial7BitEncodedLong((Int64)data);
					else
						bw.Write((Int64)data);
					break;
				case TypeCode.UInt16:
					if (CompressIntsAs7Bits)
						bw.Write7BitEncodedUShort((UInt16)data);
					else
						bw.Write((UInt16)data);
					break;
				case TypeCode.UInt32:
					if (CompressIntsAs7Bits)
						bw.Write7BitEncodedUInt((UInt32)data);
					else
						bw.Write((UInt32)data);
					break;
				case TypeCode.UInt64:
					if (CompressIntsAs7Bits)
						bw.Write7BitEncodedULong((UInt64)data);
					else
						bw.Write((UInt64)data);
					break;

				default:
#if DEBUG
					throw new Exception();
#else
						break;
#endif
			}
		}