Beispiel #1
0
        public static void FindTranslation(MongoCollection<Word> collection, string word)
        {
            bool containsWord = collection.AsQueryable<Word>().Any(w => w.WordText == word);
            if (!containsWord)
            {
                Console.WriteLine("Word does not exist in the dictionary.");
                return;
            }

            Word wordData = collection.AsQueryable<Word>().First(w => w.WordText == word);
            Console.WriteLine(wordData);
        }
Beispiel #2
0
        public static Dictionary <string, double> StatisticsAntennas()
        {
            string connectionString = "mongodb://*****:*****@ds046047.mlab.com:46047/banks-db";

            MongoClient client = null;

            client = new MongoClient(connectionString);
            MongoServer server = null;

            server = client.GetServer();
            MongoDatabase database = null;

            database = server.GetDatabase("banks-db");
            MongoCollection userCollection = null;

            userCollection = database.GetCollection <Company>("company");
            List <Company> query             = userCollection.AsQueryable <Company>().ToList();
            Dictionary <string, double> dict = new Dictionary <string, double>();

            foreach (var item in query)
            {
                dict.Add(item.CompanyName, item.Density / 10);
            }
            return(dict);
        }
        public HttpResponseMessage PostAnswerToIssue(AnswerIssue answer, [ValueProvider(typeof(HeaderValueProviderFactory <string>))] string authKey)
        {
            HttpResponseMessage responseMessage;
            User sqlUser;

            if (!ValidateCredentials.AuthKeyIsValid(db, authKey, out sqlUser) || answer.Text.Length > 300)
            {
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid information.");
                return(responseMessage);
            }

            MongoCollection <UsersProjects> usersInProjects = mongoDb.GetCollection <UsersProjects>(MongoCollections.UsersInProjects);

            // todo projects need to be recognized by id
            // the relation table has to save the id and use it in further queries



            MongoCollection <OpenIssue> issuesCollection = mongoDb.GetCollection <OpenIssue>(MongoCollections.Issues);
            var issue = issuesCollection.AsQueryable <OpenIssue>().FirstOrDefault(x => x.Id == new ObjectId(answer.IssueId));

            if (issue == null)
            {
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No such issue.");
                return(responseMessage);
            }

            issue.Answers.Add(answer);
            issuesCollection.Save(issue);

            List <AnswerIssue> entries = GetEntries(issue);

            return(responseMessage = this.Request.CreateResponse(HttpStatusCode.OK, new { Entries = entries }));
        }
        public void TestDistinctMustBeLastOperator()
        {
            _collection.RemoveAll();
            _collection.Insert(new C {
                Id = 1, X = 1
            });
            _collection.Insert(new C {
                Id = 2, X = 2
            });

            var query = _collection.AsQueryable()
                        .Select(d => d.X)
                        .Distinct();

            var result = query.AsEnumerable().OrderBy(x => x).ToList();

            Assert.AreEqual(2, result.Count);
            Assert.AreEqual(1, result[0]);
            Assert.AreEqual(2, result[1]);

            var ex      = Assert.Throws <NotSupportedException>(() => { query.Count(); });
            var message = "No further operators may follow Distinct in a LINQ query.";

            Assert.AreEqual(message, ex.Message);
        }
Beispiel #5
0
    // Use this for initialization
    void Start()
    {
        //gets the  vumark manager
        vmm = TrackerManager.Instance.GetStateManager().GetVuMarkManager();

        //connectst to the server & collections
        client = new MongoClient(new MongoUrl(connectionString));
        server = client.GetServer();
        server.Connect();
        db   = server.GetDatabase("documents");
        coll = db.GetCollection <Statue>("Other");

        //queries the database
        List <Statue> query = coll.AsQueryable <Statue>().Where <Statue>(u => u.vumark == num).ToList();

        Debug.Log(query);
        foreach (var x in query)
        {
            Debug.Log(x.name);
        }

        //whenever a new vumark is registered, call SetVumark
        vb = GameObject.Find("VuMark").GetComponent <VuMarkBehaviour> ();
        vb.RegisterVuMarkTargetAssignedCallback(new System.Action(this.SetVumark));
    }
        public HandlingHistory LookupHandlingHistoryOfCargo(TrackingId trackingId)
        {
            var cargo = new CargoRepositoryMongo(db).Find(trackingId);
            var data  = handlingEvents.AsQueryable().Where(he => he.cargoId == cargo.id);

            return(new HandlingHistory(data));
        }
        public static void WriteToSqlLite(MongoCollection reports)
        {
            string conString = @"Data Source=../../../supermarket.db;Version=3;";
            var dbSqLiteConnection = new SQLiteConnection(conString);
            try
            {
                dbSqLiteConnection.Open();
                var query = (from report in reports.AsQueryable<TotalReport>()
                             select report);

                foreach (var report in query)
                {
                    report.product_name = report.product_name.Replace("\"", "\"\"");
                    string commandText = String.Format(@"INSERT INTO TotalReports VALUES({0},""{1}"",""{2}"",{3}, {4});",
                        report.product_id, report.product_name, report.vendor_name, report.total_quantity_sold, report.total_incomes);

                    SQLiteCommand cmd = new SQLiteCommand(commandText, dbSqLiteConnection);
                    cmd.ExecuteNonQuery();
                }
            }
            catch (SQLiteException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                dbSqLiteConnection.Close();
            }
        }
Beispiel #8
0
 public static void ListAll(MongoCollection<Word> collection)
 {
     foreach (var word in collection.AsQueryable<Word>())
     {
         Console.WriteLine(word);
     }
 }
        public HttpResponseMessage PostNote(Note postedNote, [ValueProvider(typeof(HeaderValueProviderFactory <string>))] string authKey)
        {
            HttpResponseMessage responseMessage;
            User sqlUser;

            if (!ValidateCredentials.AuthKeyIsValid(db, authKey, out sqlUser))
            {
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid information.");
                return(responseMessage);
            }

            MongoCollection <UsersProjects> usersInProjects = mongoDb.GetCollection <UsersProjects>(MongoCollections.UsersInProjects);

            // todo projects need to be recognized by id
            // the relation table has to save the id and use it in further queries

            UsersProjects postingUser = usersInProjects.AsQueryable <UsersProjects>()
                                        .FirstOrDefault(x => x.Username == sqlUser.Username &&
                                                        x.ProjectName == postedNote.ProjectName && x.Role >= UserRoles.ProjectManager);

            if (postingUser == null)
            {
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "User does not participate in project or role is insufficient.");
                return(responseMessage);
            }

            MongoCollection <Note> notesCollection = mongoDb.GetCollection <Note>(MongoCollections.Notes);

            notesCollection.Save(postedNote);

            return(responseMessage = this.Request.CreateResponse(HttpStatusCode.OK, new { Posted = "Success" }));
        }
Beispiel #10
0
        public ActionResult GetFileDownloadObjectId(string objectIdValue)
        {
            FileContentResult fileContentResult = null;

            try
            {
                MongoClient     client     = new MongoClient("mongodb://localhost");
                MongoServer     server     = client.GetServer();
                MongoDatabase   database   = server.GetDatabase("test");
                MongoCollection collection = database.GetCollection("forms");
                // ObjectId id = new ObjectId(objectIdValue);
                List <Form> employees = collection.AsQueryable <Form>().Where(o => o.FileId == objectIdValue).ToList();
                foreach (var emp in employees)
                {
                    ObjectId            fileId = new ObjectId(emp.FileId);
                    MongoGridFSFileInfo file   = database.GridFS.FindOne(MongoDB.Driver.Builders.Query.EQ("_id", fileId));
                    using (var stream = file.OpenRead())
                    {
                        var bytes = new byte[stream.Length];
                        stream.Read(bytes, 0, (int)stream.Length);
                        Employee objemp = new Employee();
                        objemp.Data = bytes;
                        MemoryStream memoryStream  = new MemoryStream(bytes);
                        byte[]       bytesInStream = memoryStream.ToArray(); // simpler way of converting to array
                        fileContentResult = File(bytesInStream, "application/msword", emp.FileName);
                    }
                }
            }
            catch (Exception ee)
            {
                throw ee;
            }
            return(fileContentResult);
        }
        public Member LogIn(string openId, string email)
        {
            var member = _membersCollection.AsQueryable()
                         .FirstOrDefault(m => m.OpenId == openId);

            if (member == null)
            {
                member = CreateOnFirstLogIn(openId, email);
            }
            else
            {
                member.LastConnection = DateTime.Now;
                _membersCollection.Save(member);
            }
            return(member);
        }
Beispiel #12
0
        public List <IngredientDto> GetIngredients(int count, int skipIndex)
        {
            var ingredients = _collection.AsQueryable <Ingredient>();

            ingredients = ingredients.Skip(skipIndex * count).Take(count);

            var ingredientDtos = new List <IngredientDto>();

            foreach (var ingredient in ingredients)
            {
                var ingredientDto = new IngredientDto
                {
                    IngredientId = ingredient._id.ToString(),
                    Name         = ingredient.Name,
                    Description  = ingredient.Description,
                    CarbonHydrateWeightPercent = ingredient.CarbonHydrateWeightPercent,
                    EnergyInKcal          = ingredient.EnergyInKcal,
                    FatWeightPercent      = ingredient.FatWeightPercent,
                    ProteineWeightPercent = ingredient.ProteineWeightPercent,
                    AlcoholVolumePercent  = ingredient.AlcoholVolumePercent
                };

                ingredientDtos.Add(ingredientDto);
            }

            return(ingredientDtos);
        }
Beispiel #13
0
        public HttpResponseMessage GetRegister([FromUri] MobileDevice value)
        {
            if (value == null)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "Não foram enviados dados."));
            }

            if (value._id.Equals(Guid.Empty))
            {
                MongoCollection <MobileDevice> collection = _database.GetCollection <MobileDevice>("MobileDevices");
                MobileDevice md = collection.AsQueryable().FirstOrDefault(m => m.MACAddress == value.MACAddress);

                if (md == null)
                {
                    collection.Insert(value);
                }
                else if (value.Equals(md))
                {
                    collection.Save(md);
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, md));
                }
            }

            return(Request.CreateResponse(HttpStatusCode.Created, value));
        }
Beispiel #14
0
        public void TestQueryAgainstInheritedField()
        {
            _collection.Drop();
            _collection.Insert(new D {
                X = 1, Y = 2
            });

            var query = from d in _collection.AsQueryable <D>()
                        where d.X == 1
                        select d;

            var translatedQuery = MongoQueryTranslator.Translate(query);

            Assert.IsType <SelectQuery>(translatedQuery);
            Assert.Same(_collection, translatedQuery.Collection);
            Assert.Same(typeof(D), translatedQuery.DocumentType);

            var selectQuery = (SelectQuery)translatedQuery;

            Assert.Equal("(D d) => (d.X == 1)", ExpressionFormatter.ToString(selectQuery.Where));
            Assert.Null(selectQuery.OrderBy);
            Assert.Null(selectQuery.Projection);
            Assert.Null(selectQuery.Skip);
            Assert.Null(selectQuery.Take);

            Assert.Equal("{ \"X\" : 1 }", selectQuery.BuildQuery().ToJson());
            Assert.Equal(1, query.ToList().Count);
        }
Beispiel #15
0
        protected override TAggregateRoot DoGetByKey(Guid key)
        {
            MongoCollection collection = mongoDBRepositoryContext.GetCollectionForType(typeof(TAggregateRoot));
            Guid            id         = (Guid)key;

            return(collection.AsQueryable <TAggregateRoot>().Where(p => p.ID == id).First());
        }
        public ICollection <T> GetByExpressionSync(Expression <Func <T, bool> > predicate)
        {
            var filter = predicate.Compile();
            var result = MongoCollection.AsQueryable().Where(filter);

            return(result.ToList());
        }
 SearchFor(Expression <Func <TEntity, bool> > predicate)
 {
     return(collection
            .AsQueryable <TEntity>()
            .Where(predicate.Compile())
            .ToList());
 }
        public HttpResponseMessage PostIssue(OpenIssue postedIssue, [ValueProvider(typeof(HeaderValueProviderFactory <string>))] string authKey)
        {
            HttpResponseMessage responseMessage;
            User sqlUser;

            if (!ValidateCredentials.AuthKeyIsValid(db, authKey, out sqlUser) || postedIssue.Title.Length > 20 || postedIssue.Text.Length > 300)
            {
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid information.");
                return(responseMessage);
            }

            MongoCollection <UsersProjects> usersInProjects = mongoDb.GetCollection <UsersProjects>(MongoCollections.UsersInProjects);

            // todo projects need to be recognized by id
            // the relation table has to save the id and use it in further queries

            UsersProjects postingUser = usersInProjects.AsQueryable <UsersProjects>()
                                        .FirstOrDefault(x => x.Username == sqlUser.Username &&
                                                        x.ProjectName == postedIssue.ProjectName);

            if (postingUser == null)
            {
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "User does not participate in project.");
                return(responseMessage);
            }

            MongoCollection <OpenIssue> issuesCollection = mongoDb.GetCollection <OpenIssue>(MongoCollections.Issues);

            postedIssue.ByUser  = sqlUser.Username;
            postedIssue.Answers = new List <AnswerIssue>();
            issuesCollection.Save(postedIssue);

            return(responseMessage = this.Request.CreateResponse(HttpStatusCode.OK, new { Posted = "Success" }));
        }
        public HttpResponseMessage GetNote(string noteId, [ValueProvider(typeof(HeaderValueProviderFactory <string>))] string authKey)
        {
            HttpResponseMessage responseMessage;
            User sqlUser;

            if (!ValidateCredentials.AuthKeyIsValid(db, authKey, out sqlUser))
            {
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid information.");
                return(responseMessage);
            }

            MongoCollection <Note> notesCollection = mongoDb.GetCollection <Note>(MongoCollections.Notes);
            Note foundNote = notesCollection.FindOneAs <Note>(Query.EQ("_id", new ObjectId(noteId)));

            MongoCollection <UsersProjects> usersInProjects = mongoDb.GetCollection <UsersProjects>(MongoCollections.UsersInProjects);

            // todo projects need to be recognized by id
            UsersProjects postingUser = usersInProjects.AsQueryable <UsersProjects>()
                                        .FirstOrDefault(x => x.Username == sqlUser.Username &&
                                                        x.ProjectName == foundNote.ProjectName);

            if (postingUser == null)
            {
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "User does not participate in project.");
                return(responseMessage);
            }

            return(responseMessage = this.Request.CreateResponse(HttpStatusCode.OK, new { Note = foundNote }));
        }
Beispiel #20
0
        protected override TAggregateRoot DoGetByKey(ValueType key)
        {
            MongoCollection collection = _context.GetCollectionForType(typeof(TAggregateRoot));
            var             id         = (Guid)key;

            return(collection.AsQueryable <TAggregateRoot>().FirstOrDefault(p => p.Id == id));
        }
        public override bool Execute()
        {
            try
            {
                this.Log.LogMessage(string.Format("Applying '{0}' migration.", this.DatabaseName));
                MongoCollection <BsonDocument> migrations = this.Database.GetCollection("Migrations");
                foreach (ITaskItem migration in this.Migrations)
                {
                    var migrationId = new Guid(migration.GetMetadata(MigrationId));
                    if (migrations.AsQueryable <Migration>().Any(m => m.MigrationId == migrationId))
                    {
                        continue;
                    }

                    string fileName = migration.GetMetadata("Identity");
                    this.Log.LogMessage(string.Format("Applying migration id: '{0}' fileName: '{1}'.", migrationId,
                                                      fileName));
                    RunJavascript.Eval(this.Database, fileName);
                    var document = new BsonDocument {
                        { MigrationId, migrationId }
                    };
                    migrations.Save(document);
                }
            }
            catch (Exception ex)
            {
                this.Log.LogErrorFromException(ex);
                return(false);
            }

            this.Log.LogMessage(string.Format("'{0}' migration completed.", this.DatabaseName));
            return(true);
        }
        //
        // GET: /Error/

        public ActionResult Index()
        {
            var errors = (from error in db.AsQueryable()
                          orderby error.Date descending
                          select error).Take(20).ToArray();

            return(View(errors));
        }
Beispiel #23
0
        public ActionResult Duzenle(ObjectId id)
        {
            MongoDatabase db = DB();
            MongoCollection <rehberModel> updateColl = db.GetCollection <rehberModel>("kisiler");
            rehberModel edit = (from r in updateColl.AsQueryable() where r.id == id select r).FirstOrDefault();

            return(View("Duzenle", edit));
        }
        public void TestExplainFromLinqQueryEqualsExplainFromCursor()
        {
            var linqExplain  = _collection.AsQueryable <C>().Where(c => c.X == 2 && c.Y == 1).Take(1).Explain();
            var queryExplain = _collection.FindAs <C>(Query.And(Query.EQ("X", 2), Query.EQ("Y", 1))).SetLimit(1).Explain();

            // not all versions and/or topologies of the server return a queryPlanner.parsedQuery element in the explain result
            if (linqExplain.Contains("queryPlanner"))
            {
                if (linqExplain["queryPlanner"].AsBsonDocument.Contains("parsedQuery"))
                {
                    var linqQuery = linqExplain["queryPlanner"]["parsedQuery"];
                    var findQuery = queryExplain["queryPlanner"]["parsedQuery"];

                    Assert.Equal(linqQuery, findQuery);
                }
            }
        }
Beispiel #25
0
        public JsonResult GetAll()
        {
            MongoCollection f        = DB.GetFightersCollection();
            var             fighters = from fighter in f.AsQueryable <Fighter>()
                                       select fighter;

            return(Json(fighters, JsonRequestBehavior.AllowGet));
        }
Beispiel #26
0
        public void InsertHug(string recipient, Hug hug)
        {
            var mongUserObject = _mongoCollection.AsQueryable().Single(a => a.UserID == new BsonObjectId(recipient));
            var hugs           = mongUserObject.Hugs;

            if (hugs.Any(a => a.SenderID == hug.SenderID)) //No reason to store this - the user has already hugged.
            {
                return;
            }

            hugs.Add(hug);

            var query  = Query.EQ("_id", new BsonObjectId(recipient));
            var update = Update.AddToSet("Hugs", hug.ToBsonDocument());

            _mongoCollection.FindAndModify(query, SortBy.Null, update);
        }
        public JsonResult GetAll()
        {
            MongoCollection c          = DB.GetChallengesCollection();
            var             challenges = from challenge in c.AsQueryable <Challenge>()
                                         select challenge;

            return(Json(challenges, JsonRequestBehavior.AllowGet));
        }
        // GET:
        public ActionResult UserInformation()
        {
            var username = Membership.GetUser().UserName.ToLower();
            var user     =
                _usersCollection.AsQueryable().FirstOrDefault(x => string.Equals(x.NameLowerSpace, username));

            return(View(user));
        }
Beispiel #29
0
        internal static void CheckUser(string authKey, Organization queriedOrganization, MongoCollection <UsersOrganizations> usersAndOrganizations, out UsersOrganizations foundUser, UserRoles role, IUoWData db)
        {
            var userMongoId = db.Users.All().Single(x => x.AuthKey == authKey).MongoId;

            foundUser = usersAndOrganizations.AsQueryable <UsersOrganizations>()
                        .FirstOrDefault(x => x.Role >= role &&
                                        x.UserId == new ObjectId(userMongoId) && x.OrganizationName == queriedOrganization.Name);
        }
        private static Invitation FindInvitation(InvitationViewModel invitaion, Server.Models.User user, MongoCollection <BsonDocument> invitations)
        {
            var foundInvitation = invitations.AsQueryable <Invitation>()
                                  .FirstOrDefault(x => x.InvitedUserId == new ObjectId(user.MongoId) &&
                                                  x.Id == new ObjectId(invitaion.Id));

            return(foundInvitation);
        }
        public T SingleOrDefaultSync(Expression <Func <T, bool> > where)
        {
            var filter = where.Compile();
            var result = MongoCollection.AsQueryable()
                         .Where(filter);

            return(result.SingleOrDefault());
        }
Beispiel #32
0
        public static void BestCompany(string CompanyName)
        {
            string connectionString = "mongodb://*****:*****@ds046047.mlab.com:46047/banks-db";
            //Creating Client
            MongoClient client = null;

            try
            {
                client = new MongoClient(connectionString);
                MongoServer server = null;
                server = client.GetServer();
                MongoDatabase database = null;
                database = server.GetDatabase("banks-db");
                MongoCollection userCollection = null;
                userCollection = database.GetCollection <Company>("company");
                Console.WriteLine(userCollection.Count().ToString());
                List <Company> query   = userCollection.AsQueryable <Company>().ToList();
                Company        company = userCollection.AsQueryable <Company>().Where <Company>(sb => sb.CompanyName.Equals(CompanyName)).ToList().FirstOrDefault();
                if (company == null)
                {
                    ObjectId id = new ObjectId();
                    //Inserting document to collection/
                    try
                    {
                        company             = new Company();
                        company.id          = id;
                        company.CompanyName = CompanyName;
                        company.Density     = 1;
                        userCollection.Insert(company);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error :" + ex.Message);
                    }
                }
                else
                {
                    userCollection.Update(Query.EQ("CompanyName", CompanyName), Update.Set("Density", company.Density + 1));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error :" + ex.Message);
            }
        }
        public void TestConstructorWithTwoArguments()
        {
            var queryable  = _collection.AsQueryable <C>();
            var iqueryable = (IQueryable) new MongoQueryable <C>((MongoQueryProvider)queryable.Provider, queryable.Expression);

            Assert.AreSame(typeof(C), iqueryable.ElementType);
            Assert.AreSame(queryable.Provider, iqueryable.Provider);
            Assert.AreSame(queryable.Expression, iqueryable.Expression);
        }
        private static void PrintAllWords(MongoCollection<Word> collection)
        {
            var words = collection.AsQueryable().ToList();

            Console.WriteLine("All words in dictionary:");
            foreach (var word in words)
            {
                Console.WriteLine(word);
            }
        }
Beispiel #35
0
        public static void AddWord(MongoCollection<Word> collection, string word, string translation)
        {
            Word wordData = new Word(word, translation);
            bool containsWord = collection.AsQueryable<Word>().Any(w => w.WordText == word);
            if (containsWord)
            {
                Console.WriteLine("The word is already added to the dictionary.");
                return;
            }

            collection.Insert(wordData);
            Console.WriteLine("Word added");
        }
Beispiel #36
0
 public static void SreachWord(MongoCollection words)
 {
     Console.Write("Enter word for translation: ");
     string searchedWord = Console.ReadLine().ToLower();
     var searched = words.AsQueryable<Word>().FirstOrDefault(w => w.Value == searchedWord);
     if (searched != null)
     {
         Console.WriteLine("Word: {0}\nTranslation: {1}", searched.Value, searched.Translation);
     }
     else
     {
         Console.WriteLine("This word is not exist");
     }
 }
Beispiel #37
0
        // http://www.yoda.arachsys.com/csharp/singleton.html 线程安全的模式
        // 静态构造函数用于初始化任何静态数据,或用于执行仅需执行一次的特定操作。在创建第一个实例或引用任何静态成员之前将调用静态构造函数。
        static TaskQueue()
        {
            tasks = new List<SpiderTask>();
            agents = new List<Agent>();
            siteCollection = (DependencyResolver.Current.GetService(typeof(IMongoRepo<Site>)) as IMongoRepo<Site>).Collection;
            taskModelCollection = (DependencyResolver.Current.GetService(typeof(IMongoRepo<TaskModel>)) as IMongoRepo<TaskModel>).Collection;

            //注意必须使用ToList避免懒惰加载,否则在每次调用taskModels对象时会再次查询,从而清空已被赋值过的Timer属性。
            //这里应该是mongo driver或mongo Respository的特殊模式。
            taskModels = taskModelCollection.AsQueryable<TaskModel>().Where(d => d.Act == (int)eAct.Normal && d.Interval > 0).ToList();
            sites = siteCollection.Find(Query<Site>.EQ(d => d.Act, (int)eAct.Normal)).ToList();
            Instance = new TaskQueue();
            Instance.ModelTimerBuild();
            Instance.Maintenance();
        }
Beispiel #38
0
 public static void RemoveWords(MongoCollection words)
 {
     Console.Write("Enter word for remove: ");
     string editWord = Console.ReadLine().ToLower();
     var searched = words.AsQueryable<Word>().FirstOrDefault(w => w.Value == editWord);
     if (searched != null)
     {
         var query = Query.EQ("_id", searched.Id);
         words.Remove(query);
     }
     else
     {
         Console.WriteLine("This word is not exist");
     }
 }
Beispiel #39
0
    private static void Read(MongoCollection<Log> logs)
    {
        Console.WriteLine("READ");

        //// Native
        //var findLogsQuery = Query.And(Query.EQ("LogType.Type", "bug"), Query.GT("LogDate", DateTime.Now.AddDays(-7)));
        //logs.Find(findLogsQuery).Print();

        //// Linq
        //var findBugsQuery = Query<Log>.Where(log => log.LogType.Type == "bug" && log.LogDate > DateTime.Now.AddDays(-7));
        //logs.Find(findBugsQuery).Print();

        // LinqToMongoDB
        var newBugs = logs.AsQueryable<Log>().Where(log => log.LogType.Type == "bug" && log.LogDate > DateTime.Now.AddDays(-7));
        newBugs.Print();
    }
Beispiel #40
0
 public static void EditWord(MongoCollection words)
 {
     Console.Write("Enter word for edit: ");
     string editWord = Console.ReadLine().ToLower();
     Console.Write("Enter new translation: ");
     string translation = Console.ReadLine().ToLower();
     var searched = words.AsQueryable<Word>().FirstOrDefault(w => w.Value == editWord);
     if (searched != null)
     {
         var update = Update.Set("Translation", translation);
         var query = Query.EQ("_id", searched.Id);
         words.Update(query, update);
     }
     else
     {
         Console.WriteLine("This word is not exist");
     }
 }
Beispiel #41
0
        public static void AddWord(MongoCollection words)
        {
            Console.Write("Enter word: ");
            string loweredWordt = Console.ReadLine().ToLower();
            Console.Write("Enter translation: ");
            string loweredTranslation = Console.ReadLine().ToLower();
            Word newWord = new Word(loweredWordt, loweredTranslation);

            int countWords = words.AsQueryable<Word>().Where(w => w.Value == newWord.Value).Count();
            if (countWords > 0)
            {
                Console.WriteLine("This word already exist");
            }
            else
            {
                words.Insert<Word>(newWord);
            }
        }
        private static void FindWords(MongoCollection<Word> words)
        {
            Console.Write("Enter word to search for:");
            var word = Console.ReadLine();

            string foundWordTranslation = words.AsQueryable<Word>().
                                                Where(w => w.TheWord == word).
                                                Select(w => w.Translation).
                                                FirstOrDefault();

            if (foundWordTranslation != null)
            {
                Console.WriteLine(foundWordTranslation);
            }
            else
            {
                Console.WriteLine("No such word found!");
            }
        }
Beispiel #43
0
        public static void Insert(MongoCollection<Currency> collection, Currency currency)
        {
            try
            {
                collection.CreateIndex(IndexKeys<Currency>.Descending(c => c.Date));

                var result =
                    (from c in collection.AsQueryable<Currency>()
                     where c.Date == currency.Date
                     select c)
                    .Count();

                if (result == 0)
                    collection.Insert(currency);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #44
0
        public static void Insert(MongoCollection<Weather> collection, Weather weather)
        {
            try
            {
                collection.CreateIndex(IndexKeys<Weather>.Descending(c => c.Date));

                var result =
                    (from c in collection.AsQueryable<Weather>()
                     where c.Date == weather.Date
                     select c)
                    .Count();

                if (result == 0)
                    collection.Insert(weather);

                Console.WriteLine(weather);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        public static void ListItems(MongoCollection<DictionaryItem> dictionaryItems)
        {
            var allItems = from i in dictionaryItems.AsQueryable<DictionaryItem>()
                           select i;

            foreach (var item in allItems)
            {
                Console.WriteLine(item);
            }
        }
        private void SeedData(MongoDatabase db)
        {
            if (db == null) throw new ArgumentNullException("db");

            // Reset db
            db.GetCollection("IDSequence").Drop();

            _usersCol = db.GetCollection<MembershipAccount>(MembershipAccount.GetCollectionName());
            _usersCol.Drop();

            var salt = Crypto.GenerateSalt();

            var user1 = new MembershipAccount("User1")
                            {
                                PasswordSalt =  salt,
                                Password = Crypto.HashPassword("p@ssword" + salt),
                                IsConfirmed = false
                            };

            var user2 = new MembershipAccount("NonLocalUser")
                            {
                                IsLocalAccount = false,
                                IsConfirmed = true
                            };

            _usersCol.InsertBatch(new[] { user1, user2 });

            var oAuthTokenCol = db.GetCollection<OAuthToken>(OAuthToken.GetCollectionName());
            oAuthTokenCol.Drop();
            oAuthTokenCol.Insert(new OAuthToken("Tok3n", "tok3nSecret"));

            var oAuthMembershipCol = db.GetCollection<OAuthMembership>(OAuthMembership.GetCollectionName());
            oAuthMembershipCol.Drop();
            oAuthMembershipCol.Insert( new OAuthMembership("Test", "User1@Test", 1) );

            Users = _usersCol.AsQueryable();
            OAuthTokens = oAuthTokenCol.AsQueryable();
            OAuthMemberships = oAuthMembershipCol.AsQueryable();
        }
        /// <summary>
        /// 基本的 单一条件的  LINQ 查询.
        /// </summary>
        /// <param name="collection"></param>
        private void BasicLinq(MongoCollection<TestLinq> collection)
        {
            // 查询 FirstName 完全匹配.
            var queryFirstName =
                from data in collection.AsQueryable<TestLinq>()
                where data.FirstName == "Jac"
                select data;

            foreach (TestLinq result in queryFirstName)
            {
                Console.WriteLine("查询 FirstName = Jac  ,查询结果 = {0}", result);
            }



            // 模糊查询 LastName
            var queryLastName =
                from data in collection.AsQueryable<TestLinq>()
                where data.LastName.StartsWith("Q")
                select data;

            foreach (TestLinq result in queryLastName)
            {
                Console.WriteLine("查询 LastName LIKE Q%  ,查询结果 = {0}", result);
            }


            // 测试数字 大小.
            var querySeqNo =
                 from data in collection.AsQueryable<TestLinq>()
                 where data.SeqNumber > 13
                 select data;

            foreach (TestLinq result in querySeqNo)
            {
                Console.WriteLine("查询 SeqNumber > 13  ,查询结果 = {0}", result);
            }
        }
        private static void ListWords(MongoCollection<Word> words)
        {
            var allWords = from w in words.AsQueryable<Word>()
                           select w;

            foreach (var word in allWords)
            {
                Console.WriteLine("{0} - {1}", word.TheWord, word.Translation);
            }
        }
 public Dictionary(MongoCollection<Word> dictionary)
 {
     this.dict = dictionary;
     this.queryableCollection = dictionary.AsQueryable<Word>();
 }
Beispiel #50
0
 private static IEnumerable<Tweet> FälligeTweets(DateTime fälligkeit, MongoCollection<Tweet> collection) {
     return collection.AsQueryable().Where(x => x.Veröffentlichen <= fälligkeit).ToList();
 }
        static string GetTranslation(MongoCollection<DictionaryEntry> dictionary, string word)
        {
            var entry = dictionary.AsQueryable<DictionaryEntry>()
                .FirstOrDefault(e => e.Word == word);
            if (entry != null)
            {
                return entry.Translation;
            }

            return null;
        }
 private static void FindWord(MongoCollection<Word> collection, string key)
 {
     var word = collection.AsQueryable().Where(w => w.KeyWord == key).FirstOrDefault();
     Console.WriteLine(word);
 }
        /// <summary>
        /// 多条件查询.
        /// </summary>
        /// <param name="collection"></param>
        private void MultiCondLinq(MongoCollection<TestLinq> collection, 
            string firstName, string lastName, int? minSeqNo, int? maxSeqNo)
        {
            // 初始化查询, 没有任何条件.
            var query =
                from data in collection.AsQueryable<TestLinq>()
                select data;

            if (!String.IsNullOrEmpty(firstName))
            {
                // 如果输入了 firstName
                // 追加条件.
                query =  query.Where(p=>p.FirstName.Contains(firstName));
            }


            if (!String.IsNullOrEmpty(lastName))
            {
                // 如果输入了 firstName
                // 追加条件.
                query = query.Where(p => p.LastName.Contains(lastName));
            }



            if (minSeqNo != null)
            {
                // 如果输入了 最小编号.
                // 追加条件.
                // 注意:如果条件直接写  >=  NullAble 的, 执行将会抱错!
                query = query.Where(p => p.SeqNumber >= minSeqNo.Value);
            }

            if (maxSeqNo != null)
            {
                // 如果输入了 最大编号.
                // 追加条件.
                query = query.Where(p => p.SeqNumber <= maxSeqNo.Value);
            }


            // 输出查询结果
            Console.WriteLine("######动态查询 FirstName:{0}; LastName:{1}; SeqNumber:({2}--{3})",
                firstName, lastName, minSeqNo, maxSeqNo);

            foreach (TestLinq result in query)
            {
                Console.WriteLine("查询结果 = {0}", result);
            }
            Console.WriteLine();

        }
Beispiel #54
0
 public MongoDictionary(MongoCollection<Word> dictionaryCollection)
 {
     this.dictionaryCollection = dictionaryCollection;
     this.collectionQuery = dictionaryCollection.AsQueryable<Word>();
 }
        public static void SearchItem(MongoCollection<DictionaryItem> dictionaryItems)
        {
            Console.WriteLine("Enter word for search: ");
            string searchedWord = Console.ReadLine();

            var searchedItems = (from d in dictionaryItems.AsQueryable<DictionaryItem>()
                                where d.Word == searchedWord
                                select d).FirstOrDefault();

            Console.WriteLine(searchedItems);
        }
 public ProductsReport(MongoCollection<MongoProduct> products)
 {
     this.products = products;
     this.queryableProducts = products.AsQueryable<MongoProduct>();
 }
        private void AddUserFavoriteMovie( User user, Movie favoriteMovie, MongoCollection<User> userCollection )
        {
            var movieShort = new MovieShortDetail( favoriteMovie );
            var movieShortBson = movieShort.ToBsonDocument();

            // Add permanently to model without saving
            user.FavoriteMovies.Add( movieShort );
            // Add atomically to database
            userCollection.Update( Query.EQ( IdFieldName, user.Id ),
                                  Update.AddToSet( FavoriteMoviesFieldName, movieShortBson ) );

            // Update favorite movie collections for user's friends
            var friendIds = user.Friends.Select( f => f.UserId ).ToArray();
            var friends = userCollection.AsQueryable().Where( u => friendIds.Contains( u.Id ) );

            foreach (var friend in friends)
            {
                userCollection.Update( Query.EQ( IdFieldName, friend.Id ),
                                      Update.AddToSet( FriendsFavoriteMoviesFieldName, movieShortBson ) );
            }
        }