public void StoreExceptionTest() { var dataConnection = MockRepository.GenerateStub<IDataConnection>(); var dateHelper = new DateHelper(); var tokenStorage = new TokenStorage(dataConnection, dateHelper); var userId = 1; var userIdSalt = new byte[24]; var tokenSalt = new byte[24]; var encryptedGuid = "encrypted-guid"; var encryptedUserId = "dummy-encrypted-user-id"; var issuedAt = new DateTime(2014, 11, 21, 14, 54, 33); var hashedToken = new PasswordHash.HashInfo { Hash = encryptedGuid, Iterations = 1000, Method = "sha1", Salt = Convert.ToBase64String(tokenSalt) }; // stub fake calls dataConnection.Stub(x => x.Execute(null, null)).Throw(new Exception()).IgnoreArguments(); Assert.Throws<Exception>(() => tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt)); }
public void NowTest() { var dateHelper = new DateHelper(); var orgNow = DateTime.Now; var newNow = dateHelper.Now; Assert.IsTrue(orgNow <= newNow); }
public void IsWithinTimeOutLimitTest() { Settings.TimeOutInMinutes = 30; var expired = DateTime.Now.AddMinutes(-60); var valid = DateTime.Now.AddMinutes(-15); var dateHelper = new DateHelper(); Assert.IsFalse(dateHelper.IsWithinTimeOutLimit(expired)); Assert.IsTrue(dateHelper.IsWithinTimeOutLimit(valid)); }
public void StoreAndRetrieveTokenTest() { TestHelper.DeleteTestData(); TestHelper.InsertTestData(); var dataConnection = new DataConnection(); var dateHelper = new DateHelper(); var tokenStorage = new TokenStorage(dataConnection, dateHelper); var userId = 1; var userIdSalt = new byte[24]; var tokenSalt = new byte[24]; var encryptedGuid = "encrypted-guid"; var encryptedUserId = "dummy-encrypted-user-id"; var issuedAt = new DateTime(2014, 11, 21, 14, 54, 33); var hashedToken = new PasswordHash.HashInfo { Hash = encryptedGuid, Iterations = 1000, Method = "sha1", Salt = Convert.ToBase64String(tokenSalt) }; Assert.IsTrue(tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt)); PasswordHash.HashInfo hashedTokenResult; string encryptedUserIdResult; byte[] userIdSaltResult; DateTime issuedAtResult; DateTime refreshedResult; var retrieveTokenSuccess = tokenStorage.RetrieveToken(encryptedUserId, out hashedTokenResult, out encryptedUserIdResult, out userIdSaltResult, out issuedAtResult, out refreshedResult); Assert.IsTrue(retrieveTokenSuccess); Assert.AreEqual(hashedToken.Salt, hashedTokenResult.Salt); Assert.AreEqual(hashedToken.Hash, hashedTokenResult.Hash); Assert.AreEqual(hashedToken.Method, hashedTokenResult.Method); Assert.AreEqual(encryptedUserId, encryptedUserIdResult); Assert.AreEqual(userIdSalt, userIdSaltResult); Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), issuedAtResult); Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), refreshedResult); }
public void RetrieveTokenExceptionTest() { // declare mocks var dataConnection = MockRepository.GenerateStub<IDataConnection>(); // declare objects var dateHelper = new DateHelper(); var encryptedUserId = "dummy-encrypted-user-id"; var tokenStorage = new TokenStorage(dataConnection, dateHelper); // stub fake calls dataConnection.Stub(x => x.Query<TokenStorage.TokenStorageDb>(null, null)).Throw(new Exception()).IgnoreArguments(); PasswordHash.HashInfo hashedTokenResult; string encryptedUserIdResult; byte[] userIdSaltResult; DateTime issuedAtResult; DateTime refreshedResult; var result = tokenStorage.RetrieveToken(encryptedUserId, out hashedTokenResult, out encryptedUserIdResult, out userIdSaltResult, out issuedAtResult, out refreshedResult); Assert.IsFalse(result); }
public PlainTextMessageCodec() { _mBufferHelper = new BufferHelper(); _mDateHelper = new DateHelper(); }
/// <summary> /// Resolve dependencies for Dynamite Helpers /// </summary> protected void ResolveDependencies() { this._listHelper = AppContainer.Current.Resolve<ListHelper>(); this._dateHelper = AppContainer.Current.Resolve<DateHelper>(); }
public DragonUnitModel() { this.Name = NameHelper.GenerateName(RandomHelper.GetRandomNumber(4, 20)); this.Created_at = DateHelper.DateTimeToUnixTimestamp(DateTime.Now); this.Lives = RandomHelper.GetRandomNumber(80, 100); }
private List <Guid> GetTodayLeadIds() { return(_context.LeadStates .Where(w => w.StateId == nameof(EnumState.SL1) && DateHelper.ConvertFromUtc(w.ActionTimestamp).Date == DateHelper.ConvertFromUtc(DateHelper.Now).Date) .Select(s => s.LeadId).ToList()); }
// 重写异步处理程序 protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) { var httpContext = _accessor.HttpContext; // 获取系统中所有的角色和菜单的关系集合 if (!requirement.Permissions.Any()) { //var data = await _roleModulePermissionServices.RoleModuleMaps(); var list = new List <PermissionItem>(); // ids4和jwt切换 // ids4 if (Permissions.IsUseIds4) { //list = (from item in data // where item.IsDeleted == false // orderby item.Id // select new PermissionItem // { // Url = item.Module?.LinkUrl, // Role = item.Role?.Id.ObjToString(), // }).ToList(); } // jwt else { //var data = await _roleModulePermissionServices.RoleModuleMaps(); //list = (from item in data // where item.IsDeleted == false // orderby item.Id // select new PermissionItem // { // Url = item.Module?.LinkUrl, // Role = item.Role?.Name.ObjToString(), // }).ToList(); requirement.Permissions = list; } requirement.Permissions = list; } if (httpContext != null) { var questUrl = httpContext.Request.Path.Value.ToLower(); // 整体结构类似认证中间件UseAuthentication的逻辑,具体查看开源地址 // https://github.com/dotnet/aspnetcore/blob/master/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs httpContext.Features.Set <IAuthenticationFeature>(new AuthenticationFeature { OriginalPath = httpContext.Request.Path, OriginalPathBase = httpContext.Request.PathBase }); // Give any IAuthenticationRequestHandler schemes a chance to handle the request // 主要作用是: 判断当前是否需要进行远程验证,如果是就进行远程验证 var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>(); foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync()) { if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync()) { context.Fail(); return; } } //判断请求是否拥有凭据,即有没有登录 var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync(); if (defaultAuthenticate != null) { var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name); // 是否开启测试环境 var isTestCurrent = Appsettings.App(new string[] { "AppSettings", "UseLoadTest" }).ToBoolReq(); //result?.Principal不为空即登录成功 if (result?.Principal != null || isTestCurrent) { if (!isTestCurrent) { httpContext.User = result.Principal; } // 获取当前用户的角色信息 var currentUserRoles = new List <string>(); // ids4和jwt切换 // ids4 if (Permissions.IsUseIds4) { currentUserRoles = (from item in httpContext.User.Claims where item.Type == "role" select item.Value).ToList(); } else { // jwt currentUserRoles = (from item in httpContext.User.Claims where item.Type == requirement.ClaimType select item.Value).ToList(); } var isMatchRole = false; var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role)); foreach (var item in permisssionRoles) { try { // if (Regex.Match(questUrl, item.Url?.ToString().ToLower())?.Value == questUrl) // { isMatchRole = true; break; // } } catch (Exception) { // ignored } } //验证权限 if (currentUserRoles.Count <= 0 || !isMatchRole) { context.Fail(); return; } var isExp = false; // ids4和jwt切换 // ids4 if (Permissions.IsUseIds4) { isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp")?.Value) != null && DateHelper.StampToDateTime(httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp")?.Value) >= DateTime.Now; } else { // jwt isExp = (httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now; } if (isExp) { context.Succeed(requirement); } else { context.Fail(); return; } return; } } //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败 if (!(questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType))) { context.Fail(); return; } } //context.Succeed(requirement); }
protected LeadAssignmentVM GetLeadAssignmentViewModel(LeadAssignment item) { var itemVM = new LeadAssignmentVM(); itemVM.Id = item.Id; itemVM.LeadId = item.LeadId; if (item.Lead != null) { itemVM.LeadDetails = item.Lead.Details; if (item.Lead.LeadType != null) { itemVM.LeadTypeName = item.Lead.LeadType.Name; itemVM.LeadTypeImage = ImageHelper.PATH_CLIENT_LEAD_TYPE + item.Lead.LeadType.Image; } if (item.Lead.Customer != null) { itemVM.CustomerId = item.Lead.Customer.Id; itemVM.CustomerUnique = String.Format("{0} ({1})", item.Lead.Customer.ContactName, item.Lead.Customer.EMail); itemVM.CustomerName = item.Lead.Customer.ContactName; itemVM.CustomerBusinessName = item.Lead.Customer.BusinessName; itemVM.CustomerEMail = item.Lead.Customer.EMail; itemVM.CustomerContactNumber = item.Lead.Customer.ContactNumber; itemVM.CustomerStreetAddress = item.Lead.Customer.Address.StreetAddress; itemVM.CustomerSuburb = item.Lead.Customer.Address.Suburb; itemVM.CustomerState = item.Lead.Customer.Address.State; itemVM.CustomerPostCode = item.Lead.Customer.Address.PostCode; itemVM.CustomerAddress = AddressHelper.MergeAddress(itemVM.CustomerStreetAddress, itemVM.CustomerSuburb, itemVM.CustomerState, itemVM.CustomerPostCode); itemVM.CustomerDetails = String.Format("Business: <b>{0}</b><br>Tel: <b>{1}</b><br>Address: <b>{2}</b>", itemVM.CustomerBusinessName, itemVM.CustomerContactNumber, itemVM.CustomerAddress); } } itemVM.PartnerId = item.PartnerBranch.Partner.Id; itemVM.PartnerName = item.PartnerBranch.Partner.Name; itemVM.PartnerLogo = ImageHelper.PATH_CLIENT_PARTNER + item.PartnerBranch.Partner.Logo; itemVM.PartnerBranchId = item.PartnerBranch.Id; itemVM.PartnerBranchStreetAddress = item.PartnerBranch.Address.StreetAddress; itemVM.PartnerBranchSuburb = item.PartnerBranch.Address.Suburb; itemVM.PartnerBranchState = item.PartnerBranch.Address.State; itemVM.PartnerBranchPostCode = item.PartnerBranch.Address.PostCode; itemVM.PartnerBranchAddress = AddressHelper.MergeAddress(itemVM.PartnerBranchStreetAddress, itemVM.PartnerBranchSuburb, itemVM.PartnerBranchState, itemVM.PartnerBranchPostCode); // Current status var currentStatus = item.LeadAssignmentStates.Where(w => w.StateId != nameof(EnumState.S0)).OrderByDescending(o => o.ActionTimestamp).FirstOrDefault(); itemVM.StatusId = currentStatus.State.Id; itemVM.StatusName = currentStatus.State.Name; itemVM.StatusTag = StatusHelper.GetHtmlBadge(currentStatus.State.Id, currentStatus.State.Name); itemVM.RatingTag = RatingHelper.GetHtmlRatingTag(item.Comment, item.CommentedBy, item.CommentedOn); if (string.IsNullOrEmpty(_userRoleName)) { _userRoleName = _accountManager.GetRoleAsync(_accountManager.GetUserAsync(User.Identity.Name).Result).Result; } // Actions of current status var actions = currentStatus.State.StateActions.Where(w => this.IsActionAllowed(w.Action.Id, _userRoleName)).Select(s => new ActionLeadAssignmentVM { Id = s.ActionId, LeadId = itemVM.LeadId, PartnerBranchId = itemVM.PartnerBranchId, LeadAssignmentId = itemVM.Id, CustomerEmail = itemVM.CustomerEMail, PartnerEmails = _salesRepo.GetByPartner(itemVM.PartnerId).Select(person => person.EMail).ToList(), ControllerName = s.Action.ControllerName, ActionName = s.Action.ActionName, ActionTarget = s.Action.ActionTarget, RequestType = s.Action.RequestType, DisplayName = s.Action.DisplayName, Icon = s.Action.Icon, NextStateId = s.Action.NextStateId, Rating = new Rating() { Rate = item.Rate, Comment = item.Comment ?? string.Empty, CommentedOn = item.CommentedOn, CommentedBy = item.CommentedBy } }).ToList(); itemVM.Actions = actions; // CreatedWhen var firstSssignedOn = item.LeadAssignmentStates.OrderBy(o => o.ActionTimestamp).FirstOrDefault(); itemVM.AssignedOn = DateHelper.ConvertFromUtc(firstSssignedOn.ActionTimestamp).Date; // History var histories = item.LeadAssignmentStates .OrderByDescending(o => o.ActionTimestamp) //.Where(w => w.StateId != currentStatus.StateId) // *show all .Select(s => HistoryHelper.GetHtmlHistoryLine(DateHelper.ConvertFromUtc(s.ActionTimestamp), s.Action.ToLower(), s.Actor)); itemVM.History = HistoryHelper.GetHtmlHistoryTag(histories.ToList()); return(itemVM); }
public HeroUnitModel(string name) { this.Name = name; this.Created_at = DateHelper.DateTimeToUnixTimestamp(DateTime.Now); this.Weapon = RandomHelper.GetRandomNumber(1, 6); }
public void GetHistory_ContainsRepost_Error46() { Url = "https://api.vk.com/method/messages.getHistory"; Json = @"{ 'response':{ 'count':1940, 'items':[ { 'id':1234, 'body':'', 'user_id':4321, 'from_id':, 'date':1414993364, 'read_state':1, 'out':1, 'attachments':[ { 'type':'wall', 'wall':{ 'id':6194, 'from_id':-1267, 'to_id':-7654, 'date':1414992610, 'post_type':'post', 'text':'', 'attachments':[ { 'type':'photo', 'photo':{ 'id':76352, 'album_id':-7, 'owner_id':-9816, 'user_id':198, 'photo_75':'https://pp.vk.me/...b/uKU7pKtHLe0.jpg', 'photo_130':'https://pp.vk.me/...c/WZJpkmJWBto.jpg', 'photo_604':'https://pp.vk.me/...d/Kp44mAbDqSk.jpg', 'width':604, 'height':402, 'text':'', 'date':1414992613, 'post_id':928719, 'access_key':'test_access_key' } } ], 'post_source':{ 'type':'api' }, 'comments':{ 'count':3, 'can_post':0 }, 'likes':{ 'count':9191, 'user_likes':1, 'can_like':0, 'can_publish':1 }, 'reposts':{ 'count':953, 'user_reposted':0 } } } ] } ] } }" ; var msgs = Cat.GetHistory(new MessagesGetHistoryParams { UserId = 7712 }); // assertions Assert.That(msgs.TotalCount, Is.EqualTo(1940)); var msg = msgs.Messages.FirstOrDefault(); Assert.That(msg, Is.Not.Null); Assert.That(msg.Attachments.Count, Is.EqualTo(1)); var wall = msg.Attachments[0].Instance as Model.Wall; Assert.That(wall, Is.Not.Null); Assert.That(wall.Id, Is.EqualTo(6194)); Assert.That(wall.FromId, Is.EqualTo(-1267)); Assert.That(wall.Date, Is.EqualTo(DateHelper.TimeStampToDateTime(1414992610))); Assert.That(wall.PostType, Is.EqualTo(PostType.Post)); Assert.That(wall.Text, Is.EqualTo(string.Empty)); Assert.That(wall.Comments.Count, Is.EqualTo(3)); Assert.That(wall.Comments.CanPost, Is.False); Assert.That(wall.Likes.Count, Is.EqualTo(9191)); Assert.That(wall.Likes.UserLikes, Is.True); Assert.That(wall.Likes.CanLike, Is.False); Assert.That(wall.Likes.CanPublish, Is.EqualTo(true)); Assert.That(wall.Reposts.Count, Is.EqualTo(953)); Assert.That(wall.Reposts.UserReposted, Is.False); Assert.That(wall.Attachments.Count, Is.EqualTo(1)); var photo = wall.Attachments[0].Instance as Photo; Assert.That(photo, Is.Not.Null); }
public User Verify(string value, string type, int code, bool isEmail) { if (string.IsNullOrWhiteSpace(value)) { throw new AppException("Email or Phone is required"); } if (string.IsNullOrWhiteSpace(type)) { throw new AppException("Verification Type is required"); } var vcode = _context.VerificationCodes.FirstOrDefault(p => p.FieldType == type && p.FieldValue == value && p.Code == code && DateTime.Compare(p.ExpireDate, DateHelper.GetDate()) >= 0); if (vcode == null) { return(null); } var tempUser = isEmail ? _context.TempUsers.OrderByDescending(x => x.Id).FirstOrDefault(x => x.Email == value) : _context.TempUsers.OrderByDescending(x => x.Id).FirstOrDefault(x => x.Phone == value); var user = _mapper.Map <User>(tempUser); if (tempUser.ReferrerCode != 0) { var referrar = _context.Users.FirstOrDefault(x => x.ReferralCode == tempUser.ReferrerCode); if (referrar != null) { referrar.Balance += 10000; _context.Users.Update(referrar); } } _context.Users.Add(user); _context.SaveChanges(); return(user); }
public void VerifyTokenExistenceTest() { TestHelper.DeleteTestData(); TestHelper.InsertTestData(); //VerifyTokenExistence var dataConnection = new DataConnection(); var dateHelper = new DateHelper(); var tokenStorage = new TokenStorage(dataConnection, dateHelper); var userId = 101; var userIdSalt = new byte[24]; var tokenSalt = new byte[24]; var encryptedGuid = "encrypted-guid"; var encryptedUserId = "dummy-encrypted-user-id"; var issuedAt = new DateTime(2014, 11, 21, 14, 54, 33); var hashedToken = new PasswordHash.HashInfo { Hash = encryptedGuid, Iterations = 1000, Method = "sha1", Salt = Convert.ToBase64String(tokenSalt) }; Assert.IsTrue(tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt)); string hashedTokenResult; DateTime issuedAtResult; DateTime refreshedResult; var verifyTokenSuccess = tokenStorage.VerifyTokenExistence(userId, out hashedTokenResult, out issuedAtResult, out refreshedResult); Assert.IsTrue(verifyTokenSuccess); Assert.AreEqual(encryptedGuid, hashedTokenResult); Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), issuedAtResult); Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), refreshedResult); verifyTokenSuccess = tokenStorage.VerifyTokenExistence(102, out hashedTokenResult, out issuedAtResult, out refreshedResult); Assert.IsFalse(verifyTokenSuccess); Assert.AreEqual(null, hashedTokenResult); Assert.AreEqual(new DateTime(), issuedAtResult); Assert.AreEqual(new DateTime(), refreshedResult); }
public void RefreshTokenTest() { var dataConnection = new DataConnection(); var dateHelper = new DateHelper(); var tokenStorage = new TokenStorage(dataConnection, dateHelper); var userId = 101; var userIdSalt = new byte[24]; var tokenSalt = new byte[24]; var encryptedGuid = "encrypted-guid"; var encryptedUserId = "dummy-encrypted-user-id"; var issuedAt = new DateTime(2014, 11, 21, 14, 54, 33); var hashedToken = new PasswordHash.HashInfo { Hash = encryptedGuid, Iterations = 1000, Method = "sha1", Salt = Convert.ToBase64String(tokenSalt) }; Assert.IsTrue(tokenStorage.StoreToken(userId, hashedToken, encryptedUserId, userIdSalt, issuedAt)); Assert.IsTrue(tokenStorage.RefreshToken(userId, hashedToken.Hash, new DateTime(2014, 11, 21, 15, 55, 22))); PasswordHash.HashInfo hashedTokenResult; string encryptedUserIdResult; byte[] userIdSaltResult; DateTime issuedAtResult; DateTime refreshedResult; var retrieveTokenSuccess = tokenStorage.RetrieveToken(encryptedUserId, out hashedTokenResult, out encryptedUserIdResult, out userIdSaltResult, out issuedAtResult, out refreshedResult); Assert.IsTrue(retrieveTokenSuccess); Assert.AreEqual(hashedToken.Salt, hashedTokenResult.Salt); Assert.AreEqual(hashedToken.Hash, hashedTokenResult.Hash); Assert.AreEqual(hashedToken.Method, hashedTokenResult.Method); Assert.AreEqual(encryptedUserId, encryptedUserIdResult); Assert.AreEqual(userIdSalt, userIdSaltResult); Assert.AreEqual(new DateTime(2014, 11, 21, 14, 54, 33), issuedAtResult); Assert.AreEqual(new DateTime(2014, 11, 21, 15, 55, 22), refreshedResult); // check if using a wrong id/encryptid fails (it should fail) Assert.IsFalse(tokenStorage.RefreshToken(102, hashedToken.Hash, new DateTime(2014, 11, 21, 15, 55, 22))); Assert.IsFalse(tokenStorage.RefreshToken(userId, hashedToken.Hash + 'a', new DateTime(2014, 11, 21, 15, 55, 22))); }
//private IEnumerable<DashboardLeadVM> GetDashboardLeadVMs(DateTime dateStart, DateTime dateEnd) public IEnumerable <DashboardLeadVM> GetDashboardLeadVMs(DateTime dateStart, DateTime dateEnd) { var statusNewLeadVMs = _context.LeadStates .Where(w => w.StateId == nameof(EnumState.SL1) && //((w.ActionTimestamp.Date >= DateHelper.ConvertToUtc(dateStart).Date) //&& (w.ActionTimestamp.Date <= DateHelper.ConvertToUtc(dateEnd).Date)) ((w.ActionTimestamp.Date >= dateStart.Date) && (w.ActionTimestamp.Date <= dateEnd.Date)) ) .Include(i => i.Lead).ThenInclude(i => i.LeadType) .Select(s => new DashboardLeadVM() { LeadId = s.LeadId, LeadTypeId = s.Lead.LeadTypeId, LeadTypeName = s.Lead.LeadType.Name, LeadStateType = s.StateId, ActionTimestamp = s.ActionTimestamp, CreatedOn = DateHelper.ConvertFromUtc(s.ActionTimestamp).Date }); List <DashboardLeadVM> adjustedStatusLeadVMs = new List <DashboardLeadVM>(); foreach (var leadVM in statusNewLeadVMs) { var assignments = _context.LeadAssignments .Where(w => w.LeadId == leadVM.LeadId) .Include(i => i.LeadAssignmentStates); string leadStateType = nameof(EnumState.SL1); DateTime actionTimestamp = leadVM.ActionTimestamp; foreach (var assignment in assignments) { var assignmentCurrentStatus = assignment.LeadAssignmentStates.OrderByDescending(o => o.ActionTimestamp).First(); if (assignmentCurrentStatus.StateId == nameof(EnumState.SLA2) || assignmentCurrentStatus.StateId == nameof(EnumState.SLA4) || assignmentCurrentStatus.StateId == nameof(EnumState.SLA5)) { // If any of assignments is accepted, the lead is supposed to be accepted. leadStateType = nameof(EnumState.SLA2); actionTimestamp = DateHelper.ConvertFromUtc(assignmentCurrentStatus.ActionTimestamp); break; } else if (assignmentCurrentStatus.StateId == nameof(EnumState.SLA3)) { leadStateType = nameof(EnumState.SLA3); actionTimestamp = DateHelper.ConvertFromUtc(assignmentCurrentStatus.ActionTimestamp); } } adjustedStatusLeadVMs.Add(new DashboardLeadVM() { LeadId = leadVM.LeadId, LeadTypeId = leadVM.LeadTypeId, LeadTypeName = leadVM.LeadTypeName, CreatedOn = leadVM.CreatedOn, LeadStateType = leadStateType, ActionTimestamp = actionTimestamp }); } /* * var leadIds = statusNewLeadVMs.Select(s => s.LeadId).ToList(); * * var leadAssignmentIds = _context.LeadAssignments * .Where(w => leadIds.Contains(w.LeadId)) * .Select(s => s.Id).ToList(); * * var currentAssignmentsStatus = _context.LeadAssignmentStates * .Where(w => leadAssignmentIds.Contains(w.LeadAssignmentId)) * .Include(i => i.LeadAssignment) * .GroupBy(g => new { g.LeadAssignment.LeadId, g.LeadAssignmentId }) * .Select(s => new * { * LeadId = s.Key.LeadId * , LeadAssignmentId = s.Key.LeadAssignmentId * , CurrentTimestamp = s.Max(max => max.ActionTimestamp) * }); * * var leadAssignments = _context.LeadAssignmentStates * .Include(i => i.LeadAssignment) * .Where(w => currentAssignmentsStatus.Contains( * new { LeadId = w.LeadAssignment.LeadId, LeadAssignmentId = w.LeadAssignmentId, CurrentTimestamp = w.ActionTimestamp } * )); */ return(adjustedStatusLeadVMs); }
static Cms() { Version = CmsVariables.VERSION; PyhicPath = AppDomain.CurrentDomain.BaseDirectory; //获取编译生成的时间 //DateTime builtDate = new DateTime(2000, 1, 1).AddDays(ver.Build).AddSeconds(ver.Revision*2); string filePath = typeof(Cms).Assembly.Location; if (String.IsNullOrEmpty(filePath)) { filePath = PyhicPath + CmsVariables.FRAMEWORK_ASSEMBLY_PATH + "jrcms.dll"; } DateTime builtDate = File.GetLastWriteTime(filePath); BuiltTime = DateHelper.ToUnix(builtDate); //获取平台 Int32 platFormId = (Int32)Environment.OSVersion.Platform; if (platFormId == 4 || platFormId == 6 || platFormId == 128) { RunAtMono = true; } //判断是否已经安装 FileInfo insLockFile = new FileInfo(String.Format("{0}/config/install.lock", Cms.PyhicPath)); Installed = insLockFile.Exists; //初始化 Plugins = new CmsPluginContext(); Template = new CmsTemplate(); Cache = CacheFactory.Sington as CmsCache; Utility = new CmsUtility(); Language = new CmsLanguagePackage(); #region 缓存清除 // //UNDONE: 弱引用 // /* * WeakRefCache.OnLinkBuilting += () => * { * Cms.Cache.Clear(CacheSign.Link.ToString()); * }; * * WeakRefCache.OnModuleBuilting += () => * { * Cms.Cache.Clear(CacheSign.Module.ToString()); * }; * * WeakRefCache.OnPropertyBuilting += () => * { * Cms.Cache.Clear(CacheSign.Property.ToString()); * }; * * WeakRefCache.OnTemplateBindBuilting += () => * { * Cms.Cache.Clear(CacheSign.TemplateBind.ToString()); * }; * */ #endregion }
async Task <List <CalendarItem> > Request_iCal(Uri url) { CalendarItem currentItem = null; List <CalendarItem> items = new List <CalendarItem>(); var content = await GetStringFromUrl(url); if (content == null) { return(items); } var lines = content.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) { if (line == "BEGIN:VEVENT") { currentItem = new CalendarItem(); } else if (line == "END:VEVENT") { items.Add(currentItem); } else if (currentItem != null) { var parts = line.Split(':'); var value = parts.Length > 1 ? parts[1] : ""; var pair = new KeyValuePair <string, string>(parts[0], value); if (pair.Key.StartsWith("UID")) { currentItem.Uid = pair.Value; } else if (pair.Key.StartsWith("SUMMARY")) { currentItem.Summary = pair.Value; } else if (pair.Key.StartsWith("LOCATION")) { currentItem.Location = pair.Value; } else if (pair.Key.StartsWith("DESCRIPTION")) { currentItem.Description = pair.Value; } else if (pair.Key.StartsWith("CREATED")) { currentItem.Created = DateHelper.ParseExactDateTime(pair.Value); } else if (pair.Key.StartsWith("DTSTART")) { currentItem.Start = DateHelper.ParseExactDateTime(pair.Value); } else if (pair.Key.StartsWith("DTEND")) { currentItem.End = DateHelper.ParseExactDateTime(pair.Value); } } } return(items); }