/// <summary> /// 最多支持2W条一个dat文件 /// </summary> /// <param name="wlList"></param> /// <returns></returns> public IList <string> Export(WordLibraryList wlList) { //Win10拼音对词条长度有限制 wlList = Filter(wlList); var list = new List <WordLibraryList>(); if (wlList.Count > 20000) { SendExportErrorNotice("微软拼音自学习词库最多支持2万条记录的导入,当前词条数为:" + wlList.Count + ",超过限制,请设置过滤条件或者更换词库源。"); //以后微软拼音放开2W限制了,再把这个异常取消吧。 var item20000 = new WordLibraryList(); for (var i = 0; i < wlList.Count; i++) { item20000.Add(wlList[i]); if (i % 19999 == 0 && i != 0) { list.Add(item20000); item20000 = new WordLibraryList(); } } if (item20000.Count != 0) { list.Add(item20000); } } else { list.Add(wlList); } var fileList = ""; for (var i = 0; i < list.Count; i++) { string tempPath = Path.Combine(FileOperationHelper.GetCurrentFolderPath(), "Win10微软拼音自学习词库" + i + ".dat"); if (!string.IsNullOrEmpty(this.ExportFilePath))//For test { tempPath = this.ExportFilePath; } fileList += tempPath + "\r\n"; ExportTo1File(tempPath, list[i]); } return(new List <string>() { "词库文件在:" + fileList }); }
private void MainForm_DragDrop(object sender, DragEventArgs e) { var array = (Array)e.Data.GetData(DataFormats.FileDrop); string files = ""; foreach (object a in array) { string path = a.ToString(); files += path + " | "; } txbWLPath.Text = files.Remove(files.Length - 3); if (array.Length == 1) { cbxFrom.Text = FileOperationHelper.AutoMatchSourceWLType(array.GetValue(0).ToString()); } }
private void btnOpenFileDialog_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { //this.txbWLPath.Text = openFileDialog1.FileName; string files = ""; foreach (string file in openFileDialog1.FileNames) { files += file + " | "; } txbWLPath.Text = files.Remove(files.Length - 3); if (cbxFrom.Text != ConstantString.SELF_DEFINING) { cbxFrom.Text = FileOperationHelper.AutoMatchSourceWLType(openFileDialog1.FileName); } } }
/// <summary> /// 转换多个文件为对应文件名的多个文件 /// </summary> /// <param name="filePathes"></param> /// <param name="outputDir"></param> public void Convert(IList <string> filePathes, string outputDir) { this.timer.Start(); ExportContents = new List <string>(); int c = 0; //filePathes = GetRealPath(filePathes); int fileCount = filePathes.Count; var fileProcessed = 0; foreach (string file in filePathes) { fileProcessed++; DateTime start = DateTime.Now; try { WordLibraryList wlList = import.Import(file); wlList = Filter(wlList); if (selectedTranslate != ChineseTranslate.NotTrans) { wlList = ConvertChinese(wlList); } c += wlList.Count; GenerateWordRank(wlList); ExportContents = export.Export(RemoveEmptyCodeData(wlList)); for (var i = 0; i < ExportContents.Count; i++) { string exportPath = outputDir + (outputDir.EndsWith("\\") ? "" : "\\") + Path.GetFileNameWithoutExtension(file) + (i == 0 ? "" : i.ToString()) + ".txt"; FileOperationHelper.WriteFile(exportPath, export.Encoding, ExportContents[i]); } var costSeconds = (DateTime.Now - start).TotalSeconds; ProcessNotice?.Invoke(fileProcessed + "/" + fileCount + "\t" + Path.GetFileName(file) + "\t转换完成,耗时:" + costSeconds + "秒\r\n"); } catch (Exception ex) { ProcessNotice?.Invoke(fileProcessed + "/" + fileCount + "\t" + Path.GetFileName(file) + "\t处理时发生异常:" + ex.Message + "\r\n"); } } count = c; this.timer.Stop(); }
private void SplitFileByLine(int maxLine) { Encoding encoding = FileOperationHelper.GetEncodingType(txbFilePath.Text); string str = FileOperationHelper.ReadFile(txbFilePath.Text, encoding); string splitLineChar = "\r\n"; if (str.IndexOf(splitLineChar) < 0) { if (str.IndexOf('\r') > 0) { splitLineChar = "\r"; } else if (str.IndexOf('\n') > 0) { splitLineChar = "\n"; } else { MessageBox.Show("不能找到行分隔符"); return; } } string[] list = str.Split(new[] { splitLineChar }, StringSplitOptions.RemoveEmptyEntries); var fileContent = new StringBuilder(); int fileIndex = 1; for (int i = 0; i < list.Length; i++) { fileContent.Append(list[i]); fileContent.Append(splitLineChar); if ((i + 1) % maxLine == 0 || i == list.Length - 1) { if (i != 0) { string newFile = GetWriteFilePath(fileIndex++); FileOperationHelper.WriteFile(newFile, encoding, fileContent.ToString()); rtbLogs.AppendText(newFile + "\r\n"); fileContent = new StringBuilder(); } } } }
private void btnExportKnownWords_Click(object sender, EventArgs e) { saveFileDialog1.FileName = "known.txt"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { var rows = dbOperator.FindAllUserVocabulary(v => v.KnownStatus == KnownStatus.Known) .OrderBy(v => v.Word) .Select(w => w.Word) .ToList(); StringBuilder sb = new StringBuilder(); foreach (var row in rows) { sb.Append(row + "\r\n"); } FileOperationHelper.WriteFile(saveFileDialog1.FileName, Encoding.UTF8, sb.ToString()); MessageBox.Show("导出完成"); } }
public void StreamConvert(IList <string> filePathes, string outPath) { var textImport = import as IWordLibraryTextImport; if (textImport == null) { throw new Exception("流转换,只有文本类型的才支持。"); } StreamWriter stream = FileOperationHelper.GetWriteFileStream(outPath, export.Encoding); foreach (string filePath in filePathes) { var wlStream = new WordLibraryStream(import, export, filePath, textImport.Encoding, stream); wlStream.ConvertWordLibrary(w => IsKeep(w)); } stream.Close(); }
/// <summary> /// 转换多个文件为对应文件名的多个文件 /// </summary> /// <param name="filePathes"></param> /// <param name="outputDir"></param> public void Convert(IList <string> filePathes, string outputDir) { int c = 0; foreach (string file in filePathes) { WordLibraryList wlList = import.Import(file); wlList = Filter(wlList); if (selectedTranslate != ChineseTranslate.NotTrans) { wlList = ConvertChinese(wlList); } c += wlList.Count; GenerateWordRank(wlList); var result = export.Export(RemoveEmptyCodeData(wlList)); var exportPath = outputDir + (outputDir.EndsWith("\\")?"":"\\") + Path.GetFileNameWithoutExtension(file) + ".txt"; FileOperationHelper.WriteFile(exportPath, export.Encoding, result); } count = c; }
/// <summary> /// 读取外部的字典文件,覆盖系统默认字典 /// </summary> /// <param name="dictionary"></param> protected virtual void OverrideDictionary(IDictionary <char, IList <string> > dictionary) { var fileContent = FileOperationHelper.ReadFile("mb.txt"); if (fileContent != "") { foreach (string line in fileContent.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) { string[] arr = line.Split('\t'); if (arr[0].Length == 0) { continue; } char word = arr[0][0]; string code = arr[1]; var codes = code.Split(' '); dictionary[word] = new List <string>(codes);//强行覆盖现有字典 } } }
private string GetMutiPinyin() { string path = ConstantString.PinyinLibPath; var sb = new StringBuilder(); if (File.Exists(path)) { string txt = FileOperationHelper.ReadFile(path); var reg = new Regex(@"^('[a-z]+)+\s[\u4E00-\u9FA5]+$"); string[] lines = txt.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < lines.Length; i++) { if (reg.IsMatch(lines[i])) { sb.Append(lines[i] + "\r\n"); } } } sb.Append(Dictionaries.WordPinyin); return(sb.ToString()); }
/// <summary> /// 删除文件 /// </summary> /// <param name="saveForm"></param> /// <returns></returns> public JsonResult DeleFiles(FormCollection saveForm) { string fileRelIds = saveForm["delFileRelIds"] != null ? saveForm["delFileRelIds"] : ""; InvokeResult result = new InvokeResult(); FileOperationHelper opHelper = new FileOperationHelper(); try { string[] fileRelArray; if (fileRelIds.Length > 0) { fileRelArray = fileRelIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); List <BsonValue> fileRelIdList = new List <BsonValue>(); foreach (var tempId in fileRelArray) { fileRelIdList.Add(tempId.Trim()); } if (fileRelArray.Length > 0) { result = opHelper.DeleteFileByRelIdList(fileRelIdList); if (result.Status == Status.Failed) { throw new Exception(result.Message); } } } } catch (Exception ex) { result.Status = Status.Failed; result.Message = ex.Message; } return(Json(TypeConvert.InvokeResultToPageJson(result), JsonRequestBehavior.AllowGet)); }
private void btnExport_Click(object sender, EventArgs e) { if (MessageBox.Show("是否将文本框中的所有词条保存到本地硬盘上?", "是否保存", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { saveFileDialog1.DefaultExt = ".txt"; if (cbxTo.Text == ConstantString.MS_PINYIN) { saveFileDialog1.DefaultExt = ".dctx"; } if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if (FileOperationHelper.WriteFile(saveFileDialog1.FileName, export.Encoding, richTextBox1.Text)) { ShowStatusMessage("保存成功,词库路径:" + saveFileDialog1.FileName, true); } else { ShowStatusMessage("保存失败", false); } } } }
private void btnMergeWL_Click(object sender, EventArgs e) { string mainWL = FileOperationHelper.ReadFile(txbMainWLFile.Text); Dictionary <string, List <string> > mainDict = ConvertTxt2Dictionary(mainWL); string[] userFiles = txbUserWLFiles.Text.Split('|'); foreach (string userFile in userFiles) { string filePath = userFile.Trim(); string userTxt = FileOperationHelper.ReadFile(filePath); Dictionary <string, List <string> > userDict = ConvertTxt2Dictionary(userTxt); Merge2Dict(mainDict, userDict); } if (cbxSortByCode.Checked) { var keys = new List <string>(mainDict.Keys); keys.Sort(); var sortedDict = new Dictionary <string, List <string> >(); foreach (string key in keys) { sortedDict.Add(key, mainDict[key]); } mainDict = sortedDict; } string result = Dict2String(mainDict); richTextBox1.Text = result; if ( MessageBox.Show("是否将合并的" + mainDict.Count + "条词库保存到本地硬盘上?", "是否保存", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { FileOperationHelper.WriteFile(saveFileDialog1.FileName, Encoding.Unicode, result); } } }
//private void ClearCache() //{ // userVocabularies.Clear(); // cachedDict.Clear(); //} private void btnSave_Click(object sender, EventArgs e) { var nsubtitle = BuildSubtitleFromGrid(); if (nsubtitle == null || nsubtitle.Bodies.Count == 0) { MessageBox.Show("请先点击“载入字幕”按钮打开字幕文件"); return; } //if (meanColor != default(Color)) //{ // Regex r=new Regex(@"\(([^\)]+)\)"); // var fontFormat = "(<font color='#" + meanColor.R.ToString("x2") + meanColor.G.ToString("x2") + // meanColor.B.ToString("x2") + "'>$1</font>)"; // foreach (var kv in nsubtitle.Bodies) // { // var line = kv.Value; // if (r.IsMatch(line.Text)) // { // line.Text = r.Replace(line.Text, fontFormat); // } // } //} var path = txbSubtitleFilePath.Text; var newFile = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + "_new" + Path.GetExtension(path); //if(!File.Exists(newFile)) //{ // File.Copy(txbSubtitleFilePath.Text, newFile); //} var str = stOperator.Subtitle2String(nsubtitle); FileOperationHelper.WriteFile(newFile, Encoding.UTF8, str); ShowMessage("保存成功"); MessageBox.Show("保存成功,文件名:" + Path.GetFileName(newFile)); }
public ActionResult saveProgEval(FormCollection saveForm) { InvokeResult result = new InvokeResult(); #region 构建数据 string tbName = PageReq.GetForm("tbName"); string queryStr = PageReq.GetForm("queryStr"); string dataStr = PageReq.GetForm("dataStr"); int saveStatus = PageReq.GetFormInt("saveStatus");//0:保存 1:提交 List <string> filterStrList = new List <string>() { "tbName", "queryStr", "actionUserStr", "flowId", "stepIds", "fileTypeId", "fileObjId", "tableName", "keyName", "keyValue", "delFileRelIds", "uploadFileList", "fileSaveType", "skipStepIds" }; BsonDocument dataBson = new BsonDocument(); var allKeys = saveForm.AllKeys.Where(i => !filterStrList.Contains(i)); if (dataStr.Trim() == "") { foreach (var tempKey in allKeys) { if (tempKey == "tbName" || tempKey == "queryStr" || tempKey.Contains("fileList[") || tempKey.Contains("param.")) { continue; } dataBson.Add(tempKey, PageReq.GetForm(tempKey)); } } else { dataBson = TypeConvert.ParamStrToBsonDocument(dataStr); } #endregion #region 验证参数 string flowId = PageReq.GetForm("flowId"); BsonDocument flowObj = dataOp.FindOneByQuery("BusFlow", Query.EQ("flowId", flowId)); if (flowObj.IsNullOrEmpty()) { result.Message = "无效的流程模板"; result.Status = Status.Failed; return(Json(TypeConvert.InvokeResultToPageJson(result))); } var stepList = dataOp.FindAllByKeyVal("BusFlowStep", "flowId", flowId).OrderBy(c => c.Int("stepOrder")).ToList(); BsonDocument bootStep = stepList.Where(c => c.Int("actTypeId") == (int)FlowActionType.Launch).FirstOrDefault(); if (saveStatus == 1 && bootStep.IsNullOrEmpty())//提交时才判断 { result.Message = "该流程缺少发起步骤"; result.Status = Status.Failed; return(Json(TypeConvert.InvokeResultToPageJson(result))); } var activeStepIdList = PageReq.GetFormIntList("stepIds"); List <int> hitEnslavedStepOrder = dataOp.FindAllByKeyVal("BusFlowStep", "enslavedStepId", bootStep.Text("stepId")).OrderBy(c => c.Int("stepOrder")).Select(c => c.Int("stepOrder")).Distinct().ToList(); List <int> hitStepIds = stepList.Where(c => hitEnslavedStepOrder.Contains(c.Int("stepOrder"))).Select(c => c.Int("stepId")).ToList(); if (saveStatus == 1 && activeStepIdList.Count() <= 0 && hitEnslavedStepOrder.Count() > 0)//提交时才判断 { result.Status = Status.Failed; result.Message = "请先选定会签部门"; return(Json(TypeConvert.InvokeResultToPageJson(result))); } #endregion TableRule rule = new TableRule(tbName); ColumnRule columnRule = rule.ColumnRules.Where(t => t.IsPrimary == true).FirstOrDefault(); string keyName = columnRule != null ? columnRule.Name : ""; #region 验证重名 string newName = PageReq.GetForm("name").Trim(); BsonDocument curChange = dataOp.FindOneByQuery(tbName, TypeConvert.NativeQueryToQuery(queryStr)); BsonDocument oldChange = dataOp.FindOneByQuery(tbName, Query.EQ("name", newName)); if (!oldChange.IsNullOrEmpty() && oldChange.Int(keyName) != curChange.Int(keyName)) { result.Message = "已经存在该名称的方案评审"; result.Status = Status.Failed; return(Json(TypeConvert.InvokeResultToPageJson(result))); } #endregion #region 保存数据 result = dataOp.Save(tbName, queryStr != "" ? TypeConvert.NativeQueryToQuery(queryStr) : Query.Null, dataBson); if (result.Status == Status.Failed) { result.Message = "保存方案评审失败"; return(Json(TypeConvert.InvokeResultToPageJson(result))); } #endregion #region 文件上传 int primaryKey = 0; if (!string.IsNullOrEmpty(queryStr)) { var query = TypeConvert.NativeQueryToQuery(queryStr); var recordDoc = dataOp.FindOneByQuery(tbName, query); saveForm["keyValue"] = result.BsonInfo.Text(keyName); if (recordDoc != null) { primaryKey = recordDoc.Int(keyName); } } if (primaryKey == 0)//新建 { if (saveForm["tableName"] != null) { saveForm["keyValue"] = result.BsonInfo.Text(keyName); } } else//编辑 { #region 除文件 string delFileRelIds = saveForm["delFileRelIds"] != null ? saveForm["delFileRelIds"] : ""; if (!string.IsNullOrEmpty(delFileRelIds)) { FileOperationHelper opHelper = new FileOperationHelper(); try { string[] fileArray; if (delFileRelIds.Length > 0) { fileArray = delFileRelIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (fileArray.Length > 0) { foreach (var item in fileArray) { var result1 = opHelper.DeleteFileByRelId(int.Parse(item)); if (result1.Status == Status.Failed) { break; } } } } } catch (Exception ex) { result.Status = Status.Failed; result.Message = ex.Message; return(Json(TypeConvert.InvokeResultToPageJson(result))); } } #endregion saveForm["keyValue"] = primaryKey.ToString(); } result.FileInfo = SaveMultipleUploadFiles(saveForm); #endregion #region 保存审批人员 InvokeResult tempResult = new InvokeResult(); int proEvalId = result.BsonInfo.Int(keyName); BsonDocument proEvalObj = result.BsonInfo; PageJson json = new PageJson(); json.AddInfo("proEvalId", proEvalId.ToString()); var actionUserStr = PageReq.GetForm("actionUserStr"); #region 查找方案评审流程模板关联,没有则添加 BsonDocument proEvalFlowRel = dataOp.FindOneByQuery("ProgrammeEvaluationBusFlow", Query.EQ("proEvalId", proEvalId.ToString())); if (proEvalFlowRel.IsNullOrEmpty()) { tempResult = dataOp.Insert("ProgrammeEvaluationBusFlow", "proEvalId=" + proEvalId.ToString() + "&flowId=" + flowId); if (tempResult.Status == Status.Failed) { json.Success = false; json.Message = "插入流程关联失败"; return(Json(json)); } else { proEvalFlowRel = tempResult.BsonInfo; } } #endregion #region 初始化流程实例 var helper = new Yinhe.ProcessingCenter.BusinessFlow.FlowInstanceHelper(dataOp); var flowUserHelper = new Yinhe.ProcessingCenter.BusinessFlow.FlowUserHelper(dataOp); //当前步骤 BsonDocument curStep = null; var hasOperateRight = false; //是否可以跳转步骤 var hasEditRight = false; //是否可以编辑表单 var canForceComplete = false; //是否可以强制结束当前步骤 string curAvaiableUserName = string.Empty; //当前可执行人 BsonDocument curFlowInstance = dataOp.FindAllByQuery("BusFlowInstance", Query.And( Query.EQ("tableName", "ProgrammeEvaluation"), Query.EQ("referFieldName", "proEvalId"), Query.EQ("referFieldValue", proEvalId.ToString()) ) ).OrderByDescending(i => i.Date("createDate")).FirstOrDefault(); if (curFlowInstance.IsNullOrEmpty() == false) { //初始化流程状态 curStep = helper.InitialExecuteCondition(flowObj.Text("flowId"), curFlowInstance.Text("flowInstanceId"), dataOp.GetCurrentUserId(), ref hasOperateRight, ref hasEditRight, ref canForceComplete, ref curAvaiableUserName); if (curStep == null) { curStep = curFlowInstance.SourceBson("stepId"); } } else { curStep = bootStep; //初始化流程实例 if (flowObj != null && curStep != null) { curFlowInstance = new BsonDocument(); curFlowInstance.Add("flowId", flowObj.Text("flowId")); curFlowInstance.Add("stepId", curStep.Text("stepId")); curFlowInstance.Add("tableName", "ProgrammeEvaluation"); curFlowInstance.Add("referFieldName", "proEvalId"); curFlowInstance.Add("referFieldValue", proEvalId); curFlowInstance.Add("instanceStatus", "0"); curFlowInstance.Add("instanceName", proEvalObj.Text("name")); tempResult = helper.CreateInstance(curFlowInstance); if (tempResult.Status == Status.Successful) { curFlowInstance = tempResult.BsonInfo; } else { json.Success = false; json.Message = "创建流程实例失败:" + tempResult.Message; return(Json(json)); } helper.InitialExecuteCondition(flowObj.Text("flowId"), curFlowInstance.Text("flowInstanceId"), dataOp.GetCurrentUserId(), ref hasOperateRight, ref hasEditRight, ref canForceComplete, ref curAvaiableUserName); } if (curStep == null) { curStep = stepList.FirstOrDefault(); } } #endregion #region 保存流程实例步骤人员 List <BsonDocument> allStepList = dataOp.FindAllByKeyVal("BusFlowStep", "flowId", flowId).ToList(); //所有步骤 //获取可控制的会签步骤 string curStepId = curStep.Text("stepId"); var oldRelList = dataOp.FindAllByKeyVal("InstanceActionUser", "flowInstanceId", curFlowInstance.Text("flowInstanceId")).ToList(); //所有的审批人 //stepId + "|Y|" + uid +"|N|"+ status + "|H|"; var arrActionUserStrUserStr = actionUserStr.Split(new string[] { "|H|" }, StringSplitOptions.RemoveEmptyEntries); var storageList = new List <StorageData>(); //不需要审批的所有步骤的id--袁辉 var skipStepIds = PageReq.GetForm("skipStepIds"); var flowHelper = new FlowInstanceHelper(); foreach (var userStr in arrActionUserStrUserStr) { var arrUserStatusStr = userStr.Split(new string[] { "|N|" }, StringSplitOptions.None); if (arrUserStatusStr.Length <= 1) { continue; } string status = arrUserStatusStr[1];//该流程步骤人员是否有效 0:有效 1:无效 var arrUserStr = arrUserStatusStr[0].Split(new string[] { "|Y|" }, StringSplitOptions.RemoveEmptyEntries); var stepId = int.Parse(arrUserStr[0]); var curStepObj = allStepList.Where(c => c.Int("stepId") == stepId).FirstOrDefault(); if (curStepObj == null) { continue; } if (arrUserStr.Length <= 1) { //如果被跳过的审批没有选择人员,则在这里进行保存 var oldRels = oldRelList.Where(t => t.Int("stepId") == stepId).ToList(); if (oldRels.Count > 0) { var skipStr = "1"; if (skipStepIds.Contains(stepId.ToString())) { oldRels = oldRels.Where(t => t.Int("isSkip") == 0).ToList(); } else { oldRels = oldRels.Where(t => t.Int("isSkip") == 1).ToList(); skipStr = "0"; } if (oldRels.Count > 0) { foreach (var oldRel in oldRels) { var tempData = new StorageData(); tempData.Name = "InstanceActionUser"; tempData.Type = StorageType.Update; tempData.Query = Query.EQ("inActId", oldRel.Text("inActId")); tempData.Document = new BsonDocument().Add("isSkip", skipStr); storageList.Add(tempData); } } } else if (skipStepIds.Contains(stepId.ToString())) { var tempData = new StorageData(); tempData.Name = "InstanceActionUser"; tempData.Type = StorageType.Insert; BsonDocument actionUser = new BsonDocument(); actionUser.Add("flowInstanceId", curFlowInstance.Text("flowInstanceId")); actionUser.Add("actionConditionId", curFlowInstance.Text("flowInstanceId")); actionUser.Add("userId", ""); actionUser.Add("stepId", stepId); actionUser.Add("isSkip", "1"); //新增模板属性对象 flowHelper.CopyFlowStepProperty(actionUser, curStepObj); tempData.Document = actionUser; storageList.Add(tempData); } continue; } var userArrayIds = arrUserStr[1]; var userIds = userArrayIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (var userId in userIds) { var oldRel = oldRelList.FirstOrDefault(i => i.Int("stepId") == stepId && i.Text("userId") == userId); if (oldRel.IsNullOrEmpty()) { var tempData = new StorageData(); tempData.Name = "InstanceActionUser"; tempData.Type = StorageType.Insert; BsonDocument actionUser = new BsonDocument(); actionUser.Add("flowInstanceId", curFlowInstance.Text("flowInstanceId")); actionUser.Add("actionConditionId", curFlowInstance.Text("flowInstanceId")); actionUser.Add("userId", userId); actionUser.Add("stepId", stepId); //新增模板属性对象 flowHelper.CopyFlowStepProperty(actionUser, curStepObj); if (curStepObj.Int("actTypeId") == 2)//如果是会签步骤 { actionUser.Set("status", status); } //判断步骤是否跳过审批--袁辉 if (skipStepIds.Contains(stepId.ToString())) { actionUser.Add("isSkip", "1"); } else { actionUser.Add("isSkip", "0"); } tempData.Document = actionUser; storageList.Add(tempData); } else { var tempData = new StorageData(); tempData.Name = "InstanceActionUser"; tempData.Type = StorageType.Update; tempData.Query = Query.EQ("inActId", oldRel.Text("inActId")); BsonDocument actionUser = new BsonDocument(); if (hitStepIds.Contains(stepId)) { actionUser.Add("status", status); } actionUser.Add("converseRefuseStepId", ""); actionUser.Add("actionAvaiable", ""); flowHelper.CopyFlowStepProperty(actionUser, curStepObj); //判断步骤是否跳过审批--袁辉 if (skipStepIds.Contains(stepId.ToString())) { actionUser.Add("isSkip", "1"); } else { actionUser.Add("isSkip", "0"); } tempData.Document = actionUser; storageList.Add(tempData); oldRelList.Remove(oldRel); } } } foreach (var oldRel in oldRelList) { var tempData = new StorageData(); tempData.Name = "InstanceActionUser"; tempData.Type = StorageType.Delete; tempData.Query = Query.EQ("inActId", oldRel.Text("inActId")); storageList.Add(tempData); } tempResult = dataOp.BatchSaveStorageData(storageList); if (tempResult.Status == Status.Failed) { json.Success = false; json.Message = "保存审批人员失败"; return(Json(json)); } #endregion #endregion #region 提交时保存提交信息并跳转 if (saveStatus == 1)//提交时直接发起 { //保存发起人 BsonDocument tempData = new BsonDocument().Add("approvalUserId", dataOp.GetCurrentUserId().ToString()).Add("instanceStatus", "0"); tempResult = dataOp.Save("BusFlowInstance", Query.EQ("flowInstanceId", curFlowInstance.Text("flowInstanceId")), tempData); if (tempResult.Status == Status.Failed) { json.Success = false; json.Message = "保存发起人失败"; return(Json(json)); } //保存发起时间 var timeFormat = "yyyy-MM-dd HH:mm:ss"; tempData = new BsonDocument() { { "startTime", DateTime.Now.ToString(timeFormat) } }; tempResult = dataOp.Save("ProgrammeEvaluation", Query.EQ("proEvalId", proEvalId.ToString()), tempData); if (tempResult.Status == Status.Failed) { json.Success = false; json.Message = "保存发起时间失败"; return(Json(json)); } //跳转步骤 BsonDocument act = dataOp.FindAllByKeyVal("BusFlowAction", "type", "0").FirstOrDefault(); tempResult = helper.ExecAction(curFlowInstance, act.Int("actId"), null, bootStep.Int("stepId")); if (tempResult.Status == Status.Failed) { json.Success = false; json.Message = "流程跳转失败:" + tempResult.Message; return(Json(json)); } } #endregion return(Json(TypeConvert.InvokeResultToPageJson(result))); }
public DocumentRepository(FileOperationHelper fileOperationHelper, SmbFileOperationHelper smbFileOperationHelper) { this.fileOperationHelper = fileOperationHelper; this.smbFileOperationHelper = smbFileOperationHelper; }
private void LoadData() { //try //{ string path = GetText(); if (path == "") { MessageBox.Show("请选择一个搜狗词库的文件"); return; } string str = FileOperationHelper.ReadFile(path); string[] lines = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); int count = lines.Length; var wls = new Dictionary <string, string>(); for (int i = 0; i < count; i++) { string line = lines[i]; if (line[0] == ';') //说明 { continue; } string[] hzpy = line.Split(' '); string py = hzpy[0]; string hz = hzpy[1]; if (NeedSave(hz, py)) { //多音字做如下处理 if (!wls.ContainsKey(hz)) { wls.Add(hz, py); } } processString = i + "/" + count; } ShowTextMessage("开始载入现有的注音库"); string pylibString = FileOperationHelper.ReadFile(ConstantString.PinyinLibPath); lines = pylibString.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < lines.Length; i++) { string line = lines[i]; string[] hzpy = line.Split(' '); string py = hzpy[0]; string hz = hzpy[1]; if (!wls.ContainsKey(hz)) { wls.Add(hz, py); } processString = i + "/" + count; } ShowTextMessage("载入全部完成,开始去除重复"); Dictionary <string, string> rst = RemoveDuplicateWords(wls); ShowTextMessage("去除重复完成,开始写入文件"); StreamWriter sw = FileOperationHelper.WriteFile(ConstantString.PinyinLibPath, Encoding.Unicode); //清空注音库文件 foreach (string key in rst.Keys) { string line = rst[key] + " " + key; FileOperationHelper.WriteFileLine(sw, line); } sw.Close(); toolStripStatusLabel1.Text = "完成!"; ShowTextMessage("完成!"); timer1.Stop(); MessageBox.Show("完成!"); //} //catch (Exception ex) //{ // ShowTextErrorMessage(ex.Message); //} }
/// <summary> /// 上传多个文件 /// </summary> /// <param name="saveForm"></param> /// <returns></returns> public string SaveMultipleUploadFiles(FormCollection saveForm) { string tableName = PageReq.GetForm("tableName"); tableName = !string.IsNullOrEmpty(PageReq.GetForm("tableName")) ? PageReq.GetForm("tableName") : PageReq.GetForm("tbName"); var formKeys = saveForm.AllKeys; if (tableName == "" && formKeys.Contains("tableName")) { tableName = saveForm["tableName"]; } if (tableName == "" && formKeys.Contains("tbName")) { tableName = saveForm["tbName"]; } string keyName = formKeys.Contains("keyName") ? saveForm["keyName"] : PageReq.GetForm("keyName"); string keyValue = formKeys.Contains("keyValue") ? saveForm["keyValue"] : PageReq.GetForm("keyValue"); if (string.IsNullOrEmpty(keyName)) { keyName = saveForm["keyName"]; } if (string.IsNullOrEmpty(keyValue) || keyValue == "0") { keyValue = saveForm["keyValue"]; } string localPath = saveForm.AllKeys.Contains("uploadFileList") ? saveForm["uploadFileList"] : PageReq.GetForm("uploadFileList"); string fileSaveType = saveForm["fileSaveType"] != null ? saveForm["fileSaveType"] : "multiply"; int fileTypeId = PageReq.GetFormInt("fileTypeId"); if (formKeys.Contains("fileTypeId")) { int.TryParse(saveForm["fileTypeId"], out fileTypeId); } int fileObjId = PageReq.GetFormInt("fileObjId"); if (formKeys.Contains("fileObjId")) { int.TryParse(saveForm["fileObjId"], out fileObjId); } int uploadType = PageReq.GetFormInt("uploadType"); if (formKeys.Contains("uploadType")) { int.TryParse(saveForm["uploadType"], out uploadType); } int fileRel_profId = PageReq.GetFormInt("fileRel_profId"); if (formKeys.Contains("fileRel_profId")) { int.TryParse(saveForm["fileRel_profId"], out fileRel_profId); } int fileRel_stageId = PageReq.GetFormInt("fileRel_stageId"); if (formKeys.Contains("fileRel_stageId")) { int.TryParse(saveForm["fileRel_stageId"], out fileRel_stageId); } int fileRel_fileCatId = PageReq.GetFormInt("fileRel_fileCatId"); if (formKeys.Contains("fileRel_fileCatId")) { int.TryParse(saveForm["fileRel_fileCatId"], out fileRel_fileCatId); } int structId = PageReq.GetFormInt("structId"); if (formKeys.Contains("structId")) { int.TryParse(saveForm["structId"], out structId); } bool isPreDefine = saveForm["isPreDefine"] != null?bool.Parse(saveForm["isPreDefine"]) : false; Dictionary <string, string> propDic = new Dictionary <string, string>(); FileOperationHelper opHelper = new FileOperationHelper(); List <InvokeResult <FileUploadSaveResult> > result = new List <InvokeResult <FileUploadSaveResult> >(); //替换会到之网络路径错误,如:\\192.168.1.150\D\A\1.jpg //localPath = localPath.Replace("\\\\", "\\"); #region 如果保存类型为单个single 则删除旧的所有关联文件 if (!string.IsNullOrEmpty(fileSaveType)) { if (fileSaveType == "single") { //opHelper.DeleteFile(tableName, keyName, keyValue); opHelper.DeleteFile(tableName, keyName, keyValue, fileObjId.ToString()); } } #endregion #region 通过关联读取对象属性 if (!string.IsNullOrEmpty(localPath.Trim())) { string[] fileStr = Regex.Split(localPath, @"\|H\|", RegexOptions.IgnoreCase); Dictionary <string, string> filePath = new Dictionary <string, string>(); Dictionary <string, string> filePathInfo = new Dictionary <string, string>(); string s = fileSaveType.Length.ToString(); foreach (string file in fileStr) { if (string.IsNullOrEmpty(file)) { continue; // 防止空数据插入的情况 } string[] filePaths = Regex.Split(file, @"\|Y\|", RegexOptions.IgnoreCase); if (filePaths.Length > 0) { string[] subfile = Regex.Split(filePaths[0], @"\|Z\|", RegexOptions.IgnoreCase); if (subfile.Length > 0) { if (!filePath.Keys.Contains(subfile[0])) { if (filePaths.Length == 3) { filePath.Add(subfile[0], filePaths[1]); filePathInfo.Add(subfile[0], filePaths[2]); } else if (filePaths.Length == 2 || filePaths.Length > 3) { filePath.Add(subfile[0], filePaths[1]); } else { filePath.Add(subfile[0], ""); } } } } } if (fileObjId != 0) { List <BsonDocument> docs = new List <BsonDocument>(); docs = dataOp.FindAllByKeyVal("FileObjPropertyRelation", "fileObjId", fileObjId.ToString()).ToList(); List <string> strList = new List <string>(); strList = docs.Select(t => t.Text("filePropId")).Distinct().ToList(); var doccList = dataOp.FindAllByKeyValList("FileProperty", "filePropId", strList); foreach (var item in doccList) { var formValue = saveForm[item.Text("dataKey")]; if (formValue != null) { propDic.Add(item.Text("dataKey"), formValue.ToString()); } } } #region 文档直接关联属性 foreach (var tempKey in saveForm.AllKeys) { if (!string.IsNullOrEmpty(tempKey) && tempKey.Contains("Property_")) { var formValue = saveForm[tempKey]; propDic.Add(tempKey, formValue.ToString()); } } #endregion List <FileUploadObject> singleList = new List <FileUploadObject>(); //纯文档上传 List <FileUploadObject> objList = new List <FileUploadObject>(); //当前传入类型文件上传 foreach (var str in filePath) { FileUploadObject obj = new FileUploadObject(); List <string> infoList = new List <string>(); Dictionary <string, string> infoDc = new Dictionary <string, string>(); if (filePathInfo.ContainsKey(str.Key)) { infoList = Regex.Split(filePathInfo[str.Key], @"\|N\|", RegexOptions.IgnoreCase).ToList(); foreach (var tempInfo in infoList) { string[] tempSingleInfo = Regex.Split(tempInfo, @"\|-\|", RegexOptions.IgnoreCase); if (tempSingleInfo.Length == 2) { infoDc.Add(tempSingleInfo[0], tempSingleInfo[1]); } } } if (infoDc.ContainsKey("fileTypeId")) { obj.fileTypeId = Convert.ToInt32(infoDc["fileTypeId"]); } else { obj.fileTypeId = fileTypeId; } if (infoDc.ContainsKey("fileObjId")) { obj.fileObjId = Convert.ToInt32(infoDc["fileObjId"]); } else { obj.fileObjId = fileObjId; } if (filePathInfo.ContainsKey(str.Key)) { obj.localPath = Regex.Split(str.Key, @"\|N\|", RegexOptions.IgnoreCase)[0]; } else { obj.localPath = str.Key; } if (infoDc.ContainsKey("tableName")) { obj.tableName = infoDc["tableName"]; } else { obj.tableName = tableName; } if (infoDc.ContainsKey("keyName")) { obj.keyName = infoDc["keyName"]; } else { obj.keyName = keyName; } if (infoDc.ContainsKey("keyValue")) { if (infoDc["keyValue"] != "0") { obj.keyValue = infoDc["keyValue"]; } else { obj.keyValue = keyValue; } } else { obj.keyValue = keyValue; } if (infoDc.ContainsKey("uploadType")) { if (infoDc["uploadType"] != null && infoDc["uploadType"] != "undefined") { obj.uploadType = Convert.ToInt32(infoDc["uploadType"]); } else { obj.uploadType = uploadType; } } else { obj.uploadType = uploadType; } obj.isPreDefine = isPreDefine; if (infoDc.ContainsKey("isCover")) { if (infoDc["isCover"] == "Yes") { obj.isCover = true; } else { obj.isCover = false; } } else { obj.propvalueDic = propDic; } if (infoDc.ContainsKey("structId")) { obj.structId = Convert.ToInt32(infoDc["structId"]); } else { obj.structId = structId; } obj.rootDir = str.Value; obj.fileRel_profId = fileRel_profId.ToString(); obj.fileRel_stageId = fileRel_stageId.ToString(); obj.fileRel_fileCatId = fileRel_fileCatId.ToString(); if (uploadType != 0 && (obj.rootDir == "null" || obj.rootDir.Trim() == "")) { singleList.Add(obj); } else { objList.Add(obj); } } result = opHelper.UploadMultipleFiles(objList, (UploadType)uploadType);//(UploadType)uploadType if (singleList.Count > 0) { //result = opHelper.UploadMultipleFiles(singleList, (UploadType)0); result.AddRange(opHelper.UploadMultipleFiles(singleList, (UploadType)0)); } } else { PageJson jsonone = new PageJson(); jsonone.Success = false; return(jsonone.ToString() + "|"); } #endregion PageJson json = new PageJson(); var ret = opHelper.ResultConver(result); json.Success = ret.Status == Status.Successful ? true : false; var strResult = json.ToString() + "|" + ret.Value; return(strResult); }
public ActionResult SavePostInfo(FormCollection saveForm) { NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); InvokeResult result = new InvokeResult(); #region 构建数据 var formKeys = saveForm.AllKeys; string tbName = formKeys.Contains("tbName") ? saveForm["tbName"] : PageReq.GetForm("tbName"); string queryStr = formKeys.Contains("queryStr") ? saveForm["queryStr"] : PageReq.GetForm("queryStr"); string dataStr = formKeys.Contains("dataStr") ? saveForm["dataStr"] : PageReq.GetForm("dataStr"); TableRule rule = new TableRule(tbName); BsonDocument dataBson = new BsonDocument(); bool columnNeedConvert = false; if (dataStr.Trim() == "") { if (saveForm.AllKeys.Contains("fileObjId")) { columnNeedConvert = true; } foreach (var tempKey in saveForm.AllKeys) { if (tempKey == "tbName" || tempKey == "queryStr" || tempKey.Contains("fileList[") || tempKey.Contains("param.")) { continue; } //2016.1.25添加数据转换过滤, //由于前端通用TableManage需要上传可能会内置tableName字段,如果表中页游tableName字段可能会冲突保存不了 //目前做法前段替换,后端转化COLUMNNEEDCONVERT_ var curFormValue = saveForm[tempKey]; var curColumnName = tempKey; if (columnNeedConvert && tempKey.Contains("COLUMNNEEDCONVERT_")) { curColumnName = curColumnName.Replace("COLUMNNEEDCONVERT_", string.Empty); } dataBson.Set(curColumnName, curFormValue); } } else { dataBson = TypeConvert.ParamStrToBsonDocument(dataStr); } #endregion #region 保存数据 result = dataOp.Save(tbName, queryStr != "" ? TypeConvert.NativeQueryToQuery(queryStr) : Query.Null, dataBson); #endregion #region 文件上传 int primaryKey = 0; ColumnRule columnRule = rule.ColumnRules.Where(t => t.IsPrimary == true).FirstOrDefault(); string keyName = columnRule != null ? columnRule.Name : ""; if (!string.IsNullOrEmpty(queryStr)) { var query = TypeConvert.NativeQueryToQuery(queryStr); var recordDoc = dataOp.FindOneByQuery(tbName, query); saveForm["keyValue"] = result.BsonInfo.Text(keyName); if (recordDoc != null) { primaryKey = recordDoc.Int(keyName); } } if (primaryKey == 0)//新建 { if (saveForm["tableName"] != null) { saveForm["keyValue"] = result.BsonInfo.Text(keyName); } } else//编辑 { #region 除文件 string delFileRelIds = saveForm["delFileRelIds"] != null ? saveForm["delFileRelIds"] : ""; if (!string.IsNullOrEmpty(delFileRelIds)) { FileOperationHelper opHelper = new FileOperationHelper(); try { string[] fileArray; if (delFileRelIds.Length > 0) { fileArray = delFileRelIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (fileArray.Length > 0) { var fileRelIdList = fileArray.Select(t => (BsonValue)t).ToList(); var result1 = opHelper.DeleteFileByRelIdList(fileRelIdList); } } } catch (Exception ex) { result.Status = Status.Failed; result.Message = ex.Message; return(Json(TypeConvert.InvokeResultToPageJson(result))); } } #endregion saveForm["keyValue"] = primaryKey.ToString(); } result.FileInfo = SaveMultipleUploadFiles(saveForm); #endregion return(Json(TypeConvert.InvokeResultToPageJson(result))); }
//public List<string> GetRealPath(IList<string> filePathes) //{ // var list = new List<string>(); // filePathes.ToList().ForEach(x => // { // var dic = Path.GetDirectoryName(x); // var filen = Path.GetFileName(x); // if (filen.Contains("*")) // { // var files = Directory.GetFiles(dic, filen, SearchOption.AllDirectories); // list.AddRange(files); // } // else // { // list.Add(x); // } // }); // return list; //} /// <summary> /// 转换多个文件成一个文件 /// </summary> /// <param name="filePathes"></param> /// <returns></returns> public string Convert(IList <string> filePathes) { this.timer.Start(); ExportContents = new List <string>(); allWlList.Clear(); isImportProgress = true; //filePathes = GetRealPath(filePathes); foreach (string file in filePathes) { if (FileOperationHelper.GetFileSize(file) == 0) { ProcessNotice("词库(" + Path.GetFileName(file) + ")为空,请检查"); continue; } Debug.WriteLine("start process file:" + file); try { WordLibraryList wlList = import.Import(file); wlList = Filter(wlList); allWlList.AddRange(wlList); } catch (Exception ex) { ProcessNotice("词库(" + Path.GetFileName(file) + ")处理出现异常:" + ex.Message); } } isImportProgress = false; if (selectedTranslate != ChineseTranslate.NotTrans) { ProcessNotice("开始繁简转换..."); allWlList = ConvertChinese(allWlList); } if (export.CodeType != CodeType.NoCode) { ProcessNotice("开始生成词频..."); GenerateWordRank(allWlList); } if (import.CodeType != export.CodeType) { ProcessNotice("开始生成目标编码..."); GenerateDestinationCode(allWlList, export.CodeType); } if (export.CodeType != CodeType.NoCode) { allWlList = RemoveEmptyCodeData(allWlList); } count = allWlList.Count; ReplaceAfterCode(allWlList); //Sort //var wlDict = new Dictionary<string, WordLibrary>(); //var sorted = allWlList.Distinct().OrderBy(w => w.PinYinString).ToList(); //allWlList = new WordLibraryList(); //foreach (var wl in sorted) //{ // if (!wlDict.ContainsKey(wl.Word)) // { // wlDict.Add(wl.Word, wl); // allWlList.Add(wl); // } //} ExportContents = export.Export(allWlList); this.timer.Stop(); return(string.Join("\r\n", ExportContents.ToArray())); }
/// <summary> /// 检查更新 /// </summary> public static void CheckUpdateStatus() { string CurrentVersion = ConfigurationManager.AppSettings["CurrentVersion"]; //当前程序的version版本 string AppId = ConfigurationManager.AppSettings["AppId"]; //当前程序的AppId,唯一标示 Bll.AppVersion appVersion = new AppVersion(); string tempVal = appVersion.GetAppVersion(); //MessageBox.Show(str); JObject jo = (JObject)JsonConvert.DeserializeObject(tempVal); if (JObjectHelper.GetStrNum(jo["code"].ToString()) == 200) //请求成功 { int[] _currentVersion = Array.ConvertAll <string, int>(CurrentVersion.Split('.'), int.Parse); int[] _updateVersion = Array.ConvertAll <string, int>(jo["dataList"]["VersionNo"].ToString().Split('.'), int.Parse); int len = _currentVersion.Length >= _updateVersion.Length ? _updateVersion.Length : _currentVersion.Length; //判断是否需要更新 bool bo = false; for (int i = 0; i < len; i++) { if (!bo) { bo = _currentVersion[i] < _updateVersion[i]; } else { break; } } //bo=true可以更新,false不用更新 if (bo) { DispatcherHelper.CheckBeginInvokeOnUI(() => { AutoUpdateInfo autoUpdate = new AutoUpdateInfo(); bool?update_bo = autoUpdate.ShowDialog(); if (update_bo == null || update_bo == false) { return; } string appDir = Path.Combine(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.LastIndexOf(Path.DirectorySeparatorChar))); string updateFileDir = Path.Combine(Path.Combine(appDir.Substring(0, appDir.LastIndexOf(Path.DirectorySeparatorChar))), "temporary"); if (!Directory.Exists(updateFileDir)) { Directory.CreateDirectory(updateFileDir); } string exePath = Path.Combine(updateFileDir, "Update"); if (!Directory.Exists(exePath)) { Directory.CreateDirectory(exePath); } //File.Copy(Path.Combine(appDir,"Update"),exePath,true); FileOperationHelper.FileCopy(Path.Combine(appDir, "Update"), exePath, true); //string str= "{\"CurrentVersion\":\"" + CurrentVersion + "\",\"AppId\":\"" + AppId + "\"}"; ProcessStartInfo psi = new ProcessStartInfo(); Process ps = new Process(); psi.FileName = Path.Combine(exePath, "IntoApp.AutoUpdate.exe"); psi.Arguments = tempVal.Replace(" ", "").Replace("\"", "*") + " " + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IntoApp.exe"); psi.UseShellExecute = false; psi.RedirectStandardError = true; //Process.Start(psi); //ProcessHelper.OpenAdminProcess(psi, ps, "自动更新失败,稍后请手动更新!"); ShellExecute(IntPtr.Zero, "runas", @Path.Combine(exePath, "IntoApp.AutoUpdate.exe"), tempVal.Replace(" ", "").Replace("\"", "*") + " " + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IntoApp.exe"), "", 5); Application.Current.Shutdown(); }); } } else //请求失败 { } }
public void Run() { if (Args.Length == 0) { Console.WriteLine("输入 -? 可获取帮助"); return; } for (int i = 0; i < Args.Length; i++) { string arg = Args[i]; type = RunCommand(arg); } if (!string.IsNullOrEmpty(format)) { if ((!(wordLibraryExport is SelfDefining)) && (!(wordLibraryImport is SelfDefining))) { Console.WriteLine("-f参数用于自定义格式时设置格式样式用,导入导出词库格式均不是自定义格式,该参数无效!"); return; } } if (!string.IsNullOrEmpty(codingFile)) { if (!(wordLibraryExport is SelfDefining)) { Console.WriteLine("-f参数用于自定义格式输出时设置编码用,导出词库格式不是自定义格式,该参数无效!"); return; } } if (wordLibraryImport is SelfDefining) { ((SelfDefining)wordLibraryImport).UserDefiningPattern = pattern; } if (wordLibraryExport is SelfDefining) { ((SelfDefining)wordLibraryExport).UserDefiningPattern = pattern; } if (wordLibraryExport is Rime) { ((Rime)wordLibraryExport).CodeType = pattern.CodeType; ((Rime)wordLibraryExport).OS = pattern.OS; } if (wordLibraryImport is LingoesLd2) { var ld2Import = ((LingoesLd2)wordLibraryImport); ld2Import.WordEncoding = wordEncoding; if (xmlEncoding != null) { ld2Import.XmlEncoding = xmlEncoding; ld2Import.IncludeMeaning = true; } } if (importPaths.Count > 0 && exportPath != "") { var mainBody = new MainBody(); mainBody.Export = wordLibraryExport; mainBody.Import = wordLibraryImport; mainBody.SelectedWordRankGenerater = this.wordRankGenerater; mainBody.Filters = this.filters; mainBody.ProcessNotice += MainBody_ProcessNotice; Console.WriteLine("转换开始..."); //foreach (string importPath in importPaths) //{ // Console.WriteLine("开始转换文件:" + importPath); // wordLibraryList.AddWordLibraryList(wordLibraryImport.Import(importPath)); //} //string str = wordLibraryExport.Export(wordLibraryList); if (exportPath.EndsWith("*")) { mainBody.Convert(importPaths, exportPath.Substring(0, exportPath.Length - 1)); } else { string str = mainBody.Convert(importPaths); FileOperationHelper.WriteFile(exportPath, wordLibraryExport.Encoding, str); } Console.WriteLine("转换完成,共转换" + mainBody.Count + "个"); } Console.WriteLine("输入 -? 可获取帮助"); }
private CommandType RunCommand(string command) { if (command == "--help" || command == "-?") { showHelp(this.cbxImportItems); return(CommandType.Help); } if (command == "--version" || command == "-v") { Console.WriteLine("Version:" + Assembly.GetExecutingAssembly().GetName().Version); return(CommandType.Help); } if (command.StartsWith("-i:")) { wordLibraryImport = GetImportInterface(command.Substring(3)); beginImportFile = true; return(CommandType.Import); } if (command.StartsWith("-o:")) { wordLibraryExport = GetExportInterface(command.Substring(3)); beginImportFile = false; return(CommandType.Export); } if (command.StartsWith("-c:")) //code { codingFile = command.Substring(3); pattern.MappingTablePath = codingFile; pattern.IsPinyinFormat = false; beginImportFile = false; return(CommandType.Coding); } if (command.StartsWith("-ft:")) //filter { var filterStrs = command.Substring(4); Regex lenRegex = new Regex(@"len:(\d+)-(\d+)"); Regex rankRegex = new Regex(@"rank:(\d+)-(\d+)"); Regex rmRegex = new Regex(@"rm:(\w+)"); foreach (var filterStr in filterStrs.Split('|')) { if (lenRegex.IsMatch(filterStr)) { var match = lenRegex.Match(filterStr); var from = Convert.ToInt32(match.Groups[1].Value); var to = Convert.ToInt32(match.Groups[2].Value); var numberFilter = new LengthFilter() { MinLength = from, MaxLength = to }; this.filters.Add(numberFilter); } else if (rankRegex.IsMatch(filterStr)) { var match = rankRegex.Match(filterStr); var from = Convert.ToInt32(match.Groups[1].Value); var to = Convert.ToInt32(match.Groups[2].Value); var rFilter = new RankFilter() { MinLength = from, MaxLength = to }; this.filters.Add(rFilter); } else if (rmRegex.IsMatch(filterStr)) { var match = rmRegex.Match(filterStr); var rmType = match.Groups[1].Value; ISingleFilter filter; switch (rmType) { case "eng": filter = new EnglishFilter(); break; case "num": filter = new NumberFilter(); break; case "space": filter = new SpaceFilter(); break; case "pun": filter = new EnglishPunctuationFilter(); break; default: throw new ArgumentException("Unsupport filter type:" + rmType); } this.filters.Add(filter); } } return(CommandType.Coding); } if (command.StartsWith("-ct:")) //code type { var codeType = command.Substring(4).ToLower(); switch (codeType) { case "pinyin": pattern.CodeType = CodeType.Pinyin; break; case "wubi": pattern.CodeType = CodeType.Wubi; break; case "zhengma": pattern.CodeType = CodeType.Zhengma; break; case "cangjie": pattern.CodeType = CodeType.Cangjie; break; case "zhuyin": pattern.CodeType = CodeType.TerraPinyin; break; default: pattern.CodeType = CodeType.Pinyin; break; } return(CommandType.CodeType); } if (command.StartsWith("-r:")) //Rank { var rankType = command.Substring(3).ToLower(); switch (rankType) { case "baidu": this.wordRankGenerater = new BaiduWordRankGenerater(); break; case "google": this.wordRankGenerater = new GoogleWordRankGenerater(); break; default: { var rankNumber = Convert.ToInt32(rankType); var gen = new DefaultWordRankGenerater(); gen.ForceUse = true; gen.Rank = rankNumber; this.wordRankGenerater = gen; } break; } return(CommandType.CodeType); } if (command.StartsWith("-os:")) //code type { var os = command.Substring(4).ToLower(); switch (os) { case "windows": pattern.OS = OperationSystem.Windows; break; case "mac": case "macos": pattern.OS = OperationSystem.MacOS; break; case "linux": case "unix": pattern.OS = OperationSystem.Linux; break; default: pattern.OS = OperationSystem.Windows; break; } return(CommandType.OS); } if (command.StartsWith("-ld2:")) //ld2 encoding { string ecodes = command.Substring(5); string[] arr = ecodes.Split(','); wordEncoding = Encoding.GetEncoding(arr[0]); if (arr.Length > 1) { xmlEncoding = Encoding.GetEncoding(arr[1]); } return(CommandType.Encoding); } if (command.StartsWith("-f:")) //format { format = command.Substring(3); beginImportFile = false; var sort = new List <int>(); for (int i = 0; i < 3; i++) { char c = format[i]; sort.Add(Convert.ToInt32(c)); } pattern.Sort = sort; pattern.CodeSplitString = format[3].ToString(); pattern.SplitString = format[4].ToString(); string t = format[5].ToString().ToLower(); beginImportFile = false; if (t == "l") { pattern.CodeSplitType = BuildType.LeftContain; } if (t == "r") { pattern.CodeSplitType = BuildType.RightContain; } if (t == "b") { pattern.CodeSplitType = BuildType.FullContain; } if (t == "n") { pattern.CodeSplitType = BuildType.None; } pattern.ContainCode = (format[6].ToString().ToLower() == "y"); pattern.ContainRank = (format[8].ToString().ToLower() == "y"); return(CommandType.Format); } if (beginImportFile) { importPaths.AddRange(FileOperationHelper.GetFilesPath(command)); } if (type == CommandType.Export) { exportPath = command; } return(CommandType.Other); }
public ActionResult SavePostInfo(FormCollection saveForm) { InvokeResult result = new InvokeResult(); DataOperation dataOp = new DataOperation(); #region 构建数据 string tbName = saveForm["tbName"] != null ? saveForm["tbName"] : ""; string queryStr = saveForm["queryStr"] != null ? saveForm["queryStr"] : ""; string dataStr = saveForm["dataStr"] != null ? saveForm["dataStr"] : ""; if (dataStr.Trim() == "") { foreach (var tempKey in saveForm.AllKeys) { if (tempKey == "tbName" || tempKey == "queryStr" || tempKey.Contains("fileList[") || tempKey.Contains("param.")) { continue; } dataStr += string.Format("{0}={1}&", tempKey, saveForm[tempKey]); } } #endregion #region 保存数据 BsonDocument curData = new BsonDocument(); //当前数据,即操作前数据 if (queryStr.Trim() != "") { curData = dataOp.FindOneByQuery(tbName, TypeConvert.NativeQueryToQuery(queryStr)); } result = dataOp.Save(tbName, queryStr, dataStr); #endregion #region 文件上传 int primaryKey = 0; TableRule rule = new TableRule(tbName); ColumnRule columnRule = rule.ColumnRules.Where(t => t.IsPrimary == true).FirstOrDefault(); string keyName = columnRule != null ? columnRule.Name : ""; if (!string.IsNullOrEmpty(queryStr)) { var query = TypeConvert.NativeQueryToQuery(queryStr); var recordDoc = dataOp.FindOneByQuery(tbName, query); saveForm["keyValue"] = result.BsonInfo.Text(keyName); if (recordDoc != null) { primaryKey = recordDoc.Int(keyName); } } if (primaryKey == 0)//新建 { if (saveForm["tableName"] != null) { string str = result.BsonInfo.Text(keyName); saveForm["keyValue"] = result.BsonInfo.Text(keyName); string t = saveForm["keyValue"].ToString(); string c = result.BsonInfo.String(keyName); t = ""; } } else//编辑 { #region 除文件 string delFileRelIds = saveForm["delFileRelIds"] != null ? saveForm["delFileRelIds"] : ""; if (!string.IsNullOrEmpty(delFileRelIds)) { FileOperationHelper opHelper = new FileOperationHelper(); try { string[] fileArray; if (delFileRelIds.Length > 0) { fileArray = delFileRelIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (fileArray.Length > 0) { foreach (var item in fileArray) { result = opHelper.DeleteFileByRelId(int.Parse(item)); if (result.Status == Status.Failed) { break; } } } } } catch (Exception ex) { result.Status = Status.Failed; result.Message = ex.Message; return(Json(TypeConvert.InvokeResultToPageJson(result))); } } #endregion saveForm["keyValue"] = primaryKey.ToString(); } result.FileInfo = SaveMultipleUploadFiles(saveForm); #endregion #region 保存日志 if (result.Status == Status.Successful) { //dataOp.LogDataStorage(tbName, queryStr.Trim() == "" ? StorageType.Insert : StorageType.Update, curData, result.BsonInfo); } #endregion return(Json(TypeConvert.InvokeResultToPageJson(result))); }
/// <summary> /// 上传多个文件 /// </summary> /// <param name="saveForm"></param> /// <returns></returns> public string SaveMultipleUploadFiles(FormCollection saveForm) { DataOperation dataOp = new DataOperation(); string tableName = PageReq.GetForm("tableName"); string keyName = PageReq.GetForm("keyName"); string keyValue = saveForm["keyValue"].ToString(); string localPath = PageReq.GetForm("uploadFileList"); string fileSaveType = saveForm["fileSaveType"] != null ? saveForm["fileSaveType"] : "multiply"; int fileTypeId = PageReq.GetFormInt("fileTypeId"); int fileObjId = PageReq.GetFormInt("fileObjId"); int uploadType = PageReq.GetFormInt("uploadType"); string subMapParam = PageReq.GetForm("subMapParam"); string guid2d = PageReq.GetForm("guid2d"); string oldGuid2d = PageReq.GetForm("oldguid2d"); bool isPreDefine = saveForm["isPreDefine"] != null?bool.Parse(saveForm["isPreDefine"]) : false; Dictionary <string, string> propDic = new Dictionary <string, string>(); FileOperationHelper opHelper = new FileOperationHelper(); List <InvokeResult <FileUploadSaveResult> > result = new List <InvokeResult <FileUploadSaveResult> >(); localPath = localPath.Replace("\\\\", "\\"); #region 如果保存类型为单个single 则删除旧的所有关联文件 if (!string.IsNullOrEmpty(fileSaveType)) { if (fileSaveType == "single") { opHelper.DeleteFile(tableName, keyName, keyValue); } } #endregion #region 通过关联读取对象属性 if (!string.IsNullOrEmpty(localPath.Trim())) { string[] fileStr = Regex.Split(localPath, @"\|H\|", RegexOptions.IgnoreCase); Dictionary <string, string> filePath = new Dictionary <string, string>(); foreach (string file in fileStr) { string[] filePaths = Regex.Split(file, @"\|Y\|", RegexOptions.IgnoreCase); if (filePaths.Length > 0) { string[] subfile = Regex.Split(filePaths[0], @"\|Z\|", RegexOptions.IgnoreCase); if (subfile.Length > 0) { if (!filePath.Keys.Contains(subfile[0])) { if (filePaths.Length >= 2) { filePath.Add(subfile[0], filePaths[1]); } else { filePath.Add(subfile[0], ""); } } } } } if (fileObjId != 0) { List <BsonDocument> docs = new List <BsonDocument>(); docs = dataOp.FindAllByKeyVal("FileObjPropertyRelation", "fileObjId", fileObjId.ToString()).ToList(); List <string> strList = new List <string>(); strList = docs.Select(t => t.Text("filePropId")).Distinct().ToList(); var doccList = dataOp.FindAllByKeyValList("FileProperty", "filePropId", strList); foreach (var item in doccList) { var formValue = saveForm[item.Text("dataKey")]; if (formValue != null) { propDic.Add(item.Text("dataKey"), formValue.ToString()); } } } List <FileUploadObject> singleList = new List <FileUploadObject>(); //纯文档上传 List <FileUploadObject> objList = new List <FileUploadObject>(); //当前传入类型文件上传 foreach (var str in filePath) { FileUploadObject obj = new FileUploadObject(); obj.fileTypeId = fileTypeId; obj.fileObjId = fileObjId; obj.localPath = str.Key; obj.tableName = tableName; obj.keyName = keyName; obj.keyValue = keyValue; obj.uploadType = uploadType; obj.isPreDefine = isPreDefine; obj.isCover = false; obj.propvalueDic = propDic; obj.rootDir = str.Value; obj.subMapParam = subMapParam; obj.guid2d = guid2d; if (uploadType != 0 && (obj.rootDir == "null" || obj.rootDir.Trim() == "")) { singleList.Add(obj); } else { objList.Add(obj); } } result = opHelper.UploadMultipleFiles(objList, (UploadType)uploadType);//(UploadType)uploadType if (singleList.Count > 0) { result = opHelper.UploadMultipleFiles(singleList, (UploadType)0); } } else { PageJson jsonone = new PageJson(); jsonone.Success = false; return(jsonone.ToString() + "|"); } #endregion PageJson json = new PageJson(); var ret = opHelper.ResultConver(result); #region 如果有关联的文件Id列表,则保存关联记录 string fileVerIds = PageReq.GetForm("fileVerIds"); List <int> fileVerIdList = fileVerIds.SplitToIntList(","); if (ret.Status == Status.Successful && fileVerIdList.Count > 0) { List <StorageData> saveList = new List <StorageData>(); foreach (var tempVerId in fileVerIdList) { StorageData tempData = new StorageData(); tempData.Name = "FileAlterRelation"; tempData.Type = StorageType.Insert; tempData.Document = new BsonDocument().Add("alterFileId", result.FirstOrDefault().Value.fileId.ToString()) .Add("fileVerId", tempVerId); saveList.Add(tempData); } dataOp.BatchSaveStorageData(saveList); } #endregion json.Success = ret.Status == Status.Successful ? true : false; var strResult = json.ToString() + "|" + ret.Value + "|" + keyValue; return(strResult); }
/// <summary> /// 通过搜狗细胞词库txt内容构造词库对象 /// </summary> /// <param name="str"></param> /// <returns></returns> public virtual WordLibraryList Import(string path) { string str = FileOperationHelper.ReadFile(path); return(ImportText(str)); }
public IList <string> Export(WordLibraryList wlList) { //Win10拼音只支持最多32个字符的编码 wlList = Filter(wlList); string tempPath = Path.Combine(FileOperationHelper.GetCurrentFolderPath(), "Win10微软拼音词库.dat"); if (File.Exists(tempPath)) { File.Delete(tempPath); } var fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); bw.Write(Encoding.ASCII.GetBytes("mschxudp")); //proto8 bw.Write(BitConverter.GetBytes(0x00600002)); //Unknown bw.Write(BitConverter.GetBytes(1)); //version bw.Write(BitConverter.GetBytes(0x40)); //phrase_offset_start bw.Write(BitConverter.GetBytes(0x40 + 4 * wlList.Count)); //phrase_start=phrase_offset_start + 4*phrase_count bw.Write(BitConverter.GetBytes(0)); //phrase_end input after process all! bw.Write(BitConverter.GetBytes(wlList.Count)); //phrase_count bw.Write(BitConverter.GetBytes(DateTime.Now.Ticks)); //timestamp bw.Write(BitConverter.GetBytes((long)0)); //0 bw.Write(BitConverter.GetBytes((long)0)); //0 bw.Write(BitConverter.GetBytes((long)0)); //0 int offset = 0; for (var i = 0; i < wlList.Count; i++) { bw.Write(BitConverter.GetBytes(offset)); var wl = wlList[i]; offset += 8 + 8 + wl.Word.Length * 2 + 2 + wl.GetPinYinLength() * 2 + 2; } for (var i = 0; i < wlList.Count; i++) { bw.Write(BitConverter.GetBytes(0x00100010)); //magic var wl = wlList[i]; var hanzi_offset = 8 + 8 + wl.GetPinYinLength() * 2 + 2; bw.Write(BitConverter.GetBytes((short)hanzi_offset)); bw.Write((byte)wl.Rank); //1是詞頻 bw.Write((byte)0x6); //6不知道 bw.Write(BitConverter.GetBytes(0x00000000)); //Unknown bw.Write(BitConverter.GetBytes(0xE679CD20)); //Unknown var py = wl.GetPinYinString("", BuildType.None); bw.Write(Encoding.Unicode.GetBytes(py)); bw.Write(BitConverter.GetBytes((short)0)); bw.Write(Encoding.Unicode.GetBytes(wl.Word)); bw.Write(BitConverter.GetBytes((short)0)); } fs.Position = 0x18; fs.Write(BitConverter.GetBytes(fs.Length), 0, 4); fs.Close(); return(new List <string>() { "词库文件在:" + tempPath }); }
public void getSizeInCurrentDirectoryTest() { string tPath = "C:/Users/zhanghui03/source/repos/DirectorEditor/TestResources/xixi"; var size = FileOperationHelper.getSizeInCurrentDirectory(tPath); }
public WordLibraryList Import(string path) { string str = FileOperationHelper.ReadFile(path, Encoding); return(ImportText(str)); }
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { timer1.Enabled = false; toolStripProgressBar1.Value = toolStripProgressBar1.Maximum; ShowStatusMessage("转换完成", false); if (e.Error != null) { MessageBox.Show("不好意思,发生了错误:" + e.Error.Message); if (e.Error.InnerException != null) { richTextBox1.Text = (e.Error.InnerException.ToString()); } return; } if (streamExport && import.IsText) { ShowStatusMessage("转换完成,词库保存到文件:" + exportPath, true); return; } if (exportDirectly) { richTextBox1.Text = "为提高处理速度,“高级设置”中选中了“不显示结果,直接导出”,本文本框中不显示转换后的结果,若要查看转换后的结果再确定是否保存请取消该设置。"; } else { richTextBox1.Text = fileContent; //btnExport.Enabled = true; } if (!mergeTo1File) { MessageBox.Show("转换完成!"); return; } if ( MessageBox.Show("是否将导入的" + mainBody.Count + "条词库保存到本地硬盘上?", "是否保存", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { if (!string.IsNullOrEmpty(exportFileName)) { saveFileDialog1.FileName = exportFileName; } else if (export is MsPinyin) { saveFileDialog1.DefaultExt = ".dctx"; saveFileDialog1.Filter = "微软拼音2010|*.dctx"; } else { saveFileDialog1.DefaultExt = ".txt"; saveFileDialog1.Filter = "文本文件|*.txt"; } if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if (FileOperationHelper.WriteFile(saveFileDialog1.FileName, export.Encoding, fileContent)) { ShowStatusMessage("保存成功,词库路径:" + saveFileDialog1.FileName, true); } else { ShowStatusMessage("保存失败", true); } } } }