public override string GetMailBody(LibMailParam param, Dictionary <string, string[]> addressDic) { string html = string.Empty; string path = Path.Combine(EnvProvider.Default.MainPath, "Resource", "MailTpl", "ApproveMailTpl.html"); using (FileStream fs = new FileStream(path, FileMode.Open)) { using (StreamReader reader = new StreamReader(fs, Encoding.Default)) { html = reader.ReadToEnd(); } } html.Replace("@BILL", param.ProgName); html.Replace("@USER", addressDic[param.UserId][0]); html.Replace("@DATE", DateTime.Now.ToShortDateString()); html.Replace("@TEXT", param.Content); if (param.ExpandData.ContainsKey("@IMG")) { string base64 = param.ExpandData["@IMG"]; string imageName = string.Format("{0}-{1}.png", LibDateUtils.GetCurrentDateTime(), LibCommUtils.GetInternalId()); string imgUrl = Path.Combine(".", "PublicData", "Mail", "Image", imageName); using (FileStream fs = new FileStream(imgUrl, FileMode.Create)) { byte[] imageBytes = Convert.FromBase64String(base64); fs.Write(imageBytes, 0, imageBytes.Length); } html.Replace("@IMG", imgUrl); } html.Replace("@LINK", ""); return(html); }
private bool IsExecOfDay(LibBusinessTask task) { bool needExec = false; int curDate = LibDateUtils.GetCurrentDate(); if (task.ExecDate == 0) { if (task.RepeatDateMark != 0) { needExec = IsExecOfDay(task.RepeatDateMark, curDate); if (task.IsJustWorkDay) { string calendarId = task.CalendarId; if (!string.IsNullOrEmpty(calendarId)) { CalendarData calendarData = new CalendarData(calendarId); needExec = IsWorkDay(curDate, calendarData); } } } } else { needExec = task.ExecDate == curDate; } return(needExec); }
/// <summary> /// 添加同步信息到同步信息记录表中 /// </summary> /// <param name="syncInfo"></param> /// <returns></returns> public static bool AddSyncDataRecord(SyncDataInfo syncInfo) { try { if (syncInfo == null || string.IsNullOrEmpty(syncInfo.ProgId) || string.IsNullOrEmpty(syncInfo.InternalId) || string.IsNullOrEmpty(syncInfo.UserId)) { return(false); } string sql = string.Format("insert into AXPSYNCDATAHISTORY(INFOID,PROGID,INTERNALID,BILLNO,USERID,SITEID,SYNCTIME,SYNCOP,SYNCSTATE,SYNCINFO) " + "values({0},{1},{2},{3},{4},{5},{6},{7},{8},{9})", LibStringBuilder.GetQuotString(Guid.NewGuid().ToString()), LibStringBuilder.GetQuotString(syncInfo.ProgId), LibStringBuilder.GetQuotString(syncInfo.InternalId), LibStringBuilder.GetQuotString(syncInfo.BillNo), LibStringBuilder.GetQuotString(syncInfo.UserId), LibStringBuilder.GetQuotString(syncInfo.SiteId), LibDateUtils.DateTimeToLibDateTime(syncInfo.SyncTime), (int)syncInfo.SyncOp, (int)syncInfo.SyncState, LibStringBuilder.GetQuotString(syncInfo.SyncInfo) ); LibDataAccess dataAccess = new LibDataAccess(); int count = dataAccess.ExecuteNonQuery(sql); return(count > 0); } catch (Exception exp) { LibCommUtils.AddOutput("CrossSiteCall", string.Format("error:{0}\r\nStacktrace:{1}", exp.Message, exp.StackTrace)); return(false); } }
private static void BuildProgIdCore(ProgIdConfigListing progIdListing, List <string> files, Dictionary <string, Assembly> assemblyDic) { foreach (string file in files) { Assembly assembly = Assembly.LoadFrom(file); string dllName = assembly.ManifestModule.Name; if (!assemblyDic.ContainsKey(dllName)) { assemblyDic.Add(dllName, assembly); } DateTime fileDateTime = File.GetCreationTime(file); long version = LibDateUtils.DateTimeToLibDateTime(fileDateTime); if (!progIdListing.DllVersions.ContainsKey(dllName)) { progIdListing.DllVersions.Add(dllName, version); } Type[] types = assembly.GetTypes(); foreach (Type t in types) { if (t.IsDefined(typeof(ProgIdAttribute))) { ProgIdAttribute attr = (ProgIdAttribute)t.GetCustomAttribute(typeof(ProgIdAttribute)); ProgIdRelationDll relationDll = new ProgIdRelationDll(dllName, t.FullName); if (progIdListing.RelationDlls.ContainsKey(attr.ProgId)) { progIdListing.RelationDlls[attr.ProgId] = relationDll; } else { progIdListing.RelationDlls.Add(attr.ProgId, relationDll); } if (!string.IsNullOrEmpty(attr.VclPath)) { if (progIdListing.VclMap.ContainsKey(attr.VclClass)) { progIdListing.VclMap[attr.VclClass] = attr.VclPath; } else { progIdListing.VclMap.Add(attr.VclClass, attr.VclPath); } } if (!string.IsNullOrEmpty(attr.ViewPath)) { if (progIdListing.ViewMap.ContainsKey(attr.ViewClass)) { progIdListing.ViewMap[attr.ViewClass] = attr.ViewPath; } else { progIdListing.ViewMap.Add(attr.ViewClass, attr.ViewPath); } } } } } }
public static Result ExceptionTrack(string personId, string BillNo, DateTime PlanEndTime, string Solution, int DealwithState, string userId) { Result res = new Result(); LibBcfData bcfData = (LibBcfData)LibBcfSystem.Default.GetBcfInstance("com.AbnormalTrace"); LibEntryParam param = new LibEntryParam(); DataSet dataSet = bcfData.AddNew(param); DataTable masterDt = dataSet.Tables[0]; masterDt.BeginLoadData(); DataRow masterRow = masterDt.Rows[0]; try { masterRow.BeginEdit(); try { masterRow["TYPEID"] = "P001"; masterRow["FROMBILLNO"] = BillNo; masterRow["PLANENDTIME"] = LibDateUtils.DateTimeToLibDateTime(PlanEndTime); masterRow["SOLUTION"] = Solution; masterRow["DEALWITHSTATE"] = DealwithState; masterRow["DEALWITHPERSONID"] = personId; } catch { throw; } finally { masterRow.EndEdit(); } } catch { throw; } finally { masterDt.EndLoadData(); } bcfData.InnerSave(BillAction.AddNew, null, dataSet); if (bcfData.ManagerMessage.IsThrow) { res.Message = "数据有误"; res.ReturnValue = false; } else { res.ReturnValue = true; //Service.PushMessage(userId, PushType.Message); } return(res); }
public string ExportData(LibQueryCondition condition) { string fileName = string.Empty; bool ret = CheckHasPermission(FuncPermissionEnum.Export); if (ret) { this.GetData(condition); fileName = string.Format("{0}-{1}.xls", this.ProgId, LibDateUtils.GetCurrentDateTime()); string filePath = System.IO.Path.Combine(AxCRL.Comm.Runtime.EnvProvider.Default.RuningPath, "TempData", "ExportData", fileName); AxCRL.Core.Excel.LibExcelHelper libExcelHelper = new Core.Excel.LibExcelHelper(); libExcelHelper.ExportToExcel(filePath, this.DataSet); } return(fileName); }
private bool IsWorkDay(int curDate, CalendarData calendarData) { bool isWork = false; int year = LibDateUtils.GetLibDatePart(curDate, LibDateTimePartEnum.Year); if (calendarData.WorkDayList.ContainsKey(year)) { int month = LibDateUtils.GetLibDatePart(curDate, LibDateTimePartEnum.Month); int day = LibDateUtils.GetLibDatePart(curDate, LibDateTimePartEnum.Day); int calendar = calendarData.WorkDayList[year][month]; int temp = (int)Math.Pow(2, day); isWork = (calendar & temp) != 0; } else { isWork = true; } return(isWork); }
public TimeSpan GetTaskDueTime() { TimeSpan dueTime = TimeSpan.Zero; long currentDateTime = LibDateUtils.GetCurrentDateTime(); int curDate = LibDateUtils.GetLibTimePart(currentDateTime, LibDateTimePartEnum.Date); int currentTime = LibDateUtils.GetLibTimePart(currentDateTime, LibDateTimePartEnum.Time); if (TaskDefine.ExecTime.Count > 0) //指定时间点执行情况 { for (int i = 0; i < TaskDefine.ExecTime.Count; i++) { int execTime = TaskDefine.ExecTime[i]; if (execTime < 9999) { execTime *= 100; } if (currentTime < execTime) { long endTime = (long)curDate * 1000000 + execTime; dueTime = LibDateUtils.LibDateToDateTime(endTime) - LibDateUtils.LibDateToDateTime(currentDateTime); break; } if (TaskDefine.ExecTime.Count == i + 1) { if (TaskDefine.TaskType == LibTaskType.None) { long startTime = (long)curDate * 1000000 + execTime; long endTime = (long)LibDateUtils.AddDayToLibDate(LibDateUtils.LibDateToDateTime(curDate), 1) * 1000000 + TaskDefine.ExecTime[0] * 100; dueTime = LibDateUtils.LibDateToDateTime(endTime) - LibDateUtils.LibDateToDateTime(startTime); } } } } else if (TaskDefine.IntervalTime != 0)//间隔时间执行情况 { dueTime = new TimeSpan(0, TaskDefine.IntervalTime, 0); } return(dueTime); }
private bool IsExecOfDay(int repeatDateMark, int execDate) { DayOfWeek dayOfWeek = LibDateUtils.LibDateToDateTime(execDate).DayOfWeek; int dayOfWeekValue = 0; switch (dayOfWeek) { case DayOfWeek.Friday: dayOfWeekValue = (int)Math.Pow(2, 4); break; case DayOfWeek.Monday: dayOfWeekValue = (int)Math.Pow(2, 0); break; case DayOfWeek.Saturday: dayOfWeekValue = (int)Math.Pow(2, 5); break; case DayOfWeek.Sunday: dayOfWeekValue = (int)Math.Pow(2, 6); break; case DayOfWeek.Thursday: dayOfWeekValue = (int)Math.Pow(2, 3); break; case DayOfWeek.Tuesday: dayOfWeekValue = (int)Math.Pow(2, 1); break; case DayOfWeek.Wednesday: dayOfWeekValue = (int)Math.Pow(2, 2); break; } bool isExec = (repeatDateMark & dayOfWeekValue) != 0; return(isExec); }
public void AddTask(LibBusinessTask task, bool needAddDB = false) { int curDate = LibDateUtils.GetCurrentDate(); if (string.IsNullOrEmpty(task.ProgId) || string.IsNullOrEmpty(task.BusinessTaskId)) { return; } //如果指定的日期大于当前日期,无需执行 if (task.TaskType == LibTaskType.None && task.ExecDate != 0 && task.ExecDate > curDate) { return; } //未指定有效执行日期则跳过 if (task.ExecDate == 0 && task.RepeatDateMark == 0) { return; } //无设置执行时间点则跳过 if (task.IntervalTime == 0 && task.ExecTime.Count == 0) { return; } //初始化Timer LibTaskParam param = new LibTaskParam(task); string key = Guid.NewGuid().ToString(); param.Task = new LibTask(new Timer(ExecBusinessTask, param, param.GetTaskDueTime(), Timeout.InfiniteTimeSpan)); TaskList.TryAdd(key, param.Task); TaskMap.TryAdd(task.TaskId, key); if (task.TaskType == LibTaskType.TempTask && needAddDB) { LibDataAccess dataAccess = new LibDataAccess(); dataAccess.ExecuteNonQuery(string.Format("insert into AXPBUSINESSTEMPTASK(TASKID,PROGID,BUSINESSTASKID,EXECDATE,EXECTIME,EXECCONDITION,INTERNALID) values({0},{1},{2},{3},{4},{5},{6})", LibStringBuilder.GetQuotString(task.TaskId), LibStringBuilder.GetQuotString(task.ProgId), LibStringBuilder.GetQuotString(task.BusinessTaskId), task.ExecDate, task.ExecTime[0], LibStringBuilder.GetQuotString(task.ExecCondition), LibStringBuilder.GetQuotString(task.InternalId)), false); } }
private static ProgIdConfigListing BuildProgId(string bcfPath, string extendBcfPath, Dictionary <string, Assembly> assemblyDic) { ProgIdConfigListing progIdListing = new ProgIdConfigListing(); //处理标准业务模块 IEnumerator <string> enumerator = Directory.EnumerateFiles(bcfPath, "*.dll", SearchOption.AllDirectories).GetEnumerator(); List <string> standardList = new List <string>(); while (enumerator.MoveNext()) { string filePath = enumerator.Current; if (filePath.Contains("_Axce")) { continue; } standardList.Add(filePath); } BuildProgIdCore(progIdListing, standardList, assemblyDic); //处理二开扩展业务模块 DirectoryInfo dirInfo = new DirectoryInfo(extendBcfPath); FileInfo[] fileInfo = dirInfo.GetFiles("*.dll", SearchOption.AllDirectories); List <string> extendList = new List <string>(); if (fileInfo != null && fileInfo.Length > 0) { foreach (FileInfo file in fileInfo) { string destPath = Path.Combine(bcfPath, file.Name); extendList.Add(destPath); File.Copy(file.FullName, destPath, true); } BuildProgIdCore(progIdListing, extendList, assemblyDic); } progIdListing.Version = LibDateUtils.DateTimeToLibDateTime(DateTime.Now); return(progIdListing); }
public string ExportData(LibQueryCondition condition) { string fileName = string.Empty; bool ret = CheckHasPermission(FuncPermissionEnum.Export); if (ret) { if (condition == null || condition.QueryFields.Count == 0) { DataSetManager.GetDataSet(this.DataSet, this.DataAccess, this.ProgId); } else { GetQueryData(condition); } this.AfterChangeData(this.DataSet); fileName = string.Format("{0}-{1}.xls", this.ProgId, LibDateUtils.GetCurrentDateTime()); string filePath = System.IO.Path.Combine(AxCRL.Comm.Runtime.EnvProvider.Default.RuningPath, "TempData", "ExportData", fileName); AxCRL.Core.Excel.LibExcelHelper libExcelHelper = new Core.Excel.LibExcelHelper(); libExcelHelper.ExportToExcel(filePath, this.DataSet); AfterExportData(); } return(fileName); }
private static void SaveSysNews(LibDataAccess dataAccess, string title, string mainContent, string personId, string execTaskDataId, List <string> userList) { List <string> sqlList = new List <string>(); foreach (string userId in userList) { if (string.IsNullOrEmpty(userId)) { continue; } string newsId = Guid.NewGuid().ToString(); sqlList.Add(string.Format("Insert into AXPUSERNEWS(NEWSID,USERID,TITLE,MAINCONTENT,INFOID,CREATETIME,PERSONID,ISREAD) values({0},{1},{2},{3},{4},{5},{6},0)", LibStringBuilder.GetQuotString(newsId), LibStringBuilder.GetQuotString(userId), LibStringBuilder.GetQuotString(title), LibStringBuilder.GetQuotString(mainContent), LibStringBuilder.GetQuotString(execTaskDataId), LibDateUtils.GetCurrentDateTime(), LibStringBuilder.GetQuotString(personId))); } dataAccess.ExecuteNonQuery(sqlList); }
public void RemoveAttach(string attachSrc, int orderId, string personId) { LibDataAccess dataAccess = new LibDataAccess(); dataAccess.ExecuteNonQuery(string.Format("insert into AXPATTACHMENTRECORDDETAIL(BELONGTOID,ORDERID,FILENAME,PERSONID,CREATETIME) values('{0}',{1},'{2}','{3}',{4})", attachSrc, orderId, string.Empty, personId, LibDateUtils.GetCurrentDateTime())); }
public CodingRule GetCodingRule(BillType billType, string progId) { CodingRule codingRule = this.Get <CodingRule>(progId); if (codingRule == null) { lock (_LockRuleObj) { codingRule = this.Get <CodingRule>(progId); if (codingRule == null) { codingRule = new CodingRule(); Dictionary <int, int> listIndex = new Dictionary <int, int>(); SqlBuilder sqlBuilder = new SqlBuilder("com.CodingRule"); //string sql = sqlBuilder.GetQuerySql(1, "B.ROW_ID,B.SECTIONTYPE,B.SECTIONLENGTH,B.FIELDNAME,B.SECTIONVALUE", string.Format("A.PROGID = {0} And A.VALIDITYSTARTDATE <= {1} And (A.VALIDITYENDDATE >= {1} or A.VALIDITYENDDATE = 0)", LibStringBuilder.GetQuotString(progId), LibDateUtils.GetCurrentDate()), "B.ROWNO ASC"); string sql = sqlBuilder.GetQuerySql(1, "B.ROW_ID,B.SECTIONTYPE,B.SECTIONLENGTH,B.FIELDNAME,B.SECTIONVALUE", string.Format("A.PROGID = {0}", LibStringBuilder.GetQuotString(progId), LibDateUtils.GetCurrentDate()), "B.ROWNO ASC"); LibDataAccess dataAccess = new LibDataAccess(); using (IDataReader reader = dataAccess.ExecuteDataReader(sql)) { while (reader.Read()) { CodingRuleItem rule = new CodingRuleItem(); rule.SectionType = (SectionType)LibSysUtils.ToInt32(reader["SECTIONTYPE"]); rule.Length = LibSysUtils.ToInt32(reader["SECTIONLENGTH"]); switch (rule.SectionType) { case SectionType.None: rule.Value = LibSysUtils.ToString(reader["SECTIONVALUE"]); break; case SectionType.Dynamic: rule.FieldName = LibSysUtils.ToString(reader["FIELDNAME"]); rule.Values.Add(rule.FieldName, LibSysUtils.ToString(reader["SECTIONVALUE"])); int rowId = LibSysUtils.ToInt32(reader["ROW_ID"]); if (!listIndex.ContainsKey(rowId)) { listIndex.Add(rowId, codingRule.Items.Count); } if (!codingRule.CreateOnSave) { codingRule.CreateOnSave = true; } break; } codingRule.Items.Add(rule); } } sql = sqlBuilder.GetQuerySql(2, "C.PARENTROWID,C.FIELDVALUE,C.SECTIONVALUE", string.Format("A.PROGID = {0}", LibStringBuilder.GetQuotString(progId))); using (IDataReader reader = dataAccess.ExecuteDataReader(sql)) { while (reader.Read()) { int rowId = LibSysUtils.ToInt32(reader["PARENTROWID"]); if (listIndex.ContainsKey(rowId)) { CodingRuleItem rule = codingRule.Items[listIndex[rowId]]; string fieldValue = LibSysUtils.ToString(reader["FIELDVALUE"]); if (!rule.Values.ContainsKey(fieldValue)) { rule.Values.Add(fieldValue, LibSysUtils.ToString(reader["SECTIONVALUE"])); } } } } //如果为单据,默认产生编码规则 日期+6位流水码 if (codingRule.Items.Count == 0) { if (billType == BillType.Bill) { codingRule.Items.Add(new CodingRuleItem() { SectionType = SectionType.DateL }); codingRule.Items.Add(new CodingRuleItem() { SectionType = SectionType.SerialNum, Length = 6 }); } } else { codingRule.IsSetRule = true; } if (codingRule.Items.Count > 0) { this.Set(progId, codingRule, new TimeSpan(0, 180, 0)); } } } } return(codingRule); }
public void ExportRadXMLData(string filePath, DataSet dataSet, HashSet <int> tableIndex = null, bool dbField = false) { Stopwatch watch = new Stopwatch(); watch.Start(); #region 文件名,路径 string templateFile = System.IO.Path.Combine(AxCRL.Comm.Runtime.EnvProvider.Default.RuningPath, "TempData", "ExcelModel", "List.xml"); String bodyXML = File.ReadAllText(templateFile, Encoding.UTF8); #endregion StringBuilder names = new StringBuilder(""); StringBuilder Worksheet = new StringBuilder(""); for (int index = 0; index < dataSet.Tables.Count; index++) { StringBuilder headCols = new StringBuilder(""); StringBuilder rows = new StringBuilder(""); if (tableIndex != null && !tableIndex.Contains(index)) { continue; } System.Data.DataTable dt = dataSet.Tables[index]; string tableName = string.Empty; if (dbField) { tableName = dt.TableName; } else { if (dt.ExtendedProperties.ContainsKey(TableProperty.DisplayText)) { tableName = LibSysUtils.ToString(dt.ExtendedProperties[TableProperty.DisplayText]); } else { tableName = dt.TableName; } } names.AppendLine(String.Format("<NamedRange ss:Name=\"{0}\" ss:RefersTo=\"={0}!R1C1:R{1}C{2}\"/>", tableName, (dt.Rows.Count + 1).ToString(), dt.Columns.Count.ToString())); //如果存在文本列名相同时则需要此结构 Dictionary <string, int> sameColDic = null; if (!dbField) { sameColDic = new Dictionary <string, int>(); } #region 填充表头 foreach (DataColumn col in dt.Columns) { string name = dbField ? col.ColumnName : string.IsNullOrEmpty(col.Caption) ? col.ColumnName : col.Caption; if (sameColDic.ContainsKey(name)) { sameColDic[name]++; name += sameColDic[name].ToString(); } else { sameColDic.Add(name, 0); } headCols.Append(String.Format("<Cell><Data ss:Type=\"String\">{0}</Data><NamedCell ss:Name=\"{1}\"/></Cell>\r\n", name, tableName)); } #endregion #region 表格具体内容 string type = string.Empty; object value = string.Empty; foreach (DataRow curRow in dt.Rows) { if (curRow.RowState == DataRowState.Deleted) { continue; } StringBuilder builder = new StringBuilder(); #region 填充行的格式 rows.Append("<Row>\r\n"); for (int i = 0; i < dt.Columns.Count; i++) { string style = string.Empty; #region 填充的值和类型 DataColumn col = dt.Columns[i]; LibDataType dataType = (LibDataType)col.ExtendedProperties[FieldProperty.DataType]; LibControlType ctrlType = (LibControlType)col.ExtendedProperties[FieldProperty.ControlType]; switch (dataType) { case LibDataType.Text: case LibDataType.NText: case LibDataType.Binary: case LibDataType.Int64: if (dataType == LibDataType.Int64 && ctrlType == LibControlType.DateTime) { long dateTime = LibSysUtils.ToInt64(curRow[col]); if (dateTime != 0) { type = "DateTime"; style = string.Format(" ss:StyleID=\"s23\""); value = LibDateUtils.LibDateToDateTime(dateTime).ToString("yyyy-MM-ddTHH:mm:ss"); } else { type = "String"; value = string.Empty; } } else { type = "String"; value = curRow[col]; } break; case LibDataType.Int32: case LibDataType.Numeric: case LibDataType.Float: case LibDataType.Double: case LibDataType.Byte: if (dataType == LibDataType.Int32 && ctrlType == LibControlType.Date) { int date = LibSysUtils.ToInt32(curRow[col]); if (date != 0) { type = "DateTime"; value = string.Format("{0}T00:00:00.000", LibDateUtils.LibDateToDateTime(date).ToString("yyyy-MM-dd")); style = string.Format(" ss:StyleID=\"s23\""); } else { type = "String"; value = string.Empty; } } else if (dataType == LibDataType.Int32 && ctrlType == LibControlType.HourMinute) { type = "Number"; string time = LibSysUtils.ToString(curRow[col]); switch (time.Length) { case 1: time = "000" + time + "00"; break; case 2: time = "00" + time + "00"; break; case 3: time = "0" + time + "00"; break; case 4: time = time + "00"; break; default: time = time + "00"; break; } time = "20150101" + time; value = LibStringBuilder.GetQuotObject(LibDateUtils.LibDateToDateTime(LibSysUtils.ToInt64(time)).ToString("HH:mm")); } else if (dataType == LibDataType.Numeric) { type = "Number"; style = string.Format(" ss:StyleID=\"s24\""); value = curRow[col]; } else { type = "Number"; value = curRow[col]; } break; case LibDataType.Boolean: type = "Number"; value = LibSysUtils.ToBoolean(curRow[col.ColumnName]) ? 1 : 0; break; } #endregion rows.Append(string.Format("<Cell{3}><Data ss:Type=\"{0}\">{1}</Data><NamedCell ss:Name=\"{2}\"/></Cell>\r\n", type, value, tableName, style)); } rows.Append("</Row>\r\n"); #endregion } #endregion #region 构建表格模板 Worksheet.AppendLine(string.Format("<Worksheet ss:Name=\"{0}\">\n<Table ss:ExpandedColumnCount=\"{1}\" ss:ExpandedRowCount=\"{2}\" x:FullColumns=\"1\" x:FullRows=\"1\" ss:DefaultRowHeight=\"12\">", tableName, dt.Columns.Count.ToString(), (dt.Rows.Count + 1).ToString())); Worksheet.AppendLine(string.Format(@"<Row> {0} </Row> {1} </Table>", headCols.ToString(), rows.ToString())); Worksheet.AppendLine("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">"); Worksheet.AppendLine("<PageSetup>"); Worksheet.AppendLine("<Header x:Data=\"&A\"/>"); Worksheet.AppendLine("<Footer x:Data=\"Page &P\"/>"); Worksheet.AppendLine(@"</PageSetup> <Selected/> <ProtectObjects>False</ProtectObjects> <ProtectScenarios>False</ProtectScenarios> </WorksheetOptions> </Worksheet>"); #endregion } #region 将数据替换到模板中 DateTime datetime = DateTime.Now; bodyXML = bodyXML.Replace("{##Author##}", "Administrator"); bodyXML = bodyXML.Replace("{##Created##}", datetime.ToString()); bodyXML = bodyXML.Replace("{##Names##}", names.ToString()); bodyXML = bodyXML.Replace("{##Worksheet##}", Worksheet.ToString()); #endregion try { string path = filePath; using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs)) { sw.Write(bodyXML); } } watch.Stop(); string time = watch.ElapsedMilliseconds.ToString(); } catch (Exception ex) { throw ex; } }
public string MoveAttach(LibAttachData attachData) { LibDataAccess dataAccess = new LibDataAccess(); List <string> listSql = new List <string>(); //更新结构 UpdateAttachStruct(attachData, listSql); //更新附件记录明细 listSql.Add(string.Format("insert into AXPATTACHMENTRECORDDETAIL(BELONGTOID,ORDERID,FILENAME,PERSONID,CREATETIME) values('{0}',{1},'{2}','{3}',{4})", attachData.AttachSrc, attachData.OrderId, attachData.FileName, attachData.PersonId, LibDateUtils.GetCurrentDateTime())); LibDBTransaction trans = dataAccess.BeginTransaction(); try { dataAccess.ExecuteNonQuery(listSql); trans.Commit(); } catch { trans.Rollback(); throw; } string path = Path.Combine(EnvProvider.Default.MainPath, "AxFile", "Attachment", attachData.ProgId, attachData.AttachSrc); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string orgFilePath = Path.Combine(EnvProvider.Default.MainPath, "AxFile", "Attachment", attachData.FileName); File.Move(orgFilePath, Path.Combine(path, attachData.FileName)); return(attachData.AttachSrc); }
private void ExecBusinessTask(object obj) { LibTaskParam param = (LibTaskParam)obj; LibBusinessTask taskDefine = param.TaskDefine; //系统当天是否可以执行 if (IsExecOfDay(taskDefine)) { try { param.Task.TaskState = TaskRunState.Running; LibBcfBase bcf = LibBcfSystem.Default.GetBcfInstance(taskDefine.ProgId); bcf.Handle = LibHandleCache.Default.GetSystemHandle(); Type type = bcf.GetType(); object[] destParam = RestoreParamFormat(type, taskDefine.BusinessTaskId, new string[] { taskDefine.ExecCondition }); object result = bcf.GetType().InvokeMember(taskDefine.BusinessTaskId, BindingFlags.InvokeMethod, null, bcf, destParam); switch (bcf.Template.BillType) { case AxCRL.Template.BillType.Master: case AxCRL.Template.BillType.Bill: break; case AxCRL.Template.BillType.Grid: break; case AxCRL.Template.BillType.DataFunc: break; case AxCRL.Template.BillType.Rpt: case AxCRL.Template.BillType.DailyRpt: DataSet dataSet = result as DataSet; if (dataSet != null) { LibSysNews news = new LibSysNews(); news.Content = taskDefine.MainContent; news.Data = LibBillDataSerializeHelper.Serialize(dataSet); news.PersonId = "SYSTEM"; news.ProgId = taskDefine.ProgId; news.Title = taskDefine.Title; foreach (LibBusinessTaskLiaison item in taskDefine.Liaison) { news.UserList.Add(item.UserId); } LibSysNewsHelper.SendNews(news, false); } break; default: break; } } catch (Exception ex) { //将错误输出 string path = System.IO.Path.Combine(AxCRL.Comm.Runtime.EnvProvider.Default.MainPath, "Output", "Error", "ScheduleTask", string.Format("{0}.txt", DateTime.Now.Ticks)); OutputInfo(path, ex.ToString()); } finally { param.Task.TaskState = TaskRunState.Wait; } } bool canNextExec = true; if (taskDefine.ExecDate != 0) { int curDate = LibDateUtils.GetCurrentDate(); if (taskDefine.ExecDate > curDate) { param.Task.Timer.Dispose(); canNextExec = false; param.Task.TaskState = TaskRunState.Stop; } else if (taskDefine.ExecDate == curDate && taskDefine.ExecTime.Count > 0) { int curTime = LibDateUtils.GetLibTimePart(LibDateUtils.GetCurrentDateTime(), LibDateTimePartEnum.Time); if (taskDefine.ExecTime[taskDefine.ExecTime.Count - 1] < curTime) { param.Task.Timer.Dispose(); canNextExec = false; param.Task.TaskState = TaskRunState.Stop; } } } if (canNextExec) { param.Task.Timer.Change(param.GetTaskDueTime(), Timeout.InfiniteTimeSpan); } else if (taskDefine.TaskType == LibTaskType.TempTask) { //删除临时任务 LibDataAccess dataAccess = new LibDataAccess(); dataAccess.ExecuteNonQuery(string.Format("delete AXPBUSINESSTEMPTASK where TASKID={0}", LibStringBuilder.GetQuotString(taskDefine.TaskId)), false); } }
public void ImportToDataSet(string filePath, DataSet dataSet, Action <System.Data.DataTable> actionTable, Func <DataRow, Dictionary <string, object>, bool> actionRow, bool dbField = false) { try { string connStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'; Extended Properties='Excel 8.0;HDR=Yes;IMEX=2'", filePath); List <string> sqlList = new List <string>(); foreach (System.Data.DataTable table in dataSet.Tables) { string tableName = string.Empty; if (dbField) { tableName = table.TableName; } else { if (table.ExtendedProperties.ContainsKey(TableProperty.DisplayText)) { tableName = LibSysUtils.ToString(table.ExtendedProperties[TableProperty.DisplayText]); } else { tableName = table.TableName; } } sqlList.Add(string.Format("select * from [{0}$]", tableName)); } dataSet.EnforceConstraints = false; using (OleDbConnection conn = new OleDbConnection(connStr)) { conn.Open(); try { int i = 0; foreach (string sql in sqlList) { System.Data.DataTable curTable = dataSet.Tables[i]; Dictionary <string, DataColumn> colMap = null; if (!dbField) { colMap = new Dictionary <string, DataColumn>(); foreach (DataColumn col in curTable.Columns) { try { colMap.Add(col.Caption, col); } catch (Exception ex) { throw ex; } } } curTable.BeginLoadData(); try { using (OleDbCommand command = new OleDbCommand(sql, conn)) { using (IDataReader reader = command.ExecuteReader()) { while (reader.Read()) { bool canAdd = true; Dictionary <string, object> otherValueList = null; DataRow newRow = curTable.NewRow(); newRow.BeginEdit(); try { bool allNull = true; for (int l = 0; l < reader.FieldCount; l++) { string colName = reader.GetName(l).Trim(); if (!Convert.IsDBNull(reader[l])) { if (allNull) { allNull = false; } string realName = string.Empty; if (dbField) { if (curTable.Columns.Contains(colName)) { realName = colName; } } else { if (colMap.ContainsKey(colName)) { realName = colMap[colName].ColumnName; } } if (!string.IsNullOrEmpty(realName)) { LibControlType controlType = (LibControlType)colMap[colName].ExtendedProperties[FieldProperty.ControlType]; if (controlType == LibControlType.DateTime || controlType == LibControlType.Date) { DateTime curTime; DateTime.TryParse(LibSysUtils.ToString(reader[l]), out curTime); if (controlType == LibControlType.Date) { newRow[realName] = LibDateUtils.DateTimeToLibDate(curTime); } else if (controlType == LibControlType.DateTime) { newRow[realName] = LibDateUtils.DateTimeToLibDateTime(curTime); } } else if (controlType == LibControlType.HourMinute) { string hourtime = LibSysUtils.ToString(reader[l]); hourtime = hourtime.Replace(":", ""); newRow[realName] = LibSysUtils.ToInt32(hourtime); } else if (controlType == LibControlType.Text || controlType == LibControlType.NText) { newRow[realName] = LibSysUtils.ToString(reader[l]).Trim(); } else { newRow[realName] = reader[l]; } } else { if (otherValueList == null) { otherValueList = new Dictionary <string, object>(); } if (!otherValueList.ContainsKey(colName)) { otherValueList.Add(colName, reader[l]); } } } } canAdd = !allNull; //全为null的行是空行不需要导入 if (canAdd) { canAdd = actionRow(newRow, otherValueList); } } finally { newRow.EndEdit(); } if (canAdd) { curTable.Rows.Add(newRow); } } } actionTable(curTable); } } finally { curTable.EndLoadData(); } i++; } } catch (Exception ex) { Exception ex1 = ex; } finally { conn.Close(); dataSet.EnforceConstraints = true; } } } catch (Exception ex) { if (dataSet.HasErrors) { string errorData = string.Empty; foreach (DataTable dt in dataSet.Tables) { foreach (DataRow dr in dt.GetErrors()) { errorData += string.Format(" {0}", dr.RowError); } } Exception dsEx = new Exception(errorData); LibLog.WriteLog(dsEx); } LibLog.WriteLog(ex); throw; } }
public string ExportDataX(DataSet data) { string fileName = string.Empty; this.DataSet.EnforceConstraints = false; DataTable dt = this.DataSet.Tables[0]; DataTable subDt = this.DataSet.Tables[1]; try { dt.BeginLoadData(); subDt.BeginLoadData(); foreach (DataRow currentRow in data.Tables[0].Rows) { DataRow newRow = dt.NewRow(); newRow.BeginEdit(); foreach (DataColumn col in data.Tables[0].Columns) { newRow[col.ColumnName] = currentRow[col.ColumnName]; } newRow.EndEdit(); dt.Rows.Add(newRow); } foreach (DataRow currentRow in data.Tables[1].Rows) { DataRow newRow = subDt.NewRow(); newRow.BeginEdit(); foreach (DataColumn col in data.Tables[1].Columns) { newRow[col.ColumnName] = currentRow[col.ColumnName]; } newRow.EndEdit(); subDt.Rows.Add(newRow); } } finally { dt.EndLoadData(); subDt.EndLoadData(); this.DataSet.EnforceConstraints = true; } fileName = string.Format("{0}-{1}.xls", this.ProgId, string.Format("{0}{1}", "UnitInfo", LibDateUtils.GetCurrentDateTime())); string filePath = System.IO.Path.Combine(AxCRL.Comm.Runtime.EnvProvider.Default.RuningPath, "TempData", "ExportData", fileName); AxCRL.Core.Excel.LibExcelHelper libExcelHelper = new Core.Excel.LibExcelHelper(); libExcelHelper.ExportToExcel(filePath, this.DataSet); //} return(fileName); }
public static Result SavePictureCalidateCode(string userId, string code) { Result result = new Result(); LibDataAccess dataAccess = new LibDataAccess(); string sql = string.Format("SELECT count(*) FROM AXPVERIFYCODE WHERE USERID = {0}", LibStringBuilder.GetQuotString(userId)); int count = LibSysUtils.ToInt32(dataAccess.ExecuteScalar(sql)); // 生成或者更新验证码 if (count == 0) { sql = string.Format("INSERT INTO AXPVERIFYCODE(USERID, VERIFYCODE, TIME) VALUES({0}, {1}, {2})", LibStringBuilder.GetQuotString(userId), LibStringBuilder.GetQuotString(code), LibDateUtils.GetCurrentDateTime()); } else if (count == 1) { sql = string.Format("UPDATE AXPVERIFYCODE SET VERIFYCODE={0}, TIME={1} WHERE USERID={2}", LibStringBuilder.GetQuotString(code), LibDateUtils.GetCurrentDateTime(), LibStringBuilder.GetQuotString(userId)); } dataAccess.ExecuteNonQuery(sql); return(result); }
public BarcodeRule GetBarcodeRule(string ruleId) { BarcodeRule codingRule = this.Get <BarcodeRule>(ruleId); if (codingRule == null) { lock (_LockRuleObj) { codingRule = this.Get <BarcodeRule>(ruleId); if (codingRule == null) { string sql; SqlBuilder sqlBuilder = new SqlBuilder("com.BarcodeRule"); sql = sqlBuilder.GetQuerySql(1, "B.ROW_ID,B.SECTIONTYPE,B.SECTIONLENGTH,B.TABLEINDEX,B.FIELDNAME,B.SECTIONVALUE", string.Format("A.BARCODERULEID={0} And A.VALIDITYSTARTDATE <= {1} And (A.VALIDITYENDDATE >= {1} or A.VALIDITYENDDATE = 0)", LibStringBuilder.GetQuotString(ruleId), LibDateUtils.GetCurrentDate()), "B.ROWNO ASC"); codingRule = new BarcodeRule(); Dictionary <int, int> listIndex = new Dictionary <int, int>(); LibDataAccess dataAccess = new LibDataAccess(); using (IDataReader reader = dataAccess.ExecuteDataReader(sql)) { int startIndex = 0; while (reader.Read()) { BarcodeRuleItem rule = new BarcodeRuleItem(); rule.SectionType = (BarcodeRuleSectionType)LibSysUtils.ToInt32(reader["SECTIONTYPE"]); rule.Start = startIndex; rule.Length = LibSysUtils.ToInt32(reader["SECTIONLENGTH"]); switch (rule.SectionType) { case BarcodeRuleSectionType.None: rule.Value = LibSysUtils.ToString(reader["SECTIONVALUE"]); break; case BarcodeRuleSectionType.Dynamic: rule.TableIndex = LibSysUtils.ToInt32(reader["TABLEINDEX"]); rule.FieldName = LibSysUtils.ToString(reader["FIELDNAME"]); rule.Values.Add(rule.FieldName, LibSysUtils.ToString(reader["SECTIONVALUE"])); int rowId = LibSysUtils.ToInt32(reader["ROW_ID"]); if (!listIndex.ContainsKey(rowId)) { listIndex.Add(rowId, codingRule.Items.Count); } break; } startIndex += rule.Length; codingRule.Items.Add(rule); } } sql = sqlBuilder.GetQuerySql(2, "C.PARENTROWID,C.FIELDVALUE,C.SECTIONVALUE", string.Format("A.BARCODERULEID={0} And A.VALIDITYSTARTDATE <= {1} And (A.VALIDITYENDDATE >= {1} or A.VALIDITYENDDATE = 0)", LibStringBuilder.GetQuotString(ruleId), LibDateUtils.GetCurrentDate())); using (IDataReader reader = dataAccess.ExecuteDataReader(sql)) { while (reader.Read()) { int rowId = LibSysUtils.ToInt32(reader["PARENTROWID"]); if (listIndex.ContainsKey(rowId)) { BarcodeRuleItem rule = codingRule.Items[listIndex[rowId]]; string fieldValue = LibSysUtils.ToString(reader["FIELDVALUE"]); if (!rule.Values.ContainsKey(fieldValue)) { rule.Values.Add(fieldValue, LibSysUtils.ToString(reader["SECTIONVALUE"])); } } } } this.Set(ruleId, codingRule, new TimeSpan(0, 180, 0)); } } } return(codingRule); }
protected override void BeforeUpdate() { DataRow masterRow = this.DataSet.Tables[0].Rows[0]; bool isWorkSaturday = LibSysUtils.ToBoolean(masterRow["ISWORKSATURDAY"]); bool isWorkSunday = LibSysUtils.ToBoolean(masterRow["ISWORKSUNDAY"]); foreach (DataRow curRow in this.DataSet.Tables[1].Rows) { if (curRow.RowState == DataRowState.Deleted) { continue; } int workMark = 0; int workDayCount = 0; int year = LibSysUtils.ToInt32(curRow["YEAR"]); int month = LibSysUtils.ToInt32(curRow["MONTH"]); int days = DateTime.DaysInMonth(year, month); Dictionary <int, bool> specialDic = new Dictionary <int, bool>(); DataRow[] childRows = curRow.GetChildRows("COMCALENDARDETAIL_COMHOLIDAYDETAIL"); foreach (DataRow subRow in childRows) { int dayNum = LibDateUtils.LibDateToDateTime(LibSysUtils.ToInt32(subRow["HOLIDAYDATE"])).Day; specialDic.Add(dayNum, LibSysUtils.ToBoolean(subRow["ISWORK"])); } for (int i = 0; i < days; i++) { int date = i + 1; if (specialDic.ContainsKey(date)) { if (specialDic[date]) { workMark += (int)Math.Pow(2, i); workDayCount++; } continue; } DayOfWeek week = new DateTime(year, month, i + 1).DayOfWeek; if (week != DayOfWeek.Saturday && week != DayOfWeek.Sunday) { workMark += (int)Math.Pow(2, i); workDayCount++; } else { if ((week == DayOfWeek.Saturday && isWorkSaturday == true) || (week == DayOfWeek.Sunday && isWorkSunday == true)) { workMark += (int)Math.Pow(2, i); workDayCount++; } } } curRow.BeginEdit(); try { curRow["WEEKDAY"] = workDayCount; curRow["NONWORKDAY"] = days - workDayCount; curRow["WORKMARK"] = workMark; } finally { curRow.EndEdit(); } } }
private string GetFilterCondition() { string filter = string.Empty; if (this.DataSet.Tables[0].ExtendedProperties.ContainsKey(TableProperty.FilterSetting)) { FilterSetting filterSetting = this.DataSet.Tables[0].ExtendedProperties[TableProperty.FilterSetting] as FilterSetting; if (filterSetting != null) { DataTable table = this.DataSet.Tables[0]; if (table.Columns.Contains(filterSetting.Name)) { if (table.Columns[filterSetting.Name].ExtendedProperties.ContainsKey(FieldProperty.ControlType)) { //TODO需考虑节假日的情况,例如周五看到明天的数据,应该是看到周一的数据 LibControlType controlType = (LibControlType)table.Columns[filterSetting.Name].ExtendedProperties[FieldProperty.ControlType]; if (controlType == LibControlType.Date) { int currentDate = LibDateUtils.GetCurrentDate(); if (filterSetting.Day == 0) { filter = string.Format("A.{0} = {1}", filterSetting.Name, currentDate); } else { int otherDate = LibDateUtils.AddDayToLibDate(currentDate, filterSetting.Day); if (currentDate < otherDate) { filter = string.Format("A.{0} >= {1} and A.{0} <= {2}", filterSetting.Name, currentDate, otherDate); } else { filter = string.Format("A.{0} >= {1} and A.{0} <= {2}", filterSetting.Name, otherDate, currentDate); } } } else if (controlType == LibControlType.DateTime) { int currentDate = LibDateUtils.GetCurrentDate(); if (filterSetting.Day == 0) { filter = string.Format("A.{0} >= {1}000000 and A.{0}<={2}999999", filterSetting.Name, currentDate); } else { int otherDate = LibDateUtils.AddDayToLibDate(currentDate, filterSetting.Day); if (currentDate < otherDate) { filter = string.Format("A.{0} >= {1}000000 and A.{0} <= {2}999999", filterSetting.Name, currentDate, otherDate); } else { filter = string.Format("A.{0} >= {1}000000 and A.{0} <= {2}999999", filterSetting.Name, otherDate, currentDate); } } } } } } } return(filter); }
private static void InitBusinessTask() { Dictionary <string, LibBusinessTask> taskList = new Dictionary <string, LibBusinessTask>(); int currentDate = LibDateUtils.GetCurrentDate(); SqlBuilder sqlBuilder = new SqlBuilder("axp.ScheduleTask"); string sql = sqlBuilder.GetQuerySql(0, "A.TASKID,A.PROGID,A.BUSINESSTASKID,A.CALENDARID,A.ISJUSTWORKDAY,A.INTERVALTIME,A.EXECDATE,A.REPEATDATEMARK,A.EXECCONDITION,A.TITLE,A.MAINCONTENT,B.EXECTIME", string.Format("A.CURRENTSTATE=2 and (A.VALIDITYSTARTDATE <= {0} and (A.VALIDITYENDDATE>{0} or A.VALIDITYENDDATE = 0))", currentDate), "A.TASKID,B.EXECTIME"); LibDataAccess dataAccess = new LibDataAccess(); using (IDataReader reader = dataAccess.ExecuteDataReader(sql, false)) { while (reader.Read()) { string taskId = LibSysUtils.ToString(reader["TASKID"]); int execTime = LibSysUtils.ToInt32(reader["EXECTIME"]); if (taskList.ContainsKey(taskId)) { if (execTime > 0) { taskList[taskId].ExecTime.Add(execTime); } } else { LibBusinessTask task = new LibBusinessTask(); task.BusinessTaskId = LibSysUtils.ToString(reader["BUSINESSTASKID"]); task.CalendarId = LibSysUtils.ToString(reader["CALENDARID"]); task.ExecCondition = LibSysUtils.ToString(reader["ExecCondition"]); task.ExecDate = LibSysUtils.ToInt32(reader["EXECDATE"]); task.IntervalTime = LibSysUtils.ToInt32(reader["INTERVALTIME"]); task.IsJustWorkDay = LibSysUtils.ToBoolean(reader["ISJUSTWORKDAY"]); task.ProgId = LibSysUtils.ToString(reader["PROGID"]); task.Title = LibSysUtils.ToString(reader["TITLE"]); task.MainContent = LibSysUtils.ToString(reader["MAINCONTENT"]); task.RepeatDateMark = LibSysUtils.ToInt32(reader["REPEATDATEMARK"]); task.TaskId = taskId; if (execTime > 0) { task.ExecTime.Add(execTime); } taskList.Add(taskId, task); } } } sql = string.Format("select distinct A.TASKID,A.PERSONID,D.DEPTID,C.USERID from AXPSCHEDULETASKPERSON A " + "inner join AXPSCHEDULETASK B on B.TASKID=A.TASKID left join COMPERSON D on D.PERSONID=A.PERSONID inner join AXPUSER C on C.PERSONID=A.PERSONID " + "where B.CURRENTSTATE=2 and (B.VALIDITYSTARTDATE <= {0} and (B.VALIDITYENDDATE>{0} or B.VALIDITYENDDATE = 0))", currentDate); using (IDataReader reader = dataAccess.ExecuteDataReader(sql, false)) { while (reader.Read()) { string taskId = LibSysUtils.ToString(reader["TASKID"]); if (taskList.ContainsKey(taskId)) { taskList[taskId].Liaison.Add(new LibBusinessTaskLiaison() { PersonId = LibSysUtils.ToString(reader["PERSONID"]), DeptId = LibSysUtils.ToString(reader["DEPTID"]), UserId = LibSysUtils.ToString(reader["USERID"]) }); } } } foreach (var item in taskList) { _Default.Set(item.Key, item.Value); } }
public UpLoadFileResult UpLoadFile1(HttpPostedFile file, string progId = "") { UpLoadFileResult upLoadFileResult = new UpLoadFileResult(); bool isLocalHost = true; string fileName = LibDateUtils.Now().Ticks.ToString(); fileName = file.FileName.Replace(file.FileName.Substring(0, file.FileName.LastIndexOf('.')), fileName); string filePath = Path.Combine(EnvProvider.Default.RuningPath, "TempData", "ImportData", fileName); string url = Path.Combine("\\TempData", "ImportData", fileName); #region 对应实体图片路径 if (!string.IsNullOrEmpty(progId)) { string sql = string.Format(" SELECT Url,LocalHost FROM ComImagePath WHERE Progid='{0}' ", progId); DataSet dataSet = new LibDataAccess().ExecuteDataSet(sql); if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0) { DataRow dr = dataSet.Tables[0].Rows[0]; isLocalHost = LibSysUtils.ToBoolean(dr["LocalHost"]); url = LibSysUtils.Combine(LibSysUtils.ToString(dr["Url"]), fileName); filePath = LibSysUtils.Combine(EnvProvider.Default.RuningPath, url); } } #endregion #region 新增图片实体 LibEntryParam entryParam = new LibEntryParam(); DataSet dataset = null; LibBcfData bcfData = (LibBcfData)LibBcfSystem.Default.GetBcfInstance("KanTime.Picture"); dataset = bcfData.AddNew(entryParam); #region 填充数据 dataset.EnforceConstraints = false; try { #region 表头 DataRow masterRow = dataset.Tables[0].Rows[0]; masterRow.BeginEdit(); masterRow["Name"] = fileName; masterRow["Url"] = url; masterRow.EndEdit(); #endregion #region 明细 //dataset.Tables[1].BeginLoadData(); //dataset.Tables[1].EndLoadData(); #endregion } finally { dataset.EnforceConstraints = true; } dataset = bcfData.InnerSave(BillAction.AddNew, null, dataset); if (bcfData.ManagerMessage.IsThrow) { StringBuilder strMsg = new StringBuilder(); foreach (var item in bcfData.ManagerMessage.MessageList) { strMsg.AppendFormat("{0}", item.Message); } throw new Exception(strMsg.ToString()); } #endregion #endregion file.SaveAs(filePath); #region 返回本机或外网地址 if (isLocalHost) { upLoadFileResult.FileName = url; } else { upLoadFileResult.FileName = LibSysUtils.Combine(EnvProvider.Default.UploadHostName, url); } #endregion upLoadFileResult.success = true; return(upLoadFileResult); }
private static string SaveTaskResult(LibDataAccess dataAccess, string progId, string data) { string execTaskDataId = Guid.NewGuid().ToString(); dataAccess.ExecuteStoredProcedure("axpInsertExecTaskData", execTaskDataId, LibDateUtils.GetCurrentDateTime(), progId, data); return(execTaskDataId); }
public void ExportToExcel(string filePath, DataSet dataSet, HashSet <int> tableIndex = null, bool dbField = false) { try { IList <string> dmlSqlList = new List <string>(); IList <string> sqlList = new List <string>(); for (int index = 0; index < dataSet.Tables.Count; index++) { if (tableIndex != null && !tableIndex.Contains(index)) { continue; } System.Data.DataTable table = dataSet.Tables[index]; //如果存在文本列名相同时则需要此结构 Dictionary <string, int> sameColDic = null; if (!dbField) { sameColDic = new Dictionary <string, int>(); } string columnStr = string.Empty; StringBuilder columnDefineBuilder = new StringBuilder(); StringBuilder columnBuilder = new StringBuilder(); foreach (DataColumn col in table.Columns) { string name = dbField ? col.ColumnName : string.IsNullOrEmpty(col.Caption) ? col.ColumnName : col.Caption; if (sameColDic.ContainsKey(name)) { sameColDic[name]++; name += sameColDic[name].ToString(); } else { sameColDic.Add(name, 0); } columnBuilder.AppendFormat("{0},", name); LibDataType dataType = (LibDataType)col.ExtendedProperties[FieldProperty.DataType]; switch (dataType) { case LibDataType.Text: case LibDataType.NText: //columnDefineBuilder.AppendFormat("{0} String,", name); columnDefineBuilder.AppendFormat("{0} memo,", name); break; case LibDataType.Int32: LibControlType ctrlType = (LibControlType)col.ExtendedProperties[FieldProperty.ControlType]; if (ctrlType == LibControlType.Date) { columnDefineBuilder.AppendFormat("{0} Date,", name); } else if (ctrlType == LibControlType.HourMinute) { columnDefineBuilder.AppendFormat("{0} String,", name); } else { columnDefineBuilder.AppendFormat("{0} Integer,", name); } break; case LibDataType.Int64: ctrlType = (LibControlType)col.ExtendedProperties[FieldProperty.ControlType]; if (ctrlType == LibControlType.DateTime) { columnDefineBuilder.AppendFormat("{0} DateTime,", name); } else { columnDefineBuilder.AppendFormat("{0} Long,", name); } break; case LibDataType.Numeric: columnDefineBuilder.AppendFormat("{0} Currency,", name); break; case LibDataType.Float: columnDefineBuilder.AppendFormat("{0} Single,", name); break; case LibDataType.Double: columnDefineBuilder.AppendFormat("{0} Double,", name); break; case LibDataType.Byte: columnDefineBuilder.AppendFormat("{0} Integer,", name); break; case LibDataType.Boolean: columnDefineBuilder.AppendFormat("{0} Integer,", name); break; case LibDataType.Binary: columnDefineBuilder.AppendFormat("{0} memo,", name); break; } } if (columnBuilder.Length > 0) { columnBuilder.Remove(columnBuilder.Length - 1, 1); columnDefineBuilder.Remove(columnDefineBuilder.Length - 1, 1); } columnStr = columnBuilder.ToString(); string tableName = string.Empty; if (dbField) { tableName = table.TableName; } else { if (table.ExtendedProperties.ContainsKey(TableProperty.DisplayText)) { tableName = LibSysUtils.ToString(table.ExtendedProperties[TableProperty.DisplayText]); } else { tableName = table.TableName; } } dmlSqlList.Add(string.Format("CREATE TABLE {0} ({1})", tableName, columnDefineBuilder.ToString())); foreach (DataRow curRow in table.Rows) { if (curRow.RowState == DataRowState.Deleted) { continue; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < table.Columns.Count; i++) { DataColumn col = table.Columns[i]; LibDataType dataType = (LibDataType)col.ExtendedProperties[FieldProperty.DataType]; LibControlType ctrlType = (LibControlType)col.ExtendedProperties[FieldProperty.ControlType]; switch (dataType) { case LibDataType.Text: case LibDataType.NText: case LibDataType.Binary: case LibDataType.Int64: if (dataType == LibDataType.Int64 && ctrlType == LibControlType.DateTime) { long dateTime = LibSysUtils.ToInt64(curRow[col]); if (dateTime != 0) { builder.AppendFormat("{0},", LibStringBuilder.GetQuotObject(LibDateUtils.LibDateToDateTime(dateTime).ToString("yyyy-MM-dd HH:mm:ss"))); } else { builder.Append("null,"); } } else { builder.AppendFormat("{0},", LibStringBuilder.GetQuotObject(curRow[col])); } break; case LibDataType.Int32: case LibDataType.Numeric: case LibDataType.Float: case LibDataType.Double: case LibDataType.Byte: if (dataType == LibDataType.Int32 && ctrlType == LibControlType.Date) { int date = LibSysUtils.ToInt32(curRow[col]); if (date != 0) { builder.AppendFormat("{0},", LibStringBuilder.GetQuotObject(LibDateUtils.LibDateToDateTime(date).ToLongDateString())); } else { builder.Append("null,"); } } else if (dataType == LibDataType.Int32 && ctrlType == LibControlType.HourMinute) { string time = LibSysUtils.ToString(curRow[col]); switch (time.Length) { case 1: time = "000" + time + "00"; break; case 2: time = "00" + time + "00"; break; case 3: time = "0" + time + "00"; break; case 4: time = time + "00"; break; default: time = time + "00"; break; } time = "20150101" + time; builder.AppendFormat("{0},", LibStringBuilder.GetQuotObject(LibDateUtils.LibDateToDateTime(LibSysUtils.ToInt64(time)).ToString("HH:mm"))); } else { builder.AppendFormat("{0},", curRow[col]); } break; case LibDataType.Boolean: builder.AppendFormat("{0},", LibSysUtils.ToBoolean(curRow[col.ColumnName]) ? 1 : 0); break; } } if (builder.Length > 0) { builder.Remove(builder.Length - 1, 1); } sqlList.Add(string.Format("insert into {0}({1}) values({2})", tableName, columnBuilder, builder.ToString())); } } string connStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'; Extended Properties='Excel 8.0;HDR=Yes;IMEX=2,ReadOnly=False'", filePath); using (OleDbConnection conn = new OleDbConnection(connStr)) { conn.Open(); try { foreach (string sql in dmlSqlList) { using (OleDbCommand command = new OleDbCommand(sql, conn)) { command.ExecuteNonQuery(); } } foreach (string sql in sqlList) { using (OleDbCommand command = new OleDbCommand(sql, conn)) { command.ExecuteNonQuery(); } } } finally { conn.Close(); } } } catch (Exception ex) { string path = System.IO.Path.Combine(AxCRL.Comm.Runtime.EnvProvider.Default.MainPath, "Output", "Error", "Excel", string.Format("{0}.txt", DateTime.Now.Ticks)); using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs)) { sw.Write(ex); } } throw; } }
public static Result GenerateCode(string userId, string phoneNo) { Result res = new Result(); try { // 生成四位数的验证码 Random r = new Random(); int i = (int)(r.NextDouble() * 10000); string code = i.ToString().PadLeft(4, '0'); // 查看是否存在该帐号对应的验证码 LibDataAccess access = new LibDataAccess(); string sql = string.Format("SELECT count(*) FROM AXPVERIFYCODE WHERE USERID = {0}", LibStringBuilder.GetQuotString(userId)); int count = LibSysUtils.ToInt32(access.ExecuteScalar(sql)); // 生成或者更新验证码 if (count == 0) { sql = string.Format("INSERT INTO AXPVERIFYCODE(USERID, VERIFYCODE, TIME) VALUES({0}, {1}, {2})", LibStringBuilder.GetQuotString(userId), LibStringBuilder.GetQuotString(code), LibDateUtils.GetCurrentDateTime()); } else if (count == 1) { sql = string.Format("UPDATE AXPVERIFYCODE SET VERIFYCODE={0}, TIME={1} WHERE USERID={2}", LibStringBuilder.GetQuotString(code), LibDateUtils.GetCurrentDateTime(), LibStringBuilder.GetQuotString(userId)); } access.ExecuteNonQuery(sql); // 发送短信 SendSMSParam sendSMSParam = new SendSMSParam(); sendSMSParam.Message = "验证码为:" + code; sendSMSParam.PhoneList.Add(phoneNo); LibSMSHelper.SendMsg(sendSMSParam); res.ReturnValue = true; res.Message = "成功!"; } catch (Exception ex) { res.ReturnValue = false; res.Message = "失败!" + ex.Message; } return(res); }
public override bool Remove(string key, string regionName = null) { LibHandle handle = this.Get <LibHandle>(key); if (base.Remove(key)) { try { LibDataAccess dataAccess = new LibDataAccess(); dataAccess.ExecuteStoredProcedure("axpInsertUserLogin", handle.UserId, LibDateUtils.DateTimeToLibDateTime(handle.CreateTime), handle.Type, LibDateUtils.GetCurrentDateTime()); } catch { //即使有错也不抛出 } return(true); } return(false); }