public void CheckConnectionToLocalMongoDB() { MongoDB mongo = new MongoDB(); var isActive = mongo.CheckConnection(); Assert.IsTrue(isActive); }
public bool validarEgreso(int id_egreso) { using (var context = new MySql()) { var egreso = context.egresos .Single(e => e.id_egreso == id_egreso); bool validacion; if (egreso.id_proyecto != 0) { egreso = context.egresos .Include("items") .Include("presupuestos") .Include("proyecto") .Single(e => e.id_egreso == id_egreso); } else { egreso = context.egresos .Include("items") .Include("presupuestos") .Single(e => e.id_egreso == id_egreso); } egreso.criterioDeSeleccion = new MenorValor(); MongoDB.getInstancia().agregarBandejaAEgresoEnCasoQueNoLaTengaAsignada(egreso); validacion = ValidadorDeEgreso.egresoValido(egreso); MongoDB.getInstancia().actualizarBandejaDeMensajesNoSQL(egreso); return(validacion); } }
public override void Build(MongoDB.Bson.BsonDocument bsonPanelSetOrder, int panelSetId) { base.Build(bsonPanelSetOrder, panelSetId); string reportNo = bsonPanelSetOrder.GetValue("ReportNo").ToString(); MongoCollection surgicalSpecimenTable = this.m_SQLTransferDatabase.GetCollection<BsonDocument>("tblSurgicalSpecimen"); MongoCursor mongoCursor = surgicalSpecimenTable.FindAs<BsonDocument>(Query.EQ("ReportNo", reportNo)); BsonArray bsonArray = new BsonArray(); foreach (BsonDocument bsonSurgicalSpecimen in mongoCursor) { string surgicalSpecimenId = bsonSurgicalSpecimen.GetValue("SurgicalSpecimenId").AsString; this.BuildIC(bsonSurgicalSpecimen, surgicalSpecimenId); this.BuildStainResult(bsonSurgicalSpecimen, surgicalSpecimenId); this.BuildICD9BillingCode(bsonSurgicalSpecimen, surgicalSpecimenId); bsonArray.Add(bsonSurgicalSpecimen); } bsonPanelSetOrder.Add("SurgicalSpecimenCollection", bsonArray); MongoCollection surgicalAuditTable = this.m_SQLTransferDatabase.GetCollection<BsonDocument>("tblSurgicalAudit"); MongoCursor surgicalAuditCursor = surgicalAuditTable.FindAs<BsonDocument>(Query.EQ("ReportNo", reportNo)); BsonArray surgicalAuditArray = new BsonArray(); foreach (BsonDocument bsonSurgicalAudit in surgicalAuditCursor) { string surgicalAuditId = bsonSurgicalAudit.GetValue("SurgicalAuditId").AsString; this.BuildSurgicalSpecimenAudit(bsonSurgicalAudit, surgicalAuditId); surgicalAuditArray.Add(bsonSurgicalAudit); } bsonPanelSetOrder.Add("SurgicalAuditCollection", surgicalAuditArray); }
/// <summary> /// 获取一个实例 /// </summary> /// <returns></returns> public static WebLoader GetInstance() { var inst = new WebLoader(); inst.mongo = MongoDB.GetInst("mongodb://192.168.0.140:27017"); return(inst); }
public void ShouldReturnsAllUsers() { MongoDB mongo = new MongoDB(); var users = mongo.GetAllUsers(); CollectionAssert.AllItemsAreUnique(users); }
protected override void OnBuildIndex(MongoDB.Driver.Builders.IndexKeysBuilder builder) { foreach (var wellKnownTagName in wellKnownTagNames) { builder.Ascending("Tags." + wellKnownTagName); } }
public static void Set(MongoDB.Driver.MongoClient c, String k, BsonDocument v) { var db = c.GetServer().GetDatabase("db"); var coll = db.GetCollection(k); Entity entity = new Entity { data = v, _id = k}; coll.Save(entity); }
private void AddDataBase(MongoDB.Driver.MongoDatabase mongoDatabase) { //throw new NotImplementedException(); if (MessageBox.Show("MongoDB不需要专门建立数据库,是否输入数据?", "提示", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { } }
public List <BO.BuoiHoc.BuoiHoc> GetListBuoiHocByLopHoc(BO.GiangVien.LopHoc lh) { var collection = MongoDB <BO.BuoiHoc.BuoiHoc> .GetCollection(Config.BUOI_HOC_COLLECTION); List <BO.BuoiHoc.BuoiHoc> listBuoiHoc = collection.Find(x => lh.DSBuoiHoc.Contains(x._id)).ToList(); return(listBuoiHoc); }
public BlogFrm(MongoDB.IMongoCollection<Post> coleccion) { InitializeComponent(); this.coleccion = coleccion; gridComentarios.AutoGenerateColumns = false; gridPosts.AutoGenerateColumns = false; posts = coleccion.Linq().ToList(); }
private bool TableExists(string _TableName) { var filter = new BsonDocument("name", _TableName); var options = new ListCollectionNamesOptions { Filter = filter }; return(MongoDB.ListCollectionNames(options).Any()); }
public static Object Get(MongoDB.Driver.MongoClient c, String k) { var db = c.GetServer().GetDatabase("db"); var coll = db.GetCollection(k); var query = Query<Entity>.EQ(e => e._id, k); var entity = coll.FindOne(query); var v = entity.GetElement("data"); //return read_string.invoke(v.Value.ToString()); return v.Value; }
// GET: Toy public ActionResult Index() { MongoDB db = new MongoDB(); var toys = db.GetAllToy(); Toys model = new Toys(); model.EntityList = toys.ToList(); return(View(model)); }
public UsuarioDAO Add(Usuario user) { using (var context = new MySql()) { context.usuarios.Add(user); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha creado un usuario de id:{user.id}"); } return(this); }
public CriterioCategoriaDAO AddCriterioPorItem(Criterio e) { using (var context = new MySql()) { context.criterios.Add(e); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha creado un nuevo criterio: {e.descripcion}"); } return(this); }
public ItemDAO AddItem(Item i) { using (var context = new MySql()) { context.items.Add(i); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha creado un item de id:{i.id_item}"); } return(this); }
public PresupuestoDAO Add(Presupuesto e) { using (var context = new MySql()) { context.presupuestos.Add(e); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha creado un presupuesto de id:{e.id_presupuesto}"); } return(this); }
public void LuuLopHoc(BO.GiangVien.GiangVien gv, BO.GiangVien.LopHoc lh) { var collection = MongoDB <BO.GiangVien.GiangVien> .GetCollection(Config.GIANG_VIEN_COLLECTION); var filter = Builders <BO.GiangVien.GiangVien> .Filter.Eq(s => s.MaGv, gv.MaGv); var update = Builders <BO.GiangVien.GiangVien> .Update.Push <BO.GiangVien.LopHoc>(x => x.DSLopHoc, lh); collection.FindOneAndUpdate(filter, update); }
public CriterioCategoriaDAO AddCategoria(Categoria e) { using (var context = new MySql()) { context.categorias.Add(e); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha creado una nueva categoria para items de id:{e.id_categoria}"); } return(this); }
public Ingreso Add(Ingreso ingreso) { using (var context = new MySql()) { context.ingresos.Add(ingreso); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha creado un ingreso de id:{ingreso.id_ingreso}"); } return(ingreso); }
public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, System.Type nominalType, IBsonSerializationOptions options) { bsonReader.ReadStartArray(); var x = bsonReader.ReadDouble(); var y = bsonReader.ReadDouble(); bsonReader.ReadEndArray(); return new Vector(x, y); }
public void Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, System.Type nominalType, object value, IBsonSerializationOptions options) { var vector2 = (Vector) value; bsonWriter.WriteStartArray(); bsonWriter.WriteDouble(vector2.X); bsonWriter.WriteDouble(vector2.Y); bsonWriter.WriteEndArray(); }
public List <BO.GiangVien.GiangVien> GetListOnLyGiangVien() { List <BO.GiangVien.GiangVien> dsGiangVien = new List <BO.GiangVien.GiangVien>(); dsGiangVien = MongoDB <BO.GiangVien.GiangVien> .GetCollection(Config.GIANG_VIEN_COLLECTION) .Find(x => true) .Project <BO.GiangVien.GiangVien>("{ ho_gv:1, ten_gv:1, _id:1}") .ToList(); return(dsGiangVien); }
public ActionResult Save(TypeStatus typeStatus, string id) { if (Session["IsAdmin"] != null || typeStatus.Equals(TypeStatus.Done)) { if (string.IsNullOrWhiteSpace(typeStatus.ToString())) { throw new MissingFieldException("fill all the fields"); } bool result; MongoDB db = new MongoDB(); var Order = db.GetOrder(id); Orders toyModel = new Orders(); toyModel.ToyList = Order.ToyKids; Toy toy = new Toy(); var query = toyModel.ToyList.GroupBy(x => x) .Select(y => new { Element = y.Key, Counter = y.Count() }) .ToList(); foreach (var toyRequest in query) { toy = db.GetToy(toyRequest.Element.ToyName); if (toy.Amount <= toyRequest.Counter) { ModelState.AddModelError("", "Order no Avaible"); return(RedirectToAction("Details", id)); } } if (string.IsNullOrWhiteSpace(id)) { Order requestkid = new Order(); } result = db.UpdateOrder(new Order { ID = id, Status = typeStatus }); foreach (var toyRequest in toyModel.ToyList) { toy = db.GetToy(toyRequest.ToyName); result = db.UpdateToy(toy); if (toy.Amount == 0) { db.RemoveToy(toy.ID); } } return(RedirectToAction("Index", new { result = result })); } return(RedirectToAction("../Users/Login")); }
public BO.GiangVien.GiangVien LuuGiangVien(BO.GiangVien.GiangVien gv) { var collection = MongoDB <BO.GiangVien.GiangVien> .GetCollection(Config.GIANG_VIEN_COLLECTION); BO.GiangVien.GiangVien gvv = collection.Find(x => x.MaGv == gv.MaGv).SingleOrDefault(); if (gvv == null) { collection.InsertOne(gv); return(gv); } return(gvv); }
public static byte[] DownloadFile(MongoGridFs gridFs, MongoDB.Bson.ObjectId id) { byte[] buffer = null; using (System.IO.Stream file = gridFs.GetFile(id)) { buffer = new byte[file.Length]; // note - you'll probably want to read in // small blocks or stream to avoid // allocating large byte arrays like this file.Read(buffer, 0, (int)file.Length); } // End Using file return buffer; }
// GET: Toys public ActionResult Index() { if (Session["IsAdmin"] != null) { MongoDB db = new MongoDB(); var toys = db.GetAllToys(); Toys model = new Toys(); model.EntityList = toys.ToList(); return(View(model)); } else { return(RedirectToAction("Login", "Users")); } }
// GET: RequestKid public ActionResult Index() { if (Session["IsAdmin"] != null) { MongoDB db = new MongoDB(); var orders = db.GetAllOreders(); Orders model = new Orders(); model.EntityList = orders.ToList(); return(View(model)); } else { return(RedirectToAction("../Users/Login")); } }
public void vincularEgresoConProyecto(int id_proyecto, int id_egreso) { using (var context = new MySql()) { var i = context.egresos.Single(ing => ing.id_egreso == id_egreso); var p = context.proyectos.Single(pr => pr.id == id_proyecto); i.proyecto = p; context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha agregado un nuevo proyecto de id: {p.id} al egreso de id:{i.id_egreso} "); } }
/// <summary> /// /// <para>TryCreateTable</para> /// /// <para>If given table (collection) does not exist in the database, it will create a new table (collection)</para> /// /// /// </summary> private bool TryCreateTable(string _TableName, Action <string> _ErrorMessageAction = null) { try { if (!TableExists(_TableName)) { MongoDB.CreateCollection(_TableName); } return(true); } catch (System.Exception ex) { _ErrorMessageAction?.Invoke($"BDatabaseServiceMongoDB->TryCreateTable: Given table(collection) couldn't create. Error: {ex.Message} \n Trace: {ex.StackTrace}"); return(false); } }
public ItemDAO AgregarCriterioItem(Item item, Categoria categoria, Criterio criterio) { using (var context = new MySql()) { var item_cc = new CriterioCategoriaPorItem(); item_cc.item = item; item_cc.categoria_item = categoria; item_cc.criterio_item = criterio; context.item_categoria_criterio.Add(item_cc); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha ascodiado la categoria {categoria.descripcion} al item {item.descripcion}"); } return(this); }
public DatabaseContext(DatabaseSettings settings) { MongoClient client = new MongoClient(settings.ConnectionString); MongoDB = client.GetDatabase(settings.DatabaseName); bool isActiveServer = MongoDB.RunCommandAsync((Command <BsonDocument>) "{ping:1}") .Wait(settings.ServerResponeWaitTime); if (!isActiveServer) { throw new Exception("Mongo server didnt respond: check if the server is running"); } Predmet = MongoDB.GetCollection <PredmetModel>(settings.PredmetCollectionName); Rociste = MongoDB.GetCollection <RocisteModel>(settings.RocisteCollectionName); }
public async Task Add() { var connectionString = "mongodb://*****:*****@localhost:32772/Challenge"; var client = new Client { Name = "Pedro dos Testes", Cpf = "308.929.540-78", Estate = "PR" }; using (var mongo = new MongoDB(connectionString, "Client", "Challenge")) { await mongo.Add(client); } }
public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) { IDictionary<String, Object> dict = new Dictionary<String, Object>(); bsonReader.ReadStartDocument(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var elementName = bsonReader.ReadName(); var pi = nominalType.GetProperty(elementName); if (pi != null) { dynamic data = null; if (bsonReader.CurrentBsonType.Equals(BsonType.Null)) { bsonReader.ReadNull(); } else { data = BsonDefaultSerializer.Instance.GetSerializer(pi.PropertyType).Deserialize(bsonReader, pi.PropertyType, options); this.GetType().GetProperty(pi.Name).SetValue(this, data, null); } } else { if (bsonReader.CurrentBsonType.Equals(BsonType.Null)) { bsonReader.SkipValue(); continue; } if (dict.Keys.Contains("elementName")) { dict[elementName] = GetBsonString(ref bsonReader); } else { dict.Add(elementName, GetBsonString(ref bsonReader)); } } } bsonReader.ReadEndDocument(); SetDynamics(dict); return this; }
public ProyectoDeFinanciamiento cargarProyecto(int cant, int monto, string usuario) { using (var context = new MySql()) { var u = context.usuarios.Single(us => us.nombre == usuario); var nuevo = new ProyectoDeFinanciamiento(cant, monto, u); context.proyectos.Add(nuevo); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha creado un proyecto de financiamiento de id:{nuevo.id}"); return(nuevo); } }
public ProyectoDAO bajaProyecto(int id_proyecto) { using (var context = new MySql()) { var p = context.proyectos.Single(pr => pr.id == id_proyecto); p.cerrarProyecto(); context.proyectos.Remove(p); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"El proyecto de id:{p.id} se ha dado de baja"); } return(this); }
/// <summary> /// For a given VHO #, add any new unique AltCodes into our member vho /// When completed a VHO, cache this in the DB /// </summary> /// <param name="vhoNumber"></param> public async Task<bool> AddUniqueFromVHOAsync(MongoDB.Driver.IMongoCollection<CatalogObject> collection) { Dictionary<string, CatalogObject> vho = new Dictionary<string, CatalogObject>(); string path = GetTemplate(vhoNumber, "d:\\img\\img\\", new DateTime(2015, 7, 21)); if (path != string.Empty) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Processing VHO : " + vhoNumber); Console.ForegroundColor = ConsoleColor.White; try { String tempFile = Decompress(path); using (StreamReader file = new System.IO.StreamReader(tempFile, Encoding.UTF8)) { string line; while ((line = await file.ReadLineAsync()) != null) { CatalogObject json = JsonConvert.DeserializeObject<CatalogObject>(line); if ((json.AltCode == string.Empty))//blank AltCode, prob single screen { if (singleScreen) { //Use the PID PAID since the AltCode is missing json.AltCode = json.ProviderID + ":" + json.ProviderAssetID.Substring(4); await AddMediaAsync(collection, json); } } else if (multiScreen) { await AddMediaAsync(collection, json); } } } } catch (Exception ex) { Console.WriteLine("Exception caught opening file :" + ex.Message); } } //and Upsert the vho! //await collection.InsertManyAsync(vho.Values); return true; }
public PresupuestoDAO elegirPresupuesto(int id_egreso, int id_presupuesto) { using (var context = new MySql()) { var egreso = context.egresos .Include("items") .Include("presupuestos") .Single(e => e.id_egreso == id_egreso); var presupuesto = context.presupuestos.Include("itemsDePresupuesto").Include("proveedor").Single(e => e.id_presupuesto == id_presupuesto); egreso.elegirPresupuesto(presupuesto); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha seleccionado el presupuesto de id:{egreso.presupuestoElegido.id_presupuesto} al egreso de id:{egreso.id_egreso}"); } return(this); }
public ProyectoDAO vincularIngresoConProyecto(int id_proyecto, int id_ingreso) { using (var context = new MySql()) { var i = context.ingresos.Single(ing => ing.id_ingreso == id_ingreso); var p = context.proyectos.Single(pr => pr.id == id_proyecto); i.proyecto = p; p.agregarIngreso(i); context.SaveChanges(); MongoDB.getInstancia().agregarLogABitacora($"Se ha agregado un nuevo ingreso de id: {i.id_ingreso} al proyecto de id:{p.id} "); } return(this); }
public ActionResult Login(User user) { user.Password = Encrypt(user.Password); MongoDB db = new MongoDB(); var account = db.GetUser(user); if (account != null) { Session["email"] = account.Email.ToString(); Session["id"] = account.ID.ToString(); Session["username"] = account.UserName.ToString(); Session["isadmin"] = account.IsAdmin.ToString(); return(RedirectToAction($"../Home")); } else { ModelState.AddModelError("", "Email or Password Error"); } return(View()); }
public ActionResult Edit(string id) { if (Session["IsAdmin"] != null && Session["IsAdmin"].Equals(false)) { MongoDB db = new MongoDB(); var orders = db.GetOrder(id); //utile per estrarre tutti i giochi richiesti dal bambino Orders modelToy = new Orders(); modelToy.ToyList = orders.ToyKids; Toy toy = new Toy(); //utile per passare alla view lo stato dell ordine Order model = new Order(); model.Status = orders.Status; return(View(model)); } else { return(RedirectToAction("../Users/Login")); } }
async System.Threading.Tasks.Task FindAll(MongoDB.Driver.IMongoCollection<AlertType> collection, List<AlertType> results ) { results = new List<AlertType>(); var filter = new MongoDB.Bson.BsonDocument(); var count = 0; using (var cursor = await collection.FindAsync<AlertType>(filter,null)) { while (await cursor.MoveNextAsync()) { var batch = cursor.Current; foreach (var document in batch) { // process document count++; results.Add(document); } } } }
public static void DownloadFile(MongoGridFs gridFs, MongoDB.Bson.ObjectId id, string path) { using (System.IO.Stream file = gridFs.GetFile(id)) { int bytesRead = 0; int offset = 0; const int BUFFER_SIZE = 1024 * 1024 * 10; byte[] buffer = new byte[BUFFER_SIZE]; using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create)) { while ((bytesRead = (int)file.Read(buffer, offset, BUFFER_SIZE)) > 0) { fs.Write(buffer, 0, bytesRead); offset += bytesRead; } // Whend fs.Close(); } // End Using fs } // End Using file }
private void TreeTree(MongoDB.Bson.BsonDocument bd, DevComponents.AdvTree.Node nd) { //throw new NotImplementedException(); foreach (MongoDB.Bson.BsonElement be in bd.Elements) { if (be.Value.IsBsonDocument) { DevComponents.AdvTree.Node nddd = new DevComponents.AdvTree.Node(be.Name); nddd.Cells.Add(new DevComponents.AdvTree.Cell()); nddd.Cells.Add(new DevComponents.AdvTree.Cell(be.Value.BsonType.ToString())); nd.Nodes.Add(nddd); TreeTree((MongoDB.Bson.BsonDocument)be.Value, nddd); } else { DevComponents.AdvTree.Node ndd = new DevComponents.AdvTree.Node(be.Name); ndd.Cells.Add(new DevComponents.AdvTree.Cell(be.Value.AsString)); ndd.Cells.Add(new DevComponents.AdvTree.Cell(be.Value.BsonType.ToString())); nd.Nodes.Add(ndd); } } }
internal LastError(MongoDB.Driver.LastError lastError) : base(lastError.ErrorMessage) { ActualLastError = lastError; }
private void AddIndex(MongoDB.Driver.MongoDatabase mongoDatabase) { //throw new NotImplementedException(); }
public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, System.Type nominalType, IBsonSerializationOptions options) { return Deserialize(bsonReader, nominalType, nominalType, options); }
private void MakeTree(MongoDB.Bson.BsonDocument bd, DevComponents.AdvTree.AdvTree avt,int i) { //throw new NotImplementedException(); DevComponents.AdvTree.Node nd =new DevComponents.AdvTree.Node(); nd.Text = "(" + i.ToString() + "){.}"; nd.Cells.Add(new DevComponents.AdvTree.Cell()); DevComponents.AdvTree.Cell c = new DevComponents.AdvTree.Cell(); c.Text = bd.BsonType.ToString(); nd.Cells.Add(c); avt.Nodes.Add(nd); foreach (MongoDB.Bson.BsonElement be in bd.Elements) { if (be.Value.IsBsonDocument) { DevComponents.AdvTree.Node nddd = new DevComponents.AdvTree.Node(be.Name); nddd.Cells.Add(new DevComponents.AdvTree.Cell()); nddd.Cells.Add(new DevComponents.AdvTree.Cell(be.Value.BsonType.ToString())); nd.Nodes.Add(nddd); TreeTree((MongoDB.Bson.BsonDocument)be.Value, nddd); } else { DevComponents.AdvTree.Node ndd = new DevComponents.AdvTree.Node(); ndd.Text = be.Name; DevComponents.AdvTree.Cell cc = new DevComponents.AdvTree.Cell(); cc.Text = be.Value.ToString(); ndd.Cells.Add(cc); DevComponents.AdvTree.Cell ccc = new DevComponents.AdvTree.Cell(); ccc.Text = be.Value.BsonType.ToString(); ndd.Cells.Add(ccc); nd.Nodes.Add(ndd); } } }
public static TerrainTile TileFromDocument(MongoDB.Document Doc) { return new TerrainTile() { X = (int)Doc["x"], Y = (int)Doc["y"], TileID = (byte)(int)Doc["tile_type"], Passable = true, }; }
protected override void OnBuildIndex(MongoDB.Driver.Builders.IndexKeysBuilder builder) { builder.GeoSpatial("Location.Center"); }
public void MoveToPossibleModified(MongoDB.Driver.Document original) { this.State = TrackedEntityState.PossiblyModified; this.Original = original; }
public abstract void Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, System.Type nominalType, object value,IBsonSerializationOptions options);
public abstract object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, System.Type nominalType, System.Type actualType, IBsonSerializationOptions options);
private void MakeUsers(TreeNode treeNode, MongoDB.Driver.MongoDatabase mongoDatabase, bool bRefresh) { //throw new NotImplementedException(); if (bRefresh) treeNode.Nodes.Clear(); if (treeNode.Nodes.Count <= 0) { Log("db.system.users.find()"); foreach (MongoDB.Driver.MongoUser mu in mongoDatabase.FindAllUsers()) { Data.MTag mt = new Data.MTag(Data.Data.DbCludes.user); mt.tag = mu; TreeNode tn = new TreeNode(mu.Username); tn.ImageIndex = (int)Data.Data.DbCludes.user; tn.SelectedImageIndex = (int)Data.Data.DbCludes.user; tn.Tag = mt; treeNode.Nodes.Add(tn); } treeNode.ExpandAll(); } }
protected void WhenReceiveDocument(MongoDB.Bson.BsonDocument userDoc) { string userName = this.textBox_name.Text; string userPassword = this.textBox_password.Text; // 아이피 얻어옴 var hostIPList = Util.Utility.GetHostIPList(); // 아이피 배열 만듬 MongoDB.Bson.BsonArray ipArr = new MongoDB.Bson.BsonArray(hostIPList); if (userDoc == null) { var selection = MessageBox.Show(@"해당 계정이 없습니다. 현재 정보로 가입하시겠습니까? ※ 자주 쓰시는 계정정보로 설정하시면 보안문제가 있을 수 있습니다.", "Login Error!", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (selection == DialogResult.Yes) { RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.GenerateKey(); List<MongoDB.Bson.BsonDocument> overlapDocList; // 계정 중복 확인 if (m_db.CheckCountIf("Users", "Unique", ipArr, out overlapDocList) > 0) { // 중복 var retryResult = MessageBox.Show(@"동일한 IP로 등록된 다른 계정이 존재하여 진행할 수 없습니다. 이전 계정을 삭제하고 이 정보로 다시 가입을 시도하시겠습니까? ※ 이전 계정이 소유한 타일은 전부 초기화됩니다.", "Login Error!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (retryResult == DialogResult.Yes) { DeleteUser(overlapDocList); } else { EnableUI(); return; } } // 개인정보수집 동의 if (MessageBox.Show(@"[안내] 계정의 중복을 확인하기 위해서 로그인시 현재 PC의 IP주소와 MAC주소를 DB로 전송합니다. 계정의 정보를 확인하는 것 외의 목적으로 사용되지 않습니다. 동의하시겠습니까?", "Agreement", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { EnableUI(); return; } // 계정정보 암호화 string encryptKey = BitConverter.ToString(aes.Key).Replace("-", ""); string encryptedPass = Util.EncoderDecoder.Encode(userPassword, aes.Key); // 계정 생성 userDoc = m_db.CreateDocument("Users", userName, new MongoDB.Bson.BsonDocument { { "Name", userName }, { "Pass", encryptedPass }, { "Key", encryptKey }, { "Unique", ipArr } }); // 계정 생성 실패시 if (userDoc == null) { MessageBox.Show("계정을 생성할 수 없습니다.", "DB Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); EnableUI(); return; } } else { EnableUI(); return; } } else { // 암호화된 암호 해독 string encryptKey = userDoc["Key"].AsString; string decryptedPass = Util.EncoderDecoder.Decode(userDoc["Pass"].AsString, Enumerable.Range(0, encryptKey.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(encryptKey.Substring(x, 2), 16)) .ToArray()); // 로그인 정보 대조 if (userDoc["Name"] != userName || decryptedPass != userPassword) { MessageBox.Show("로그인 정보가 올바르지 않습니다.", "Login Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning); EnableUI(); return; } else { // 계정의 아이피 정보 갱신 if (userDoc["Unique"] != ipArr) { userDoc["Unique"] = ipArr; m_db.UpdateDocument("Users", userName, userDoc); } // 계정 중복 확인 List<MongoDB.Bson.BsonDocument> overlapDocList; if (m_db.CheckCountIf("Users", "Unique", ipArr, out overlapDocList) > 1) { var retryResult = MessageBox.Show(@"동일한 IP로 등록된 다른 계정이 존재하여 진행할 수 없습니다. 이전 계정을 삭제하고 이 정보로 다시 가입을 시도하시겠습니까? ※ 이전 계정이 소유한 타일은 전부 초기화됩니다.", "Login Error!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (retryResult == DialogResult.Yes) { // 현재 계정은 삭제될 계정 목록에서 제거 overlapDocList.RemoveAll(delegate (MongoDB.Bson.BsonDocument doc) { return (doc["Name"] == userName); }); DeleteUser(overlapDocList); } else { EnableUI(); return; } } } } // 여기까지 왔으면 로그인 성공 EnableUI(); // 자동 로그인 정보 갱신 this.Invoke(new MethodInvoker(() => this.UpdateAutoLogin())); // 게임 화면 띄우기 this.Invoke(new MethodInvoker(() => this.SequenceToGame())); }
public fAddUser(MongoDB.Driver.MongoDatabase mongoDatabase) { InitializeComponent(); db = mongoDatabase; Text = "Add User For DB:" + mongoDatabase.Name; }
private List<BaseSearchableEnabledItem> FillGeoSearchItems(MongoDB.Driver.GeoNearResult<RestaurantBasicData> geoResults, Location sourceLocation) { List<BaseSearchableEnabledItem> returnValue = new List<BaseSearchableEnabledItem>(); foreach (var result in geoResults.Hits) { BaseSearchableEnabledItem item = result.Document; Location targetLocation = item.ItemLocation; //Check if it is possible to produce on mongodb part //http://api.mongodb.org/wiki/current/Geospatial%20Indexing.html item.Distance = CalcDistance(sourceLocation, targetLocation); returnValue.Add(item); } return returnValue.OrderBy(s => s.Distance).ToList(); }
public void FromBsonDocument(MongoDB.Bson.BsonDocument doc) { this.Owner = doc["Owner"].AsString; this.Power = doc["Power"].AsInt32; this.Sign = doc["Sign"].AsString; this.IsLastVersion = true; }
private List<BaseSearchableEnabledItem> FillGeoSearchItems(MongoDB.Driver.GeoNearResult<RestaurantBasicData> geoResults) { List<BaseSearchableEnabledItem> returnValue = new List<BaseSearchableEnabledItem>(); foreach (var result in geoResults.Hits) { BaseSearchableEnabledItem item = result.Document; item.Distance = result.Distance; returnValue.Add(item); } return returnValue; }
public void SetCurrentDB(MongoDB.Driver.Database database) { _currentDB = database; }