public Presence[] GetPresence(string from, string to, Matrix.Xmpp.PresenceType? type, bool remove)
        {
            List<Presence> presences = new List<Presence>();
            var db = GetDatabase();
            var collection = db.GetCollection("offline_presence");
            var query = new QueryDocument();
            if (from != null)
                query.Add("from", from);
            if (to != null)
                query.Add("to", to);
            if (type != null)
                query.Add("type", type.ToString());

            MongoCursor<BsonDocument> cursor;
            if (from == null && to == null)
                cursor = collection.FindAll();
            else
                cursor = collection.Find(query);

            foreach (var item in cursor)
            {
                Presence presence = (Presence)Presence.LoadXml(item.GetValue("value").AsString);
                presences.Add(presence);
            }
            if (remove)
                collection.Remove(query);
            return presences.ToArray();
        }
 public int NumberCharactersOnServer(string region, string server)
 {
     QueryDocument query = new QueryDocument();
     query.Add("Server", server);
     query.Add("Region", region);
     return (int)Collection.Find(query).Count();
 }
Ejemplo n.º 3
0
        //# Function to list of cars that are eligible for users request
        public List<Car> GetCars(InputRequestAttributes RequestQuery)
        {
            //# Get the list of zipcodes that are located in specified distance from user requested zipcode
            ConnectedRepository ctx = new ConnectedRepository(DbName);
            LocationDataLayer lctx = new LocationDataLayer();
            List<string> NearByZipCodes = new List<string>();
            if (!string.IsNullOrEmpty(RequestQuery.Zipcode))
            {
                List<Location> locationsAround = lctx.GetNearZipcodes(RequestQuery.Zipcode,RequestQuery.distance);
                if (locationsAround.Count != 0)
                {
                    foreach (Location location in locationsAround)
                    {
                        NearByZipCodes.Add(location.zip);
                    }
                    NearByZipCodes.Add(RequestQuery.Zipcode);
                }
            }
            //# Build a DB query based on user constraint. Check request if it has value and add it to query.
            QueryDocument CarQuery = new QueryDocument();

            if (RequestQuery.Year > 2000)
                CarQuery.Add("Year", RequestQuery.Year);
            if (RequestQuery.Name != null)
                CarQuery.Add("Name", RequestQuery.Name);
            if (RequestQuery.Maker != null)
                CarQuery.Add("Maker", RequestQuery.Maker);
            if (RequestQuery.MaxPrice >= 1000)
                CarQuery.Add("Price", new BsonDocument("$lt", RequestQuery.MaxPrice));
            if (NearByZipCodes.Count() != 0)
                CarQuery.Add("Zipcode", new BsonDocument("$in", new BsonArray(NearByZipCodes)));
            MongoCursor<Car> Cars = ctx.Cars.Find(CarQuery);
            List<Car> carsList = Cars.ToList();
            return carsList;
        }
        // GET api/reportingrecord/5
        public HttpResponseMessage Get(string id, [FromBody]JObject JsonObject)
        {
            //Setup variables From Body
            JToken Project;
            JToken Oid;
            JToken Format;
            JToken userRole;

            JsonObject.TryGetValue("Project", out Project);
            JsonObject.TryGetValue("FormOid", out Oid);
            JsonObject.TryGetValue("Format", out Format);
            //just for POC, needs to be derived
            JsonObject.TryGetValue("Role", out userRole);

            if(Project==null ||Oid==null|| Format==null)
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            userRole = userRole ?? 0;

            //Run Query against database and pull back records
            var query = new QueryDocument("project", Project.ToString());
            query.Add("FormOid", Oid.ToString());
            query.Add("DatabaseGuid", id);
            var ClinicalViews = CVCollection.Find(query);

            //Build Matrix from records and Create output
            switch(Format.ToString().ToLower())
            {
                case "csv":
                    return GetCsvOutput(ClinicalViews, int.Parse(userRole.ToString()));
                case "json":
                    return GetjsonOutput(ClinicalViews, int.Parse(userRole.ToString()));
                default:
                    return Request.CreateResponse(HttpStatusCode.NotImplemented);
            }
        }
 public IList<Character> GetCharactersInGuild(string region, string server, string guild)
 {
     QueryDocument query = new QueryDocument();
     query.Add("Server", server);
     query.Add("Region", region);
     query.Add("Guild", guild);
     return Collection.Find(query).OrderBy(c => c.CurrentPoints).ToList();
 }
        public IList<Character> ListCharactersOnServerByPoints(string region, string server, int start, int limit)
        {
            QueryDocument query = new QueryDocument();
            query.Add("Server", server);
            query.Add("Region", region);

            SortByBuilder sortBy = new SortByBuilder();
            sortBy.Descending("CurrentPoints");

            return Collection.Find(query).SetSortOrder(sortBy).SetSkip(start).SetLimit(limit).OrderByDescending(c => c.CurrentPoints).ToList();
        }
        public Message[] GetChatMessage(string user, bool delete)
        {
            if (string.IsNullOrEmpty(user))
                return null;

            user = user.ToLower();
            var db = GetDatabase();
            var collection = db.GetCollection("offline_msg");
            var query = from x in collection.AsQueryable<OfflineMessageItem>() where x.To == user select x;
            List<Message> msgs = new List<Message>();

            foreach (var item in query)
            {
                msgs.Add(new Matrix.Xmpp.Client.Message()
                {
                    From = item.From + "@gjtalk.com",
                    To = item.To + "@gjtalk.com",
                    Body = item.Body,
                    Delay = new Matrix.Xmpp.Delay.Delay(item.Time, item.From + "@gjtalkc.com"),
                    Type = (Matrix.Xmpp.MessageType)Enum.Parse(
                    typeof(Matrix.Xmpp.MessageType), item.MessageType)
                });
            }
            if (delete)
            {
                QueryDocument doc = new QueryDocument();
                doc.Add("To", user);
                collection.Remove(doc);
            }
            return msgs.ToArray();
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            //连接信息
            string conn = "mongodb://localhost";
            string database = "demoBase";
            string collection = "demoCollection";
            MongoServer mongodb = MongoServer.Create(conn);
            //连接数据库
            MongoDatabase mongoDataBase = mongodb.GetDatabase(database);
            //选择数据库名
            MongoCollection mongoCollection = mongoDataBase.GetCollection(collection);
            //选择集合,相当于表
            mongodb.Connect();
            //普通插入
            var o = new { Uid = 123, Name = "xixiNormal", PassWord = "******" };
            mongoCollection.Insert(o);
            //对象插入
            Person p = new Person { Uid = 124, Name = "xixiObject", PassWord = "******" };
            mongoCollection.Insert(p);
            //BsonDocument 插入
            BsonDocument b = new BsonDocument();
            b.Add("Uid", 125);
            b.Add("Name", "xixiBson");
            b.Add("PassWord", "333333");
            mongoCollection.Insert(b);

            Console.WriteLine(mongoCollection.FullName);

            QueryDocument query = new QueryDocument();
            query.Add("Uid", 125);
            MongoCursor<Person> pers = mongoCollection.FindAs<Person>(query);
            //Console.WriteLine(pe.Name);
            Console.ReadLine();
        }
 public CarFacts GetReport(string Vin)
 {
     string DbName = "CarFactsDB";
     ConnectedRepository fctx = new ConnectedRepository(DbName);
     QueryDocument FaxQuery = new QueryDocument();
     FaxQuery.Add("_id", Vin);
     CarFacts carFaxReport = fctx.CarFacts.FindOne(FaxQuery);
     return carFaxReport;
 }
Ejemplo n.º 10
0
 public ActionResult Forms(string id, string Project)
 {
     //var CVCollection = MongoDBHelper.GetCollection("ClinicalViewDocuments");
     var query = new QueryDocument("project", Project.ToString());
     query.Add("DatabaseGuid", id);
     var ClinicalViews = CVCollection.Find(query);
     var forms = CVCollection.Distinct("FormOid", query).OrderBy(x => x);
     ViewBag.forms = forms;
     return View();
 }
Ejemplo n.º 11
0
        public static IEnumerable<Report> GetByUser(IApiUserSource api, User user)
        {
            using (MongoConnection db = FooRuntime.GetDatabase())
            {
                QueryDocument query = new QueryDocument();
                query.AddApiConstraint(api);
                query.Add("ownerUserId", user._id);

                return db.GetCollection<Report>().Find(query);
            }
        }
Ejemplo n.º 12
0
        public static Token GetByToken(IApiUserSource api, Guid token)
        {
            using (MongoConnection db = FooRuntime.GetDatabase())
            {
                QueryDocument query = new QueryDocument();
                query.AddApiConstraint(api);
                query.Add(TheTokenKey, token);

                return db.GetCollection<Token>().FindOne(query);
            }
        }
 public Features GetFeature(string carName)
 {
     string DbName = "CarFeaturesDB";
     ConnectedRepository fctx = new ConnectedRepository(DbName);
     QueryDocument FeatureQuery = new QueryDocument();
     FeatureQuery.Add("CarName", carName);
     Features featuresOfCar = fctx.Features.FindOne(FeatureQuery);
     if (featuresOfCar != null)
         return featuresOfCar;
     else
         return null;
 }
Ejemplo n.º 14
0
        public ActionResult Forms(string id,string Project)
        {
            if (id == null || id == "")
                return new RedirectResult("./Databases");

            if (Project == null || Project == "")
                return new RedirectResult("./Project/?id="+id);

            var query = new QueryDocument("DatabaseGuid", id);
            query.Add("project", Project);
            var Forms = CVCollection.Distinct("FormOid", query).OrderBy(x => x);

            ViewBag.Forms = Forms;
            ViewBag.dbId = id;
            ViewBag.Project = Project;
            return View();
        }
Ejemplo n.º 15
0
        public static User GetById(IApiUserSource api, ObjectId userId, bool throwIfNotFound)
        {
            using (MongoConnection db = FooRuntime.GetDatabase())
            {
                QueryDocument query = new QueryDocument();
                query.AddApiConstraint(api);
                query.Add(IdKey, userId);

                User user = db.GetCollection<User>().FindOne(query);
                if (user != null)
                    return user;
                else
                {
                    if (throwIfNotFound)
                        throw new InvalidOperationException(string.Format("A user with ID '{0}' was not found.", userId));
                    else
                        return null;
                }
            }
        }
 public List<Location> GetNearZipcodes(string zip, int distance)
 {
     LocationDataLayer lctx = new LocationDataLayer();
     QueryDocument ZipQuery = new QueryDocument();
     ZipQuery.Add("zip", zip);
     double distance1 = distance * (1/69.0);
     Location GeoLocation = lctx.zips.FindOne(ZipQuery);
     if (GeoLocation != null)
     {
         var query = Query.Near("loc", GeoLocation.loc.lat, GeoLocation.loc.lon, distance1);
         MongoCursor<Location> Zips = zips.Find(query);
         List<Location> NearbyZips = Zips.ToList();
         return NearbyZips;
     }
     else
     {
         // need to handle Exception in much better way
         return null;
     }
 }
Ejemplo n.º 17
0
        public bool ValidateUser(String User, String Password)
        {
            try
            {
                string connectionString = "mongodb://localhost:27017";
                MongoClient client = new MongoClient(connectionString);
                MongoServer server = client.GetServer();
                MongoDatabase db = server.GetDatabase("hdb");

                using (server.RequestStart(db))
                {
                    //db.DropCollection("Users");
                    //db.DropCollection("Pats");
                 var Usercollection = db.GetCollection<mUser>("Users");
                    //mUser u = new mUser();
                    //u.UserName = "******";
                    //u.PassWord = "******";
                    //Usercollection.Insert(u);

                    QueryDocument query = new QueryDocument();
                   BsonDocument b = new BsonDocument();
                   b.Add("UserName", User);
                   b.Add("PassWord", Password);
                   query.Add(b);
                    mUser user = Usercollection.FindOne(query);
                    if (user == null)
                    {
                        return false;
                    }
                    return true;
                }
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// This method stores a burrito.
        /// </summary>
        /// <param name="b">The burrito object to store</param>
        /// <returns>Success/Failure</returns>
        public Boolean storeBurrito(Burrito b)
        {
            dLog.Info("Entering method storeBurrito | ID: " + b.id);
            Boolean result = false;

            try
            {
                MongoServer server = MongoServer.Create();
                MongoDatabase db = server.GetDatabase("neatoBurrito");
                //MongoCredentials credentials = new MongoCredentials("username", "password");
                //MongoDatabase salaries = server.GetDatabase("salaries", credentials);

                using (server.RequestStart(db))
                {
                    MongoCollection<BsonDocument> coll = db.GetCollection("burrito");
                    var query = new QueryDocument("id", b.id);

                    dLog.Debug("Finding if burrito exists");
                    BsonDocument myDoc = coll.FindOne(query);

                    query.Add("beef", b.Beef);
                    query.Add("blackBeans", b.BlackBeans);
                    query.Add("brownRice", b.BrownRice);
                    query.Add("chicken", b.Chicken);
                    query.Add("chiliTortilla", b.ChiliTortilla);
                    query.Add("cucumber", b.Cucumber);
                    query.Add("flourTortilla", b.FlourTortilla);
                    query.Add("guacamole", b.Guacamole);
                    query.Add("herbGarlicTortilla", b.HerbGarlicTortilla);
                    query.Add("hummus", b.Hummus);
                    query.Add("jalapenoCheddarTortilla", b.JalapenoCheddarTortilla);
                    query.Add("jalapenos", b.Jalapenos);
                    query.Add("lettuce", b.Lettuce);
                    query.Add("onion", b.Onion);
                    query.Add("orderID", b.orderID);
                    query.Add("pintoBeans", b.PintoBeans);
                    query.Add("price", b.Price.ToString());
                    query.Add("salsaPico", b.SalsaPico);
                    query.Add("salsaSpecial", b.SalsaSpecial);
                    query.Add("salsaVerde", b.SalsaVerde);
                    query.Add("tomatoBasilTortilla", b.TomatoBasilTortilla);
                    query.Add("tomatoes", b.Tomatoes);
                    query.Add("wheatTortilla", b.WheatTortilla);
                    query.Add("whiteRice", b.WhiteRice);

                    //ensure we were passed a valid object before attempting to write
                    if (myDoc == null)
                    {
                        dLog.Debug("Inserting burrito");
                        coll.Insert(query);

                        result = true;
                    }
                    else
                    {
                        var update = new UpdateDocument();
                        update.Add(query.ToBsonDocument());
                        dLog.Debug("Updating burrito");
                        dLog.Debug("myDoc: " + myDoc.ToString());
                        dLog.Debug("update Query: " + update.ToString());

                        SafeModeResult wr = coll.Update(new QueryDocument("id", b.id), update, SafeMode.True);

                        dLog.Debug("SafeModeResult: " + wr.Ok);
                        if (wr.LastErrorMessage == null && wr.Ok)
                        {
                            result = true;
                        }
                        else
                        {
                            dLog.Debug("SafeModeResult: " + wr.LastErrorMessage);
                        }
                    }
                }
            }
            catch (Exception e2)
            {
                dLog.Error("Exception in storeBurrito: " + e2.Message);
            }
            finally
            {
                //using statement above already calls RequestDone()
            }

            return result;
        }
Ejemplo n.º 19
0
        void IPropertyPredicateOperator.PutContainsPredicate(QueryDocument doc, object value)
        {
            var arrayProcessor = this.TypeProcessor as IArrayProcessor;
            if (arrayProcessor == null)
            {
                throw new NotSupportedException("Only IArrayProcessor instance support Contains predicate.");
            }

            var containingValue = arrayProcessor.GetContainingValue(value);
            doc.Add(this.FieldName, containingValue);
        }
Ejemplo n.º 20
0
        void IPropertyPredicateOperator.PutRegexMatchPredicate(QueryDocument doc, string expression, string options)
        {
            var name = this.FieldName;
            if (doc.Contains(name))
            {
                throw new InvalidOperationException(
                    String.Format(
                        "this document should not contain {0} field.", name));
            }

            doc.Add(name, new BsonRegularExpression(expression, options));
        }
Ejemplo n.º 21
0
        private void PutInnerPredicate(QueryDocument doc, string op, object value)
        {
            var name = this.FieldName;
            BsonDocument innerDoc;

            if (doc.Contains(name))
            {
                innerDoc = doc[name] as BsonDocument;
                if (innerDoc == null)
                {
                    throw new InvalidOperationException("Should have nothing or BsonDocument object");
                }
            }
            else
            {
                innerDoc = new BsonDocument();
                doc.Add(name, innerDoc);
            }

            innerDoc.Add(op, this.TypeProcessor.ToBsonValue(value));
        }
Ejemplo n.º 22
0
        void IPropertyPredicateOperator.PutEqualPredicate(QueryDocument doc, object value)
        {
            var name = this.FieldName;
            if (doc.Contains(name))
            {
                throw new InvalidOperationException(
                    String.Format(
                        "this document should not contain {0} field.", name));
            }

            doc.Add(name, this.TypeProcessor.ToBsonValue(value));
        }
Ejemplo n.º 23
0
        void IPropertyPredicateOperator.PutInPredicate(QueryDocument doc, IEnumerable<object> collection)
        {
            var name = this.FieldName;
            if (doc.Contains(name))
            {
                throw new InvalidOperationException(
                    String.Format(
                        "this document should not contain {0} field.", name));
            }

            var array = new BsonArray();
            foreach (var item in collection)
            {
                var value = this.TypeProcessor.ToBsonValue(item);
                array.Add(value);
            }

            doc.Add(name, new BsonDocument().Add("$in", array));
        }
Ejemplo n.º 24
0
        //
        // GET: /ClinicalView/
        public ActionResult Index(string study, string oid)
        {
            if (study == null || oid == null)
            {
                return new RedirectResult("../Home");
            }
            List<string> results = new List<string>();
            JToken Project = study;
            JToken Oid = oid;

            var query = new QueryDocument("project", Project.ToString());
            query.Add("FormOid", Oid.ToString());

            var ClinicalViews = CVCollection.Find(query);
            foreach (BsonDocument doc in ClinicalViews)
            {
                results.Add(doc.ToString());
            }
            ViewBag.docs = results;
            return View();
        }
        public void select_new_data_to_sqlserver(string doc_id)
        {
            string sql = "";
            string max_timespan = "";
            DataTable dt_temp = new DataTable();

            //find the last insert data
            QueryDocument doc_query = new QueryDocument();
            doc_query.Add("doc_id", doc_id);
            BsonDocument doc = MongoHelper.query_bson_from_bson(doc_query);

            switch (doc["type"].ToString())
            {
                case "win0":
                    sql = " select max(timespan) from win" +
                          " where website='{0}'"+
                          " start_time='{1}'" +
                          " and host='{2}'" +
                          " and client='{3}'" +
                          " and give_type='{4}'";
                    sql = string.Format(sql, doc["website"].ToString(),doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), "0");
                    max_timespan = SQLServerHelper.get_table(sql).Rows[0][0].ToString();

                    sql = " select * from win" +
                          " where website='{0}'"+
                          " start_time='{1}'" +
                          " and host='{2}'" +
                          " and client='{3}'" +
                          " and give_type='{4}'"+
                          " and timespan='{5}'";
                    sql = string.Format(sql, doc["website"].ToString(),doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), "0",max_timespan);
                    dt_temp = SQLServerHelper.get_table(sql);

                    if (dt_temp.Rows[0]["three"].ToString() != doc["three0"].ToString() ||
                        dt_temp.Rows[0]["one"].ToString() != doc["one0"].ToString()||
                        dt_temp.Rows[0]["zero"].ToString() != doc["zero0"].ToString())
                    {
                        sql = " insert into win" +
                              " (timespan,website,start_time,host,client,give_type,three,one,zero)" +
                              " values" +
                              " ({0},{1},{2},{3},{4},{5},{6},{7},{8})";
                        sql=string.Format(sql,doc["doc_id"].ToString(),doc["website"].ToString(),doc["start_time"].ToString(),doc["host"].ToString(),doc["client"].ToString(),"0",
                                          doc["three0"].ToString(), doc["one0"].ToString(), doc["zero0"].ToString());
                        SQLServerHelper.exe_sql(sql);
                    }
                    break;
                case "win1":
                    sql = " select max(timespan) from win" +
                          " where website='{0}'" +
                          " start_time='{1}'" +
                          " and host='{2}'" +
                          " and client='{3}'" +
                          " and give_type='{4}'";
                    sql = string.Format(sql, doc["website"].ToString(), doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), "1");
                    max_timespan = SQLServerHelper.get_table(sql).Rows[0][0].ToString();

                    sql = " select * from win" +
                            " where website='{0}'" +
                            " start_time='{1}'" +
                            " and host='{2}'" +
                            " and client='{3}'" +
                            " and give_type='{4}'" +
                            " and timespan='{5}'";
                    sql = string.Format(sql, doc["website"].ToString(), doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), "1", max_timespan);
                    dt_temp = SQLServerHelper.get_table(sql);

                    if (dt_temp.Rows[0]["three"].ToString() != doc["three1"].ToString() ||
                        dt_temp.Rows[0]["one"].ToString() != doc["one1"].ToString() ||
                        dt_temp.Rows[0]["zero"].ToString() != doc["zero1"].ToString())
                    {
                        sql = " insert into win" +
                              " (timespan,website,start_time,host,client,give_type,three,one,zero)" +
                              " values" +
                              " ({0},{1},{2},{3},{4},{5},{6},{7},{8})";
                        sql = string.Format(sql, doc["doc_id"].ToString(), doc["website"].ToString(), doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), "1",
                                          doc["three1"].ToString(), doc["one1"].ToString(), doc["zero1"].ToString());
                        SQLServerHelper.exe_sql(sql);
                    }
                    break;
                case "win_1":
                    sql = " select max(timespan) from win" +
                           " where website='{0}'" +
                           " start_time='{1}'" +
                           " and host='{2}'" +
                           " and client='{3}'" +
                           " and give_type={4}";
                    sql = string.Format(sql, doc["website"].ToString(), doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), "-1");
                    max_timespan = SQLServerHelper.get_table(sql).Rows[0][0].ToString();

                    sql = " select * from win" +
                         " where website='{0}'" +
                         " start_time='{1}'" +
                         " and host='{2}'" +
                         " and client='{3}'" +
                         " and give_type='{4}'" +
                         " and timespan='{5}'";
                    sql = string.Format(sql, doc["website"].ToString(), doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), "-1", max_timespan);
                    dt_temp = SQLServerHelper.get_table(sql);

                    if (dt_temp.Rows[0]["three"].ToString() != doc["three_1"].ToString() ||
                        dt_temp.Rows[0]["one"].ToString() != doc["one_1"].ToString() ||
                        dt_temp.Rows[0]["zero"].ToString() != doc["zero_1"].ToString())
                    {
                        sql = " insert into win" +
                              " (timespan,website,start_time,host,client,give_type,three,one,zero)" +
                              " values" +
                              " ({0},{1},{2},{3},{4},{5},{6},{7},{8})";
                        sql = string.Format(sql, doc["doc_id"].ToString(), doc["website"].ToString(), doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), "-1",
                                          doc["three_1"].ToString(), doc["one_1"].ToString(), doc["zero_1"].ToString());
                        SQLServerHelper.exe_sql(sql);
                    }
                    break;
                case "point":
                    sql = " select max(timespan) from point" +
                          " website='{0}'"+
                          " where start_time='{1}'" +
                          " and host='{2}'" +
                          " and client='{3}'";
                    sql = string.Format(sql,doc["website"].ToString(), doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString());
                    max_timespan = SQLServerHelper.get_table(sql).Rows[0][0].ToString();

                    sql = " select * from win" +
                          " where website='{0}'"+
                          " start_time='{1}'" +
                          " and host='{2}'" +
                          " and client='{3}'" +
                          " and timespan='{4}'";
                    sql = string.Format(sql, doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), max_timespan);
                    dt_temp = SQLServerHelper.get_table(sql);
                    if (dt_temp.Rows[0]["point_1_0"].ToString() != doc["point_1_0"].ToString() ||
                        dt_temp.Rows[0]["point_2_0"].ToString() != doc["point_2_0"].ToString() ||
                        dt_temp.Rows[0]["point_3_0"].ToString() != doc["point_3_0"].ToString() ||
                        dt_temp.Rows[0]["point_4_0"].ToString() != doc["point_4_0"].ToString() ||
                        dt_temp.Rows[0]["point_5_0"].ToString() != doc["point_5_0"].ToString() ||
                        dt_temp.Rows[0]["point_2_1"].ToString() != doc["point_2_1"].ToString() ||
                        dt_temp.Rows[0]["point_3_1"].ToString() != doc["point_3_1"].ToString() ||
                        dt_temp.Rows[0]["point_4_1"].ToString() != doc["point_4_1"].ToString() ||
                        dt_temp.Rows[0]["point_5_1"].ToString() != doc["point_5_1"].ToString() ||
                        dt_temp.Rows[0]["point_3_2"].ToString() != doc["point_3_2"].ToString() ||
                        dt_temp.Rows[0]["point_4_2"].ToString() != doc["point_4_2"].ToString() ||
                        dt_temp.Rows[0]["point_5_2"].ToString() != doc["point_5_2"].ToString() ||
                        dt_temp.Rows[0]["point_other_3"].ToString() != doc["point_other_3"].ToString() ||
                        dt_temp.Rows[0]["point_0_0"].ToString() != doc["point_0_0"].ToString() ||
                        dt_temp.Rows[0]["point_1_1"].ToString() != doc["point_1_1"].ToString() ||
                        dt_temp.Rows[0]["point_2_2"].ToString() != doc["point_2_2"].ToString() ||
                        dt_temp.Rows[0]["point_3_3"].ToString() != doc["point_3_3"].ToString() ||
                        dt_temp.Rows[0]["point_other_1"].ToString() != doc["point_other_1"].ToString() ||
                        dt_temp.Rows[0]["point_0_1"].ToString() != doc["point_0_1"].ToString() ||
                        dt_temp.Rows[0]["point_0_2"].ToString() != doc["point_0_2"].ToString() ||
                        dt_temp.Rows[0]["point_0_3"].ToString() != doc["point_0_3"].ToString() ||
                        dt_temp.Rows[0]["point_0_4"].ToString() != doc["point_0_4"].ToString() ||
                        dt_temp.Rows[0]["point_0_5"].ToString() != doc["point_0_5"].ToString() ||
                        dt_temp.Rows[0]["point_1_2"].ToString() != doc["point_1_2"].ToString() ||
                        dt_temp.Rows[0]["point_1_3"].ToString() != doc["point_1_3"].ToString() ||
                        dt_temp.Rows[0]["point_1_4"].ToString() != doc["point_1_4"].ToString() ||
                        dt_temp.Rows[0]["point_1_5"].ToString() != doc["point_1_5"].ToString() ||
                        dt_temp.Rows[0]["point_2_3"].ToString() != doc["point_2_3"].ToString() ||
                        dt_temp.Rows[0]["point_2_4"].ToString() != doc["point_2_4"].ToString() ||
                        dt_temp.Rows[0]["point_2_5"].ToString() != doc["point_2_5"].ToString() ||
                        dt_temp.Rows[0]["point_other_0"].ToString() != doc["point_other_0"].ToString())
                    {
                       sql = " insert into point" +
                             " (timespan,website,start_time,host,client,"+
                             "  point_1_0,point_2_0,point_3_0,point_4_0,point_5_0,point_2_1,point_3_1,point_4_1,point_5_1,point_3_2,point_4_2,point_5_2,point_other_3,"+
                             "  point_0_0,point_1_1,point_2_2,point_3_3,point_other_1"+
                             "  point_0_1,point_0_2,point_0_3,point_0_4,point_0_5,point_1_2,point_1_3,point_1_4,point_1_5,point_2_3,point_2_4,point_2_5,point_other_0)"+
                             " values" +
                             " ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}',"+
                             "  '{22}','{23}','{24}','{25}','{26}','{27}','{28}','{29}','{30}','{31}','{32}','{33}','{34}','{35}',)";

                        sql = string.Format(sql,doc["doc_id"].ToString(),doc["website"].ToString(),doc["start_time"].ToString(),doc["host"].ToString(),doc["client"].ToString(),
                                            doc["point_1_0"].ToString(), doc["point_2_0"].ToString(), doc["point_3_0"].ToString(), doc["point_4_0"].ToString(), doc["point_5_0"].ToString(),
                                            doc["point_2_1"].ToString(), doc["point_3_1"].ToString(), doc["point_4_1"].ToString(), doc["point_5_1"].ToString(),
                                            doc["point_3_2"].ToString(), doc["point_4_2"].ToString(), doc["point_5_2"].ToString(),
                                            doc["point_other_3"].ToString(),
                                            doc["point_0_0"].ToString(), doc["point_1_1"].ToString(), doc["point_2_2"].ToString(), doc["point_3_3"].ToString(),
                                            doc["point_other_1"].ToString(),
                                            doc["point_0_1"].ToString(), doc["point_0_2"].ToString(), doc["point_0_3"].ToString(), doc["point_0_4"].ToString(), doc["point_0_5"].ToString(),
                                            doc["point_1_2"].ToString(), doc["point_1_3"].ToString(), doc["point_1_4"].ToString(), doc["point_1_5"].ToString(),
                                            doc["point_2_3"].ToString(), doc["point_2_4"].ToString(), doc["point_2_5"].ToString(),
                                            doc["point_other_0"].ToString());
                        SQLServerHelper.exe_sql(sql);
                    }
                    break;
                case "total":
                    sql = " select max(timespan) from total" +
                          " where website='{0}'"+
                          " start_time='{1}'" +
                          " and host='{2}'" +
                          " and client='{3}'";
                    sql = string.Format(sql, doc["website"].ToString(),doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString());
                    max_timespan = SQLServerHelper.get_table(sql).Rows[0][0].ToString();

                    sql = " select * from total" +
                          " where website='{0}'"+
                          " start_time='{1}'" +
                          " and host='{2}'" +
                          " and client='{3}'" +
                          " and timespan='{4}'";
                    sql = string.Format(sql, doc["website"].ToString(),doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(), max_timespan);
                    dt_temp = SQLServerHelper.get_table(sql);
                    if (dt_temp.Rows[0]["total_0"].ToString() != doc["total_0"].ToString() ||
                        dt_temp.Rows[0]["total_1"].ToString() != doc["total_1"].ToString() ||
                        dt_temp.Rows[0]["total_2"].ToString() != doc["total_2"].ToString() ||
                        dt_temp.Rows[0]["total_3"].ToString() != doc["total_3"].ToString() ||
                        dt_temp.Rows[0]["total_4"].ToString() != doc["total_4"].ToString() ||
                        dt_temp.Rows[0]["total_5"].ToString() != doc["total_5"].ToString() ||
                        dt_temp.Rows[0]["total_6"].ToString() != doc["total_6"].ToString() ||
                       dt_temp.Rows[0]["total_more"].ToString() != doc["total_more"].ToString())
                    {
                       sql = " insert into total" +
                             " (timespan,website,start_time,host,client,total_0,total_1,total_2,total_3,total_4,total_5,total_6,total_more" +
                             "  values"+
                             " ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}')";
                        sql = string.Format(sql, doc["doc_id"].ToString(), doc["website"].ToString(), doc["start_time"].ToString(), doc["host"].ToString(), doc["client"].ToString(),
                                            doc["total_0"].ToString(), doc["total_1"].ToString(), doc["total_2"].ToString(), doc["total_3"].ToString(), doc["total_4"].ToString(),
                                            doc["total_5"].ToString(), doc["total_6"].ToString(), doc["total_more"].ToString());
                        SQLServerHelper.exe_sql(sql);
                    }
                    break;
                default:
                    break;
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Get a non running message from queue
        /// </summary>
        /// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
        /// <param name="resetRunning">duration before this message is considered abandoned and will be given with another call to Get()</param>
        /// <param name="wait">duration to keep polling before returning null</param>
        /// <param name="poll">duration between poll attempts</param>
        /// <returns>message or null</returns>
        /// <exception cref="ArgumentNullException">query is null</exception>
        public BsonDocument Get(QueryDocument query, TimeSpan resetRunning, TimeSpan wait, TimeSpan poll)
        {
            if (query == null) throw new ArgumentNullException("query");

            //reset stuck messages
            collection.Update(
                new QueryDocument { { "running", true }, { "resetTimestamp", new BsonDocument("$lte", DateTime.UtcNow) } },
                new UpdateDocument("$set", new BsonDocument("running", false)),
                UpdateFlags.Multi
            );

            var builtQuery = new QueryDocument("running", false);
            foreach (var field in query)
                builtQuery.Add("payload." + field.Name, field.Value);

            builtQuery.Add("earliestGet", new BsonDocument("$lte", DateTime.UtcNow));

            var resetTimestamp = DateTime.UtcNow;
            try
            {
                resetTimestamp += resetRunning;
            }
            catch (ArgumentOutOfRangeException)
            {
                resetTimestamp = resetRunning > TimeSpan.Zero ? DateTime.MaxValue : DateTime.MinValue;
            }

            var sort = new SortByDocument { { "priority", 1 }, { "created", 1 } };
            var update = new UpdateDocument("$set", new BsonDocument { { "running", true }, { "resetTimestamp", resetTimestamp } });
            var fields = new FieldsDocument("payload", 1);

            var end = DateTime.UtcNow;
            try
            {
                end += wait;
            }
            catch (ArgumentOutOfRangeException)
            {
                end = wait > TimeSpan.Zero ? DateTime.MaxValue : DateTime.MinValue;
            }

            while (true)
            {
                var message = collection.FindAndModify(builtQuery, sort, update, fields, false, false).ModifiedDocument;
                if (message != null)
                    //using merge without overwriting so a possible id in payload doesnt wipe it out the generated one
                    return new BsonDocument("id", message["_id"]).Merge(message["payload"].AsBsonDocument);

                if (DateTime.UtcNow >= end)
                    return null;

                try
                {
                    Thread.Sleep(poll);
                }
                catch (ArgumentOutOfRangeException)
                {
                    poll = poll < TimeSpan.Zero ? TimeSpan.Zero : TimeSpan.FromMilliseconds(int.MaxValue);

                    Thread.Sleep(poll);
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Count in queue
        /// </summary>
        /// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
        /// <param name="running">count running messages or not running</param>
        /// <returns>count</returns>
        /// <exception cref="ArgumentNullException">query is null</exception>
        public long Count(QueryDocument query, bool running)
        {
            if (query == null) throw new ArgumentNullException("query");

            var completeQuery = new QueryDocument("running", running);
            foreach (var field in query)
                completeQuery.Add("payload." + field.Name, field.Value);

            return collection.Count(completeQuery);
        }
Ejemplo n.º 28
0
        public DataTable getMongoData(xFerDb db, xFerQuery q, string mongoCollection)
        {
            DataTable dt = new DataTable();

            if (q.QueryText != null)
            {
                try
                {
                    MongoServer server = MongoServer.Create(db.ConnectionString);
                    MongoDatabase database = server.GetDatabase(db.DbName);

                    MongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(mongoCollection);
                    setQuery(q.QueryText.ToString());
                    QueryDocument _q = new QueryDocument();
                    if (q.QueryText.ToString() == string.Empty)
                    {
                        q.QueryText = "{}";
                    }

                    BsonDocument query = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(_Query);

                    _q.Add(query);

                    FieldsDocument _fields = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<FieldsDocument>(_Field);

                    MongoCursor<BsonDocument> _ret = collection.Find(_q).SetFields(_fields).SetSortOrder(_Sort).SetLimit(_Limit);

                    bool isSet = false;
                    foreach (BsonDocument i in _ret)
                    {

                        if (!isSet)
                        {
                            foreach (BsonElement mei in i.Elements)
                            {
                                dt.Columns.Add(mei.Name);
                                isSet = true;
                            }
                        }


                        DataRow _dr = dt.NewRow();

                        foreach (BsonElement mei in i.Elements)
                        {
                            _dr[mei.Name] = mei.Value;
                        }

                        dt.Rows.Add(_dr);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message.ToString());
                }
            }

            return dt;
        }
Ejemplo n.º 29
0
 private void btn_select_Click(object sender, EventArgs e)
 {
     if (String.IsNullOrEmpty(this.txt_select.Text))
     {
         QueryDocument doc_query = new QueryDocument();
         doc_query.Add("id", this.txt_id.Text);
         BsonDocument doc = MongoHelper.query_bson_from_bson(doc_query);
         this.txt_db_result.Text = doc.ToString();
     }
     else
     {
         QueryDocument doc_query1 = MongoHelper.get_query_from_str(this.txt_select.Text);
         BsonDocument doc1 = MongoHelper.query_bson_from_bson(doc_query1);
         this.txt_db_result.Text = doc1.ToString();
         doc1[""][""][""].ToString();
     }
 }
Ejemplo n.º 30
0
        private void btn_update_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txt_select.Text))
            {
                try
                {
                    QueryDocument doc_query = new QueryDocument();
                    doc_query.Add("id", this.txt_id.Text);

                    UpdateDocument doc_update = MongoHelper.get_update_from_str(this.txt_update.Text);
                    MongoHelper.update_bson(doc_query, doc_update);
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                }
            }
        }