public DatabaseDtoP(string connectionString)
 {
     ConnectString = connectionString;
         dtopallocation = new MongoHelper<DToPAllocation>(ConnectString);
         PAccount = new DatabasePAccount(ConnectString);
         DAccount = new DatabaseDAccount(ConnectString);
 }
        // GET api/Categories/5
        public async Task<string> GetAsync(string id)
        {
            MongoHelper<Category> categoryHelper = new MongoHelper<Category>();
            var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
            
            Category cat = await categoryHelper.Collection
                .Find(c => c.Id.Equals(ObjectId.Parse(id))) // TODO filter by userId
                .FirstAsync(); 

            return cat.ToJson(jsonWriterSettings);
            
        }
        // GET api/Categories/5
        public async Task<string> GetAsync(string id)
        {
            MongoHelper<PaymentType> paymentTypeHelper = new MongoHelper<PaymentType>();
            var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };

            PaymentType paymentType = await paymentTypeHelper.Collection
                .Find(p => p.Id.Equals(ObjectId.Parse(id))) // TODO filter by userId
                .FirstAsync();

            return paymentType.ToJson(jsonWriterSettings);

        }
        // POST api/PaymentTypeApi
        public async Task PostAsync(PaymentType paymentTypePosted)
        {
            MongoHelper<PaymentType> paymentTypeHelper = new MongoHelper<PaymentType>();

            try 
            {
                await paymentTypeHelper.Collection.InsertOneAsync(paymentTypePosted);
            }
            catch (Exception e)
            {
                Trace.TraceError("PaymentTypeApi PostAsync error : " + e.Message);
                throw;
            }

        }
        // POST api/ExpenseApi
        public async Task PostAsync(Expense expensePosted)
        {
            MongoHelper<Expense> expenseHelper = new MongoHelper<Expense>();

            try
            {
                await expenseHelper.Collection.InsertOneAsync(expensePosted);
            }
            catch (Exception e)
            {
                Trace.TraceError("ExpenseApi PostAsync error : " + e.Message);
                throw;
            }
            
        }
        // POST api/CategoryApi
        public async Task PostAsync(Category categoryPosted)
        {
            MongoHelper<Category> categoryHelper = new MongoHelper<Category>();

            try
            {
                await categoryHelper.Collection.InsertOneAsync(categoryPosted);
            }
            catch (Exception e)
            {
                Trace.TraceError("CategoryApi PostAsync error : " + e.Message);
                throw;
            }

        }
        // GET api/CategoryApi
        public async Task<IEnumerable<string>> GetAsync()
        {
            MongoHelper<Category> categoryHelper = new MongoHelper<Category>();
                
            IList<string> returnList = new List<string>();
            var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
            await categoryHelper.Collection.Find(e => e.Name != null) // TODO filter by userId
                .ForEachAsync(categoryDocument => 
                {
                    string docJson = categoryDocument.ToJson(jsonWriterSettings);
                    returnList.Add(docJson);
                }
            );

            return returnList.ToArray();
        }
        // PUT api/Categories/5
        public async Task PutAsync(string id, PaymentType paymentTypePut)
        {
            try
            {
                var filter = Builders<PaymentType>.Filter.Eq(p => p.Id, ObjectId.Parse(id));
                var update = Builders<PaymentType>.Update.Set("Name", paymentTypePut.Name);

                MongoHelper<PaymentType> paymentTypeHelper = new MongoHelper<PaymentType>();
                await paymentTypeHelper.Collection.UpdateOneAsync(filter, update);
            }
            catch (Exception e)
            {
                Trace.TraceError("PaymentTypes PutAsync error : " + e.Message);
                throw;
            }
        }
        // GET api/ExpenseApi
        public async Task<IEnumerable<string>> GetAsync()
        {            
            MongoHelper<Expense> expenseHelper = new MongoHelper<Expense>();
                
            IList<string> returnList = new List<string>();
            var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
            await expenseHelper.Collection.Find(e => e.Value > 0) // TODO filter by userId
                .ForEachAsync(expenseDocument => 
                {
                    string docJson = expenseDocument.ToJson(jsonWriterSettings);
                    returnList.Add(docJson);
                }
            );                    

            return returnList.ToArray();
        }
        // PUT api/Categories/5
        public async Task PutAsync(string id, Category categoryPut)
        {
            try
            {
                var filter = Builders<Category>.Filter.Eq(c => c.Id, ObjectId.Parse(id));
                var update = Builders<Category>.Update.Set("Name", categoryPut.Name);

                MongoHelper<Category> categoryHelper = new MongoHelper<Category>();
                await categoryHelper.Collection.UpdateOneAsync(filter, update);                
            }
            catch (Exception e)
            {
                Trace.TraceError("Categories PutAsync error : " + e.Message);
                throw;
            }
        }
        public override void OnException(ExceptionContext filterContext)
        {
            //#if DEBUG
            //将异常加入队列
            ErrorModel error = new ErrorModel();
            error.UID = Guid.NewGuid().ToString();
            error.Time = DateTime.Now;
            error.TypeValue = "MVC框架错误";
            error.ControllName = filterContext.Controller.ControllerContext.Controller.ToString();
            error.Message = filterContext.Exception.Message;
            error.StackTrace = filterContext.Exception.StackTrace;
            ExceptionQueue.Enqueue(error);
            MongoHelper<ErrorModel> helper = new MongoHelper<ErrorModel>("Server=127.0.0.1:27017", "errordatabase", "errorinfo");
            helper.Insert(error);
            //filterContext.HttpContext.Request.Path; 报错url路径
            filterContext.HttpContext.Response.Redirect("/Base/ErrorPage?message=" + error.Message);
            base.OnException(filterContext);

        }
        public SearchService()
        {
            _dishes = new MongoHelper<Dish>("dishes");
            _users = new MongoHelper<User>("users");
            _geocode = new GoogleGeoCoder();

            //takes 2 parameters:
            //the current user given by the linq query ( selector )
            //the address given by the user performing the search, instanciated as a Geocoding.Address type.
            //returns true if the distance between the current user selector and the given address is less than the distance scope,
            // otherwise, false.
            dishinmiles = (user, addressrequested) =>
                {
                  return _geocode
                   .ReverseGeocode(user.Location.Coordinates[1], user.Location.Coordinates[0])
                   .FirstOrDefault()
                   .DistanceBetween(addressrequested, DistanceUnits.Miles).Value < Scope;
                };
        }
Exemple #13
0
        public static void WriteJSON(NewEntitiesModel context)
        {
            var productItemsCollection = new MongoHelper<ProductItem>("Products");
            productItemsCollection.MongoCollection.Drop();

            foreach (var product in context.Products.Include("Vendor").Include("Reports"))
            {
                int productId = product.Id;
                string vendorName = product.Vendor.VendorName;
                string productName = product.ProductName;
                decimal quantity = 0;
                decimal sum = 0;
                foreach (var report in product.Reports)
                {
                    quantity += report.Quantity.Value;
                    sum += report.Sum.Value;
                }

                // Console.WriteLine(productId + " : " + vendorName + " : " + productName + " : " + quantity + " : " + sum);
                var tempObject = new ProductItem()
                {
                    ProductId = productId,
                    ProductName = productName,
                    VendorName = vendorName,
                    Quantity = quantity,
                    Sum = sum
                };
                productItemsCollection.InsertData(tempObject);
            }

            var productList = productItemsCollection.LoadData<ProductItem>().ToJson();
            var removeId = Regex.Replace(productList, "\"_id\".*?\\,", "", RegexOptions.IgnoreCase);
            var formatedList = Regex.Replace(removeId, ",", ",\n", RegexOptions.IgnoreCase);
            var removedBracesRight = Regex.Replace(formatedList, "},", "\n},", RegexOptions.IgnoreCase);
            var removedBracesLeft = Regex.Replace(removedBracesRight, "{", "{\n", RegexOptions.IgnoreCase);
            File.Delete(@"../../../GeneratedReports/report.json");
            File.WriteAllText(@"../../../GeneratedReports/report.json", removedBracesLeft);
            Console.WriteLine("JSON report created.");
        }
 public DishService()
 {
     //Instance of the collection.
        _dishes = new MongoHelper<Dish>("dishes");
 }
 public DatabasePDetails()
 {
     patientdetails = new MongoHelper<PatientDetails>();
 }
Exemple #16
0
    public static void save_html_item_to_db(string type, string url, string html, string doc_id, string html_path, string regular_path, string doc_path, string redirect_template_id)
    {
        /*---------------------------------------------------------------------------------------------------|
        | type     |  HTML PATH        |     Regular PATH    |        DOC PATH       |  Redirect Template ID |
        | ---------|-------------------|---------------------|-----------------------|-----------------------|
        | F        | Fixed Value       |           X         |ALL                    |           X           |
        | ---------|-------------------|---------------------|-----------------------|-----------------------|
        | U        | URL  Value        |          √         |ALL                    |           X           |
        | ---------|-------------------|---------------------|-----------------------|-----------------------|
        | H        | HTML Path         |          √         |ALL,INNER,PROPERTY     |           X           |
        | ---------|-------------------|---------------------|-----------------------|-----------------------|
        | FR       | Fixed Value       |           X         |ALL                    |          √           |
        | ---------|-------------------|---------------------|-----------------------|-----------------------|
        | HR       | HTML Path         |          √         |ALL,INNER,PROPERTY     |          √           |
        |------------------------------|---------------------|-----------------------|-----------------------|
        | IMG      | HTML Path         |          √         |ALL,INNER,PROPERTY     |           X           |
        |------------------------------|---------------------|-----------------------|----------------------*/

        QueryDocument doc_query = new QueryDocument();

        doc_query.Add("doc_id", doc_id);
        UpdateDocument doc_update = new UpdateDocument();
        Regex          reg;

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        HtmlNodeCollection           nodes;

        string str_from   = "";
        string str_update = "";

        switch (type)
        {
        case "F":
            str_update = doc_path.Replace("#ALL#", html_path);
            doc_update = MongoHelper.get_update_from_str(str_update);
            MongoHelper.update_bson(doc_query, doc_update);
            break;

        case "U":
            if (string.IsNullOrEmpty(regular_path))
            {
                str_from = url;
            }
            else
            {
                reg      = new Regex(regular_path);
                str_from = reg.Match(url).Value;
            }
            str_update = doc_path.Replace("#ALL#", str_from);
            doc_update = MongoHelper.get_update_from_str(str_update);
            MongoHelper.update_bson(doc_query, doc_update);
            break;

        case "H":
            doc.LoadHtml(html);
            nodes = doc.DocumentNode.SelectNodes(html_path);

            foreach (HtmlNode node in nodes)
            {
                string value_orig = "";
                string value_new  = "";

                reg = new Regex(@"#[^#]*#");
                MatchCollection colloct = reg.Matches(doc_path);
                value_orig = colloct[0].Value;

                if (value_orig == "#ALL#")
                {
                    value_new = node.WriteTo();
                }
                else if (value_orig == "#INNER#")
                {
                    value_new = node.InnerHtml;
                }
                else
                {
                    value_new = node.Attributes[value_orig.Replace("#", "").Trim()].Value.ToString();
                }

                //使用正则表达式选取值
                if (string.IsNullOrEmpty(regular_path))
                {
                    str_from = value_new;
                }
                else
                {
                    reg      = new Regex(regular_path);
                    str_from = reg.Match(value_new).Value;
                }

                //替代update_path中设置的参数
                str_update = doc_path.Replace(value_orig, str_from);
                doc_update = MongoHelper.get_update_from_str(str_update);
                MongoHelper.update_bson(doc_query, doc_update);
            }
            break;

        case "FR":
            str_update = doc_path.Replace("#ALL#", html_path);
            doc_update = MongoHelper.get_update_from_str(str_update);
            MongoHelper.update_bson(doc_query, doc_update);

            save_redirect_html_to_db(HtmlHelper.get_full_url(url, html_path), redirect_template_id, doc_id);
            break;

        case "HR":
            doc.LoadHtml(html);
            nodes = doc.DocumentNode.SelectNodes(html_path);

            foreach (HtmlNode node in nodes)
            {
                string value_orig = "";
                string value_new  = "";

                reg = new Regex(@"#[^#]*#");
                MatchCollection colloct = reg.Matches(doc_path);
                value_orig = colloct[0].Value;

                if (value_orig == "#ALL#")
                {
                    value_new = node.WriteTo();
                }
                else if (value_orig == "#INNER#")
                {
                    value_new = node.InnerHtml;
                }
                else
                {
                    value_new = node.Attributes[value_orig.Replace("#", "").Trim()].Value.ToString();
                }

                //使用正则表达式选取值
                if (string.IsNullOrEmpty(regular_path))
                {
                    str_from = value_new;
                }
                else
                {
                    reg      = new Regex(regular_path);
                    str_from = reg.Match(value_new).Value;
                }

                //替代update_path中设置的参数
                str_update = doc_path.Replace(value_orig, str_from);
                doc_update = MongoHelper.get_update_from_str(str_update);
                MongoHelper.update_bson(doc_query, doc_update);

                save_redirect_html_to_db(HtmlHelper.get_full_url(url, str_from), redirect_template_id, doc_id);
            }
            break;

        case "IMG":
            doc.LoadHtml(html);
            nodes = doc.DocumentNode.SelectNodes(html_path);

            string img_url = "";
            foreach (HtmlNode node in nodes)
            {
                string value_orig = "";
                string value_new  = "";

                reg = new Regex(@"#[^#]*#");
                MatchCollection colloct = reg.Matches(doc_path);
                value_orig = colloct[0].Value;

                if (value_orig == "#ALL#")
                {
                    value_new = node.WriteTo();
                }
                else if (value_orig == "#INNER#")
                {
                    value_new = node.InnerHtml;
                }
                else
                {
                    value_new = node.Attributes[value_orig.Replace("#", "").Trim()].Value.ToString();
                }

                //使用正则表达式选取值
                if (string.IsNullOrEmpty(regular_path))
                {
                    img_url = value_new;
                }
                else
                {
                    reg     = new Regex(regular_path);
                    img_url = reg.Match(value_new).Value;
                }

                str_from = img_url.Replace(@"/", "-").Replace(@"\", "-");
                //替代update_path中设置的参数
                str_update = doc_path.Replace(value_orig, str_from);
                doc_update = MongoHelper.get_update_from_str(str_update);
                MongoHelper.update_bson(doc_query, doc_update);

                HtmlHelper.down_img_from_url(HtmlHelper.get_full_url(url, img_url), doc_id + str_from);
            }
            break;

        default:
            break;
        }
    }
 public KataChallengeService()
 {
     _kataChallenges = new MongoHelper<KataChallenge>();
 }
        public JsonResult ResetPassword(ResetPasswordModel model)
        {
            ObjectId userID;

            if (!ObjectId.TryParse(model.UserID, out userID))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (model.NewPassword == null || model.NewPassword.Trim() == "")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "New password is not allowed to be empty."
                }));
            }

            if (model.ConfirmPassword == null || model.ConfirmPassword.Trim() == "")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Confirm password is not allowed to be empty."
                }));
            }

            if (model.NewPassword != model.ConfirmPassword)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "New password and confirm password is not the same."
                }));
            }

            // 判断用户是否存在
            var mongo = new MongoHelper();

            var filter = Builders <BsonDocument> .Filter.Eq("ID", userID);

            var doc = mongo.FindOne(Constant.UserCollectionName, filter);

            if (doc == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The user is not existed."
                }));
            }

            // 修改密码
            var salt     = DateTime.Now.ToString("yyyyMMddHHmmss");
            var password = MD5Helper.Encrypt(model.NewPassword + salt);

            var update1 = Builders <BsonDocument> .Update.Set("Password", password);

            var update2 = Builders <BsonDocument> .Update.Set("Salt", salt);

            var update = Builders <BsonDocument> .Update.Combine(update1, update2);

            mongo.UpdateOne(Constant.UserCollectionName, filter, update);

            return(Json(new
            {
                Code = 200,
                Msg = "Password reset successfully."
            }));
        }
Exemple #19
0
        public static async Task <SyncedData> SetSyncedDataAsync(int year, int week, string employee)
        {
            DateTime dayInWeek = new DateTime(year, 1, 1);

            dayInWeek = dayInWeek.AddDays((week - 1) * 7);
            while (dayInWeek.DayOfWeek != DayOfWeek.Monday)
            {
                dayInWeek = dayInWeek.AddDays(-1);
            }
            DateTime startDate = dayInWeek.Date;
            DateTime endDate   = startDate.AddDays(6);
            var      start     = startDate.Day + "_" + startDate.Month + "_" + startDate.Year;
            var      end       = endDate.Day + "_" + endDate.Month + "_" + endDate.Year;

            var records = RecordManager.GetRecords(start, end, employee);

            var hash = "";
            var csv  = "Fecha,Hora,Tipo,Empleado";

            foreach (var record in records)
            {
                var csv_line = new List <string>();
                record.DateTime = record.DateTime.AddHours(2);
                csv_line.Add(record.DateTime.Day + "/" + record.DateTime.Month + "/" + record.DateTime.Year);
                csv_line.Add(record.DateTime.Hour + ":" + record.DateTime.Minute);
                csv_line.Add(record.Type == "entrance" ? "Entrada" : "Salida");
                csv_line.Add(record.EmployeeName);
                csv = csv + "\n" + String.Join(',', csv_line);
            }
            using (var sha256 = SHA256.Create())
            {
                Byte[]        hashedCsv = sha256.ComputeHash(Encoding.UTF8.GetBytes(csv));
                StringBuilder sb        = new StringBuilder();
                foreach (Byte b in hashedCsv)
                {
                    sb.Append(b.ToString("x2"));
                }
                hash = sb.ToString();
            }

            var tx      = "";
            var web3    = new Web3(PROVIDER);
            var account = new Account(PRIVATE_KEY);

            try
            {
                //var balance = await web3.Eth.GetBalance.SendRequestAsync("0xF510450c7731B584E58635D361Fd33570dD92A98");
                //var etherAmount = Web3.Convert.FromWei(balance.Value);
                var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(WALLET);

                var encoded         = Web3.OfflineTransactionSigner.SignTransaction(PRIVATE_KEY, WALLET, new HexBigInteger(0), txCount.Value, new BigInteger(2), new BigInteger(26000), "0x" + hash);
                var transactionHash = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encoded);

                tx = transactionHash;
            }
            catch (System.Exception e)
            {
                throw e;
            }


            var result = new SyncedData {
                Id       = "",
                Year     = year,
                Week     = week,
                Employee = employee,
                Tx       = tx
            };
            BsonDocument newData = new BsonDocument();

            newData.Add("year", result.Year);
            newData.Add("week", result.Week);
            newData.Add("employee", result.Employee);
            newData.Add("tx", result.Tx);
            MongoHelper.GetDatabase().GetCollection <BsonDocument>("synced_data").InsertOne(newData);
            result.Id = newData.GetValue("_id").ToString();
            return(result);
        }
 public CategoryRepository()
 {
     _posts      = new MongoHelper <Post>();
     _categories = new MongoHelper <Category>();
 }
Exemple #21
0
 public IActionResult GetAll()
 {
     return(new ObjectResult(MongoHelper.GetAllData()));
 }
        /// <summary>
        /// 保存模型
        /// </summary>
        /// <returns></returns>
        public JsonResult Add()
        {
            var Request = HttpContext.Current.Request;
            var Server  = HttpContext.Current.Server;

            // 文件信息
            var file               = Request.Files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileExt == null || fileExt.ToLower() != ".zip")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "只允许上传zip格式文件!"
                }));
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Model/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = Server.MapPath(savePath);

            var tempPath = physicalPath + "\\temp"; // zip压缩文件临时保存目录

            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }

            file.SaveAs($"{tempPath}\\{fileName}");

            // 解压文件
            ZipHelper.Unzip($"{tempPath}\\{fileName}", physicalPath);

            // 删除临时目录
            Directory.Delete(tempPath, true);

            // 判断文件类型
            string entryFileName = null;
            var    meshType      = MeshType.unknown;

            var files = Directory.GetFiles(physicalPath);

            if (files.Where(o => o.ToLower().EndsWith(".3ds")).Count() > 0) // 3ds文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".3ds")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType._3ds;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".3mf")).Count() > 0) // 3mf文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".3mf")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType._3mf;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".amf")).Count() > 0) // amf文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".amf")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.amf;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".assimp")).Count() > 0) // assimp文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".assimp")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.assimp;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".json")).Count() > 0 && files.Where(o => o.ToLower().EndsWith(".bin")).Count() > 0) // binary文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".json")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.binary;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".json")).Count() > 0) // json文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".json")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.json;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".js")).Count() > 0) // Skinned json文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".js")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.js;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".awd")).Count() > 0) // awd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".awd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.awd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".babylon")).Count() > 0) // babylon文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".babylon")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.babylon;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".bvh")).Count() > 0) // bvh文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".bvh")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.bvh;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".ctm")).Count() > 0) // ctm文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".ctm")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.ctm;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".dae")).Count() > 0) // dae文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".dae")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.dae;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".drc")).Count() > 0) // drc文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".drc")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.drc;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".fbx")).Count() > 0) // fbx文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".fbx")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.fbx;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".gcode")).Count() > 0) // gcode文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".gcode")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.gcode;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".glb")).Count() > 0) // glb文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".glb")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.glb;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".gltf")).Count() > 0) // gltf文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".gltf")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.gltf;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".kmz")).Count() > 0) // kmz文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".kmz")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.kmz;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".md2")).Count() > 0) // md2文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".md2")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.md2;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".nrrd")).Count() > 0) // nrrd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".nrrd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.nrrd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".obj")).Count() > 0) // obj文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".obj")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.obj;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".pcd")).Count() > 0) // pcd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".pcd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.pcd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".pdb")).Count() > 0) // pdb文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".pdb")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.pdb;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".ply")).Count() > 0) // ply文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".ply")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.ply;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".pmd")).Count() > 0) // pmd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".pmd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.pmd;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".pmx")).Count() > 0) // pmd文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".pmx")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.pmx;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".prwm")).Count() > 0) // prwm文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".prwm")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.prwm;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".sea")).Count() > 0) // sea3d文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".sea")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.sea3d;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".stl")).Count() > 0) // stl文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".stl")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.stl;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".vrm")).Count() > 0) // vrm文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".vrm")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.vrm;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".wrl")).Count() > 0) // vrml文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".wrl")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.vrml;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".vtk")).Count() > 0) // vtk文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".vtk")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.vtk;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".lmesh")).Count() > 0) // lol文件
            {
                if (files.Where(o => o.ToLower().EndsWith(".lanim")).Count() == -1)
                {
                    Directory.Delete(physicalPath, true);

                    return(Json(new
                    {
                        Code = 300,
                        Msg = "未上传动画(.lanim)文件!"
                    }));
                }

                if (files.Where(o => o.ToLower().EndsWith(".png")).Count() == -1)
                {
                    Directory.Delete(physicalPath, true);

                    return(Json(new
                    {
                        Code = 300,
                        Msg = "未上传贴图(.png)文件!"
                    }));
                }

                var lmeshName    = files.Where(o => o.ToLower().EndsWith(".lmesh")).FirstOrDefault();
                var lanimName    = files.Where(o => o.ToLower().EndsWith(".lanim")).FirstOrDefault();
                var ltextureName = files.Where(o => o.ToLower().EndsWith(".png")).FirstOrDefault();

                lmeshName    = $"{savePath}/{Path.GetFileName(lmeshName)}";
                lanimName    = $"{savePath}/{Path.GetFileName(lanimName)}";
                ltextureName = $"{savePath}/{Path.GetFileName(ltextureName)}";

                entryFileName = $"{lmeshName};{lanimName};{ltextureName}";

                meshType = MeshType.lol;
            }
            else if (files.Where(o => o.ToLower().EndsWith(".x")).Count() > 0) // x文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".x")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                meshType      = MeshType.x;
            }

            if (entryFileName == null || meshType == MeshType.unknown)
            {
                Directory.Delete(physicalPath, true);

                return(Json(new
                {
                    Code = 300,
                    Msg = "未知文件类型!"
                }));
            }

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            // 保存到Mongo
            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["Thumbnail"]   = "",
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Type"]        = meshType.ToString(),
                ["Url"]         = entryFileName
            };

            mongo.InsertOne(Constant.MeshCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "上传成功!"
            }));
        }
        public JsonResult Save(ParticleSaveModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID不合法。"
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "名称不允许为空。"
                }));
            }

            // 查询
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.ParticleCollectionName, filter);

            var now = DateTime.Now;

            if (doc == null) // 新建
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc = new BsonDocument
                {
                    ["ID"]           = objectId,
                    ["Name"]         = model.Name,
                    ["CategoryID"]   = 0,
                    ["CategoryName"] = "",
                    ["TotalPinYin"]  = string.Join("", pinyin.TotalPinYin),
                    ["FirstPinYin"]  = string.Join("", pinyin.FirstPinYin),
                    ["Version"]      = 0,
                    ["CreateTime"]   = BsonDateTime.Create(now),
                    ["UpdateTime"]   = BsonDateTime.Create(now),
                    ["Data"]         = BsonDocument.Parse(model.Data),
                    ["Thumbnail"]    = ""
                };
                mongo.InsertOne(Constant.ParticleCollectionName, doc);
            }
            else // 更新
            {
                var update1 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update2 = Builders <BsonDocument> .Update.Set("Data", BsonDocument.Parse(model.Data));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.ParticleCollectionName, filter, update);
            }

            return(Json(new
            {
                Code = 200,
                Msg = "保存成功!",
                ID = objectId
            }));
        }
        private void OnGUI()
        {
            GUILayout.BeginHorizontal();
            string[] filesArray = this.files.ToArray();
            this.selectedIndex = EditorGUILayout.Popup(this.selectedIndex, filesArray);

            string lastFile = this.fileName;

            this.fileName = this.files[this.selectedIndex];

            if (this.fileName != lastFile)
            {
                this.LoadConfig();
            }

            this.newFileName = EditorGUILayout.TextField("文件名", this.newFileName);

            if (GUILayout.Button("添加"))
            {
                this.fileName    = this.newFileName;
                this.newFileName = "";
                File.WriteAllText(this.GetFilePath(), "");
                this.files         = this.GetConfigFiles();
                this.selectedIndex = this.files.IndexOf(this.fileName);
                this.LoadConfig();
            }

            if (GUILayout.Button("复制"))
            {
                this.fileName = $"{this.fileName}-copy";
                this.Save();
                this.files         = this.GetConfigFiles();
                this.selectedIndex = this.files.IndexOf(this.fileName);
                this.newFileName   = "";
            }

            if (GUILayout.Button("重命名"))
            {
                if (this.newFileName == "")
                {
                    Log.Debug("请输入新名字!");
                }
                else
                {
                    File.Delete(this.GetFilePath());
                    this.fileName = this.newFileName;
                    this.Save();
                    this.files         = this.GetConfigFiles();
                    this.selectedIndex = this.files.IndexOf(this.fileName);
                    this.newFileName   = "";
                }
            }

            if (GUILayout.Button("删除"))
            {
                File.Delete(this.GetFilePath());
                this.files         = this.GetConfigFiles();
                this.selectedIndex = 0;
                this.newFileName   = "";
            }

            GUILayout.EndHorizontal();

            GUILayout.Label("配置内容:");
            for (int i = 0; i < this.startConfigs.Count; ++i)
            {
                StartConfig startConfig = this.startConfigs[i];
                GUILayout.BeginHorizontal();
                GUILayout.Label($"AppId:");
                startConfig.AppId = EditorGUILayout.IntField(startConfig.AppId);
                GUILayout.Label($"服务器IP:");
                startConfig.ServerIP = EditorGUILayout.TextField(startConfig.ServerIP);
                GUILayout.Label($"AppType:");
                startConfig.AppType = (AppType)EditorGUILayout.EnumPopup(startConfig.AppType);

                InnerConfig innerConfig = startConfig.GetComponent <InnerConfig>();
                if (innerConfig != null)
                {
                    GUILayout.Label($"InnerHost:");
                    innerConfig.Host = EditorGUILayout.TextField(innerConfig.Host);
                    GUILayout.Label($"InnerPort:");
                    innerConfig.Port = EditorGUILayout.IntField(innerConfig.Port);
                }

                OuterConfig outerConfig = startConfig.GetComponent <OuterConfig>();
                if (outerConfig != null)
                {
                    GUILayout.Label($"OuterHost:");
                    outerConfig.Host = EditorGUILayout.TextField(outerConfig.Host);
                    GUILayout.Label($"OuterHost2:");
                    outerConfig.Host2 = EditorGUILayout.TextField(outerConfig.Host2);
                    GUILayout.Label($"OuterPort:");
                    outerConfig.Port = EditorGUILayout.IntField(outerConfig.Port);
                }

                ClientConfig clientConfig = startConfig.GetComponent <ClientConfig>();
                if (clientConfig != null)
                {
                    GUILayout.Label($"Host:");
                    clientConfig.Host = EditorGUILayout.TextField(clientConfig.Host);
                    GUILayout.Label($"Port:");
                    clientConfig.Port = EditorGUILayout.IntField(clientConfig.Port);
                }

                HttpConfig httpConfig = startConfig.GetComponent <HttpConfig>();
                if (httpConfig != null)
                {
                    GUILayout.Label($"AppId:");
                    httpConfig.AppId = EditorGUILayout.IntField(httpConfig.AppId);
                    GUILayout.Label($"AppKey:");
                    httpConfig.AppKey = EditorGUILayout.TextField(httpConfig.AppKey);
                    GUILayout.Label($"Url:");
                    httpConfig.Url = EditorGUILayout.TextField(httpConfig.Url);
                    GUILayout.Label($"ManagerSystemUrl:");
                    httpConfig.ManagerSystemUrl = EditorGUILayout.TextField(httpConfig.ManagerSystemUrl);
                }

                DBConfig dbConfig = startConfig.GetComponent <DBConfig>();
                if (dbConfig != null)
                {
                    GUILayout.Label($"Connection:");
                    dbConfig.ConnectionString = EditorGUILayout.TextField(dbConfig.ConnectionString);

                    GUILayout.Label($"DBName:");
                    dbConfig.DBName = EditorGUILayout.TextField(dbConfig.DBName);
                }

                if (GUILayout.Button("删除"))
                {
                    this.startConfigs.Remove(startConfig);
                    break;
                }
                if (GUILayout.Button("复制"))
                {
                    for (int j = 1; j < this.copyNum + 1; ++j)
                    {
                        StartConfig newStartConfig = MongoHelper.FromBson <StartConfig>(startConfig.ToBson());
                        newStartConfig.AppId += j;
                        this.startConfigs.Add(newStartConfig);
                    }
                    break;
                }

                if (i > 0)
                {
                    if (GUILayout.Button("上移"))
                    {
                        StartConfig s = this.startConfigs[i];
                        this.startConfigs.RemoveAt(i);
                        this.startConfigs.Insert(i - 1, s);
                        for (int j = 0; j < startConfigs.Count; ++j)
                        {
                            this.startConfigs[j].AppId = j + 1;
                        }
                        break;
                    }
                }

                if (i < this.startConfigs.Count - 1)
                {
                    if (GUILayout.Button("下移"))
                    {
                        StartConfig s = this.startConfigs[i];
                        this.startConfigs.RemoveAt(i);
                        this.startConfigs.Insert(i + 1, s);
                        for (int j = 0; j < startConfigs.Count; ++j)
                        {
                            this.startConfigs[j].AppId = j + 1;
                        }
                        break;
                    }
                }
                GUILayout.EndHorizontal();
            }

            GUILayout.Label("");

            GUILayout.BeginHorizontal();
            this.copyNum = EditorGUILayout.IntField("复制数量: ", this.copyNum);

            GUILayout.Label($"添加的AppType:");
            this.AppType = (AppType)EditorGUILayout.EnumPopup(this.AppType);

            if (GUILayout.Button("添加一行配置"))
            {
                StartConfig newStartConfig = new StartConfig();

                newStartConfig.AppType = this.AppType;

                if (this.AppType.Is(AppType.Gate | AppType.Realm | AppType.Manager))
                {
                    newStartConfig.AddComponent <OuterConfig>();
                }

                if (this.AppType.Is(AppType.Gate | AppType.Realm | AppType.Manager | AppType.Http | AppType.DB))
                {
                    newStartConfig.AddComponent <InnerConfig>();
                }

                if (this.AppType.Is(AppType.Benchmark))
                {
                    newStartConfig.AddComponent <ClientConfig>();
                }

                if (this.AppType.Is(AppType.Http))
                {
                    newStartConfig.AddComponent <HttpConfig>();
                }

                if (this.AppType.Is(AppType.DB))
                {
                    newStartConfig.AddComponent <DBConfig>();
                }

                this.startConfigs.Add(newStartConfig);
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();

            if (GUILayout.Button("保存"))
            {
                this.Save();
            }

            if (GUILayout.Button("启动"))
            {
                StartConfig startConfig = null;
                foreach (StartConfig config in this.startConfigs)
                {
                    if (config.AppType.Is(AppType.Manager))
                    {
                        startConfig = config;
                    }
                }

                if (startConfig == null)
                {
                    Log.Error("没有配置Manager!");
                    return;
                }

                string arguments = $"--appId={startConfig.AppId} --appType={startConfig.AppType} --config=../Config/StartConfig/{this.fileName}";

                ProcessStartInfo info = new ProcessStartInfo(@"App.exe", arguments)
                {
                    UseShellExecute = true, WorkingDirectory = @"..\Bin\"
                };
                Process.Start(info);
            }
            GUILayout.EndHorizontal();
        }
Exemple #25
0
        public async Task YeyItWorks()
        {
            CirqusLoggerFactory.Current = new ConsoleLoggerFactory();

            var mongoDatabase = MongoHelper.InitializeTestDatabase();

            var firstView  = new MongoDbViewManager <HeyCounter>(mongoDatabase);
            var secondView = new MongoDbViewManager <WordCounter>(mongoDatabase);

            /*         ________.......------=====^^!^^=====------.......________             */
            var dependentView = new MongoDbViewManager <HeyPercentageCalculator>(mongoDatabase);
            /*         ________.......------=====^^!^^=====------.......________             */

            var waitHandle        = new ViewManagerWaitHandle();
            var specialWaitHandle = new ViewManagerWaitHandle();

            var commandProcessor = CommandProcessor.With()
                                   .EventStore(e => e.UseInMemoryEventStore())
                                   .EventDispatcher(e =>
            {
                e.UseViewManagerEventDispatcher(firstView)
                .WithWaitHandle(waitHandle);

                e.UseViewManagerEventDispatcher(secondView)
                .WithWaitHandle(waitHandle);

                e.UseDependentViewManagerEventDispatcher(dependentView)
                .WithWaitHandle(specialWaitHandle)
                .DependentOn(firstView, secondView)
                .WithViewContext(new Dictionary <string, object>
                {
                    { "heys", mongoDatabase.GetCollection <HeyCounter>(typeof(HeyCounter).Name).AsQueryable() },
                    { "words", mongoDatabase.GetCollection <WordCounter>(typeof(WordCounter).Name).AsQueryable() },
                });
            })
                                   .Create();

            RegisterForDisposal(commandProcessor);

            var result = Enumerable.Range(0, 100)
                         .Select(i => commandProcessor.ProcessCommand(new DoStuff("test", "hej meddig min ven " + i)))
                         .Last();

            await waitHandle.WaitForAll(result, TimeSpan.FromSeconds(5));

            var viewId = InstancePerAggregateRootLocator.GetViewIdFromAggregateRootId("test");

            var firstViewInstance  = firstView.Load(viewId);
            var secondViewInstance = secondView.Load(viewId);

            Assert.That(firstViewInstance.Count, Is.EqualTo(100));
            Assert.That(secondViewInstance.Count, Is.EqualTo(500));

            Console.WriteLine("Waiting for dependent views to catch up...");
            await specialWaitHandle.WaitForAll(result, TimeSpan.FromSeconds(5));

            Console.WriteLine("DOne!");

            var heyPercentageCalculator = dependentView.Load(viewId);

            Assert.That(heyPercentageCalculator.HeyPercentage, Is.EqualTo(20));
        }
Exemple #26
0
    //根据定义的模板,保存HTML内容到DB
    public static void save_html_to_db(string url, string template_id)
    {
        string html = HtmlHelper.get_html(url);


        string sql = "select * from template_main a,template_list b where a.template_id=b.template_id and a.template_id='{0}' and is_use='Y' ";

        sql = String.Format(sql, template_id);
        DataTable dt = SQLServerHelper.get_table(sql);

        //Get Query Document
        string doc_id = "";

        foreach (DataRow row in dt.Rows)
        {
            if (row["is_doc_id"].ToString().ToLower() == "y")
            {
                doc_id = get_doc_id(row["type"].ToString(), url, html, row["html_path"].ToString(), row["regular_path"].ToString(), row["doc_path"].ToString());
            }
        }

        if (string.IsNullOrEmpty(doc_id))
        {
            Random rand         = new Random();
            string doc_id_start = "T-" + template_id + "-";
            sql    = "select count(*) from template_main where template_id like '{0}%'";
            sql    = string.Format(sql, doc_id_start);
            doc_id = doc_id_start + SQLServerHelper.get_table(sql).Rows.Count.ToString("0000");
        }


        //Create Document
        QueryDocument doc_query = new QueryDocument();

        doc_query.Add("doc_id", doc_id);


        if (MongoHelper.query_cursor_from_bson(doc_query).Count() == 0)
        {
            BsonDocument doc_insert = new BsonDocument();
            doc_insert.Add("doc_id", doc_id);
            MongoHelper.insert_bson(doc_insert);
            sql = "insert into data (doc_id,create_time) values ('{0}','{1}') ";
            sql = string.Format(sql, doc_id, DateTime.Now.ToString());
            SQLServerHelper.exe_sql(sql);
        }


        //Save Each Document to DB
        foreach (DataRow row in dt.Rows)
        {
            if (row["is_doc_id"].ToString() == "Y")
            {
                continue;
            }
            try
            {
                save_html_item_to_db(row["type"].ToString(), url, html, doc_id, row["html_path"].ToString(), row["regular_path"].ToString(),
                                     row["doc_path"].ToString(), row["redirect_template_id"].ToString());
            }
            catch (Exception error) { }
        }
    }
 public UserManager()
 {
     _users = new MongoHelper<User>();
 }
 public MongoRepository(string connectionString, string collectionName)
 {
     this.collection = MongoHelper.GetCollection <TEntity>(connectionString, collectionName);
 }
Exemple #29
0
 public PostRepository()
 {
     _posts = new MongoHelper<Post>();
 }
 public MongoRepository(MongoUrl url, string collectionName)
 {
     this.collection = MongoHelper.GetCollection <TEntity>(url, collectionName);
 }
        public JsonResult ChangePassword(ChangePasswordModel model)
        {
            var user = UserHelper.GetCurrentUser();

            if (user == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The user is not existed."
                }));
            }

            // 验证密码是否为空
            if (model.OldPassword == null || model.OldPassword.Trim() == "")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Old password is not allowed to be empty."
                }));
            }

            if (model.NewPassword == null || model.NewPassword.Trim() == "")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "New password is not allowed to be empty."
                }));
            }

            if (model.ConfirmPassword == null || model.ConfirmPassword.Trim() == "")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Confirm password is not allowed to be empty."
                }));
            }

            if (model.NewPassword != model.ConfirmPassword)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "New password and confirm password is not the same."
                }));
            }

            // 验证旧密码
            var oldPassword = MD5Helper.Encrypt(model.OldPassword + user.Salt);

            if (oldPassword != user.Password)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Old password is not correct."
                }));
            }

            // 修改密码
            var salt     = DateTime.Now.ToString("yyyyMMddHHmmss");
            var password = MD5Helper.Encrypt(model.NewPassword + salt);

            var filter = Builders <BsonDocument> .Filter.Eq("ID", ObjectId.Parse(user.ID));

            var update1 = Builders <BsonDocument> .Update.Set("Password", password);

            var update2 = Builders <BsonDocument> .Update.Set("Salt", salt);

            var update = Builders <BsonDocument> .Update.Combine(update1, update2);

            var mongo = new MongoHelper();

            mongo.UpdateOne(Constant.UserCollectionName, filter, update);

            return(Json(new
            {
                Code = 200,
                Msg = "Password changed successfully!"
            }));
        }
Exemple #32
0
 public override string ToString()
 {
     return(MongoHelper.ToJson(this));
 }
        public JsonResult List()
        {
            var mongo = new MongoHelper();

            // 获取所有类别
            var filter = Builders <BsonDocument> .Filter.Eq("Type", "Prefab");

            var categories = mongo.FindMany(Constant.CategoryCollectionName, filter).ToList();

            var docs = new List <BsonDocument>();

            if (ConfigHelper.EnableAuthority)
            {
                var user = UserHelper.GetCurrentUser();

                if (user != null)
                {
                    var filter1 = Builders <BsonDocument> .Filter.Eq("UserID", user.ID);

                    if (user.Name == "Administrator")
                    {
                        var filter2 = Builders <BsonDocument> .Filter.Exists("UserID");

                        var filter3 = Builders <BsonDocument> .Filter.Not(filter2);

                        filter1 = Builders <BsonDocument> .Filter.Or(filter1, filter3);
                    }
                    docs = mongo.FindMany(Constant.PrefabCollectionName, filter1).ToList();
                }
            }
            else
            {
                docs = mongo.FindAll(Constant.PrefabCollectionName).ToList();
            }

            var list = new List <PrefabModel>();

            foreach (var i in docs)
            {
                var categoryID   = "";
                var categoryName = "";

                if (i.Contains("Category") && !i["Category"].IsBsonNull && !string.IsNullOrEmpty(i["Category"].ToString()))
                {
                    var doc = categories.Where(n => n["_id"].ToString() == i["Category"].ToString()).FirstOrDefault();
                    if (doc != null)
                    {
                        categoryID   = doc["_id"].ToString();
                        categoryName = doc["Name"].ToString();
                    }
                }

                var info = new PrefabModel
                {
                    ID           = i["ID"].AsObjectId.ToString(),
                    Name         = i["Name"].AsString,
                    CategoryID   = categoryID,
                    CategoryName = categoryName,
                    TotalPinYin  = i["TotalPinYin"].ToString(),
                    FirstPinYin  = i["FirstPinYin"].ToString(),
                    CreateTime   = i["CreateTime"].ToUniversalTime(),
                    UpdateTime   = i["UpdateTime"].ToUniversalTime(),
                    Thumbnail    = i.Contains("Thumbnail") && !i["Thumbnail"].IsBsonNull ? i["Thumbnail"].ToString() : null
                };

                list.Add(info);
            }

            list = list.OrderByDescending(n => n.UpdateTime).ToList();

            return(Json(new
            {
                Code = 200,
                Msg = "Get Successfully!",
                Data = list
            }));
        }
        public JsonResult Save(PrefabSaveModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            // 查询
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.PrefabCollectionName, filter);

            var now = DateTime.Now;

            if (doc == null) // 新建
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc = new BsonDocument
                {
                    ["ID"]           = objectId,
                    ["Name"]         = model.Name,
                    ["CategoryID"]   = 0,
                    ["CategoryName"] = "",
                    ["TotalPinYin"]  = string.Join("", pinyin.TotalPinYin),
                    ["FirstPinYin"]  = string.Join("", pinyin.FirstPinYin),
                    ["Version"]      = 0,
                    ["CreateTime"]   = BsonDateTime.Create(now),
                    ["UpdateTime"]   = BsonDateTime.Create(now),
                    ["Data"]         = BsonDocument.Parse(model.Data),
                    ["Thumbnail"]    = ""
                };

                if (ConfigHelper.EnableAuthority)
                {
                    var user = UserHelper.GetCurrentUser();

                    if (user != null)
                    {
                        doc["UserID"] = user.ID;
                    }
                }

                mongo.InsertOne(Constant.PrefabCollectionName, doc);
            }
            else // 更新
            {
                var update1 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update2 = Builders <BsonDocument> .Update.Set("Data", BsonDocument.Parse(model.Data));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.PrefabCollectionName, filter, update);
            }

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!",
                ID = objectId
            }));
        }
Exemple #35
0
        public JsonResult Save(SaveSceneModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "场景ID不合法。"
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "场景名称不允许为空。"
                }));
            }

            if (model.Name.StartsWith("_"))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "场景名称不允许以下划线开头。"
                }));
            }

            // 查询场景信息
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.SceneCollectionName, filter);

            var now = DateTime.Now;

            string collectionName;

            if (doc == null) // 新建场景
            {
                collectionName = "Scene" + now.ToString("yyyyMMddHHmmss");
            }
            else // 编辑场景
            {
                collectionName = doc["CollectionName"].ToString();
            }

            // 保存或更新场景综合信息
            if (doc == null)
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc                   = new BsonDocument();
                doc["ID"]             = objectId;
                doc["Name"]           = model.Name;
                doc["TotalPinYin"]    = string.Join("", pinyin.TotalPinYin);
                doc["FirstPinYin"]    = string.Join("", pinyin.FirstPinYin);
                doc["CollectionName"] = collectionName;
                doc["Version"]        = 0;
                doc["CreateTime"]     = BsonDateTime.Create(now);
                doc["UpdateTime"]     = BsonDateTime.Create(now);
                mongo.InsertOne(Constant.SceneCollectionName, doc);
            }
            else
            {
                var update1 = Builders <BsonDocument> .Update.Set("Version", int.Parse(doc["Version"].ToString()) + 1);

                var update2 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.SceneCollectionName, filter, update);
            }

            // 保存场景信息
            var list = JsonHelper.ToObject <JArray>(model.Data);

            var docs = new List <BsonDocument>();

            foreach (var i in list)
            {
                docs.Add(BsonDocument.Parse(i.ToString()));
            }

            mongo.DeleteAll(collectionName);
            mongo.InsertMany(collectionName, docs);

            return(Json(new
            {
                Code = 200,
                Msg = "保存成功!",
                ID = objectId
            }));
        }
 public MongoRepository(MongoUrl url)
 {
     this.collection = MongoHelper.GetCollection <TEntity>(url);
 }
Exemple #37
0
 public MongoDbRepository()
 {
     _entitys = new MongoHelper();
 }
 public CompanyService()
 {
     _companys = new MongoHelper<Company>();
 }
 public PhotoTypeManager()
 {
     _photoTypes = new MongoHelper<PhotoType>();
 }
 public DatabasePAccount()
 {
     patientlogin = new MongoHelper<PatientLogin>();
 }
Exemple #41
0
        private void OnGUI()
        {
            {
                GUILayout.BeginHorizontal();
                string[] filesArray = this.files.ToArray();
                this.selectedIndex = EditorGUILayout.Popup(this.selectedIndex, filesArray);

                string lastFile = this.fileName;
                this.fileName = this.files[this.selectedIndex];

                if (this.fileName != lastFile)
                {
                    this.LoadConfig();
                }

                this.newFileName = EditorGUILayout.TextField("文件名", this.newFileName);

                if (GUILayout.Button("添加"))
                {
                    this.fileName    = this.newFileName;
                    this.newFileName = "";
                    File.WriteAllText(this.GetFilePath(), "");
                    this.files         = this.GetConfigFiles();
                    this.selectedIndex = this.files.IndexOf(this.fileName);
                    this.LoadConfig();
                }

                if (GUILayout.Button("复制"))
                {
                    this.fileName = $"{this.fileName}-copy";
                    this.Save();
                    this.files         = this.GetConfigFiles();
                    this.selectedIndex = this.files.IndexOf(this.fileName);
                    this.newFileName   = "";
                }

                if (GUILayout.Button("重命名"))
                {
                    if (this.newFileName == "")
                    {
                        Log.Debug("请输入新名字!");
                    }
                    else
                    {
                        File.Delete(this.GetFilePath());
                        this.fileName = this.newFileName;
                        this.Save();
                        this.files         = this.GetConfigFiles();
                        this.selectedIndex = this.files.IndexOf(this.fileName);
                        this.newFileName   = "";
                    }
                }

                if (GUILayout.Button("删除"))
                {
                    File.Delete(this.GetFilePath());
                    this.files         = this.GetConfigFiles();
                    this.selectedIndex = 0;
                    this.newFileName   = "";
                }

                GUILayout.EndHorizontal();
            }

            scrollPos = GUILayout.BeginScrollView(this.scrollPos, true, true);
            for (int i = 0; i < this.startConfigs.Count; ++i)
            {
                StartConfig startConfig = this.startConfigs[i];


                GUILayout.BeginHorizontal();
                {
                    GUILayout.BeginHorizontal(GUILayout.Width(1700));
                    {
                        GUILayout.BeginHorizontal(GUILayout.Width(350));
                        GUILayout.Label($"AppId:");
                        startConfig.AppId = EditorGUILayout.IntField(startConfig.AppId, GUILayout.Width(30));
                        GUILayout.Label($"服务器IP:");
                        startConfig.ServerIP = EditorGUILayout.TextField(startConfig.ServerIP, GUILayout.Width(100));
                        GUILayout.Label($"AppType:");
                        startConfig.AppType = (AppType)EditorGUILayout.EnumPopup(startConfig.AppType);
                        GUILayout.EndHorizontal();
                    }
                    {
                        GUILayout.BeginHorizontal(GUILayout.Width(150));
                        InnerConfig innerConfig = startConfig.GetComponent <InnerConfig>();
                        if (innerConfig != null)
                        {
                            GUILayout.Label($"内网地址:");
                            innerConfig.Address = EditorGUILayout.TextField(innerConfig.Address, GUILayout.Width(120));
                        }

                        GUILayout.EndHorizontal();
                    }
                    {
                        GUILayout.BeginHorizontal(GUILayout.Width(350));
                        OuterConfig outerConfig = startConfig.GetComponent <OuterConfig>();
                        if (outerConfig != null)
                        {
                            GUILayout.Label($"外网地址:");
                            outerConfig.Address = EditorGUILayout.TextField(outerConfig.Address, GUILayout.Width(120));
                            GUILayout.Label($"外网地址2:");
                            outerConfig.Address2 = EditorGUILayout.TextField(outerConfig.Address2, GUILayout.Width(120));
                        }

                        GUILayout.EndHorizontal();
                    }
                    {
                        GUILayout.BeginHorizontal(GUILayout.Width(350));
                        ClientConfig clientConfig = startConfig.GetComponent <ClientConfig>();
                        if (clientConfig != null)
                        {
                            GUILayout.Label($"连接地址:");
                            clientConfig.Address = EditorGUILayout.TextField(clientConfig.Address, GUILayout.Width(120));
                        }

                        HttpConfig httpConfig = startConfig.GetComponent <HttpConfig>();
                        if (httpConfig != null)
                        {
                            GUILayout.Label($"AppId:");
                            httpConfig.AppId = EditorGUILayout.IntField(httpConfig.AppId, GUILayout.Width(20));
                            GUILayout.Label($"AppKey:");
                            httpConfig.AppKey = EditorGUILayout.TextField(httpConfig.AppKey);
                            GUILayout.Label($"Url:");
                            httpConfig.Url = EditorGUILayout.TextField(httpConfig.Url);
                            GUILayout.Label($"ManagerSystemUrl:");
                            httpConfig.ManagerSystemUrl = EditorGUILayout.TextField(httpConfig.ManagerSystemUrl);
                        }

                        DBConfig dbConfig = startConfig.GetComponent <DBConfig>();
                        if (dbConfig != null)
                        {
                            GUILayout.Label($"Connection:");
                            dbConfig.ConnectionString = EditorGUILayout.TextField(dbConfig.ConnectionString);

                            GUILayout.Label($"DBName:");
                            dbConfig.DBName = EditorGUILayout.TextField(dbConfig.DBName);
                        }

                        GUILayout.EndHorizontal();
                    }
                    GUILayout.EndHorizontal();
                }

                {
                    GUILayout.BeginHorizontal();
                    if (GUILayout.Button("删除"))
                    {
                        this.startConfigs.Remove(startConfig);
                        break;
                    }

                    if (GUILayout.Button("复制"))
                    {
                        for (int j = 1; j < this.copyNum + 1; ++j)
                        {
                            StartConfig newStartConfig = MongoHelper.FromBson <StartConfig>(startConfig.ToBson());
                            newStartConfig.AppId += j;
                            this.startConfigs.Add(newStartConfig);
                        }

                        break;
                    }

                    if (i >= 0)
                    {
                        if (GUILayout.Button("上移"))
                        {
                            if (i == 0)
                            {
                                break;
                            }
                            StartConfig s = this.startConfigs[i];
                            this.startConfigs.RemoveAt(i);
                            this.startConfigs.Insert(i - 1, s);
                            for (int j = 0; j < startConfigs.Count; ++j)
                            {
                                this.startConfigs[j].AppId = j + 1;
                            }

                            break;
                        }
                    }

                    if (i <= this.startConfigs.Count - 1)
                    {
                        if (GUILayout.Button("下移"))
                        {
                            if (i == this.startConfigs.Count - 1)
                            {
                                break;
                            }
                            StartConfig s = this.startConfigs[i];
                            this.startConfigs.RemoveAt(i);
                            this.startConfigs.Insert(i + 1, s);
                            for (int j = 0; j < startConfigs.Count; ++j)
                            {
                                this.startConfigs[j].AppId = j + 1;
                            }

                            break;
                        }
                    }
                    GUILayout.EndHorizontal();
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.EndScrollView();



            GUILayout.Label("");

            GUILayout.BeginHorizontal();
            this.copyNum = EditorGUILayout.IntField("复制数量: ", this.copyNum);

            GUILayout.Label($"添加的AppType:");
            this.AppType = (AppType)EditorGUILayout.EnumPopup(this.AppType);

            if (GUILayout.Button("添加一行配置"))
            {
                StartConfig newStartConfig = new StartConfig();

                newStartConfig.AppType = this.AppType;

                if (this.AppType.Is(AppType.Gate | AppType.Realm | AppType.Manager))
                {
                    newStartConfig.AddComponent <OuterConfig>();
                }

                if (this.AppType.Is(AppType.Gate | AppType.Realm | AppType.Manager | AppType.Http | AppType.DB | AppType.Map | AppType.Location))
                {
                    newStartConfig.AddComponent <InnerConfig>();
                }

                if (this.AppType.Is(AppType.Http))
                {
                    newStartConfig.AddComponent <HttpConfig>();
                }

                if (this.AppType.Is(AppType.DB))
                {
                    newStartConfig.AddComponent <DBConfig>();
                }

                if (this.AppType.Is(AppType.Benchmark))
                {
                    newStartConfig.AddComponent <ClientConfig>();
                }

                if (this.AppType.Is(AppType.BenchmarkWebsocketServer))
                {
                    newStartConfig.AddComponent <OuterConfig>();
                }

                if (this.AppType.Is(AppType.BenchmarkWebsocketClient))
                {
                    newStartConfig.AddComponent <ClientConfig>();
                }

                this.startConfigs.Add(newStartConfig);
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("保存"))
            {
                this.Save();
            }

            if (GUILayout.Button("启动"))
            {
                StartConfig startConfig = null;
                foreach (StartConfig config in this.startConfigs)
                {
                    if (config.AppType.Is(AppType.Manager))
                    {
                        startConfig = config;
                    }
                }

                if (startConfig == null)
                {
                    Log.Error("没有配置Manager!");
                    return;
                }

                string arguments = $"App.dll --appId={startConfig.AppId} --appType={startConfig.AppType} --config=../Config/StartConfig/{this.fileName}";
                ProcessHelper.Run("dotnet", arguments, "../Bin/");
            }
            GUILayout.EndHorizontal();
        }
Exemple #42
0
        public JsonResult Add()
        {
            var Request = HttpContext.Current.Request;
            var Server  = HttpContext.Current.Server;

            // 文件信息
            var file               = Request.Files[0];
            var fileName           = file.FileName;
            var fileSize           = file.ContentLength;
            var fileType           = file.ContentType;
            var fileExt            = Path.GetExtension(fileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileExt == null || fileExt.ToLower() != ".zip")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Only zip file is allowed!"
                }));
            }

            // 保存文件
            var now = DateTime.Now;

            var savePath     = $"/Upload/Animation/{now.ToString("yyyyMMddHHmmss")}";
            var physicalPath = Server.MapPath(savePath);

            var tempPath = physicalPath + "\\temp"; // zip压缩文件临时保存目录

            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }

            file.SaveAs($"{tempPath}\\{fileName}");

            // 解压文件
            ZipHelper.Unzip($"{tempPath}\\{fileName}", physicalPath);

            // 删除临时目录
            Directory.Delete(tempPath, true);

            // 判断文件类型
            string entryFileName = null;
            var    animationType = AnimationType.unknown;

            var files = Directory.GetFiles(physicalPath);

            if (files.Where(o => o.ToLower().EndsWith(".vmd")).Count() > 0) // mmd动画文件或mmd相机动画文件
            {
                entryFileName = files.Where(o => o.ToLower().EndsWith(".vmd")).FirstOrDefault();
                entryFileName = $"{savePath}/{Path.GetFileName(entryFileName)}";
                animationType = AnimationType.mmd;
            }

            if (entryFileName == null || animationType == AnimationType.unknown)
            {
                Directory.Delete(physicalPath, true);

                return(Json(new
                {
                    Code = 300,
                    Msg = "Unknown file type!"
                }));
            }

            var pinyin = PinYinHelper.GetTotalPinYin(fileNameWithoutExt);

            // 保存到Mongo
            var mongo = new MongoHelper();

            var doc = new BsonDocument
            {
                ["AddTime"]     = BsonDateTime.Create(now),
                ["FileName"]    = fileName,
                ["FileSize"]    = fileSize,
                ["FileType"]    = fileType,
                ["FirstPinYin"] = string.Join("", pinyin.FirstPinYin),
                ["Name"]        = fileNameWithoutExt,
                ["SaveName"]    = fileName,
                ["SavePath"]    = savePath,
                ["Thumbnail"]   = "",
                ["TotalPinYin"] = string.Join("", pinyin.TotalPinYin),
                ["Type"]        = animationType.ToString(),
                ["Url"]         = entryFileName
            };

            if (ConfigHelper.EnableAuthority)
            {
                var user = UserHelper.GetCurrentUser();

                if (user != null)
                {
                    doc["UserID"] = user.ID;
                }
            }

            mongo.InsertOne(Constant.AnimationCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "Upload successfully!"
            }));
        }
Exemple #43
0
 public CalleService()
 {
     this._calles = new MongoHelper<Calle>("calles");
 }
        public JsonResult Run(string ID, int version = -1)
        {
            var mongo = new MongoHelper();

            var filter = Builders <BsonDocument> .Filter.Eq("ID", BsonObjectId.Create(ID));

            var doc = mongo.FindOne(Constant.SceneCollectionName, filter);

            if (doc == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The scene is not existed!"
                }));
            }

            // 获取场景数据
            var collectionName = doc["CollectionName"].AsString;

            List <BsonDocument> docs;

            if (version == -1) // 最新版本
            {
                docs = mongo.FindAll(collectionName).ToList();
            }
            else // 特定版本
            {
                filter = Builders <BsonDocument> .Filter.Eq(Constant.VersionField, BsonInt32.Create(version));

                docs = mongo.FindMany($"{collectionName}{Constant.HistorySuffix}", filter).ToList();
            }

            // 创建临时目录
            var now = DateTime.Now;

            var path = HttpContext.Current.Server.MapPath($"~/temp/{now.ToString("yyyyMMddHHmmss")}");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // 拷贝静态资源
            var viewPath = HttpContext.Current.Server.MapPath("~/view.html");

            var viewFileData = File.ReadAllText(viewPath, Encoding.UTF8);

            viewFileData = viewFileData.Replace("location.origin", "'.'"); // 替换server地址,以便部署到Git Pages上
            viewFileData = viewFileData.Replace("<%SceneID%>", ID);        // 发布场景自动把`<%SceneID%>`替换成真实场景ID,不再需要加`SceneID`或`SceneFile`参数
            File.WriteAllText($"{path}/view.html", viewFileData, Encoding.UTF8);

            var faviconPath = HttpContext.Current.Server.MapPath("~/favicon.ico");

            File.Copy(faviconPath, $"{path}/favicon.ico", true);

            var assetsPath = HttpContext.Current.Server.MapPath($"~/assets");

            DirectoryHelper.Copy(assetsPath, $"{path}/assets");

            var buildPath = HttpContext.Current.Server.MapPath($"~/build");

            DirectoryHelper.Copy(buildPath, $"{path}/build");

            // 分析场景,拷贝使用的资源
            var data = new JArray();

            var urls = new List <string>();

            foreach (var i in docs)
            {
                i["_id"] = i["_id"].ToString(); // ObjectId

                var generator = i["metadata"]["generator"].ToString();

                if (generator == "ServerObject")                            // 服务端模型
                {
                    urls.Add(i["userData"]["Url"].ToString());              // 模型文件

                    if (i["userData"].AsBsonDocument.Contains("Animation")) // MMD模型动画
                    {
                        urls.Add(i["userData"]["Animation"]["Url"].ToString());
                    }
                    if (i["userData"].AsBsonDocument.Contains("CameraAnimation")) // MMD相机动画
                    {
                        urls.Add(i["userData"]["CameraAnimation"]["Url"].ToString());
                    }
                    if (i["userData"].AsBsonDocument.Contains("Audio")) // MMD音频
                    {
                        urls.Add(i["userData"]["Audio"]["Url"].ToString());
                    }
                }
                else if (generator == "SceneSerializer")                                                    // 场景
                {
                    if (i["background"].IsBsonDocument)                                                     // 贴图或立方体纹理
                    {
                        if (i["background"]["metadata"]["generator"].ToString() == "CubeTextureSerializer") // 立方体纹理
                        {
                            var array = i["background"]["image"].AsBsonArray;
                            foreach (var j in array)
                            {
                                urls.Add(j["src"].ToString());
                            }
                        }
                        else // 普通纹理
                        {
                            urls.Add(i["background"]["image"]["src"].ToString());
                        }
                    }
                }
                else if (generator == "MeshSerializer" || generator == "SpriteSerializer") // 模型
                {
                    if (i["material"].IsBsonArray)
                    {
                        foreach (BsonDocument material in i["material"].AsBsonArray)
                        {
                            GetUrlInMaterial(material, urls);
                        }
                    }
                    else if (i["material"].IsBsonDocument)
                    {
                        GetUrlInMaterial(i["material"].AsBsonDocument, urls);
                    }
                }
                else if (generator == "AudioSerializer")
                {
                    urls.Add(i["userData"]["Url"].ToString());
                }

                data.Add(JsonHelper.ToObject <JObject>(i.ToJson()));
            }

            // 将场景写入文件
            if (!Directory.Exists($"{path}/Scene"))
            {
                Directory.CreateDirectory($"{path}/Scene");
            }

            // 复制资源
            var file   = new FileStream($"{path}/Scene/{ID}.txt", FileMode.Create, FileAccess.Write);
            var writer = new StreamWriter(file);

            writer.Write(JsonHelper.ToJson(data));
            writer.Close();
            file.Close();

            foreach (var url in urls)
            {
                if (!url.StartsWith("/")) // 可能是base64地址
                {
                    continue;
                }

                // LOL模型存在多个url,两个url之间用分号分隔
                var _urls = url.Split(';');

                foreach (var _url in _urls)
                {
                    if (string.IsNullOrEmpty(_url))
                    {
                        continue;
                    }

                    var sourceDirName = Path.GetDirectoryName(HttpContext.Current.Server.MapPath($"~{_url}"));
                    var targetDirName = Path.GetDirectoryName($"{path}{_url}");

                    DirectoryHelper.Copy(sourceDirName, targetDirName);
                }
            }

            return(Json(new
            {
                Code = 200,
                Msg = "Export successfully!",
                Url = $"/temp/{now.ToString("yyyyMMddHHmmss")}/view.html?sceneFile={ID}"
            }));
        }
 public ReservationStateService()
 {
     _ReservationTypes = new MongoHelper<ReservationState>("reservationstate");
 }
Exemple #46
0
        private static void Main(string[] args)
        {
            // 异步方法全部会回掉到主线程
            OneThreadSynchronizationContext contex = new OneThreadSynchronizationContext();

            SynchronizationContext.SetSynchronizationContext(contex);

            MongoHelper.Init();

            try
            {
                ObjectEvents.Instance.Add("Model", typeof(Game).Assembly);
                ObjectEvents.Instance.Add("Hotfix", DllHelper.GetHotfixAssembly());

                Options     options     = Game.Scene.AddComponent <OptionComponent, string[]>(args).Options;
                StartConfig startConfig = Game.Scene.AddComponent <StartConfigComponent, string, int>(options.Config, options.AppId).StartConfig;

                if (!options.AppType.Is(startConfig.AppType))
                {
                    Log.Error("命令行参数apptype与配置不一致");
                    return;
                }

                IdGenerater.AppId = options.AppId;

                LogManager.Configuration.Variables["appType"]       = startConfig.AppType.ToString();
                LogManager.Configuration.Variables["appId"]         = startConfig.AppId.ToString();
                LogManager.Configuration.Variables["appTypeFormat"] = $"{startConfig.AppType,-8}";
                LogManager.Configuration.Variables["appIdFormat"]   = $"{startConfig.AppId:D3}";

                Log.Info("server start........................");

                Game.Scene.AddComponent <OpcodeTypeComponent>();
                Game.Scene.AddComponent <MessageDispatherComponent>();

                // 根据不同的AppType添加不同的组件
                OuterConfig  outerConfig  = startConfig.GetComponent <OuterConfig>();
                InnerConfig  innerConfig  = startConfig.GetComponent <InnerConfig>();
                ClientConfig clientConfig = startConfig.GetComponent <ClientConfig>();

                switch (startConfig.AppType)
                {
                case AppType.Manager:
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                    Game.Scene.AddComponent <AppManagerComponent>();
                    break;

                case AppType.Realm:
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <ActorManagerComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <RealmGateAddressComponent>();
                    break;

                case AppType.Gate:
                    Game.Scene.AddComponent <PlayerComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <ActorManagerComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <ActorProxyComponent>();
                    Game.Scene.AddComponent <GateSessionKeyComponent>();
                    Game.Scene.AddComponent <DBProxyComponent>();
                    break;

                case AppType.Location:
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <LocationComponent>();
                    break;

                case AppType.Match:
                {
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <MatchComponent>();
                }
                break;

                case AppType.Map:
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <ActorManagerComponent>();
                    Game.Scene.AddComponent <UnitComponent>();
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <ActorProxyComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <ServerFrameComponent>();
                    break;

                case AppType.AllServer:
                    Game.Scene.AddComponent <ActorProxyComponent>();
                    Game.Scene.AddComponent <PlayerComponent>();
                    Game.Scene.AddComponent <UnitComponent>();
                    Game.Scene.AddComponent <DBComponent>();
                    Game.Scene.AddComponent <DBProxyComponent>();
                    Game.Scene.AddComponent <DBCacheComponent>();
                    Game.Scene.AddComponent <LocationComponent>();
                    Game.Scene.AddComponent <ActorMessageDispatherComponent>();
                    Game.Scene.AddComponent <ActorManagerComponent>();
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);
                    Game.Scene.AddComponent <LocationProxyComponent>();
                    Game.Scene.AddComponent <AppManagerComponent>();
                    Game.Scene.AddComponent <RealmGateAddressComponent>();
                    Game.Scene.AddComponent <GateSessionKeyComponent>();
                    Game.Scene.AddComponent <ConfigComponent>();
                    Game.Scene.AddComponent <ServerFrameComponent>();
                    break;

                case AppType.Benchmark:
                    Game.Scene.AddComponent <NetOuterComponent>();
                    Game.Scene.AddComponent <BenchmarkComponent, IPEndPoint>(clientConfig.IPEndPoint);
                    break;

                case AppType.DB:
                    Game.Scene.AddComponent <NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
                    Game.Scene.AddComponent <DBCacheComponent>();
                    Game.Scene.AddComponent <DBComponent>();
                    break;

                default:
                    throw new Exception($"命令行参数没有设置正确的AppType: {startConfig.AppType}");
                }

                while (true)
                {
                    try
                    {
                        Thread.Sleep(1);
                        contex.Update();
                        ObjectEvents.Instance.Update();
                    }
                    catch (Exception e)
                    {
                        Log.Error(e.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e.ToString());
            }
        }
Exemple #47
0
 public static void ParseIntoMongo(VendorExpensesEntity entity)
 {
     var db = new MongoHelper<VendorExpensesEntity>();
     db.InsertData(entity);
 }
        public JsonResult Edit(SceneEditModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            if (model.Name.StartsWith("_"))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to start with _."
                }));
            }

            var mongo = new MongoHelper();

            var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var update1 = Builders <BsonDocument> .Update.Set("Name", model.Name);

            var update2 = Builders <BsonDocument> .Update.Set("TotalPinYin", pinyin.TotalPinYin);

            var update3 = Builders <BsonDocument> .Update.Set("FirstPinYin", pinyin.FirstPinYin);

            var update4 = Builders <BsonDocument> .Update.Set("Thumbnail", model.Image);

            UpdateDefinition <BsonDocument> update5;

            if (string.IsNullOrEmpty(model.Category))
            {
                update5 = Builders <BsonDocument> .Update.Unset("Category");
            }
            else
            {
                update5 = Builders <BsonDocument> .Update.Set("Category", model.Category);
            }

            var update = Builders <BsonDocument> .Update.Combine(update1, update2, update3, update4, update5);

            mongo.UpdateOne(Constant.SceneCollectionName, filter, update);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!"
            }));
        }
 public DatabasePAccount(string connectionString)
 {
     ConnectString = connectionString;
         patientlogin = new MongoHelper<PatientLogin>(ConnectString);
 }
        public JsonResult Save(SceneSaveModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            if (model.Name.StartsWith("_"))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to start with _."
                }));
            }

            // 查询场景信息
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.SceneCollectionName, filter);

            var now = DateTime.Now;

            string collectionName;
            var    version = -1;

            if (doc == null) // 新建场景
            {
                collectionName = "Scene" + now.ToString("yyyyMMddHHmmss");
                version        = 0;
            }
            else // 编辑场景
            {
                collectionName = doc["CollectionName"].ToString();
                version        = doc.Contains("Version") ? int.Parse(doc["Version"].ToString()) : 0;
                version++;
            }

            // 保存或更新场景综合信息
            if (doc == null)
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc = new BsonDocument
                {
                    ["ID"]             = objectId,
                    ["Name"]           = model.Name,
                    ["TotalPinYin"]    = string.Join("", pinyin.TotalPinYin),
                    ["FirstPinYin"]    = string.Join("", pinyin.FirstPinYin),
                    ["CollectionName"] = collectionName,
                    ["Version"]        = version,
                    ["CreateTime"]     = BsonDateTime.Create(now),
                    ["UpdateTime"]     = BsonDateTime.Create(now)
                };
                mongo.InsertOne(Constant.SceneCollectionName, doc);
            }
            else
            {
                var update1 = Builders <BsonDocument> .Update.Set("Version", version);

                var update2 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.SceneCollectionName, filter, update);

                // 将当前场景移入历史表
                var old = mongo.FindAll(collectionName).ToList();

                foreach (var i in old)
                {
                    i[Constant.VersionField] = version - 1;
                }

                if (old.Count > 0)
                {
                    // 移除_id,避免移入历史表时重复
                    for (var i = 0; i < old.Count; i++)
                    {
                        old[i].Remove("_id");
                    }

                    mongo.InsertMany($"{collectionName}{Constant.HistorySuffix}", old);
                }
            }

            // 保存新的场景信息
            var list = JsonHelper.ToObject <JArray>(model.Data);

            var docs = new List <BsonDocument>();

            foreach (var i in list)
            {
                docs.Add(BsonDocument.Parse(i.ToString()));
            }

            mongo.DeleteAll(collectionName);
            mongo.InsertMany(collectionName, docs);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!",
                ID = objectId
            }));
        }
 public CommentService()
 {
     _posts = new MongoHelper<Post>();
 }
Exemple #52
0
        private async ETVoid RunAsync(Session session, C2R_RegisterAndLogin message, Action <R2C_RegisterAndLogin> reply)
        {
            Console.WriteLine(" --> C2R_RegisterAndLoginHandler");

            R2C_RegisterAndLogin response = new R2C_RegisterAndLogin();

            try
            {
                Console.WriteLine("account : " + message.Account + " password : "******"dbProxy : " + dbProxy);

                    //查询账号是否存在  使用LINQ和Lambda表达式根据特定条件来查询
                    List <ComponentWithId> result = await dbProxy.Query <AccountInfo>(_account => _account.Account == message.Account);

                    Console.WriteLine("result : " + result);

                    if (result.Count > 0)
                    {
                        Console.WriteLine("result.Count : " + result.Count);

                        response.Error = ErrorCode.ERR_AccountAlreadyRegister;
                        reply(response);
                        return;
                    }
                    Console.WriteLine("新建账号 : ");

                    //新建账号
                    AccountInfo newAccount = ComponentFactory.CreateWithId <AccountInfo>(IdGenerater.GenerateId());
                    newAccount.Account  = message.Account;
                    newAccount.Password = message.Password;

                    Log.Info($"注册新账号:{MongoHelper.ToJson(newAccount)}");

                    //新建用户信息
                    UserInfo newUser = ComponentFactory.CreateWithId <UserInfo>(newAccount.Id);
                    newUser.Nickname = $"用户{message.Account}";
                    newUser.Gold     = 10000;

                    //保存到数据库
                    await dbProxy.Save(newAccount);

                    await dbProxy.Save(newUser);

                    //释放数据库连接
                    dbProxy.Dispose();
                }

                // 随机分配一个Gate
                StartConfig config = Game.Scene.GetComponent <RealmGateAddressComponent>().GetAddress();
                //Log.Debug($"gate address: {MongoHelper.ToJson(config)}");
                IPEndPoint innerAddress = config.GetComponent <InnerConfig>().IPEndPoint;
                Session    gateSession  = Game.Scene.GetComponent <NetInnerComponent>().Get(innerAddress);

                // 向gate请求一个key,客户端可以拿着这个key连接gate
                G2R_GetLoginKey g2RGetLoginKey = (G2R_GetLoginKey)await gateSession.Call(new R2G_GetLoginKey()
                {
                    Account = message.Account
                });

                string outerAddress = config.GetComponent <OuterConfig>().Address2;

                response.Address = outerAddress;
                response.Key     = g2RGetLoginKey.Key;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
 public MatrixService()
 {
     _db = new MongoHelper<Matrix>();
 }
 static TestNewSnapshotting()
 {
     _database = MongoHelper.InitializeTestDatabase();
 }
 public DatabasePDetails(string connectionString)
 {
     ConnectString = connectionString;
         patientdetails = new MongoHelper<PatientDetails>(ConnectString);
 }
        public JsonResult Add(UserEditModel model)
        {
            if (string.IsNullOrEmpty(model.Username))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Username is not allowed to be empty.",
                }));
            }

            if (string.IsNullOrEmpty(model.Password))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Password is not allowed to be empty.",
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            if (string.IsNullOrEmpty(model.RoleID))
            {
                model.RoleID = "";
            }

            var mongo = new MongoHelper();

            var filter = Builders <BsonDocument> .Filter.Eq("Username", model.Username);

            var count = mongo.Count(Constant.UserCollectionName, filter);

            if (count > 0)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The username is already existed.",
                }));
            }

            var now = DateTime.Now;

            var salt = DateTime.Now.ToString("yyyyMMddHHmmss");

            var doc = new BsonDocument
            {
                ["ID"]         = ObjectId.GenerateNewId(),
                ["Username"]   = model.Username,
                ["Password"]   = MD5Helper.Encrypt(model.Password + salt),
                ["Name"]       = model.Name,
                ["RoleID"]     = model.RoleID,
                ["DeptID"]     = model.DeptID,
                ["Gender"]     = 0,
                ["Phone"]      = "",
                ["Email"]      = "",
                ["QQ"]         = "",
                ["CreateTime"] = now,
                ["UpdateTime"] = now,
                ["Salt"]       = salt,
                ["Status"]     = 0,
            };

            mongo.InsertOne(Constant.UserCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!"
            }));
        }
        public static void LoadMongoProducts()
        {
            var productItemsCollection = new MongoHelper<ProductItem>("Products");
            var products = productItemsCollection.LoadData<ProductItem>().ToList();

            
            //"ProductId" : 1,
            // "ProductName" : "BeerZagorka",
            // "VendorName" : "Zagorka",
            // "Quantity" : "673.00",
            // "Sum" : "609.24" 

            using (var dbConnection = new SQLiteConnection("Data Source=SQLiteSupermarketDB.sqlite;Version=3;"))
            {
                dbConnection.Open();
                //create table
                //string sqlStatement = "create table Products(" +
                //                      "Id integer not null," +
                //                      "ProductId integer," +
                //                      "ProductName nvarchar(50)," +
                //                      "VendorName nvarchar(50)," +
                //                      "Quantity numeric(10,5)," +
                //                      "Sum numeric(10,5)," +
                //                      "primary key (Id)" +
                //                      ");";
                //SQLiteCommand createTable = new SQLiteCommand(sqlStatement, dbConnection);
                //createTable.ExecuteNonQuery();

                //insert data
                StringBuilder sb = new StringBuilder();
                sb.Append("insert into Products(ProductId, ProductName, VendorName, Quantity, Sum) values");

                foreach (var prod in products)
                {
                    sb.AppendFormat("('{0}','{1}','{2}','{3}','{4}'),", prod.ProductId
                        , prod.ProductName, prod.VendorName, prod.Quantity, prod.Sum);
                }
                sb.Length--;
                sb.Append(";");

                //Console.WriteLine(sb.ToString());

                SQLiteCommand populateProducts = new SQLiteCommand(sb.ToString(), dbConnection);
                populateProducts.ExecuteNonQuery();
            }
        }
        public JsonResult Edit(UserEditModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Username))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Username is not allowed to be empty.",
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            if (string.IsNullOrEmpty(model.RoleID))
            {
                model.RoleID = "";
            }

            var mongo = new MongoHelper();

            // 判断是否是系统内置用户
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.UserCollectionName, filter);

            if (doc == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The user is not existed."
                }));
            }

            var userName = doc["Username"].ToString();

            if (userName == "admin")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Modifying system built-in users is not allowed."
                }));
            }

            // 判断用户名是否重复
            var filter1 = Builders <BsonDocument> .Filter.Ne("ID", objectId);

            var filter2 = Builders <BsonDocument> .Filter.Eq("Username", model.Username);

            filter = Builders <BsonDocument> .Filter.And(filter1, filter2);

            var count = mongo.Count(Constant.UserCollectionName, filter);

            if (count > 0)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The username is already existed.",
                }));
            }

            filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var update1 = Builders <BsonDocument> .Update.Set("Username", model.Username);

            var update2 = Builders <BsonDocument> .Update.Set("Name", model.Name);

            var update3 = Builders <BsonDocument> .Update.Set("RoleID", model.RoleID);

            var update4 = Builders <BsonDocument> .Update.Set("DeptID", model.DeptID);

            var update5 = Builders <BsonDocument> .Update.Set("UpdateTime", DateTime.Now);

            var update = Builders <BsonDocument> .Update.Combine(update1, update2, update3, update4, update5);

            mongo.UpdateOne(Constant.UserCollectionName, filter, update);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!"
            }));
        }
 public PostService()
 {
     _posts = new MongoHelper<Post>();
 }
        public JsonResult List(int pageSize = 20, int pageNum = 1, string keyword = "")
        {
            var mongo = new MongoHelper();

            // 获取所有角色
            var roleDocs = mongo.FindAll(Constant.RoleCollectionName).ToList();

            var roles = new List <RoleModel>();

            foreach (var doc in roleDocs)
            {
                roles.Add(new RoleModel
                {
                    ID          = doc["ID"].ToString(),
                    Name        = doc["Name"].ToString(),
                    CreateTime  = doc["CreateTime"].ToLocalTime(),
                    UpdateTime  = doc["UpdateTime"].ToLocalTime(),
                    Description = doc.Contains("Description") ? doc["Description"].ToString() : "",
                    Status      = doc["Status"].ToInt32(),
                });
            }

            // 获取所有机构
            var deptDocs = mongo.FindAll(Constant.DepartmentCollectionName).ToList();

            var depts = new List <DepartmentModel>();

            foreach (var doc in deptDocs)
            {
                depts.Add(new DepartmentModel
                {
                    ID       = doc["ID"].ToString(),
                    ParentID = doc["ParentID"].ToString(),
                    Name     = doc["Name"].ToString(),
                    Status   = doc["Status"].ToInt32()
                });
            }

            // 获取用户
            var filter = Builders <BsonDocument> .Filter.Ne("Status", -1);

            if (!string.IsNullOrEmpty(keyword))
            {
                var filter1 = Builders <BsonDocument> .Filter.Regex("Name", keyword);

                filter = Builders <BsonDocument> .Filter.And(filter, filter1);
            }

            var sort = Builders <BsonDocument> .Sort.Descending("_id");

            var total = mongo.Count(Constant.UserCollectionName, filter);
            var docs  = mongo.FindMany(Constant.UserCollectionName, filter)
                        .Sort(sort)
                        .Skip(pageSize * (pageNum - 1))
                        .Limit(pageSize)
                        .ToList();

            var rows = new List <UserModel>();

            foreach (var doc in docs)
            {
                var roleID   = doc.Contains("RoleID") ? doc["RoleID"].ToString() : "";
                var roleName = "";

                var role = roles.Where(n => n.ID == roleID).FirstOrDefault();
                if (role != null)
                {
                    roleName = role.Name;
                }

                var deptID   = doc.Contains("DeptID") ? doc["DeptID"].ToString() : "";
                var deptName = "";

                var dept = depts.Where(n => n.ID == deptID).FirstOrDefault();
                if (dept != null)
                {
                    deptName = dept.Name;
                }

                rows.Add(new UserModel
                {
                    ID         = doc["ID"].ToString(),
                    Username   = doc["Username"].ToString(),
                    Password   = "",
                    Name       = doc["Name"].ToString(),
                    RoleID     = roleID,
                    RoleName   = roleName,
                    DeptID     = deptID,
                    DeptName   = deptName,
                    Gender     = doc["Gender"].ToInt32(),
                    Phone      = doc["Phone"].ToString(),
                    Email      = doc["Email"].ToString(),
                    QQ         = doc["QQ"].ToString(),
                    CreateTime = doc["CreateTime"].ToLocalTime(),
                    UpdateTime = doc["UpdateTime"].ToLocalTime(),
                    Status     = doc["Status"].ToInt32(),
                });
            }

            return(Json(new
            {
                Code = 200,
                Msg = "Get Successfully!",
                Data = new
                {
                    total,
                    rows,
                },
            }));
        }