public void GuidGen_MultiInitTest() { int serverIdExpect = 0; int serverId = 0; long key = 0; DateTime createTime; //init by id 2; serverIdExpect = 2; GuidGen.Init(serverIdExpect, "ABCDEFG", 6); string s1 = GuidGen.NewGUID(); key = GuidGen.DecryptGUID(s1, out serverId, out createTime); DateTime utcNow = DateTime.UtcNow; Assert.IsTrue(serverId == serverIdExpect, $"server id == {serverId}, not expected {serverIdExpect}"); Assert.IsTrue((utcNow - createTime).TotalSeconds < 1, "create time should be correct"); //init by id 66; serverIdExpect = 66; GuidGen.Init(serverIdExpect, "ABCDEFG", 6); string s2 = GuidGen.NewGUID(); key = GuidGen.DecryptGUID(s2, out serverId, out createTime); utcNow = DateTime.UtcNow; Assert.IsTrue(serverId == serverIdExpect, $"server id == {serverId}, not expected {serverIdExpect}"); Assert.IsTrue((utcNow - createTime).TotalSeconds < 1, "create time should be correct"); }
/// <summary> /// 添加子节点 /// </summary> /// <param name="data"></param> /// <returns></returns> public async Task AddChildNode(T data) { var parentNode = await _DbContext.Set <T>().FindAsync(data.ParentId); if (parentNode != null) { data.Id = GuidGen.NewGUID(); data.LValue = parentNode.RValue; data.RValue = data.LValue + 1; data.RootOrganizationId = parentNode.RootOrganizationId; var refNodes = await _DbContext.Set <T>().Where(x => x.RootOrganizationId == data.RootOrganizationId && x.RValue >= parentNode.RValue).ToListAsync(); for (int idx = refNodes.Count - 1; idx >= 0; idx--) { var cur = refNodes[idx]; //支线上只改变右值 if (cur.LValue <= parentNode.LValue) { cur.RValue += 2; } else { cur.LValue += 2; cur.RValue += 2; } _DbContext.Set <T>().Update(cur); } //添加新节点 _DbContext.Set <T>().Add(data); await _DbContext.SaveChangesAsync(); } }
private void btnGuidGen_Click(object sender, EventArgs e) { var ggen = new GuidGen(); ggen.Show(); ggen.Focus(); }
public ProductPermissionGroup(string name, string description, string organizationId) { Id = GuidGen.NewGUID(); Name = name; Description = description; OrganizationId = organizationId; }
public static ProjectDefinition CreateNetStandardProject(string name, string moniker, Guid?solutionFolder = null, Dictionary <string, SectionDefinition> innerProjectSections = null) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("message", nameof(name)); } if (string.IsNullOrEmpty(moniker)) { throw new ArgumentException("message", nameof(moniker)); } return(new ProjectDefinition { Id = GuidGen.Generate(), ProjectType = ProjectTypeGuids.NetStandard, SolutionFolder = solutionFolder, Name = name, Moniker = moniker, InnerProjectSections = innerProjectSections ?? new Dictionary <string, SectionDefinition>() }); }
public void GuidGen_SaltTest() { int serverIdExpect = 0; int serverId = 0; long key = 0; DateTime createTime; //init by id 2, salt A>a; serverIdExpect = 2; GuidGen.Init(serverIdExpect, "ABCDEFGHIJKLabcdefghijkl", 8); string s1 = GuidGen.NewGUID(); key = GuidGen.DecryptGUID(s1, out serverId, out createTime); DateTime utcNow = DateTime.UtcNow; Assert.IsTrue(serverId == serverIdExpect, $"server id == {serverId}, not expected {serverIdExpect}"); Assert.IsTrue((utcNow - createTime).TotalSeconds < 1, "create time should be correct"); //init by same id, salt a>A; GuidGen.Init(serverIdExpect, "abcdefghijklABCDEFGHIJKL", 8); key = GuidGen.DecryptGUID(s1, out serverId, out createTime); Assert.IsTrue(serverId == 0, $"server id == {serverId}, but should be 0 here, cos salt differnt"); //init by same id, salt a>A; GuidGen.Init(serverIdExpect, "BACDEFGHIJKLabcdefghijkl", 8); key = GuidGen.DecryptGUID(s1, out serverId, out createTime); Assert.IsTrue(serverId == 0, $"server id == {serverId}, but should be 0 here, cos salt differnt"); }
public UserRole(string accountId, string roleId) : this() { Id = GuidGen.NewGUID(); AccountId = accountId; CustomRoleId = roleId; }
public Account Register(RegisterAccountModel param) { if (param == null) { return(null); } if (string.IsNullOrWhiteSpace(param.Email)) { return(null); } string mail = param.Email.Trim().ToLower(); Account acc = context.Accounts.FirstOrDefault(d => d.Mail == mail); if (acc != null) { return(acc); } acc = new Account(); acc.Id = GuidGen.NewGUID(); acc.Mail = mail; acc.Password = param.Password; acc.Frozened = false; acc.ActivationTime = DateTime.UtcNow; acc.ExpireTime = DateTime.UtcNow.AddYears(10); acc.Type = ""; context.Accounts.Add(acc); context.SaveChangesAsync(); return(acc); }
public ProjectDefinition() { ProjectType = GuidGen.Generate(); Id = GuidGen.Generate(); Name = string.Empty; Moniker = string.Empty; }
public async Task <IActionResult> UpdateHierarchySetting([FromBody] MemberHierarchyParamSettingUpdateModel model) { var setting = await _Context.MemberHierarchySettings.Where(x => x.MemberHierarchyParamId == model.MemberHierarchyParamId && x.OrganizationId == CurrentAccountOrganizationId).FirstOrDefaultAsync(); if (setting == null) { setting = new MemberHierarchySetting(); setting.OrganizationId = CurrentAccountOrganizationId; } setting.MemberHierarchyParamId = model.MemberHierarchyParamId; setting.Rate = model.Rate; if (string.IsNullOrWhiteSpace(setting.Id)) { setting.Id = GuidGen.NewGUID(); _Context.MemberHierarchySettings.Add(setting); } else { _Context.MemberHierarchySettings.Update(setting); } await _Context.SaveChangesAsync(); return(Ok()); }
public async Task CreateAsync(Order data, string accountId) { data.Id = GuidGen.NewGUID(); data.Creator = accountId; data.Modifier = accountId; data.CreatedTime = DateTime.Now; data.ModifiedTime = data.CreatedTime; data.ActiveFlag = AppConst.Active; if (data.OrderDetails != null && data.OrderDetails.Count > 0) { data.TotalNum = data.OrderDetails.Select(x => x.Num).Sum(); data.TotalPrice = data.OrderDetails.Select(x => x.TotalPrice).Sum(); } //生成订单编号 var beginTime = new DateTime(data.CreatedTime.Year, data.CreatedTime.Month, data.CreatedTime.Day); var endTime = beginTime.AddDays(1); var orderCount = await _Context.Orders.Where(x => x.CreatedTime >= beginTime && x.CreatedTime < endTime).CountAsync(); data.OrderNo = beginTime.ToString("yyyyMMdd") + (orderCount + 1).ToString().PadLeft(5, '0'); //计算最优包装 foreach (var item in data.OrderDetails) { await ReCalculatePackage(item); } _Context.Orders.Add(data); await _Context.SaveChangesAsync(); }
public async Task <IActionResult> TransToLayout([FromBody] MapTransLayoutModel model) { var map = await _Repository._GetByIdAsync(model.MapId); var accid = AuthMan.GetAccountId(this); var layout = new Layout(); layout.Id = GuidGen.NewGUID(); layout.Name = map.Name; layout.Description = string.Format("auto generate at {0}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); layout.OrganizationId = map.OrganizationId; layout.Icon = map.Icon; layout.Creator = accid; layout.Modifier = accid; layout.CreatedTime = DateTime.Now; layout.ModifiedTime = DateTime.Now; layout.ActiveFlag = AppConst.I_DataState_Active; var layoutData = new MapTransLayoutDataModel(); layoutData.Map = layout.Name; layoutData.MapId = map.Id; layout.Data = JsonConvert.SerializeObject(layoutData); _Repository._DbContext.Layouts.Add(layout); await _Repository._DbContext.SaveChangesAsync(); return(Ok()); }
public void GuidGen_Repeat_ReturnsCorrectGuidWhenCharacterIsString() { Guid actual = GuidGen.Repeat("1"); Guid expected = new Guid("11111111-1111-1111-1111-111111111111"); Assert.AreEqual(expected, actual); }
public async Task <IActionResult> UpdateAdditionalRole([FromBody] UserAdditionalRoleEditModel model) { var accid = AuthMan.GetAccountId(this); Account acc = await _Repository._DbContext.Accounts.Where(x => x.Id == model.UserId).FirstOrDefaultAsync(); //清除之前的角色信息 var originRoles = _Repository._DbContext.AccountRoles.Where(x => x.Account == acc); foreach (var originItem in originRoles) { _Repository._DbContext.Remove(originItem); } await _Repository._DbContext.SaveChangesAsync(); var newRoles = new List <AccountRole>(); var roleIdArr = model.AdditionalRoleIds.Split(",", StringSplitOptions.RemoveEmptyEntries).Distinct().ToList(); foreach (var roleId in roleIdArr) { var newRole = new AccountRole(); newRole.Id = GuidGen.NewGUID(); newRole.Account = acc; newRole.UserRoleId = roleId; newRoles.Add(newRole); } acc.AdditionRoles = newRoles; _Repository._DbContext.Update(acc); await _Repository._DbContext.SaveChangesAsync(); return(Ok()); }
/*********************Collection*********************/ #region _PostCollectionRequest 处理添加收藏数据请求 /// <summary> /// 处理添加收藏数据请求 /// </summary> /// <param name="mapping"></param> /// <returns></returns> protected async Task <IActionResult> _PostCollectionRequest(Func <Collection, Task <Collection> > mapping) { var accid = AuthMan.GetAccountId(this); var account = await _Repository._DbContext.Accounts.FindAsync(accid); var metadata = new Collection(); //var canCreate = await _Repository.CanCreateAsync(accid); //if (!canCreate) // return Forbid(); var data = await mapping(metadata); data.Id = GuidGen.NewGUID(); data.CreatedTime = DateTime.UtcNow; data.ModifiedTime = DateTime.UtcNow; data.Creator = accid; data.Modifier = accid; data.OrganizationId = account.OrganizationId; _Repository._DbContext.Collections.Add(data); await _Repository._DbContext.SaveChangesAsync(); //await _Repository.SatisfyCreateAsync(accid, data, ModelState); //if (!ModelState.IsValid) // return new ValidationFailedResult(ModelState); //await _Repository.CreateAsync(accid, data); //var dto = await _Repository.GetByIdAsync(metadata.Id); ////如果handle不为空,由handle掌控ActionResult //if (handle != null) // return await handle(data); return(Ok()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider, IApplicationLifetime lifetime) { var dbContext = serviceProvider.GetService <AppDbContext>(); var settingsOptions = serviceProvider.GetService <IOptions <AppConfig> >(); var appConfig = settingsOptions.Value; app.UseCors("AllowAll"); app.UseAuthentication(); #region Authorization Middleware var apiGateway = Configuration["APIGatewayServer"]; app.Use(AuthorizeMiddleWare.Authorize(apiGateway)); #endregion app.UseMvc(); #region App Init { var serverId = Configuration["GuidSettings:ServerId"]; var guidSalt = Configuration["GuidSettings:GuidSalt"]; var guidMinLen = Configuration["GuidSettings:GuidMinLen"]; GuidGen.Init(serverId, guidSalt, guidMinLen); } #endregion #region Database Init { dbContext.Database.Migrate(); DatabaseInitTool.InitDatabase(app, env, serviceProvider, dbContext); } #endregion }
public CustomRole(string name, string description, string organizationId) : this() { Id = GuidGen.NewGUID(); Name = name; Description = description; OrganizationId = organizationId; }
public PackageMap(string package, string resourceId, string resourceType) : this() { Id = GuidGen.NewGUID(); Package = package; ResourceId = resourceId; ResourceType = resourceType; }
public async Task <IActionResult> Post([FromBody] OrderCreateModel model) { var mapping = new Func <Order, Task <Order> >(async(entity) => { entity.Name = model.Name; entity.Description = model.Description; entity.OrganizationId = CurrentAccountOrganizationId; entity.CustomerName = model.CustomerName; entity.CustomerPhone = model.CustomerPhone; entity.CustomerAddress = model.CustomerAddress; entity.SolutionId = model.SolutionId; entity.Data = model.Data; var details = new List <OrderDetail>(); if (model.Content != null && model.Content.Count > 0) { model.Content.ForEach(item => { var detail = new OrderDetail(); detail.Id = GuidGen.NewGUID(); detail.ProductSpecId = item.ProductSpecId; detail.Num = item.Num; //detail.UnitPrice = item.UnitPrice; detail.UnitPrice = Math.Round(item.UnitPrice, 2, MidpointRounding.AwayFromZero); detail.Remark = item.Remark; detail.Room = item.Room; detail.Owner = item.Owner; detail.CreatedTime = DateTime.Now; detail.ModifiedTime = detail.CreatedTime; detail.Creator = CurrentAccountId; detail.Modifier = CurrentAccountId; detail.OrganizationId = CurrentAccountOrganizationId; details.Add(detail); }); } entity.OrderDetails = details; var customizedProducts = new List <OrderDetailCustomizedProduct>(); if (model.CustomizedProduct != null && model.CustomizedProduct.Count > 0) { model.CustomizedProduct.ForEach(item => { var customiedProd = new OrderDetailCustomizedProduct(); customiedProd.Id = GuidGen.NewGUID(); customiedProd.Name = item.Name; customiedProd.Icon = item.Icon; customizedProducts.Add(customiedProd); }); } entity.CustomizedProducts = customizedProducts; return(await Task.FromResult(entity)); }); return(await _PostRequest(mapping)); }
/// <summary> /// 添加新节点 /// </summary> /// <param name="data"></param> /// <returns></returns> public async Task AddNewNode(T data) { data.Id = GuidGen.NewGUID(); data.LValue = 1; data.RValue = 2; data.RootOrganizationId = data.OrganizationId; _DbContext.Set <T>().Add(data); await _DbContext.SaveChangesAsync(); }
/// <summary> /// 获取所有分类,已经整理为树结构 /// </summary> /// <param name="type"></param> /// <param name="organId"></param> /// <returns></returns> public async Task <AssetCategoryDTO> GetCategoryAsync(string type, string organId) { //之所以采用这个方式,是因为tree表里面没有active标记,不清楚分类节点是否已经属于删除状态 var rootCatTreeNodeQ = from tree in _DbContext.AssetCategoryTrees join cat in _DbContext.AssetCategories on tree.ObjId equals cat.Id where cat.ActiveFlag == AppConst.I_DataState_Active && cat.OrganizationId == organId && tree.NodeType == type && tree.LValue == 1 select tree; var rootCatTreeNode = await rootCatTreeNodeQ.FirstAsync(); var tmpQ = from cat in _DbContext.AssetCategories join tree in _DbContext.AssetCategoryTrees on cat.Id equals tree.ObjId where cat.ActiveFlag == AppConst.I_DataState_Active && tree.OrganizationId == organId && tree.NodeType == rootCatTreeNode.NodeType && tree.LValue >= rootCatTreeNode.LValue && tree.RValue <= rootCatTreeNode.RValue select cat; var templist = await tmpQ.ToListAsync(); LinkedList <AssetCategory> list = new LinkedList <AssetCategory>(); foreach (var item in templist) { list.AddLast(item); } AssetCategoryDTO root = FindRoot(list); FindChildren(list, root); if (root == null) { AssetCategory rootNode = new AssetCategory(); rootNode.Id = GuidGen.NewGUID(); rootNode.ParentId = ""; rootNode.OrganizationId = organId; rootNode.Type = type; rootNode.Name = type + "_root"; rootNode.Icon = ""; rootNode.Description = "auto generated node for " + type + ", do not need to display this node"; rootNode.ResourceType = (int)ResourceTypeEnum.Organizational; _DbContext.AssetCategories.Add(rootNode); await _DbContext.SaveChangesAsync(); #region 添加tree节点 { var oTree = new AssetCategoryTree(); oTree.NodeType = type; oTree.Name = rootNode.Name; oTree.ObjId = rootNode.Id; oTree.OrganizationId = organId; await _AssetCategoryTreeRepository.AddNewNode(oTree); } #endregion root = rootNode.ToDTO(); } return(root); }
public async Task CreateAsync(Member data, string accountId) { data.Id = GuidGen.NewGUID(); data.Creator = accountId; data.Modifier = accountId; data.CreatedTime = DateTime.Now; data.ModifiedTime = data.CreatedTime; _Context.Members.Add(data); await _Context.SaveChangesAsync(); }
public async Task AddAsync(OrganizationTree entity) { if (string.IsNullOrWhiteSpace(entity.ParentObjId)) { entity.SetLValue(1); entity.SetRValue(2); entity.SetGroup(GuidGen.NewGUID()); } else { var parentNode = _context.Set <OrganizationTree>().FirstOrDefault(x => x.ObjId == entity.ParentObjId); if (parentNode == null) { throw new Exception($"找不到ObjId为{entity.ParentObjId}的上级节点"); } var referenceNodes = _context.Set <OrganizationTree>().Where(x => x.Group == parentNode.Group).ToList(); //新节点 entity.SetLValue(parentNode.RValue); entity.SetRValue(parentNode.RValue + 1); entity.SetGroup(parentNode.Group); entity.SetParentId(parentNode.Id); for (int idx = referenceNodes.Count - 1; idx >= 0; idx--) { var node = referenceNodes[idx]; //1.父节点 //只是右值加2 if (node.Id == parentNode.Id) { node.SetRValue(node.RValue + 2); continue; } //2.顶级节点 //只是右值加2 if (node.LValue == 1) { node.SetRValue(node.RValue + 2); continue; } //3.沿线节点 //左右值都加2 if (node.LValue > parentNode.LValue && node.RValue > parentNode.RValue) { node.SetLValue(node.LValue + 2); node.SetRValue(node.RValue + 2); continue; } } _context.Set <OrganizationTree>().UpdateRange(referenceNodes); } _context.Set <OrganizationTree>().Add(entity); await _context.SaveEntitiesAsync(); }
public void SetFingerprint(string fingerprint = null) { if (string.IsNullOrWhiteSpace(fingerprint)) { Fingerprint = GuidGen.NewGUID(); } else { Fingerprint = fingerprint; } }
public void GuidGen_Run100000TimesTest() { HashSet <string> ids = new HashSet <string>(); for (int i = 0; i < 100000; i++) { string s = GuidGen.NewGUID(); Assert.IsTrue(ids.Contains(s) == false, "repeated guid found!!"); ids.Add(s); } }
public async Task CreateAsync(WorkFlow data, string accountId) { data.Id = GuidGen.NewGUID(); data.Creator = accountId; data.Modifier = accountId; data.CreatedTime = DateTime.Now; data.ModifiedTime = data.CreatedTime; data.ActiveFlag = AppConst.Active; _Context.WorkFlows.Add(data); await _Context.SaveChangesAsync(); }
public void GuidGen_Repeat_ThrowsWhenCharacterOutOfRange() { try { Guid actual = GuidGen.Repeat("Z"); Assert.Fail("Expected ArgumentException not Thrown!"); } catch (ArgumentException) { } }
public void GuidGen_Repeat_ThrowsWhenCharacterLengthGreaterThan1() { try { Guid actual = GuidGen.Repeat("11"); Assert.Fail("Expected ArgumentOutOfRangeException not Thrown!"); } catch (ArgumentOutOfRangeException) { } }
public void GuidGen_Repeat_ThrowsWhenCharacterIsNull() { try { Guid actual = GuidGen.Repeat(null); Assert.Fail("Expected ArgumentNullException not Thrown!"); } catch (ArgumentNullException) { } }
public void GuidGen_Repeat_ThrowsWhenCharacterIsEmptyString() { try { Guid actual = GuidGen.Repeat(string.Empty); Assert.Fail("Expected ArgumentException not Thrown!"); } catch (ArgumentException) { } }