예제 #1
0
        public void CheckConnectionToLocalMongoDB()
        {
            MongoDB mongo    = new MongoDB();
            var     isActive = mongo.CheckConnection();

            Assert.IsTrue(isActive);
        }
예제 #2
0
        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);
        }
예제 #4
0
        /// <summary>
        /// 获取一个实例
        /// </summary>
        /// <returns></returns>
        public static WebLoader GetInstance()
        {
            var inst = new WebLoader();

            inst.mongo = MongoDB.GetInst("mongodb://192.168.0.140:27017");
            return(inst);
        }
예제 #5
0
        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);
     }
 }
예제 #7
0
 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);
 }
예제 #8
0
        private void AddDataBase(MongoDB.Driver.MongoDatabase mongoDatabase)
        {
            //throw new NotImplementedException();
            if (MessageBox.Show("MongoDB不需要专门建立数据库,是否输入数据?", "提示", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {

            }
        }
예제 #9
0
        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);
        }
예제 #10
0
 public BlogFrm(MongoDB.IMongoCollection<Post> coleccion)
 {
     InitializeComponent();
     this.coleccion = coleccion;
     gridComentarios.AutoGenerateColumns = false;
     gridPosts.AutoGenerateColumns = false;
     posts = coleccion.Linq().ToList();
 }
예제 #11
0
        private bool TableExists(string _TableName)
        {
            var filter  = new BsonDocument("name", _TableName);
            var options = new ListCollectionNamesOptions {
                Filter = filter
            };

            return(MongoDB.ListCollectionNames(options).Any());
        }
예제 #12
0
 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;
 }
예제 #13
0
        // GET: Toy
        public ActionResult Index()
        {
            MongoDB db    = new MongoDB();
            var     toys  = db.GetAllToy();
            Toys    model = new Toys();

            model.EntityList = toys.ToList();

            return(View(model));
        }
예제 #14
0
        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);
        }
예제 #15
0
        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);
        }
예제 #16
0
        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);
        }
예제 #17
0
        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);
        }
예제 #18
0
        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);
        }
예제 #19
0
        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);
        }
예제 #20
0
        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);
        }
예제 #21
0
        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);
        }
예제 #22
0
        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();
        }
예제 #23
0
        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);
        }
예제 #24
0
        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"));
        }
예제 #25
0
        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);
        }
예제 #26
0
        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;
        }
예제 #27
0
 // 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"));
     }
 }
예제 #28
0
 // 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"));
     }
 }
예제 #29
0
        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} ");
            }
        }
예제 #30
0
 /// <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);
     }
 }
예제 #31
0
        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);
        }
예제 #32
0
        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);
        }
예제 #33
0
        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);
            }
        }
예제 #34
0
        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;
        }
예제 #35
0
        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);
            }
        }
예제 #36
0
        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);
        }
예제 #37
0
        /// <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;
        }
예제 #38
0
        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);
        }
예제 #39
0
        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);
        }
예제 #40
0
        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());
        }
예제 #41
0
 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"));
     }
 }
예제 #42
0
        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);
                    }
                }
            }
        }
예제 #43
0
        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
        }
예제 #44
0
 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);
         }
     }
 }
예제 #45
0
 internal LastError(MongoDB.Driver.LastError lastError)
     : base(lastError.ErrorMessage)
 {
     ActualLastError = lastError;
 }
예제 #46
0
 private void AddIndex(MongoDB.Driver.MongoDatabase mongoDatabase)
 {
     //throw new NotImplementedException();
 }
예제 #47
0
 public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, System.Type nominalType, IBsonSerializationOptions options)
 {
     return Deserialize(bsonReader, nominalType, nominalType, options);
 }
예제 #48
0
        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);
                }
            }
        }
예제 #49
0
 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");
 }
예제 #51
0
 public void MoveToPossibleModified(MongoDB.Driver.Document original)
 {
     this.State = TrackedEntityState.PossiblyModified;
     this.Original = original;
 }
예제 #52
0
 public abstract void    Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, System.Type nominalType, object value,IBsonSerializationOptions options);
예제 #53
0
 public abstract object  Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, System.Type nominalType, System.Type actualType, IBsonSerializationOptions options);
예제 #54
0
 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();
     }
 }
예제 #55
0
        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()));
        }
예제 #56
0
 public fAddUser(MongoDB.Driver.MongoDatabase mongoDatabase)
 {
     InitializeComponent();
     db = mongoDatabase;
     Text = "Add User For DB:" + mongoDatabase.Name;
 }
예제 #57
0
        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();
        }
예제 #58
0
        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;
        }
예제 #59
0
        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;
        }
예제 #60
0
 public void SetCurrentDB(MongoDB.Driver.Database database)
 {
     _currentDB = database;
 }