// Method to execute the trade public void executeTrade(String symbol, SignalResult signal) { try { TRADE_OPERATION op; double price, lots; int slippage = 5000; double stoploss = this.getStopLoss(symbol, signal); double takeprofit = this.getTakeProfit(symbol, signal); String comment = this.getComment(symbol); int magic = this.getMagicNumber(symbol); DateTime expiration = this.getExpiry(symbol, signal); COLOR arrowColor = COLOR.Aqua; double stopDistance; DateTime lastBuyOpen, lastSellOpen; bool openBuyOrder = false, openSellOrder = false, openBuyStopOrder = false, openSellStopOrder = false, openBuyLimitOrder = false, openSellLimitOrder = false; if (signal.getSignal() == SignalResult.BUYMARKET) { op = TRADE_OPERATION.OP_BUY; } else if (signal.getSignal() == SignalResult.SELLMARKET) { op = TRADE_OPERATION.OP_SELL; } else if (signal.getSignal() == SignalResult.BUYSTOP) { op = TRADE_OPERATION.OP_BUYSTOP; } else if (signal.getSignal() == SignalResult.SELLSTOP) { op = TRADE_OPERATION.OP_SELLSTOP; } else if (signal.getSignal() == SignalResult.BUYLIMIT) { op = TRADE_OPERATION.OP_BUYLIMIT; } else if (signal.getSignal() == SignalResult.SELLLIMIT) { op = TRADE_OPERATION.OP_SELLLIMIT; } else { throw new Exception("Invalid Signal signal=" + signal); } //LOG.Debug("stopDistance: " + stopDistance); //LOG.Debug("price: " + price); //LOG.Debug("stoploss: " + stoploss); //LOG.Debug("takeprofit: " + takeprofit); // Check open trades on this symbol for (int i = 0; i < OrdersTotal(); i++) { OrderSelect(i, (int)SELECTION_TYPE.SELECT_BY_POS, (int)SELECTION_POOL.MODE_TRADES); if (OrderType() == (int)TRADE_OPERATION.OP_BUY && OrderSymbol().Equals(symbol) && OrderMagicNumber() == magic) { lastBuyOpen = OrderOpenTime(); openBuyOrder = true; if (closeOnOpposingSignal && signal.getSignal() < 0) { closeOutThisOrder(symbol); } } else if (OrderType() == (int)TRADE_OPERATION.OP_SELL && OrderSymbol().Equals(symbol) && OrderMagicNumber() == magic) { lastSellOpen = OrderOpenTime(); openSellOrder = true; if (closeOnOpposingSignal && signal.getSignal() > 0) { closeOutThisOrder(symbol); } } else if (OrderType() == (int)TRADE_OPERATION.OP_BUYSTOP && OrderSymbol().Equals(symbol) && OrderMagicNumber() == magic) { openBuyStopOrder = true; } else if (OrderType() == (int)TRADE_OPERATION.OP_SELLSTOP && OrderSymbol().Equals(symbol) && OrderMagicNumber() == magic) { openSellStopOrder = true; } else if (OrderType() == (int)TRADE_OPERATION.OP_BUYLIMIT && OrderSymbol().Equals(symbol) && OrderMagicNumber() == magic) { openBuyLimitOrder = true; } else if (OrderType() == (int)TRADE_OPERATION.OP_SELLLIMIT && OrderSymbol().Equals(symbol) && OrderMagicNumber() == magic) { openSellLimitOrder = true; } } // Calculate lots double entryPrice = this.getEntryPrice(symbol, signal); if (signal.getSignal() > 0) { stopDistance = entryPrice - stoploss; } else { stopDistance = stoploss - entryPrice; } lots = this.getLotSize(symbol, stopDistance); if ((signal.getSignal() == SignalResult.BUYMARKET && !openBuyOrder) || (signal.getSignal() == SignalResult.SELLMARKET && !openSellOrder) || (signal.getSignal() == SignalResult.BUYLIMIT && !openBuyLimitOrder && !openBuyOrder) || (signal.getSignal() == SignalResult.SELLLIMIT && !openSellLimitOrder && !openSellOrder) || (signal.getSignal() == SignalResult.BUYSTOP && !openBuyStopOrder && !openBuyOrder) || (signal.getSignal() == SignalResult.SELLSTOP && !openSellStopOrder && !openSellOrder)) { LOG.Info(String.Format("Executing Trade at " + DateUtil.FromUnixTime((long)MarketInfo(symbol, (int)MARKET_INFO.MODE_TIME)) + "\n\tsymbol:\t{0}" + "\n\top:\t\t{1}" + "\n\tlots:\t\t{2}" + "\n\tentryPrice:\t{3}" + "\n\tslippage:\t{4}" + "\n\tstoploss:\t{5}" + "\n\ttakeprofit:\t{6}" + "\n\tcomment:\t{7}" + "\n\tmagic:\t\t{8}" + "\n\texpiration:\t{9}" + "\n\tarrowColor:\t{0}", symbol, (int)op, lots, entryPrice, slippage, stoploss, takeprofit, comment, magic, expiration, arrowColor)); OrderSend(symbol, (int)op, lots, entryPrice, slippage, stoploss, takeprofit, comment, magic, expiration, arrowColor); } } catch (Exception e) { LOG.Error(e); throw; } }
public void SetCellValue(DateOnly value) { bool date1904 = Sheet.Workbook.IsDate1904(); SetCellValue(DateUtil.GetExcelDate(value, date1904)); }
public JsonResult UploadRulesFile(string verifyType, Guid activityId, string importRoundType) { var result = false; var msg = string.Empty; var files = Request.Files; var file = files[0]; string fileExtension = System.IO.Path.GetExtension(Request.Files[0].FileName); if (files.Count <= 0 || (file.ContentType != "application/vnd.ms-excel" && file.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { msg = "请上传Excel文件"; } else { var stream = file.InputStream; var buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); var workBook = new XSSFWorkbook(new MemoryStream(buffer)); var sheet = workBook.GetSheetAt(0); var titleRow = sheet.GetRow(sheet.FirstRowNum); var userRules = new List <BankMRActivityUser>(); try { Func <ICell, string> getStringValue = cell => { if (cell != null) { if (cell.CellType == CellType.Numeric) { return(DateUtil.IsCellDateFormatted(cell) ? cell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss.fff") : cell.NumericCellValue.ToString()); } return(cell.StringCellValue); } return(null); }; var column = GetBankRuleExcelColumn(verifyType); for (var rowIndex = sheet.FirstRowNum; rowIndex <= sheet.LastRowNum; rowIndex++)//遍历每一行 { BankMRActivityUser rule = new BankMRActivityUser() { BankCardNum = "" }; var row = sheet.GetRow(rowIndex); if (row == null) { continue; } var cellIndex = row.FirstCellNum; for (var i = 0; i < column.Count; i++)//遍历每一列 { var itemValue = getStringValue(row.GetCell(cellIndex++)); if (string.IsNullOrWhiteSpace(itemValue)) { throw new Exception("必要列不能为空"); } itemValue = itemValue.Replace("\n", "").Replace("\t", "").Replace("\r", "").Replace(" ", "").Trim(); if (rowIndex == sheet.FirstRowNum) { if (!string.Equals(itemValue, column[i].Item1)) { throw new Exception("Excel头部列名不对"); } } else { switch (column[i].Item2) { case "Moble1": long mobile = 0; if (long.TryParse(itemValue, out mobile)) { rule.Mobile = mobile; } else { throw new Exception("手机号码格式有不正确的,请检查"); } break; case "Card1": if (itemValue.Contains("*") && itemValue.Split('*')[0].Length > 0 && itemValue.Split('*')[1].Length > 0) { rule.BankCardNum = itemValue; } else { throw new Exception("银行卡不满足前N后M,中间用*号隔开"); } break; case "Card2": if (Regex.IsMatch(itemValue, "^[0-9]+$")) { rule.BankCardNum = itemValue; } else { throw new Exception("银行卡号不正确"); } break; case "Other1": rule.OtherNum = itemValue; break; case "LimitCount": rule.LimitCount = Convert.ToInt32(itemValue); break; case "DayLimit": rule.DayLimit = Convert.ToInt32(itemValue); break; default: throw new Exception("未知列"); } } } if (rowIndex != sheet.FirstRowNum) { userRules.Add(rule); } } if (userRules.Any()) { var note = GetRepeatDataRemark(userRules); var rounds = manager.GetBankMRActivityRoundConfigsByActivityId(activityId); rounds = rounds?.Where(s => s.IsActive); var roundIds = new List <int>(); switch (importRoundType) { case "AllRound": roundIds = rounds?.Select(t => t.PKID)?.ToList() ?? new List <int>(); break; case "CurrentRound": var currentDate = DateTime.Now.Date; var avaiableRoundId = rounds.FirstOrDefault(s => s.StartTime <= currentDate && s.EndTime >= currentDate)?.PKID ?? 0; if (avaiableRoundId > 0) { roundIds.Add(avaiableRoundId); } else { throw new Exception("当前没有有效场次"); } break; case "NextRound": var nowDate = DateTime.Now.Date; var notOverdueRound = rounds.Where(s => s.EndTime >= nowDate).OrderBy(s => s.StartTime); if (notOverdueRound.Count() > 1) { var nextId = notOverdueRound.Skip(1).Take(1).First().PKID; roundIds.Add(nextId); } else { throw new Exception("没有下一个场次"); } break; } if (roundIds.Any()) { var operateUser = HttpContext.User.Identity.Name; result = manager.BatchImportBankMRActivityUsers(userRules, roundIds, operateUser, importRoundType, note); } } else { msg = "规则不能为空"; } } catch (Exception ex) { msg = ex.Message; } } return(Json(new { Status = result, Msg = msg })); }
public object tokenisexist(string token, int id) { var tok = _context.LoginTokens.Where(w => w.Token == token & w.StudentID == id & w.ExpiryDate.Value.Date >= DateUtil.Now()).FirstOrDefault(); if (tok == null) { return(CreatedAtAction(nameof(login), new { result = ResultCode.DataHasNotFound, message = ResultMessage.DataHasNotFound })); } return(CreatedAtAction(nameof(loginstudent), new { result = ResultCode.Success, message = ResultMessage.Success })); }
/// <summary> /// Try get cell value. /// </summary> /// <param name="cell">The cell to retrieve value.</param> /// <param name="targetType">Type of target property.</param> /// <param name="value">The returned value for cell.</param> /// <returns><c>true</c> if get value successfully; otherwise false.</returns> public static bool TryGetCellValue(ICell cell, Type targetType, out object value) { value = null; if (cell == null) { return(true); } var success = true; switch (GetCellType(cell)) { case CellType.String: if (targetType?.IsEnum == true) // Enum type. { value = Enum.Parse(targetType, cell.StringCellValue, true); } else // String type. { value = cell.StringCellValue; } break; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(cell) || targetType == typeof(DateTime)) // DateTime type. { value = cell.DateCellValue; } else if (targetType?.IsEnum == true) // Enum type. { value = Enum.Parse(targetType, cell.NumericCellValue.ToString(CultureInfo.InvariantCulture)); } else // Number type { value = cell.NumericCellValue; } break; case CellType.Boolean: value = cell.BooleanCellValue; break; case CellType.Error: case CellType.Unknown: case CellType.Blank: // Dose nothing to keep return value null. break; default: success = false; break; } return(success); }
public void TestReturnWorkdays() { Assert.AreEqual(new DateTime(2009, APRIL, 30), DateUtil.GetJavaDate(((NumberEval)WorkdayFunction.instance.Evaluate(new ValueEval[] { new StringEval(STARTING_DATE), new NumberEval(151) }, EC)).NumberValue)); }
public JsonResult execModify(String cFunctionId, String cFunctionName, int iSortBy, String cFlag, String vFunctionUrl, String vFunctionMemo) { CodeFuncDao codeFuncDao = new CodeFuncDao(); if (codeFuncDao.chkFuncName(cFunctionId, cFunctionName) != null) { var jsonData = new { success = false, err = "功能名稱:”功能名稱”已存在,請重新輸入!" }; return(Json(jsonData, JsonRequestBehavior.AllowGet)); } FuncMgrDetailModel funcO = codeFuncDao.qryByKey(cFunctionId); CODE_FUNC func = new CODE_FUNC(); func.SYS_CD = "TREASURY"; func.FUNC_ID = cFunctionId; func.PARENT_FUNC_ID = funcO.cParentFunctionID; func.FUNC_NAME = StringUtil.toString(cFunctionName); func.FUNC_LEVEL = funcO.iFunctionLevel; func.FUNC_MEMO = StringUtil.toString(vFunctionMemo); func.FUNC_URL = vFunctionUrl; func.FUNC_ORDER = iSortBy; func.IS_DISABLED = cFlag; func.CREATE_UID = funcO.cCrtUserID; func.CREATE_DT = DateUtil.stringToDatetime(funcO.cCrtDate); func.LAST_UPDATE_UID = Session["UserID"].ToString(); func.LAST_UPDATE_DT = DateTime.Now; string strConn = DbUtil.GetDBTreasuryConnStr(); using (SqlConnection conn = new SqlConnection(strConn)) { conn.Open(); SqlTransaction transaction = conn.BeginTransaction("Transaction"); try { func = codeFuncDao.update(func, conn, transaction); Log log = new Log(); log.CFUNCTION = "功能維護作業-修改"; log.CACTION = "U"; log.CCONTENT = codeFuncDao.funcLogContent(func); LogDao.Insert(log, Session["UserID"].ToString()); transaction.Commit(); var jsonData = new { success = true, id = func.FUNC_ID.Trim() }; return(Json(jsonData, JsonRequestBehavior.AllowGet)); } catch (Exception e) { transaction.Rollback(); logger.Error("[execModify]其它錯誤:" + e.ToString()); var jsonData = new { success = false, err = "其它錯誤,請洽系統管理員!!" }; return(Json(jsonData, JsonRequestBehavior.AllowGet)); } } }
private DateTime GetDate(double date) { return(DateUtil.GetJavaDate(date)); }
private string GetCellValue(ICell cell) { string cellStr = string.Empty; switch (cell.CellType) { // 文字列型 case CellType.String: cellStr = cell.StringCellValue; break; // 数値型(日付の場合もここに入る) case CellType.Numeric: // セルが日付情報が単なる数値かを判定 if (DateUtil.IsCellDateFormatted(cell)) { // 日付型 // 本来はスタイルに合わせてフォーマットすべきだが、 // うまく表示できないケースが若干見られたので固定のフォーマットとして取得 cellStr = cell.DateCellValue.ToString("yyyy/MM/dd HH:mm:ss"); } else { // 数値型 cellStr = cell.NumericCellValue.ToString(); } break; // bool型(文字列でTrueとか入れておけばbool型として扱われた) case CellType.Boolean: cellStr = cell.BooleanCellValue.ToString(); break; // 入力なし case CellType.Blank: cellStr = cell.ToString(); break; // 数式 case CellType.Formula: // 下記で数式の文字列が取得される //cellStr = cell.CellFormula.ToString(); // 数式の元となったセルの型を取得して同様の処理を行う // コメントは省略 switch (cell.CachedFormulaResultType) { case CellType.String: cellStr = cell.StringCellValue; break; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(cell)) { cellStr = cell.DateCellValue.ToString("yyyy/MM/dd HH:mm:ss"); } else { cellStr = cell.NumericCellValue.ToString(); } break; case CellType.Boolean: cellStr = cell.BooleanCellValue.ToString(); break; case CellType.Blank: break; case CellType.Error: cellStr = cell.ErrorCellValue.ToString(); break; case CellType.Unknown: break; default: break; } break; // エラー case CellType.Error: cellStr = cell.ErrorCellValue.ToString(); break; // 型不明なセル case CellType.Unknown: break; // もっと不明なセル(あぶない刑事をなぜか思い出しました) default: break; } return(cellStr); }
private void UpdateView(List <DateTime> lst, List <CalendarVo> vos) { _dateTimes = lst; _calendarVos = vos; DateTime curDt = lst[0]; ShowTypes curShowType = curDt.Day < 8 && curDt.Day > 1 ? ShowTypes.Five : ShowTypes.Six; MonthState curState = curDt.Day < 8 && curDt.Day > 1 ? MonthState.Current : MonthState.Previous; if (curState == MonthState.Current) { SetYearAndMonth(curDt); } bool isNextFive = true; for (int i = 0; i < lst.Count; i++) { curDt = lst[i]; if (curDt.Day == 1)//每月第一天 { curState += 1; if (curState == MonthState.Current) { SetYearAndMonth(curDt); } else if (curState == MonthState.Next) { isNextFive = LoveDiaryModel.IsFiveLine(curDt); } } GameObject item = _scrollRect.content.GetChild(i).gameObject; if (curState == MonthState.Previous) { item.transform.Find("Contain").gameObject.Hide(); item.GetComponent <Button>().interactable = false; item.transform.Find("Contain/NextMonth").gameObject.Hide(); } else if (curState == MonthState.Current) { item.transform.Find("Contain").gameObject.Show(); item.GetComponent <Button>().interactable = true; item.transform.Find("Contain/NextMonth").gameObject.Hide(); } else if (curState == MonthState.Next) { if (isNextFive) { item.transform.Find("Contain").gameObject.Hide(); item.GetComponent <Button>().interactable = false; item.transform.Find("Contain/NextMonth").gameObject.Hide(); } else { item.transform.Find("Contain").gameObject.Show(); item.GetComponent <Button>().interactable = true; item.transform.Find("Contain/NextMonth").gameObject.Show(); } } //item.transform.Find("Contain").gameObject.Show(); // item.GetComponent<Button>().interactable = curState == MonthState.Current; bool isShowHasImg = vos.Find(m => { return(m.Year == curDt.Year && m.Month == curDt.Month && m.Day == curDt.Day); }) == null; item.transform.Find("Contain/HasImg").gameObject.SetActive(!isShowHasImg); bool isToday = DateUtil.CheckIsToday(curDt) == 0; item.transform.Find("Contain/TodayBg").gameObject.SetActive(isToday); string numpath = "UIAtlas_LoveDiary_Calendar_Num" + curDt.Day.ToString(); item.transform.Find("Contain/Num").GetComponent <Image>().sprite = AssetManager.Instance.GetSpriteAtlas(numpath); } }
private static void HandleDateParameter(SearchParameter parameter, IDictionary <string, object> resultDictionary, KeyValuePair <string, SearchParameter> searchParameter, DateTime dt) { if (parameter.IsEqualOrNotEqual()) { if (!parameter.HasHour) { //this shall create a between interval resultDictionary.Add(searchParameter.Key + DateSearchParamBegin, DateUtil.BeginOfDay(dt)); resultDictionary.Add(searchParameter.Key + DateSearchParamEnd, DateUtil.EndOfDay(dt)); } else { //EQ 16:46 should become BETWEEN 16:46:00 and 16:46:59.999 resultDictionary.Add(searchParameter.Key + DateSearchParamBegin, dt); resultDictionary.Add(searchParameter.Key + DateSearchParamEnd, dt.AddSeconds(59).AddMilliseconds(999)); //resultDictionary.Add(searchParameter.Key, dt); } } else if (parameter.IsGtOrGte()) { if (!parameter.HasHour) { if (parameter.SearchOperator == SearchOperator.GT) { //if GT, then we need to exclude the current day from the search dt = dt.AddDays(1); } resultDictionary.Add(searchParameter.Key + DateSearchParamBegin, DateUtil.BeginOfDay(dt)); } else { if (parameter.SearchOperator == SearchOperator.GT) { //if GT let's add one minute since screen doesn't show seconds --> so GT > 16:36 becomes actually GT > 16:36:59.999 dt = dt.AddSeconds(59).AddMilliseconds(999); } //if GTE: GTE>= 16:36 keep it as it is resultDictionary.Add(searchParameter.Key + DateSearchParamBegin, dt.FromUserToMaximo(SecurityFacade.CurrentUser())); } } else if (parameter.IsLtOrLte()) { if (!parameter.HasHour) { if (parameter.SearchOperator == SearchOperator.LT) { //if GT, then we need to exclude the current day from the search, making the beggining of yesterday instead dt = dt.AddDays(-1); } resultDictionary.Add(searchParameter.Key + DateSearchParamEnd, DateUtil.EndOfDay(dt)); } else { dt = dt.AddSeconds(59).AddMilliseconds(999); if (parameter.SearchOperator == SearchOperator.LT) { //if LT let's subtract one minute since screen doesn't show seconds --> LT < 16:36 becomes LT <16:35.59.999 dt = dt.AddMinutes(-1); } resultDictionary.Add(searchParameter.Key + DateSearchParamEnd, dt.FromUserToMaximo(SecurityFacade.CurrentUser())); } } }
/// <summary> /// Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as /// a date. /// </summary> /// <param name="value">the date value to Set this cell to. For formulas we'll Set the /// precalculated value, for numerics we'll Set its value. For other types we /// will Change the cell to a numeric cell and Set its value.</param> public void SetCellValue(DateTime value) { SetCellValue(DateUtil.GetExcelDate(value, this.book.Workbook.IsUsing1904DateWindowing)); }
/// <summary> /// Renders the versions. /// /// </summary> /// <param name="item">The item. /// </param> protected void RenderVersions(Item item) { Assert.ArgumentNotNull((object)item, "item"); IEnumerable <Item> enumerable = (IEnumerable <Item>)Enumerable.ThenBy <Item, int>(Enumerable.OrderBy <Item, string>((IEnumerable <Item>)item.Versions.GetVersions(true), (Func <Item, string>)(i => i.Language.Name)), (Func <Item, int>)(i => i.Version.Number)); StringBuilder stringBuilder1 = new StringBuilder("<table width=\"100%\" class=\"scListControl\" cellpadding=\"0\" cellspacing=\"0\">"); stringBuilder1.Append("<tr>"); stringBuilder1.Append("<td></td>"); stringBuilder1.Append("<td><b>" + Translate.Text("Language") + "</b></td>"); stringBuilder1.Append("<td><b>" + Translate.Text("Version") + "</b></td>"); stringBuilder1.Append("<td width=\"100%\" style=\"text-align:center;\"><b>" + Translate.Text("Updated Date Time") + "</b></td>"); stringBuilder1.Append("</tr>"); this.Versions.Controls.Add((System.Web.UI.Control) new LiteralControl(stringBuilder1.ToString())); foreach (Item obj in enumerable) { StringBuilder stringBuilder2 = new StringBuilder(); this.Versions.Controls.Add((System.Web.UI.Control) new LiteralControl(stringBuilder2.ToString())); Checkbox checkBoxPick = new Checkbox(); checkBoxPick.ID = "archive_" + (object)obj.Language.Name + "_" + (object)obj.Version.Number.ToString(); checkBoxPick.Attributes.Add("VersionNumber", obj.Version.Number.ToString()); checkBoxPick.Class = "scComboBoxPick"; checkBoxPick.Name = "scComboBoxPick[]"; checkBoxPick.Attributes.Add("OnClick", "javascript:scPersistSelectedValue();"); checkBoxPick.Width = new Unit(100.0, UnitType.Percentage); this.Versions.Controls.Add((System.Web.UI.Control) new LiteralControl("<tr><td style=\"text-align:center\">")); this.Versions.Controls.Add((System.Web.UI.Control)checkBoxPick); this.Versions.Controls.Add((System.Web.UI.Control) new LiteralControl("</td>")); stringBuilder2.AppendFormat("<td style=\"text-align:center\"><b>{0}</b><td style=\"text-align:center\"><b>{1}</b></td><td style=\"text-align:center\"><b>{2}</b></td>", (object)obj.Language.Name, (object)obj.Version.Number, DateUtil.FormatShortDateTime(DateUtil.IsoDateToDateTime(obj.Fields["__Updated"].Value))); this.Versions.Controls.Add((System.Web.UI.Control) new LiteralControl(stringBuilder2.ToString())); this.Versions.Controls.Add((System.Web.UI.Control) new LiteralControl("</tr>")); } this.Versions.Controls.Add((System.Web.UI.Control) new LiteralControl("</table>")); }
public override void ValidarArchivoInstanciaXBRL(DocumentoInstanciaXbrlDto instancia, IDictionary <string, string> parametros, ResultadoValidacionDocumentoXBRLDto resultadoValidacion) { LogUtil.Info("Validando reglas REPORTE ANUAL para:" + instancia.NombreArchivo); if (!ESPACIOS_NOMBRE.ContainsKey(instancia.EspacioNombresPrincipal)) { throw new Exception("Documento de instancia a validar no corresponde a ninguna taxonomía de ReporteAnual (" + instancia.EspacioNombresPrincipal + ")"); } String cvePizarra; if (!parametros.TryGetValue(PARAMETRO_CLAVE_PIZARRRA, out cvePizarra) || String.IsNullOrEmpty(cvePizarra)) { AgregarError(resultadoValidacion, null, null, String.Format(MSG_ERROR_FALTA_PARAMETRO, PARAMETRO_CLAVE_PIZARRRA), true); return; } String valorPeroiodo; if (!parametros.TryGetValue(PARAMETRO_VALOR_PERIODO, out valorPeroiodo) || String.IsNullOrEmpty(valorPeroiodo)) { AgregarError(resultadoValidacion, null, null, String.Format(MSG_ERROR_FALTA_PARAMETRO, PARAMETRO_VALOR_PERIODO), true); return; } Int32 anio; if (!Int32.TryParse(valorPeroiodo.Trim(), out anio)) { AgregarError(resultadoValidacion, null, null, String.Format("El periodo indicado ({0}) no es valido para la taxonomía de reporte anual.", valorPeroiodo), true); return; } String claveFideicomitente = null; if (parametros.TryGetValue(CVE_FIDEICOMITENTE, out claveFideicomitente) && !String.IsNullOrEmpty(claveFideicomitente)) { LogUtil.Info("{clavePizarra:[" + cvePizarra + "] ,claveFideicomientente: [" + claveFideicomitente + "]}"); cvePizarra = claveFideicomitente; } var aliasClaveCotizacion = ObtenerAliasEmpresa(cvePizarra); if (aliasClaveCotizacion != null) { LogUtil.Info("{clavePizarra:[" + cvePizarra + "], alias: [" + aliasClaveCotizacion + "]}"); cvePizarra = aliasClaveCotizacion; } LogUtil.Info("{clavePizarra:[" + cvePizarra + "]}"); var plantilla = new AbaxXBRLCore.Viewer.Application.Model.Impl.DefinicionPlantillaReporteAnualProspecto2016(); var parametrosDocumento = plantilla.DeterminaParametrosConfiguracionDocumento(instancia); String claveEmisoraXBRL; if (!parametrosDocumento.TryGetValue("emisora", out claveEmisoraXBRL) || String.IsNullOrEmpty(claveEmisoraXBRL)) { AgregarError(resultadoValidacion, null, null, "No fue posible determinar la clave de cotización de la emisora del documento.", true); return; } else { if (!claveEmisoraXBRL.Equals(cvePizarra, StringComparison.InvariantCultureIgnoreCase)) { LogUtil.Info("Error comparar {clavePizarra: [" + cvePizarra + "],claveCotizacionXBRL: [" + claveEmisoraXBRL + "]}"); AgregarError(resultadoValidacion, null, null, String.Format(M_ERROR_RV007, claveEmisoraXBRL, cvePizarra), true); } } String paramfechaReporte; DateTime fechaReporteXBRL; if (!parametrosDocumento.TryGetValue("anio", out paramfechaReporte) || String.IsNullOrEmpty(paramfechaReporte) || !DateUtil.ParseDate(paramfechaReporte, (DateUtil.YMDateFormat + "T06:00:00.000Z"), out fechaReporteXBRL)) { AgregarError(resultadoValidacion, null, null, "No fue posible determinar el periodo del documento XBRL (" + paramfechaReporte ?? "null" + ").", true); } else { if (fechaReporteXBRL.Year != anio) { LogUtil.Info("Error periodo {clavePizarra: [" + cvePizarra + "],fechaReporte: [" + paramfechaReporte + "], anio:[" + anio + "]}"); AgregarError(resultadoValidacion, null, null, String.Format(M_ERROR_RA008, anio, fechaReporteXBRL.Year), true); } } //if (!ValidarDecimalesHechosMonetarios(instancia, DECIMALES_PERMITIDOS)) //{ // AgregarError(resultadoValidacion, null, null, M_ERROR_RV011, true); //} if (!ValidarMonedasDocumento(instancia, UNIDADES_PERMITIDAS)) { AgregarError(resultadoValidacion, null, null, M_ERROR_RV010, true); } }
/** * 设置过期时间起始值 * * 参数示例:<pre>20180717174002000+0800</pre> * 此参数必填 */ public void setStartExpiredTime(DateTime startExpiredTime) { this.startExpiredTime = DateUtil.format(startExpiredTime); }
/// <summary> /// 填充数据 /// </summary> /// <param name="row"></param> /// <param name="evaluator"></param> /// <param name="dr"></param> private static void FillDataRowByRow(IRow row, IFormulaEvaluator evaluator, ref DataRow dr) { if (row != null) { for (int j = 0; j < dr.Table.Columns.Count; j++) { ICell cell = row.GetCell(j); if (cell != null) { switch (cell.CellType) { case CellType.Blank: { dr[j] = DBNull.Value; break; } case CellType.Boolean: { dr[j] = cell.BooleanCellValue; break; } case CellType.Numeric: { if (DateUtil.IsCellDateFormatted(cell)) { dr[j] = cell.DateCellValue; } else { dr[j] = cell.NumericCellValue; } break; } case CellType.String: { dr[j] = cell.StringCellValue; break; } case CellType.Error: { dr[j] = cell.ErrorCellValue; break; } case CellType.Formula: { cell = evaluator.EvaluateInCell(cell) as HSSFCell; dr[j] = cell.ToString(); break; } default: throw new NotSupportedException(string.Format("Unsupported format type:{0}", cell.CellType)); } } } } }
/** * 设置过期时间结束值 * * 参数示例:<pre>20180717174002000+0800</pre> * 此参数必填 */ public void setEndExpiredTime(DateTime endExpiredTime) { this.endExpiredTime = DateUtil.format(endExpiredTime); }
static void Main0(string[] args) { string endl = "\r\n"; // Ground station Vector R_Sta = new Geo.Algorithm.Vector(+1344.143e3, +6068.601e3, +1429.311e3); // Position vector GeoCoord Sta = CoordTransformer.XyzToGeoCoord(new XYZ(R_Sta.OneDimArray)); //new GeoCoord(R_Sta, OrbitConsts.RadiusOfEarth, OrbitConsts.FlatteningOfEarth);// Geodetic coordinates // Observations ObsType[] Obs = new ObsType[] { new ObsType(DateUtil.DateToMjd(1999, 04, 02, 00, 30, 00.0), 132.67 * OrbitConsts.RadPerDeg, 32.44 * OrbitConsts.RadPerDeg, 16945.450e3), new ObsType(DateUtil.DateToMjd(1999, 04, 02, 03, 00, 00.0), 123.08 * OrbitConsts.RadPerDeg, 50.06 * OrbitConsts.RadPerDeg, 37350.340e3) }; // Variables int i, j; double Az, El, d; Geo.Algorithm.Vector s = new Geo.Algorithm.Vector(3); Geo.Algorithm.Vector[] r = new Geo.Algorithm.Vector[2]; // Transformation to local tangent coordinates Matrix E = Sta.ToLocalNez_Matrix(); // Convert observations for (i = 0; i < 2; i++) { // Earth rotation Matrix U = Matrix.RotateZ3D(IERS.GetGmstRad(Obs[i].Mjd_UTC)); // Topocentric position vector Az = Obs[i].Azimuth; El = Obs[i].Elevation; d = Obs[i].Range; s = d * Geo.Algorithm.Vector.VecPolar(OrbitConsts.PI / 2 - Az, El); // Inertial position vector r[i] = U.Transpose() * (E.Transpose() * s + R_Sta); } // Orbital elements Geo.Algorithm.Vector Kep = Kepler.Elements(OrbitConsts.GM_Earth, Obs[0].Mjd_UTC, Obs[1].Mjd_UTC, r[0], r[1]); // Output var info = "Exercise 2-6: Initial orbit determination" + "\r\n"; info += "Inertial positions:" + "\r\n"; info += " "; info += "[km]" + " [km]" + " [km]"; Console.WriteLine(info); for (i = 0; i < 2; i++) { info = " " + DateUtil.MjdToDateTimeString(Obs[i].Mjd_UTC); for (j = 0; j < 3; j++) { info += " " + String.Format("{0, 12:F3}", r[i][j] / 1000.0); } ; Console.WriteLine(info); } Console.WriteLine(); info = "Orbital elements:" + "\r\n" + " Epoch (1st obs.) " + DateUtil.MjdToDateTimeString(Obs[0].Mjd_UTC) + endl + " Semimajor axis " + String.Format("{0, 10:F3}", Kep[0] / 1000.0) + " km" + endl + " Eccentricity " + String.Format("{0, 10:F3}", Kep[1]) + endl + " Inclination " + String.Format("{0, 10:F3}", Kep[2] * OrbitConsts.DegPerRad) + " deg" + endl + " RA ascend. node " + String.Format("{0, 10:F3}", Kep[3] * OrbitConsts.DegPerRad) + " deg" + endl + " Arg. of perigee " + String.Format("{0, 10:F3}", Kep[4] * OrbitConsts.DegPerRad) + " deg" + endl + " Mean anomaly " + String.Format("{0, 10:F3}", Kep[5] * OrbitConsts.DegPerRad) + " deg" + endl; Console.WriteLine(info); Console.ReadKey(); }
/// <summary> /// 金庫進出管理作業-申請覆核 /// </summary> /// <param name="saveData">申請覆核的資料</param> /// <param name="searchModel">查詢ViwModel</param> /// <returns></returns> public MSGReturnModel <IEnumerable <ITinItem> > TinApplyAudit(IEnumerable <ITinItem> saveData, ITinItem searchModel) { var searchData = (TreasuryMaintainSearchViewModel)searchModel; var result = new MSGReturnModel <IEnumerable <ITinItem> >(); result.RETURN_FLAG = false; DateTime dt = DateTime.Now; try { if (saveData != null) { var datas = (List <TreasuryMaintainViewModel>)saveData; if (datas.Any()) { using (TreasuryDBEntities db = new TreasuryDBEntities()) { //取得流水號 SysSeqDao sysSeqDao = new SysSeqDao(); String qPreCode = DateUtil.getCurChtDateTime().Split(' ')[0]; string _Aply_No = string.Empty; var cId = sysSeqDao.qrySeqNo("G2", qPreCode).ToString().PadLeft(3, '0'); _Aply_No = $@"G2{qPreCode}{cId}"; //申請單號 G2+系統日期YYYMMDD(民國年)+3碼流水號 string logStr = string.Empty; //log foreach (var item in datas) { var _Trea_Equip_Id = string.Empty; var _TE = new TREA_EQUIP(); #region 金庫設備設定檔 //判斷執行功能 switch (item.vExec_Action) { case "A": //新增 _Trea_Equip_Id = ""; //_Trea_Equip_Id = sysSeqDao.qrySeqNo("D2", string.Empty).ToString().PadLeft(3, '0'); //_Trea_Equip_Id = $@"D2{_Trea_Equip_Id}"; //_TE = new TREA_EQUIP() //{ // TREA_EQUIP_ID = _Trea_Equip_Id, // EQUIP_NAME = item.vEquip_Name, // CONTROL_MODE = item.vControl_Mode, // NORMAL_CNT = item.vNormal_Cnt, // RESERVE_CNT = item.vReserve_Cnt, // MEMO = item.vMemo, // IS_DISABLED = "N", // DATA_STATUS = "2",//凍結中 // CREATE_UID = searchData.vLast_Update_Uid, // CREATE_DT = dt, // LAST_UPDATE_UID = searchData.vLast_Update_Uid, // LAST_UPDATE_DT = dt, // FREEZE_UID = searchData.vLast_Update_Uid, // FREEZE_DT = dt //}; //db.TREA_EQUIP.Add(_TE); //logStr += "|"; //logStr += _TE.modelToString(); break; case "U": //修改 _TE = db.TREA_EQUIP.FirstOrDefault(x => x.TREA_EQUIP_ID == item.vTrea_Equip_Id); if (_TE.LAST_UPDATE_DT != null && _TE.LAST_UPDATE_DT > item.vLast_Update_Dt) { result.DESCRIPTION = Ref.MessageType.already_Change.GetDescription(); return(result); } _Trea_Equip_Id = item.vTrea_Equip_Id; _TE.DATA_STATUS = "2";//凍結中 _TE.LAST_UPDATE_UID = searchData.vLast_Update_Uid; _TE.LAST_UPDATE_DT = dt; _TE.FREEZE_UID = searchData.vLast_Update_Uid; _TE.FREEZE_DT = dt; logStr += "|"; logStr += _TE.modelToString(); break; case "D": //刪除 _TE = db.TREA_EQUIP.FirstOrDefault(x => x.TREA_EQUIP_ID == item.vTrea_Equip_Id); if (_TE.LAST_UPDATE_DT != null && _TE.LAST_UPDATE_DT > item.vLast_Update_Dt) { result.DESCRIPTION = Ref.MessageType.already_Change.GetDescription(); return(result); } _Trea_Equip_Id = item.vTrea_Equip_Id; _TE.DATA_STATUS = "2";//凍結中 _TE.LAST_UPDATE_UID = searchData.vLast_Update_Uid; _TE.LAST_UPDATE_DT = dt; _TE.FREEZE_UID = searchData.vLast_Update_Uid; _TE.FREEZE_DT = dt; logStr += "|"; logStr += _TE.modelToString(); break; default: break; } #endregion 金庫設備設定檔 #region 金庫設備異動檔 var _TE_Data = db.TREA_EQUIP.FirstOrDefault(x => x.TREA_EQUIP_ID == item.vTrea_Equip_Id); if (_TE_Data == null) { var _TEH = new TREA_EQUIP_HIS() { APLY_NO = _Aply_No, TREA_EQUIP_ID = _Trea_Equip_Id, EXEC_ACTION = item.vExec_Action, EQUIP_NAME = item.vEquip_Name, CONTROL_MODE = item.vControl_Mode, NORMAL_CNT = item.vNormal_Cnt, RESERVE_CNT = item.vReserve_Cnt, MEMO = item.vMemo, IS_DISABLED = item.vIs_Disabled, APPR_STATUS = "1",//表單申請 APLY_UID = searchData.vLast_Update_Uid, APLY_DATE = dt }; db.TREA_EQUIP_HIS.Add(_TEH); logStr += "|"; logStr += _TEH.modelToString(); } else { var _TEH = new TREA_EQUIP_HIS() { APLY_NO = _Aply_No, TREA_EQUIP_ID = _Trea_Equip_Id, EXEC_ACTION = item.vExec_Action, EQUIP_NAME = item.vEquip_Name, CONTROL_MODE = item.vControl_Mode, NORMAL_CNT = item.vNormal_Cnt, RESERVE_CNT = item.vReserve_Cnt, MEMO = item.vMemo, IS_DISABLED = item.vIs_Disabled, APPR_STATUS = "1",//表單申請 EQUIP_NAME_B = _TE_Data.EQUIP_NAME, CONTROL_MODE_B = _TE_Data.CONTROL_MODE, NORMAL_CNT_B = _TE_Data.NORMAL_CNT, RESERVE_CNT_B = _TE_Data.RESERVE_CNT, MEMO_B = _TE_Data.MEMO, IS_DISABLED_B = _TE_Data.IS_DISABLED, APLY_UID = searchData.vLast_Update_Uid, APLY_DATE = dt }; db.TREA_EQUIP_HIS.Add(_TEH); logStr += "|"; logStr += _TEH.modelToString(); } #endregion 金庫設備異動檔 } #region Save Db var validateMessage = db.GetValidationErrors().getValidateString(); if (validateMessage.Any()) { result.DESCRIPTION = validateMessage; } else { try { db.SaveChanges(); #region LOG //新增LOG Log log = new Log(); log.CFUNCTION = "申請覆核-新增金庫設備"; log.CACTION = "A"; log.CCONTENT = logStr; LogDao.Insert(log, searchData.vLast_Update_Uid); #endregion LOG result.RETURN_FLAG = true; result.DESCRIPTION = Ref.MessageType.Apply_Audit_Success.GetDescription(null, $@"單號為{_Aply_No}"); } catch (DbUpdateException ex) { result.DESCRIPTION = ex.exceptionMessage(); } } #endregion Save Db } } else { result.DESCRIPTION = Ref.MessageType.not_Find_Audit_Data.GetDescription(); } } else { result.DESCRIPTION = Ref.MessageType.not_Find_Audit_Data.GetDescription(); } } catch (Exception ex) { result.DESCRIPTION = ex.exceptionMessage(); } return(result); }
/// <summary> /// 将制定sheet中的数据导出到datatable中 /// </summary> /// <param name="sheet">需要导出的sheet</param> /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param> /// <returns></returns> static DataTable ImportDt(HSSFSheet sheet, int HeaderRowIndex, bool needHeader) { DataTable table = new DataTable(); HSSFRow headerRow; int cellCount; try { if (HeaderRowIndex < 0 || !needHeader) { headerRow = sheet.GetRow(0) as HSSFRow; cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i <= cellCount; i++) { DataColumn column = new DataColumn(Convert.ToString(i)); table.Columns.Add(column); } } else { headerRow = sheet.GetRow(HeaderRowIndex) as HSSFRow; cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i <= cellCount; i++) { if (headerRow.GetCell(i) == null) { if (table.Columns.IndexOf(Convert.ToString(i)) > 0) { DataColumn column = new DataColumn(Convert.ToString("重复列名" + i)); table.Columns.Add(column); } else { DataColumn column = new DataColumn(Convert.ToString(i)); table.Columns.Add(column); } } else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0) { DataColumn column = new DataColumn(Convert.ToString("重复列名" + i)); table.Columns.Add(column); } else { DataColumn column = new DataColumn(headerRow.GetCell(i).ToString()); table.Columns.Add(column); } } } int rowCount = sheet.LastRowNum; for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++) { try { HSSFRow row; if (sheet.GetRow(i) == null) { row = sheet.CreateRow(i) as HSSFRow; } else { row = sheet.GetRow(i) as HSSFRow; } DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j <= cellCount; j++) { try { if (row.GetCell(j) != null) { switch (row.GetCell(j).CellType) { case CellType.STRING: string str = row.GetCell(j).StringCellValue; if (str != null && str.Length > 0) { dataRow[j] = str.ToString(); } else { dataRow[j] = null; } break; case CellType.NUMERIC: if (DateUtil.IsCellDateFormatted(row.GetCell(j))) { dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue); } else { dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue); } break; case CellType.BOOLEAN: dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue); break; case CellType.ERROR: dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue); break; case CellType.FORMULA: switch (row.GetCell(j).CachedFormulaResultType) { case CellType.STRING: string strFORMULA = row.GetCell(j).StringCellValue; if (strFORMULA != null && strFORMULA.Length > 0) { dataRow[j] = strFORMULA.ToString(); } else { dataRow[j] = null; } break; case CellType.NUMERIC: dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue); break; case CellType.BOOLEAN: dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue); break; case CellType.ERROR: dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue); break; default: dataRow[j] = ""; break; } break; default: dataRow[j] = ""; break; } } } catch (Exception exception) { //wl.WriteLogs(exception.ToString()); } } table.Rows.Add(dataRow); } catch (Exception exception) { //wl.WriteLogs(exception.ToString()); } } } catch (Exception exception) { //wl.WriteLogs(exception.ToString()); } return(table); }
public object loginstudent(string username, string password) { var user = _context.Users.Where(w => w.UserName == username).FirstOrDefault(); if (user == null) { return(CreatedAtAction(nameof(login), new { result = ResultCode.WrongAccountorPassword, message = ResultMessage.WrongAccountorPassword })); } var dpassword = DataEncryptor.Decrypt(user.Password); if (password == dpassword) { var token = CreateToken(user); var student = _context.Students.Where(w => w.UserID == user.ID & w.Status == StatusType.Active).Select(s => new { username = s.User.UserName, id = s.UserID, studentid = s.ID, studentcode = s.StudentCode, course = s.Course, prefix = s.Prefix.toPrefixName(), firstname = s.FirstName, lastname = s.LastName, idcard = s.IDCard, profileImg = "", }).FirstOrDefault(); if (student == null) { return(CreatedAtAction(nameof(loginstudent), new { result = ResultCode.DataHasNotFound, message = ResultMessage.DataHasNotFound })); } var log = new LoginStudentHistory(); log.StudentID = student.studentid; log.UserID = student.id; log.AuthType = AuthType.Login; log.Create_On = DateUtil.Now(); log.Create_By = student.username; log.Update_On = DateUtil.Now(); log.Update_By = student.username; _context.LoginStudentHistorys.Add(log); var tokens = _context.LoginTokens.Where(w => w.StudentID == student.studentid); if (tokens.Count() > 0) { _context.LoginTokens.RemoveRange(tokens); } var tok = new LoginToken(); tok.StudentID = student.studentid; tok.UserID = student.id; tok.Token = token; tok.Create_On = DateUtil.Now(); tok.Create_By = student.username; tok.Update_On = DateUtil.Now(); tok.Update_By = student.username; tok.ExpiryDate = DateUtil.Now().AddHours(8); _context.LoginTokens.Add(tok); _context.SaveChanges(); return(CreatedAtAction(nameof(loginstudent), new { result = ResultCode.Success, message = ResultMessage.Success, token = token, user = student })); } return(CreatedAtAction(nameof(loginstudent), new { result = ResultCode.WrongAccountorPassword, message = ResultMessage.WrongAccountorPassword })); }
/** * 设置产品修改开始时间 * * 参数示例:<pre>20180717174002000+0800</pre> * 此参数必填 */ public void setStartModifyTime(DateTime startModifyTime) { this.startModifyTime = DateUtil.format(startModifyTime); }
public object login(string username, string password) { var user = _context.Users.Where(w => w.UserName == username).FirstOrDefault(); if (user == null) { return(CreatedAtAction(nameof(login), new { result = ResultCode.WrongAccountorPassword, message = ResultMessage.WrongAccountorPassword })); } var dpassword = DataEncryptor.Decrypt(user.Password); if (password == dpassword) { var token = CreateToken(user); var staff = _context.Staffs.Where(w => w.UserID == user.ID); if (staff.FirstOrDefault() == null) { return(CreatedAtAction(nameof(login), new { result = ResultCode.DataHasNotFound, message = ResultMessage.DataHasNotFound })); } if (staff.FirstOrDefault().Status == StatusType.InActive) { return(CreatedAtAction(nameof(login), new { result = ResultCode.InactiveAccount, message = ResultMessage.InactiveAccount })); } var s = staff.Select(s => new { username = s.User.UserName, id = s.UserID, staffid = s.ID, firstname = s.FirstName, lastname = s.LastName, profileImg = "", isAdmin = s.isAdmin, isMasterAdmin = s.isMasterAdmin, isQuestionAppr = s.isQuestionAppr, isMasterQuestionAppr = s.isMasterQuestionAppr, isTestAppr = s.isTestAppr, isMasterTestAppr = s.isMasterTestAppr, }).FirstOrDefault(); if (s == null) { return(CreatedAtAction(nameof(login), new { result = ResultCode.DataHasNotFound, message = ResultMessage.DataHasNotFound })); } var log = new LoginStaffHistory(); log.StaffID = s.staffid; log.UserID = s.id; log.AuthType = AuthType.Login; log.Create_On = DateUtil.Now(); log.Create_By = s.username; log.Update_On = DateUtil.Now(); log.Update_By = s.username; _context.LoginStaffHistorys.Add(log); _context.SaveChanges(); return(CreatedAtAction(nameof(login), new { result = ResultCode.Success, message = ResultMessage.Success, token = token, user = s })); } return(CreatedAtAction(nameof(login), new { result = ResultCode.WrongAccountorPassword, message = ResultMessage.WrongAccountorPassword })); }
/** * 设置产品修改结束时间 * * 参数示例:<pre>20180717174002000+0800</pre> * 此参数必填 */ public void setEndModifyTime(DateTime endModifyTime) { this.endModifyTime = DateUtil.format(endModifyTime); }
/// <summary> /// Copy cell value, formula and style, from srcCell per cell copy policy /// If srcCell is null, clears the cell value and cell style per cell copy policy /// /// This does not shift references in formulas. Use {@link XSSFRowShifter} to shift references in formulas. /// </summary> /// <param name="srcCell">The cell to take value, formula and style from</param> /// <param name="policy">The policy for copying the information, see {@link CellCopyPolicy}</param> /// <exception cref="ArgumentException">if copy cell style and srcCell is from a different workbook</exception> public void CopyCellFrom(ICell srcCell, CellCopyPolicy policy) { // Copy cell value (cell type is updated implicitly) if (policy.IsCopyCellValue) { if (srcCell != null) { CellType copyCellType = srcCell.CellType; if (copyCellType == CellType.Formula && !policy.IsCopyCellFormula) { // Copy formula result as value // FIXME: Cached value may be stale copyCellType = srcCell.CachedFormulaResultType; } switch (copyCellType) { case CellType.Boolean: SetCellValue(srcCell.BooleanCellValue); break; case CellType.Error: SetCellErrorValue(srcCell.ErrorCellValue); break; case CellType.Formula: SetCellFormula(srcCell.CellFormula); break; case CellType.Numeric: // DataFormat is not copied unless policy.isCopyCellStyle is true if (DateUtil.IsCellDateFormatted(srcCell)) { SetCellValue(srcCell.DateCellValue); } else { SetCellValue(srcCell.NumericCellValue); } break; case CellType.String: SetCellValue(srcCell.StringCellValue); break; case CellType.Blank: SetBlankInternal(); break; default: throw new ArgumentException("Invalid cell type " + srcCell.CellType); } } else { //srcCell is null SetBlankInternal(); } } // Copy CellStyle if (policy.IsCopyCellStyle) { if (srcCell != null) { CellStyle = (srcCell.CellStyle); } else { // clear cell style CellStyle = (null); } } if (policy.IsMergeHyperlink) { // if srcCell doesn't have a hyperlink and destCell has a hyperlink, don't clear destCell's hyperlink IHyperlink srcHyperlink = srcCell.Hyperlink; if (srcHyperlink != null) { Hyperlink = new XSSFHyperlink(srcHyperlink); } } else if (policy.IsCopyHyperlink) { // overwrite the hyperlink at dest cell with srcCell's hyperlink // if srcCell doesn't have a hyperlink, clear the hyperlink (if one exists) at destCell IHyperlink srcHyperlink = srcCell.Hyperlink; if (srcHyperlink == null) { Hyperlink = (null); } else { Hyperlink = new XSSFHyperlink(srcHyperlink); } } }
/** * 设置发布时间起始值 * * 参数示例:<pre>20180717174002000+0800</pre> * 此参数必填 */ public void setStartPublishTime(DateTime startPublishTime) { this.startPublishTime = DateUtil.format(startPublishTime); }
public override bool GenerarVariablesDocumentoInstancia() { bool resultado = true; var parametrosConfiguracion = this.ObtenerParametrosConfiguracion(); var numeroTrimestre = parametrosConfiguracion.ContainsKey("trimestre") ? parametrosConfiguracion["trimestre"] : null; var emisora = parametrosConfiguracion.ContainsKey("emisora") ? parametrosConfiguracion["emisora"] : null; var anio = parametrosConfiguracion.ContainsKey("anio") ? parametrosConfiguracion["anio"] : null; var moneda = parametrosConfiguracion.ContainsKey("moneda") ? parametrosConfiguracion["moneda"] : null; var mesFinTrimestre = ((numeroTrimestre.Equals("4D") ? 4 : int.Parse(numeroTrimestre)) * 3); var mesInicioTrimestre = mesFinTrimestre - 2; DateTime fechaAnio = new DateTime(); var nAnio = 0; if (XmlUtil.ParsearUnionDateTime(anio, out fechaAnio, DateTimeStyles.AdjustToUniversal)) { nAnio = fechaAnio.Year; } var inicioTrimestre = new DateTime(nAnio, mesInicioTrimestre, 1); var finTrimestre = new DateTime(nAnio, mesFinTrimestre, DateTime.DaysInMonth(nAnio, mesFinTrimestre)); var inicioAnio = new DateTime(nAnio, 1, 1); var finAnio = new DateTime(nAnio, 12, 31); this.variablesPlantilla.Add("nombreEntidad", emisora); if (parametrosConfiguracion.ContainsKey("namespaceEmisora") && parametrosConfiguracion["namespaceEmisora"] != null) { this.variablesPlantilla.Add("esquemaEntidad", parametrosConfiguracion["namespaceEmisora"]); } else { this.variablesPlantilla.Add("esquemaEntidad", "http://www.bmv.com.mx/id"); } if (moneda == null) { moneda = "MXN"; } this.variablesPlantilla.Add("medida_MXN", moneda.Replace("http://www.xbrl.org/2003/iso4217:", "")); this.variablesPlantilla.Add("medida_http___www_xbrl_org_2003_iso4217", "http://www.xbrl.org/2003/iso4217"); this.variablesPlantilla.Add("valorDefaultNumerico", "0"); this.variablesPlantilla.Add("valorDefaultNoNumerico", " "); this.variablesPlantilla.Add("medida_http___www_xbrl_org_2003_instance", "http://www.xbrl.org/2003/instance"); this.variablesPlantilla.Add("medida_shares", "shares"); this.variablesPlantilla.Add("medida_pure", "pure"); this.variablesPlantilla.Add("fecha_2014_12_31", DateUtil.ToFormatString(finAnio.AddYears(-1), DateUtil.YMDateFormat)); //fecha fin del año anterior this.variablesPlantilla.Add("fecha_2015_09_30", DateUtil.ToFormatString(finTrimestre, DateUtil.YMDateFormat)); //fecha de fin de trimestre actual this.variablesPlantilla.Add("fecha_2014_07_01", DateUtil.ToFormatString(inicioTrimestre.AddYears(-1), DateUtil.YMDateFormat)); //fecha de inicio de trimestre del año anterior this.variablesPlantilla.Add("fecha_2014_09_30", DateUtil.ToFormatString(finTrimestre.AddYears(-1), DateUtil.YMDateFormat)); //fecha de fin de trimestre del año anterior this.variablesPlantilla.Add("fecha_2015_07_01", DateUtil.ToFormatString(inicioTrimestre, DateUtil.YMDateFormat)); //fecha de inicio de trimestre año actual this.variablesPlantilla.Add("fecha_2014_01_01", DateUtil.ToFormatString(inicioAnio.AddYears(-1), DateUtil.YMDateFormat)); //fecha de inicio del año anterior this.variablesPlantilla.Add("fecha_2015_01_01", DateUtil.ToFormatString(inicioAnio, DateUtil.YMDateFormat)); //fecha de inicio del año actual this.variablesPlantilla.Add("fecha_2013_10_01", DateUtil.ToFormatString(finTrimestre.AddYears(-2).AddDays(1), DateUtil.YMDateFormat)); //fecha de fin de trimestre de dos años atrás + 1 día this.variablesPlantilla.Add("fecha_2014_10_01", DateUtil.ToFormatString(finTrimestre.AddYears(-1).AddDays(1), DateUtil.YMDateFormat)); //fecha de fin de trimestre de un año atrás + 1 día this.variablesPlantilla.Add("fecha_2013_12_31", DateUtil.ToFormatString(finAnio.AddYears(-2), DateUtil.YMDateFormat)); //fecha fin de dos años atrás this.variablesPlantilla.Add("esDictaminado", numeroTrimestre.Equals("4D") ? "true" : "false"); return(resultado); }
/** * 设置发布时间结束值 * * 参数示例:<pre>20180717174002000+0800</pre> * 此参数必填 */ public void setEndPublishTime(DateTime endPublishTime) { this.endPublishTime = DateUtil.format(endPublishTime); }
private void CheckOffset(DateTime startDate, int offset) { NumberEval result = (NumberEval)eOMonth.Evaluate(new ValueEval[] { new NumberEval(DateUtil.GetExcelDate(startDate)), new NumberEval(offset) }, ec); DateTime resultDate = DateUtil.GetJavaDate(result.NumberValue); //the month DateTime dtEnd = startDate.AddMonths(offset); //next month dtEnd = dtEnd.AddMonths(1); //first day of next month dtEnd = new DateTime(dtEnd.Year, dtEnd.Month, 1); //last day of the month dtEnd = dtEnd.AddDays(-1); Assert.AreEqual(dtEnd, resultDate); }
public void TestEDateDecrease() { EDate eDate = (EDate)EDate.Instance; DateTime startDate = DateTime.Now; int offset = -2; NumberEval result = (NumberEval)eDate.Evaluate(new ValueEval[] { new NumberEval(DateUtil.GetExcelDate(startDate)), new NumberEval(offset) }, null); DateTime resultDate = DateUtil.GetJavaDate(result.NumberValue); CompareDateTimes(resultDate, startDate.AddMonths(offset)); }