Example #1
0
 public Like()
 {
     _id = ObjectId.GenerateNewId().ToString();
 }
 public void TestDownload_1()
 {
     var service = CreateFileStorage();
     var stream  = service.DownLoad <FileEntity>(ObjectId.GenerateNewId());
 }
        private async Task ProcessAutoSessionsAsync(ICollection <EventContext> contexts)
        {
            var identityGroups = contexts
                                 .OrderBy(c => c.Event.Date)
                                 .GroupBy(c => c.Event.GetUserIdentity()?.Identity);

            foreach (var identityGroup in identityGroups)
            {
                string projectId = identityGroup.First().Project.Id;

                // group events into sessions (split by session ends)
                foreach (var session in CreateSessionGroups(identityGroup))
                {
                    bool isNewSession      = false;
                    var  firstSessionEvent = session.First();
                    var  lastSessionEvent  = session.Last();

                    // cancel duplicate start events
                    session.Where(ev => ev.Event.IsSessionStart()).Skip(1).ForEach(ev => ev.IsCancelled = true);
                    var sessionStartEvent = session.FirstOrDefault(ev => ev.Event.IsSessionStart());

                    // sync the session start event with the first session event.
                    if (sessionStartEvent != null)
                    {
                        sessionStartEvent.Event.Date = firstSessionEvent.Event.Date;
                    }

                    // mark the heart beat events as hidden. This will cause new stacks to be marked as hidden, otherwise this value will be reset by the stack.
                    session.Where(ev => ev.Event.IsSessionHeartbeat()).ForEach(ctx => ctx.Event.IsHidden = true);

                    string sessionId = await GetIdentitySessionIdAsync(projectId, identityGroup.Key).AnyContext();

                    // if session end, without any session events, cancel
                    if (String.IsNullOrEmpty(sessionId) && session.Count == 1 && firstSessionEvent.Event.IsSessionEnd())
                    {
                        firstSessionEvent.IsCancelled = true;
                        continue;
                    }

                    // no existing session, create a new one
                    if (String.IsNullOrEmpty(sessionId))
                    {
                        sessionId    = ObjectId.GenerateNewId(firstSessionEvent.Event.Date.DateTime).ToString();
                        isNewSession = true;
                    }

                    session.ForEach(s => s.Event.SetSessionId(sessionId));

                    if (isNewSession)
                    {
                        if (sessionStartEvent != null)
                        {
                            sessionStartEvent.Event.UpdateSessionStart(lastSessionEvent.Event.Date.UtcDateTime, lastSessionEvent.Event.IsSessionEnd());
                            sessionStartEvent.SetProperty("SetSessionStartEventId", true);
                        }
                        else
                        {
                            await CreateSessionStartEventAsync(firstSessionEvent, lastSessionEvent.Event.Date.UtcDateTime, lastSessionEvent.Event.IsSessionEnd()).AnyContext();
                        }

                        if (!lastSessionEvent.IsCancelled && !lastSessionEvent.Event.IsSessionEnd())
                        {
                            await SetIdentitySessionIdAsync(projectId, identityGroup.Key, sessionId).AnyContext();
                        }
                    }
                    else
                    {
                        // we already have a session start, cancel this one
                        if (sessionStartEvent != null)
                        {
                            sessionStartEvent.IsCancelled = true;
                        }

                        await UpdateSessionStartEventAsync(projectId, sessionId, lastSessionEvent.Event.Date.UtcDateTime, lastSessionEvent.Event.IsSessionEnd()).AnyContext();
                    }
                }
            }
        }
Example #4
0
        public List <Book> GetMockData()
        {
            List <Book> books = new List <Book>();

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "For whom the Bell Tolls",
                PublisherName     = "",
                AuthorName        = "Ernest Hemingway",
                Status            = Entities.Enums.StatusEnum.Issued,
                ShelfRackPosition = "Middle Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Book,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC",
            });
            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "Kurukku",
                PublisherName     = "",
                AuthorName        = "Faustina Bama",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Middle Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Novel,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "The Economic Times",
                PublisherName     = "Bennet Collman and Company",
                AuthorName        = "Bennet",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Middle Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Newspaper,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "Times of India",
                PublisherName     = "Bennet Collman and Company",
                AuthorName        = "Bennet",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Middle Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Newspaper,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "The Hindu",
                PublisherName     = "Manoroma",
                AuthorName        = "Manoroma",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Middle Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Newspaper,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "Nature",
                PublisherName     = "Manoroma",
                AuthorName        = "Manoroma",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Middle Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Journal,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "The Science Journal",
                PublisherName     = "Manoroma",
                AuthorName        = "Manoroma",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Middle Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Journal,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "Think and Grow Rich",
                PublisherName     = "Scholastic India",
                AuthorName        = "Jane G. Austin",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Top Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Book,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "Unlimited Power",
                PublisherName     = "Ballantine Books",
                AuthorName        = "Anthony Robbins",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Top Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Book,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });

            books.Add(new Book()
            {
                Id                = ObjectId.GenerateNewId(),
                SchoolId          = ObjectId.Parse("56e45c3af289df1048faced3"),
                Name              = "The Tale of Peter Rabbit",
                PublisherName     = "FingerPrint Publishing",
                AuthorName        = "Mohammed Awzal",
                Status            = Entities.Enums.StatusEnum.Available,
                ShelfRackPosition = "Bottom Position",
                Subject           = "English",
                Category          = Entities.Enums.CategoryEnum.Book,
                ISBNNo            = "ISB No",
                DDC               = "DDC",
                Keywords          = "Keywords",
                Pages             = 1,
                CreatedAt         = DateTime.Now,
                Remarks           = "ABC"
            });
            return(books);
        }
Example #5
0
 public MEResponse()
 {
     Id = ObjectId.GenerateNewId();
 }
        public async Task RemoveWithOutOfSyncIndexAsync()
        {
            var utcNow       = SystemClock.UtcNow;
            var yesterdayLog = await _dailyRepository.AddAsync(LogEventGenerator.Generate(ObjectId.GenerateNewId().ToString(), createdUtc: utcNow.AddDays(-1)), o => o.ImmediateConsistency());

            Assert.NotNull(yesterdayLog?.Id);

            Assert.Equal(1, await _dailyRepository.CountAsync());

            await _dailyRepository.RemoveAsync(yesterdayLog, o => o.ImmediateConsistency());

            Assert.Equal(1, await _dailyRepository.CountAsync());
        }
Example #7
0
        public JsonResult Save(MaterialSaveModel 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.MaterialCollectionName, 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"]    = model.Thumbnail
                };

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

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

                mongo.InsertOne(Constant.MaterialCollectionName, 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.MaterialCollectionName, filter, update);
            }

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!",
                ID = objectId
            }));
        }
Example #8
0
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="userid">用户ID</param>
        /// <param name="key">权限验证</param>
        /// <param name="cart_id">购物车商品集合,格式【sku_id|数量sku_id|数量】</param>
        /// <param name="address_id">地址ID</param>
        /// <param name="pay_name">支付方式【online:在线支付,offline:不在线支付】</param>
        /// <param name="invoice_id">发票ID</param>
        /// <param name="pay_message">店铺留言【53|message,113|message,】</param>
        /// <param name="point">使用积分数量</param>
        /// <param name="coin">使用币数量</param>
        /// <param name="voucher">代金券【undefined|53|undefined,undefined|113|undefined】</param>
        /// <returns></returns>
        public ActionResult GainOrder(int userid = 0, string key = "", string cart_id = "", string address_id = "", string pay_name = "", string invoice_id = "", string pay_message = "", int point = 0, int coin = 0)
        {
            //验证权限

            //校验数据
            //验证购物车商品状态 && 商品数量 && 最小购买数量
            //验证积分


            //解析数据
            var cart_list = SerializeData(cart_id);

            if (cart_list.Count == 0)
            {
                return(Show(new { code = 0, message = "未选择商品!" }));
            }

            //获取数据

            //获取sku列表
            var item_sku_id_list = cart_list.Select(a => a.sku_id).ToList();
            var item_sku_list    = ItemService.item_sku.Where(x => item_sku_id_list.Contains(x.sku_id) && x.sku_status == 1).ToList();

            //获取item列表
            var item_id_list = item_sku_list.Select(a => a.item_id).ToList();
            var item_list    = ItemService.Items.Where(a => item_id_list.Contains(a.item_id)).ToList();

            //合并数据
            var item_full_list = (from sku in item_sku_list
                                  join cart in cart_list on sku.sku_id equals cart.sku_id into r1
                                  from result1 in r1.DefaultIfEmpty()
                                  join item in item_list on sku.item_id equals item.item_id into r2
                                  from result2 in r2.DefaultIfEmpty()
                                  select new
            {
                sku.sku_id,                     //SKU_ID
                sku.item_id,                    //商品ID
                sku.sku_name,                   //SKU名称
                result2.shop_freight_template_id,
                sku.price,                      //价格
                sku.inventory,                  //库存
                sku.volume,                     //体积
                sku.weight,                     //重量
                result1.num,                    //数量
                sku.shop_id,                    //店铺
                result2.item_name,              //商品名称
            }).ToList();


            //获取店铺列表
            var shop_id_list = item_list.Select(a => a.shop_id).Distinct().ToList();
            //店铺列表
            var storelist = ShopService.Shops.Where(x => shop_id_list.Contains(x.shop_id)).ToList();

            ///获取用户收货地址
            var address = AddressService.Address.Where(x => x.ID == address_id).FirstOrDefault();;

            if (address == null)
            {
                return(Show(new { code = 0, message = "请重新选择收货地址!" }));
            }

            ///计算运费
            //根据 item_list中的shop_freight_template_id 获取出运费模板列表
            var shop_freight_template_id_list = item_list.Select(x => x.shop_freight_template_id).ToList();
            var shop_freight_template_list    = AddressService.shop_freight_template.Where(x => shop_freight_template_id_list.Contains(x.shop_freight_template_id)).ToList();

            //根据 shop_freight_template_id_配送城市 获取店铺运费
            var shop_fare_list           = AddressService.shop_fare.Where(x => shop_freight_template_id_list.Contains(x.shop_freight_template_id)).ToList();
            Dictionary <int, double> dic = new Dictionary <int, double>();

            //List<Temp> temp_list = new List<Temp>();
            foreach (var item in item_full_list)
            {
                var freight = 0.00;
                var shop_freight_template = shop_freight_template_list.Where(x => x.shop_freight_template_id == item.shop_freight_template_id).FirstOrDefault();
                if (shop_freight_template != null)
                {
                    var list        = shop_fare_list.Where(x => x.shop_freight_template_id == shop_freight_template.shop_freight_template_id).ToList();
                    var fare_region = new shop_fare();
                    if (list.Count > 0)
                    {
                        fare_region = list.Where(x => x.fare_region.Contains(address.provice_name)).FirstOrDefault();
                        if (fare_region == null)
                        {
                            fare_region = list.Where(x => x.fare_region.Contains("全国")).FirstOrDefault();
                        }
                        if (fare_region != null)
                        {
                            //开始计算
                            //1:自定义运费,2包邮
                            if (shop_freight_template.postage_free == 1)
                            {
                                //计价方式,1件数,2重量,3体积
                                switch (shop_freight_template.valuation_way)
                                {
                                case 1:
                                    //首件价格+续件价格((总数量-首件数量)/续件数量)
                                    freight = fare_region.first_weight_price + fare_region.continue_weight_price * ((item.num - fare_region.first_weight) / fare_region.continue_weight);
                                    break;

                                case 2:
                                    //首重价格+续重价格((总重量-首重)/续重数量)
                                    freight = fare_region.first_weight_price + fare_region.continue_weight_price * ((item.weight * item.num - fare_region.first_weight) / fare_region.continue_weight);
                                    break;

                                case 3:
                                    freight = fare_region.first_weight_price + fare_region.continue_weight_price * ((item.volume * item.num - fare_region.first_weight) / fare_region.continue_weight);
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                    }
                }
                dic.Add(item.item_id, freight);
            }
            //合并数据
            var item_full_list_new = (from item in item_full_list
                                      join d in dic on item.item_id equals d.Key into r
                                      from result in r.DefaultIfEmpty()
                                      select new
            {
                item.sku_id,                       //SKU_ID
                item.sku_name,
                item.item_id,                      //商品ID
                item.shop_freight_template_id,
                item.price,                        //价格
                item.inventory,                    //库存
                item.num,                          //数量
                item.shop_id,                      //店铺
                item.item_name,                    //商品名称
                freight = result.Value,            //运费
            }).ToList();

            lock ("orderlock")
            {
                //获取用户
                var user = UserService.user.Where(a => a.user_id == userid && a.deleted == 0).FirstOrDefault();
                if (user == null)
                {
                    return(Show(new { code = 0, message = "用户不存在!" }));
                }


                //计算优惠  优惠券,满减,折扣,积分

                //计算商品总价,实际支付金额

                #region 生成订单

                //订单
                trade_orders order = new trade_orders
                {
                    _id = ObjectId.GenerateNewId(),
                    //seller_id = ,
                    //shop_id = ,
                    buyer_id = userid,
                    order_id = InitOrderNum(),
                    //配送地址信息
                    name              = address.contact_person,
                    mobile            = address.contact_phone,
                    province_id       = address.provice_code,
                    city_id           = address.city_code,
                    county_id         = address.country_code,
                    detail_address    = address.attach_address,
                    full_address      = address.full_address,
                    shipment_type     = 0,
                    logistics_company = "顺丰快递",
                    logistics_no      = "2012365511254456",
                    logistics_remark  = "",
                    //价格信息
                    parent_order_id   = 0,
                    total_price       = 0.00,
                    freight           = 0.00,
                    integral          = 0,
                    exchange_rate     = 0.01,
                    integral_discount = 0.00,
                    discount_amount   = 0.0,
                    promo_code        = "",
                    total_discount    = 0.00,
                    payment_price     = 0.00,
                    payment_method    = 1,
                    payment_type      = 0,
                    //发票信息
                    invoice         = 1,
                    invoice_title   = "",
                    invoice_content = "",
                    //订单状态
                    evaluate        = 1,
                    seller_evaluate = 1,
                    paid            = 1,
                    locked          = 1,
                    delay           = 1,
                    yn          = 1,
                    state       = 1,
                    refund      = 1,
                    deleted     = 1,
                    create_time = DateTime.Now,
                    update_time = DateTime.Now,
                    //订单备注
                    memo = "",
                };
                //订单详情
                List <trade_order_items> order_item_list = new List <trade_order_items>();
                foreach (var item in item_full_list_new)
                {
                    //创建订单
                    trade_order_items order_item = new trade_order_items
                    {
                        _id      = ObjectId.GenerateNewId(),
                        order_id = order.order_id,
                        //商品信息
                        item_id = item.item_id,
                        shop_freight_template_id = item.shop_freight_template_id,
                        sku_id          = item.sku_id,
                        sku_name        = item.sku_name,
                        num             = item.num,
                        primitive_price = item.price,
                        //优惠信息
                        integral           = 0,//该商品使用的积分,需要计算
                        integral_discount  = 0.00,
                        coupon_discount    = 0.00,
                        promotion_type     = "",
                        promotion_id       = "",
                        promotion_discount = 0.00,
                        pay_price          = 0.00,
                        pay_price_total    = 0.00,
                        //配送方式
                        delivery_type = 1,
                        //订单时间
                        update_time = DateTime.Now,
                        create_time = DateTime.Now,
                    };
                    order_item_list.Add(order_item);
                }
                //保存订单, 同时创建订单记录&积分消费记录&币消费记录&优惠券使用记录&。。。

                //更新用户积分和币
                UserService.user.UpdateOne(a => a._id == user._id, Builders <user> .Update.Set("Point", 1));

                //删除购物车商品

                #endregion
            }
            //根据付款方式判断是否需要拆单,一般是订单支付完成后拆分订单
            var datas = new
            {
                ///订单号
                ///订单金额
                ///订单金额
                ///支付方式
            };
            return(Show(new { code = 1, message = "下单成功", datas, }));
        }
Example #9
0
        public async Task <bool> UpdateTalentProfile(TalentProfileViewModel model, string updaterId)
        {
            try
            {
                if (model.Id != null)
                {
                    var user = (await _userRepository.GetByIdAsync(updaterId));
                    user.LinkedAccounts   = model.LinkedAccounts;
                    user.Summary          = model.Summary;
                    user.Description      = model.Description;
                    user.FirstName        = model.FirstName;
                    user.LastName         = model.LastName;
                    user.Email            = model.Email;
                    user.Phone            = model.Phone;
                    user.Address          = model.Address;
                    user.Nationality      = model.Nationality;
                    user.VisaStatus       = model.VisaStatus;
                    user.VisaExpiryDate   = model.VisaExpiryDate;
                    user.JobSeekingStatus = model.JobSeekingStatus;

                    var newLanguage = new List <UserLanguage>();
                    foreach (var item in model.Languages)
                    {
                        var language = user.Languages.SingleOrDefault(x => x.Id == item.Id);
                        if (language == null)
                        {
                            language = new UserLanguage
                            {
                                Id        = ObjectId.GenerateNewId().ToString(),
                                IsDeleted = false
                            };
                        }
                        UpdateLanguageFromView(item, language);
                        newLanguage.Add(language);
                    }

                    user.Languages = newLanguage;

                    var newSkill = new List <UserSkill>();
                    foreach (var item in model.Skills)
                    {
                        var skill = user.Skills.SingleOrDefault(x => x.Id == item.Id);
                        if (skill == null)
                        {
                            skill = new UserSkill
                            {
                                Id        = ObjectId.GenerateNewId().ToString(),
                                IsDeleted = false
                            };
                        }
                        UpdateSkillFromView(item, skill);
                        newSkill.Add(skill);
                    }
                    user.Skills = newSkill;

                    var newExperience = new List <UserExperience>();
                    foreach (var item in model.Experience)
                    {
                        var experience = user.Experience.SingleOrDefault(x => x.Id == item.Id);
                        if (experience == null)
                        {
                            experience = new UserExperience
                            {
                                Id = ObjectId.GenerateNewId().ToString(),
                            };
                        }
                        UpdateExperienceFromView(item, experience);
                        newExperience.Add(experience);
                    }
                    user.Experience = newExperience;

                    await _userRepository.Update(user);

                    return(true);
                }
                return(false);
            }
            catch (MongoException e)
            {
                return(false);
            }
            //Your code here;
            //throw new NotImplementedException();
        }
Example #10
0
 public static ApplicationUser Create(TelegramIdentity telegramIdentity)
 {
     return(new ApplicationUser(ObjectId.GenerateNewId(), false, telegramIdentity.Id, telegramIdentity.Name, DateTime.Now, DateTime.Now));
 }
Example #11
0
 public Person(string name, int age)
 {
     Id   = ObjectId.GenerateNewId().ToString();
     Name = name;
     Age  = age;
 }
Example #12
0
 public ParentEntity()
 {
     _id = ObjectId.GenerateNewId().ToString();
 }
Example #13
0
        public JsonResult Register(RegisterModel model)
        {
            if (model.Username == null || string.IsNullOrEmpty(model.Username))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Username is not allowed to be empty.",
                }));
            }

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

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

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

            if (model.Name == null || 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("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 defaultRegisterRole = "";

            var config = mongo.FindAll(Constant.ConfigCollectionName).FirstOrDefault();

            if (config != null && config.Contains("DefaultRegisterRole"))
            {
                defaultRegisterRole = config["DefaultRegisterRole"].ToString();
            }
            else
            {
                filter = Builders <BsonDocument> .Filter.Eq("Name", "User");

                var role = mongo.FindOne(Constant.RoleCollectionName, filter);
                if (role == null)
                {
                    return(Json(new
                    {
                        Code = 300,
                        Msg = "The system has not been initialized.",
                    }));
                }

                defaultRegisterRole = role["ID"].ToString();
            }

            // 添加用户
            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"]     = defaultRegisterRole,
                ["Gender"]     = 0,
                ["Phone"]      = "",
                ["Email"]      = "",
                ["QQ"]         = "",
                ["CreateTime"] = now,
                ["UpdateTime"] = now,
                ["Salt"]       = salt,
                ["Status"]     = 0,
            };

            mongo.InsertOne(Constant.UserCollectionName, doc);

            return(Json(new
            {
                Code = 200,
                Msg = "Register successfully!"
            }));
        }
 public appointment()
 {
     this._id = ObjectId.GenerateNewId();
 }
        public async Task CanGetDateAggregationAsync()
        {
            var utcNow       = SystemClock.UtcNow;
            var yesterdayLog = await _dailyRepository.AddAsync(LogEventGenerator.Generate(ObjectId.GenerateNewId().ToString(), createdUtc: utcNow.AddDays(-1)), o => o.ImmediateConsistency());

            Assert.NotNull(yesterdayLog?.Id);

            var result = await _dailyRepository.CountBySearchAsync(null, aggregations : "date:(createdUtc min:createdUtc)");

            Assert.Equal(1, result.Aggregations.Count);
            var dateAgg = result.Aggregations.DateHistogram("date_createdUtc");

            Assert.NotNull(dateAgg);
            Assert.Equal(1, dateAgg.Buckets.Count);
            Assert.Equal(utcNow.AddDays(-1).Date, dateAgg.Buckets.First().Date);
            Assert.Equal(utcNow.AddDays(-1).Floor(TimeSpan.FromMilliseconds(1)), dateAgg.Buckets.First().Aggregations.Min <DateTime>("min_createdUtc").Value.Floor(TimeSpan.FromMilliseconds(1)));

            result = await _dailyRepository.CountBySearchAsync(null, aggregations : "date:(createdUtc~1h^-3h min:createdUtc)");

            Assert.Equal(1, result.Aggregations.Count);
            dateAgg = result.Aggregations.DateHistogram("date_createdUtc");
            Assert.NotNull(dateAgg);
            Assert.Equal(1, dateAgg.Buckets.Count);
        }
 public static string GenerateNewObjectId()
 {
     return(ObjectId.GenerateNewId().ToString());
 }
        public async Task CanGetGeoGridAggregationAsync()
        {
            var utcNow   = SystemClock.UtcNow;
            var employee = await _employeeRepository.AddAsync(EmployeeGenerator.Generate(ObjectId.GenerateNewId().ToString(), createdUtc: utcNow.AddDays(-1)), o => o.ImmediateConsistency());

            Assert.NotNull(employee?.Id);
            await _employeeRepository.AddAsync(EmployeeGenerator.GenerateEmployees(), o => o.ImmediateConsistency());

            var result = await _employeeRepository.CountBySearchAsync(null, aggregations : "geogrid:(location~6 max:age)");

            Assert.Equal(1, result.Aggregations.Count);
            var geoAgg = result.Aggregations.GeoHash("geogrid_location");

            Assert.NotNull(geoAgg);
            Assert.InRange(geoAgg.Buckets.Count, 1, 11);
        }
Example #18
0
        public void UpdateYAnalyticsReports()
        {
            while (true)
            {
                try
                {
                    Helper.DatabaseRepository dbr = new Helper.DatabaseRepository();

                    string            apiKey = AppSettings.googleApiKey;
                    oAuthTokenYoutube ObjoAuthTokenYtubes = new oAuthTokenYoutube(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);
                    oAuthToken        objToken            = new oAuthToken(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);
                    YAnalytics        ObjYAnalytics       = new YAnalytics(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl);

                    List <Domain.Socioboard.Models.YoutubeChannel> lstYtChannels = dbr.Find <Domain.Socioboard.Models.YoutubeChannel>(t => t.IsActive).ToList();
                    long count = 0;
                    Console.WriteLine("---------------- Youtube Analytics Dataservices Started ----------------");
                    foreach (var item in lstYtChannels)
                    {
                        #region count for mongo data
                        MongoRepository mongoreposs = new MongoRepository("YoutubeReportsData");
                        var             result      = mongoreposs.Find <Domain.Socioboard.Models.Mongo.YoutubeReports>(t => t.channelId.Equals(item.YtubeChannelId));
                        var             task        = Task.Run(async() =>
                        {
                            return(await result);
                        });
                        IList <Domain.Socioboard.Models.Mongo.YoutubeReports> lstYanalytics = task.Result;
                        int count90AnalyticsUpdated = lstYanalytics.Count();
                        #endregion

                        try
                        {
                            if (!item.Days90Update || count90AnalyticsUpdated < 90)
                            {
                                if (item.IsActive)
                                {
                                    try
                                    {
                                        ////////code of reports here///////////////////////

                                        DateTime to_Date = DateTime.UtcNow;
                                        string   to_dd   = "0" + Convert.ToString(to_Date.Day);
                                        to_dd = to_dd.Substring(to_dd.Length - 2);
                                        string to_mm = "0" + Convert.ToString(to_Date.Month);
                                        to_mm = to_mm.Substring(to_mm.Length - 2);
                                        string   to_yyyy   = Convert.ToString(to_Date.Year);
                                        DateTime from_Date = DateTime.UtcNow.AddDays(-90);
                                        string   from_dd   = "0" + Convert.ToString(from_Date.Day);
                                        from_dd = from_dd.Substring(from_dd.Length - 2);
                                        string from_mm = "0" + Convert.ToString(from_Date.Month);
                                        from_mm = from_mm.Substring(from_mm.Length - 2);
                                        string from_yyyy = Convert.ToString(from_Date.Year);

                                        string YaFrom_Date = from_yyyy + "-" + from_mm + "-" + from_dd;
                                        string YaTo_Date   = to_yyyy + "-" + to_mm + "-" + to_dd;


                                        MongoRepository mongorepo = new MongoRepository("YoutubeReportsData");


                                        string  AnalyticData  = ObjYAnalytics.Get_YAnalytics_ChannelId(item.YtubeChannelId, item.RefreshToken, YaFrom_Date, YaTo_Date);
                                        JObject JAnalyticData = JObject.Parse(AnalyticData);

                                        JArray dataArray = (JArray)JAnalyticData["rows"];

                                        List <string> datesJdata = new List <string>();
                                        if (dataArray != null)
                                        {
                                            foreach (var rows in dataArray)
                                            {
                                                datesJdata.Add(rows[0].ToString());
                                            }

                                            foreach (var items in dataArray)
                                            {
                                                YoutubeReports _YReports = new YoutubeReports();

                                                string date                       = items[0].ToString();
                                                string channelIdd                 = items[1].ToString();
                                                int    SubscribersGained          = Convert.ToInt32(items[2]);
                                                int    views                      = Convert.ToInt32(items[3]);
                                                int    likes                      = Convert.ToInt32(items[4]);
                                                int    comments                   = Convert.ToInt32(items[5]);
                                                int    shares                     = Convert.ToInt32(items[6]);
                                                int    dislikes                   = Convert.ToInt32(items[7]);
                                                int    subscribersLost            = Convert.ToInt32(items[8]);
                                                double averageViewDuration        = Convert.ToInt64(items[9]);
                                                double estimatedMinutesWatched    = Convert.ToInt64(items[10]);
                                                double annotationClickThroughRate = Convert.ToInt64(items[11]);
                                                double annotationCloseRate        = Convert.ToInt64(items[12]);
                                                string uniqueIdentifier           = item.YtubeChannelId + "_" + date;
                                                double datetime_unix              = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(date)));

                                                _YReports.Id                         = ObjectId.GenerateNewId();
                                                _YReports.date                       = date;
                                                _YReports.channelId                  = channelIdd;
                                                _YReports.SubscribersGained          = SubscribersGained;
                                                _YReports.views                      = views;
                                                _YReports.likes                      = likes;
                                                _YReports.comments                   = comments;
                                                _YReports.dislikes                   = dislikes;
                                                _YReports.subscribersLost            = subscribersLost;
                                                _YReports.averageViewDuration        = averageViewDuration;
                                                _YReports.estimatedMinutesWatched    = estimatedMinutesWatched;
                                                _YReports.annotationClickThroughRate = annotationClickThroughRate;
                                                _YReports.annotationCloseRate        = annotationCloseRate;
                                                _YReports.uniqueIdentifier           = uniqueIdentifier;
                                                _YReports.datetime_unix              = datetime_unix;

                                                mongorepo.Add(_YReports);
                                            }
                                        }
                                        else
                                        {
                                            datesJdata.Add("Null");
                                        }

                                        for (int i = 1; i <= 90; i++)
                                        {
                                            YoutubeReports _YReports    = new YoutubeReports();
                                            DateTime       dateTimeTemp = DateTime.UtcNow.AddDays(-i);

                                            string now_dd = "0" + Convert.ToString(dateTimeTemp.Day);
                                            now_dd = now_dd.Substring(now_dd.Length - 2);
                                            string now_mm = "0" + Convert.ToString(dateTimeTemp.Month);
                                            now_mm = now_mm.Substring(now_mm.Length - 2);
                                            string now_yyyy  = Convert.ToString(dateTimeTemp.Year);
                                            string Ynow_Date = now_yyyy + "-" + now_mm + "-" + now_dd;

                                            if (!(datesJdata.Contains(Ynow_Date)))
                                            {
                                                _YReports.Id                         = ObjectId.GenerateNewId();
                                                _YReports.date                       = Ynow_Date;
                                                _YReports.channelId                  = item.YtubeChannelId;
                                                _YReports.SubscribersGained          = 0;
                                                _YReports.views                      = 0;
                                                _YReports.likes                      = 0;
                                                _YReports.comments                   = 0;
                                                _YReports.dislikes                   = 0;
                                                _YReports.subscribersLost            = 0;
                                                _YReports.averageViewDuration        = 0;
                                                _YReports.estimatedMinutesWatched    = 0;
                                                _YReports.annotationClickThroughRate = 0;
                                                _YReports.annotationCloseRate        = 0;
                                                _YReports.uniqueIdentifier           = item.YtubeChannelId + "_" + Ynow_Date;
                                                _YReports.datetime_unix              = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(Ynow_Date)));

                                                mongorepo.Add(_YReports);
                                            }
                                        }

                                        item.Days90Update      = true;
                                        item.LastReport_Update = DateTime.UtcNow;
                                        dbr.Update <Domain.Socioboard.Models.YoutubeChannel>(item);
                                    }
                                    catch (Exception)
                                    {
                                        Thread.Sleep(600000);
                                    }
                                }
                            }
                            else
                            {
                                if (item.LastReport_Update.AddHours(24) < DateTime.UtcNow)
                                {
                                    //dailyReport Code here//

                                    if (item.IsActive)
                                    {
                                        try
                                        {
                                            //code of reports here//
                                            DateTime to_Date = DateTime.UtcNow;
                                            string   to_dd   = "0" + Convert.ToString(to_Date.Day);
                                            to_dd = to_dd.Substring(to_dd.Length - 2);
                                            string to_mm = "0" + Convert.ToString(to_Date.Month);
                                            to_mm = to_mm.Substring(to_mm.Length - 2);
                                            string   to_yyyy   = Convert.ToString(to_Date.Year);
                                            DateTime from_Date = DateTime.UtcNow.AddDays(-4);
                                            string   from_dd   = "0" + Convert.ToString(from_Date.Day);
                                            from_dd = from_dd.Substring(from_dd.Length - 2);
                                            string from_mm = "0" + Convert.ToString(from_Date.Month);
                                            from_mm = from_mm.Substring(from_mm.Length - 2);
                                            string from_yyyy = Convert.ToString(from_Date.Year);

                                            string YaFrom_Date = from_yyyy + "-" + from_mm + "-" + from_dd;
                                            string YaTo_Date   = to_yyyy + "-" + to_mm + "-" + to_dd;



                                            string  AnalyticData  = ObjYAnalytics.Get_YAnalytics_ChannelId(item.YtubeChannelId, item.RefreshToken, YaFrom_Date, YaTo_Date);
                                            JObject JAnalyticData = JObject.Parse(AnalyticData);

                                            JArray dataArray = (JArray)JAnalyticData["rows"];

                                            List <string> datesJdata = new List <string>();
                                            if (dataArray != null)
                                            {
                                                foreach (var rows in dataArray)
                                                {
                                                    datesJdata.Add(rows[0].ToString());
                                                }

                                                foreach (var items in dataArray)
                                                {
                                                    YoutubeReports _YReports = new YoutubeReports();

                                                    string date                       = items[0].ToString();
                                                    string channelIdd                 = items[1].ToString();
                                                    int    SubscribersGained          = Convert.ToInt32(items[2]);
                                                    int    views                      = Convert.ToInt32(items[3]);
                                                    int    likes                      = Convert.ToInt32(items[4]);
                                                    int    comments                   = Convert.ToInt32(items[5]);
                                                    int    shares                     = Convert.ToInt32(items[6]);
                                                    int    dislikes                   = Convert.ToInt32(items[7]);
                                                    int    subscribersLost            = Convert.ToInt32(items[8]);
                                                    double averageViewDuration        = Convert.ToInt64(items[9]);
                                                    double estimatedMinutesWatched    = Convert.ToInt64(items[10]);
                                                    double annotationClickThroughRate = Convert.ToInt64(items[11]);
                                                    double annotationCloseRate        = Convert.ToInt64(items[12]);
                                                    string uniqueIdentifier           = item.YtubeChannelId + "_" + date;
                                                    double datetime_unix              = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(date)));

                                                    _YReports.Id                         = ObjectId.GenerateNewId();
                                                    _YReports.date                       = date;
                                                    _YReports.channelId                  = channelIdd;
                                                    _YReports.SubscribersGained          = SubscribersGained;
                                                    _YReports.views                      = views;
                                                    _YReports.likes                      = likes;
                                                    _YReports.comments                   = comments;
                                                    _YReports.dislikes                   = dislikes;
                                                    _YReports.subscribersLost            = subscribersLost;
                                                    _YReports.averageViewDuration        = averageViewDuration;
                                                    _YReports.estimatedMinutesWatched    = estimatedMinutesWatched;
                                                    _YReports.annotationClickThroughRate = annotationClickThroughRate;
                                                    _YReports.annotationCloseRate        = annotationCloseRate;
                                                    _YReports.uniqueIdentifier           = uniqueIdentifier;
                                                    _YReports.datetime_unix              = datetime_unix;


                                                    try
                                                    {
                                                        MongoRepository mongoRepotsRepo = new MongoRepository("YoutubeReportsData");
                                                        var             ret             = mongoRepotsRepo.Find <YoutubeReports>(t => t.uniqueIdentifier.Equals(_YReports.uniqueIdentifier));
                                                        var             task_Reports    = Task.Run(async() =>
                                                        {
                                                            return(await ret);
                                                        });
                                                        int count_Reports = task_Reports.Result.Count;
                                                        if (count_Reports < 1)
                                                        {
                                                            try
                                                            {
                                                                mongoRepotsRepo.Add(_YReports);
                                                            }
                                                            catch { }
                                                        }
                                                        else
                                                        {
                                                            try
                                                            {
                                                                FilterDefinition <BsonDocument> filter = new BsonDocument("uniqueIdentifier", _YReports.uniqueIdentifier);
                                                                var update = Builders <BsonDocument> .Update.Set("SubscribersGained", _YReports.SubscribersGained).Set("views", _YReports.views).Set("likes", _YReports.likes).Set("comments", _YReports.comments).Set("dislikes", _YReports.dislikes).Set("subscribersLost", _YReports.subscribersLost).Set("averageViewDuration", _YReports.averageViewDuration).Set("estimatedMinutesWatched", _YReports.estimatedMinutesWatched).Set("annotationClickThroughRate", _YReports.annotationClickThroughRate).Set("annotationCloseRate", _YReports.annotationCloseRate);

                                                                mongoRepotsRepo.Update <YoutubeReports>(update, filter);
                                                            }
                                                            catch { }
                                                        }
                                                    }
                                                    catch { }
                                                }
                                            }
                                            else
                                            {
                                                datesJdata.Add("Null");
                                            }

                                            for (int i = 1; i <= 4; i++)
                                            {
                                                YoutubeReports _YReports    = new YoutubeReports();
                                                DateTime       dateTimeTemp = DateTime.UtcNow.AddDays(-i);

                                                string now_dd = "0" + Convert.ToString(dateTimeTemp.Day);
                                                now_dd = now_dd.Substring(now_dd.Length - 2);
                                                string now_mm = "0" + Convert.ToString(dateTimeTemp.Month);
                                                now_mm = now_mm.Substring(now_mm.Length - 2);
                                                string now_yyyy  = Convert.ToString(dateTimeTemp.Year);
                                                string Ynow_Date = now_yyyy + "-" + now_mm + "-" + now_dd;

                                                if (!(datesJdata.Contains(Ynow_Date)))
                                                {
                                                    _YReports.Id                         = ObjectId.GenerateNewId();
                                                    _YReports.date                       = Ynow_Date;
                                                    _YReports.channelId                  = item.YtubeChannelId;
                                                    _YReports.SubscribersGained          = 0;
                                                    _YReports.views                      = 0;
                                                    _YReports.likes                      = 0;
                                                    _YReports.comments                   = 0;
                                                    _YReports.dislikes                   = 0;
                                                    _YReports.subscribersLost            = 0;
                                                    _YReports.averageViewDuration        = 0;
                                                    _YReports.estimatedMinutesWatched    = 0;
                                                    _YReports.annotationClickThroughRate = 0;
                                                    _YReports.annotationCloseRate        = 0;
                                                    _YReports.uniqueIdentifier           = item.YtubeChannelId + "_" + Ynow_Date;
                                                    _YReports.datetime_unix              = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(Ynow_Date)));

                                                    MongoRepository mongoRepotsRepo = new MongoRepository("YoutubeReportsData");
                                                    mongoRepotsRepo.Add(_YReports);
                                                }
                                            }

                                            item.LastReport_Update = DateTime.UtcNow;
                                            dbr.Update <Domain.Socioboard.Models.YoutubeChannel>(item);
                                        }
                                        catch (Exception)
                                        {
                                            Thread.Sleep(600000);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Thread.Sleep(600000);
                        }


                        long oldcount = count;
                        count++;
                        long newcount      = count;
                        long totalcount    = lstYtChannels.Count();
                        long percentagenew = (newcount * 100) / totalcount;
                        long percentageold = (oldcount * 100) / totalcount;
                        if (percentagenew != percentageold)
                        {
                            Console.WriteLine("---------------- {0}% Completed ----------------", percentagenew);
                        }
                    }
                    Thread.Sleep(600000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("issue in web api calling" + ex.StackTrace);
                    Thread.Sleep(600000);
                }
            }
        }
 public Task RemoveUnsavedDocumentAsync()
 {
     return(_dailyRepository.RemoveAsync(LogEventGenerator.Generate(ObjectId.GenerateNewId().ToString(), createdUtc: SystemClock.UtcNow)));
 }
        public async Task <bool> UpdateTalentProfile(TalentProfileViewModel model, string updaterId)
        {
            try
            {
                if (model.Id != null)
                {
                    User existingTalent = (await _userRepository.GetByIdAsync(model.Id));
                    existingTalent.LinkedAccounts.LinkedIn = model.LinkedAccounts.LinkedIn;
                    existingTalent.LinkedAccounts.Github   = model.LinkedAccounts.Github;
                    existingTalent.Description             = model.Description;
                    existingTalent.Summary          = model.Summary;
                    existingTalent.FirstName        = model.FirstName;
                    existingTalent.MiddleName       = model.MiddleName;
                    existingTalent.LastName         = model.LastName;
                    existingTalent.Email            = model.Email;
                    existingTalent.Phone            = model.Phone;
                    existingTalent.ProfilePhoto     = model.ProfilePhoto;
                    existingTalent.ProfilePhotoUrl  = model.ProfilePhotoUrl;
                    existingTalent.Nationality      = model.Nationality;
                    existingTalent.VisaStatus       = model.VisaStatus;
                    existingTalent.VisaExpiryDate   = model.VisaExpiryDate;
                    existingTalent.JobSeekingStatus = model.JobSeekingStatus;
                    existingTalent.Address.Number   = model.Address.Number;
                    existingTalent.Address.Street   = model.Address.Street;
                    existingTalent.Address.Suburb   = model.Address.Suburb;
                    existingTalent.Address.PostCode = model.Address.PostCode;
                    existingTalent.Address.City     = model.Address.City;
                    existingTalent.Address.Country  = model.Address.Country;
                    existingTalent.UpdatedBy        = updaterId;
                    existingTalent.UpdatedOn        = DateTime.Now;

                    var newlanguage = new List <UserLanguage>();
                    foreach (var item in model.Languages)
                    {
                        UserLanguage language = existingTalent.Languages.SingleOrDefault(x => x.Id == item.Id);
                        if (language == null)
                        {
                            language = new UserLanguage
                            {
                                Id        = ObjectId.GenerateNewId().ToString(),
                                UserId    = model.Id,
                                IsDeleted = false
                            };
                        }
                        UpdateLanguageFromView(item, language);

                        newlanguage.Add(language);
                    }

                    existingTalent.Languages = newlanguage;


                    var newSkills = new List <UserSkill>();
                    foreach (var item in model.Skills)
                    {
                        var skill = existingTalent.Skills.SingleOrDefault(x => x.Id == item.Id);
                        if (skill == null)
                        {
                            skill = new UserSkill
                            {
                                Id        = ObjectId.GenerateNewId().ToString(),
                                UserId    = model.Id,
                                IsDeleted = false
                            };
                        }
                        UpdateSkillFromView(item, skill);
                        newSkills.Add(skill);
                    }
                    existingTalent.Skills = newSkills;

                    var newExperiences = new List <UserExperience>();
                    foreach (var item in model.Experience)
                    {
                        var experience = existingTalent.Experience.SingleOrDefault(x => x.Id == item.Id);
                        if (experience == null)
                        {
                            experience = new UserExperience
                            {
                                Id = ObjectId.GenerateNewId().ToString(),
                            };
                        }
                        UpdateExperienceFromView(item, experience);
                        newExperiences.Add(experience);
                    }
                    existingTalent.Experience = newExperiences;

                    await _userRepository.Update(existingTalent);
                }

                return(true);
            }
            catch (MongoException e)
            {
                return(false);
            }
        }
 protected string GenerateId()
 {
     return(ObjectId.GenerateNewId().ToString());
 }
        public void CreateRule_GivenRuleDataModelWithComposedNodeAndChildNodesOfEachDataType_ReturnsRuleInstance()
        {
            // Arrange
            dynamic content = new ExpandoObject();

            content.Prop1 = 123;
            content.Prop2 = "Sample string";
            content.Prop3 = 500.34m;

            ValueConditionNodeDataModel integerConditionNodeDataModel = new ValueConditionNodeDataModel
            {
                ConditionType   = "SampleIntegerCondition",
                DataType        = DataTypes.Integer,
                LogicalOperator = LogicalOperators.Eval,
                Operand         = 20,
                Operator        = Operators.GreaterThan
            };

            ValueConditionNodeDataModel stringConditionNodeDataModel = new ValueConditionNodeDataModel
            {
                ConditionType   = "SampleStringCondition",
                DataType        = DataTypes.String,
                LogicalOperator = LogicalOperators.Eval,
                Operand         = "TEST",
                Operator        = Operators.Equal
            };

            ValueConditionNodeDataModel decimalConditionNodeDataModel = new ValueConditionNodeDataModel
            {
                ConditionType   = "SampleDecimalCondition",
                DataType        = DataTypes.Decimal,
                LogicalOperator = LogicalOperators.Eval,
                Operand         = 50.3m,
                Operator        = Operators.LesserThanOrEqual
            };

            ValueConditionNodeDataModel booleanConditionNodeDataModel = new ValueConditionNodeDataModel
            {
                ConditionType   = "SampleBooleanCondition",
                DataType        = DataTypes.Boolean,
                LogicalOperator = LogicalOperators.Eval,
                Operand         = true,
                Operator        = Operators.NotEqual
            };

            RuleDataModel ruleDataModel = new RuleDataModel
            {
                Content       = content,
                ContentType   = "ContentTypeSample",
                DateBegin     = new System.DateTime(2020, 1, 1),
                DateEnd       = null,
                Id            = ObjectId.GenerateNewId(),
                Name          = "My rule used for testing purposes",
                Priority      = 1,
                RootCondition = new ComposedConditionNodeDataModel
                {
                    LogicalOperator     = LogicalOperators.And,
                    ChildConditionNodes = new ConditionNodeDataModel[]
                    {
                        integerConditionNodeDataModel,
                        stringConditionNodeDataModel,
                        decimalConditionNodeDataModel,
                        booleanConditionNodeDataModel
                    }
                }
            };

            IContentSerializationProvider <ContentType> contentSerializationProvider = Mock.Of <IContentSerializationProvider <ContentType> >();

            RuleFactory <ContentType, ConditionType> ruleFactory = new RuleFactory <ContentType, ConditionType>(contentSerializationProvider);

            // Act
            Rule <ContentType, ConditionType> rule = ruleFactory.CreateRule(ruleDataModel);

            // Assert
            rule.Should().NotBeNull();
            rule.ContentContainer.Should().NotBeNull()
            .And.BeOfType <SerializedContentContainer <ContentType> >();
            rule.DateBegin.Should().Be(ruleDataModel.DateBegin);
            rule.DateEnd.Should().BeNull();
            rule.Name.Should().Be(ruleDataModel.Name);
            rule.Priority.Should().Be(ruleDataModel.Priority);
            rule.RootCondition.Should().BeOfType <ComposedConditionNode <ConditionType> >();

            ComposedConditionNode <ConditionType> composedConditionNode = rule.RootCondition.As <ComposedConditionNode <ConditionType> >();

            composedConditionNode.LogicalOperator.Should().Be(LogicalOperators.And);
            composedConditionNode.ChildConditionNodes.Should().HaveCount(4);

            IEnumerable <IntegerConditionNode <ConditionType> > integerConditionNodes = composedConditionNode.ChildConditionNodes.OfType <IntegerConditionNode <ConditionType> >();

            integerConditionNodes.Should().HaveCount(1);
            IntegerConditionNode <ConditionType> integerConditionNode = integerConditionNodes.First();

            integerConditionNode.Should().NotBeNull();
            integerConditionNode.ConditionType.Should().Match <ConditionType>(x => x == Enum.Parse <ConditionType>(integerConditionNodeDataModel.ConditionType));
            integerConditionNode.DataType.Should().Be(integerConditionNodeDataModel.DataType);
            integerConditionNode.LogicalOperator.Should().Be(integerConditionNodeDataModel.LogicalOperator);
            integerConditionNode.Operand.Should().Match(x => object.Equals(x, integerConditionNodeDataModel.Operand));
            integerConditionNode.Operator.Should().Be(integerConditionNodeDataModel.Operator);

            IEnumerable <StringConditionNode <ConditionType> > stringConditionNodes = composedConditionNode.ChildConditionNodes.OfType <StringConditionNode <ConditionType> >();

            stringConditionNodes.Should().HaveCount(1);
            StringConditionNode <ConditionType> stringConditionNode = stringConditionNodes.First();

            stringConditionNode.Should().NotBeNull();
            stringConditionNode.ConditionType.Should().Match <ConditionType>(x => x == Enum.Parse <ConditionType>(stringConditionNodeDataModel.ConditionType));
            stringConditionNode.DataType.Should().Be(stringConditionNodeDataModel.DataType);
            stringConditionNode.LogicalOperator.Should().Be(stringConditionNodeDataModel.LogicalOperator);
            stringConditionNode.Operand.Should().Match(x => object.Equals(x, stringConditionNodeDataModel.Operand));
            stringConditionNode.Operator.Should().Be(stringConditionNodeDataModel.Operator);

            IEnumerable <DecimalConditionNode <ConditionType> > decimalConditionNodes = composedConditionNode.ChildConditionNodes.OfType <DecimalConditionNode <ConditionType> >();

            decimalConditionNodes.Should().HaveCount(1);
            DecimalConditionNode <ConditionType> decimalConditionNode = decimalConditionNodes.First();

            decimalConditionNode.Should().NotBeNull();
            decimalConditionNode.ConditionType.Should().Match <ConditionType>(x => x == Enum.Parse <ConditionType>(decimalConditionNodeDataModel.ConditionType));
            decimalConditionNode.DataType.Should().Be(decimalConditionNodeDataModel.DataType);
            decimalConditionNode.LogicalOperator.Should().Be(decimalConditionNodeDataModel.LogicalOperator);
            decimalConditionNode.Operand.Should().Match(x => object.Equals(x, decimalConditionNodeDataModel.Operand));
            decimalConditionNode.Operator.Should().Be(decimalConditionNodeDataModel.Operator);

            IEnumerable <BooleanConditionNode <ConditionType> > booleanConditionNodes = composedConditionNode.ChildConditionNodes.OfType <BooleanConditionNode <ConditionType> >();

            booleanConditionNodes.Should().HaveCount(1);
            BooleanConditionNode <ConditionType> booleanConditionNode = booleanConditionNodes.First();

            booleanConditionNode.Should().NotBeNull();
            booleanConditionNode.ConditionType.Should().Match <ConditionType>(x => x == Enum.Parse <ConditionType>(booleanConditionNodeDataModel.ConditionType));
            booleanConditionNode.DataType.Should().Be(booleanConditionNodeDataModel.DataType);
            booleanConditionNode.LogicalOperator.Should().Be(booleanConditionNodeDataModel.LogicalOperator);
            booleanConditionNode.Operand.Should().Be(Convert.ToBoolean(booleanConditionNodeDataModel.Operand));
            booleanConditionNode.Operator.Should().Be(booleanConditionNodeDataModel.Operator);
        }
Example #23
0
 public MyStandaloneEntity(string name, SharedClass myProperty)
 {
     Id         = ObjectId.GenerateNewId().ToString();
     Name       = name;
     MyProperty = myProperty;
 }
Example #24
0
 public ObjectMongo()
 {
     Id = ObjectId.GenerateNewId();
 }
Example #25
0
 public async Task AddUser(User user)
 {
     user.Id = ObjectId.GenerateNewId().ToString();
     await _collection.InsertOneAsync(user);
 }
Example #26
0
 public IdentityRole()
 {
     Id = ObjectId.GenerateNewId().ToString();
 }
        public JsonResult Get()
        {
            var mongo = new MongoHelper();

            var filter = Builders <BsonDocument> .Filter.Empty;

            // 获取配置
            var config = mongo.FindOne(Constant.ConfigCollectionName, filter);

            if (config == null)
            {
                config = new BsonDocument
                {
                    ["ID"]                  = ObjectId.GenerateNewId(),
                    ["Initialized"]         = false,
                    ["DefaultRegisterRole"] = ""
                };
                mongo.InsertOne(Constant.ConfigCollectionName, config);
            }

            var model = new JObject
            {
                ["ID"] = config["ID"].ToString(),
                ["EnableAuthority"]     = ConfigHelper.EnableAuthority,
                ["Initialized"]         = config.Contains("Initialized") ? config["Initialized"].ToBoolean() : false,
                ["DefaultRegisterRole"] = config.Contains("DefaultRegisterRole") ? config["DefaultRegisterRole"].ToString() : "",
                ["IsLogin"]             = false,
                ["Username"]            = "",
                ["Name"]                 = "",
                ["RoleID"]               = 0,
                ["RoleName"]             = "",
                ["DeptID"]               = 0,
                ["DeptName"]             = "",
                ["OperatingAuthorities"] = new JArray(),
                ["EnableRemoteEdit"]     = ConfigHelper.EnableRemoteEdit,
                ["WebSocketServerPort"]  = ConfigHelper.WebSocketServerPort
            };

            // 获取用户登录信息
            var user = UserHelper.GetCurrentUser();

            if (user != null)
            {
                model["IsLogin"]  = true;
                model["Username"] = user.Username;
                model["Name"]     = user.Name;
                if (user.RoleID != null)
                {
                    model["RoleID"] = user.RoleID;
                }
                if (user.RoleName != null)
                {
                    model["RoleName"] = user.RoleName;
                }
                if (user.DeptID != null)
                {
                    model["DeptID"] = user.DeptID;
                }
                if (user.DeptName != null)
                {
                    model["DeptName"] = user.DeptName;
                }
                model["OperatingAuthorities"] = new JArray(user.OperatingAuthorities);
            }

            return(Json(new
            {
                Code = 200,
                Msg = "Get Successfully!",
                Data = model,
            }));
        }
        public async Task CanGetAggregationsAsync()
        {
            var utcNow       = SystemClock.UtcNow;
            var yesterdayLog = await _dailyRepository.AddAsync(LogEventGenerator.Generate(ObjectId.GenerateNewId().ToString(), createdUtc: utcNow.AddDays(-1)), o => o.ImmediateConsistency());

            Assert.NotNull(yesterdayLog?.Id);

            var result = await _dailyRepository.CountBySearchAsync(null, aggregations : "cardinality:companyId max:createdUtc");

            Assert.Equal(2, result.Aggregations.Count);
            var cardinalityAgg = result.Aggregations.Cardinality("cardinality_companyId");

            Assert.NotNull(cardinalityAgg);
            Assert.Equal(1, cardinalityAgg.Value.GetValueOrDefault());

            var maxAgg = result.Aggregations.Max <DateTime>("max_createdUtc");

            Assert.NotNull(maxAgg);
            Assert.True(yesterdayLog.CreatedUtc.Subtract(maxAgg.Value).TotalSeconds < 1);
        }
        public async Task <bool> UpdateEmployerProfile(EmployerProfileViewModel employer, string updaterId, string role)
        {
            try
            {
                if (employer.Id != null)
                {
                    switch (role)
                    {
                    case "employer":
                        Employer existingEmployer = (await _employerRepository.GetByIdAsync(employer.Id));
                        existingEmployer.CompanyContact  = employer.CompanyContact;
                        existingEmployer.PrimaryContact  = employer.PrimaryContact;
                        existingEmployer.ProfilePhoto    = employer.ProfilePhoto;
                        existingEmployer.ProfilePhotoUrl = employer.ProfilePhotoUrl;
                        existingEmployer.DisplayProfile  = employer.DisplayProfile;
                        existingEmployer.UpdatedBy       = updaterId;
                        existingEmployer.UpdatedOn       = DateTime.Now;

                        var newSkills = new List <UserSkill>();
                        foreach (var item in employer.Skills)
                        {
                            var skill = existingEmployer.Skills.SingleOrDefault(x => x.Id == item.Id);
                            if (skill == null)
                            {
                                skill = new UserSkill
                                {
                                    Id        = ObjectId.GenerateNewId().ToString(),
                                    IsDeleted = false
                                };
                            }
                            UpdateSkillFromView(item, skill);
                            newSkills.Add(skill);
                        }
                        existingEmployer.Skills = newSkills;

                        await _employerRepository.Update(existingEmployer);

                        break;

                    case "recruiter":
                        Recruiter existingRecruiter = (await _recruiterRepository.GetByIdAsync(employer.Id));
                        existingRecruiter.CompanyContact  = employer.CompanyContact;
                        existingRecruiter.PrimaryContact  = employer.PrimaryContact;
                        existingRecruiter.ProfilePhoto    = employer.ProfilePhoto;
                        existingRecruiter.ProfilePhotoUrl = employer.ProfilePhotoUrl;
                        existingRecruiter.DisplayProfile  = employer.DisplayProfile;
                        existingRecruiter.UpdatedBy       = updaterId;
                        existingRecruiter.UpdatedOn       = DateTime.Now;

                        var newRSkills = new List <UserSkill>();
                        foreach (var item in employer.Skills)
                        {
                            var skill = existingRecruiter.Skills.SingleOrDefault(x => x.Id == item.Id);
                            if (skill == null)
                            {
                                skill = new UserSkill
                                {
                                    Id        = ObjectId.GenerateNewId().ToString(),
                                    IsDeleted = false
                                };
                            }
                            UpdateSkillFromView(item, skill);
                            newRSkills.Add(skill);
                        }
                        existingRecruiter.Skills = newRSkills;
                        await _recruiterRepository.Update(existingRecruiter);

                        break;
                    }
                    return(true);
                }
                return(false);
            }
            catch (MongoException e)
            {
                return(false);
            }
        }
 /// <summary>
 /// Internal constructor
 /// </summary>
 protected Entity()
 {
     Id = ObjectId.GenerateNewId().ToString();
 }