public async Task PingBot(CommandContext ctx) { Int32 now = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; DbConnection conn = new DbConnection(Bot.dbSettings); DbApi dbApi = new DbApi(conn); Int32 last_sent = Int32.Parse(dbApi.GetLastSent()); Int32 cooldown = Int32.Parse(dbApi.GetCooldown()); Int32 next_send = last_sent + cooldown; if (now > next_send) { next_send = now; } string last_sent_str = UnixTimeStampToDateTime(last_sent).ToString(); if (last_sent == 0) { last_sent_str = "Never"; } string message = dbApi.GetMessage(); string channel = dbApi.GetChannel(); await ctx.Channel.SendMessageAsync( "message: " + message + "\n" + "channel: <#" + channel + ">\n" + "next send: " + UnixTimeStampToDateTime(next_send).ToString() + "\n" + "last sent: " + last_sent_str + "\n" + "cooldown: " + cooldown.ToString() + " sec");; }
static public Dictionary <string, dynamic> GetCompanyCategories(DbApi db, int company_id) { List <string> categories = db.Products.Where(p => p.CompanyId == company_id).GroupBy(p => p.Category).Select(c => c.Key).ToList(); Dictionary <string, dynamic> tree = build_tree_from_paths(categories); return(tree); }
override protected void Do() { base.Do(); DbApi db = Fhr.ProductOffice.Models.DbApi.Create(); if (Properties.Settings.Default.DeletePricesOlderThanDays > 0) { DateTime old_time = DateTime.Now.AddDays(-Properties.Settings.Default.DeletePricesOlderThanDays); IQueryable <Cliver.Fhr.ProductOffice.Models.Price> prices = db.Prices.Where(p => p.Time < old_time); db.Prices.RemoveRange(prices); Log.Main.Write("Deleting Prices older than " + old_time.ToShortDateString() + ": " + prices.Count()); db.SaveChanges(); } DbApi.RenewContext(ref db); if (Properties.Settings.Default.DeleteProductsOlderThanDays > 0) { DateTime old_time = DateTime.Now.AddDays(-Properties.Settings.Default.DeleteProductsOlderThanDays); IQueryable <Fhr.ProductOffice.Models.Product> products = db.Products.Where(p => p.UpdateTime == null || p.UpdateTime < old_time); foreach (Fhr.ProductOffice.Models.Product product in products) { Fhr.ProductOffice.DataApi.Product.Delete(db, product.Id); } Log.Main.Write("Deleting Products older than " + old_time.ToShortDateString() + ": " + products.Count()); } }
public async Task CounterMM(CommandContext ctx) { DbConnection conn = new DbConnection(Bot.dbSettings); DbApi dbApi = new DbApi(conn); int total = dbApi.GetServerTotal(); total--; dbApi.SetServerTotal(total); await ctx.Channel.SendMessageAsync("Server Counter: " + total.ToString()).ConfigureAwait(false); }
internal SettingsForm() { InitializeComponent(); CrawlerProcessMaxNumber.Text = CrawlerHostManager.Properties.Settings.Default.CrawlerProcessMaxNumber.ToString(); SmtpHost.Text = CrawlerHost.Properties.Settings.Default.SmtpHost; SmtpLogin.Text = CrawlerHost.Properties.Settings.Default.SmtpLogin; SmtpPassword.Text = CrawlerHost.Properties.Settings.Default.SmtpPassword; SmtpPort.Text = CrawlerHost.Properties.Settings.Default.SmtpPort.ToString(); AdminEmailSender.Text = CrawlerHost.Properties.Settings.Default.EmailSender; DefaultAdminEmails.Text = CrawlerHost.Properties.Settings.Default.DefaultAdminEmails; DbConnectionString.Text = DbApi.GetConnectionString(); //if (string.IsNullOrWhiteSpace(DbConnectionString.Text)) // DbConnectionString.Text = CrawlerHost.Properties.Settings.Default.DbConnectionString; }
public async Task Dict(CommandContext ctx) { DbConnection conn = new DbConnection(Bot.dbSettings); DbApi dbApi = new DbApi(conn); string[] args = ctx.Message.Content.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); if ((args.Length == 2 || args.Length == 3) && args[1] == "list") { int perPage = 25; string[] list = dbApi.LoadDictionary().ToArray(); int start = 0; if (args.Length == 3) { start = int.Parse(args[2]) - 1; } string message = "Swear Dictionary : Page " + (start + 1).ToString() + " of " + ((list.Count() / 25) + 1).ToString() + "\n```\n"; if (start + 1 > (list.Count() / 25) + 1) { return; } for (int i = start * perPage; i < (start * perPage) + perPage; i++) { if (i < list.Length) { message += list[i] + "\n"; } } message += "```"; await ctx.Channel.SendMessageAsync(message); } else if (args.Length != 3) { await ctx.Channel.SendMessageAsync("Invalid format, please try again\nExample:\n.dict [add|rm] <word>\n.dict list <n>"); } else if (args[1] == "rm") { string word = args[2]; dbApi.DictRm(word); await ctx.Channel.SendMessageAsync("Removed '" + word + "'"); } else { string word = args[2]; dbApi.DictAdd(word); await ctx.Channel.SendMessageAsync("Added '" + word + "'"); } }
static void Main(string[] args) { //Model model=new Model(){Id=10,Name = "life2",CreateDate = DateTime.Now}; DbApi api=new DbApi(); //api.Update(model); //api.Insert(model); Condition A1=new Condition("Id",1,Op.Equal); Condition A2=new Condition("Id",3,Op.Equal); Condition A3=new Condition("Name","life",Op.NotEqual); Query query = new Query() { WhereExpression = new OpExpression(new OpExpression(new OpExpression(A1),new OpExpression(A2),JoinOP.Or ), new OpExpression(A3), JoinOP.And) }; var list=api.Select<Model>(query); //api.Insert(model); //api.Delete(model); }
static void Main(string[] args) { //Model model=new Model(){Id=10,Name = "life2",CreateDate = DateTime.Now}; DbApi api = new DbApi(); //api.Update(model); //api.Insert(model); Condition A1 = new Condition("Id", 1, Op.Equal); Condition A2 = new Condition("Id", 3, Op.Equal); Condition A3 = new Condition("Name", "life", Op.NotEqual); Query query = new Query() { WhereExpression = new OpExpression(new OpExpression(new OpExpression(A1), new OpExpression(A2), JoinOP.Or), new OpExpression(A3), JoinOP.And) }; var list = api.Select <Model>(query); //api.Insert(model); //api.Delete(model); }
public IActionResult Search(int p, string o, string q, int t) { var db = new DbApi(); if (p == 0) { p = 1; } int?tagId = t; if (t == 0) { tagId = null; } if (o == null) { o = "created-desc"; } var content = ContentApi.Search(10, p, "question", q, o, tagId); var result = new ContentListModel(); result.Content = content; result.ResultsCount = ContentApi.GetSearchResultCount("question", q, t); result.MaxPages = Math.Min(5, (int)Math.Floor((double)result.ResultsCount / 10)); if (result.ResultsCount % 10 != 0) { result.MaxPages++; } result.Page = p; result.SearchText = q; result.OrderBy = o; result.Tags = TagApi.Select().OrderByDescending(tag => tag.Count).Take(8).ToList(); return(View("Results", result)); }
public async Task SwearBot(CommandContext ctx) { DbConnection conn = new DbConnection(Bot.dbSettings); DbApi dbApi = new DbApi(conn); string[] args = ctx.Message.Content.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (args.Length == 1) { int total = dbApi.GetServerTotal(); await ctx.Channel.SendMessageAsync("Server Counter: " + total.ToString()).ConfigureAwait(false); } else if (args.Length == 2) { if (args[1].StartsWith("<@!") && args[1].EndsWith(">")) { int user_total = dbApi.UserGetTotal(args[1]); await ctx.Channel.SendMessageAsync("Counter for " + args[1] + " is " + user_total.ToString()).ConfigureAwait(false); } } }
public String fetchSolutionDetails(int solutionId, int batchId) { var dbapi = new DbApi(new MySqlConnectionRetriever(_config)); string fetchdValue = dbapi.FetchSerializedDataFromDb(solutionId, batchId); var deserializeObject = JsonConvert.DeserializeObject <ProductionSchedule>(fetchdValue); var propsedSchedule = deserializeObject.getProposedOrder(); List <Object> objList = new List <object>(); string[] details = new string[] { "machineId", "orderId", "dueDate", "highPriority", "productCode", "productionCycles" }; for (int i = 0; i < propsedSchedule.Count; i++) { var values = new object[propsedSchedule[i].Count]; for (int j = 0; j < propsedSchedule[i].Count; j++) { var orders = propsedSchedule[i][j]; values[j] = new { machineId = i, orders.orderId, orders.dueDate, orders.highPriority, orders.productCode, orders.productionCycles }; } var collectionWrapper = new { values, details }; objList.Add(collectionWrapper); } return(SerializeAndReturn(objList)); }
bool process_file(string file, Import import, Action <int> progress = null) { DateTime start_time = DateTime.Now; Excel.IExcelDataReader edr; FileStream stream = System.IO.File.Open(file, FileMode.Open, FileAccess.Read); if (file.EndsWith(".xlsx", StringComparison.InvariantCultureIgnoreCase)) { edr = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream); } else { edr = Excel.ExcelReaderFactory.CreateBinaryReader(stream); } //edr = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream); System.Data.DataSet ds = edr.AsDataSet(); edr.Close(); Fhr.ProductOffice.Models.ImportMap import_map = db.ImportMaps.Where(r => r.Id == import.MapId).First(); //if (import_map.C_CompanyProductIdI == null) // throw new Exception("C_CompanyProductIdI in map #" + import_map.Id + " is not specified."); //if (import_map.C_NameI == null) // throw new Exception("C_NameI in map #" + import_map.Id + " is not specified."); db.Configuration.AutoDetectChangesEnabled = false; db.Configuration.ValidateOnSaveEnabled = false; int sheet_count = ds.Tables.Count; int invalid_product_count = 0; int new_product_count = 0; int updated_product_count = 0; int processed_product_count = 0; int invalid_price_count = 0; int new_price_count = 0; int updated_price_count = 0; int processed_price_count = 0; int row_number = -1; List <string> error_messages = new List <string>(); foreach (System.Data.DataTable dt in ds.Tables) { if (import_map.SkipFirstRow) { dt.Rows.RemoveAt(0); } foreach (System.Data.DataRow row in dt.Rows) { row_number++; Fhr.ProductOffice.Models.Product product = new Fhr.ProductOffice.Models.Product(); product.CompanyId = import_map.CompanyId; product.ExternalId = row[import_map.C_CompanyProductIdI].ToString().Trim(); if (string.IsNullOrWhiteSpace(product.ExternalId)) { bool line_is_empty = true; for (int i = 0; i < 5; i++) { if (!string.IsNullOrWhiteSpace(row[i].ToString())) { line_is_empty = false; break; } } if (!line_is_empty) { string error = "Cell (" + import_map.C_PriceI + ", " + row_number + ") ExternalId is empty."; if (import.CheckNotImport) { invalid_product_count++; error_messages.Add(error); } else { throw new Exception(error); } } continue; } product.ModifyTime = null; product.UpdateTime = import.UpdateTime; product.Name = row[import_map.C_NameI].ToString().Trim(); if (product.Name == null) { string error = "Cell (" + import_map.C_PriceI + ", " + row_number + ") Name is empty."; if (import.CheckNotImport) { invalid_product_count++; error_messages.Add(error); } else { throw new Exception(error); } } product.Source = "file:" + import.File.FileName; if (import_map.C_SkuI != null) { product.Sku = row[(int)import_map.C_SkuI].ToString().Trim(); } if (import_map.C_CategoryI != null) { product.Category = row[(int)import_map.C_CategoryI].ToString().Trim(); } if (import_map.C_DescriptionI != null) { product.Description = row[(int)import_map.C_DescriptionI].ToString().Trim(); } if (!import.CheckNotImport) { Fhr.ProductOffice.Models.Product p = db.Products.Where(r => r.CompanyId == product.CompanyId && r.ExternalId == product.ExternalId).FirstOrDefault(); if (p == null) { product.CreateTime = import.UpdateTime; product.LinkId = null; db.Products.Add(product); new_product_count += db.SaveChanges(); } else { product.Id = p.Id; if (product.Description != null) { p.Description = product.Description; } if (product.ImageUrls != null) { p.ImageUrls = product.ImageUrls; } if (product.ModifyTime != null) { p.ModifyTime = product.ModifyTime; } p.UpdateTime = product.UpdateTime; if (product.Name != null) { p.Name = product.Name; } if (product.Sku != null) { p.Sku = product.Sku; } if (product.Source != null) { p.Source = product.Source; } if (product.Url != null) { p.Url = product.Url; } //db.Entry(product).State = EntityState.Modified; updated_product_count += db.SaveChanges(); } } processed_product_count++; if (progress != null) { progress(processed_product_count); } if (import_map.C_PriceI != null) { Price price = new Price(); price.CurrencyId = import_map.CurrencyId; price.ProductId = product.Id; price.Time = (DateTime)product.UpdateTime; decimal v; if (!decimal.TryParse(row[(int)import_map.C_PriceI].ToString().Trim(), out v)) { string error = "Cell (" + import_map.C_PriceI + ", " + row_number + ") Price cannot be parsed:" + row[(int)import_map.C_PriceI].ToString().Trim(); if (import.CheckNotImport) { invalid_price_count++; error_messages.Add(error); } else { throw new Exception(error); } } price.Value = v; if (!import.CheckNotImport) { Price p = db.Prices.Where(r => r.ProductId == price.ProductId && r.Time == price.Time).FirstOrDefault(); if (p == null) { db.Prices.Add(price); new_price_count += db.SaveChanges(); } else { price.Id = p.Id; db.Entry(p).CurrentValues.SetValues(price); updated_price_count += db.SaveChanges(); } } processed_price_count++; } DbApi.RenewContext(ref db); } } if (import.CheckNotImport) { Messages.Add("CHECK RESULT", "File " + import.File.FileName + " has been checked with map " + db.ImportMaps.Where(r => r.Id == import.MapId).First().Name); Messages.Add("CHECK RESULT", "Spreadsheets: " + sheet_count); Messages.Add("CHECK RESULT", "Found products: " + processed_product_count); Messages.Add("CHECK RESULT", "Invalid products: " + invalid_product_count); Messages.Add("CHECK RESULT", "Invalid prices: " + invalid_price_count); Messages.Add("CHECK RESULT", "Process time: " + String.Format("{0:0.00}", (DateTime.Now - start_time).TotalSeconds) + " secs"); add_error_messages("CHECK RESULT", error_messages); } else { Messages.Add("IMPORT RESULT", "File " + import.File.FileName + " has been imported with map " + db.ImportMaps.Where(r => r.Id == import.MapId).First().Name); Messages.Add("IMPORT RESULT", "Spreadsheets: " + sheet_count); Messages.Add("IMPORT RESULT", "Processed products: " + processed_product_count); Messages.Add("IMPORT RESULT", "Invalid products: " + invalid_product_count); Messages.Add("IMPORT RESULT", "Added products: " + new_product_count); Messages.Add("IMPORT RESULT", "Changed products: " + updated_product_count); Messages.Add("IMPORT RESULT", "Invalid prices: " + invalid_price_count); Messages.Add("IMPORT RESULT", "Added prices: " + new_price_count); Messages.Add("IMPORT RESULT", "Changed prices: " + updated_price_count); Messages.Add("CHECK RESULT", "Process time: " + String.Format("{0:0.00}", (DateTime.Now - start_time).TotalSeconds) + " secs"); add_error_messages("IMPORT RESULT", error_messages); } return(true); }
private void load_table() { try { this.crawlersTableAdapter1.Connection.ConnectionString = DbApi.GetConnectionString(); this.crawlersTableAdapter1.Fill(this.cliverCrawlersDataSet1.Crawlers); //dataGridView1.AutoResizeColumns(); //foreach (DataColumn c in CrawlersTableAdapter1.GetData().Columns) // if (c.ColumnName.StartsWith("_")) // c.AllowDBNull = true; DataGridViewComboBoxColumn c_ = (DataGridViewComboBoxColumn)dataGridView1.Columns["Command_"]; c_.DataSource = Enum.GetValues(typeof(Crawler.Command)); c_.ValueType = typeof(Crawler.Command); //c_.ValueMember = "Value"; //c_.DisplayMember = "Display"; foreach (DataGridViewRow r in dataGridView1.Rows) { try { r.Cells[command_i_].Value = (Crawler.Command)r.Cells[command_i].Value; } catch { r.Cells[command_i_].Value = -1; } } c_ = (DataGridViewComboBoxColumn)dataGridView1.Columns["State_"]; c_.DataSource = Enum.GetValues(typeof(Crawler.State)); c_.ValueType = typeof(Crawler.State); foreach (DataGridViewRow r in dataGridView1.Rows) { try { r.Cells[state_i_].Value = (Crawler.State)r.Cells[state_i].Value; } catch { r.Cells[state_i_].Value = -1; } } c_ = (DataGridViewComboBoxColumn)dataGridView1.Columns["_LastSessionState_"]; c_.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing; c_.DataSource = Enum.GetValues(typeof(Crawler.SessionState)); c_.ValueType = typeof(Crawler.SessionState); foreach (DataGridViewRow r in dataGridView1.Rows) { try { r.Cells[_last_session_state_i_].Value = (Crawler.SessionState)r.Cells[_last_session_state_i].Value; } catch { r.Cells[_last_session_state_i_].Value = 0; } } } catch (Exception ex) { LogMessage.Error(ex); } }