示例#1
0
        public DatingBookUserInfo GetDatingBookUserInfo(string appName, ObjectId userId)
        {
            var datingBookUserInfo = _userDataProvider.GetDatingBookUserInfoByFacebookId(appName, userId);

            if (datingBookUserInfo == null)
                return null;

            if (!CheckIfUserPictureExist(appName, datingBookUserInfo))
                DownloadUserPicture(appName, datingBookUserInfo);

            datingBookUserInfo.LastVisit = DateTime.Now;
            ObjectId visitId = ObjectId.Empty;
            var whiteList = _userDataProvider.GetUsersWhitelist(appName);

            if (!whiteList.Exists((usr) => usr == datingBookUserInfo.FacebookId))
            {
                BsonDocument visit = new BsonDocument();
                visit.Add("dating_book_id", datingBookUserInfo.ObjectId);
                visit.Add("entered_at", datingBookUserInfo.LastVisit);
                visitId = _userDataProvider.InsertVisit(appName, visit);
            }

            datingBookUserInfo = _userDataProvider.UpdateDatingBookLastVisit(appName, datingBookUserInfo, visitId);

            var userEventInfo = new UserEventInfo
            {
                UserId = datingBookUserInfo.ObjectId,
                EventType = 1,
                DateCreated = DateTime.Now
            };

            _userDataProvider.InsertUserEvent(appName, userEventInfo);

            return datingBookUserInfo;
        }
        /// <summary>
        /// Converts all numeric BsonElement values from string represenjtation to numeric values (Int32/Double), i.e. {"id":"1"} => {"id":1}
        /// </summary>
        public static BsonDocument parseNumericElements(this BsonDocument original)         
        {
            var result = new BsonDocument();
            Int32 numInt32;
            Int64 numInt64;
            double numDouble;
            
            foreach(var el in original)
            {
                string elValue = el.Value.ToString();

                if (elValue.Contains('.') && Double.TryParse(elValue, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out numDouble))
                {
                    result.Add(el.Name, numDouble); 
                }
                else if(Int32.TryParse(elValue, out numInt32))
                {
                    result.Add(el.Name, numInt32);
                }
                else if (Int64.TryParse(elValue, out numInt64))
                {
                    result.Add(el.Name, numInt64);
                }
                else
                {
                    result.Add(el);
                }

            }

            return result;
        }
示例#3
0
        static void Main(string[] args)
        {
            var server = MongoServer.Create("mongodb://localhost");

            MongoDatabase test = server.GetDatabase("test");
            MongoCredentials credentials = new MongoCredentials("username", "password");
            MongoDatabase salaries = server.GetDatabase("salaries", credentials);

            MongoCollection docs = test.GetCollection("docs");
            docs.EnsureIndex("title");

            Console.WriteLine("adding some test documents");

            for (int x = 0; x < 1000; x++) {

                BsonDocument doc = new BsonDocument();
                doc.Add("title", "title: " + x);
                doc.Add("body", "body: " + x);
                docs.Insert(doc);
            }

            Console.WriteLine("querying");

            foreach (var doc in docs.FindAllAs<BsonDocument>()) {
                Console.WriteLine("doc: {0}", doc["body"]);
            }
        }
示例#4
0
        public static BsonDocument ToBsonDocument(this XElement xElement)
        {
            var bsonDocument = new BsonDocument();

            var type = xElement.Name.ToString();
            bsonDocument.Add(Constants._TYPE, type);
            var mainId = xElement.Attribute(Constants._ID) != null ? xElement.Attribute(Constants._ID).Value : null;

            foreach (XAttribute attribure in xElement.Attributes())
            {
                var key = attribure.Name.ToString();
                var value = attribure.Value;
                if (bsonDocument.Contains(key))
                    bsonDocument.Set(key, value);
                else
                    bsonDocument.Add(key, value);
            }
            foreach (XElement kid in xElement.Descendants())
            {
                var id = kid.Attribute(Constants._ID);
                if (id == null || mainId == null)
                {
                    bsonDocument.Add(kid.Name.ToString(), kid.ToBsonDocument());
                }
                else
                {
                    kid.SetAttributeValue(Constants.PARENT_ID, mainId);
                    DBFactory.GetData().Save(kid);
                }
            }
            return bsonDocument;
        }
示例#5
0
 public void AddBsonArray()
 {
     var person = new BsonDocument();
     person.Add("Name", new BsonString("Nameirakpam"));
     person.Add("address", new BsonArray(new[] {"Swapanalok","D-504","Pade Basti","Phursungi","Hadapsar"}));
     Console.WriteLine(person.ToJson());
 }
示例#6
0
 /// <summary>
 /// 删除标记
 /// </summary>
 /// <param name="Data">删除条件</param>
 /// <param name="ReceiveMessage">回调消息</param>
 public void RemoveMark(BsonDocument Data, BsonDocument ReceiveMessage)
 {
     Data.Add("ForCase", CaseInfo.CaseName);
     if (mm.RemoveMark(Data.GetValue("MarkName").AsString))
     {
         if (ms.RemoveMark(Data).IsAcknowledged)
         {
             ReceiveMessage.Add("StateCode", 0);
             ReceiveMessage.Add("ReData", "标记已删除!");
             CallBack();
         }
         else
         {
             ReceiveMessage.Add("StateCode", -1);
             ReceiveMessage.Add("ReData", "标记删除失败!");
             CallBack();
         }
     }
     else
     {
         ReceiveMessage.Add("StateCode", -2);
         ReceiveMessage.Add("ReData", "移除邮件标记失败!");
         CallBack();
     }
 }
示例#7
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();
        }
 /// <summary>
 ///     全文检索功能
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnSearch_Click(object sender, EventArgs e)
 {
     //检索文法: http://docs.mongodb.org/manual/reference/command/text/#text-search-languages
     //检索关键字
     BsonDocument TextSearchOption = new BsonDocument().Add(new BsonElement("search", txtKey.Text));
     //语言
     if (cmbLanguage.SelectedIndex != 0)
     {
         TextSearchOption.Add(new BsonElement("language", cmbLanguage.Text));
     }
     //返回数限制
     TextSearchOption.Add(new BsonElement("limit", (BsonValue) NUDLimit.Value));
     try
     {
         CommandResult SearchResult = CommandHelper.ExecuteMongoColCommand("text",
             SystemManager.GetCurrentCollection(), TextSearchOption);
         Result = SearchResult.Response;
         MongoDbHelper.FillDataToTreeView("Text Search Result", trvResult, Result);
         cmdSave.Enabled = true;
     }
     catch (Exception ex)
     {
         SystemManager.ExceptionDeal(ex);
     }
 }
示例#9
0
        private static void InsertGopIpIpBlocks()
        {
            Console.WriteLine("inserting ip blocks");

            var csv = new CsvReader(new StreamReader("GeoLiteCity-Blocks.csv"));

            csv.Read();

            var bsonDocuments = new List<BsonDocument>();

            while (csv.Read())
            {
                var document = new BsonDocument();

                document.Add(new BsonElement("start_ip_num", long.Parse(csv.GetField(0))));
                document.Add(new BsonElement("end_ip_num", long.Parse(csv.GetField(1))));
                document.Add(new BsonElement("location_id", int.Parse(csv.GetField(2))));

                bsonDocuments.Add(document);
            }

            var geoIpDataProvider = new GeoIpDataProvider();

            geoIpDataProvider.InsertGeoIpBlocks(bsonDocuments);

            Console.WriteLine("done");
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="SubNode"></param>
 /// <returns></returns>
 private static BsonDocument ConvertTreeNodeTozTreeBsonDoc(TreeNode SubNode)
 {
     BsonDocument SingleNode = new BsonDocument();
     SingleNode.Add("name", SubNode.Text + GetTagText(SubNode));
     if (SubNode.Nodes.Count == 0)
     {
         SingleNode.Add("icon", "MainTreeImage" + String.Format("{0:00}", SubNode.ImageIndex) + ".png");
     }
     else
     {
         BsonArray ChildrenList = new BsonArray();
         foreach (TreeNode item in SubNode.Nodes)
         {
             ChildrenList.Add(ConvertTreeNodeTozTreeBsonDoc(item));
         }
         SingleNode.Add("children", ChildrenList);
         SingleNode.Add("icon", "MainTreeImage" + String.Format("{0:00}", SubNode.ImageIndex) + ".png");
     }
     if (SubNode.IsExpanded)
     {
         SingleNode.Add("open", "true");
     }
     if (SubNode.Tag != null)
     {
         SingleNode.Add("click", "ShowData('" + SystemManager.GetTagType(SubNode.Tag.ToString()) + "','" + SystemManager.GetTagData(SubNode.Tag.ToString()) + "')");
     }
     return SingleNode;
 }
示例#11
0
        private static void InsertGopIpLocations()
        {
            Console.WriteLine("inserting ip locations");

            var csv = new CsvReader(new StreamReader("GeoLiteCity-Location.csv"));

            csv.Read();

            var bsonDocuments = new List<BsonDocument>();

            while (csv.Read())
            {
                var document = new BsonDocument();

                document.Add(new BsonElement("location_id", int.Parse(csv.GetField(0))));
                document.Add(new BsonElement("country", csv.GetField(1)));
                document.Add(new BsonElement("region", csv.GetField(2)));
                document.Add(new BsonElement("city_name", csv.GetField(3).ToLower()));
                document.Add(new BsonElement("city_display_name", csv.GetField(3)));
                document.Add(new BsonElement("postal_code", csv.GetField(4)));
                document.Add(new BsonElement("latitude", double.Parse(csv.GetField(5))));
                document.Add(new BsonElement("longitude", double.Parse(csv.GetField(6))));
                document.Add(new BsonElement("metro_code",
                    string.IsNullOrEmpty(csv.GetField(7)) ? 0 : int.Parse(csv.GetField(7))));
                document.Add(new BsonElement("area_code", csv.GetField(8)));

                bsonDocuments.Add(document);
            }

            var geoIpDataProvider = new GeoIpDataProvider();

            geoIpDataProvider.InsertGeoIpLocations(bsonDocuments);

            Console.WriteLine("done");
        }
示例#12
0
        /* create english record */
        static BsonDocument CreateEnglisthRecord()
        {
            BsonDocument obj = new BsonDocument();
            try
            {
                obj.Add("name", "tom");
                obj.Add("age", 60);
                obj.Add("id", 2000);

                // an embedded bson object
                BsonDocument phone = new BsonDocument
                {
                    {"0", "1808835242"},
                    {"1", "1835923246"}
                };

                obj.Add("phone", phone);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create record.");
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            return obj;
        }
        public async Task<UserValidationResult> CreateUserAsync(User user)
        {
            var userDoc = new BsonDocument();
           
            foreach (PropertyInfo prop in typeof(User).GetProperties())
            {
                if (prop.Name != "Id")
                {
                    if (prop.GetValue(user) != null)
                    {
                        if (prop.Name == "Role")
                        {
                            userDoc.Add(prop.Name.ToLower(), new BsonDouble((int)(prop.GetValue(user) as Role?)));
                        }
                        else
                        {
                            userDoc.Add(prop.Name.ToLower(), new BsonString(prop.GetValue(user) as string));
                        }
                    }
                    else
                    {
                        userDoc.Add(prop.Name.ToLower(), new BsonString(string.Empty));
                    }   
                }
            }

            await _usersCollection.InsertOneAsync(userDoc).ConfigureAwait(false);

            //check to see if user was actually inserted
             var result = await  GetUsersAsync(user);

            return result;
        }
示例#14
0
 /// <summary>
 /// 查询标记
 /// </summary>
 /// <param name="Data">查询条件</param>
 /// <param name="ReceiveMessage">回调消息</param>
 public void GetMarks(BsonDocument ReceiveMessage)
 {
     List<BsonDocument> MarkList = ms.FindMarks(new BsonDocument("ForCase", CaseInfo.CaseName));
     ReceiveMessage.Add("StateCode", 0);
     ReceiveMessage.Add("ReData", MarkList.ToJson(jsonSettings));
     CallBack();
 }
示例#15
0
        static BsonDocument CreateChineseRecord()
        {
            BsonDocument obj = new BsonDocument();
            try
            {
                obj.Add("姓名", "杰克");
                obj.Add("年龄", 70);
                obj.Add("id", 2001);

                // an embedded bson object
                BsonDocument phone = new BsonDocument
                {
                    {"0", "1808835242"},
                    {"1", "1835923246"}
                };

                obj.Add("电话", phone);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to create record.");
                Console.WriteLine(e.Message);
                Environment.Exit(0);
            }

            return obj;
        }
        public static BsonDocument ToBsonDocument(this Tag tag, BsonDocument document)
        {
            document.Add(new BsonElement("name", new BsonString(tag.Name)));
            document.Add(new BsonElement("type", new BsonString(tag.Type.ToString())));

            return document;
        }
示例#17
0
        private void btn_start_Click(object sender, EventArgs e)
        {
            //线程更新窗体内容
            _thread = new Thread(new ThreadStart(set_txt));
            _thread.Start();

            //线程传递参数
            ParameterizedThreadStart start = new ParameterizedThreadStart(set_txt);
            Thread thread = new Thread(start);
            object obj = "From Thread With Pareameter:Hello ParameterizedThreadStart!!! ";
            thread.Start(obj);

            Thread thread2 = new Thread(() => set_txt("From Thread With Lambda:Hello Lam!!!"));
            thread2.Start();

            ThreadPool.SetMaxThreads(100, 50);
            ThreadPool.QueueUserWorkItem(set_txt, "From Thread With ThreadPool:Hello ThreadPool!!!");

            //传递BsonDocument
            BsonDocument doc_input = new BsonDocument();
            doc_input.Add("sleep", 700);
            doc_input.Add("txt", "From BsonDocument!!!");

            ParameterizedThreadStart start3 = new ParameterizedThreadStart(set_txt_with_doc);
            Thread thread3 = new Thread(start3);
            object obj3 = (object)doc_input;
            thread3.Start(obj3);

            //异步调用
            D_Add handler = new D_Add(f_add);
            sb.AppendLine("Start Add!!");
            IAsyncResult result = handler.BeginInvoke(1, 2, new AsyncCallback(f_complete), "AsycState:OK");
            sb.AppendLine("Start do other work!!");
            this.txt_result.Text = sb.ToString();
        }
示例#18
0
        public override IList<BsonDocument> GetData(string area, string stockCode)
        {
            var docs = new List<BsonDocument>();

            for (int i = 2004; i <= 2015; i++)
            {
                Console.WriteLine("正在处理: " + stockCode + "," + i);

                string url = string.Format(baseUrl, stockCode, i);

                DomFinder _finder = new DomFinder(downloadHtml(url));

                var dataTables = _finder.Find.AllByTagName<HtmlTable>("table");

                HtmlTable dataTable = null;

                foreach (var tbl in dataTables)
                {
                    if (tbl.ID == "BalanceSheetNewTable0")
                    {
                        dataTable = tbl;
                        break;
                    }
                }

                if (dataTable == null)
                {
                    Console.WriteLine("没有找到资产负债表数据," + stockCode + ":" + i);
                    continue;
                }

                var strColPrefix = string.Empty;
                var reportCnt = dataTable.Rows[0].Cells.Count - 1; //第一行数据为报表日期,可以标识出有多少分报表

                for (int j = 0; j < reportCnt; j++)
                {
                    BsonDocument doc = new BsonDocument();
                    doc.Add(new BsonElement("stockCode", new BsonString(stockCode)));

                    strColPrefix = string.Empty;

                    foreach (var row in dataTable.Rows)
                    {
                        if (row.Cells.Count == (reportCnt + 1))
                        {
                            doc.Add(new BsonElement(strColPrefix + "_" + row.Cells[0].InnerText, getCellData(row.Cells[j + 1].InnerText)));
                        }
                        else if (row.Cells.Count == 1)
                        {
                            strColPrefix = row.Cells[0].InnerText;
                        }
                    }

                    docs.Add(doc);
                }
            }

            return docs;
        }
示例#19
0
 /// <summary>
 /// 获取案件的邮件数据
 /// </summary>
 /// <param name="Search">查询对象</param>
 /// <param name="ReceiveMessage">回调消息</param>
 public void GetMailDataForCase(BsonDocument Search, BsonDocument ReceiveMessage)
 {
     Search.Add("ForCase", CaseInfo.CaseName);
     List<BsonDocument> MailData = SortMail(ms.GetMailData(Search), Search);
     ReceiveMessage.Add("StateCode", 0);
     ReceiveMessage.Add("ReData", MailData.ToJson(jsonSettings));
     CallBack();
 }
 /// <summary>
 /// 使用Shell Helper命令
 /// </summary>
 /// <param name="JsShell"></param>
 /// <param name="mongoSvr"></param>
 /// <returns></returns>
 public static CommandResult ExecuteJsShell(String JsShell, MongoServer mongoSvr)
 {
     BsonDocument cmd = new BsonDocument();
     cmd.Add("$eval", new BsonJavaScript(JsShell));
     //必须nolock
     cmd.Add("nolock", true);
     CommandDocument mongoCmd = new CommandDocument() { cmd };
     return ExecuteMongoCommand(mongoCmd, mongoSvr);
 }
        public static void AddLogToCollection(string jsonDocument,string collectionName)
        {
            try
            {
                var document = BsonDocument.Parse(jsonDocument);

                document = CorrectDateField(document);

                var keyValue = document.First().Value.ToString();

                var result = new BsonDocument();
                result.Add("_id", keyValue);

                var mongoRepo = new MongoDBRepository<MongoDBContext>();
                var fResult = mongoRepo.FinObjectByKey(collectionName, keyValue).ToList();

                if (fResult != null && fResult.Count == 1)
                {
                    var value = fResult.First().Last().Value as BsonArray;
                    if (value != null)
                    {
                        var doc = fResult.First().Last().Value as BsonArray;
                        doc.Add(document.Last().Value);
                        CopyMidelElmentInResult(document, result);
                        result.Add(document.Last().Name, doc);
                        mongoRepo.ReplaceOne(keyValue, collectionName, result);
                    }
                    else
                    {
                        var doc = fResult.First().Last().Value as BsonDocument;
                        var list = new BsonArray();
                        list.Add(doc);
                        list.Add(document.Last().Value);
                        CopyMidelElmentInResult(document, result);
                        result.Add(doc.Last().Name, list);
                        mongoRepo.ReplaceOne(keyValue, collectionName, result);
                    }
                }
                else
                {

                    CopyMidelElmentInResult(document, result);
                    var list = new BsonArray();
                    list.Add(document.Last().Value);
                    result.Add(document.Last().Name, list);
                    mongoRepo.AddOne(collectionName, result);
                }

            }
            catch(Exception ex)
            {
                APILogger.Write(ex.Message, LogLevel.Error);
            }
           
        }
示例#22
0
        /// <summary>
        /// Update测试。
        /// </summary>
        /// <param name="sdb"></param>
        static void TestUpdate(Sequoiadb sdb)
        {
            // The collection space name
            string csName = "sample";
            // The collection name
            string cName = "sample";

            // connect
            CollectionSpace cs;
            if (sdb.IsCollectionSpaceExist(csName))
                cs = sdb.GetCollecitonSpace(csName);
            else
                cs = sdb.CreateCollectionSpace(csName);

            DBCollection coll = null;
            if (cs.IsCollectionExist(cName))
                coll = cs.GetCollection(cName);
            else
                coll = cs.CreateCollection(cName);

            // delete all records from the collection
            BsonDocument bson = new BsonDocument();
            coll.Delete(bson);
            
            String[] record = new String[4];
            record[0] = "{cust_id:\"A123\",amount:500,status:\"A\"}";
            record[1] = "{cust_id:\"A123\",amount:250,status:\"A\"}";
            record[2] = "{cust_id:\"B212\",amount:200,status:\"A\"}";
            record[3] = "{cust_id:\"A123\",amount:300,status:\"D\"}";
            // insert record into database
            for (int i = 0; i < record.Length; i++)
            {
                BsonDocument obj = new BsonDocument();
                obj = BsonDocument.Parse(record[i]);
                Console.WriteLine("Record is: " + obj.ToString());
                coll.Insert(obj);
            }
            
            //准备update
            BsonDocument updater = new BsonDocument();
            BsonDocument matcher = new BsonDocument();
            BsonDocument modifier = new BsonDocument();
            BsonDocument hint = new BsonDocument();           

            //条件
            matcher.Add("cust_id", new BsonDocument("$et", "A123"));
            //更新。
            updater.Add("amount", "1000");
            updater.Add("status", "C");
            modifier.Add("$set", updater);
            //update
            coll.Update(matcher, modifier, hint);

            System.Console.ReadLine();
        }
示例#23
0
 public void EmbeedeDocument()
 {
     var person = new BsonDocument();
     person.Add("Name", new BsonString("Nameirakpam"));
     person.Add("contact", new BsonDocument
     {
         {"email","*****@*****.**"},
         {"phone", new BsonString("9022566099")}
     });
     Console.WriteLine(person.ToJson());
 }
示例#24
0
 public void AddElements()
 {
     var person = new BsonDocument
     {
         {"Age", 54 },
         {"IsTall", true }
     };
     person.Add("FirstName", "Yannnis");
     person.Add("Rank", new BsonInt32(10));
     Console.WriteLine(person);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //MyDB db = new MyDB();
            //var coll = db.GetBColl("registration");
            //string sss = "";
            BsonDocument bson = new BsonDocument();
            //BsonElement bstorename = null;
            //var queryformerch = new QueryDocument("type", "merchant");
            //foreach (BsonDocument bmerchs in coll.Find(queryformerch))
            //{
                //bstorename = bmerchs.GetElement("storename");
                //sss += "\"" + bstorename.Value + "\"" + ",";
            //}

            if (Session["order"] != null)
            {
                var myorder = Session["order"].ToString();
                bson.Add("myorder", myorder);
            }

            //string ss1 = "[ " + sss.Remove(sss.Length - 1, 1) + "]";
            //bson.Add("stores", ss1);
            if (Session["objid"] != null)
            {
                Response.Clear();
                Response.CacheControl = "no-cache";
                Response.ContentType = "application/json";
                bson.Add("response", "1");
                Response.Write(bson); //User logged in
                Response.End();
            }
            else
            {
                Response.Clear();
                Response.CacheControl = "no-cache";
                Response.ContentType = "application/json";
                bson.Add("response", "0");
                Response.Write(bson);  ////User logged off
                Response.End();
            }
        }
        catch (ThreadAbortException ee) { }
        catch (Exception eee)
        {
            Response.Clear();
            Response.CacheControl = "no-cache";
            Response.ContentType = "application/json";
            Response.Write("exception");  //Valid User
            Response.End();
        }
    }
示例#26
0
 public string Create(int dvid, BsonDocument data)
 {
     if (!DataDV.GetDV().CheckConnected())
     {
         return Errors.e7006;
     }
     var last = sss.FindAll().LastOrDefault();
     data.Add("dvid", dvid);
     data.Add("ssid", last == null ? 1 : last["ssid"].AsInt32 + 1);
     sss.Insert(data);
     return "{sensor_id:" + data["ssid"].ToString() + "}";
 }
示例#27
0
 public string Create(string appKey, BsonDocument data)
 {
     if (!DataDV.GetDV().CheckConnected())
     {
         return Errors.e7006;
     }
     var last = dvs.FindAll().LastOrDefault();
     data.Add("ukey", appKey);
     data.Add("dvid", last == null ? 1 : last["dvid"].AsInt32 + 1);
     dvs.Insert(data);
     return "{device_id:" + data["dvid"].ToString() + "}";
 }
示例#28
0
        public async void SaveActiveQuests(string npcId) {
            BsonDocument quest = new BsonDocument();

            BsonArray activeQuests = new BsonArray();
            activeQuests.Add(quest);
            
            BsonDocument result = new BsonDocument();
            result.Add("_id", npcId);
            result.Add("ActiveQuests", activeQuests);

            await MongoUtils.MongoData.SaveAsync<BsonDocument>(MongoUtils.MongoData.GetCollection<BsonDocument>("NPCS", "Quests"), q => q["_id"] == npcId, result);
        }
示例#29
0
static void Main(string[] args) {
MongoServer m; try {
m = MongoServer.Create("mongodb://localhost:27017"); //WriteConcern w = new WriteConcern( 1, 2000 ); //m.setWriteConcern( w );
} catch (Exception e) { throw e;
}
MongoDatabase db = m.GetDatabase( "training" ); MongoCollection<BsonDocument> coll = db.GetCollection( "messages" );
for(int i=0; i<10; i++) {
BsonDocument obj = new BsonDocument(); obj.Add( "text", "Hello World!" ); obj.Add( "n", i );
coll.Insert(obj);
}
// Now iterate over the results foreach ( var o in coll.FindAll() ) {
Console.WriteLine( o.ToJson() ); }
示例#30
0
        public static BsonDocument SaFillerAe(List <EntityObject> userEntity, List <EntityObject> computerEntity,
                                              EntityObject domainController, string domainName)
        {
            var records      = new List <BsonDocument>();
            var detailRecord = new BsonDocument();

            for (var i = 0; i < 100000; i++)
            {
                detailRecord.Add("DomainName", domainName);
                detailRecord.Add("Name", "ABCDEFGHIJKLMNOP" + i);
                records.Add(detailRecord);
                detailRecord = new BsonDocument();
            }
            var failedSourceAccountNames  = new BsonArray(records);
            var suspicousActivityDocument = new BsonDocument
            {
                { "_id", ObjectId.GenerateNewId() },
                {
                    "_t", new BsonArray(new[]
                    {
                        "Entity", "Alert", "SuspiciousActivity", "AccountEnumerationSuspiciousActivity"
                    })
                },
                { "StartTime", DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0, 0)) },
                { "EndTime", DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0, 0)) },
                { "IsVisible", BsonValue.Create(true) },
                { "Severity", "Medium" },
                { "Status", "Open" },
                { "TitleKey", "AccountEnumerationSuspiciousActivityTitle" },
                { "TitleDetailKeys", new BsonArray(new string[] { }) },
                { "DescriptionFormatKey", "AccountEnumerationSuspiciousActivityDescription" },
                { "DescriptionDetailFormatKeys", new BsonArray(new string[] { }) },
                { "SystemUpdateTime", DateTime.UtcNow },
                { "HasDetails", BsonValue.Create(false) },
                { "HasInput", BsonValue.Create(false) },
                { "InputTitleKey", "AccountEnumerationSuspiciousActivityInputTitle" },
                { "IsInputProvided", BsonValue.Create(false) },
                { "Note", BsonValue.Create(null) },
                { "RelatedActivityCount", 127 },
                {
                    "RelatedUniqueEntityIds", new BsonArray(new[]
                    {
                        computerEntity[2].Id, domainController.Id, userEntity[0].Id, userEntity[1].Id, userEntity[2].Id,
                        userEntity[3].Id, userEntity[4].Id,
                        userEntity[5].Id, userEntity[6].Id
                    })
                },
                { "SourceComputerId", computerEntity[2].Id },
                { "DestinationComputerIds", new BsonArray(new[] { domainController.Id }) },
                { "FailedSourceAccountNames", failedSourceAccountNames },
                {
                    "SuccessSourceAccountIds", new BsonArray(new[]
                    {
                        userEntity[0].Id, userEntity[1].Id, userEntity[2].Id, userEntity[3].Id, userEntity[4].Id,
                        userEntity[5].Id, userEntity[6].Id
                    })
                }
            };

            return(suspicousActivityDocument);
        }
示例#31
0
        public static BsonDocument NtlmCreator(EntityObject userEntity, EntityObject computerEntity,
                                               EntityObject domainController, string userDomainName, string computerDomainName, ObjectId sourceGateway, EntityObject targetMachine = null,
                                               int daysToSubtruct = 0, int hoursToSubtract = 0)
        {
            var oldTime       = DateTime.UtcNow.Subtract(new TimeSpan(daysToSubtruct, hoursToSubtract, 0, 0, 0));
            var sourceAccount = new BsonDocument {
                { "DomainName", userDomainName }, { "Name", userEntity.Name }
            };
            var sourceComputerName = new BsonDocument {
                { "DomainName", computerDomainName }, { "Name", computerEntity.Name }
            };
            var resourceIdentifier = new BsonDocument();
            var targetAccount      = targetMachine ?? domainController;
            var targetSpnName      = $"krbtgt/{userDomainName}";

            resourceIdentifier.Add("AccountId", targetAccount.Id);
            var resourceName = new BsonDocument {
                { "DomainName", userDomainName }, { "Name", targetSpnName }
            };

            resourceIdentifier.Add("ResourceName", resourceName);
            var destinationComputerName = new BsonDocument {
                { "DomainName", userDomainName }, { "Name", targetAccount.Name }
            };
            var networkActivityDocument = new BsonDocument
            {
                { "_id", ObjectId.GenerateNewId() },
                { "_t", new BsonArray(new[] { "Entity", "NetworkActivity", "Ntlm" }) },
                { "SourceGatewaySystemProfileId", sourceGateway },
                { "SourceComputerId", computerEntity.Id },
                { "DestinationComputerId", targetAccount.Id },
                { "HorizontalParentId", ObjectId.GenerateNewId() },
                { "StartTime", oldTime },
                { "EndTime", oldTime },
                { "SourceIpAddress", "[daf::daf]" },
                { "SourcePort", 51510 },
                { "SourceComputerCertainty", "High" },
                { "SourceComputerResolutionMethod", new BsonArray(new[] { "RpcNtlm" }) },
                { "DestinationIpAddress", "[daf::daf]" },
                { "DestinationPort", 445 },
                { "DestinationComputerCertainty", "High" },
                { "DestinationComputerResolutionMethod", new BsonArray(new[] { "RpcNtlm" }) },
                { "DestinationComputerName", destinationComputerName },
                { "DomainControllerStartTime", oldTime },
                { "TransportProtocol", "Tcp" },
                { "Version", 2 },
                { "SourceComputerName", sourceComputerName },
                { "SourceComputerNetbiosName", computerEntity.Name },
                { "SourceAccountName", sourceAccount },
                { "SourceAccountId", userEntity.Id },
                { "SourceAccountBadPasswordTime", BsonValue.Create(null) },
                { "ResourceIdentifier", resourceIdentifier },
                { "DceRpcStatus", BsonValue.Create(null) },
                { "LdapResultCode", BsonValue.Create(null) },
                { "SmbStatus", "Success" },
                { "Smb1Status", BsonValue.Create(null) },
                { "IsOldPassword", BsonValue.Create(null) },
                { "IsSuccess", BsonValue.Create(true) }
            };

            return(networkActivityDocument);
        }
示例#32
0
        public static BsonDocument SamrCreator(EntityObject userEntity, EntityObject computerEntity,
                                               EntityObject domainController, string userDomainName, string computerDomainName, ObjectId sourceGateway, bool sensitive,
                                               SamrViewModel.SamrQueryType queryType, SamrViewModel.SamrQueryOperation queryOperation, string domainId,
                                               int daysToSubtruct = 0, EntityObject queriedEntityObject = null)
        {
            var dateTime           = DateTime.UtcNow.Subtract(new TimeSpan(daysToSubtruct, 0, 0, 0, 0));
            var sourceComputerName =
                new BsonDocument {
                { "DomainName", computerDomainName }, { "Name", computerEntity.Name }
            };
            var destinationComputerName =
                new BsonDocument {
                { "DomainName", userDomainName }, { "Name", domainController.Name }
            };
            var networkActivityDocument = new BsonDocument
            {
                { "_id", ObjectId.GenerateNewId() },
                { "_t", new BsonArray(new[] { "Entity", "Activity", "NetworkActivity", "Samr", queryType.ToString() }) },
                { "SourceGatewaySystemProfileId", sourceGateway },
                { "HorizontalParentId", ObjectId.GenerateNewId() },
                { "StartTime", dateTime },
                { "EndTime", dateTime },
                { "SourceIpAddress", "[daf::daf]" },
                { "SourcePort", 38014 },
                { "SourceComputerName", sourceComputerName },
                { "SourceComputerId", computerEntity.Id },
                { "SourceComputerCertainty", "High" },
                { "SourceComputerResolutionMethod", new BsonArray(new[] { "RpcNtlm" }) },
                { "DestinationIpAddress", "[daf::200]" },
                { "DestinationPort", 445 },
                { "DestinationComputerName", destinationComputerName },
                { "DestinationComputerId", domainController.Id },
                { "DestinationComputerCertainty", "High" },
                { "DestinationComputerResolutionMethod", new BsonArray(new[] { "RpcNtlm" }) },
                { "DomainControllerStartTime", dateTime },
                { "TransportProtocol", "Tcp" },
                { "NtStatus", "Success" },
                { "OperationType", queryType.ToString() },
                { "DomainId", domainId }
            };

            switch (queryType)
            {
            case SamrViewModel.SamrQueryType.QueryUser:
                networkActivityDocument.Add("UserName", queriedEntityObject?.Name);
                networkActivityDocument.Add("UserId", queriedEntityObject?.Id);
                networkActivityDocument.Add("IsSensitiveUser", BsonBoolean.True);
                break;

            case SamrViewModel.SamrQueryType.QueryGroup:
                networkActivityDocument.Add("GroupName", queriedEntityObject?.Name);
                networkActivityDocument.Add("GroupId", queriedEntityObject?.Id);
                networkActivityDocument.Add("IsSensitiveGroup", BsonBoolean.True);
                break;

            case SamrViewModel.SamrQueryType.EnumerateGroups:
                break;

            case SamrViewModel.SamrQueryType.EnumerateUsers:
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(queryType), queryType, null);
            }
            return(networkActivityDocument);
        }
示例#33
0
        private BsonDocument buildLossSetup(LOSSetup tcd)
        {
            Measurement measurement = null;

            // Initialize object that will be stored under 'device' in mongo document
            BsonDocument nestedDevice = null;

            if (tcd.RxSetup != null)
            {
                try
                {
                    measurement = tcd.RxSetup.Measurement;
                }
                catch (Exception exc)
                {
                    Program.log("ERROR LOS SETUP: " + tcd.Id + " - " + exc.Message);
                }
                finally
                {
                    nestedDevice = SyncManager.Instance.getNestedDevice(measurement);
                }
            }
            if (nestedDevice == null)
            {
                return(null);
            }

            // Initialize object that will be stored under 'meta' in mongo document
            BsonDocument nestedMeta = SyncManager.Instance.getNestedMeta(measurement);

            if (nestedMeta == null)
            {
                return(null);
            }

            // Initialize object that will be stored under 'data' in mongo document
            BsonDocument nestedData = SyncManager.Instance.getNestedData(tcd, excludeDataFields);

            // Custom code to move some set fields to meta object
            nestedMeta.Add("SetTemperature_C", nestedData["SetTemperature"]);
            nestedData.Remove("SetTemperature");
            nestedMeta.Add("SetVoltage", nestedData["SetVoltage"]);
            nestedData.Remove("SetVoltage");

            //System.Diagnostics.Trace.WriteLine("D " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"));

            // Initialize object in root of the document
            BsonDocument rootDoc = new BsonDocument {
                { "_id", tcd.Id.ToString() },
                { "mid", measurement.Id.ToString() },
                { "timestamp", tcd.TimeStamp },
                { "type", domain() },
                { "subtype", "losssetup" },
                { "result", getResult(nestedData["Result"].ToString()) },
                { "downstatus", getDownStatus(nestedData["Result"].ToString()) },
                { "status", getStatus(measurement.Result) }
            };

            nestedData.Remove("Result");

            rootDoc.Add("device", nestedDevice);
            rootDoc.Add("meta", nestedMeta);
            rootDoc.Add("data", nestedData);

            return(rootDoc);
        }
示例#34
0
 /// <summary>
 /// Adds a $all test to the query.
 /// </summary>
 /// <param name="values">A BsonArray of values.</param>
 /// <returns>The builder (so method calls can be chained).</returns>
 public QueryConditionList All(
     BsonArray values
     )
 {
     conditions.Add("$all", values);
     return(this);
 }
示例#35
0
        public static BsonDocument SimpleBindCreator(EntityObject userEntity, EntityObject computerEntity,
                                                     EntityObject domainControllerName, string userDomainName, string computerDomainName, ObjectId sourceGateway, int daysToSubtruct = 0)
        {
            var oldTime       = DateTime.UtcNow.Subtract(new TimeSpan(daysToSubtruct, 0, 0, 0, 0));
            var sourceAccount = new BsonDocument {
                { "DomainName", userDomainName }, { "Name", userEntity.Name }
            };
            var sourceComputerName = new BsonDocument {
                { "DomainName", computerDomainName }, { "Name", computerEntity.Name }
            };
            var resourceIdentifier = new BsonDocument {
                { "AccountId", domainControllerName.Id }
            };
            var targetSpnName = $"krbtgt/{userDomainName}";
            var resourceName  = new BsonDocument {
                { "DomainName", userDomainName }, { "Name", targetSpnName }
            };

            resourceIdentifier.Add("ResourceName", resourceName);
            var destinationComputerName = new BsonDocument
            {
                { "DomainName", userDomainName },
                { "Name", domainControllerName.Name }
            };
            var networkActivityDocument = new BsonDocument
            {
                { "_id", ObjectId.GenerateNewId() },
                { "_t", new BsonArray(new[] { "Entity", "Activity", "NetworkActivity", "Ldap", "LdapBind" }) },
                { "StartTime", oldTime },
                { "EndTime", oldTime },
                { "HorizontalParentId", ObjectId.GenerateNewId() },
                { "SourceIpAddress", "[daf::daf]" },
                { "SourcePort", 6666 },
                { "SourceComputerId", computerEntity.Id },
                { "SourceComputerName", sourceComputerName },
                { "SourceComputerCertainty", "High" },
                { "SourceComputerResolutionMethod", new BsonArray(new[] { "RpcNtlm" }) },
                { "DestinationIpAddress", "[daf::daf]" },
                { "DestinationPort", 389 },
                { "DestinationComputerId", domainControllerName.Id },
                { "DestinationComputerCertainty", "High" },
                { "DestinationComputerName", destinationComputerName },
                { "DestinationComputerResolutionMethod", new BsonArray(new[] { "RpcNtlm" }) },
                { "DomainControllerStartTime", oldTime },
                { "TransportProtocol", "Tcp" },
                { "AuthenticationType", "Simple" },
                { "SourceAccountName", sourceAccount },
                { "SourceAccountId", userEntity.Id },
                {
                    "SourceAccountPasswordHash",
                    "9apJEBIqcse0SNKVm4WzIxaHoLkUareMCDlAzhADI72CLmxOMmA8WzicPPI84xxlewEEIqZZOJJ1VqpE5VJT4g=="
                },
                { "ResultCode", "Success" },
                { "IsSuccess", BsonValue.Create(true) },
                { "SourceGatewaySystemProfileId", sourceGateway },
                { "SourceAccountBadPasswordTime", BsonValue.Create(null) },
                { "IsOldPassword", BsonValue.Create(null) },
                { "ResourceIdentifier", resourceIdentifier }
            };

            return(networkActivityDocument);
        }
示例#36
0
        /// <summary>
        /// 数据接收处理,失败后抛出NullReferenceException异常,主线程会进行捕获
        /// cool62061/1.html?s=10&d=0
        ///
        /// </summary>
        /// <param name="args">url参数</param>
        public void DataReceive(DataReceivedEventArgs args)
        {
            HtmlDocument htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(args.Html);
            var root             = htmlDoc.DocumentNode;
            var contentTableNode = htmlDoc.GetElementbyId("content");
            var projId           = args.urlInfo.UniqueKey;
            var page             = GetUrlParam(args.Url, "page");

            //获取页数
            if (contentTableNode != null)
            {
                var add        = 0;
                var update     = 0;
                var trNodeList = contentTableNode.SelectNodes("//table/tr").Where(c => !c.InnerText.Contains("楼盘表"));
                if (trNodeList != null)
                {
                    foreach (var trNode in trNodeList)
                    {
                        if (trNode.InnerText.Contains("房屋代码") || trNode.InnerText.Contains("面积"))
                        {
                            continue;
                        }
                        if (trNode.InnerText.Contains("页/共"))
                        {
                            continue;
                        }
                        var tdList = trNode.SelectNodes("./td");
                        if (tdList == null)
                        {
                            continue;
                        }
                        if (tdList.Count == 9)
                        {
                            var codeNode = tdList[0];
                            var code     = GetInnerText(codeNode).Trim();
                            var aNode    = codeNode.SelectSingleNode("./a");
                            if (aNode == null || aNode.Attributes["href"] == null)
                            {
                                continue;
                            }
                            var href       = aNode.Attributes["href"].Value;
                            var houseId    = GetGuidFromUrl(href);
                            var buildNO    = GetInnerText(tdList[1]).Trim();
                            var unitNO     = GetInnerText(tdList[2]).Trim();
                            var roomNo     = GetInnerText(tdList[3]).Trim();
                            var purpose    = GetInnerText(tdList[4]).Trim();
                            var saleArea   = GetInnerText(tdList[5]).Trim();
                            var drawStatus = GetInnerText(tdList[6]).Trim();
                            var price      = GetInnerText(tdList[7]).Trim();
                            var saleStatus = GetInnerText(tdList[8]).Trim();
                            var houseDoc   = new BsonDocument();
                            houseDoc.Add("houseId", houseId);
                            houseDoc.Add("code", code);
                            houseDoc.Add("buildNO", buildNO);
                            houseDoc.Add("unitNO", unitNO);
                            houseDoc.Add("roomNo", roomNo);
                            houseDoc.Add("purpose", purpose);
                            houseDoc.Add("saleArea", saleArea);
                            houseDoc.Add("drawStatus", drawStatus);
                            houseDoc.Add("price", price);
                            houseDoc.Add("saleStatusName", saleStatus);
                            houseDoc.Add("projId", projId);
                            if (saleStatus == "待售")
                            {
                                houseDoc.Set("saleStatus", "0");
                            }
                            if (saleStatus == "已售")
                            {
                                houseDoc.Set("saleStatus", "1");
                            }
                            var curHouseObj = this.dataop.FindOneByQuery(this.DataTableNameHouse, Query.EQ("houseId", houseId));
                            if (!idFilter.Contains(houseId) && curHouseObj == null)
                            {
                                add++;
                                DBChangeQueue.Instance.EnQueue(new StorageData()
                                {
                                    Document = houseDoc, Name = DataTableNameHouse, Type = StorageType.Insert
                                });
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(curHouseObj.Text("projId")))
                                {
                                    var updateDoc = new BsonDocument().Add("projId", projId);
                                    DBChangeQueue.Instance.EnQueue(new StorageData()
                                    {
                                        Document = updateDoc, Query = Query.EQ("houseId", houseId), Name = DataTableNameHouse, Type = StorageType.Update
                                    });
                                }
                                update++;
                            }
                        }
                        else
                        {
                            Console.WriteLine("列Td格式大于9个");
                        }
                    }

                    Console.WriteLine("新增{0}更新:{1}", add, update);
                    //获取其他分页
                    if (string.IsNullOrEmpty(page) || page == "1")
                    {
                        var pageSpan = contentTableNode.SelectSingleNode("//span[@class='pagelist_last']/a");
                        if (pageSpan != null && pageSpan.Attributes["href"] != null)
                        {
                            var num        = GetUrlParam(pageSpan.Attributes["href"].Value, "page");
                            var maxPageNum = 0;
                            if (int.TryParse(num, out maxPageNum))
                            {
                                Console.WriteLine("获取页数{0}", maxPageNum);
                                for (var i = 2; i <= maxPageNum; i++)
                                {
                                    var url = string.Format("{0}&page={1}", args.Url, i);
                                    if (!filter.Contains(url))//详情添加
                                    {
                                        filter.Add(url);
                                        UrlQueue.Instance.EnQueue(new UrlInfo(url)
                                        {
                                            Depth = args.urlInfo.Depth, PostData = args.urlInfo.PostData, UniqueKey = args.urlInfo.UniqueKey
                                        });
                                    }
                                }
                            }
                        }
                    }
                    //  DBChangeQueue.Instance.EnQueue(new StorageData() { Document = new BsonDocument().Add("isUpdate",1) , Name = DataTableName,Query=Query.EQ("projId", projId), Type = StorageType.Update });
                }
            }
        }
示例#37
0
        public async Task <List <ExpedienteDTO> > filtrado(ParametrosBusquedaExpediente parametrosbusqueda)
        {
            BsonArray embebedpipeline = new BsonArray();

            embebedpipeline.Add(
                new BsonDocument("$match", new BsonDocument(
                                     "$expr", new BsonDocument(
                                         "$eq", new BsonArray {
                "$_id", new BsonDocument(
                    "$toObjectId", "$$iddoc")
            }
                                         ))));
            var lookup = new BsonDocument("$lookup",
                                          new BsonDocument("from", "documentos").
                                          Add("let", new BsonDocument("iddoc", "$documentos.iddocumento")).
                                          Add("pipeline", embebedpipeline).
                                          Add("as", "documentoobj"));

            var filtroDocumento = new BsonDocument();

            if (parametrosbusqueda.estado != null & parametrosbusqueda.estado != "")
            {
                filtroDocumento.Add("estado",
                                    new BsonDocument("$regex", parametrosbusqueda.estado + ".*")
                                    .Add("$options", "i"));
            }

            if (parametrosbusqueda.tipo != null & parametrosbusqueda.tipo != "")
            {
                filtroDocumento.Add("tipo",
                                    new BsonDocument("$regex", parametrosbusqueda.tipo + ".*")
                                    .Add("$options", "i"));
            }

            if (parametrosbusqueda.nombrecliente != null & parametrosbusqueda.nombrecliente != "")
            {
                filtroDocumento.Add("cliente.nombre",
                                    new BsonDocument("$regex", parametrosbusqueda.nombrecliente + ".*")
                                    .Add("$options", "i"));
            }


            List <ExpedienteDTO> expedientes = new List <ExpedienteDTO>();

            expedientes = await _expedientes.Aggregate()
                          .Unwind <Expediente, ExpedienteDTO_ur1>(e => e.documentos)
                          .AppendStage <ExpedienteDTO_look_up>(lookup)
                          .Unwind <ExpedienteDTO_look_up, ExpedienteDTO_ur2>(p => p.documentoobj)
                          .Group <ExpedienteDTO>(new BsonDocument
            {
                { "_id", "$_id" },
                {
                    "tipo", new BsonDocument
                    {
                        { "$first", "$tipo" }
                    }
                },
                { "cliente", new BsonDocument {
                      { "$first", "$cliente" }
                  } },
                { "fechainicio", new BsonDocument {
                      { "$first", "$fechainicio" }
                  } },
                { "fechafin", new BsonDocument {
                      { "$first", "$fechafin" }
                  } },
                { "documentos", new BsonDocument {
                      { "$push", "$documentos" }
                  } },
                { "documentosobj", new BsonDocument {
                      { "$push", "$documentoobj" }
                  } },
                { "derivaciones", new BsonDocument {
                      { "$first", "$derivaciones" }
                  } },
                { "estado", new BsonDocument {
                      { "$first", "$estado" }
                  } }
            })
                          .Match(filtroDocumento)
                          .ToListAsync();

            return(expedientes);
        }
        private void convertItems(String table)
        {
            var coll = database.GetCollection <BsonDocument>(table);

            tbProgressLog.Text += "Started processing table " + table + "\r\n";
            connectionString    = tbConnectionString.Text;
            using (conn = new SqlConnection(connectionString))
            {
                string query = "SELECT * FROM " + table;

                using (objcmd = new SqlCommand(query, conn))
                {
                    database.DropCollection(table);
                    conn.Open();
                    SqlDataReader       objReader = objcmd.ExecuteReader();
                    List <BsonDocument> bsonlist  = new List <BsonDocument>(10000000);
                    while (objReader.Read())
                    {
                        BsonDocument objBson = new BsonDocument();
                        for (int j = 0; j < objReader.FieldCount; j++)
                        {
                            //CHECK TYPE OF ALL COLUMN NAMES SO THAT WE CAN STORE ALL RECORDS IN COLLECTION "DATATYPE WISE"
                            if (objReader[j].GetType() == typeof(String))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), objReader[j].ToString()));
                            }
                            else if ((objReader[j].GetType() == typeof(Int16)))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), BsonValue.Create(objReader.GetInt16(j))));
                            }
                            else if ((objReader[j].GetType() == typeof(Int32)))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), BsonValue.Create(objReader.GetInt32(j))));
                            }
                            else if ((objReader[j].GetType() == typeof(Int64)))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), BsonValue.Create(objReader.GetInt64(j))));
                            }
                            else if (objReader[j].GetType() == typeof(Decimal))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), BsonValue.Create(objReader.GetDecimal(j))));
                            }
                            else if (objReader[j].GetType() == typeof(Double))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), BsonValue.Create(objReader.GetDouble(j))));
                            }
                            else if (objReader[j].GetType() == typeof(DateTime))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), BsonValue.Create(objReader.GetDateTime(j))));
                            }
                            else if (objReader[j].GetType() == typeof(Boolean))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), BsonValue.Create(objReader.GetBoolean(j))));
                            }
                            else if (objReader[j].GetType() == typeof(DBNull))
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), BsonNull.Value));
                            }
                            else
                            {
                                objBson.Add(new BsonElement(objReader.GetName(j), objReader[j].ToString()));
                            }
                        }

                        bsonlist.Add(objBson);
                    }
                    coll = database.GetCollection <BsonDocument>(table);
                    coll.InsertMany(bsonlist);
                    bsonlist.RemoveRange(0, bsonlist.Count);
                }
            }
            tbProgressLog.Text += "Finishing migrating table " + table + "\r\n";
        }
示例#39
0
        /// <summary>
        ///     OK
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            //Project
            var project     = QueryFieldPicker.GetAggregation();
            var supressAggr = project[0];
            var projectAggr = project[1];

            if (supressAggr[0].AsBsonDocument.ElementCount > 0)
            {
                Aggregation.Add(supressAggr);
            }
            //TODO:需要优化,全项目的时候,不用输出
            if (projectAggr[0].AsBsonDocument.ElementCount > 0)
            {
                Aggregation.Add(projectAggr);
            }

            //match
            var match = ConditionPan.GetMatchDocument();

            if (match != null)
            {
                Aggregation.Add(match);
            }

            //Sort
            var sort = SortPanel.GetSortDocument();

            if (sort != null)
            {
                Aggregation.Add(sort);
            }

            //Group
            if (chkIdNull.Checked)
            {
                var id = new BsonDocument
                {
                    new BsonElement("_id", BsonNull.Value)
                };
                id.AddRange(FieldsElement.Value.AsBsonDocument.Elements);
                var group = new BsonDocument("$group", id);
                Aggregation.Add(group);
            }
            else
            {
                if (!string.IsNullOrEmpty(GroupIdElement.Name))
                {
                    var id = new BsonDocument
                    {
                        new BsonElement("_id", GroupIdElement.Value)
                    };
                    id.AddRange(FieldsElement.Value.AsBsonDocument.Elements);
                    var group = new BsonDocument("$group", id);
                    Aggregation.Add(group);
                }
            }


            //Skip
            if (chkSkip.Checked && int.Parse(txtSkip.Text) > 0)
            {
                Aggregation.Add(new BsonDocument("$skip", int.Parse(txtSkip.Text)));
            }
            //Limit
            if (chkLimit.Checked && int.Parse(txtLimit.Text) > 0)
            {
                Aggregation.Add(new BsonDocument("$limit", int.Parse(txtLimit.Text)));
            }
            //IndexStats
            if (chkIndexStats.Checked)
            {
                Aggregation.Add(new BsonDocument("$indexStats", new BsonDocument()));
            }
            //sortByCount
            if (chkSortByCount.Checked)
            {
                Aggregation.Add(new BsonDocument("$sortByCount", cmbSortByCount.Text));
            }
            //Sample
            if (chkSample.Checked)
            {
                var size = new BsonDocument("size", (int.Parse(txtSample.Text)));
                Aggregation.Add(new BsonDocument("$sample", size));
            }
            //unwind
            if (chkUnwind.Checked)
            {
                if (!chkPreserveNullAndEmptyArrays.Checked && string.IsNullOrEmpty(txtincludeArrayIndex.Text))
                {
                    Aggregation.Add(new BsonDocument("$unwind", cmbUnwind.Text));
                }
                else
                {
                    var UnwindDoc = new BsonDocument();
                    var field     = new BsonElement("path", cmbUnwind.Text);
                    UnwindDoc.Add(field);
                    if (chkPreserveNullAndEmptyArrays.Checked)
                    {
                        var preserveNullAndEmptyArrays = new BsonElement("preserveNullAndEmptyArrays", BsonBoolean.True);
                        UnwindDoc.Add(preserveNullAndEmptyArrays);
                    }
                    if (!string.IsNullOrEmpty(txtincludeArrayIndex.Text))
                    {
                        var includeArrayIndex = new BsonElement("includeArrayIndex", txtincludeArrayIndex.Text);
                        UnwindDoc.Add(includeArrayIndex);
                    }
                    Aggregation.Add(new BsonDocument("$unwind", UnwindDoc));
                }
            }
            Close();
        }
示例#40
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["objid"] != null)
            {
                string       type_user = Session["typeofuser"].ToString();
                string       objectidvalue = Session["objid"].ToString();
                MyDB         md = new MyDB();
                var          orders = md.GetBColl("orders");
                var          queryid = new QueryDocument("user", objectidvalue);
                BsonDocument borders = new BsonDocument();
                string       str1 = null; string str2 = null; string str3 = null;
                bool         val = Convert.ToBoolean(orders.Find(queryid).Count());

                string strusertomer = Session["mertouser"].ToString();
                if (strusertomer == "205")
                {
                    foreach (BsonDocument bit in orders.Find(queryid))
                    {
                        borders = null;
                        borders = new BsonDocument();
                        borders.Add("mobile", bit.GetElement("mobile").Value.ToDouble());
                        borders.Add("order", bit.GetElement("order").Value);
                        str2 += borders.ToJson() + ",";
                        str3  = str2;
                    }
                    if (str2 != null)
                    {
                        str1 = str2.Remove(str2.Length - 1, 1);
                        Response.Clear();
                        Response.CacheControl = "no-cache";
                        Response.ContentType  = "application/json";
                        Response.Write(str1);
                        Session["mertouser"] = "******";
                        Response.End();
                    }
                    else
                    {
                        Response.Clear();
                        Response.CacheControl = "no-cache";
                        Response.ContentType  = "application/json";
                        Response.Write("407");
                        Session["mertouser"] = "******";
                        Response.End();
                    }
                }
                if (type_user == "merchant")
                {
                    Response.Write("105");
                    Response.End();
                    //goto letsgo;
                }

                if (val)
                {
                    foreach (BsonDocument bit in orders.Find(queryid))
                    {
                        borders = null;
                        borders = new BsonDocument();
                        borders.Add("mobile", bit.GetElement("mobile").Value.ToDouble());
                        borders.Add("order", bit.GetElement("order").Value);
                        str2 += borders.ToJson() + ",";
                        str3  = str2;
                    }
                    str1 = str2.Remove(str2.Length - 1, 1);
                    Response.Clear();
                    Response.CacheControl = "no-cache";
                    Response.ContentType  = "application/json";
                    Response.Write(str1);
                    Response.End();
                }

                else
                {
                    Response.Clear();
                    Response.CacheControl = "no-cache";
                    Response.ContentType  = "application/json";
                    Response.Write("0");
                    Response.End();
                }
            }
            else
            {
                Response.Clear();
                Response.CacheControl = "no-cache";
                Response.ContentType  = "application/json";
                Response.Write("77");
                Response.End();
            }
        }
        catch (ThreadAbortException ee) { }
        catch (Exception eee)
        {
            Response.Clear();
            Response.CacheControl = "no-cache";
            Response.ContentType  = "application/json";
            Response.Write("exception");  //Valid User
            Response.End();
        }
    }
        // private methods
        private void Run(BsonDocument shared, BsonDocument test)
        {
            JsonDrivenHelper.EnsureAllFieldsAreValid(shared, "_path", "database_name", "database2_name", "collection_name", "collection2_name", "tests");
            JsonDrivenHelper.EnsureAllFieldsAreValid(test, "description", "minServerVersion", "maxServerVersion", "topology", "target", "changeStreamPipeline", "changeStreamOptions", "operations", "expectations", "result", "async", "failPoint");

            RequireServer.Check().RunOn(EmulateRunOn());

            _databaseName    = shared["database_name"].AsString;
            _database2Name   = shared.GetValue("database2_name", null)?.AsString;
            _collectionName  = shared["collection_name"].AsString;
            _collection2Name = shared.GetValue("collection2_name", null)?.AsString;

            CreateCollections();

            List <ChangeStreamDocument <BsonDocument> > actualResult = null;
            Exception actualException = null;
            List <CommandStartedEvent> actualEvents = null;

            var eventCapturer = CreateEventCapturer();

            using (ConfigureFailPoint(test))
                using (var client = CreateDisposableClient(eventCapturer))
                {
                    try
                    {
                        var async = test["async"].AsBoolean;
                        using (var cursor = Watch(client, test, async))
                        {
                            var globalClient = DriverTestConfiguration.Client;
                            ExecuteOperations(globalClient, test["operations"].AsBsonArray);

                            actualResult = ReadChangeStreamDocuments(cursor, test, async);
                            actualEvents = GetEvents(eventCapturer);
                        }
                    }
                    catch (Exception exception)
                    {
                        actualException = exception;
                    }
                }

            if (test.Contains("expectations") && actualEvents != null)
            {
                var expectedEvents = test["expectations"].AsBsonArray.Cast <BsonDocument>().ToList();
                AssertEvents(actualEvents, expectedEvents);
            }

            if (test.Contains("result"))
            {
                var expectedResult = test["result"].AsBsonDocument;
                AssertResult(actualResult, actualException, expectedResult);
            }

            BsonArray EmulateRunOn()
            {
                var condition = new BsonDocument();

                if (test.TryGetElement("minServerVersion", out var minServerVersion))
                {
                    condition.Add(minServerVersion);
                }
                if (test.TryGetElement("maxServerVersion", out var maxServerVersion))
                {
                    condition.Add(maxServerVersion);
                }
                if (test.TryGetElement("topology", out var topology))
                {
                    condition.Add(topology);
                }

                return(new BsonArray {
                    condition
                });
            }
        }
示例#42
0
        /// <summary>
        /// 数据接收处理,失败后抛出NullReferenceException异常,主线程会进行捕获
        /// cool62061/1.html?s=10&d=0
        ///
        /// </summary>
        /// <param name="args">url参数</param>
        public void DataReceive(DataReceivedEventArgs args)
        {
            //获取图片地址
            HtmlDocument htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(args.Html);
            var root    = htmlDoc.DocumentNode;
            var trNodes = root.SelectNodes("//tr[contains(@onclick,'FirstHandProjectInfo.jsp')]");

            if (trNodes != null)
            {
                var add    = 0;
                var update = 0;
                foreach (HtmlNode aNode in trNodes)
                {
                    if (aNode.Attributes["onclick"].Value == null || !aNode.Attributes["onclick"].Value.ToString().Contains("FirstHandProjectInfo"))
                    {
                        continue;
                    }
                    if (aNode != null && aNode.Attributes["onclick"] != null)
                    {
                        var tdNodes = aNode.SelectNodes("./td");
                        if (tdNodes.Count() < 6)
                        {
                            Console.WriteLine("列名与字段无法对应正在跳出");
                            continue;
                        }
                        var url = Toolslib.Str.Sub(aNode.Attributes["onclick"].Value.ToString(), "('", "')");
                        if (string.IsNullOrEmpty(url))
                        {
                            Console.WriteLine("url为空");
                            continue;
                        }
                        var projId = Toolslib.Str.Sub(url, "projectID=", "");
                        if (string.IsNullOrEmpty(projId))
                        {
                            Console.WriteLine("projId为空");
                            continue;
                        }
                        var curDoc = new BsonDocument();
                        curDoc.Add("projId", projId);
                        curDoc.Add("no", tdNodes[0].InnerText.Trim());
                        curDoc.Add("saleNo", tdNodes[1].InnerText.Trim());
                        curDoc.Add("name", tdNodes[2].InnerText.Trim());
                        curDoc.Add("address", tdNodes[3].InnerText.Trim());
                        curDoc.Add("saleDate", tdNodes[4].InnerText.Trim());
                        curDoc.Add("region", tdNodes[5].InnerText.Trim());
                        curDoc.Add("url", url);


                        ///cool286073/1.html?s=11
                        //提取数字

                        if (!idFilter.Contains(projId) && !hasExistObj(projId))
                        {
                            add++;
                            this.idFilter.Add(projId);
                            DBChangeQueue.Instance.EnQueue(new StorageData()
                            {
                                Document = curDoc, Name = DataTableName, Type = StorageType.Insert
                            });
                        }
                        else
                        {
                            update++;
                            //Console.WriteLine("已存在");
                        }
                    }
                }
                Console.WriteLine("增加:{0}更新:{1}", add, update);
            }
            else
            {
                Console.WriteLine("目录不存在");
            }
        }
        public void CorpusTest(
            [Values(false, true)] bool useLocalSchema,
            [Values(false, true)] bool async)
        {
            RequireServer.Check().Supports(Feature.ClientSideEncryption);

            var corpusSchema = JsonFileReader.Instance.Documents["corpus.corpus-schema.json"];
            var schemaMap    = useLocalSchema ? new BsonDocument("db.coll", corpusSchema) : null;

            using (var client = ConfigureClient())
                using (var clientEncrypted = ConfigureClientEncrypted(schemaMap))
                    using (var clientEncryption = ConfigureClientEncryption(clientEncrypted.Wrapped as MongoClient))
                    {
                        CreateCollection(client, __collCollectionNamespace, new BsonDocument("$jsonSchema", corpusSchema));

                        var corpusKeyLocal     = JsonFileReader.Instance.Documents["corpus.corpus-key-local.json"];
                        var corpusKeyAws       = JsonFileReader.Instance.Documents["corpus.corpus-key-aws.json"];
                        var keyVaultCollection = GetCollection(client, __keyVaultCollectionNamespace);
                        Insert(keyVaultCollection, async, corpusKeyLocal, corpusKeyAws);

                        var corpus       = JsonFileReader.Instance.Documents["corpus.corpus.json"];
                        var corpusCopied = new BsonDocument
                        {
                            corpus.GetElement("_id"),
                            corpus.GetElement("altname_aws"),
                            corpus.GetElement("altname_local")
                        };

                        foreach (var corpusElement in corpus.Elements.Where(c => c.Value.IsBsonDocument))
                        {
                            var corpusValue = corpusElement.Value.DeepClone();
                            var kms         = corpusValue["kms"].AsString;
                            var abbreviatedAlgorithmName = corpusValue["algo"].AsString;
                            var identifier = corpusValue["identifier"].AsString;
                            var allowed    = corpusValue["allowed"].ToBoolean();
                            var value      = corpusValue["value"];
                            var method     = corpusValue["method"].AsString;
                            switch (method)
                            {
                            case "auto":
                                corpusCopied.Add(corpusElement);
                                continue;

                            case "explicit":
                            {
                                var            encryptionOptions = CreateEncryptOptions(abbreviatedAlgorithmName, identifier, kms);
                                BsonBinaryData encrypted         = null;
                                var            exception         = Record.Exception(() =>
                                    {
                                        encrypted = ExplicitEncrypt(
                                            clientEncryption,
                                            encryptionOptions,
                                            value,
                                            async);
                                    });
                                if (allowed)
                                {
                                    exception.Should().BeNull();
                                    encrypted.Should().NotBeNull();
                                    corpusValue["value"] = encrypted;
                                }
                                else
                                {
                                    exception.Should().NotBeNull();
                                }
                                corpusCopied.Add(new BsonElement(corpusElement.Name, corpusValue));
                            }
                            break;

                            default:
                                throw new ArgumentException($"Unsupported method name {method}.", nameof(method));
                            }
                        }

                        var coll = GetCollection(clientEncrypted, __collCollectionNamespace);
                        Insert(coll, async, corpusCopied);

                        var corpusDecrypted = Find(coll, new BsonDocument(), async).Single();
                        corpusDecrypted.Should().Be(corpus);

                        var corpusEncryptedExpected = JsonFileReader.Instance.Documents["corpus.corpus-encrypted.json"];
                        coll = GetCollection(client, __collCollectionNamespace);
                        var corpusEncryptedActual = Find(coll, new BsonDocument(), async).Single();
                        foreach (var expectedElement in corpusEncryptedExpected.Elements.Where(c => c.Value.IsBsonDocument))
                        {
                            var expectedElementValue = expectedElement.Value;
                            var expectedAlgorithm    = ParseAlgorithm(expectedElementValue["algo"].AsString);
                            var expectedAllowed      = expectedElementValue["allowed"].ToBoolean();
                            var expectedValue        = expectedElementValue["value"];
                            var actualValue          = corpusEncryptedActual.GetValue(expectedElement.Name)["value"];

                            switch (expectedAlgorithm)
                            {
                            case EncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic:
                                actualValue.Should().Be(expectedValue);
                                break;

                            case EncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Random:
                                if (expectedAllowed)
                                {
                                    actualValue.Should().NotBe(expectedValue);
                                }
                                break;

                            default:
                                throw new ArgumentException($"Unsupported expected algorithm {expectedAllowed}.", nameof(expectedAlgorithm));
                            }

                            if (expectedAllowed)
                            {
                                var actualDecryptedValue   = ExplicitDecrypt(clientEncryption, actualValue.AsBsonBinaryData, async);
                                var expectedDecryptedValue = ExplicitDecrypt(clientEncryption, expectedValue.AsBsonBinaryData, async);
                                actualDecryptedValue.Should().Be(expectedDecryptedValue);
                            }
                            else
                            {
                                actualValue.Should().Be(expectedValue);
                            }
                        }
                    }

            EncryptOptions CreateEncryptOptions(string algorithm, string identifier, string kms)
            {
                Guid?  keyId         = null;
                string alternateName = null;

                if (identifier == "id")
                {
                    switch (kms)
                    {
                    case "local":
                        keyId = GuidConverter.FromBytes(Convert.FromBase64String("LOCALAAAAAAAAAAAAAAAAA=="), GuidRepresentation.Standard);
                        break;

                    case "aws":
                        keyId = GuidConverter.FromBytes(Convert.FromBase64String("AWSAAAAAAAAAAAAAAAAAAA=="), GuidRepresentation.Standard);
                        break;

                    default:
                        throw new ArgumentException($"Unsupported kms type {kms}.");
                    }
                }
                else if (identifier == "altname")
                {
                    alternateName = kms;
                }
                else
                {
                    throw new ArgumentException($"Unsupported identifier {identifier}.", nameof(identifier));
                }

                return(new EncryptOptions(ParseAlgorithm(algorithm).ToString(), alternateName, keyId));
            }

            EncryptionAlgorithm ParseAlgorithm(string algorithm)
            {
                switch (algorithm)
                {
                case "rand":
                    return(EncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Random);

                case "det":
                    return(EncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic);

                default:
                    throw new ArgumentException($"Unsupported algorithm {algorithm}.");
                }
            }
        }
示例#44
0
        public static BsonDocument KerberosCreator(EntityObject userEntity, EntityObject computerEntity,
                                                   EntityObject domainController, string userDomainName, string computerDomainName, ObjectId sourceGateway, string targetSpn = null,
                                                   EntityObject targetMachine = null, string actionType = "As", int daysToSubtruct = 0,
                                                   int hoursToSubtract        = 0,
                                                   ObjectId parentId          = new ObjectId())
        {
            var kerberosTime  = DateTime.UtcNow.Subtract(new TimeSpan(daysToSubtruct, hoursToSubtract, 0, 5, 0));
            var sourceAccount = new BsonDocument {
                { "DomainName", userDomainName }, { "Name", userEntity.Name }
            };
            var sourceComputerName = new BsonDocument {
                { "DomainName", computerDomainName }, { "Name", computerEntity.Name }
            };
            var resourceIdentifier = new BsonDocument();
            var targetSpnName      = $"krbtgt/{userDomainName}";

            if (targetSpn != null)
            {
                targetSpnName = targetSpn;
            }
            resourceIdentifier.Add("AccountId", targetMachine?.Id ?? domainController.Id);
            var resourceName = new BsonDocument {
                { "DomainName", userDomainName }, { "Name", targetSpnName }
            };

            resourceIdentifier.Add("ResourceName", resourceName);
            var destinationComputerName =
                new BsonDocument {
                { "DomainName", userDomainName }, { "Name", domainController.Name }
            };
            var responseTicket = new BsonDocument
            {
                { "EncryptionType", "Aes256CtsHmacSha196" },
                { "IsReferral", false },
                { "Realm", userDomainName },
                { "ResourceIdentifier", resourceIdentifier },
                { "Size", 1084 },
                { "Hash", new byte[16] }
            };
            var networkActivityDocument = new BsonDocument
            {
                { "_id", ObjectId.GenerateNewId() },
                {
                    "_t",
                    new BsonArray(new[]
                                  { "Entity", "NetworkActivity", "Kerberos", "KerberosKdc", "Kerberos" + actionType })
                },
                { "HorizontalParentId", ObjectId.GenerateNewId() },
                { "StartTime", kerberosTime },
                { "EndTime", kerberosTime },
                { "SourceIpAddress", "[daf::daf]" },
                { "SourcePort", 38014 },
                { "SourceComputerId", computerEntity.Id },
                { "SourceComputerCertainty", "High" },
                { "SourceComputerResolutionMethod", new BsonArray(new[] { "RpcNtlm" }) },
                { "DestinationIpAddress", "[daf::200]" },
                { "DestinationComputerId", domainController.Id },
                { "DestinationComputerCertainty", "High" },
                { "DestinationComputerResolutionMethod", new BsonArray(new[] { "RpcNtlm" }) },
                { "DestinationComputerName", destinationComputerName },
                { "TransportProtocol", "Tcp" },
                { "DomainControllerStartTime", kerberosTime },
                { "SourceAccountName", sourceAccount },
                { "SourceAccountId", userEntity.Id },
                { "ResourceIdentifier", resourceIdentifier },
                { "SourceComputerName", sourceComputerName },
                { "Error", "Success" },
                { "NtStatus", BsonValue.Create(null) },
                { "SourceGatewaySystemProfileId", sourceGateway },
                { "RequestTicketKerberosId", parentId },
                { "SourceAccountBadPasswordTime", BsonValue.Create(null) },
                { "IsOldPassword", BsonValue.Create(null) },
                { "IsSuccess", BsonValue.Create(true) }
            };

            switch (actionType)
            {
            case "As":

                networkActivityDocument.Add("SourceComputerNetbiosName", computerEntity.Name);
                networkActivityDocument.Add("IsIncludePac", BsonValue.Create(true));
                networkActivityDocument.Add("SourceAccountSupportedEncryptionTypes", new BsonArray(new string[0]));
                networkActivityDocument.Add("EncryptedTimestampEncryptionType", BsonValue.Create(null));
                networkActivityDocument.Add("EncryptedTimestamp", BsonValue.Create(null));
                networkActivityDocument.Add("RequestTicket", BsonValue.Create(null));
                networkActivityDocument.Add("ResponseTicket", responseTicket);
                networkActivityDocument.Add("IsSmartcardRequiredRc4", BsonValue.Create(false));
                networkActivityDocument.Add("ArmoringEncryptionType", BsonValue.Create(null));
                networkActivityDocument.Add("RequestedTicketExpiration", DateTime.UtcNow);
                networkActivityDocument.Add("SourceComputerSupportedEncryptionTypes",
                                            new BsonArray(new[] { "Rc4Hmac" }));
                networkActivityDocument.Add("DestinationPort", "88");
                networkActivityDocument.Add("Options",
                                            new BsonArray(new[] { "RenewableOk", "Canonicalize", "Renewable", "Forwardable" }));
                break;

            case "Tgs":
                networkActivityDocument.Add("IsServiceForUserToSelf", BsonValue.Create(false));
                networkActivityDocument.Add("IsUserToUser", BsonValue.Create(false));
                networkActivityDocument.Add("AuthorizationDataSize", BsonValue.Create(null));
                networkActivityDocument.Add("AuthorizationDataEncryptionType", BsonValue.Create(null));
                networkActivityDocument.Add("ParentsOptions", "None");
                networkActivityDocument.Add("AdditionalTickets", new BsonArray(new string[0]));
                networkActivityDocument.Add("RequestTicket", responseTicket);
                networkActivityDocument.Add("ResponseTicket", responseTicket);
                networkActivityDocument.Add("ArmoringEncryptionType", BsonValue.Create(null));
                networkActivityDocument.Add("RequestedTicketExpiration", DateTime.UtcNow);
                networkActivityDocument.Add("SourceComputerSupportedEncryptionTypes",
                                            new BsonArray(new[] { "Rc4Hmac" }));
                networkActivityDocument.Add("DestinationPort", "88");
                networkActivityDocument.Add("Options",
                                            new BsonArray(new[] { "RenewableOk", "Canonicalize", "Renewable", "Forwardable" }));
                break;

            default:
                networkActivityDocument.Set(1,
                                            new BsonArray(new[] { "Entity", "Activity", "NetworkActivity", "Kerberos", "KerberosAp" }));
                networkActivityDocument.Add("RequestTicket", responseTicket);
                networkActivityDocument.Add("DestinationPort", "445");
                networkActivityDocument.Add("Options", "MutualRequired");
                break;
            }
            return(networkActivityDocument);
        }
示例#45
0
        private BsonDocument CreateBsonDocument(string userId, string userName, DateTime date, string leaveCodeName, string reason)
        {
            var leave = new BsonDocument();

            leave.Add("_id", BsonObjectId.GenerateNewId().ToString());
            leave.Add("tag", "Leave");
            leave.Add("type", "leave");

            var createdBy = new BsonDocument();

            createdBy.Add("id", userId);
            createdBy.Add("name", userName);

            leave.Add("createBy", createdBy);
            leave.Add("engineer", createdBy);

            leave.Add("hours", 8);
            leave.Add("reason", reason);
            leave.Add("leave_type", leaveCodeName);
            leave.Add("isApproved", false);
            leave.Add("date", date);
            leave.Add("created_on", DateTime.Now);

            return(leave);
        }
示例#46
0
        /// <summary>
        ///     确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdOK_Click(object sender, EventArgs e)
        {
            var mongoCol  = RuntimeMongoDbContext.GetCurrentCollection();
            var query     = QueryHelper.GetQuery(GroupConditionList);
            var groupdoc  = new GroupByDocument();
            var chartTite = string.Empty;

            foreach (CheckBox item in panColumn.Controls)
            {
                if (!item.Checked)
                {
                    continue;
                }
                groupdoc.Add(item.Name, true);
                chartTite += item.Name + ",";
            }
            chartTite = chartTite.TrimEnd(",".ToCharArray());
            var initial = new BsonDocument();

            for (var i = 0; i < _conditionCount; i++)
            {
                var ctl = (CtlAddBsonEl)Controls.Find("BsonEl" + (i + 1), true)[0];
                if (ctl.IsSetted)
                {
                    initial.Add(ctl.GetElement());
                }
            }

            var reduce    = new BsonJavaScript(ctlReduce.Context);
            var finalize  = new BsonJavaScript(ctlFinalize.Context);
            var resultlst = new List <BsonDocument>();

            try
            {
                //SkipCnt Reset
                var result = mongoCol.Group(query, groupdoc, initial, reduce, finalize);
                //图形化初始化
                chartResult.Series.Clear();
                chartResult.Titles.Clear();
                var seriesResult = new Series("Result");

                //防止错误的条件造成的海量数据
                var count = 0;
                foreach (var item in result)
                {
                    if (count == 1000)
                    {
                        break;
                    }
                    resultlst.Add(item);
                    //必须带有Count元素
                    var dPoint = new DataPoint(0, (double)item.GetElement("count").Value);
                    seriesResult.Points.Add(dPoint);
                    count++;
                }
                ViewHelper.FillJsonDataToTextBox(txtResult, resultlst, 0);
                if (count == 1001)
                {
                    txtResult.Text = "Too many result,Display first 1000 records" + Environment.NewLine + txtResult.Text;
                }
                txtResult.Select(0, 0);
                //图形化加载
                chartResult.Series.Add(seriesResult);
                chartResult.Titles.Add(new Title(chartTite));
                tabGroup.SelectedIndex = 4;
            }
            catch (Exception ex)
            {
                Utility.ExceptionDeal(ex, "Exception", "Exception is Happened");
            }
        }
示例#47
0
        private void Zatwierdz(object sender, RoutedEventArgs e)
        {
            Window window           = this;
            var    areTextboxesNull = false;

            /* var kryminalista = new BsonDocument
             * {
             *  {"imie", new BsonString(imie.Text)},
             *  {"nazwisko", new BsonString(nazwisko.Text)},
             *  {"pseudonim", new BsonString(pseudonim.Text)},
             *  //{"data_urodzenia", new BsonDateTime(data_urodzenia)},
             *  {"miejsce_urodzenia", new BsonString(urodzenie.Text)},
             *  {"miejsce_zameldowania", new BsonString(zamieszkanie.Text)},
             *  //{"poszukiwany", new BsonBoolean(poszukiwany)}
             * }; */
            var kryminalista = new BsonDocument();

            foreach (TextBox textBox in FindVisualChildren <TextBox>(window))
            {
                if (String.IsNullOrEmpty(textBox.Text) || String.IsNullOrWhiteSpace(textBox.Text))
                {
                    areTextboxesNull = true;
                }
            }

            if (!String.IsNullOrWhiteSpace(imie.Text) || !String.IsNullOrEmpty(imie.Text))
            {
                BsonElement element = new BsonElement("imie", new BsonString(imie.Text));
                kryminalista.Add(element);
            }
            if (!String.IsNullOrWhiteSpace(nazwisko.Text) || !String.IsNullOrEmpty(nazwisko.Text))
            {
                BsonElement element = new BsonElement("nazwisko", new BsonString(nazwisko.Text));
                kryminalista.Add(element);
            }
            if (!String.IsNullOrWhiteSpace(pseudonim.Text) || !String.IsNullOrEmpty(pseudonim.Text))
            {
                BsonElement element = new BsonElement("pseudonim", new BsonString(pseudonim.Text));
                kryminalista.Add(element);
            }
            if (!String.IsNullOrWhiteSpace(urodzenie.Text) || !String.IsNullOrEmpty(urodzenie.Text))
            {
                BsonElement element = new BsonElement("miejsce_urodzenia", new BsonString(urodzenie.Text));
                kryminalista.Add(element);
            }
            if (!String.IsNullOrWhiteSpace(zamieszkanie.Text) || !String.IsNullOrEmpty(zamieszkanie.Text))
            {
                BsonElement element = new BsonElement("miejsce_zamieszkania", new BsonString(zamieszkanie.Text));
                kryminalista.Add(element);
            }

            if (isDateKnown == true)
            {
                BsonElement element = new BsonElement("data_urodzenia", new BsonDateTime((DateTime)data_urodzenia.SelectedDate));
                kryminalista.Add(element);
            }
            if ((bool)poszukiwany.IsChecked)
            {
                BsonElement element = new BsonElement("poszukiwany", new BsonBoolean(true));
                kryminalista.Add(element);
            }
            else
            {
                BsonElement element = new BsonElement("poszukiwany", new BsonBoolean(false));
                kryminalista.Add(element);
            }

            if (areTextboxesNull == false)
            {
                StartMongo.collectionPrzestepcy.InsertOne(kryminalista);

                var getData = new StringBuilder();
                getData.Append("Dodano nowego przestepce: " + imie.Text + ", ");
                getData.Append(nazwisko.Text + ", ");
                getData.Append("pseudonim: " + pseudonim.Text + " do bazy danych.");
                MessageBox.Show(getData.ToString(), "Rezultat");
                DialogResult = true;
            }
            else
            {
                MessageBoxResult isUserSure = MessageBox.Show("Czy na pewno chcesz dodać obiekt do bazy danych, bez wszystkich wypełnionych pól?", "Pytanie", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (isUserSure == MessageBoxResult.Yes && imie.Text != "" && nazwisko.Text != "")
                {
                    StartMongo.collectionPrzestepcy.InsertOne(kryminalista);

                    var getData = new StringBuilder();
                    getData.Append("Dodano nowego przestepce: " + imie.Text + ", ");
                    getData.Append(nazwisko.Text + ", ");
                    getData.Append("pseudonim: " + pseudonim.Text + " do bazy danych.");
                    MessageBox.Show(getData.ToString(), "Rezultat");
                    DialogResult = true;
                }
                else
                {
                    MessageBox.Show("Nie dodano nowego przestępcy do bazy danych. Podaj przynajmniej imię i nazwisko!", "Rezultat");
                    DialogResult = false;
                }
            }
        }
示例#48
0
        static void Main(string[] args)
        {
            try
            {
                MongoClient dbClient = new MongoClient("mongodb://127.0.0.1:27017");

                //Database List
                var dbList = dbClient.ListDatabases().ToList();

                Console.WriteLine("The list of databases are :");
                foreach (var item in dbList)
                {
                    Console.WriteLine(item);
                }

                Console.WriteLine("\n\n");

                //Get Database and Collection
                IMongoDatabase db       = dbClient.GetDatabase("test");
                var            collList = db.ListCollections().ToList();
                Console.WriteLine("The list of collections are :");
                foreach (var item in collList)
                {
                    Console.WriteLine(item);
                }

                var things = db.GetCollection <BsonDocument>("things");

                //CREATE
                BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Luis");

                BsonDocument personDoc = new BsonDocument();
                personDoc.Add(personFirstNameElement);
                personDoc.Add(new BsonElement("PersonAge", 23));

                things.InsertOne(personDoc);

                //UPDATE
                BsonElement updatePersonFirstNameElement = new BsonElement("PersonFirstName", "Alfredo");

                BsonDocument updatePersonDoc = new BsonDocument();
                updatePersonDoc.Add(updatePersonFirstNameElement);
                updatePersonDoc.Add(new BsonElement("PersonAge", 24));

                BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Luis"));

                var updateDoc = things.FindOneAndReplace(findPersonDoc, updatePersonDoc);

                Console.WriteLine(updateDoc);

                //DELETE
                BsonDocument findAnotherPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Alfredo"));

                things.FindOneAndDelete(findAnotherPersonDoc);

                //READ
                var resultDoc = things.Find(new BsonDocument()).ToList();
                foreach (var item in resultDoc)
                {
                    Console.WriteLine(item.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
示例#49
0
        bool DataInsertToDB(string fileName, int version)
        {
            string mongoDBIP             = ""; //"mongodb://localhost:27017/?maxPoolSize=200"
            string mongoDBDatabaseName   = "";
            string mongoDBCollectionName = "";

            var       stream      = new FileStream(fileName, FileMode.Open);
            var       excelReader = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream);
            DataSet   result      = excelReader.AsDataSet();
            DataTable table       = result.Tables[0];

            // 기존 컬렉션에 있는 문서를 모두 지우고 새로 넣는다.
            var CollectionName = Path.GetFileNameWithoutExtension(fileName);

            var Datas = GetDBCollection <BsonDocument>(mongoDBIP, mongoDBDatabaseName, mongoDBCollectionName);

            Datas.DeleteManyAsync(new BsonDocument());


            try
            {
                string strTemp;
                int    excelInt;
                double excelDouble;

                // Excel 1열, 2열을 제외하고 for문 시작
                for (int rCnt = 2; rCnt < table.Rows.Count; rCnt++)
                {
                    BsonDocument data = new BsonDocument();

                    if (string.IsNullOrEmpty(table.Rows[rCnt].ItemArray[0].ToString()))
                    {
                        break;
                    }

                    for (int cCnt = 0; cCnt < table.Columns.Count; cCnt++)
                    {
                        strTemp = table.Rows[1].ItemArray[cCnt].ToString();
                        var strTemp2 = table.Rows[rCnt].ItemArray[cCnt].ToString();

                        if (strTemp == "")
                        {
                            continue;
                        }

                        if (Int32.TryParse(strTemp2, out excelInt))
                        {
                            // string에서 double 값이 있으면 excelDouble로 추출
                            data.Add(strTemp, excelInt);
                        }
                        else if (Double.TryParse(strTemp2, out excelDouble))
                        {
                            // string에서 double 값이 있으면 excelDouble로 추출
                            data.Add(strTemp, excelDouble);
                        }
                        else
                        {
                            // string에서 double 값이 없으면 strTemp2로 string 추출
                            data.Add(strTemp, strTemp2);
                        }
                    }

                    Datas.InsertOneAsync(data).Wait();
                }


                //var propertyData = new DBDataProperty();
                //propertyData._id = CollectionName; //dataName;

                //for (int cCnt = 0; cCnt < table.Columns.Count; cCnt++)
                //{
                //    var exportMark = table.Rows[0].ItemArray[cCnt].ToString();
                //    if (exportMark == "C" || exportMark == "CS")
                //    {
                //        var fieldName = table.Rows[1].ItemArray[cCnt].ToString();
                //        propertyData.ClientExportField.Add(fieldName);
                //    }
                //}

                //CreateDataProperty(propertyData);
            }
            catch (Exception ex)
            {
                //alertMessage = e.ToString();

                //var msg_E = "\r\n-------------------------------------------------------" +
                //"\r\n예외 발생 일자 : " + DateTime.Now.ToString() + e;

                //string path_E = Server.MapPath("~/Temp/") + "log.txt";

                //StreamWriter tw_E = System.IO.File.AppendText(path_E);
                //tw_E.WriteLine(msg_E);
                //tw_E.Close();

                return(false);
            }

            excelReader.Close();

            return(true);
        }
示例#50
0
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        protected bool importData(string filePath)
        {
            string name = title.SelectedItem.ToString();

            if (name == SELECT)
            {
                MessageBox.Show("请先选择要上传的类型!");
                return(false);
            }

            List <BsonDocument> docs = new List <BsonDocument>(); //保存要插入的数据
            int duplicate            = 0;                         //记录文件中包含的重复数据个数

            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                    {
                        string[] csv_title = sr.ReadLine().Split(',');//设置列标题

                        switch (name)
                        {
                        case STOPWORD:
                        {
                            csv_title = "停用词".Split(',');
                        }
                        break;

                        case SYNONYM:
                        {
                            csv_title = "标准词,同义词".Split(',');
                        }
                        break;

                        case PROPERNOUNS:
                        {
                            csv_title = "专有名词".Split(',');
                        }
                        break;
                        }


                        string           row_text = "";
                        HashSet <string> unique   = new HashSet <string>();

                        while ((row_text = sr.ReadLine()) != null)
                        {
                            BsonDocument doc = new BsonDocument();

                            string[] datas = null;

                            if (row_text.Contains(','))
                            {
                                datas = row_text.Split(',');
                            }
                            else if (row_text.Contains("\t"))
                            {
                                datas = row_text.Split('\t');
                            }
                            else
                            {
                                datas = row_text.Split();
                            }
                            //if(datas.Length > 1)
                            //{
                            //    MessageBox.Show("csv格式错误" + datas);
                            //    return false;
                            //}

                            if (datas.Length != keyCount[name])
                            {
                                MessageBox.Show("格式错误:" + datas);
                                return(false);
                            }
                            if (unique.Contains(datas[0]))
                            {
                                duplicate += 1; continue;
                            }
                            else if (string.IsNullOrEmpty(datas[0]))
                            {
                                duplicate += 1; continue;
                            }

                            unique.Add(datas[0]);

                            switch (name)
                            {
                            case STOPWORD:
                            {
                                var col = database.GetCollection <Stopword>(collectionDict[name]);
                                //首先查询是否有重复的value
                                var result = col.AsQueryable <Stopword>().Count(e => e.stopword == datas[0]);

                                if (result > 0)
                                {
                                    duplicate += 1;
                                    continue;
                                }
                            }
                            break;

                            case SYNONYM:
                            {
                                var col = database.GetCollection <Synonym>(collectionDict[name]);
                                //首先查询是否有重复的value
                                var result = col.AsQueryable <Synonym>().Count(e => e.standard == datas[0]);

                                if (result > 0)
                                {
                                    duplicate += 1;
                                    continue;
                                }
                            }
                            break;

                            case PROPERNOUNS:
                            {
                                var col = database.GetCollection <Proper>(collectionDict[name]);
                                //首先查询是否有重复的value
                                var result = col.AsQueryable <Proper>().Count(e => e.properNouns == datas[0]);

                                if (result > 0)
                                {
                                    duplicate += 1;
                                    continue;
                                }
                            }
                            break;
                            }

                            for (int i = 0; i < csv_title.Length; i++)
                            {
                                doc.Add(field[csv_title[i]], datas[i].Trim());
                            }
                            docs.Add(doc);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("打开文件失败!");
                return(false);
            }

            try
            {
                ///插入数据库
                var collection = database.GetCollection <BsonDocument>(collectionDict[name]);
                collection.InsertMany(docs);
            }
            catch (Exception)
            {
                MessageBox.Show("数据库连接异常!");
                return(false);
            }

            if (duplicate > 0)
            {
                MessageBox.Show("数据全部导入成功!去除重复数据条数为:" + duplicate.ToString());
            }
            else
            {
                MessageBox.Show("数据全部导入成功!");
            }

            return(true);
        }
示例#51
0
        public ActionResult SaveResultItemMatRelInfoXC(FormCollection saveForm)
        {
            InvokeResult result = new InvokeResult();
            PageJson     json   = new PageJson();

            string tbName   = "XH_StandardResult_ResultItemMatRelation"; //表名
            string queryStr = PageReq.GetForm("queryStr");               //定位记录
            string matIds   = PageReq.GetForm("matIds");                 //材料Id列表

            if (PageReq.GetForm("retId").Trim() == "" || PageReq.GetForm("itemId").Trim() == "")
            {
                json.Success = false;
                json.Message = "传入参数有空值!";
                return(Json(json));
            }

            BsonDocument dataBson = new BsonDocument();             //数据

            foreach (var tempKey in saveForm.AllKeys)
            {
                if (tempKey == "tbName" || tempKey == "queryStr" || tempKey.Contains("matIds"))
                {
                    continue;
                }

                dataBson.Add(tempKey, saveForm[tempKey]);
            }

            var query = TypeConvert.NativeQueryToQuery(queryStr); //定位关联

            if (queryStr != "")                                   //编辑材料记录
            {
                result = dataOp.Save(tbName, query, dataBson);    //保存关联
            }
            else if (matIds.Trim() != "")                         //有选择材料
            {
                List <StorageData> allDataList = new List <StorageData>();
                List <string>      matIdList   = matIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();

                foreach (var matId in matIdList)
                {
                    BsonDocument tempBson = new BsonDocument();

                    tempBson.Add("retId", dataBson.String("retId"));
                    tempBson.Add("typeId", dataBson.String("typeId"));
                    tempBson.Add("itemId", dataBson.String("itemId"));
                    tempBson.Add("matId", matId);

                    StorageData tempData = new StorageData();
                    tempData.Document = tempBson;
                    tempData.Name     = tbName;
                    tempData.Type     = StorageType.Insert;

                    allDataList.Add(tempData);
                }

                result = dataOp.BatchSaveStorageData(allDataList);
            }
            else
            {
                result = dataOp.Save(tbName, query, dataBson);    //保存关联
            }

            json = TypeConvert.InvokeResultToPageJson(result);

            return(Json(json));
        }
示例#52
0
        /// <summary>
        /// 数据接收处理,失败后抛出NullReferenceException异常,主线程会进行捕获
        /// </summary>
        /// <param name="args">url参数</param>
        public void DataReceive(DataReceivedEventArgs args)
        {
            var          hmtl               = args.Html;
            HtmlDocument htmlDoc            = new HtmlDocument();
            var          curAddBsonDocument = new BsonDocument();

            htmlDoc.LoadHtml(args.Html);//提取文章
            var companyId = Toolslib.Str.Sub(args.Url, "-", "/");
            var root      = htmlDoc.DocumentNode;

            if (root == null)
            {
                return;
            }

            var companyName = root.SelectSingleNode("//h1[@class='companyname']");

            if (companyName != null)
            {
                curAddBsonDocument.Add("name", companyName.InnerText);
            }

            var companyShow = root.SelectSingleNode("//div[@class='company-show']");

            if (companyShow != null)
            {
                var liList = companyShow.SelectNodes("./div/div/ul/li");
                foreach (var liNode in liList)
                {
                    var txt = liNode.InnerText;

                    if (txt.Contains(":") && !txt.Contains("浏览次数"))
                    {
                        var txtArr = txt.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                        if (txtArr.Length == 2)
                        {
                            curAddBsonDocument.Set(txtArr[0].Trim(), txtArr[1].Trim());
                        }
                    }
                }
            }
            var detailUrl = string.Format("http://www.rc.cc/plus/ajax.php?id={0}&time=1488436660210&act=company_contact", companyId);

            hi.Url = detailUrl;
            var ho = LibCurlNet.HttpManager.Instance.ProcessRequest(hi);

            if (ho.IsOK)
            {
                HtmlDocument htmlDocNew = new HtmlDocument();
                htmlDocNew.LoadHtml(ho.TxtData); //提取文章
                var company_contact = htmlDocNew.DocumentNode;
                if (company_contact != null)
                {
                    var ul = company_contact.FirstChild;
                    if (ul != null)
                    {
                        var lilist = ul.ChildNodes;
                        foreach (var liNode in lilist)
                        {
                            var txt = liNode.InnerText;
                            if (txt.Contains(":"))
                            {
                                var txtArr = txt.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                                if (txtArr.Length == 2)
                                {
                                    curAddBsonDocument.Set(txtArr[0].Trim(), txtArr[1].Trim());
                                }
                            }
                        }
                    }
                }
            }
            curAddBsonDocument.Add("companyId", companyId);
            curAddBsonDocument.Add("url", args.Url);
            curAddBsonDocument.Add("isUpdate", "1");
            DBChangeQueue.Instance.EnQueue(new StorageData()
            {
                Document = curAddBsonDocument,
                Name     = DataTableName,
                Type     = StorageType.Insert
            });
            //DBChangeQueue.Instance.EnQueue(new StorageData() { Document = curAddBsonDocument, Name = DataTableName, Query = Query.EQ("url", args.Url), Type = StorageType.Update });
            Console.WriteLine("{0}", args.Url);
        }
示例#53
0
        /// <summary>
        /// 保存外部项目基本信息
        /// </summary>
        /// <param name="saveForm"></param>
        /// <returns></returns>
        public ActionResult SaveOutProjInfo(FormCollection saveForm)
        {
            PageJson      json           = new PageJson();
            InvokeResult  result         = new InvokeResult();
            string        tbName         = PageReq.GetForm("tbName");
            string        queryStr       = PageReq.GetForm("queryStr");
            string        propertyStr    = PageReq.GetForm("propertyIdArray");//物业形态
            BsonDocument  projInfo       = new BsonDocument();
            List <string> propertyIdList = new List <string>();

            if (!string.IsNullOrEmpty(propertyStr))
            {
                propertyIdList = propertyStr.SplitParam(StringSplitOptions.RemoveEmptyEntries, ",").ToList();
            }
            List <StorageData> dataSource = new List <StorageData>();

            if (!string.IsNullOrEmpty(queryStr))
            {
                projInfo = dataOp.FindOneByQuery("StandardResult_OutSideProject", TypeConvert.NativeQueryToQuery(queryStr));
                if (projInfo != null)
                {
                    foreach (var tempKey in saveForm.AllKeys)
                    {
                        if (tempKey == "tbName" || tempKey == "queryStr" || tempKey == "str" || tempKey == "propertyIdArray" || tempKey == "" || tempKey.Contains("fileList[") || tempKey.Contains("param."))
                        {
                            continue;
                        }
                        if (projInfo.Contains(tempKey))
                        {
                            projInfo[tempKey] = PageReq.GetForm(tempKey);
                        }
                        else
                        {
                            projInfo.Add(tempKey, PageReq.GetForm(tempKey));
                        }
                    }
                    StorageData tempData1 = new StorageData();
                    tempData1.Name     = "StandardResult_OutSideProject";
                    tempData1.Type     = StorageType.Update;
                    tempData1.Document = projInfo;
                    tempData1.Query    = Query.EQ("OutProjId", projInfo.String("OutProjId"));
                    dataSource.Add(tempData1);
                    var exitProperty = dataOp.FindAllByQuery("OutProjectProperty", Query.EQ("OutProjId", projInfo.String("OutProjId"))).ToList();
                    foreach (var tempProperty in propertyIdList)
                    {
                        var temp = exitProperty.Where(x => x.String("propertyId") == tempProperty).FirstOrDefault();

                        if (temp != null)
                        {
                            exitProperty.Remove(temp);
                        }
                        else
                        {
                            BsonDocument tempProper = new BsonDocument();
                            tempProper.Add("OutProjId", projInfo.String("OutProjId"));
                            tempProper.Add("propertyId", tempProperty);
                            StorageData tempData = new StorageData();
                            tempData.Name     = "OutProjectProperty";
                            tempData.Type     = StorageType.Insert;
                            tempData.Document = tempProper;
                            dataSource.Add(tempData);
                            // newPropertyIdList.Add(tempProperty);
                        }
                    }
                    if (exitProperty.Count() > 0)
                    {
                        foreach (var tempProperty in exitProperty)
                        {
                            StorageData tempData = new StorageData();
                            tempData.Name     = "OutProjectProperty";
                            tempData.Type     = StorageType.Delete;
                            tempData.Query    = Query.EQ("outProjPropertyId", tempProperty.String("outProjPropertyId"));
                            tempData.Document = tempProperty;
                            dataSource.Add(tempData);
                            //delPropertyId.Add(tempProperty.String("propertyId"));
                        }
                    }
                    result = dataOp.BatchSaveStorageData(dataSource);
                }
            }
            else
            {
                foreach (var tempKey in saveForm.AllKeys)
                {
                    if (tempKey == "tbName" || tempKey == "queryStr" || tempKey == "str" || tempKey == "propertyIdArray")
                    {
                        continue;
                    }
                    if (projInfo.Contains(tempKey))
                    {
                        projInfo[tempKey] = PageReq.GetForm(tempKey);
                    }
                    else
                    {
                        projInfo.Add(tempKey, PageReq.GetForm(tempKey));
                    }
                }
                result = dataOp.Insert("StandardResult_OutSideProject", projInfo);
                if (result.Status == Status.Successful)
                {
                    projInfo = result.BsonInfo; projInfo = result.BsonInfo;
                    try
                    {
                        foreach (var tempProperty in propertyIdList)
                        {
                            BsonDocument tempProper = new BsonDocument();
                            tempProper.Add("OutProjId", projInfo.String("OutProjId"));
                            tempProper.Add("propertyId", tempProperty);
                            StorageData tempData = new StorageData();
                            tempData.Name     = "OutProjectProperty";
                            tempData.Type     = StorageType.Insert;
                            tempData.Document = tempProper;
                            dataSource.Add(tempData);
                        }
                        result = dataOp.BatchSaveStorageData(dataSource);
                    }
                    catch (Exception ex) { }
                }
            }

            if (result.Status == Status.Successful)
            {
                json.htInfo = new System.Collections.Hashtable();;
                json.htInfo.Add("OutProjId", projInfo.String("OutProjId"));
                json.Success = true;
            }
            else
            {
                json = TypeConvert.InvokeResultToPageJson(result);
            }
            return(Json(json));
        }
示例#54
0
        private void NewFieldMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (InputBoxWindow.ShowDialog("Enter name of new field.", "New field name:", "", out string fieldName) != true)
            {
                return;
            }

            if (currentDocument.Keys.Contains(fieldName))
            {
                MessageBox.Show(string.Format("Field \"{0}\" already exists!", fieldName), "", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var       menuItem = sender as MenuItem;
            BsonValue newValue;

            switch (menuItem.Header as string)
            {
            case "String":
                newValue = new BsonValue(string.Empty);
                break;

            case "Boolean":
                newValue = new BsonValue(false);
                break;

            case "Double":
                newValue = new BsonValue((double)0);
                break;

            case "Int32":
                newValue = new BsonValue((int)0);
                break;

            case "Int64":
                newValue = new BsonValue((long)0);
                break;

            case "DateTime":
                newValue = new BsonValue(DateTime.MinValue);
                break;

            case "Array":
                newValue = new BsonArray();
                break;

            case "Document":
                newValue = new BsonDocument();
                break;

            default:
                throw new Exception("Uknown value type.");
            }

            currentDocument.Add(fieldName, newValue);
            var newField = NewField(fieldName, false);

            customControls.Add(newField);
            newField.EditControl.Focus();
            ItemsField_SizeChanged(ListItems, null);
            ListItems.ScrollIntoView(newField);
        }
示例#55
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            var      offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
            DateTime dt     = DateTime.Now;
            var      dateto = dt;

            string       obj              = Request["reqdata"];
            BsonDocument add              = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(obj);
            BsonValue    shipmob          = add.GetElement("alternateMobileNo").Value.ToDouble();
            BsonValue    shipadd          = add.GetElement("alternateAddress").Value;
            string       objectidvalue    = Session["objid"].ToString();
            MyDB         md               = new MyDB();
            var          registration     = md.GetBColl("registration");
            var          orders           = md.GetBColl("Test3");
            var          temporders       = md.GetBColl("temporders");
            var          queryid          = new QueryDocument("_id", ObjectId.Parse(objectidvalue));
            var          queryidwithvalue = new QueryDocument("user", objectidvalue);
            var          order            = Session["order"];

            if (order == null)
            {
                BsonDocument bd1 = new BsonDocument();
                foreach (BsonDocument bits in temporders.Find(queryidwithvalue))
                {
                    bits.Remove("regtoship");
                    bits.Add("user", objectidvalue);
                    string username = Session["username"].ToString();
                    bits.Add("name", username);
                    bits.Add("mobile", shipmob);
                    bits.Add("ISODate", dateto);
                    bits.Add("shipadd", shipadd);
                    bits.Add("orderstatus", "undeliver");
                    orders.Insert(bits);
                    orders.Save(bits);
                    temporders.Remove(queryidwithvalue);
                }
                Response.Clear();
                Response.CacheControl = "no-cache";
                Response.ContentType  = "application/json";
                Session.Remove("order");
                Response.Write(1.ToString());  //Valid User
                Response.End();
            }
            else
            {
                string       ordersend = "[" + order + "]";
                var          res       = MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonArray>(ordersend.ToString());
                BsonDocument bd        = new BsonDocument();
                bd.Add("user", objectidvalue);
                string username = Session["username"].ToString();
                bd.Add("name", username);
                bd.Add("mobile", shipmob);
                bd.Add("ISODate", dateto);
                bd.Add("shipadd", shipadd);
                bd.Add("order", res);
                bd.Add("orderstatus", "undeliver");
                orders.Insert(bd);
                orders.Save(bd);
                Response.Clear();
                Response.CacheControl = "no-cache";
                Response.ContentType  = "application/json";
                Session.Remove("order");
                Response.Write(1.ToString());  //Valid User
                Response.End();
            }
        }
        catch (ThreadAbortException ee) { }
        catch (Exception eee)
        {
            Response.Clear();
            Response.CacheControl = "no-cache";
            Response.ContentType  = "application/json";
            Response.Write("exception");  //Valid User
            Response.End();
        }
    }
示例#56
0
        protected void info_show()
        {
            #region conditions 废弃

            ////ip
            //string ip = "";
            //if (ddlMachineIP.Text != "0")
            //{
            //    ip = ddlMachineIP.Text;
            //}

            ////页面名称
            //string pagename = "";
            //if (ddlPageUrl.Text != "0")
            //{
            //    pagename = ddlPageUrl.Text;
            //}
            ////等级
            //string level = "";
            //if (ddlLogLevel.Text != "0")
            //{
            //    level = ddlLogLevel.Text;
            //}
            ////类别名称
            //string categoryName = "";
            //if (ddlCategoryName.Text != "0")
            //{
            //    categoryName = ddlCategoryName.Text;
            //}
            ////日志内容
            //string message = "";
            //if (tbMessage.Text.Trim() != "")
            //{
            //    message = tbMessage.Text.Trim();
            //}

            //Document docWhere = new Document();

            //if (!string.IsNullOrEmpty(ip))
            //{
            //    docWhere.Append("MachineIP", ip);
            //}
            //if (!string.IsNullOrEmpty(pagename))
            //{
            //    docWhere.Append("PageName", pagename);
            //}
            //if (beginDate.HasValue && endDate.HasValue)
            //{
            //    docWhere.Append("WebServerTime", new Document().Append("$gte", beginDate).Append("$lte", endDate));
            //}
            //if (!string.IsNullOrEmpty(categoryName))
            //{
            //    docWhere.Append("CategoryName", categoryName);
            //}
            //if (!string.IsNullOrEmpty(level))
            //{
            //    docWhere.Append("LogLevel", int.Parse(level));
            //}
            //if (!string.IsNullOrEmpty(message))
            //{
            //    docWhere.Append("Message", "/^.*" + message + ".*/");//模糊查询  /^.*aa.*/ 相当于 like '%aa%'
            //}
            #endregion


            //开始日期时间. 结束日期时间
            DateTime?beginDate = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59");
            DateTime?endDate   = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
            if (tbBeginDate.Text != "")
            {
                //有日期有时间
                try
                {
                    beginDate = DateTime.Parse(tbBeginDate.Text);
                }
                catch
                {
                    beginDate = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59");
                }
            }

            if (tbEndDate.Text != "")
            {
                //有日期有时间
                try
                {
                    endDate = DateTime.Parse(tbEndDate.Text);
                }
                catch
                {
                    endDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
                }
            }

            //分页查询

            currentDate    = ddlMonth.Text;
            collectionName = ddlDatabaseName.Text;
            if (currentDate != "-1")
            {
                dbName = "WcfLog" + currentDate;//数据库名字

                #region 条件
                BsonDocument where = new BsonDocument();
                if (beginDate.HasValue && endDate.HasValue)
                {
                    where.Add("Time", new BsonDocument().Add("$gte", beginDate).Add("$lte", endDate));
                }
                #endregion

                #region 排序
                string[] orderby = { "Time" };
                #endregion

                #region 字段
                BsonDocument fields = new BsonDocument();
                #endregion

                //查询数据库
                if (collectionName == "ClientExceptionInfo")
                {
                    List <ClientExceptionInfo> list = MongoDBUtil.GetPaged <ClientExceptionInfo>(dbName, collectionName, where, orderby, fields, PageIndex, 20);
                    Repeater1.DataSource = list;
                    Repeater1.DataBind();
                }
                else if (collectionName == "ClientInvokeInfo")
                {
                    List <ClientInvokeInfo> list = MongoDBUtil.GetPaged <ClientInvokeInfo>(dbName, collectionName, where, orderby, fields, PageIndex, 20);
                    Repeater1.DataSource = list;
                    Repeater1.DataBind();
                }
                else if (collectionName == "ClientMessageInfo")
                {
                    List <ClientMessageInfo> list = MongoDBUtil.GetPaged <ClientMessageInfo>(dbName, collectionName, where, orderby, fields, PageIndex, 20);
                    Repeater1.DataSource = list;
                    Repeater1.DataBind();
                }
                else if (collectionName == "ServerExceptionInfo")
                {
                    List <ServerExceptionInfo> list = MongoDBUtil.GetPaged <ServerExceptionInfo>(dbName, collectionName, where, orderby, fields, PageIndex, 20);
                    Repeater1.DataSource = list;
                    Repeater1.DataBind();
                }
                else if (collectionName == "ServerInvokeInfo")
                {
                    List <ServerInvokeInfo> list = MongoDBUtil.GetPaged <ServerInvokeInfo>(dbName, collectionName, where, orderby, fields, PageIndex, 20);
                    Repeater1.DataSource = list;
                    Repeater1.DataBind();
                }
                else if (collectionName == "ServerMessageInfo")
                {
                    List <ServerMessageInfo> list = MongoDBUtil.GetPaged <ServerMessageInfo>(dbName, collectionName, where, orderby, fields, PageIndex, 20);
                    Repeater1.DataSource = list;
                    Repeater1.DataBind();
                }
                else if (collectionName == "ClientStartInfo")
                {
                    List <ClientStartInfo> list = MongoDBUtil.GetPaged <ClientStartInfo>(dbName, collectionName, where, orderby, fields, PageIndex, 20);
                    Repeater1.DataSource = list;
                    Repeater1.DataBind();
                }
                else if (collectionName == "ServerStartInfo")
                {
                    List <ServerStartInfo> list = MongoDBUtil.GetPaged <ServerStartInfo>(dbName, collectionName, where, orderby, fields, PageIndex, 20);
                    Repeater1.DataSource = list;
                    Repeater1.DataBind();
                }
                else
                {
                    Repeater1.DataSource = new List <ServerStartInfo> {
                    };
                    Repeater1.DataBind();
                }
            }
        }
        static async Task NMain(int p,string q,string r)
        {

            List<string> serverList = new List<string>();
            serverList.Add("mongodb://*****:*****@"C:\Users\eliaszaman\Desktop\test\"+FileID);
                            tw.Write(FileData,Encoding.UTF8);
                            tw.Close();


                            String FileKey = document.GetElement("FileKey").ToString();
                            var theString3 = FileKey;
                            var aStringBuilder3 = new StringBuilder(theString3);
                            aStringBuilder3.Remove(0, 8);
                            FileKey = aStringBuilder3.ToString();
                           
                            TextWriter tw2 = File.CreateText(@"C:\Users\eliaszaman\Desktop\test\key\encr.txt");
                            tw2.Write(FileKey, Encoding.UTF8);
                            tw2.Close();


                            String FileExtension = document.GetElement("FileExtension").ToString();
                            var theString4 = FileExtension;
                            var aStringBuilder4 = new StringBuilder(theString4);
                            aStringBuilder4.Remove(0, 14);
                            FileExtension = aStringBuilder4.ToString();
                            
                            TextWriter tw3 = File.CreateText(@"C:\Users\eliaszaman\Desktop\test\install\extension.x");
                            tw3.Write(FileExtension, Encoding.UTF8);
                            tw3.Close();
                        }
                    }
     

                }
                //watch.Stop();
               // string pTime = elapsedMss.ToString();
                stW.Stop();
           
                File.AppendAllText(@"C:\Users\eliaszaman\Desktop\test\install\time.txt", stW.ElapsedMilliseconds.ToString()+Environment.NewLine);
                stW.Reset();
            }
             
               
        }
示例#58
0
 public Dictionary(object id)
 {
     _document = new BsonDocument();
     _document.Add(MyValue.Id, BsonValue.Create(id));
 }
示例#59
0
文件: Character.cs 项目: vadian/Novus
        public void Save()
        {
            MongoUtils.MongoData.ConnectToDatabase();
            MongoDatabase characterDB = MongoUtils.MongoData.GetDatabase("Characters");

            if (this.ID == null)
            {
                this.ID = new MongoDB.Bson.ObjectId().ToString();
            }
            ;  //new character
            MongoCollection characterCollection = characterDB.GetCollection <BsonDocument>("PlayerCharacter");
            IMongoQuery     search          = Query.EQ("_id", ObjectId.Parse(this.ID));
            BsonDocument    playerCharacter = characterCollection.FindOneAs <BsonDocument>(search);

            if (playerCharacter == null)
            {
                //this is the players first save, create everything from scratch
                playerCharacter = new BsonDocument {
                    //no _id let MongoDB assign it one so we don't have to deal with duplicate values logic
                    { "FirstName", this.FirstName.ToLower() },
                    { "LastName", this.LastName.ToLower() },
                    { "Race", this.Race.CamelCaseWord() },
                    { "Class", this.Class.CamelCaseWord() },
                    { "Gender", this.Gender.CamelCaseWord() },
                    { "SkinColor", this.SkinColor.CamelCaseWord() },
                    { "SkinType", this.SkinType.CamelCaseWord() },
                    { "HairColor", this.HairColor.CamelCaseWord() },
                    { "EyeColor", this.EyeColor.CamelCaseWord() },
                    { "Weight", (double)this.Weight },
                    { "Height", (double)this.Height },
                    { "ActionState", this.ActionState.ToString().CamelCaseWord() },
                    { "StanceState", this.StanceState.ToString().CamelCaseWord() },
                    { "Description", this.Description },
                    { "Location", this.Location },
                    { "Password", this.Password },
                    { "IsNPC", this.IsNPC },
                    { "Experience", this.Experience },
                    { "NextLevelExperience", this.NextLevelExperience },
                    { "PointsToSpend", this.PointsToSpend },
                    { "Level", this.Level },
                    { "Leveled", this.Leveled },
                    { "MainHand", this.MainHand },
                    { "KillerID", this.KillerID },
                    { "Title", this.Title }
                };

                BsonDocument attributes = new BsonDocument {
                    { "Name", "" },
                    { "Value", "" },
                    { "Max", "" },
                    { "RegenRate", "" },
                    { "Rank", "" }
                };

                BsonArray attributeList = new BsonArray();

                foreach (Attribute a in this.Attributes.Values)
                {
                    attributes["Name"]      = a.Name;
                    attributes["Value"]     = (double)a.Value;
                    attributes["Max"]       = (double)a.Max;
                    attributes["RegenRate"] = (double)a.RegenRate;
                    attributes["Rank"]      = (double)a.Rank;

                    attributeList.Add(attributes);
                }

                playerCharacter.Add("Attributes", attributeList);

                BsonArray Inventory = new BsonArray();
                playerCharacter.Add("Inventory", Inventory);

                BsonArray Equipment = new BsonArray();
                playerCharacter.Add("Equipment", Equipment);

                playerCharacter.Add("Bonuses", Bonuses.GetBson());
            }
            else
            {
                playerCharacter["FirstName"]           = this.FirstName.ToLower();
                playerCharacter["LastName"]            = this.LastName.ToLower();
                playerCharacter["Race"]                = this.Race;
                playerCharacter["Class"]               = this.Class;
                playerCharacter["Gender"]              = this.Gender.CamelCaseWord();
                playerCharacter["SkinColor"]           = this.SkinColor.CamelCaseWord();
                playerCharacter["SkinType"]            = this.SkinType.CamelCaseWord();
                playerCharacter["HairColor"]           = this.HairColor.CamelCaseWord();
                playerCharacter["EyeColor"]            = this.EyeColor.CamelCaseWord();
                playerCharacter["Weight"]              = this.Weight;
                playerCharacter["Height"]              = this.Height;
                playerCharacter["Description"]         = this.Description;
                playerCharacter["Location"]            = this.Location;
                playerCharacter["ActionState"]         = this.ActionState.ToString().CamelCaseWord();
                playerCharacter["StanceState"]         = this.StanceState.ToString().CamelCaseWord();
                playerCharacter["Password"]            = this.Password;
                playerCharacter["IsNPC"]               = this.IsNPC;
                playerCharacter["Experience"]          = this.Experience;
                playerCharacter["NextLevelExperience"] = this.NextLevelExperience;
                playerCharacter["PointsToSpend"]       = this.PointsToSpend;
                playerCharacter["Level"]               = this.Level;
                playerCharacter["Leveled"]             = this.Leveled;
                playerCharacter["MainHand"]            = this.MainHand;
                playerCharacter["KillerID"]            = this.KillerID;
                playerCharacter["Title"]               = this.Title;

                BsonArray attributeList = new BsonArray();
                BsonArray inventoryList = new BsonArray();
                BsonArray equipmentList = new BsonArray();



                foreach (Attribute attrib in Attributes.Values)
                {
                    BsonDocument attributes = new BsonDocument {
                        { "Name", "" },
                        { "Value", "" },
                        { "Max", "" },
                        { "RegenRate", "" },
                        { "Rank", "" }
                    };

                    attributes["Name"]      = attrib.Name;
                    attributes["Value"]     = attrib.Value;
                    attributes["Max"]       = attrib.Max;
                    attributes["RegenRate"] = attrib.RegenRate;
                    attributes["Rank"]      = attrib.Rank;

                    attributeList.Add(attributes);
                }

                playerCharacter["Attributes"] = attributeList;

                BsonDocument items = new BsonDocument {
                    { "_id", "" }
                };

                //Inventory and equipment

                foreach (Items.Iitem item in Inventory.inventory)
                {
                    items["_id"] = item.Id;
                    inventoryList.Add(items);
                }

                playerCharacter["Inventory"] = inventoryList;

                foreach (KeyValuePair <Items.Wearable, Items.Iitem> item in Equipment.equipped)
                {
                    items["_id"] = item.Value.Id;

                    equipmentList.Add(items);
                }

                playerCharacter["Equipment"] = equipmentList;

                playerCharacter["Bonuses"] = Bonuses.GetBson();
            }



            characterCollection.Save(playerCharacter);

            if (this.ID == "000000000000000000000000")
            {
                this.ID = playerCharacter["_id"].AsObjectId.ToString();
            }
        }
示例#60
-1
 /// <summary>
 /// 添加案件
 /// </summary>
 /// <param name="Options">添加信息</param>
 /// <param name="ReceiveMessage">回掉消息</param> 
 public void AddCase(BsonDocument Options, BsonDocument ReceiveMessage)
 {
     String CaseName = Options.GetValue("CaseName").AsString;
     String CaseDescription = Options.GetValue("CaseDescription").AsString;
     ObjectId UserId = new ObjectId(Options.GetValue("AddUser").AsString);
     int Type = Options.GetValue("Type").AsInt32;
     if (cs.ExitCase(CaseName))
     {
         BsonDocument CaseDoc = new BsonDocument();
         CaseDoc.Add("CaseName", CaseName);
         CaseDoc.Add("CaseDescription", CaseDescription);
         CaseDoc.Add("AddUser", UserId);
         CaseDoc.Add("Type", Type);
         CaseDoc.Add("AddTime", DateTime.Now);
         if (cs.AddCase(CaseDoc))
         {
             ReceiveMessage.Add("StateCode", 0);
             ReceiveMessage.Add("ReData", "案件添加成功!");
             CallBack();
         }
         else
         {
             ReceiveMessage.Add("StateCode", -2);
             ReceiveMessage.Add("ReData", "案件添加失败!");
             CallBack();
         }
     }
     else
     {
         ReceiveMessage.Add("StateCode", -1);
         ReceiveMessage.Add("ReData", "案件已存在!");
         CallBack();
     }
 }