public static void BulkInsert(ArrayList al) { BaseDb bd = DB.Open(false); try { DbParam[] dps = new DbParam[] { new DbParam("@ConditionId", DbType.Int32, 0), new DbParam("@QuoteCode", DbType.String, ""), }; foreach (object oo in al) { string[] ss = oo.ToString().Split(','); dps[0].Value = ss[0]; dps[1].Value = ss[1]; try { bd.DoCommand("insert into ScanedQuote (ConditionId,QuoteCode) values (?,?)", dps); } catch (Exception e) { Tools.Log("Bulk Insert:" + ss[0] + "," + ss[1] + "," + e); } } } finally { bd.Close(); } }
public void CheckSolution() { SubmissionResult s = InternalCheckSolution(); BaseDb db = DbFactory.ConstructDatabase(); db.AddResult(s, int.Parse(subm)); db.Close(); }
private void Bind(ArrayList sids) { DataTable dt = new DataTable(); DataRow dr; Submission s; BaseDb db = DbFactory.ConstructDatabase(); Contest con = db.GetContest(_rp.ContestID); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("Время"); dt.Columns.Add("Команда"); dt.Columns.Add("Задача"); dt.Columns.Add("Язык"); dt.Columns.Add("Статус"); dt.Columns.Add("Тест №", typeof(uint)); dt.Columns.Add("Время работы"); dt.Columns.Add("Выделено памяти"); foreach (int sid in sids) { dr = dt.NewRow(); s = db.GetSubmission(sid); dr[0] = sid; dr[1] = HtmlFunctions.BeautifyTimeSpan(s.Time - con.Beginning, true); dr[2] = db.GetUser(s.UID).Fullname; dr[3] = String.Format("<a href='problem.aspx?pid={0}'>{1}</a>", s.PID, db.GetProblemShortName(s.PID)); dr[4] = s.SubmissionLanguage; string pattern = "<a href='viewdata.aspx?mode={0}&sid={1}'>{2}</a>"; if (s.Result.Code == Result.CE) { dr[5] = String.Format(pattern, "comp-report", sid, s.Result.ToHtmlString()); } else if (s.Result.Code == Result.FA) { dr[5] = String.Format(pattern, "error-report", sid, s.Result.ToHtmlString()); } else { dr[5] = s.Result.ToHtmlString(); } if (s.Result.TestNumber > 0) { dr[6] = s.Result.TestNumber; } if (s.Result.Code != Result.CE && s.Result.Code != Result.FA && s.Result.Code != Result.WAIT && s.Result.Code != Result.RU && s.Result.Code != Result.TLE) { dr[7] = Math.Round(s.Result.TimeWorked, 4) + " сек"; } if (s.Result.Code != Result.CE && s.Result.Code != Result.FA && s.Result.Code != Result.WAIT && s.Result.Code != Result.RU && s.Result.Code != Result.MLE) { dr[8] = s.Result.MemoryUsed + " КБ"; } dt.Rows.Add(dr); } db.Close(); statusGrid.DataSource = dt; statusGrid.DataBind(); }
private void loginButton_Click(object sender, EventArgs e) { bool authenticated = false; if (FormsAuthentication.Authenticate(usernameTextBox.Text, passwordTextBox.Text)) { authenticated = true; } BaseDb db = DbFactory.ConstructDatabase(); if (!authenticated) { try { authenticated = db.Authenticate(usernameTextBox.Text, passwordTextBox.Text); } catch (Exception ex) { ErrorMessage.Message = "Ошибка аутентификации: <br /<br />" + ex.Message + "<br />" + ex.Source; authenticated = false; } } if (authenticated) { string roles = db.GetRoles(usernameTextBox.Text).ToString("d"); // Create the authentication ticket and store the roles in the // custom UserData property of the authentication ticket FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, // version usernameTextBox.Text, // user name DateTime.Now, // creation persistCheckBox.Checked ? DateTime.Now.AddYears(50) : DateTime.Now.AddMinutes(300), //TODO:получать timeout из конфига Expiration persistCheckBox.Checked, // Persistent roles); // User data string encryptedTicket = FormsAuthentication.Encrypt(authTicket); HttpCookie cook = new HttpCookie(FormsAuthentication.FormsCookieName, //+"Roles", encryptedTicket); if (persistCheckBox.Checked) { cook.Expires = authTicket.Expiration; } Response.Cookies.Add(cook); Response.Redirect(FormsAuthentication.GetRedirectUrl( usernameTextBox.Text, persistCheckBox.Checked)); //FormsAuthentication.RedirectFromLoginPage(usernameTextBox.Text, persistCheckBox.Checked); } else { ErrorMessage.Message = "<b>Логин или пароль неверен</b>, пожалуйста, введите снова.<br/> Возможно, Вы не зарегистрированы - <a href=\"edituser.aspx\">сделайте это</a>"; } db.Close(); }
private void oldpassValidator_ServerValidate(object source, ServerValidateEventArgs args) { if (oldpassTextBox.Text != "") { BaseDb db = DbFactory.ConstructDatabase(); args.IsValid = db.Authenticate(Page.User.Identity.Name, oldpassTextBox.Text); db.Close(); } }
public override IDataProvider GetData(string Code, int Count) { try { CommonDataProvider cdp = new CommonDataProvider(this); DbParam[] dps = new DbParam[] { new DbParam("@Q1", DbType.DateTime, StartTime), new DbParam("@Q2", DbType.DateTime, EndTime), }; BaseDb bd = DB.Open(false); try { DataTable dt = bd.GetDataTable("select Tick,tstamp from " + Code + "_tick where tstamp>=? and tstamp<=? order by tstamp", dps); dps[1].Value = ((DateTime)dps[0].Value).AddSeconds(-1); dps[0].Value = ((DateTime)dps[0].Value).AddDays(-30); DataRow drr = bd.GetFirstRow("select Tick from " + Code + "_tick where tstamp>=? and tstamp<=? order by tstamp desc", dps); if (dt.Rows.Count > 0) { cdp.SetStringData("LastTradeTime", ((DateTime)dt.Rows[dt.Rows.Count - 1]["tstamp"]).ToString()); } if (drr != null) { cdp.SetStringData("LastPrice", drr[0].ToString()); } if (dt.Rows.Count == 0) { dt.Rows.Add(new object[] { Single.NaN, StartTime }); } double[] CLOSE = new double[dt.Rows.Count]; double[] VOLUME = new double[dt.Rows.Count]; double[] DATE = new double[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { CLOSE[i] = ToDouble(dt.Rows[i]["Tick"]); VOLUME[i] = 0; DATE[i] = ((DateTime)dt.Rows[i]["tstamp"]).ToOADate(); } cdp.LoadBinary("CLOSE", CLOSE); cdp.LoadBinary("DATE", DATE); cdp.LoadBinary("VOLUME", VOLUME); } finally { bd.Close(); } return(cdp); } catch { } return(base.GetData(Code, Count)); }
private void Page_Load(object sender, EventArgs e) { ArrayList tids = new ArrayList(); BaseDb db = DbFactory.ConstructDatabase(); if (now) { int[] nowtids = db.GetNowTids(); foreach (int tid in nowtids) { tids.Add(tid); } } if (old) { int[] oldtids = db.GetOldTids(); foreach (int tid in oldtids) { tids.Add(tid); } } if (future) { int[] futuretids = db.GetFutureTids(); foreach (int tid in futuretids) { tids.Add(tid); } } Contest t; string str = ""; foreach (int tid in tids) { if (!IsPostBack) { t = db.GetContest(tid); selContests.Items.Add(new ListItem(t.Name, tid.ToString())); } foreach (Problem p in db.GetProblems(tid)) { str += "new Problem(\"Задача " + p.ShortName + ". " + p.Name + "\"," + p.PID + "," + tid + "),"; } } db.Close(); Page.RegisterArrayDeclaration("arr", (str.Length != 0) ? str.Substring(0, str.Length - 1) : str); Page.RegisterArrayDeclaration("hi", ctrlsl2hide); if (!Page.IsStartupScriptRegistered("Startup")) { Page.RegisterStartupScript("Startup", "<script>Init()</script>"); } }
private void Page_Load(object sender, EventArgs e) { if (!BaseDb.IsAdmin(Page.User)) { throw new NeJudgeSecurityException("Administrator"); } if (!IsPostBack) { try { pid = int.Parse(Request.QueryString["pid"]); } catch { pid = -1; } try { tid = int.Parse(Request.QueryString["tid"]); } catch { tid = -1; } BaseDb db = DbFactory.ConstructDatabase(); if (db.CheckPid(pid)) { tid = db.GetTid(pid); Problem p = db.GetProblem(pid); problemNameTextBox.Text = Server.HtmlDecode(p.Name); problemTextTextBox.Text = Server.HtmlDecode(p.Text); inputFormatTextBox.Text = Server.HtmlDecode(p.InputFormat); outputFormatTextBox.Text = Server.HtmlDecode(p.OutputFormat); inputSampleTextbox.Text = Server.HtmlDecode(p.InputSample); outputSampleTextbox.Text = Server.HtmlDecode(p.OutputSample); authorTextBox.Text = Server.HtmlDecode(p.Author); } else if (db.CheckTid(tid)) { pid = -1; finishButton.Text = "Добавить задачу"; if (db.GetContest(tid).Old) { throw new NeJudgeInvalidParametersException("tid"); } } else { throw new NeJudgeInvalidParametersException("tid"); } db.Close(); } }
private void btnGet_Click(object sender, System.EventArgs e) { string[] ss = DownloadData("http://eoddata.com/SymbolList.asp?e=" + Exchange); DbParam[] dps = new DbParam[] { new DbParam("@QuoteCode", DbType.String, ""), new DbParam("@QuoteName", DbType.String, ""), new DbParam("@Exchange", DbType.String, Exchange), }; int succ = 0; int failed = 0; BaseDb bd = DB.Open(false); try { for (int i = 1; i < ss.Length; i++) { string[] rr = ss[i].Split('\t'); if (rr.Length != 2) { continue; } if (Exchange == "INDEX") { dps[0].Value = "^" + rr[0].Trim(); } else { dps[0].Value = rr[0].Trim(); } dps[1].Value = rr[1].Trim(); try { if (bd.GetFirstRow("select QuoteCode from StockData where QuoteCode=?", new DbParam[] { dps[0] }) == null) { bd.DoCommand("insert into stockdata (QuoteCode,QuoteName,Exchange) values (?,?,?)", dps); succ++; } } catch { failed++; } } } finally { bd.Close(); } lExchangeMsg.Text = "succ: " + succ + "; failed " + failed; }
private void loginTextBoxValidator_ServerValidate(object source, ServerValidateEventArgs args) { BaseDb db = DbFactory.ConstructDatabase(); if (db.IsRegistered(loginTextBox.Text.Trim())) { loginTextBoxValidator.ErrorMessage = "<FONT COLOR='Red'><b>Этот логин зарезервирован. Попробуйте ввести другой.</b></FONT>"; args.IsValid = false; } else if (loginTextBox.Text.Trim() == "") { args.IsValid = false; } db.Close(); }
public static void DeleteWrongData(object sender) { BaseDb bd = DB.Open(true); try { bd.DoCommand("delete from StockData where QuoteCode in (select QuoteCode from ScanedQuote where ConditionId=-1)"); bd.DoCommand("delete from Realtime where QuoteCode in (select QuoteCode from ScanedQuote where ConditionId=-1)"); bd.DoCommand("delete from ScanedQuote where ConditionId=-1"); } finally { bd.Close(); } }
private void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { RequirementsProcessor rp = new RequirementsProcessor(GetType(), Context); rp.ProcessRequirements(); selprob.AddHidableControl(goButton); if (rp.PidDefined) { selprob.PID = rp.ProblemID; BaseDb db = DbFactory.ConstructDatabase(); Problem p = db.GetProblem(rp.ProblemID); Contest t = db.GetContest(p.TID); db.Close(); if (!BaseDb.IsAdmin(Page.User) && t.Future) { throw new NeJudgeInvalidParametersException("pid"); //"Соревнование, задачу с которого вы хотите просмотреть, ещё не началось. Попробуйте позже." } #region Возня со ссылками InitLinks(rp.ProblemID); if (BaseDb.IsAdmin(Page.User)) { Hyperlink2.Text = "Редактировать"; Hyperlink2.NavigateUrl = "../editproblem.aspx?pid=" + rp.ProblemID + "&ret=p"; Hyperlink3.Visible = Hyperlink4.Visible = false; } else { if (BaseDb.IsAnonymous(Page.User) || t.Old) { Hyperlink2.Visible = Hyperlink3.Visible = Hyperlink4.Visible = false; } } #endregion FillLiterals(p); } else { Hide(); } } }
private int InsertProblem(Problem p) { BaseDb db = DbFactory.ConstructDatabase(); int ret = -1; try { ret = db.AddProblem(p); } catch (SystemException ex) { outerror.InnerHtml = "<b>An exception of type " + ex.GetType() + " was encountered while attempting to roll back the transaction. Message:</b> <br/><br/> <i>" + ex.Message + "</i>"; } db.Close(); return(ret); }
public override void SaveSymbolList(string[] ss, out int succ, out int failed) { DbParam[] dps = new DbParam[] { new DbParam("@QuoteCode", DbType.String, ""), new DbParam("@QuoteName", DbType.String, ""), new DbParam("@Exchange", DbType.String, ""), }; succ = 0; failed = 0; // false to support mysql BaseDb bd = DB.Open(false); try { for (int i = 0; i < ss.Length; i++) { string[] rr = ss[i].Trim().Split(';'); if (rr.Length != 3) { continue; } dps[0].Value = rr[0].Trim(); dps[1].Value = rr[1].Trim(); dps[2].Value = rr[2].Trim(); try { if (bd.GetFirstRow("select QuoteCode from StockData where QuoteCode=?", new DbParam[] { dps[0] }) == null) { bd.DoCommand("insert into StockData (QuoteCode,QuoteName,Exchange) values (?,?,?)", dps); succ++; } } catch { failed++; } } } finally { bd.Close(); }; }
private void finishButton_Click(object sender, EventArgs e) { if (pid == -1) { Problem p = new Problem(Server.HtmlEncode(problemNameTextBox.Text), Server.HtmlEncode(problemTextTextBox.Text), Server.HtmlEncode(inputFormatTextBox.Text), Server.HtmlEncode(outputFormatTextBox.Text), Server.HtmlEncode(inputSampleTextbox.Text), Server.HtmlEncode(outputSampleTextbox.Text), null, Server.HtmlEncode(authorTextBox.Text), -1, tid); //TODO:SharpDfTest.DfTest.CreateProblem pid = InsertProblem(p); } else { Problem p = new Problem(Server.HtmlEncode(problemNameTextBox.Text), Server.HtmlEncode(problemTextTextBox.Text), Server.HtmlEncode(inputFormatTextBox.Text), Server.HtmlEncode(outputFormatTextBox.Text), Server.HtmlEncode(inputSampleTextbox.Text), Server.HtmlEncode(outputSampleTextbox.Text), null, Server.HtmlEncode(authorTextBox.Text), pid, tid); BaseDb db = DbFactory.ConstructDatabase(); //TODO:SharpDfTest.DfTest.CreateProblem db.UpdateProblem(p); db.Close(); } string ret; if (Request.QueryString["ret"] != null) { ret = "~/problem.aspx?pid=" + pid; } else { ret = "~/editcontest.aspx?tid=" + tid; } Response.Redirect(ret); }
private void finishButton_Click(object sender, EventArgs e) { if (Page.IsValid) { BaseDb db = DbFactory.ConstructDatabase(); User u = new User(loginTextBox.Text.Trim(), passTextBox.Text, nameTextBox.Text.Trim(), mailTextBox.Text.Trim()); if (uid == -1) { db.AddUser(u); Response.Redirect("~/default.aspx", false); } else { if (oldpassTextBox.Text == "") { u.Password = db.GetUser(uid).Password; } db.UpdateUser(u, uid); errLiteral.Text = "Данные сохранены"; errLiteral.Visible = true; } db.Close(); } }
private void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { uid = int.Parse(Request.QueryString["uid"]); } catch { uid = -1; } BaseDb db = DbFactory.ConstructDatabase(); if (db.CheckUid(uid)) //редактирование { if (!Page.User.Identity.IsAuthenticated || BaseDb.IsAnonymous(Page.User) || db.GetUid(Page.User.Identity.Name) != uid) { throw new NeJudgeException("Identity"); } else { Table1.Rows[2].Visible = false; loginTextBoxValidator.Enabled = false; User u = db.GetUser(uid); nameTextBox.Text = u.Fullname; mailTextBox.Text = u.Email; } } else //регистрация { Table1.Rows[3].Visible = false; oldpassTextBoxValidator.Enabled = false; } db.Close(); } }
private void Page_Init(object sender, EventArgs e) { if (!IsPostBack) { BaseDb db = DbFactory.ConstructDatabase(); Contest t; if (now) { int[] nowtids = db.GetNowTids(); for (int i = 0; i < nowtids.Length; i++) { t = db.GetContest(nowtids[i]); tidDropDownList.Items.Add(new ListItem(t.Name, nowtids[i].ToString())); } } if (old) { int[] oldtids = db.GetOldTids(); for (int i = 0; i < oldtids.Length; i++) { t = db.GetContest(oldtids[i]); tidDropDownList.Items.Add(new ListItem(t.Name, oldtids[i].ToString())); } } if (future) { int[] futuretids = db.GetFutureTids(); for (int i = 0; i < futuretids.Length; i++) { t = db.GetContest(futuretids[i]); tidDropDownList.Items.Add(new ListItem(t.Name, futuretids[i].ToString())); } } db.Close(); } }
private void Page_Unload(object sender, EventArgs e) { db.Close(); }
private void Page_Load(object sender, EventArgs e) { anon_div.Visible = false; //common_div.Visible = false; account_div.Visible = false; admin_div.Visible = false; ArrayList cons = new ArrayList(); cons.Add(new Link("Главная страница", "~/default.aspx")); cons.Add(new Link("Список соревнований", "~/contests.aspx")); cons.Add(new Link("Монитор", "~/monitor.aspx")); common_repeater.DataSource = cons; ArrayList acc = new ArrayList(); if (!Page.User.Identity.IsAuthenticated) { ArrayList anon = new ArrayList(); anon.Add(new Link("Войти в систему", "~/login.aspx")); anon.Add(new Link("Регистрация", "~/edituser.aspx")); anon_repeater.DataSource = anon; anon_div.Visible = true; } else if (!BaseDb.IsAnonymous(Page.User)) { BaseDb db = DbFactory.ConstructDatabase(); acc.Add(new Link("Личные данные", "~/edituser.aspx?uid=" + db.GetUid(Page.User.Identity.Name))); db.Close(); if (BaseDb.IsAdmin(Page.User)) { ArrayList adm = new ArrayList(); adm.Add(new Link("Управление соревнованиями", "~/editcontest.aspx")); adm.Add(new Link("Управление задачами", "~/editproblem.aspx")); adm.Add(new Link("Просмотр всех решений", "~/status.aspx")); adm.Add(new Link("Просмотр вопросов", "~/questions.aspx")); admin_repeater.DataSource = adm; admin_div.Visible = true; } else { cons.Add(new Link("Послать на проверку", "~/submit.aspx")); cons.Add(new Link("Задать вопрос", "~/ask.aspx")); acc.Add(new Link("Посланные решения", "~/status.aspx")); acc.Add(new Link("Заданные вопросы", "~/questions.aspx")); } account_repeater.DataSource = acc; account_div.Visible = true; } DataBind(); /*if(!basedb.IsAnonymous(Page.User)) * { * basedb db = dbfactory.ConstructDatabase(); * acc.Add(new Link("Личные данные","~/edituser.aspx?uid="+db.GetUid(Page.User.Identity.Name))); * db.Close(); * } * if ( basedb.IsAdmin(Page.User) ) * { * ArrayList adm = new ArrayList(); * adm.Add(new Link("Управление соревнованиями","~/editcontest.aspx")); * adm.Add(new Link("Управление задачами","~/editproblem.aspx")); * adm.Add(new Link("Просмотр всех решений","~/status.aspx")); * adm.Add(new Link("Просмотр вопросов","~/questions.aspx")); * admin_repeater.DataSource = adm; * admin_div.Visible = true; * } * else if ( !basedb.IsAnonymous(Page.User) ) * { * cons.Add(new Link("Послать на проверку","~/submit.aspx")); * cons.Add(new Link("Задать вопрос","~/ask.aspx")); * acc.Add(new Link("Посланные решения","~/status.aspx")); * acc.Add(new Link("Заданные вопросы","~/questions.aspx")); * } * common_repeater.DataSource = cons; * common_div.Visible = true; * account_repeater.DataSource = acc; * account_div.Visible = true; * } * if ( !Page.User.Identity.IsAuthenticated ) * { * ArrayList anon = new ArrayList(); * anon.Add(new Link("Войти в систему","~/login.aspx")); * anon.Add(new Link("Регистрация","~/edituser.aspx")); * anon_repeater.DataSource = anon; * anon_div.Visible = true; * }*/ }
private void btnScan_Click(object sender, System.EventArgs e) { CurrentFullName = ddlFormula.SelectedItem.Value; Exchange = ddlExchange.SelectedItem.Value; string Param = ""; foreach (string s in Request.Form) { if (s.StartsWith("__Param")) { if (Param != "") { Param += ","; } Param += double.Parse(Request.Form[s]); } } Condition = CurrentFullName; if (Param != "") { Condition = CurrentFullName + "(" + Param + ")"; } DbParam[] dps = new DbParam[] { new DbParam("@Condition", DbType.String, Condition), new DbParam("@Exchange", DbType.String, Exchange), new DbParam("@StartTime", DbType.DateTime, DateTime.Now.AddHours(- Tools.ToIntDef(ConfigurationManager.AppSettings["ScanCacheTime"], 0))) }; bool b = true; BaseDb bd = DB.Open(true); try { DataRow dr = bd.GetFirstRow("select * from condition where Condition=? and Exchange=? and StartTime>?", dps); if (dr != null && !Config.KeepLatestScanResultOnly) { ConditionId = dr["ConditionId"].ToString(); b = false; } else { dps[2] = null; if (Config.KeepLatestScanResultOnly) { DataTable dt = bd.GetDataTable("select ConditionId from condition where Condition=? and Exchange=?", dps); foreach (DataRow drDel in dt.Rows) { bd.DoCommand("delete from ScanedQuote where ConditionId = " + drDel["ConditionId"]); } bd.DoCommand("delete from condition where Condition=? and Exchange=?", dps); } bd.DoCommand("insert into condition (Condition,Exchange,Scaned) values (?,?,0)", dps); ConditionId = bd.GetFirstRow("select max(ConditionId) from condition")[0].ToString(); } } finally { bd.Close(); } if (b) { ThreadPool.QueueUserWorkItem(new WaitCallback(Scanning), new ScanId(ConditionId, Condition, Exchange)); Response.Redirect("Progress.aspx?ConditionId=" + ConditionId); } else { Response.Redirect("StockList.aspx?ConditionId=" + ConditionId); } }
static public void PreScan(object Sender) { Tools.Log("Prescan starting"); if (StartTime > DateTime.MinValue) { return; } StartTime = DateTime.Now; try { string[] PreExchange = Config.PreScanExchange.Split(';'); for (int i = 0; i < PreExchange.Length; i++) { PreExchange[i] = Utils.GetPart1(PreExchange[i]); } string[] PreScan = Config.PreScan.Split(';'); Hashtable htConditionIdMap = new Hashtable(); DbParam[] dpPreScan = new DbParam[] { new DbParam("@Condition", DbType.String, ""), new DbParam("@Exchange", DbType.String, ""), new DbParam("@StartTime", DbType.DateTime, DateTime.Now), new DbParam("@ScanType", DbType.Int32, 1), }; // Insert pre-defined scan to condition // Get condition id . BaseDb bd = DB.Open(false); try { string s = bd.GetCommaValues("select ConditionId from Condition " + GetWhere("EndTime"), ""); if (s != "") { bd.DoCommand("delete from ScanedQuote where ConditionId in (" + s + ")"); bd.DoCommand("delete from Condition " + GetWhere("EndTime")); } Tools.Log("PreScan=" + PreScan.Length + ";PreExchange=" + PreExchange.Length); for (int i = 0; i < PreScan.Length; i++) { for (int j = 0; j < PreExchange.Length; j++) { dpPreScan[0].Value = Utils.GetName(PreScan[i]); dpPreScan[1].Value = PreExchange[j]; dpPreScan[3].Value = Utils.GetParam(PreScan[i], "1"); bd.DoCommand("insert into Condition (Condition,Exchange,StartTime,Scaned,ScanType) values (?,?,?,0,?)", dpPreScan); } } DataTable dtPreScan = bd.GetDataTable("select ConditionId,Condition,Exchange from Condition " + GetWhere("StartTime"), null, PreScan.Length * PreExchange.Length); foreach (DataRow dr in dtPreScan.Rows) { htConditionIdMap[dr["Condition"].ToString().Trim() + dr["Exchange"].ToString().Trim()] = dr["ConditionId"].ToString(); } } finally { bd.Close(); } Tools.Log("Get scan formulas"); // Get scan formulas FormulaBase[] fbs = new FormulaBase[PreScan.Length]; int[] Ns = new int[PreScan.Length]; int N = 0; for (int i = 0; i < fbs.Length; i++) { fbs[i] = FormulaBase.GetFormulaByName("Scan." + Utils.GetValue(PreScan[i])); Tools.Log(fbs[i].FullName); if (fbs[i] != null) { Ns[i] = fbs[i].DataCountAtLeast(); N = Math.Max(N, Ns[i]); } } if (Config.PrescanLoadToMemory) { N = Config.MaxDataForPull; } Tools.Log("Pre-Scan- N = " + N); DataManagerBase dmb = Utils.GetDataManager(Config.DefaultDataManager); DataTable dt = dmb.GetStockList(); if (dt == null) { return; } Tools.Log(dt.Rows.Count.ToString()); // Scan int Progress = 0; Hashtable htTotal = new Hashtable(); Hashtable htResultCount = new Hashtable(); ArrayList al = new ArrayList(); try { foreach (DataRow dr in dt.Rows) { try { string Symbol = dr[0].ToString(); IDataProvider idp = GetDataProvider(dmb, Symbol, N); if (!Utils.VerifyVolumeAndDate(idp)) { continue; } string NowExchange = dr["Exchange"].ToString(); foreach (string s in PreExchange) { if (s.Length <= NowExchange.Length) { if (string.Compare(s, NowExchange.Substring(0, s.Length), true) == 0) { NowExchange = s; break; } } } for (int j = 0; j < fbs.Length; j++) { try { if (fbs[j] != null) { idp.MaxCount = Ns[j]; FormulaPackage fp = fbs[j].Run(idp); string ConditionId = (string)htConditionIdMap[Utils.GetName(PreScan[j]) + NowExchange]; if (ConditionId != null) { FormulaData fd = fp[fp.Count - 1]; if (fd.Length > 0) { if (fd.LASTDATA > 0) { al.Add(ConditionId + "," + Symbol); htResultCount[ConditionId] = Utils.ObjPlusDef(htResultCount[ConditionId], 1); } } htTotal[ConditionId] = Utils.ObjPlusDef(htTotal[ConditionId], 1); } Progress++; if ((Progress % 10) == 0) { HttpRuntime.Cache["PreScan"] = Progress; } } } catch (Exception e) { Tools.Log(Symbol + "/" + fbs[j] + "/" + e); } } Thread.Sleep(1); } catch (Exception e) { Tools.Log("Pre-scan symbol loop:" + e.Message); } } } finally { Utils.BulkInsert(al); } // Update pre-scan conditions dpPreScan = new DbParam[] { new DbParam("@Scaned", DbType.Int32, 0), new DbParam("@Total", DbType.Int32, 0), new DbParam("@ResultCount", DbType.Int32, 0), new DbParam("@EndTime", DbType.DateTime, DateTime.Now), }; bd = DB.Open(false); try { for (int i = 0; i < PreScan.Length; i++) { for (int j = 0; j < PreExchange.Length; j++) { string ConditionId = (string)htConditionIdMap[Utils.GetName(PreScan[i]) + PreExchange[j]]; dpPreScan[0].Value = Utils.ObjDef(htTotal[ConditionId], 0); dpPreScan[1].Value = Utils.ObjDef(htTotal[ConditionId], 0); dpPreScan[2].Value = Utils.ObjDef(htResultCount[ConditionId], 0); bd.DoCommand("update Condition set Scaned=?,Total=?,ResultCount=?,EndTime=? where ConditionId=" + ConditionId, dpPreScan); } } } finally { bd.Close(); } } catch (Exception e) { Tools.Log("Update pre-scan service:" + e.Message); } finally { StartTime = DateTime.MinValue; } }
public override IDataProvider GetData(string Code, int Count) { try { CommonDataProvider cdp = new CommonDataProvider(this); DbParam[] dps = new DbParam[] { new DbParam("@Symbol", DbType.String, Code), new DbParam("@Q1", DbType.DateTime, StartTime), new DbParam("@Q2", DbType.DateTime, EndTime), }; BaseDb bd = DB.Open(false); try { DataTable dt = bd.GetDataTable("select Price,Volume,QuoteTime from Intraday where Symbol=? and QuoteTime>=? and QuoteTime<=? order by QuoteTime", dps); double LastV = -1; foreach (DataRow dr in dt.Rows) { double NowV = (double)dr["Volume"]; if (LastV >= 0) { if (NowV > LastV) { dr["Volume"] = NowV - LastV; } else { dr["Volume"] = (double)0; } } LastV = NowV; } dps[2].Value = ((DateTime)dps[1].Value).AddSeconds(-1); dps[1].Value = ((DateTime)dps[1].Value).AddDays(-30); DataRow drr = bd.GetFirstRow("select Price from Intraday where Symbol=? and QuoteTime>=? and QuoteTime<=? order by QuoteTime desc", dps); if (dt.Rows.Count > 0) { cdp.SetStringData("LastTradeTime", ((DateTime)dt.Rows[dt.Rows.Count - 1]["QuoteTime"]).ToString()); } if (drr != null) { cdp.SetStringData("LastPrice", drr[0].ToString()); } SetStrings(cdp, Code); if (dt.Rows.Count == 0) { dt.Rows.Add(new object[] { double.NaN, 0, StartTime }); } double[] CLOSE = new double[dt.Rows.Count]; double[] VOLUME = new double[dt.Rows.Count]; double[] DATE = new double[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { CLOSE[i] = ToDouble(dt.Rows[i]["Price"]); VOLUME[i] = ToDouble(dt.Rows[i]["Volume"]); DATE[i] = ((DateTime)dt.Rows[i]["QuoteTime"]).ToOADate(); } cdp.LoadBinary("CLOSE", CLOSE); cdp.LoadBinary("DATE", DATE); cdp.LoadBinary("VOLUME", VOLUME); } finally { bd.Close(); } return(cdp); } catch { } return(base.GetData(Code, Count)); }
private void Page_Load(object sender, EventArgs e) { BaseDb db = DbFactory.ConstructDatabase(); if (db.CheckPid(pid)) { Problem p = db.GetProblem(pid); if (db.GetContest(p.TID).Future) { Hide("Соревнование, задачу с которого вы хотите просмотреть, ещё не началось. Попробуйте позже."); } else { nameLiteral.Text = "<h1> Задача " + p.ShortName + " ( #"+ pid + " ). "+ p.Name + "</h1>"; Limits l = DfTest.GetLimits(pid.ToString()); tlLiteral.Text += l.Time + " секунды"; mlLiteral.Text += l.Memory + " КБ"; olLiteral.Text += l.Output + " байт"; if (p.Text == "") { textLiteral.Visible = false; } else { textLiteral.Text += p.Text; } if (p.InputFormat == "") { infoLiteral.Visible = false; } else { infoLiteral.Text += p.InputFormat; } if (p.OutputFormat == "") { outfoLiteral.Visible = false; } else { outfoLiteral.Text += p.OutputFormat; } string str = ""; if (p.InputSample == "") { inexLiteral.Visible = false; } else { StringReader str_rdr = new StringReader(p.InputSample); while ((str = str_rdr.ReadLine()) != null) { inexLiteral.Text += str + "<br>"; } inexLiteral.Text += "</code>"; } if (p.OutputSample == "") { outexLiteral.Visible = false; } else { StringReader str_rdr2 = new StringReader(p.OutputSample); while ((str = str_rdr2.ReadLine()) != null) { outexLiteral.Text += str + "<br>"; } outexLiteral.Text += "</code>"; } if (p.Author == "") { authorLiteral.Visible = false; } else { authorLiteral.Text += p.Author; authorLiteral.Text += "<hr>"; } } } else { throw new NeJudgeInvalidParametersException("pid"); } db.Close(); }
private void close_db() { _db.Close(); }
private void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { RequirementsProcessor rp = new RequirementsProcessor(GetType(), Context); rp.ProcessRequirements(); //Page.Response.AddHeader("Refresh","300"); if (rp.TidDefined) { Contest con; BaseDb db = DbFactory.ConstructDatabase(); using ( db ) { con = db.GetContest(rp.ContestID); if (con.Future) { Hide("Нельзя просмотреть монитор будущего соревнования"); db.Close(); } else { DateTime cur_time = TimeUtils.ZeroDateTime(DateTime.Now); DateTime t_begin = TimeUtils.ZeroDateTime(con.Beginning); DateTime t_end = TimeUtils.ZeroDateTime(con.Ending); // Последнее обновление TimeSpan dur = TimeUtils.ZeroTimeSpan(t_end - t_begin); TimeSpan elapsed = TimeUtils.ZeroTimeSpan((cur_time - t_begin < dur) ? cur_time - t_begin : dur); TimeSpan estimated = TimeUtils.ZeroTimeSpan(dur - elapsed); if (elapsed >= dur) { st_label.InnerHtml += "<span style='color:red;font-size:small;display:block;'>(Соревнование окончено)</span>"; } refresh.Text = HtmlFunctions.BeautifyTimeSpan(elapsed, false); // Продолжительность соревнования period.Text = HtmlFunctions.BeautifyTimeSpan(dur, false); left.Text = HtmlFunctions.BeautifyTimeSpan(estimated, false); } } /*DataTable mon_dt = new DataTable("Результаты"), stat_dt = new DataTable("Статистика"); * mon_dt.Columns.Add("ID"); * mon_dt.Columns.Add("Имя участника"); * //mon_dt.PrimaryKey = new DataColumn[]{mon_dt.Columns[0]}; * * stat_dt.Columns.Add("Показатель"); * DataRow dr = stat_dt.NewRow(); * dr[0] = "Команд решили"; * stat_dt.Rows.Add(dr); * dr = stat_dt.NewRow(); * dr[0] = "Команд решили/команд всего"; * stat_dt.Rows.Add(dr); * * int tid = rp.ContestID; * selcon.TID = tid; * BaseDb db = DbFactory.ConstructDatabase(); * //HyperLink1.NavigateUrl += tid; * //Прочитали результаты * Contest t; * * if ((t = db.GetContest(tid)).Future) * { * Hide("Нельзя просмотреть монитор будущего сорвевнования"); * db.Close(); * } * else * { * DateTime cur_time = ZeroDateTime(DateTime.Now); * DateTime t_begin = ZeroDateTime(t.Beginning); * DateTime t_end = ZeroDateTime(t.Ending); * * // Последнее обновление * TimeSpan dur = ZeroTimeSpan(t_end - t_begin); * TimeSpan elapsed = ZeroTimeSpan( (cur_time - t_begin < dur) ? cur_time - t_begin : dur); * TimeSpan estimated = ZeroTimeSpan(dur - elapsed); * if ( elapsed >= dur ) * { * st_label.InnerHtml += * "<span style='color:red;font-size:small;display:block;'>(Соревнование окончено)</span>"; * } * refresh.Text = HtmlFunctions.BeautifyTimeSpan(elapsed, false); * // Продолжительность соревнования * period.Text = HtmlFunctions.BeautifyTimeSpan(dur, false); * left.Text = HtmlFunctions.BeautifyTimeSpan(estimated, false); * * ArrayList ps = db.GetProblems(tid); * if (ps.Count == 0) * { * Hide("В этом соревновании нет задач"); * return; * } * int i = 0; * for (i = 0; i < ps.Count; i++) * { * mon_dt.Columns.Add(((Problem) ps[i]).ShortName); * //mon_dt.Columns.Add(string.Format("<a style='grid_first' href='problem.aspx?pid={0}'>{1}</a>",((Problem)ps[i]).PID, ((Problem)ps[i]).ShortName)); * stat_dt.Columns.Add(((Problem) ps[i]).ShortName); * //stat_dt.Columns.Add(string.Format("<a href='problem.aspx?pid={0}'>{1}</a>",((Problem)ps[i]).PID, ((Problem)ps[i]).ShortName)); * } * mon_dt.Columns.Add("Всего решено"); * mon_dt.Columns.Add("Время"); * mon_dt.Columns.Add("Место"); * //Колонки созданы * TimeSpan the_latest = new TimeSpan(0, 0, 0, 0, 0); * bool has_ac = false; * ArrayList user_data = new ArrayList(); * #region обработка очереди * * foreach (Submission s in db.GetSubmissions(tid, 0)) * { * // Юзер, пославший текущий сабмишн * UserData u = null; * foreach (UserData ud in user_data) * { * if (ud.UID == s.UID) * { * u = ud; * break; * } * } * // Новая строка с юзером * if (u == null) * { * u = new UserData(); * u.UID = (uint) s.UID; * u.Solved = 0; * u.Time = new TimeSpan(0, 0, 0, 0, 0); * u.Problems = new ArrayList(); * foreach (Problem p in ps) * { * Attempts at = new Attempts(); * at.AcTime = new TimeSpan(0, 0, 0, 0, 0); * at.Count = 0; * at.PID = (uint) p.PID; * u.Problems.Add(at); * } * user_data.Add(u); * } * Attempts subm_att = null; * foreach (Attempts sat in u.Problems) * { * if (sat.PID == s.PID) * { * subm_att = sat; * break; * } * } * if (subm_att == null) * { * throw new ApplicationException("Невозможно найти задачу в описании участника"); * } * if (s.Result.Code == Result.AC) * { * if (subm_att.Count <= 0) * { * // вычисление попыток * subm_att.Count = -subm_att.Count + 1; * subm_att.AcTime = s.Time - t_begin; * subm_att.AcTime = ZeroTimeSpan(subm_att.AcTime); * has_ac = true; * if (the_latest < subm_att.AcTime) * { * the_latest = subm_att.AcTime; * } * // начисление времени с учетом штрафа * u.Time += subm_att.AcTime + * new TimeSpan(0, 0, (subm_att.Count - 1)*20, 0, 0); * } * } * else if (s.Result.Code != Result.WAIT && s.Result.Code != Result.RU) * { * if (subm_att.Count <= 0) * { * subm_att.Count--; * } * } * } * #endregion * * foreach (UserData ud in user_data) * { * foreach (Attempts atte in ud.Problems) * { * if (atte.Count > 0) * { * ud.Solved++; * } * } * } * * if (has_ac) * { * lastac.Text = HtmlFunctions.BeautifyTimeSpan(the_latest, false); * } * else * { * lastac.Text = "Еще не было"; * } * user_data.Sort(new UserCompare()); * if (user_data.Count == 0) * { * st_label.InnerHtml += "<span style='color:#CFC411;font-size:small;display:block;'>(Не было послано ни одного решения)</span>"; * } * int[] ac_counts = new int[ps.Count]; * int[] total_counts = new int[ps.Count]; * foreach (UserData ud in user_data) * { * DataRow mon_dtr = mon_dt.NewRow(); * mon_dtr[0] = ud.UID; * User us = db.GetUser((int) ud.UID); * mon_dtr[1] = us.Fullname; * mon_dt.Rows.Add(mon_dtr); * for (int j = 0; j < ud.Problems.Count; j++) * { * int count = ((Attempts) ud.Problems[j]).Count; * if (count > 0) * { * // Write a result to the problem's column * mon_dtr[2 + j] = "<span style='color:blue;'>+"; * if (count != 1) * { * mon_dtr[2 + j] += (count - 1).ToString(); * } * mon_dtr[2 + j] += "</span><span style='font-size:smaller;display:block;'>("; * mon_dtr[2 + j] += HtmlFunctions.BeautifyTimeSpan(((Attempts) ud.Problems[j]).AcTime, true); * mon_dtr[2 + j] += ")</span>"; * // Update AC received users count * ac_counts[j]++; * total_counts[j]++; * } * else if (count < 0) * { * mon_dtr[2 + j] = "<span style='color:red;'>"; * mon_dtr[2 + j] += count.ToString(); * mon_dtr[2 + j] += "</span>"; * total_counts[j]++; * } * else * { * mon_dtr[2 + j] = ""; * } * } * mon_dtr[mon_dt.Columns.Count - 2] = (int) ud.Time.TotalMinutes; * mon_dtr[mon_dt.Columns.Count - 3] = ud.Solved; * } * db.Close(); * for (int l = 0; l < mon_dt.Rows.Count; l++) * { * mon_dt.Rows[l][mon_dt.Columns.Count - 1] = l + 1; * } * * * monitorDG.DataSource = mon_dt; * monitorDG.DataBind(); * #region статистика * * for (int k = 0; k < ps.Count; k++) * { * stat_dt.Rows[0][k + 1] = ac_counts[k]; * double ac_percent = (total_counts[k] == 0) * ? 0 : (double)ac_counts[k] / (double)total_counts[k] * 100.0; * stat_dt.Rows[1][k + 1] = String.Format("{0:F2}%", ac_percent); * } * statDG.DataSource = stat_dt; * statDG.DataBind(); * #endregion * * Draw(mon_dt.Columns.Count - 3); * }*/ Monitor m = MonitorManager.GetMonitor(rp.ContestID, Context); m.Reload(); if (m.HasAccepted) { lastac.Text = String.Format("{0}<br><strong>Задача {1}</strong>", HtmlFunctions.BeautifyTimeSpan( TimeUtils.ZeroTimeSpan(m.LastAccepted.Time - con.Beginning), false), m.LastAccepted.ProblemShortName); } else { lastac.Text = "Еще не было"; } DataTable mon = m.FormatMonitor(); monitorDG.DataSource = mon; monitorDG.DataBind(); Draw(mon.Columns.Count - 3); statDG.DataSource = m.FormatStats(); statDG.DataBind(); } else { Hide(""); } } }