private static void ProcessPath(string strPath, List <string> listLua) { string strPrefex = Application.dataPath; strPrefex = strPrefex.Replace("Assets", ""); string strFullPath = strPrefex + strPath; if (FileFunc.IsExistDirectory(strFullPath)) { int i; string[] arrFiles = FileFunc.GetFileNames(strFullPath, "*.lua", true); for (i = 0; i < arrFiles.Length; i++) { arrFiles[i] = arrFiles[i].Replace("\\", "/"); } listLua.AddRange(arrFiles); } else { if (strFullPath.LastIndexOf(".lua") != -1 || strFullPath.LastIndexOf(".Lua") != -1 || strFullPath.LastIndexOf(".LUA") != -1) { strFullPath = strFullPath.Replace("\\", "/"); listLua.Add(strFullPath); } } }
private void moveToWithStructureToolStripMenuItem_Click(object sender, EventArgs e) { try { FolderBrowserDialog dlg = new FolderBrowserDialog(); dlg.SelectedPath = txtPath.Text; dlg.ShowNewFolderButton = true; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { for (int i = 0; i < data.SelectedRows.Count; i++) { try { clData cur = (clData)data.SelectedRows[i].Tag; string movePath = dlg.SelectedPath + "\\" + cur.fileInfo.FullName.Substring(txtPath.Text.Length); Directory.CreateDirectory(FileFunc.GetDirOfFullName(movePath)); cur.fileInfo.MoveTo(movePath); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } catch (Exception ex) { GenFunc.LogAdd(ex); } }
public MainWindow() { InitializeComponent(); this.txtFolderPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); _fileFunctions = new FileFunc(); }
/// <summary> /// 動態建立功能層級商業邏輯物件。 /// </summary> /// <param name="assemblyFile">組件檔案名稱。</param> /// <param name="typeName">類別名稱。</param> /// <param name="sessionGuid">連線識別。</param> /// <param name="progID">程式代碼。</param> private static IBusinessLogic CreateBusinessLogic(string assemblyFile, string typeName, Guid sessionGuid, string progID) { //取得組件的完整路徑 var sAssemblyFile = FileFunc.PathCombine(FileFunc.GetAssemblyPath(), assemblyFile); //動態載入組件,建立指定類別的物件 var oAssemblyLoader = new GAssemblyLoader(sAssemblyFile); return (IBusinessLogic)oAssemblyLoader.CreateInstance(typeName, new object[] { sessionGuid, progID }); }
/// <summary> /// 動態建立 Entity 資料列。 /// </summary> /// <param name="instanceType">動態載入物件的型別描述。</param> /// <returns></returns> public static GEntityRow CreateEntityRow(GInstanceType instanceType) { //取得組件的完整路徑 var assemblyFilePath = FileFunc.PathCombine(FileFunc.GetAssemblyPath(), instanceType.AssemblyFile); //動態載入組件,建立指定類別的物件 var assemblyLoader = new GAssemblyLoader(assemblyFilePath); return (GEntityRow)assemblyLoader.CreateInstance(instanceType.TypeName, new object[] { }); }
/// <summary> /// 清單查詢 /// </summary> public void FindData() { var bl = BusinessFunc.CreateBusinessLogic(this.SessionGuid, "Employee"); var result = bl.Find(new GFindInputArgs()); var table = result.EntityTable; var json = JsonConvert.SerializeObject(table, Formatting.Indented); FileFunc.FileWriteAllText($@"{CurrentPath}\DemoData\FindData", "Employee.json", json); }
/// <summary> /// 儲存定義檔案 /// </summary> /// <param name="defineFile"></param> /// <returns></returns> public void SaveDefine(IDefineFile defineFile) { if (defineFile == null) { throw new GException("Define is null"); } var json = JsonFunc.ObjectToJson(defineFile); FileFunc.FileWriteAllText(defineFile.GetDefineFilePath(), json, true); }
static void initClientModule() { try { foreach (Module module in serverOptions.Modules) { module.Hash = FileFunc.Datei2MD5(@"Modules/" + module.name); } } catch (System.Exception ex) { Log.Logger.log(Log.Logger.LOG_ERROR, ex.ToString()); } }
internal void EncodeVideo() { Status = EnEncoding.Processing; frmMain.isDirty = true; string originalPath = fileInfo.FullName; string newName = fileInfo.FullName.Replace(fileInfo.Extension, ".mp4"); System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(pathBackup)); fileInfo.MoveTo(pathBackup); fileInfo = new System.IO.FileInfo(newName); try { var ffMpeg = new FFMpegConverter(); ConvertSettings c = new ConvertSettings(); //c.VideoCodec = "libx264"; //c.CustomOutputArgs = "-crf 23"; //ffMpeg.ConvertMedia(cur.fileInfo.FullName, null, newName + "23", "MP4", c); //c.CustomOutputArgs = "-crf 1"; //ffMpeg.ConvertMedia(cur.fileInfo.FullName, null, newName + "1", "MP4", c); c.VideoCodec = "libx265"; c.CustomOutputArgs = "-crf 28"; EncodingLog = new StringBuilder(); ffMpeg.FFMpegProcessPriority = System.Diagnostics.ProcessPriorityClass.BelowNormal; ffMpeg.LogReceived += FfMpeg_LogReceived; ffMpeg.ConvertMedia(fileInfo.FullName, null, newName, "MP4", c); string s = EncodingLog.ToString(); updateInfo(); Status = EnEncoding.Encoded; } catch (Exception ex) { GenFunc.LogAdd(ex); FileFunc.TryDelete(newName); fileInfo = new System.IO.FileInfo(pathBackup); fileInfo.MoveTo(originalPath); updateInfo(); Status = EnEncoding.Error; } frmMain.isDirty = true; }
/// <summary> /// 新增資料 /// </summary> public void AddData() { var files = from f in Directory.EnumerateFiles($@"{this.CurrentPath}\DemoData\ImportData", "*.json", SearchOption.TopDirectoryOnly) select new { FileName = FileFunc.GetFileName(f).Replace(".json", ""), Text = FileFunc.FileReadAllText(f) }; foreach (var file in files) { var dt = JsonConvert.DeserializeObject <DataTable>(file.Text); dt.TableName = file.FileName; var table = new GEntityTable(dt); var dataSet = new GEntitySet(file.FileName); dataSet.Tables.Add(table); var bl = BusinessFunc.CreateBusinessLogic(this.SessionGuid, file.FileName); var result = bl.Save(new GSaveInputArgs { EntitySet = dataSet, SaveMode = ESaveMode.Add }); } }
// dir-walk-cb - Higher Order Perl pp. 21-22 public static object Dir_Walk_CB(string top, FileFunc fileFunc, DirFunc dirFunc) { if (PerlFileOps.IsDir(top)) // -d { // There is not an equivalent to Perl's opendir/readir. The line below tries to read the files and directories // in directory "top" and will throw an exception if the directory with this name doesn't exist or has some // kind of access error FileSystemInfo[] filesAndDirs; try { filesAndDirs = (new DirectoryInfo(top)).GetFileSystemInfos(); } catch (Exception e) { Console.WriteLine("Couldn't open directory {0}: {1} - skipping.", top, e.Message); return(null); } // Using List<object> vs. ArrayList, references: // https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netframework-4.8#remarks // https://github.com/dotnet/platform-compat/blob/master/docs/DE0006.md List <object> results = new List <object>(); foreach (FileSystemInfo file in filesAndDirs) { // System.IO doesn't return aliases like "." or ".." for any GetXXX calls // so we don't need code to exclude them object r = Dir_Walk_CB(file.FullName, fileFunc, dirFunc); if (r != null) { results.Add(r); } } return(dirFunc(top, results)); } else { return(fileFunc(top)); } }
/// <summary> /// 程式進入點 /// </summary> /// <param name="args"></param> public static void Main(string[] args) { var baseDir = AppDomain.CurrentDomain.BaseDirectory; var path = FileFunc.PathCombine(baseDir, SysDefineSettingName.Setting); if (!FileFunc.FileExists(path)) { Console.WriteLine($"Set {SysDefineSettingName.APP_Data} Path"); var result = Console.ReadLine(); var json = new JObject { { SysDefineSettingName.APP_Data, result } }; FileFunc.FileWriteAllText(path, json.ToString()); } var setting = JObject.Parse(FileFunc.FileReadAllText(path)); BaseInfo.AppDataPath = setting.TokenAsString(SysDefineSettingName.APP_Data); Console.WriteLine($"{SysDefineSettingName.APP_Data}:{BaseInfo.AppDataPath}"); FileFunc.DirectoryCheck(BaseInfo.AppDataPath); Console.WriteLine(""); Execute(); }
// dir-walk-cb-def - Higher Order Perl p. 24 public static object Dir_Walk_CB_Def(string top, FileFunc fileFunc, DirFunc dirFunc) { if (PerlFileOps.IsDir(top)) // -d { // There is not an equivalent to Perl's opendir/readir. The line below tries to read the files and directories // in directory "top" and will throw an exception if the directory with this name doesn't exist or has some // kind of access error FileSystemInfo[] filesAndDirs; try { filesAndDirs = (new DirectoryInfo(top)).GetFileSystemInfos(); } catch (Exception e) { Console.WriteLine("Couldn't open directory {0}: {1} - skipping.", top, e.Message); return(null); } List <object> results = new List <object>(); foreach (FileSystemInfo file in filesAndDirs) { // System.IO doesn't return aliases like "." or ".." for any GetXXX calls // so we don't need code to exclude them object r = Dir_Walk_CB_Def(file.FullName, fileFunc, dirFunc); if (r != null) { results.Add(r); } } return((dirFunc != null) ? dirFunc(top, results) : null); } else { return((fileFunc != null) ? fileFunc(top) : null); } }
public static void Initialize() { ms_strTemplateLuaPrefix = Application.dataPath + "/MagnaChain/Contract/Src/"; FileInfo[] arrFI = FileFunc.FindAllFiles(ms_strTemplateLuaPrefix, "*.lua", true); int i; int k; string strS; string strP; if (ms_listTemplateLuaFile == null) { ms_listTemplateLuaFile = new List <string>(); } else { ms_listTemplateLuaFile.Clear(); } ms_listTemplateLuaFile.Add("None"); for (i = 0; i < arrFI.Length; i++) { strS = arrFI[i].FullName.Replace("\\", "/"); k = strS.IndexOf("/Src/"); if (k == -1) { continue; } strP = strS.Substring(k + 5); ms_listTemplateLuaFile.Add(strP); } ms_arrTemplateLuaFile = ms_listTemplateLuaFile.ToArray(); ms_kSig.m_texIcon = AssetDatabase.LoadAssetAtPath("Assets/MagnaChain/Editor/res/celllink_icon.png", typeof(Texture)) as Texture; }
private void btnTest_Click(object sender, EventArgs e) { if (Directory.Exists(txtFolder.Text) == true) { //DateTime dt1 = DateTime.Parse(dateTimePicker1.Text); //DateTime dt2 = DateTime.Parse(dateTimePicker2.Text); Config.CreateReportFolder(txtFolder.Text); FileFunc fnc = new FileFunc(); DataTable DT = fnc.GetPDFFileList(txtFolder.Text); if (DT.Rows.Count > 0) { TableLogOnInfo logonInfo = new TableLogOnInfo(); logonInfo.ConnectionInfo.DatabaseName = Config.DbGetDbName; logonInfo.ConnectionInfo.ServerName = Config.DbGetDataSource; logonInfo.ConnectionInfo.UserID = Config.DbGetUserID; logonInfo.ConnectionInfo.Password = Config.DbGetPwd; SummaryReport rpt = new SummaryReport(); frmPrintPreview frm = new frmPrintPreview(); rpt.SetDataSource(DT); rpt.Database.Tables[0].ApplyLogOnInfo(logonInfo); frm.crystalReportViewer1.ReportSource = rpt; frm.StartPosition = FormStartPosition.CenterScreen; frm.WindowState = FormWindowState.Maximized; frm.Show(); } else { MessageBox.Show("ไม่พบข้อมูล"); } } else { MessageBox.Show("ไม่พบโฟล์เดอร์ที่ระบุ"); } }
public override void OnAddedToCommLine() // Выполняем действия при добавлении Линии связи - Чтение шаблона, создание списка Тегов { base.OnAddedToCommLine(); devTemplate = null; fileName = ReqParams.CmdLine == null ? "" : ReqParams.CmdLine.Trim(); string filePath = AppDirs.ConfigDir + fileName; if (fileName == "") { WriteToLog(string.Format(Localization.UseRussian ? "{0} Ошибка: Не задан шаблон устройства для {1}" : "{0} Error: Template is undefined for the {1}", CommUtils.GetNowDT(), Caption)); } else { try { devTemplate = FileFunc.LoadXml(typeof(DevTemplate), filePath) as DevTemplate; fileyes = true; } catch (Exception err) { WriteToLog(string.Format(Localization.UseRussian ? "Ошибка: " + err.Message : "Error: " + err.Message, CommUtils.GetNowDT(), Caption)); } } // Проверка на наличие конфигурации XML if (devTemplate != null) { // Определить Номера активных запросов, посылку команд проводить согласно списку активных запросов. if (devTemplate.SndGroups.Count != 0) // Определить активные запросы и записать в массив номера запросов для создания тегов по номерам телеграмм // Можно упростить до определения индекса { for (int snd = 0; snd < devTemplate.SndGroups.Count; snd++) { if (devTemplate.SndGroups[snd].SndActive) // Если запрос активен, заносим его номер Cnt в Словарь { if (!ActiveSnd.ContainsKey(devTemplate.SndGroups[snd].SndCnt)) // Ключ = SndCnt - Значение = Индекс Активного запроса SndCnt { ActiveSnd.Add(devTemplate.SndGroups[snd].SndCnt, devTemplate.SndGroups.FindIndex(x => x.SndCnt == devTemplate.SndGroups[snd].SndCnt)); } byte[] sndcode = ScadaUtils.HexToBytes(devTemplate.SndGroups[snd].SndCode, true); // Чтение строки HEX из параметра SndCode sndcode_ = sndcode[0]; if (sndcode_ == 0x01) // Проверяем какой номер запроса у параметра SndCode - F=0x01 Текущие параметры { xValCnt01 = devTemplate.SndGroups[snd].SndCnt; // Сохраняем номер запроса (SndCnt) if (devTemplate.SndGroups[snd].SndData != "") { startCnl = Convert.ToInt32(ScadaUtils.StrToDouble(devTemplate.SndGroups[snd].SndData.Trim())); // Сохранить начальный номер сигнала Текущих параметров } } else if (sndcode_ == 0x07) // Или F=0x07 (Вес импульса для Регистратора импульсов) { xValCnt07 = devTemplate.SndGroups[snd].SndCnt; // Сохраняем номер запроса (SndCnt) if (devTemplate.SndGroups[snd].SndData != "") { startCnlv = Convert.ToInt32(ScadaUtils.StrToDouble(devTemplate.SndGroups[snd].SndData.Trim())); // Сохранить начальный номер сигнала Весов импульсов (Регистратор импульсов) } } activeuse = true; // Есть активные запросы } } } if (devTemplate.CmdGroups.Count != 0) // Определяем наличие активных команд и заносим в словарь Индексов команд { for (int cmd = 0; cmd < devTemplate.CmdGroups.Count; cmd++) { if (devTemplate.CmdGroups[cmd].CmdActive) { if (!ActiveCmd.ContainsKey(devTemplate.CmdGroups[cmd].CmdCnl)) // Ключ = номер команды CmdCnl - Значение = Индекс Активной команды CmdCnl { ActiveCmd.Add(devTemplate.CmdGroups[cmd].CmdCnl, devTemplate.CmdGroups.FindIndex(x => x.CmdCnl == devTemplate.CmdGroups[cmd].CmdCnl)); } } } } if (devTemplate.Values.Count != 0) // Проверка наличия записей переменных в конфигурации { if (activeuse) { // ------------------- Сформировать Список параметров по меню ------------------ for (int ac = 0; ac < ActiveSnd.Count; ac++) { var valCnt_ = devTemplate.Values.FindIndex(x => x.ValCnt == ActiveSnd.ElementAt(ac).Key); for (int val = 0; val < devTemplate.Values[valCnt_].Vals.Count; val++) // МЕНЯЕМ valCnt_ на уже проиндексированный Словарь { if (devTemplate.Values[valCnt_].Vals[val].SigActive) // Проверяем переменную на активность { sigN = devTemplate.Values[valCnt_].Vals[val].SigCnl; // читаем номер сигнала переменной ActiveCnl.Add(new ActiveCnlList() { Cnl = sigN, // Номер текущего активного сигнала Name = devTemplate.Values[valCnt_].Vals[val].SigName, // Имя текущего активного сигнала Format = devTemplate.Values[valCnt_].Vals[val].SigType, // Тип переменной активного сигнала IdxValue = valCnt_, // Индекс группы ответа (ValCnt), в которой находится сигнал MenuName = devTemplate.Values[valCnt_].ValMenu }); // Проверяем номер запроса с параметром SndCode = F=0x01 и создаем маску запросов if (devTemplate.Values[valCnt_].ValCnt == xValCnt01) { // Заносим в маску номер сигнала - startCnl (1 по умолчанию) бит по расположению. mask_ch = BitFunc.SetBit(mask_ch, devTemplate.Values[valCnt_].Vals[val].SigCnl - startCnl, devTemplate.Values[valCnt_].Vals[val].SigActive); //maxch = ActiveCnl.FindLast(s => s.IdxValue == ActiveCnl.Find(d => d.Cnl == sigN).IdxValue).Cnl; // Поиск Максимального номер канала для Текущих параметров } // SigCnl - startCnl (1 по умолчанию) определяет какой бит 32-х разрядного числа выставить в 1 (единицу) if (devTemplate.Values[valCnt_].ValCnt == xValCnt07) { // Заносим в маску номер сигнала - startCnlv (41 по умолчанию) бит по расположению. // Номера сигналов для запроса F=0x07, Вес импульса Регистратора импульсов должны начинаться с 41-ого если не задан в SndData mask_chv = BitFunc.SetBit(mask_chv, devTemplate.Values[valCnt_].Vals[val].SigCnl - startCnlv, devTemplate.Values[valCnt_].Vals[val].SigActive); } // SigCnl - startCnlv (41 по умолчанию) определяет какой бит 32-х разрядного числа выставить в 1 (единицу) } } } // ------------ Создание тегов на основе созданного Списка Активных переменных ------------ List <TagGroup> tagGroups = new List <TagGroup>(); TagGroup tagGroup; var categoryCounts = // Считаем количество Меню и количество переменных в Меню в шаблоне from p in ActiveCnl group p by p.MenuName into g select new { NameMenu = g.Key, counts = g.Count() }; int cnt = 0; foreach (var menu in categoryCounts) { tagGroup = new TagGroup(menu.NameMenu); // Создание меню Тегов var actcnl = ActiveCnl.FindAll(s => s.MenuName == menu.NameMenu).OrderBy(d => d.Cnl); // Сортировка активных каналов по каждому меню foreach (var tags in actcnl) { sigN = ActiveCnl.Find(f => f.Cnl == tags.Cnl).Cnl; tagGroup.KPTags.Add(new KPTag(sigN, ActiveCnl.Find(f => f.Cnl == tags.Cnl).Name)); // Заносим в тег Коммуникатора ActiveCnl.Find(s => s.Cnl == sigN).IdxTag = cnt; // Заносим номер тега Коммуникатора в Список cnt++; // Увеличиваем счетчик тегов } tagGroups.Add(tagGroup); // Добавляем группу тегов } InitKPTags(tagGroups); // Инициализация всех тегов // Определяем диапазон каналов в группах Текущие параметры и Вес импульса if (xValCnt01 != 0) // Если запрос с кодом 0x01 активен, переменная xValCnt01 содержит номер запроса { int idx = devTemplate.SndGroups.FindIndex(f => f.SndCnt == xValCnt01); maxch = ActiveCnl.FindLast(d => d.IdxValue == idx).Cnl; // Максимальный номер канала для Текущих параметров res_ch = BitFunc.CountBit32(mask_ch); // Определяем количество бит = 1 в маске текущих параметров string format = ActiveCnl.Find(d => d.IdxValue == idx).Format; if (format == "float" || format == "uint32") { col = 4; } if (format == "double") { col = 8; } } if (xValCnt07 != 0) // Если запрос с кодом 0x07 активен, переменная xValCnt07 содержит номер запроса { int idx = devTemplate.SndGroups.FindIndex(f => f.SndCnt == xValCnt07); maxchv = ActiveCnl.FindLast(d => d.IdxValue == idx).Cnl; // Максимальный номер канала для Веса импульсов res_chv = BitFunc.CountBit32(mask_chv); // Определяем количество бит = 1 в маске Веса импульсов } } } } }
/// <summary> /// 展開程式設定 /// </summary> private static void ExtractProgramSetting() { var progSettings = from f in Directory.EnumerateFiles(SysDefineSettingName.SystemPath, SysDefineSettingName.ProgramSettingName, SearchOption.AllDirectories) select new { Setting = JsonFunc.JsonToObject <GProgramSetting>(FileFunc.FileReadAllText(f)) }; foreach (var set in progSettings) { if (!CacheKeeper.HasItem <GProgramSetting>(nameof(GProgramSetting))) { CacheKeeper.AddItem(nameof(GProgramSetting), set.Setting); ExtractProgramSetting(set.Setting); } } }
/// <summary> /// 程式定義檔案路徑 /// </summary> /// <param name="progID">功能定義</param> /// <returns></returns> public static string ProgramDefineFilePath(string progID) => FileFunc.PathCombine(ProgramDefinePath, $@"{progID}.{ProgramDefineName}");
/// <summary> /// 資料表定義檔案路徑 /// </summary> /// <param name="progID">功能定義</param> /// <returns></returns> public static string DbTableDefineFilePath(string progID) => FileFunc.PathCombine(DbTableDefinePath(), $@"{progID}.{DbTableDefineName}");
/// <summary> /// 資料表定義檔案路徑 /// </summary> /// <returns></returns> public static string DbTableDefinePath() => FileFunc.PathCombine(SystemPath, $@"DbTableDefine");
/// <summary> /// json檔案轉型為定義 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filePath"></param> /// <returns></returns> private static T ConvertToDefine <T>(string filePath) { var json = FileFunc.FileReadAllText(filePath); return(JsonFunc.JsonToObject <T>(json)); }
private void ListPDFFile(DateTime dateFrom, DateTime dateTo, string fldName) { if (Directory.Exists(fldName) == false) { MessageBox.Show("ไม่พบโฟลเดอร์ที่ระบุ"); txtFolder.Focus(); txtFolder.SelectAll(); return; } FileFunc fnc = new FileFunc(); gvFileList.AutoGenerateColumns = false; //gvFileList.DataSource = fnc.GetPDFFileList(dateFrom, dateTo, fldName); gvFileList.DataSource = fnc.GetFileList(dateFrom, dateTo, fldName, "JPG"); }