public RecordMetadata(string key, string?value, Guid record) { this.Key = key; this.Value = value; this.Record = record; this.Guid = GuidCreator.Create(this.Record, this.Key); }
private void buttonSearch_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(this.textBoxSearchKeyword.Text)) { MessageBox.Show("You must enter a search keyword"); return; } if (!this.userkeysLoaded) { MessageBox.Show("You must load user keys first"); return; } Guid attributeId = GuidCreator.CreateGuidFromString(this.textBoxSearchKeyword.Text); IGatewayService proxy = CreateServiceProxy(); this.searchResults = proxy.FindData(GetUserIdentity(), attributeId); DecryptSearchResultsMetadata(); ShowSearchResults(); MessageBox.Show("Search complete"); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); Logger.LogError("Error searching for entities", ex); } }
public async Task <IActionResult> CreateBook(BookDto book) { if (ModelState.IsValid) { var dbBook = _mapper.Map <Book>(book); dbBook.Id = GuidCreator.CreateGuid(); var result = await _repository.AddItemAsync(dbBook); if (result > 0) { _logger.LogInformation($"New book with id {dbBook.Id} successfully created."); return(Ok()); } _logger.LogError($"Failed to create new book, book info: name {dbBook.Name}, author {dbBook.Author}, genre {dbBook.Genre}, price: {dbBook.Cost}."); return(StatusCode(500)); } _logger.LogError("Invalid request model, some fields are missed or have invalid format."); return(BadRequest(ModelState.Values)); }
private void buttonSearch_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(this.textBoxSearchKeyword.Text)) { MessageBox.Show("You must enter a search keyword"); return; } if (this.keyPair == null) { MessageBox.Show("You must load user keys first"); return; } Guid attributeId = GuidCreator.CreateGuidFromString(this.textBoxSearchKeyword.Text); IGatewayService proxy = CreateServiceProxy(); this.searchResults = proxy.SearchForDataEntities(this.myId, attributeId); if (RefreshRoles(this.rolesUserControlDownload)) { DecryptSearchResultsMetadata(); ShowSearchResults(); MessageBox.Show("Search complete"); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); Logger.LogError("Error searching for entities", ex); } }
private void buttonAddUserToRole_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(this.textBoxNewUserName.Text)) { MessageBox.Show("You must enter a username"); return; } Guid userId = GuidCreator.CreateGuidFromString(this.textBoxNewUserName.Text); if (this.treeViewRoles.SelectedNode != null && this.treeViewRoles.SelectedNode.Tag is RoleDescription) { RoleDescription selectedRole = (RoleDescription)this.treeViewRoles.SelectedNode.Tag; DialogResult result = MessageBox.Show("Are you sure you wan't to grant the role " + selectedRole.Name.GetString() + " to the user " + this.textBoxNewUserName.Text + "?", "Role assignment confirmation", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { IGatewayService proxy = GetServiceProxy(); proxy.AssignRoleToUser(this.myId, selectedRole.Id, userId); buttonRefreshRolesAndUsers_Click(this, EventArgs.Empty); } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); Logger.LogError("Error updating sub-role user", ex); } }
public MainForm() { InitializeComponent(); this.textBoxYourName.Text = Environment.UserName; this.myId = GuidCreator.CreateGuidFromString(this.textBoxYourName.Text); this.textBoxYourUniqueId.Text = this.myId.ToString(); }
public Form1() { InitializeComponent(); this.textBoxYourName.Text = Environment.UserName; this.myId = GuidCreator.CreateGuidFromString(this.textBoxYourName.Text); this.textBoxYourUniqueId.Text = this.myId.ToString(); InitializeSearchResultGrid(); }
public async Task <IActionResult> LoginUser(UserLoginForm loginForm) { var user = await _userManager.FindByNameAsync(loginForm.UserName); var result = await _signInManager.CheckPasswordSignInAsync(user, loginForm.Password, false); if (result.Succeeded) { var appUser = await _userManager.Users.FirstOrDefaultAsync( u => u.NormalizedUserName == loginForm.UserName.ToUpper()); var roles = await _userManager.GetRolesAsync(appUser); var userProfile = _mapper.Map <UserProfileDto>(appUser); var tokenKey = _securityConfigurations.tokenKey; var issuer = _securityConfigurations.Issuer; var appKey = _securityConfigurations.appKey; var token = TokensGenerator.GenerateJwtToken(appUser, roles, tokenKey, issuer); var refreshToken = TokensGenerator.GenerateRefreshToken(); HttpContext.AddCookies(token, appKey); HttpContext.AddCookies(refreshToken, $"{appKey}Refresh"); var existingToken = await _tokenRepository.FindItemAsync( t => t.UserId == appUser.Id && t.DeviceName == Request.Headers["device-info"].ToString()); if (existingToken != null) { _logger.LogWarning($"User with Id {appUser.Id} has already logged in from this device, old refresh token will be removed."); await _tokenRepository.RemoveItemAsync(existingToken); _logger.LogInformation($"Old refresh token for user with Id {appUser.Id} removed from database."); } await _tokenRepository.AddItemAsync( new RefreshToken { Id = GuidCreator.CreateGuid(), TokenValue = refreshToken, DeviceName = Request.Headers["device-info"], UserId = appUser.Id }); _logger.LogInformation($"User with id {appUser.Id} successfully logged in."); return(Ok(new { user = userProfile, token, refreshToken })); } return(Unauthorized()); }
private void textBoxTestName_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(this.textBoxTestName.Text)) { this.labelTestId.Text = GuidCreator.CreateGuidFromString(this.textBoxTestName.Text).ToString(); } else { this.labelTestId.Text = string.Empty; } }
private void buttonGenerateKeypairsForUser_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(this.textBoxNewUserId.Text)) { MessageBox.Show("You must enter a username"); return; } this.newUserId = GuidCreator.CreateGuidFromString(this.textBoxNewUserId.Text); if (this.masterKeypair == null) { MessageBox.Show("You must load master key pair first"); return; } string filename = FileDialogs.AskUserForFileNameToSaveIn(); if (!string.IsNullOrEmpty(filename)) { if (!Path.HasExtension(filename)) { filename = filename + ".xml"; } this.signKeyPair = DataSigner.GenerateSignKeyPair(); IPreService proxy = GetPreProxy(); this.userKeypair = proxy.GenerateKeyPair(); proxy = GetPreProxy(); this.delegationToken.ToUser = proxy.GenerateDelegationKey(this.masterKeypair.Private, this.userKeypair.Public); IGatewayService gateWayproxy = GetServiceProxy(); gateWayproxy.RegisterUser(this.myId, this.newUserId, this.delegationToken, this.signKeyPair.PublicOnly); UserKeys uk = new UserKeys(); uk.MasterKeyPublicKey = Convert.ToBase64String(this.masterKeypair.Public); uk.UserPrivateKey = Convert.ToBase64String(this.userKeypair.Private); uk.UserSignKeys = Convert.ToBase64String(this.signKeyPair.PublicAndPrivate); XmlFile.WriteFile(uk, filename); MessageBox.Show("Done"); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); Logger.LogError("Error generating user keypair", ex); } }
unsafe static ThumbnailBuilder() { (qualityEncoder = new EncoderParameters(1)).Param[0] = new EncoderParameter(Encoder.Quality, 100L); ImageCodecInfo[] infos = ImageCodecInfo.GetImageDecoders(); imageCodecs = new AutoCSer.StateSearcher.ByteSearcher <ImageCodecInfo>(infos.getArray(value => toByteArray(value.FormatID)), infos, true); GuidCreator guid = new GuidCreator { Value = ImageFormat.Jpeg.Guid }; jpegImageCodecInfo = imageCodecs.Get(&guid, 16); }
private void textBoxNewUserId_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(this.textBoxNewUserName.Text)) { this.labelAddUserGeneratedId.Text = GuidCreator.CreateGuidFromString(this.textBoxNewUserName.Text).ToString(); } else { this.labelAddUserGeneratedId.Text = string.Empty; } }
internal void Parse(ref Guid value) { BufferIndex *indexs = queryIndex + 1; if (indexs->Length == 0) { value = new Guid(); } else if (end - current != 36) { state = HeaderQueryParseState.NotGuid; } else { current = bufferStart + indexs->StartIndex; end = current + indexs->Length; GuidCreator guid = new GuidCreator(); guid.Byte3 = (byte)parseHex2(); guid.Byte2 = (byte)parseHex2(); guid.Byte1 = (byte)parseHex2(); guid.Byte0 = (byte)parseHex2(); if (*++current != '-') { state = HeaderQueryParseState.NotGuid; return; } guid.Byte45 = (ushort)parseHex4(); if (*++current != '-') { state = HeaderQueryParseState.NotGuid; return; } guid.Byte67 = (ushort)parseHex4(); if (*++current != '-') { state = HeaderQueryParseState.NotGuid; return; } guid.Byte8 = (byte)parseHex2(); guid.Byte9 = (byte)parseHex2(); if (*++current != '-') { state = HeaderQueryParseState.NotGuid; return; } guid.Byte10 = (byte)parseHex2(); guid.Byte11 = (byte)parseHex2(); guid.Byte12 = (byte)parseHex2(); guid.Byte13 = (byte)parseHex2(); guid.Byte14 = (byte)parseHex2(); guid.Byte15 = (byte)parseHex2(); value = guid.Value; } }
private IList <Attribute> CollectAndEncryptAttributes(AesEncryptionInfo encryptionInfo) { IList <Attribute> attributes = new List <Attribute>(); foreach (string s in this.listBoxUploadKeywords.Items) { byte[] att = SymmetricEncryptor.Encrypt(s.GetBytes(), encryptionInfo); attributes.Add(new Attribute(GuidCreator.CreateGuidFromString(s), att)); } return(attributes); }
public void ShouldBeSequentialAndNotEqual() { var guidCreator = new GuidCreator(); Guid lastGuid = Guid.Empty; for (int i = 0; i < 1000000; i++) { var guid = guidCreator.CreateClrSequential(); Assert.IsTrue(guid.CompareTo(lastGuid) > 0); lastGuid = guid; } }
/// <summary> /// /// </summary> /// <param name="model"></param> /// <returns></returns> public BaseMessage CreateOrderAndInfo(OrderModel model) { BaseMessage respose = new BaseMessage(); var stock = configDao.GetOrderStock(); if (stock.Remain - model.Num < 0) { respose.Msg = "剩余库存不足"; return(respose); } var createTime = DateTime.Now; OrderQueue orderQueue = new OrderQueue() { CreateTime = createTime, Num = model.Num, Status = 0, OrderNum = GuidCreator.GetUniqueKey("INK"), OrderType = model.OrderType }; OrderInfo info = new OrderInfo() { CoAddr = model.CoAddr, CoName = model.CoName, Content = model.Content ?? "", CoTelPhone = model.CoTelPhone, FontType = model.FontType, HQID = orderQueue.OrderNum, SignName = model.SignName }; using (var trans = DbContext.BeginTransaction()) { try { stock.Remain -= model.Num; DbContext.Update <OrderStock>(stock, trans); DbContext.Insert(orderQueue, trans); DbContext.Insert(info, trans); trans.Commit(); } catch (Exception ex) { trans.Rollback(); respose.Msg = "异常" + ex.ToString(); } } respose.IsSuccess = true; respose.Msg = "创单成功"; return(respose); }
private void textBoxYourName_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(this.textBoxYourName.Text)) { this.myId = GuidCreator.CreateGuidFromString(this.textBoxYourName.Text); this.textBoxYourUniqueId.Text = this.myId.ToString(); } else { this.myId = Guid.Empty; this.textBoxYourUniqueId.Text = ""; } }
public Entity Create(string keyName, RoomInstance room, HexCell cell, BaseParams param) { JEntityConfig config = GetEntityConfig(keyName); if (config == null) { Debug.LogError("找不到名为 " + keyName + "的EntityConfig"); return(null); } Type type = config.entityType; if (type == null) { Debug.LogError(keyName + " 找不到类型 " + config.type); return(null); } EntityModel entityModel = EntityModelManager.instance.GetEntityModel(config.entityModel); if (entityModel == null) { Debug.LogError("找不到 " + keyName + "的EntityModel " + config.entityModel); return(null); } HexagonsWithCenter cells = room.hexRoom.FindClearCellsInRange(config.size, cell, -1); if (cells == null) { Debug.LogError("找不到出生点!对象" + keyName); return(null); } //保证Y轴 uint oid = 0; do { oid = GuidCreator.GetOid(); }while (m_EntityDict.ContainsKey(oid)); Entity entity = Entity.CreateEntity(type, oid, keyName, config, entityModel, cells, param); if (entity != null) { m_EntityDict.Add(entity.oid, entity); room.AddEntity(entity); entity.Born(cells); } return(entity); }
/// <summary> /// 获取字节数组 /// </summary> /// <param name="guid">Guid</param> /// <returns>字节数组</returns> private unsafe static byte[] toByteArray(Guid guid) { byte[] data = new byte[16]; GuidCreator newGuid = new GuidCreator { Value = guid }; fixed(byte *dataFixed = data) { *(ulong *)dataFixed = *(ulong *)&newGuid; *(ulong *)(dataFixed + sizeof(ulong)) = *(ulong *)((byte *)&newGuid + sizeof(ulong)); } return(data); }
public async Task <IActionResult> PlaceOrder(OrderForCreateDto orderForCreate) { if (ModelState.IsValid) { var bookId = Guid.Parse(orderForCreate.BookId); var book = await _booksRepository.GetItemByIdAsync(bookId); var user = await _userManager.FindByNameAsync(orderForCreate.UserName); var existingOrder = _repository.FindItemAsync( o => o.UserId == user.Id && o.BookId == bookId && o.OrderDate.ToShortDateString() == DateTime.Today.ToShortDateString()); if (existingOrder != null) { _logger.LogWarning($"This user {user.Id} has already order book with id {bookId} today."); } var order = new Order { Id = GuidCreator.CreateGuid(), BookId = book.Id, UserId = user.Id, OrderCost = book.Cost, OrderDate = DateTime.UtcNow, DeliveryAdress = $"city:{user.City}, adress(post office #): {user.DeliveryAdress}." }; var result = await _repository.AddItemAsync(order); if (result > 0) { _logger.LogInformation($"New book with id {order.Id} successfully created."); return(Ok()); } _logger.LogError($"Failed to place new order, order info: bookId {book.Id}, userId {user.Id}."); return(StatusCode(500)); } _logger.LogError("Invalid request model, some fields are missed or have invalid format."); return(BadRequest(ModelState.Values)); }
public void CallParse(ref Guid value) { getValue(); if (State == ParseState.Success) { if (valueSize == 36) { GuidCreator guid = new GuidCreator(); parse(ref guid); value = guid.Value; getValueEnd(); } else { State = ParseState.NotGuid; } } }
public static string Add(IFormFile imageFile, string defaultPath, string defaultFile) { if (imageFile != null && imageFile.Length > 0) { string path = @"wwwroot/" + defaultPath; string guidImageName = GuidCreator.Create(imageFile.FileName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (FileStream fileStream = System.IO.File.Create(path + guidImageName)) { imageFile.CopyTo(fileStream); fileStream.Flush(); } return(defaultPath + guidImageName); } else { return(defaultPath + defaultFile); } }
private Guid GetUserIdentity() { return(GuidCreator.CreateGuidFromString(this.textBoxYourName.Text)); }
private void buttonCreateUser_Click(object sender, EventArgs e) { try { if (this.treeViewRoles.SelectedNode == null || !(this.treeViewRoles.SelectedNode.Tag is RoleDescription)) { return; } if (string.IsNullOrEmpty(this.textBoxNewUserName.Text)) { MessageBox.Show("You must enter a username"); return; } Guid newUserId = GuidCreator.CreateGuidFromString(this.textBoxNewUserName.Text); if (this.masterKeypair == null && this.keyPair == null) { MessageBox.Show("You must load your key pair first"); return; } string filename = FileDialogs.AskUserForFileNameToSaveIn(); if (!string.IsNullOrEmpty(filename)) { if (!Path.HasExtension(filename)) { filename = filename + ".xml"; } SignKeys userSignKeyPair = DataSigner.GenerateSignKeyPair(); IPreService proxy; KeyPair userKeypair; DelegationToken userDelegationToken; if (this.masterKeypair != null) { proxy = GetPreProxy(); userKeypair = proxy.GenerateKeyPair(); userDelegationToken = new DelegationToken(); proxy = GetPreProxy(); userDelegationToken.ToUser = proxy.GenerateDelegationKey(this.masterKeypair.Private, userKeypair.Public); } else { userKeypair = this.keyPair; // I am not a DO, so when creating a new user then reuse my key userDelegationToken = null; // I do not know my own delegation key. The server will put it in for me. } proxy = GetPreProxy(); byte[] username = proxy.Encrypt(this.keyPair.Public, this.textBoxNewUserName.Text.GetBytes()); User user = new User(); user.DelegationToken = userDelegationToken; user.Id = newUserId; user.Name = username; user.SignPublicKey = userSignKeyPair.PublicOnly; RoleDescription role = (RoleDescription)this.treeViewRoles.SelectedNode.Tag; IGatewayService gateWayproxy = GetServiceProxy(); gateWayproxy.CreateUser(this.myId, role.Id, user); KeyCollection uk = new KeyCollection(); uk.PublicKey = Convert.ToBase64String(this.keyPair.Public); // use original DO public key uk.PrivateKey = Convert.ToBase64String(userKeypair.Private); uk.SignKeys = Convert.ToBase64String(userSignKeyPair.PublicAndPrivate); XmlFile.WriteFile(uk, filename); buttonRefreshRolesAndUsers_Click(this, EventArgs.Empty); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); Logger.LogError("Error generating user keypair", ex); } }