コード例 #1
0
        public ActionResult Create(String id, FormCollection collection)
        {
            try {
                // TODO: Add insert logic here
                DataAccess.Entity.Component nComponent = new DataAccess.Entity.Component();

                nComponent.Name = "New";

                //Get the associated device
                var bSonId = new MongoDB.Bson.ObjectId(id);
                var query  = Query <HomeAutomation.DataAccess.Entity.Device> .EQ(e => e.Id, bSonId);

                nComponent.Device = DataAccess.DatabaseFacade.DatabaseManager.Devices.FindOne(query);

                nComponent.Type = DataAccess.DatabaseFacade.DatabaseManager.ComponentTypes.AsQueryable().Single(u => u.Category == collection["Type"] & u.Mode == collection["SubType"]);
                if (nComponent.Type.TemplateOptions != null)
                {
                    nComponent.Options = new Dictionary <string, string>(nComponent.Type.TemplateOptions);
                }
                nComponent.IsActive = false;

                DataAccess.DatabaseFacade.DatabaseManager.Components.Insert(nComponent);

                var device = nComponent.Device;
                device.ComponentIds.Add(new MongoDB.Driver.MongoDBRef("Component", nComponent.Id));

                DataAccess.DatabaseFacade.DatabaseManager.Devices.Save(device);

                return(RedirectToAction("Edit", new { id = nComponent.Id }));
                //return View("Edit", nComponent);
            } catch {
                return(View());
            }
        }
コード例 #2
0
        public byte[] DownloadFile(MongoDB.Bson.ObjectId id)
        {
            var bucket = new GridFSBucket(getDatabase());
            var file   = bucket.DownloadAsBytes(id);

            return(file);
        }
コード例 #3
0
        public void GetValueWithId_CacheExists_Returns()
        {
            var objectId            = new MongoDB.Bson.ObjectId();
            var configurationRecord = new ConfigurationRecord()
            {
                Value = "boyner.com.tr",
                Type  = "String",
                GuId  = objectId,
                Name  = "site"
            };
            List <ConfigurationRecord> configurationRecords = new List <ConfigurationRecord>()
            {
                new ConfigurationRecord()
                {
                    Name  = "site",
                    Value = "boyner.com.tr",
                    Type  = "String"
                }
            };

            _configurationStorage.Get(Arg.Any <string>(), applicationName).Returns(configurationRecord);
            _cacheManager.Get <IEnumerable <ConfigurationRecord> >("site").Returns(configurationRecords);

            var manager     = new ConfigurationReader(applicationName, "hede", 10, _configurationStorageFactory, _cacheManagerFactory, _configurationStorage);
            var returnValue = manager.GetValueWithId("site");

            Assert.AreEqual(configurationRecords[0].Value, returnValue.Value);
        }
コード例 #4
0
 /// <summary>
 /// 操作成功
 /// </summary>
 static public ResultView Success(MongoDB.Bson.ObjectId id)
 {
     return(new ResultView()
     {
         Code = 0, Message = id.ToString()
     });
 }
コード例 #5
0
        public async Task DeleteUserById(MongoDB.Bson.ObjectId objectID)
        {
            var result = await _mongoDbRepo.DeleteUserById(objectID);

            Console.WriteLine("Delete is {0}", result ? "Success" : "Failed");
            Console.WriteLine("\n");
        }
        static int _m_Deserialize(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                MongoDB.Bson.Serialization.Serializers.ObjectIdSerializer gen_to_be_invoked = (MongoDB.Bson.Serialization.Serializers.ObjectIdSerializer)translator.FastGetCSObj(L, 1);



                {
                    MongoDB.Bson.Serialization.BsonDeserializationContext _context = (MongoDB.Bson.Serialization.BsonDeserializationContext)translator.GetObject(L, 2, typeof(MongoDB.Bson.Serialization.BsonDeserializationContext));
                    MongoDB.Bson.Serialization.BsonDeserializationArgs    _args; translator.Get(L, 3, out _args);

                    MongoDB.Bson.ObjectId gen_ret = gen_to_be_invoked.Deserialize(_context, _args);
                    translator.Push(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
コード例 #7
0
        public ActionResult Edit(String id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                var bSonId = new MongoDB.Bson.ObjectId(id);
                var query  = Query <HomeAutomation.DataAccess.Entity.Device> .EQ(e => e.Id, bSonId);

                var nDevice = DataAccess.DatabaseFacade.DatabaseManager.Devices.FindOne(query);

                nDevice.Name        = collection["Name"];
                nDevice.Description = collection["Description"];
                nDevice.Location    = collection["Location"];
                nDevice.IPAddress   = collection["IPAddress"];
                nDevice.OwnerEmail  = collection["OwnerEmail"];

                DataAccess.DatabaseFacade.DatabaseManager.Devices.Save(nDevice);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(RedirectToAction("Index"));
            }
        }
コード例 #8
0
        public object SetObjectData(object obj, SerializationInfo info,
                                    StreamingContext context, ISurrogateSelector selector)
        {
            string val    = info.GetString("oid");
            var    result = new MongoDB.Bson.ObjectId(val);

            return(result);
        }
コード例 #9
0
        public void GetObjectData(
            object obj, SerializationInfo info, StreamingContext context)
        {
            MongoDB.Bson.ObjectId oid = (MongoDB.Bson.ObjectId)obj;
            var val = oid.ToString();

            info.AddValue("oid", val);
        }
コード例 #10
0
 public void Log(string message)
 {
     LogCollection.Insert(new NoSqlLog {
         Id        = ObjectId.GenerateNewId(),
         TimeStamp = DateTime.Now,
         Message   = message
     });
 }
コード例 #11
0
        internal ResultBase SendMessage(string userKey, string message, string communityId)
        {
            IMongoCollection <DBEntry.Community> communitiesCollection = Program.Database.GetCollection <DBEntry.Community>("communities");
            IMongoCollection <DBEntry.Message>   messageCollection     = Program.Database.GetCollection <DBEntry.Message>("messages");

            (UserGatewayController.CheckUserResult userResult, DBEntry.User user) = UserGatewayController.CheckUser(userKey);
            if (!userResult.success)
            {
                return(userResult);
            }
            List <DBEntry.Community> communities = communitiesCollection.Find(x => x.UniqueName == communityId).ToList();

            if (communities.Count != 1)
            {
                return(new Api.Result()
                {
                    type = "no community", authorized = true, success = false, message = "community does not exists"
                });
            }
            DBEntry.Community community = communities[0];
            if (!community.Users.Contains(user.Username))
            {
                return(new Api.Result()
                {
                    type = "unauthorized for community", authorized = true, success = false, message = "you are not part of that community"
                });
            }
            MongoDB.Bson.ObjectId objectId = MongoDB.Bson.ObjectId.GenerateNewId();
            messageCollection.InsertOneAsync(new DBEntry.Message()
            {
                Author = user.Username, CommunityId = communityId, Content = message, Ip = Request.HttpContext.Connection.RemoteIpAddress.ToString(), TimeOfSending = DateTime.Now, _id = objectId
            });
            if (RESTMessageDictionary.ContainsKey(community.UniqueName))
            {
                GetMessageResult.Message RESTMessage = new GetMessageResult.Message()
                {
                    author        = user.Username,
                    content       = message,
                    timeOfSending = ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds(),
                    objectId      = objectId.ToString()
                };
                while (RESTMessageDictionary[community.UniqueName].Count != 0)
                {
                    if (!RESTMessageDictionary[community.UniqueName][0].Task.Task.IsCompleted)
                    {
                        RESTMessageDictionary[community.UniqueName][0].Task.SetResult(RESTMessage);
                    }
                    try {
                        RESTMessageDictionary[community.UniqueName].RemoveAt(0);
                    }
                    catch (Exception) { };
                }
            }
            return(new Api.Result()
            {
                type = "successful", authorized = true, success = true, message = "all good"
            });
        }
コード例 #12
0
        static int __CreateInstance(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
                if (LuaAPI.lua_gettop(L) == 2 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING))
                {
                    byte[] _bytes = LuaAPI.lua_tobytes(L, 2);

                    MongoDB.Bson.ObjectId gen_ret = new MongoDB.Bson.ObjectId(_bytes);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 5 && translator.Assignable <System.DateTime>(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 5))
                {
                    System.DateTime _timestamp; translator.Get(L, 2, out _timestamp);
                    int             _machine   = LuaAPI.xlua_tointeger(L, 3);
                    short           _pid       = (short)LuaAPI.xlua_tointeger(L, 4);
                    int             _increment = LuaAPI.xlua_tointeger(L, 5);

                    MongoDB.Bson.ObjectId gen_ret = new MongoDB.Bson.ObjectId(_timestamp, _machine, _pid, _increment);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 5 && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 5))
                {
                    int   _timestamp = LuaAPI.xlua_tointeger(L, 2);
                    int   _machine   = LuaAPI.xlua_tointeger(L, 3);
                    short _pid       = (short)LuaAPI.xlua_tointeger(L, 4);
                    int   _increment = LuaAPI.xlua_tointeger(L, 5);

                    MongoDB.Bson.ObjectId gen_ret = new MongoDB.Bson.ObjectId(_timestamp, _machine, _pid, _increment);
                    translator.Push(L, gen_ret);

                    return(1);
                }
                if (LuaAPI.lua_gettop(L) == 2 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING))
                {
                    string _value = LuaAPI.lua_tostring(L, 2);

                    MongoDB.Bson.ObjectId gen_ret = new MongoDB.Bson.ObjectId(_value);
                    translator.Push(L, gen_ret);

                    return(1);
                }

                if (LuaAPI.lua_gettop(L) == 1)
                {
                    translator.Push(L, default(MongoDB.Bson.ObjectId));
                    return(1);
                }
            }
            catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
            return(LuaAPI.luaL_error(L, "invalid arguments to MongoDB.Bson.ObjectId constructor!"));
        }
コード例 #13
0
        //
        // GET: /Device/Edit/5

        public ActionResult Edit(String id)
        {
            var bSonId = new MongoDB.Bson.ObjectId(id);
            var query  = Query <HomeAutomation.DataAccess.Entity.Device> .EQ(e => e.Id, bSonId);

            var Device = DataAccess.DatabaseFacade.DatabaseManager.Devices.FindOne(query);

            return(View(Device));
        }
コード例 #14
0
        public async Task UpdateUserById(MongoDB.Bson.ObjectId objectId)
        {
            bool isUpdate = await _mongoDbRepo.UpdateUser(objectId, "Age", "100");

            var user = isUpdate ? await _mongoDbRepo.GetUserById(objectId) : null;

            Console.WriteLine("Age is updated to {0}", isUpdate ? user.Age.ToString() : "nothing because it's failed.");
            Console.WriteLine("\n");
        }
コード例 #15
0
        //
        // GET: /Component/Details/5

        public ActionResult Details(String id)
        {
            var bSonId = new MongoDB.Bson.ObjectId(id);
            var query  = Query <HomeAutomation.DataAccess.Entity.Component> .EQ(e => e.Id, bSonId);

            var model = DataAccess.DatabaseFacade.DatabaseManager.Components.FindOne(query);

            return(View(model));
        }
コード例 #16
0
 public void Clear()
 {
     Id             = new MongoDB.Bson.ObjectId();
     CreatedDate    = null;
     GroupCode      = "";
     GroupName      = "";
     PermissionRank = 0;
     AvaliableCommands.Clear();
 }
コード例 #17
0
        public Document ObterDocumentoById(MongoDB.Bson.ObjectId id)
        {
            IMongoDatabase db = getDatabase();

            var filter = Builders <Document> .Filter.Eq("_id", id);

            return(db.GetCollection <Document>("Forms")
                   .Find(filter)
                   .FirstOrDefault());
        }
コード例 #18
0
        //
        // GET: /Device/ListComponent/5

        public ActionResult ListComponent(String id)
        {
            //var model = DataAccess.DatabaseFacade.DatabaseManager.Devices.AsQueryable().SingleOrDefault(u => u.Id.Equals(id));
            //var model = DataAccess.DatabaseFacade.DatabaseManager.Devices.FindOneAs<DataAccess.Entity.Device>(new MongoDB.Driver.FindOneArgs(){F})
            var bSonId = new MongoDB.Bson.ObjectId(id);
            var query  = Query <HomeAutomation.DataAccess.Entity.Device> .EQ(e => e.Id, bSonId);

            var model = DataAccess.DatabaseFacade.DatabaseManager.Devices.FindOne(query);

            return(View(model));
        }
コード例 #19
0
        } // End Sub Test

        public static MongoDB.Bson.ObjectId UploadFile(MongoGridFs gridFs, string fileName)
        {
            MongoDB.Bson.ObjectId id = MongoDB.Bson.ObjectId.Empty;
            // UploadFile
            using (System.IO.Stream file = System.IO.File.OpenRead(fileName))
            {
                id = gridFs.AddFile(file, fileName);
            } // End Using file

            return(id);
        } // End Sub UploadFile
コード例 #20
0
        public async Task <User> FindByIdAsync(string userId, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentNullException(nameof(userId));
            }

            MongoDB.Bson.ObjectId id = new MongoDB.Bson.ObjectId(userId);

            var resultUser = await(from user in _Users.AsQueryable() where user.Id == id select user).FirstOrDefaultAsync(cancellationToken);

            return(resultUser);
        }
コード例 #21
0
        public void TestDouble()
        {
            DataAccess.DatabaseFacade.DatabaseManager.InitializeDatabaseConnection("mongodb://localhost", "HomeAutomation");

            var refDocument = new MongoDB.Bson.ObjectId("53fc96c0f59e1008ace5649d");
            var query       = MongoDB.Driver.Builders.Query <Entity.Component> .EQ(e => e.Id, refDocument);

            var component = DataAccess.DatabaseFacade.DatabaseManager.Components.FindOne(query);

            component.MaxThreshold = 40;

            component.SetNewValue(50);
        }
コード例 #22
0
        internal static void UpdateMail(long p, MongoDB.Bson.ObjectId objectId)
        {
            using (var db = GetContext())
            {
                var dbObj = db.Mails.Where(x => x.Id == p).FirstOrDefault();

                if (dbObj != null)
                {
                    dbObj.MongoId = objectId.ToString();
                    db.SubmitChanges();
                }
            }
        }
コード例 #23
0
ファイル: Default.aspx.cs プロジェクト: ststeiger/MongoUpload
        protected void Unnamed1_Click(object sender, System.EventArgs e)
        {
            string fileName = @"D:\stefan.steiger\Downloads\keywords.xlsx";

            MongoDB.Driver.MongoClient   client   = new MongoDB.Driver.MongoClient("mongodb://localhost/27017/mydb");
            MongoDB.Driver.MongoServer   server   = client.GetServer();
            MongoDB.Driver.MongoDatabase database = server.GetDatabase("testdb");
            MongoGridFs gridFs = new MongoGridFs(database);

            MongoDB.Bson.ObjectId id = MongoGridFsUsage.UploadFile(gridFs, fileName);
            // byte[] baFile = DownloadFile(gridFs, id);
            // DownloadFile(gridFs, id, @"d:\test.rar");
        }
コード例 #24
0
        public void TestInt()
        {
            DataAccess.DatabaseFacade.DatabaseManager.InitializeDatabaseConnection("mongodb://localhost", "HomeAutomation");

            var refDocument = new MongoDB.Bson.ObjectId("53ff1d3e55ed340d04e73091");
            var query       = MongoDB.Driver.Builders.Query <Entity.Component> .EQ(e => e.Id, refDocument);

            var component = DataAccess.DatabaseFacade.DatabaseManager.Components.FindOne(query);

            component.MinThreshold = 0;

            component.SetNewValue(0);
        }
コード例 #25
0
        // http://odetocode.com/blogs/scott/archive/2013/04/16/using-gridfs-in-mongodb-from-c.aspx
        public static void Test()
        {
            string fileName = "clip_image071.jpg";

            MongoDB.Driver.MongoClient   client   = new MongoDB.Driver.MongoClient();
            MongoDB.Driver.MongoServer   server   = client.GetServer();
            MongoDB.Driver.MongoDatabase database = server.GetDatabase("testdb");
            MongoGridFs gridFs = new MongoGridFs(database);


            MongoDB.Bson.ObjectId id = UploadFile(gridFs, fileName);
            byte[] baFile            = DownloadFile(gridFs, id);
            DownloadFile(gridFs, id, @"d:\test.rar");
        } // End Sub Test
コード例 #26
0
        }         // End Sub DownloadFile

        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);
        } // End Function DownloadFile
コード例 #27
0
        static int _m_GenerateNewId_xlua_st_(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);



                int gen_param_count = LuaAPI.lua_gettop(L);

                if (gen_param_count == 0)
                {
                    MongoDB.Bson.ObjectId gen_ret = MongoDB.Bson.ObjectId.GenerateNewId(  );
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 1 && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 1))
                {
                    int _timestamp = LuaAPI.xlua_tointeger(L, 1);

                    MongoDB.Bson.ObjectId gen_ret = MongoDB.Bson.ObjectId.GenerateNewId(_timestamp);
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 1 && translator.Assignable <System.DateTime>(L, 1))
                {
                    System.DateTime _timestamp; translator.Get(L, 1, out _timestamp);

                    MongoDB.Bson.ObjectId gen_ret = MongoDB.Bson.ObjectId.GenerateNewId(_timestamp);
                    translator.Push(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }

            return(LuaAPI.luaL_error(L, "invalid arguments to MongoDB.Bson.ObjectId.GenerateNewId!"));
        }
コード例 #28
0
ファイル: ctrlNotices.cs プロジェクト: thynquest/wfBiblio
 private void btnSupprimerExeplaire_Click(object sender, EventArgs e)
 {
     if (dgvExemplaires.SelectedRows.Count > 0)
     {
         if (MessageBox.Show("Confirmez-vous la suppression de cet exemplaire?", "Suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
         {
             MongoDB.Bson.ObjectId id = MongoDB.Bson.ObjectId.Parse(dgvExemplaires.SelectedRows[0].Cells["id"].Value.ToString());
             Notice notice            = GetNotice();
             if (notice.exemplaires == null)
             {
                 notice.exemplaires = new List <Exemplaire>();
             }
             notice.exemplaires.Remove(notice.exemplaires.Find(a => a._id == id));
             RemplirExemplaires(notice);
         }
     }
 }
コード例 #29
0
ファイル: RequestTests.cs プロジェクト: zzti/DotnetSpider
        public void SerializeAndDeserialize3()
        {
            var hashAlgorithm = new MurmurHashAlgorithmService();
            var ownerId       = ObjectId.GenerateNewId().ToString();
            var r1            = new Request("http://www.a.com")
            {
                Owner = ownerId
            };
            var h1 = r1.ComputeHash(hashAlgorithm);

            var r2 = new Request("http://www.a.com")
            {
                Owner = ownerId
            };
            var h2 = r1.ComputeHash(hashAlgorithm);

            Assert.Equal(h1, h2);
        }
コード例 #30
0
        public String GetDataTableJson(String id)
        {
            DataTable dt = new DataTable();

            var bSonId = new MongoDB.Bson.ObjectId(id);
            var query  = Query <HomeAutomation.DataAccess.Entity.Component> .EQ(e => e.Id, bSonId);

            var model = DataAccess.DatabaseFacade.DatabaseManager.Components.FindOne(query);

            //Act -----------------
            dt.AddColumn(new Column(ColumnType.Datetime, "Date", "Date"));
            dt.AddColumn(new Column(ColumnType.Number, "Value", model.Name));

            // var bSonId = new MongoDB.Driver.MongoDBRef("Component",new MongoDB.Bson.ObjectId( id));
            var refDocument = new MongoDB.Bson.BsonDocument {
                { "$ref", "Component" },
                { "$id", new MongoDB.Bson.ObjectId(id) }
            };
            var queryHist = Query.EQ("ComponentId", refDocument);

            var values = DataAccess.DatabaseFacade.DatabaseManager.ComponentValueHistory.Find(queryHist);


            foreach (var value in values)
            {
                var row = dt.NewRow();
                row.AddCellRange(new[] { new Cell(value.TimeStamp), new Cell(value.Value) });
                dt.AddRow(row);
            }
            var rowCur = dt.NewRow();

            rowCur.AddCellRange(new[] { new Cell(model.LastContact), new Cell(model.CurrentValue) });
            dt.AddRow(rowCur);

            //row1.AddCellRange(new[] { new Cell(2012), new Cell(150) });
            //row2.AddCellRange(new[] { new Cell(2013), new Cell(100) });

            //dt.AddRow(row1);
            //dt.AddRow(row2);

            return(dt.GetJson());
        }
コード例 #31
0
ファイル: ServiceTests.cs プロジェクト: Ancestry/quality-bot
        //[Test]
        public void CanCompareScrapes()
        {
            //Arrange
            var tmpScraper = new Service();
            var tmpScrapeA = tmpScraper.Scrape(new Request("www.ancestry.com"));
            var tmpMongoIdA = new MongoDB.Bson.ObjectId(DateTime.Now, 0, 0, 0);
            tmpScrapeA.Id = tmpMongoIdA;

            var tmpScrapeB = tmpScraper.Scrape(new Request("www.ancestrystage.com"));
            var tmpMongoIdB = new MongoDB.Bson.ObjectId(DateTime.Now, 0, 0, 0);
            tmpScrapeB.Id = tmpMongoIdB;

            //Act
            var qbService = new Comparer();
            var retvalComparison = qbService.Compare(tmpScrapeA, tmpScrapeB);

            //Assert
            Assert.AreEqual(retvalComparison.Scrapes[0].IdString, tmpScrapeA.IdString, "Compare failed: Invalid ScrapeIDs Expected: {0}", tmpMongoIdA);
            Assert.AreEqual(retvalComparison.Scrapes[1].IdString, tmpScrapeB.IdString, "Compare failed: Invalid ScrapeIDs Expected: {0}", tmpMongoIdB);
        }