public static HeroBasicInfo[] getBasicInfos(List <int> heroIDs) { var lst = new List <HeroBasicInfo>(); if (heroIDs.Count == 0) { return(lst.ToArray()); } var res = DB2.GetInstance().Select( "heroID, playerName, basicInfo", "Hero", $"heroID IN ({string.Join(",", heroIDs)})" ); HeroBasicInfo tmp; if (res != null) { foreach (var row in res) { tmp = HeroBasicInfo.fromJson(row[2]); tmp.heroID = int.Parse(row[0]); tmp.heroName = row[1]; lst.Add(tmp); } } return(lst.ToArray()); }
public static DataTable GetDataOfType(DB2 db, string[] fields, Type type) { var method = typeof(DTODataHelper).GetMethod("GetData").MakeGenericMethod(type); var result = method.Invoke(null, new object[] { db, fields }) as DataTable; return(result); }
private List <MainContract> Load_Contact(string filename) { List <MainContract> result = new List <MainContract>(); SqlConnection con = DB2 <SqlConnection> .GetConnection(Config["Connection"]["Conn"].Value);// Get_Connection(); string sql = Config["Sql"]["Load_Contract"].Value; if (con != null) { try { using (SqlDataReader sr = DB_BLL.SQLHelp.ExecuteReader(con, CommandType.Text, sql, null)) { while (sr.Read()) { MainContract s = new MainContract(Convert.ToInt32(sr["CID"]), Convert.ToInt32(sr["area_id"]), sr["area_name"].ToString().Trim(), sr["cust_name"].ToString().Trim(), sr["Address_Comment"].ToString().Trim(), sr["contract_name"].ToString().Trim(), myArray, Config["Connection"]["Conn"].Value); string[] keys = s.SubSys.Keys.ToArray <string>(); foreach (string a in keys) { //此处获取子系统的合同号,用配置文件中的子系统名称-连接到配置数据库中的字段定义,再填到sql中 s.SubSys[a] = sr[Config["Generic"][a].Value].ToString().Trim(); } result.Add(s); } } return(result); } catch (Exception ex) { return(null); } } return(null); }
/// <summary> /// Run this code at launch /// </summary> void Start() { Network.Disconnect(); Settings.ApplicationPath = Application.streamingAssetsPath; if (!File.Exists("Settings.ini")) { File.WriteAllLines("Settings.ini", Settings.Data); } else { long length = new System.IO.FileInfo("Settings.ini").Length; if (length > 0) { string[] DataBuffer = File.ReadAllLines("Settings.ini"); for (int i = 0; i < DataBuffer.Length; i++) { Settings.Data[i] = DataBuffer[i]; } } else { File.WriteAllLines("Settings.ini", Settings.Data); // defaults } } SettingsInit(); ADT.Initialize(); if (Settings.Data[2] == Settings.WoWSource.Extracted.ToString()) { DB2.Initialize(); } }
private object FlushSth(string strsql, SqlParameter[] paras, string returnpara) { SqlConnection conn = DB2 <SqlConnection> .GetConnection(_sqlConnection); object result = null; if (conn != null) { try { using (SqlDataReader sr = DB_BLL.SQLHelp.ExecuteReader(conn, CommandType.Text, strsql, paras)) { while (sr.Read()) { result = sr[returnpara]; } } return(result); } catch (Exception ex) { return(null); } } return(null); }
private void DB2Operate() { entities = new DB2Entities <T>(tableName); DB2.GetSomeData(sql); foreach (DataRow dr in DB2.dt.Rows) { T t = new T(); // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { if (DB2.dt.Columns.Contains(pi.Name)) { if (!pi.CanWrite) { continue; } object value = dr[pi.Name]; if (value != DBNull.Value) { pi.SetValue(t, value, null); } } } entities.EntityList.Add(t); } }
private bool UpdateSth(string strsql, SqlParameter[] paras) { using (SqlCommand cmd = new SqlCommand()) { SqlConnection conn = DB2 <SqlConnection> .GetConnection(_sqlConnection);//Get_Connection(); SqlTransaction tr = null; try { conn.Open(); tr = conn.BeginTransaction(); cmd.Connection = conn; cmd.Transaction = tr; cmd.CommandType = CommandType.Text; cmd.CommandText = strsql; cmd.Parameters.AddRange(paras); cmd.ExecuteNonQuery(); tr.Commit(); return(true); } catch (Exception ex) { if (tr != null) { tr.Rollback(); } return(false); } finally { conn.Close(); } } }
public void loadItemsFromDB() { Console.WriteLine("[!] Bag: " + string.Join(",", items)); // TODO: load items from db if (items.Count == 0) { return; } var res = DB2.GetInstance().Select( "itemUID, itemInfo", "UniqueItem", $"itemUID IN ({string.Join(",", items)});" ); if (res == null) { return; } // load items to memory Item item; foreach (var db_item in res) { item = Item.fromJson(db_item[1]); itemDict.Add(uint.Parse(db_item[0]), item); itemPos.Add(item.position, item.itemUID); } }
public ActionResult Publication(long Id, bool Enabled) { var promotion = DB2.Promotions.SingleOrDefault(x => x.Id == Id); if (promotion == null) { ErrorMessage("Акция не найдена"); return(RedirectToAction("Index")); } ; if (!promotion.CheckSecurity(CurrentUser)) { ErrorMessage("У вас нет прав для изменения данной акции"); return(RedirectToAction("Index")); } promotion.Enabled = Enabled; DB2.PromotionHistory.Add(new PromotionSnapshot(CurrentUser, promotion, DB, DB2) { SnapshotName = "Изменения статуса акции" }); DB2.SaveChanges(); Mails.PromotionNotification(MailType.EditPromotion, promotion); var message = promotion.GetStatus().DisplayName(); SuccessMessage($"Новый статус: {message}"); return(RedirectToAction("Index", new { Id = Id.ToString() })); }
public new List <Clock> GetList() { List <Clock> result = new List <Clock>(); DbConnection con = null; DbDataReader sr = null; string sql = Config["Sql"]["Load_Clock"].Value; if (Config["Connection"]["Type"].Value == "Sqlserver") { con = DB2 <SqlConnection> .GetConnection(Config["Connection"]["Conn"].Value); sr = DB_BLL.SQLHelp.ExecuteReader((SqlConnection)con, CommandType.Text, sql, null); } if (Config["Connection"]["Type"].Value == "Oracle") { con = DB2 <OracleConnection> .GetConnection(Config["Connection"]["Conn"].Value); sr = DB_BLL.OraHelp.ExecuteReader((OracleConnection)con, CommandType.Text, sql, null); } if (con != null) { try { while (sr.Read()) { if (Convert.ToInt64(sr["本次用量"]) > 0) { Clock s = new Clock(); s.Sy_con_id = sr["合同编号"].ToString().Trim(); s.Sy_Addr_Id = sr["资源编号"].ToString().Trim(); s.Clock_name = sr["表名"].ToString().Trim(); s.Lmrd = Convert.ToInt64(Convert.ToDouble(sr["上次抄表数"].ToString())); s.Tmrd = Convert.ToInt64(Convert.ToDouble(sr["本次抄表数"].ToString())); s.Current_use = Convert.ToInt64(Convert.ToDouble(sr["本次用量"])); s.Ldate = Convert.ToDateTime(sr["上次抄表时间"]); s.Rdate = Convert.ToDateTime(sr["本次抄表时间"]); s.Clock_type = Convert.ToString(sr["表类型"]); s.Account_Date = Convert.ToString(sr["所属账期"]); s.Address = sr["室号"].ToString().Trim(); result.Add(s); } } sr.Close(); con.Close(); con.Dispose(); return(result); } catch (Exception ex) { return(null); } finally { sr.Close(); con.Close(); con.Dispose(); } } return(null); }
public ActionResult Autorise(Admin admin) { using (var db = DB2.Aeroport()) { try { var detail = db.Admins.Where(x => x.NomUtilisateur == admin.NomUtilisateur && x.MotPasse == admin.MotPasse).FirstOrDefault(); if (detail == null) { admin.LoginErrorMessage = "mauvais nom d'utilisateur ou mot de passe"; return(View("Index", admin)); } else { Session["Id_Admin"] = detail.Id_Admin; Session["NomUtilisateur"] = detail.NomUtilisateur; return(RedirectToAction("DashBoard", "Admin")); } } catch (Exception e) { } } return(View()); }
public JsonResult GetStudents(string term) { DB2 db = new DB2(); List <string> students; students = db.AllocatedLecturers.Where(x => x.Supervisors.StartsWith(term)).Select(y => y.Supervisors).ToList(); return(Json(students, JsonRequestBehavior.AllowGet)); }
private List <SysTicket> Load_Contact() { List <SysTicket> result = new List <SysTicket>(); DbConnection con = null; DbDataReader sr = null; string sql = Config["Sql"]["Load_Bill"].Value; if (Config["Connection"]["Type"].Value == "Sqlserver") { con = DB2 <SqlConnection> .GetConnection(Config["Connection"]["Conn"].Value);// Get_SqlConnection(); sr = DB_BLL.SQLHelp.ExecuteReader((SqlConnection)con, CommandType.Text, sql, null); } if (Config["Connection"]["Type"].Value == "Oracle") { //con = Get_OracleConnection(); con = DB2 <OracleConnection> .GetConnection(Config["Connection"]["Conn"].Value); sr = DB_BLL.OraHelp.ExecuteReader((OracleConnection)con, CommandType.Text, sql, null); } if (con != null) { try { while (sr.Read()) { SysTicket s = new SysTicket(); s.Fee_name = sr["收费项目"].ToString().Trim(); s.Contract_id = sr["合同编号"].ToString().Trim(); s.Fee = Convert.ToDouble(sr["本金欠收"].ToString()); s.Account_Date = sr["所属账期"].ToString(); //yyyy-mm; s.Data_start = Convert.ToDateTime(sr["应收期间开始日期"]); s.Data_end = Convert.ToDateTime(sr["应收期间结束日期"]); s.Addrss_id = ""; result.Add(s); } sr.Close(); con.Close(); con.Dispose(); return(result); } catch { return(null); } finally { sr.Close(); con.Close(); con.Dispose(); } } return(null); }
/// <summary> /// Безвозвратно удалить /// </summary> /// <param name="id">идентификатор новости</param> /// <returns></returns> public ActionResult Delete(long id) { var news = DB2.Newses.Find(id); DB2.Newses.Remove(news); DB2.SaveChanges(); Mails.NewsChanged(news, "Новость удалена", root); SuccessMessage("Новость удалена"); return(RedirectToAction("Archive")); }
public ActionResult DeleteLinksToFile(int id, List <int> fileId) { var mailForm = DB2.Emails.Find(id); var mediaFiles = DB2.MediaFiles.Where(x => fileId.Contains(x.Id)).ToList(); foreach (var f in mediaFiles) { mailForm.MediaFiles.Remove(f); } DB2.SaveChanges(); return(RedirectToAction("Edit", new { id })); }
public void RefreshDB() { var context = ((IObjectContextAdapter)DB2.Aeroport()).ObjectContext; var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries( EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged) where entry.EntityKey != null select entry.Entity).ToList(); context.Refresh(RefreshMode.StoreWins, refreshableObjects); }
private List <Sys_Contract> Load_Contact() { List <Sys_Contract> result = new List <Sys_Contract>(); DbConnection con = null; DbDataReader sr = null; string sql = Config["Sql"]["Load_Contract"].Value; if (Config["Connection"]["Type"].Value == "Sqlserver") { con = DB2 <SqlConnection> .GetConnection(Config["Connection"]["Conn"].Value);//Get_SqlConnection(); sr = DB_BLL.SQLHelp.ExecuteReader((SqlConnection)con, CommandType.Text, sql, null); } if (Config["Connection"]["Type"].Value == "Oracle") { con = DB2 <OracleConnection> .GetConnection(Config["Connection"]["Conn"].Value);//Get_OracleConnection(); sr = DB_BLL.OraHelp.ExecuteReader((OracleConnection)con, CommandType.Text, sql, null); } if (con != null) { try { while (sr.Read()) { Sys_Contract s = new Sys_Contract(Config["Generic"]["Sys_Name"].Value); s.Cust_Name = sr["客户名称"].ToString().Trim(); s.ContractCode = sr["合同编号"].ToString().Trim(); s.Add_id = sr["资源编号"].ToString().Trim(); s.Add_name = sr["租用单元"].ToString().Trim(); result.Add(s); } sr.Close(); con.Close(); con.Dispose(); return(result); } catch { return(null); } finally { sr.Close(); con.Close(); con.Dispose(); } } return(null); }
private static void CASCInitThread() { CurrentDataVersion = Settings.Data[3]; Working = true; EncryptionKeys.ParseKeyFile(Settings.ApplicationPath + @"\ListFiles\keys1.txt"); /// will need more keys maybe /// Casc.ClearData(); CurrentWorkerText = "Reading WoW Folder"; Casc.ReadWoWFolder(); // check for correct wow data path CurrentWorkerPercent = .05f; CurrentWorkerText = "Find Build Config"; Casc.FindWoWBuildConfig(); CurrentWorkerPercent = .10f; CurrentWorkerText = "Reading IDX files"; Casc.ReadWoWIDXfiles(); // read the IDX files Debug.Log("LocalIndexData Size : " + IndexBlockParser.LocalIndexData.Count); CurrentWorkerPercent = .25f; CurrentWorkerText = "Loading Encoding File"; Casc.LoadEncodingFile(); // Locate and extract encoding file from the data files using the MD5 found in build configuration file Debug.Log("Encoding File Size : " + Casc.EncodingData.Count); CurrentWorkerPercent = .40f; CurrentWorkerText = "Loading Root File"; Casc.LoadWoWRootFile(); Debug.Log("Root Data Size : " + Casc.MyRootData.Count); CurrentWorkerPercent = .55f; CurrentWorkerText = "Loading the Filelist"; Casc.LoadFilelist(); CurrentWorkerPercent = .75f; CurrentWorkerText = "Sorting the Filelist"; Casc.LoadTreeData(); CurrentWorkerPercent = .90f; Working_InitializationFinished = true; Initialized = true; TerrainImport.Initialized = false; CASCThread.Abort(); CASCThread = null; ThreadRunning = false; DB2.Initialize(); }
/// <summary> /// Подтверждение промоакции /// </summary> /// <param name="Id">идентификатор промоакции</param> public ActionResult Confirm(long id) { var model = DB2.Promotions.Find(id); model.Status = PromotionStatus.Confirmed; DB2.PromotionHistory.Add(new PromotionSnapshot(CurrentUser, model, DB, DB2) { SnapshotName = "Подтверждение промоакции" }); DB2.SaveChanges(); Mails.PromotionNotification(MailType.StatusPromotion, model); SuccessMessage("Промоакция подтверждена"); return(RedirectToAction("Index")); }
public ActionResult Edit(MailFormUi model) { var mailForm = DB2.Emails.SingleOrDefault(x => x.Id == model.Id); if (mailForm == null) { return(RedirectToAction("Index")); } mailForm.Body = model.Body; mailForm.Subject = model.Subject; DB2.SaveChanges(); return(RedirectToAction("Edit", new { id = model.Id })); }
public static DataTable GetData <T>(DB2 db, string[] fields) { var dtoType = typeof(T); var source = Mapper.Configuration.GetAllTypeMaps().Where(i => i.DestinationType == dtoType).Select(i => i.SourceType).FirstOrDefault(); if (source == null) { throw new HMException("Не найден источник данных"); } var dbSet = db.Set(source); var querable = dbSet.AsQueryable(); var list = dbSet.ProjectTo <T>().ToList(); return(GetDataTable(list, fields)); }
/// <summary> /// /// </summary> /// <param name="ids"></param> /// <returns></returns> public ActionResult DeleteFile(List <int> ids) { if (ids == null || !ids.Any()) { return(RedirectToAction("Index")); } var files = DB2.MediaFiles.Where(x => ids.Contains(x.Id)); foreach (var file in files) { DB2.MediaFiles.Remove(file); } DB2.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// Отмена подтверждения промоакции /// </summary> /// <param name="Id">идентификатор промоакции</param> public ActionResult Reject(int id, string comment) { var model = DB2.Promotions.Find(id); model.Status = PromotionStatus.Rejected; DB2.PromotionHistory.Add(new PromotionSnapshot(CurrentUser, model, DB, DB2) { SnapshotName = "Отклонение промоакции", SnapshotComment = comment }); DB2.SaveChanges(); Mails.PromotionNotification(MailType.StatusPromotion, model, comment); SuccessMessage("Промоакция отклонена"); return(RedirectToAction("Index")); }
public ActionResult Create(News news) { if (!ModelState.IsValid) { return(View(news)); } var user = DB2.Users.Find(CurrentUser.Id); if (news.Id > 0) { var model = DB2.Newses.Find(news.Id); // добавляем в историю изменения var description = "Изменена новость"; if (!model.Enabled) { description = "Опубликована архивная новость"; } model.DatePublication = DateTime.Now; model.Body = news.Body; model.Subject = news.Subject; model.Enabled = true; var history = new NewsSnapshot(model, user, description); DB2.NewsHistory.Add(history); Mails.NewsChanged(model, description, root); //важно, сохранить после отправки уведомления иначе не будет работать вычисление изменений DB2.SaveChanges(); SuccessMessage("Изменения успешно сохранены"); } else { // добавляем новость news.DatePublication = DateTime.Now; news.Enabled = true; DB2.Newses.Add(news); DB2.SaveChanges(); // пишем в историю var history = new NewsSnapshot(news, user, "Добавлена новость"); DB2.NewsHistory.Add(history); DB2.SaveChanges(); Mails.NewsChanged(news, "Добавлена новость", root); SuccessMessage("Новость успешно добавлена"); } return(RedirectToAction("Index")); }
private bool Retire() { int itemsToDequeue = retirePhoneList.Count; using (db = DB2.Aeroport()) { try { while (itemsToDequeue-- > 0) { Notification item; bool isTaken = retirePhoneList.TryDequeue(out item); if (isTaken) { var dbelem = db.Notifications.Find(item.Id); if (dbelem != null) { twilloInstance.WriteNewNotification(item); item.Statut = true; } else { notFoundPhoneList.Enqueue(item); } } else { if (retirePhoneList.IsEmpty) { db.SaveChanges(); return(true); } } } db.SaveChanges(); } catch (Exception e) { return(false); } } return(true); }
public ActionResult DeleteNews(long id) { // отправляем новость в архив var news = DB2.Newses.Find(id); news.Enabled = false; DB2.SaveChanges(); // добавляем историю изменений var history = new NewsSnapshot(news, DB2.Users.Find(CurrentUser.Id), "Новость отправлена в архив"); DB2.NewsHistory.Add(history); DB2.SaveChanges(); Mails.NewsChanged(news, "Новость отправлена в архив", root); SuccessMessage("Новость отправлена в архив"); return(RedirectToAction("Index")); }
private bool isNotificationExist(DAL.Notification notification, ref List <string> _messages) { var dbContext = DB2.Aeroport(); /*if (dbContext.VolsCedules.Find( dbContext.Vols.Find(notification.Num_Vol) ) == null ) * { * _messages.Add("Le vols na pas etes trouver."); * return false; * }*/ if ((from nt in dbContext.Notifications where nt.Num_Phone == notification.Num_Phone && nt.Num_Vol == notification.Num_Vol select nt).Count() > 0) { _messages.Add("Le vol " + notification.Num_Vol + " est deja inscript."); return(false); } return(true); }
public void verifyNotification() { DateTime todayOffset = DateTime.Now.AddDays(-2); List <Notification> notifList; using (db = DB2.Aeroport()) { notifList = db.Notifications.ToList(); notifList.ForEach((m) => { if (m.Date_Notification.CompareTo(todayOffset) < 0 && m.Statut != true) { db.Entry(m).Property(u => u.Statut).CurrentValue = true; } }); db.SaveChanges(); } }
private MediaFile SaveFile(HttpPostedFileBase src) { if (src == null) { return(null); } var file = new MediaFile(src.FileName); var ms = new MemoryStream(); src.InputStream.CopyTo(ms); file.ImageFile = ms.ToArray(); file.ImageType = src.ContentType; file.ImageSize = ms.Length; file.EntityType = EntityType.Promotion; DB2.MediaFiles.Add(file); DB2.SaveChanges(); return(file); }
public bool addItem(Hero p, Item item) { // TODO: pick up auto stack // TODO: send add-item to backpack packet byte pos; for (pos = 1; pos < size; pos++) { // looking for empty pos if (!itemPos.ContainsKey(pos)) { break; } } if (pos < size) { item.position = pos; this.items.Add(item.itemUID); this.itemPos.Add(pos, item.itemUID); this.itemDict.Add(item.itemUID, item); DB2.GetInstance().Insert( "UniqueItem", new Dictionary <string, object>() { { "itemUID", item.itemUID }, { "itemInfo", item.toJson() }, { "belongsTo", p.heroID }, } ); return(true); } else { // backpack is full. // TODO: send cannot pick up packet return(false); } }
//int bitIndex = 1; private void button1_Click(object sender, EventArgs e) { var db2 = new DB2<AreaPOIRec>(Memory.BaseAddress + 0xC80540); foreach (var row in db2) { Console.WriteLine("{0}: {1}", row.Key, row.Value.GetString("Name")); } //Stopwatch sw = new Stopwatch(); //sw.Start(); //for (int i = 0; i < 50000; ++i) //{ // var db = Game.FactionTemplateDB; // foreach (var f in db) // { // } //} //sw.Stop(); //var passed1 = sw.ElapsedMilliseconds; //MessageBox.Show(passed1.ToString()); //new DescriptorsDumper(); var db = Game.AreaTableDB; foreach (var area in db) { Console.WriteLine("{0}: {1}", area.Key, area.Value.AreaName); } listView1.Items.Clear(); int total = 0; int items = 0; int conts = 0; int units = 0; int plrs = 0; int gos = 0; int other = 0; //var objects = Game.ObjMgr.Where(o => o.Type == WowObjectType.GameObject).Where(o => (o as WowGameObject).TypeId == GameObjectTypeId.Chest).OrderBy(o => (o as WowGameObject).DistanceToMe); //var objects = Game.ObjMgr.Where(o => o.Type == WowObjectType.GameObject).OrderBy(o => (o as WowGameObject).DistanceToMe); var objects = Game.ObjMgr; foreach (WowObject obj in objects) { //if (obj.Entry == 223103) //{ // if (bitIndex == 1) // obj.DynamicFlags = 0; // obj.DynamicFlags = (1u << bitIndex); // bitIndex++; //} //if (obj.GetValue<int>(CGGameObjectData.DisplayID) == 5744) // obj.SetValue<int>(CGGameObjectData.StateSpellVisualID, 23216); total++; if (obj.IsA(ObjectTypeFlags.Item)) { items++; if (obj.IsA(ObjectTypeFlags.Container)) conts++; } else if (obj.IsA(ObjectTypeFlags.Unit)) { units++; if (obj.IsA(ObjectTypeFlags.Player)) plrs++; } else if (obj.IsA(ObjectTypeFlags.GameObject)) gos++; else other++; //if (obj.Type != WowObjectType.Player) // continue; //if (obj.Guid != Game.ObjMgr.ActivePlayer) // continue; ListViewItem itm = listView1.Items.Add(new ListViewItem(new string[] { obj.ToString(), obj.Type.ToString(), obj.VisibleGuid.ToString(), obj.Entry.ToString(), obj.Scale.ToString(), GetObjInfo(obj) })); itm.Tag = obj.Guid; } bool showSelf = false; if (showSelf) { var pl = Game.ObjMgr.ActivePlayerObj; ListViewItem lvItm = listView1.Items.Add(new ListViewItem(new string[] { pl.ToString(), pl.Type.ToString(), pl.VisibleGuid.ToString(), pl.Entry.ToString(), pl.Scale.ToString(), GetObjInfo(pl) })); lvItm.Tag = pl.Guid; } label1.Text = total.ToString(); label4.Text = String.Format("{0} ({1} players)", units, plrs); label6.Text = gos.ToString(); label8.Text = String.Format("{0} ({1} containters)", items, conts); label10.Text = other.ToString(); }