public UserEditorDialog(ISchemaProvider schemaProvider, UserSchema user, bool create) { this.Build(); if (schemaProvider == null) { throw new ArgumentNullException("schemaProvider"); } if (user == null) { throw new ArgumentNullException("user"); } this.schemaProvider = schemaProvider; this.user = user; this.action = create ? SchemaActions.Create : SchemaActions.Alter; this.Build(); if (create) { Title = GettextCatalog.GetString("Create User"); } else { Title = GettextCatalog.GetString("Alter User"); } notebook = new Notebook(); vboxContent.PackStart(notebook, true, true, 0); vboxContent.ShowAll(); }
public void SaveAndLoad_InbuiltSchemas() { var originalSecurity = new UserSchema(); using (IReadWriteUnitOfWork writer = ReadWriteProviderViaHiveGovernor.CreateReadWriteUnitOfWork()) { writer.ReadWriteRepository.AddOrUpdate(originalSecurity); writer.Commit(); } // Clear session to avoid caching when testing readbacks PostWriteCallback.Invoke(); using (IReadOnlyUnitOfWork reader = ReaderProviderViaHiveGovernor.CreateReadOnlyUnitOfWork()) { // Reload. Shouldn't matter that we're newing up the schemas to get the Id as Id should // have been left alone when saving, so leave it here as a test case var securitySchema = reader.ReadRepository.GetEntity<EntitySchema>(originalSecurity.Id); Assert.IsNotNull(securitySchema, "Security schema"); Assert.AreEqual(originalSecurity.AttributeDefinitions.Count, securitySchema.AttributeDefinitions.Count, "Security attrib defs count differ"); Assert.AreEqual(originalSecurity.AttributeGroups.Count, securitySchema.AttributeGroups.Count, "Security attrib groups count differ"); Assert.AreEqual(originalSecurity.AttributeTypes.Count, securitySchema.AttributeTypes.Count, "Security attrib types count differ"); } }
public override UserSchemaCollection GetUsers() { UserSchemaCollection users = new UserSchemaCollection(); using (IPooledDbConnection conn = connectionPool.Request()) { using (IDbCommand command = conn.CreateCommand(@"SELECT DISTINCT user from mysql.user where user != '';" )) { try { using (IDataReader r = command.ExecuteReader()) { while (r.Read()) { UserSchema user = new UserSchema(this); user.Name = r.GetString(0); users.Add(user); } r.Close(); } } catch (Exception e) { QueryService.RaiseException(e); } finally { conn.Release(); } } } return(users); }
public IActionResult Login([FromBody] LoginViewModel user, UserSchema mongo) { var loginUser = _authService.Authenticate(user.Username, user.Password); if (loginUser == null) { Unauthorized(); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); //debug tokenDescriptor variable var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, mongo.InternalId.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info (without password) and token to store client side return(Ok(new { user.Username, user.FirstName, user.LastName, token = tokenString })); }
public UserDataWindow(Api api, User user, UserSchema schema = null) : this() { this.Api = api; this.User = user; this.Text = string.Format("User: {0}", user.Name); this.UsersSchema = schema ?? Api.UserSchemas.Get(user.SchemaId); UpdateUserDisplay(); }
private Tuple <string, string> ValidationAnnotation( UserSchema userSchema) { var validationAnnotationMessage = $"data-valmsg-replace=true data-valmsg-for='{userSchema.PropertyName}' class='field-validation-valid'"; var validationAnnotationInput = $"data-val=true data-val-required='{userSchema.Title} is required'"; return(new Tuple <string, string>(validationAnnotationMessage, validationAnnotationInput)); }
public async Task TestUserSchemaEndpoint() { string json = Helpers.ReadExternalJsonFile("UserEndpoints", "UserSchema.json"); IKudosApi kudos = new KudosApi(null, Helpers.PrepareHttpClient(json)); UserSchema schema = await kudos.GetUserSchemaAsync(); Assert.IsNotNull(schema); }
public UserNode(DatabaseConnectionContext context, UserSchema user) : base(context) { if (user == null) { throw new ArgumentNullException("user"); } this.user = user; }
public async Task <UserSchema> EditAsync(int userId, UserSchema userSchema, string editUser) { var userVerification = Context.Users.SingleOrDefault(u => u.UserName == userSchema.UserName); if (userVerification != null && userVerification.Id != userId) { throw new Exception("already-exists"); } var user = Context.Users.SingleOrDefault(t => t.Id == userId); if (user == null) { throw new Exception("not-found"); } var formerUsername = user.UserName; Mapper.Map(userSchema, user); if (!userSchema.LockoutEndDateUtc.HasValue && !userSchema.LockoutEnabled) { user.LockoutEnabled = false; user.ResetAccessFailedCount(); } else { user.LockoutEnabled = userSchema.LockoutEnabled || userSchema.LockoutEndDateUtc.Value >= DateTimeOffset.UtcNow; } var groupsDb = GetUserGroupsByUserIdAsync(userId).Result; foreach (var groupDb in groupsDb) { Context.Remove(groupDb); } if (userSchema.Groups != null) { user.UserGroups = userSchema.Groups.Select(x => new UserGroup() { GroupId = x, UserId = userId }).ToList(); } if (userSchema.IsExternalUser && userSchema.AccountManagerId.HasValue) { TratarUserAccountManagerAsync(userSchema.IsMaster, formerUsername, userSchema.UserName, editUser, userSchema.AccountManagerId.Value); } Context.SaveChanges(); return(await Task.FromResult(MapResult(user))); }
private void OnCreateUserThreaded(object state) { object[] objs = state as object[]; IEditSchemaProvider provider = objs[0] as IEditSchemaProvider; UserSchema user = objs[1] as UserSchema; BaseNode node = objs[2] as BaseNode; provider.CreateUser(user); node.Refresh(); }
public async void Update(UserSchema userParam, string password = null) { var user = _context.Users.Find(userParam.Id).FirstOrDefault(); var filter = Builders <UserSchema> .Filter.Eq(s => s.Id, userParam.Id); var update = Builders <UserSchema> .Update .Set(s => s.FirstName, userParam.FirstName) .Set(s => s.LastName, userParam.LastName) .Set(s => s.Username, userParam.Username); try { UpdateResult actionResult = await _context.Users.UpdateOneAsync(filter, update); } catch (Exception ex) { // log or manage the exception throw ex; } if (user == null) { throw new AppException("User not found"); } //if (userParam.Username != user.Username) //{ // username has changed so check if the new username is already taken //if (_context.Users.Any(x => x.Username == userParam.Username)) //throw new AppException("Username " + userParam.Username + " is already taken"); //} // update user properties //user.FirstName = userParam.FirstName; //user.LastName = userParam.LastName; //user.Username = userParam.Username; // update password if it was entered //if (!string.IsNullOrWhiteSpace(password)) //{ // byte[] passwordHash, passwordSalt; // CreatePasswordHash(password, out passwordHash, out passwordSalt); // user.PasswordHash = passwordHash; // user.PasswordSalt = passwordSalt; //} //_context.Users.Update(user); }
protected void OnCreateUser() { BaseNode node = CurrentNode.DataItem as BaseNode; IDbFactory fac = node.ConnectionContext.DbFactory; IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider; UserSchema user = schemaProvider.CreateUserSchema("NewUser"); if (fac.GuiProvider.ShowUserEditorDialog(schemaProvider, user, true)) { ThreadPool.QueueUserWorkItem(new WaitCallback(OnCreateUserThreaded), new object[] { schemaProvider, user, node } as object); } }
public void SetDatabaseOptions(NpgsqlDatabaseSchema schema) { TreeIter iter; if (comboOwner.GetActiveIter(out iter)) { schema.Owner = (UserSchema)ownersStore.GetValue(iter, 1); } else if (comboOwner.ActiveText != String.Empty) { Console.WriteLine("Elegido"); UserSchema user = new UserSchema(schema.SchemaProvider); user.Name = comboOwner.ActiveText; } if (comboTemplate.GetActiveIter(out iter)) { schema.Template = (DatabaseSchema)templatesStore.GetValue(iter, 1); } else if (comboTemplate.ActiveText != string.Empty) { DatabaseSchema db = new DatabaseSchema(schema.SchemaProvider); db.Name = comboTemplate.ActiveText; } if (comboEncoding.GetActiveIter(out iter)) { schema.Encoding = (NpgsqlEncoding)encodingsStore.GetValue(iter, 1); } else if (comboEncoding.ActiveText != string.Empty) { NpgsqlEncoding enc = new NpgsqlEncoding(schema.SchemaProvider); enc.Name = comboEncoding.ActiveText; } if (comboTablespace.GetActiveIter(out iter)) { schema.Tablespace = (NpgsqlTablespace)tablespacesStore.GetValue(iter, 1); } else if (comboTablespace.ActiveText != string.Empty) { NpgsqlTablespace ts = new NpgsqlTablespace(schema.SchemaProvider); ts.Name = comboTablespace.ActiveText; } }
public async Task <ActionResult <UserSchema> > EditAsync([FromRoute] int id, [FromBody] UserSchema body) { try { var result = await this.UserService.EditAsync(id, body, User.Identity.Name); return(Ok(result)); } catch (System.Exception ex) { if (ex.Message == "not-found") { return(NotFound()); } throw; } }
private static async Task UserEndpoint(IKudosApi kudos) { UserSchema schema = await kudos.GetUserSchemaAsync(); Console.WriteLine(schema.Description); Users users = await kudos.GetUsersAsync(); foreach (User u in users.Resources) { Console.WriteLine("{0} {1} {2}", u.Name.GivenName, u.Name.FamilyName, u.Id); } User user = await kudos.GetUserAsync(42); Console.WriteLine("{0} {1} in {2}, Born {3}", user.Name.GivenName, user.Name.FamilyName, user.Enterprise.Department, user.Kudos.DateOfBirth.ToShortDateString()); UpdateUser update = new UpdateUser() { Kudos = new Kudos.Models.Extensions.UpdateKudosExtension() { DateOfBirth = new DateTime(1953, 1, 20) } }; User result = await kudos.UpdateUserAsync(42, update); Console.WriteLine("{0} {1} in {2}, born {3}", result.Name.GivenName, result.Name.FamilyName, result.Enterprise.Department, result.Kudos.DateOfBirth.ToShortDateString()); User newUser = new User() { UserName = "******" }; User response = await kudos.CreateUserAsync(newUser); Console.WriteLine("User ID {0} created for {1}", response.Id, response.UserName); await kudos.DeleteUserAsync(42); }
public void Post([FromBody] UserSchema RegData) { string password = RegData.Password; // generate a 128-bit salt using a secure PRNG byte[] salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}"); // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations) string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8)); var data = RegData; }
public async Task <ActionResult <UserSchema> > RegisterNewAsync([FromBody] UserSchema body) { try { var result = await this.UserService.RegisterNewAsync(body, User.Identity.Name); return(Ok(result)); } catch (System.Exception ex) { if (ex.Message == "not-found") { return(NotFound()); } else if (ex.Message == "already-exists") { return(Conflict()); } throw; } }
public HttpStatusCode Create(UserViewModel userDto, string password) { // validation if (string.IsNullOrWhiteSpace(userDto.Password)) { return(HttpStatusCode.NotAcceptable); } var filter = Builders <UserSchema> .Filter.Eq(s => s.Username, userDto.Username); var userResult = _context.Users.Find(filter).FirstOrDefault(); if (userResult != null) { return(HttpStatusCode.Found); } byte[] passwordHash, passwordSalt; CreatePasswordHash(password, out passwordHash, out passwordSalt); UserSchema user = new UserSchema() { Email = userDto.Email, FirstName = userDto.FirstName, LastName = userDto.LastName, Username = userDto.Username, PasswordHash = passwordHash, PasswordSalt = passwordSalt }; try { _context.Users.InsertOne(user); return(HttpStatusCode.OK); } catch (Exception) { return(HttpStatusCode.BadRequest); } }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.Content.AppendHtml("<div>"); string validationAnnotationMessage = string.Empty, validationAnnotationInput = string.Empty; UserSchema userSchema = new UserSchema { PropertyName = "Title", Title = "Title", Type = "string" }; (validationAnnotationMessage, validationAnnotationInput) = ValidationAnnotation(userSchema); if (userSchema.Type == "string") { output.Content.AppendHtml("<div>"); string value = string.Empty; output.Content.AppendHtml( $"<Label for= {userSchema.PropertyName}> {userSchema.Title} </Label>"); output.Content.AppendHtml( $"<Input {validationAnnotationInput} for= '{userSchema.PropertyName}' Id='{userSchema.PropertyName}' name='{userSchema.PropertyName}' value='{value}'/>"); output.Content.AppendHtml($"<span />"); output.Content.AppendHtml($"<span {validationAnnotationMessage} ></span>"); output.Content.AppendHtml("</div>"); } output.Content.AppendHtml("</div>"); }
public override UserSchemaCollection GetUsers () { UserSchemaCollection users = new UserSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (@"SELECT DISTINCT user from mysql.user where user != '';")) { try { using (IDataReader r = command.ExecuteReader ()) { while (r.Read ()) { UserSchema user = new UserSchema (this); user.Name = r.GetString (0); users.Add (user); } r.Close (); } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } } return users; }
/// <summary> /// Перевизначений метод обробки повідомлень. /// </summary> /// <param name="m">Повідомлення</param> protected override void WndProc(ref Message m) { base.WndProc(ref m); //winapi.WinAPI.OutputDebugString(m.ToString()); if (m.Msg == (int)CoreLib.MyMsgs.WM_HOTKEY) { //winapi.Funcs.OutputDebugString("Q"); #region hot key control switch (m.WParam.ToInt32()) { case 0x10: #region CONTROL + DELETE { //if (this.Cheque.ExtendedProperties.ContainsKey("BILL") && this.Cheque.ExtendedProperties["BILL"] != null && bool.Parse(this.Cheque.ExtendedProperties["LOCK"].ToString())) if ((bool)DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.IS_LOCKED, false)) { MMessageBox.Show("Поточний рахунок № " + DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.BILL_NO) + " надрукований клієнту.\r\nЗробіть з нього чек.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } if (Cheque.Rows.Count == 0) break;//r if (!(ADMIN_STATE || UserConfig.Properties[24]) && (DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.OWNER_NO, string.Empty).ToString() == string.Empty)) if (admin.ShowDialog() != DialogResult.OK) break;//r try { int index = chequeDGV.CurrentRow.Index; if (DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.OID, string.Empty).ToString() != string.Empty) { try { Dictionary<string, object[]> deletedRows = new Dictionary<string, object[]>(); deletedRows = (Dictionary<string, object[]>)DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.DELETED_ROWS, deletedRows); //DataRow[] dRow = new DataRow[1] { }; //this.Cheque.Rows.CopyTo(dRow, index); if (!deletedRows.ContainsKey(this.Cheque.Rows[index]["C"].ToString())) { deletedRows.Add(this.Cheque.Rows[index]["C"].ToString(), this.Cheque.Rows[index].ItemArray); DataWorkShared.SetBillProperty(this.Cheque, CoreConst.DELETED_ROWS, deletedRows); } } catch { } } Cheque.Rows.RemoveAt(index); //AppFunc.OutputDebugString("k"); RowsRemoved_MyEvent(true); index--; if (index < 0) if (Cheque.Rows.Count != 0) index = 0; else break;//r chequeDGV.CurrentCell = chequeDGV.Rows[index].Cells[chequeDGV.Columns.GetFirstColumn(DataGridViewElementStates.Visible).Name]; chequeDGV.Rows[index].Selected = true; } catch { } break; } #endregion case 0x11: #region CONTROL + SHIFT + DELETE { //if (this.Cheque.ExtendedProperties.ContainsKey("BILL") && this.Cheque.ExtendedProperties["BILL"] != null && bool.Parse(this.Cheque.ExtendedProperties["LOCK"].ToString())) if ((bool)DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.IS_LOCKED, false)) { MMessageBox.Show("Поточний рахунок № " + DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.BILL_NO) + " надрукований клієнту.\r\nЗробіть з нього чек.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } if (Cheque.Rows.Count == 0) break;//r if (!(ADMIN_STATE || UserConfig.Properties[24])) if (admin.ShowDialog() != DialogResult.OK) break;//r if (DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.OID, string.Empty).ToString() != string.Empty) { try { Dictionary<string, object[]> deletedRows = new Dictionary<string, object[]>(); deletedRows = (Dictionary<string, object[]>)DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.DELETED_ROWS, deletedRows); for (int index = 0; index < this.Cheque.Rows.Count ; index++) { if (!deletedRows.ContainsKey(this.Cheque.Rows[index]["C"].ToString())) deletedRows.Add(this.Cheque.Rows[index]["C"].ToString(), this.Cheque.Rows[index].ItemArray); } DataWorkShared.SetBillProperty(this.Cheque, CoreConst.DELETED_ROWS, deletedRows); } catch { } } Cheque.Rows.Clear(); RowsRemoved_MyEvent(true); break; } #endregion case 0x12: #region CONTROL + PageDown { if ((bool)DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.IS_LOCKED, false)) { MMessageBox.Show("Поточний рахунок № " + DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.BILL_NO) + " надрукований клієнту.\r\nЗробіть з нього чек.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } if (inventChq) return; if (!(ADMIN_STATE || UserConfig.Properties[3])) if (admin.ShowDialog() != DialogResult.OK) return; double discSUMA = 0.0; try { discSUMA = (double)Cheque.Compute("Sum(SUM)", "USEDDISC = " + Boolean.TrueString); } catch { } uiWndDiscountRequest d = new uiWndDiscountRequest(discSUMA, true); d.SetDiscount(ref discArrPercent, ref discArrCash); d.Dispose(); if (discArrPercent[0] == 0.0 && discArrPercent[1] == 0.0 && discArrCash[0] == 0.0 && discArrCash[1] == 0.0) ResetDiscount(); else { відмінитиЗнижкунадбавкуToolStripMenuItem.Enabled = true; if (AppConfig.APP_OnlyDiscount) відмінитиЗнижкунадбавкуToolStripMenuItem.Text = "Скасувати знижку"; else { if ((discArrPercent[0] != 0.0 && discArrPercent[1] != 0.0) || (discArrCash[0] != 0.0 && discArrCash[1] != 0.0)) відмінитиЗнижкунадбавкуToolStripMenuItem.Text = "Скасувати знижку і націнку"; if ((discArrPercent[0] == 0.0 && discArrPercent[1] != 0.0) || (discArrCash[0] == 0.0 && discArrCash[1] != 0.0)) відмінитиЗнижкунадбавкуToolStripMenuItem.Text = "Скасувати націнку"; if ((discArrPercent[0] != 0.0 && discArrPercent[1] == 0.0) || (discArrCash[0] != 0.0 && discArrCash[1] == 0.0)) відмінитиЗнижкунадбавкуToolStripMenuItem.Text = "Скасувати знижку"; } } UpdateSumInfo(true); break; } #endregion case 0x13: #region CONTROL + PageUp { if ((bool)DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.IS_LOCKED, false)) { MMessageBox.Show("Поточний рахунок № " + DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.BILL_NO) + " надрукований клієнту.\r\nЗробіть з нього чек.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } if (inventChq) return; if (!(ADMIN_STATE || UserConfig.Properties[3])) if (admin.ShowDialog() != DialogResult.OK) return; double discSUMA = 0; try { discSUMA = (double)Cheque.Compute("Sum(SUM)", "USEDDISC = " + Boolean.TrueString); } catch { } uiWndDiscountRequest d = new uiWndDiscountRequest(discSUMA, false); d.SetDiscount(ref discArrPercent, ref discArrCash); d.Dispose(); if (discArrPercent[0] == 0.0 && discArrPercent[1] == 0.0 && discArrCash[0] == 0.0 && discArrCash[1] == 0.0) ResetDiscount(); else { відмінитиЗнижкунадбавкуToolStripMenuItem.Enabled = true; if (AppConfig.APP_OnlyDiscount) відмінитиЗнижкунадбавкуToolStripMenuItem.Text = "Скасувати націнку"; else { if ((discArrPercent[0] != 0.0 && discArrPercent[1] != 0.0) || (discArrCash[0] != 0.0 && discArrCash[1] != 0.0)) відмінитиЗнижкунадбавкуToolStripMenuItem.Text = "Скасувати знижку і націнку"; if ((discArrPercent[0] == 0.0 && discArrPercent[1] != 0.0) || (discArrCash[0] == 0.0 && discArrCash[1] != 0.0)) відмінитиЗнижкунадбавкуToolStripMenuItem.Text = "Скасувати націнку"; if ((discArrPercent[0] != 0.0 && discArrPercent[1] == 0.0) || (discArrCash[0] != 0.0 && discArrCash[1] == 0.0)) відмінитиЗнижкунадбавкуToolStripMenuItem.Text = "Скасувати знижку"; } } UpdateSumInfo(true); break; } #endregion case 0x14: #region SHIFT + DELETE { if ((bool)DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.IS_LOCKED, false)) { MMessageBox.Show("Поточний рахунок № " + DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.BILL_NO) + " надрукований клієнту.\r\nЗробіть з нього чек.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } if (inventChq) return; ResetDiscount(); UpdateSumInfo(true); break; } #endregion case 0x21: { //winapi.WApi.OutputDebugString("LINE FEED KEY HOT"); break; } case 0x20: { //winapi.WApi.OutputDebugString("RETURN KEY HOT"); break; } case 0x15: #region ENTER { //if ( this.Cheque.ExtendedProperties.ContainsKey("BILL") && this.Cheque.ExtendedProperties["BILL"] != null && bool.Parse(((Dictionary<string, object>)this.Cheque.ExtendedProperties["BILL"])["IS_LOCKED"].ToString())) if ((bool)DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.IS_LOCKED, false)) { MMessageBox.Show("Поточний рахунок № " + DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.BILL_NO) + " надрукований клієнту.\r\nЗробіть з нього чек.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } //for (int i = 0x10; i < 0x20; i++) //AppFunc.UnregisterHotKey(this, i); bool editWasClosed = false; //winapi.WinAPI.OutputDebugString("Enter"); if (!UserConfig.Properties[22]) if (lastInputChar.AddMilliseconds(AppConfig.APP_ScannerCharReadFrequency) > DateTime.Now && chararray != null && chararray.Length != 0) { //if (chequeDGV.CurrentCell != null && chequeDGV.CurrentCell.IsInEditMode) //{ // if (chequeDGV.CurrentCell.EditedFormattedValue.ToString().Contains(chararray)) // { // string val = chequeDGV.CurrentCell.EditedFormattedValue.ToString(); // int bcidx = val.IndexOf(chararray); // val = val.Substring(0, bcidx); // if (val == string.Empty) // val = "0"; // chequeDGV.CurrentCell.Value = Convert.ToDouble(val); // } // chequeDGV.EndEdit(); // editWasClosed = true; //} // char filtering string newCharArray = string.Empty; foreach (char sci in this.chararray) { if (Char.IsLetter(sci) || Char.IsNumber(sci)) newCharArray += sci; } //winapi.WApi.OutputDebugString("SEARCHING WITH BARCODE: [" + chararray + "]"); SearchFilter(false, 2, true); SrchTbox.Text = newCharArray; SrchTbox.Select(); this.chararray = string.Empty; } //close edit if (chequeDGV.CurrentCell != null && chequeDGV.CurrentCell.IsInEditMode) { chequeDGV.EndEdit(); editWasClosed = true; } //lastInputChar = DateTime.Now; //launch article property if (chequeDGV.Focused && chequeDGV.RowCount != 0) { if (!(ADMIN_STATE || UserConfig.Properties[24]) && (DataWorkShared.ExtractBillProperty(this.Cheque, CoreConst.OWNER_NO, string.Empty).ToString() == string.Empty)) if (admin.ShowDialog() != DialogResult.OK) return; DataRow dRow = Cheque.Rows.Find(chequeDGV.CurrentRow.Cells["C"].Value); Request req = new Request(dRow, CoreLib.GetDouble(dRow["TOT"])); req.UpdateRowSource(); req.Dispose(); UpdateSumInfo(true); break;//r } //Adding article to Cheque if (articleDGV.Focused && articleDGV.RowCount != 0) { DataRow article = Articles.Rows.Find(articleDGV.CurrentRow.Cells["C"].Value); if (!this._fl_isOk && this.Cheque.Rows.Count >= 3 && this.Cheque.Rows.Find(article["C"].ToString()) == null) { MMessageBox.Show(this, "Ви не можете продавати більше позицій в демо-режимі", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); break; } if (article != null) CoreLib.AddArticleToCheque(chequeDGV, articleDGV, article, AppConfig.APP_StartTotal, Articles); break;//r } //winapi.WinAPI.OutputDebugString("srch: " + SrchTbox.Text); //Searching if (!editWasClosed && SrchTbox.Focused && SrchTbox.Text != string.Empty) { DataTable sTable = Articles.Clone(); bool allowToShow = false; int i = 0; //Debug.Write("BeginAdd"); #region search box //winapi.WApi.OutputDebugString("SEARCH BOX TEXT: [" + SrchTbox.Text + "]"); if (SrchTbox.Text != "") { switch (currSrchType) { case 0: { #region by name string[] words = SrchTbox.Text.Trim().Split(' '); DataRow[] dr1 = new DataRow[0]; DataRow[] dr2 = new DataRow[0]; DataTable dTable = (DataTable)articleDGV.DataSource; //string srchString = string.Empty; SrchTbox.Text = string.Empty; for (int l = 0; l < words.Length; l++) { try { dr1 = dTable.Select("NAME Like '%" + words[l] + "%'"); dr2 = dTable.Select("DESC Like '%" + words[l] + "%'"); } catch { } sTable.Clear(); sTable.BeginLoadData(); if (dr1.Length > dr2.Length) { for (i = 0; i < dr1.Length; i++) sTable.Rows.Add(dr1[i].ItemArray); } else { for (i = 0; i < dr2.Length; i++) sTable.Rows.Add(dr2[i].ItemArray); } sTable.EndLoadData(); dTable = sTable.Copy(); if (dTable.Rows.Count > 0) { articleDGV.DataSource = dTable; articleDGV.Select(); allowToShow = true; SrchTbox.Text += words[l] + " "; //SrchTbox.Select(0, srchString.Length); } } if (SrchTbox.Text == string.Empty) //if (SrchTbox.SelectedText == string.Empty) { MMessageBox.Show(this, "Нажаль нічого не вдалось знайти", "Результат пошуку", MessageBoxButtons.OK, MessageBoxIcon.Information); SearchFilter(false, AppConfig.APP_SearchType, true); } #endregion break; } case 1: { #region by id try { DataRow[] dr = Articles.Select("ID Like \'" + SrchTbox.Text + "%\'"); if (dr.Length == 0) { MMessageBox.Show(this, "Нажаль нічого не вдалось знайти", "Результат пошуку", MessageBoxButtons.OK, MessageBoxIcon.Information); SearchFilter(false, AppConfig.APP_SearchType, true); break; } if (dr.Length == 1) { SearchFilter(false, currSrchType, true); CoreLib.AddArticleToCheque(chequeDGV, articleDGV, dr[0], AppConfig.APP_StartTotal, Articles); allowToShow = false; break; } else { sTable.Clear(); sTable.BeginLoadData(); for (i = 0; i < dr.Length; i++) sTable.Rows.Add(dr[i].ItemArray); sTable.EndLoadData(); articleDGV.DataSource = sTable; articleDGV.Select(); allowToShow = true; } } catch { SrchTbox.Focus(); SrchTbox.SelectAll(); } #endregion break; } case 2: { #region by bc try { string _bcvalue = SrchTbox.Text.Trim('C', ' '); allowToShow = BCSearcher(_bcvalue, true); } catch (FormatException) { SrchTbox.Focus(); SrchTbox.SelectAll(); } #endregion break; } } } #endregion if (splitContainer1.Panel2Collapsed && allowToShow) { вікноТоварівToolStripMenuItem.PerformClick(); splitContainer1.Panel2.Tag = new object(); articleDGV.Select(); } articleDGV.Update(); //Debug.Write("EndAdd"); } break; } #endregion case 0x16: #region CONTROL + ENTER { if (inventChq || Cheque.Rows.Count == 0) break;//r if (!(ADMIN_STATE || UserConfig.Properties[23])) { //if (admin.ShowDialog() != DialogResult.OK) MMessageBox.Show(this, "Закриття чеку заблоковано", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); break;//r } // if we use legal printer if (Program.Service.UseEKKR) { // we close legal cheque CloseCheque(true); } else { // if we don't use legal printer and // if we allow to close normal cheque or admin mode is active if (UserConfig.Properties[6]) { // we close normal cheque CloseCheque(false); } else MMessageBox.Show(this, "Закриття чеку заблоковано", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } break; } #endregion case 0x17: #region CONTROL + SHIFT + ENTER { if (inventChq) break;//r if (Cheque.Rows.Count == 0 && UserConfig.Properties[12]) { string nextChqNom = string.Empty; object[] localData = CoreLib.NonFxChqsInfo(0, ref nextChqNom); DDM_Status.Text = string.Format("За {1} продано {0} чек(ів) на суму {2:F" + AppConfig.APP_MoneyDecimals + "}", localData[0], localData[1], CoreLib.GetDouble(localData[2].ToString())); break;//r } if (Cheque.Rows.Count == 0)// || !Program.Service.UseEKKR) break;//r if (!(ADMIN_STATE || (UserConfig.Properties[23] && UserConfig.Properties[6]) )) { MMessageBox.Show(this, "Закриття чеку заблоковано", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); break; } if (AppConfig.Content_Common_PromptMsgOnIllegal && DialogResult.Yes != MMessageBox.Show(this, "Закрити чек без фіксації оплати", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)) break;//r /* if (!(ADMIN_STATE || (UserConfig.Properties[23] && UserConfig.Properties[6]))) if (admin.ShowDialog() != DialogResult.OK) break;//r */ CloseCheque(false); break; } #endregion case 0x18: #region F5 { if (!AppConfig.APP_SrchTypesAccess[0]) { MMessageBox.Show(this, "Пошук по назві не дозволений", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } if (currSrchType != 0) SearchFilter(false, 0, true); else { SrchTbox.Focus(); SrchTbox.Select(SrchTbox.Text.Length, 0); } break; } #endregion case 0x19: #region F6 { if (!AppConfig.APP_SrchTypesAccess[1]) { MMessageBox.Show(this, "Пошук по коду не дозволений", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } if (currSrchType != 1) SearchFilter(false, 1, true); else { SrchTbox.Focus(); SrchTbox.Select(SrchTbox.Text.Length, 0); } break; } #endregion case 0x1A: #region F7 { //winapi.WinAPI.OutputDebugString("F7"); if (!AppConfig.APP_SrchTypesAccess[2]) { MMessageBox.Show(this, "Пошук по штрих-коду не дозволений", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break;//r } if (currSrchType != 2) SearchFilter(false, 2, true); else { SrchTbox.Focus(); SrchTbox.Select(0, SrchTbox.Text.Length); } break; } #endregion case 0x1B: #region F8 { if (Cheque.ExtendedProperties.Contains("BILL")) MMessageBox.Show(this, "Відкритий рахунок №" + " " + Cheque.ExtendedProperties["NOM"], Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); break; } #endregion case 0x1C: #region F9 { string infoText = string.Empty; UserSchema us = new UserSchema(); infoText += UserConfig.UserID; infoText += "\r\n\r\n--------------------------------------------------\r\n\r\n"; for (int i = 0; i < UserSchema.ITEMS_COUNT; i++) infoText += us.SchemaItems[i] + " : " + (UserConfig.Properties[i] ? "Так" : "Ні") + "\r\n"; MMessageBox.Show(infoText, UserConfig.UserID); break; } #endregion case 0x1D: #region ESCAPE { SearchFilter(false, AppConfig.APP_SearchType, true); break; } #endregion case 0x1E: #region CONTROL + Q { if (inventChq) break;//r nakladna = !nakladna; if (nakladna) CashLbl.Image = Properties.Resources.naklad; else CashLbl.Image = null; break; } #endregion case 0x1F: #region CONTROL { if (chequeDGV.CurrentCell != null && chequeDGV.CurrentCell.IsInEditMode) chequeDGV.EndEdit(); break; } #endregion } #endregion //winapi.Funcs.OutputDebugString("W"); } if (m.Msg == (int)CoreLib.MyMsgs.WM_UPDATE) { if (_fl_canUpdate) this.timer1_Tick(this.timer1, EventArgs.Empty); } }
//http://dev.mysql.com/doc/refman/5.1/en/create-user.html public override void CreateUser(UserSchema user) { throw new NotImplementedException(); }
public async Task UpdateApplicationUserSchema() { var rawResponse = @" { ""id"": ""https://${yourOktaDomain}/meta/schemas/apps/0oa25gejWwdXNnFH90g4/default"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""name"": ""Example App"", ""title"": ""Example App User"", ""lastUpdated"": ""2017-07-18T23:18:43.000Z"", ""created"": ""2017-07-18T22:35:30.000Z"", ""definitions"": { ""base"": { ""id"": ""#base"", ""type"": ""object"", ""properties"": { ""userName"": { ""title"": ""Username"", ""type"": ""string"", ""required"": true, ""scope"": ""NONE"", ""maxLength"": 100 } }, ""required"": [ ""userName"" ] }, ""custom"": { ""id"": ""#custom"", ""type"": ""object"", ""properties"": { ""twitterUserName"": { ""title"": ""Twitter username"", ""description"": ""User's username for twitter.com"", ""type"": ""string"", ""scope"": ""NONE"", ""minLength"": 1, ""maxLength"": 20 } }, ""required"": [] } }, ""type"": ""object"", ""properties"": { ""profile"": { ""allOf"": [ { ""$ref"": ""#/definitions/base"" }, { ""$ref"": ""#/definitions/custom"" } ] } } }"; var mockRequestExecutor = new MockedStringRequestExecutor(rawResponse); var client = new TestableOktaClient(mockRequestExecutor); // Add custom attribute var customAttributeDetails = new UserSchemaAttribute() { Title = "Twitter username", Type = "string", Description = "User's username for twitter.com", MinLength = 1, MaxLength = 20, }; var customAttribute = new Resource(); customAttribute["twitterUserName"] = customAttributeDetails; var userSchema = new UserSchema(); userSchema.Definitions = new UserSchemaDefinitions { Custom = new UserSchemaPublic { Properties = customAttribute, }, }; var updatedUserSchema = await client.UserSchemas.UpdateApplicationUserProfileAsync(userSchema, "foo"); var retrievedCustomAttribute = updatedUserSchema.Definitions.Custom.Properties.GetProperty <UserSchemaAttribute>("twitterUserName"); retrievedCustomAttribute.Title.Should().Be("Twitter username"); retrievedCustomAttribute.Type.Should().Be(UserSchemaAttributeType.String); retrievedCustomAttribute.Description.Should().Be("User's username for twitter.com"); retrievedCustomAttribute.Required.Should().BeNull(); retrievedCustomAttribute.MinLength.Should().Be(1); retrievedCustomAttribute.MaxLength.Should().Be(20); mockRequestExecutor.ReceivedHref.Should().StartWith("/api/v1/meta/schemas/apps/foo/default"); }
//http://dev.mysql.com/doc/refman/5.1/en/rename-user.html public override void RenameUser (UserSchema user, string name) { ExecuteNonQuery (string.Concat("RENAME USER ", user.Name, " TO ", name, ";")); user.Name = name; }
public async Task DeleteUserDocument(string databaseName, string collectionName, UserSchema deleteuser) { try { await this.client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, deleteuser.Id), new RequestOptions { PartitionKey = new PartitionKey(deleteuser.UserId) }); this.WriteToConsoleAndPromptToContinue("Deleted user {0}", deleteuser.Id); } catch (DocumentClientException de) { if (de.StatusCode == HttpStatusCode.NotFound) { this.WriteToConsoleAndPromptToContinue("User {0} not found for deletion", deleteuser.Id); } else { throw; } } }
public bool ShowUserEditorDialog(IEditSchemaProvider schemaProvider, UserSchema user, bool create) { return(false); //TODO: implement ShowUserEditorDialog }
//http://dev.mysql.com/doc/refman/5.1/en/drop-user.html public override void DropUser(UserSchema user) { ExecuteNonQuery(string.Concat("DROP USER ", user.Name, ";")); }
public void SetDatabaseOptions (NpgsqlDatabaseSchema schema) { TreeIter iter; if (comboOwner.GetActiveIter (out iter)) schema.Owner = (UserSchema)ownersStore.GetValue (iter,1); else if (comboOwner.ActiveText != String.Empty) { Console.WriteLine ("Elegido"); UserSchema user = new UserSchema (schema.SchemaProvider); user.Name = comboOwner.ActiveText; } if (comboTemplate.GetActiveIter (out iter)) schema.Template = (DatabaseSchema)templatesStore.GetValue (iter,1); else if (comboTemplate.ActiveText != string.Empty) { DatabaseSchema db = new DatabaseSchema (schema.SchemaProvider); db.Name = comboTemplate.ActiveText; } if (comboEncoding.GetActiveIter (out iter)) schema.Encoding = (NpgsqlEncoding)encodingsStore.GetValue (iter, 1); else if (comboEncoding.ActiveText != string.Empty) { NpgsqlEncoding enc = new NpgsqlEncoding (schema.SchemaProvider); enc.Name = comboEncoding.ActiveText; } if (comboTablespace.GetActiveIter (out iter)) schema.Tablespace = (NpgsqlTablespace)tablespacesStore.GetValue (iter, 1); else if (comboTablespace.ActiveText != string.Empty) { NpgsqlTablespace ts = new NpgsqlTablespace (schema.SchemaProvider); ts.Name = comboTablespace.ActiveText; } }
public bool ShowUserEditorDialog (IEditSchemaProvider schemaProvider, UserSchema user, bool create) { throw new NotImplementedException ();
private void saveToolStripButton1_Click(object sender, EventArgs e) { UserSchema sh = new UserSchema(); string oldName = string.Empty; if (toolStripComboBox1.Items.Count != 0) oldName = toolStripComboBox1.SelectedItem.ToString(); sh.SchemaName = toolStripTextBox1.Text; if (!isNewSch && oldName != sh.SchemaName) { DialogResult rez = MMessageBox.Show("Обновити схему \"" + oldName + "\" ?", "Сервіс", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (rez == DialogResult.No) { toolStripTextBox1.Focus(); toolStripTextBox1.SelectAll(); return; } File.Delete(AppConfig.Path_Schemes + "\\" + oldName + ".mst"); } FileStream fs = new FileStream(AppConfig.Path_Schemes + "\\" + sh.SchemaName + ".mst", FileMode.Create, FileAccess.Write); sh.SchemaTable = new bool[checkedListBox1.Items.Count]; for (int i = 0; i < UserSchema.ITEMS_COUNT; i++) sh.SchemaTable[i] = checkedListBox1.GetItemChecked(i); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binF.Serialize(fs, sh); fs.Close(); if (isNewSch) { toolStripComboBox1.Items.Add(sh.SchemaName); toolStripComboBox1.SelectedItem = sh.SchemaName; comboBox1.Items.Add(sh.SchemaName); } else if (sh.SchemaName != oldName) { toolStripComboBox1.Items.RemoveAt(toolStripComboBox1.Items.IndexOf(oldName)); toolStripComboBox1.Items.Add(sh.SchemaName); comboBox1.Items.RemoveAt(comboBox1.Items.IndexOf(oldName)); comboBox1.Items.Add(sh.SchemaName); toolStripComboBox1.SelectedItem = sh.SchemaName; comboBox1.SelectedIndex = 0; } toolStripTextBox1.Text = ""; toolStripTextBox1.Enabled = false; CleanLib.ClearCheckedBox(ref checkedListBox1); AutoEnableToolBar(); isNewSch = false; }
//Methods for administration of schemas private void LoadSchemesList() { if (!Directory.Exists(AppConfig.Path_Schemes)) Directory.CreateDirectory(AppConfig.Path_Schemes); UserSchema sch = new UserSchema(); checkedListBox1.Items.AddRange(sch.SchemaItems); userProperties.Items.AddRange(sch.SchemaItems); string[] sMas = Directory.GetFiles(AppConfig.Path_Schemes + "\\", "*.mst"); for (int i = 0; i < sMas.Length; i++) { try { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); sch = (UserSchema)binF.Deserialize(new FileStream(sMas[i], FileMode.Open)); toolStripComboBox1.Items.Add(sch.SchemaName); comboBox1.Items.Add(sch.SchemaName); } catch { } } if (toolStripComboBox1.Items.Count != 0) { toolStripComboBox1.SelectedIndex = 0; comboBox1.SelectedIndex = 0; } AutoEnableToolBar(); }
public async Task RunStoredProcedure(string databaseName, string collectionName, UserSchema user) { await client.ExecuteStoredProcedureAsync <string>(UriFactory.CreateStoredProcedureUri(databaseName, collectionName, "UpdateOrderTotal"), new RequestOptions { PartitionKey = new PartitionKey(user.UserId) }); Console.WriteLine("Stored procedure complete"); }
//http://dev.mysql.com/doc/refman/5.1/en/create-user.html public override void CreateUser (UserSchema user) { throw new NotImplementedException (); }
//http://dev.mysql.com/doc/refman/5.1/en/rename-user.html public override void RenameUser(UserSchema user, string name) { ExecuteNonQuery(string.Concat("RENAME USER ", user.Name, " TO ", name, ";")); user.Name = name; }
//http://dev.mysql.com/doc/refman/5.1/en/drop-user.html public override void DropUser (UserSchema user) { ExecuteNonQuery (string.Concat("DROP USER ", user.Name, ";")); }
public async Task <UserSchema> RegisterNewAsync(UserSchema userSchema, string creationUser) { var userVerification = Context.Users.SingleOrDefault( u => u.UserName == userSchema.UserName ); if (userVerification != null) { throw new Exception("already-exists"); } byte[] salt = new byte[128 / 8]; byte[] senhaBytes = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); rng.GetBytes(senhaBytes); } var senha = Convert.ToBase64String(senhaBytes); string passwordHash = Services.AuthService.GetHashed(senha, Convert.ToBase64String(salt)); var user = Mapper.Map <User>(userSchema); user.PasswordExpirationDate = DateTimeOffset.Now; user.CreationDate = DateTimeOffset.Now; user.ChangeDate = DateTimeOffset.Now; user.EmailConfirmed = true; user.PhoneNumberConfirmed = true; user.Salt = Convert.ToBase64String(salt); user.PasswordHash = passwordHash; if (!userSchema.LockoutEndDateUtc.HasValue && !userSchema.LockoutEnabled) { user.LockoutEnabled = false; user.ResetAccessFailedCount(); } else { user.LockoutEnabled = userSchema.LockoutEnabled || userSchema.LockoutEndDateUtc.Value >= DateTimeOffset.Now; } CreatePasswordHistory(user, passwordHash); user.UserGroups = new List <UserGroup>(); if (userSchema.Groups != null) { foreach (var group in userSchema.Groups) { var userGroup = new UserGroup() { GroupId = group, UserId = user.Id }; user.UserGroups.Add(userGroup); } } if (userSchema.IsExternalUser && userSchema.AccountManagerId.HasValue) { TratarUserAccountManagerAsync(userSchema.IsMaster, userSchema.UserName, userSchema.UserName, creationUser, userSchema.AccountManagerId.Value); } Context.Users.Add(user); Context.SaveChanges(); var dictValoresEmail = new Dictionary <string, string>(); dictValoresEmail.Add("[[NOME]]", userSchema.Name); dictValoresEmail.Add("[[USERNAME]]", userSchema.UserName); dictValoresEmail.Add("[[SENHA]]", senha); dictValoresEmail.Add("[[URL]]", ApplicationSettings.Url); await this.EmailService.SendEmailAsync(userSchema.Email, "Criação de Usuário", null, Entities.Enums.EmailTemplateEnum.PasswordCreation, dictValoresEmail); return(await Task.FromResult(MapResult(user))); }
public async Task CreateUserDocumentIfNotExists(string databaseName, string collectionName, UserSchema user) { try { await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, user.Id), new RequestOptions { PartitionKey = new PartitionKey(user.UserId) }); this.WriteToConsoleAndPromptToContinue("User {0} already exists in the database", user.Id); } catch (DocumentClientException de) { if (de.StatusCode == HttpStatusCode.NotFound) { await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), user); this.WriteToConsoleAndPromptToContinue("Created User {0}", user.Id); } else { throw; } } }
public async Task ReplaceUserDocument(string databaseName, string collectionName, UserSchema updatedUser) { try { await this.client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, updatedUser.Id), updatedUser, new RequestOptions { PartitionKey = new PartitionKey(updatedUser.UserId) }); this.WriteToConsoleAndPromptToContinue("Replaced last name for {0}", updatedUser.LastName); } catch (DocumentClientException de) { if (de.StatusCode == HttpStatusCode.NotFound) { WriteToConsoleAndPromptToContinue("User {0} not found to replacement", updatedUser.Id); } else { throw; } } }
public bool ShowUserEditorDialog (IEditSchemaProvider schemaProvider, UserSchema user, bool create) { return false; //TODO: implement ShowUserEditorDialog
public override UserSchemaCollection GetUsers () { UserSchemaCollection users = new UserSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand ("SELECT * FROM pg_user;")) { try { using (IDataReader r = command.ExecuteReader ()) { while (r.Read ()) { UserSchema user = new UserSchema (this); user.Name = r.GetString (0); user.UserId = String.Format ("{0}", r.GetValue (1)); user.Expires = r.IsDBNull (6) ? DateTime.MinValue : r.GetDateTime (6); user.Password = r.GetString (5); StringBuilder sb = new StringBuilder (); sb.AppendFormat ("-- User: \"{0}\"\n\n", user.Name); sb.AppendFormat ("-- DROP USER {0};\n\n", user.Name); sb.AppendFormat ("CREATE USER {0}", user.Name); sb.AppendFormat (" WITH SYSID {0}", user.UserId); if (user.Password != "********") sb.AppendFormat (" ENCRYPTED PASSWORD {0}", user.Password); if (user.Expires != DateTime.MinValue) sb.AppendFormat (" VALID UNTIL {0}", user.Expires); sb.Append (";"); user.Definition = sb.ToString (); users.Add (user); } r.Close (); } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } } return users;
private void editToolStripButton5_Click(object sender, EventArgs e) { ToolBarItemsEnable(false); saveToolStripButton1.Enabled = true; cancelToolStripButton1.Enabled = true; toolStripTextBox1.Enabled = true; UserSchema sch = new UserSchema(); string[] sMas = Directory.GetFiles(AppConfig.Path_Schemes + "\\", "*.mst"); FileStream fs = null; for (int i = 0; i < sMas.Length; i++) { fs = new FileStream(sMas[i], FileMode.Open); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); sch = (UserSchema)binF.Deserialize(fs); if (sch.SchemaName == toolStripComboBox1.SelectedItem.ToString()) { for (int j = 0; j < UserSchema.ITEMS_COUNT; j++) checkedListBox1.SetItemChecked(j, sch.SchemaTable[j]); fs.Close(); break; } fs.Close(); } toolStripTextBox1.Text = sch.SchemaName; checkedListBox1.Enabled = true; }
private void GenerateUserDataViewWindow(User user, UserSchema schema = null) { // var schema = UserSchemaList[user.SchemaId]; foreach (var child in this.MdiChildren) { if (child.GetType() == typeof(UserDataWindow)) { var userWin = (UserDataWindow)child; if (userWin.User != null && userWin.User.Id == user.Id) { ShowWindow(userWin); return; } } } var win = new UserDataWindow(Api, user, schema); win.MdiParent = this; win.Visible = true; win.OnUserUpdated += (obj, usr, method) => { if (method == UserDataWindow.UserUpdateMethod.Create) { // just reload all the users, when a new user is added this.RefreshUserTree(); } // find the corrosponding TreeNode for the UserSchema and the User var schemaNodes = from node in tnUsersRoot.Nodes.Cast <TreeNode>() where node.Tag != null && node.Tag.GetType() == typeof(UserSchema) && ((UserSchema)node.Tag).Id == user.SchemaId select node; // this is the node where the schema is displayed var schemaNode = schemaNodes.FirstOrDefault(); if (schemaNode != null) { var userNodes = from node in schemaNode.Nodes.Cast <TreeNode>() where node.Tag != null && node.Tag.GetType() == typeof(User) // && ((User)node.Tag).Id == user.Id select node; // this is the node where the user is displayed var userNode = userNodes.FirstOrDefault(o => (o.Tag as User).Name == user.Name); if (userNode != null) { tnUsersRoot.Expand(); schemaNode.Expand(); if (method == UserDataWindow.UserUpdateMethod.Create) { // select the newly generated user tvSchemas.SelectedNode = userNode; } else { // simply update the selected text userNode.Text = user.Name; } } } }; }
/// <summary> /// Перевірка параметрів користувача з існуючими схемами /// </summary> /// <param name="schema">Список існуючих схем</param> /// <returns>Назва схеми, яка співападає з параметрами користувачів</returns> private string RecognizeSchema(bool[] schema) { UserSchema sch = new UserSchema(); int j = 0; string[] sMas = Directory.GetFiles(AppConfig.Path_Schemes + "\\", "*.mst"); bool match = true; FileStream fs = null; for (int i = 0; i < sMas.Length; i++) { fs = new FileStream(sMas[i], FileMode.Open); try { sch = (UserSchema)binF.Deserialize(fs); } catch { } fs.Close(); fs.Dispose(); for (j = 0; j < UserSchema.ITEMS_COUNT - 1; j++) if (schema[j] != sch.SchemaTable[j]) { match = false; break; } if (match) return sch.SchemaName; else match = true; } return ""; }
public void Post([FromBody] UserSchema LoginData) { var data = LoginData; }
//Use schema private void button5_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex == -1) return; UserSchema sch = new UserSchema(); string[] sMas = Directory.GetFiles(AppConfig.Path_Schemes + "\\", "*.mst"); FileStream fs = null; for (int i = 0; i < sMas.Length; i++) { fs = new FileStream(sMas[i], FileMode.Open); sch = (UserSchema)binF.Deserialize(fs); fs.Close(); fs.Dispose(); if (sch.SchemaName == comboBox1.Text) { for (int j = 0; j < sch.SchemaTable.Length; j++) userProperties.SetItemChecked(j, sch.SchemaTable[j]); //SaveUser(treeView1.SelectedNode.Index); SaveUser(listBox1.SelectedIndex); } } }
bool IGuiProvider.ShowUserEditorDialog(IEditSchemaProvider schemaProvider, UserSchema user, bool create) { return false; }