public int Register(string phoneNumber, string password, string name) { try { var userObj = new User() { CreatedDate = DateTime.Now.Date.ToString(), Username = phoneNumber, Password = password, Name = name }; _phonebookContext.User.Add(userObj); _phonebookContext.SaveChanges(); var phonebook = new Phonebook() { Name = $"{name}{phonebook_text}", UserId = userObj.Id }; _phonebookContext.Phonebook.Add(phonebook); _phonebookContext.SaveChanges(); return(userObj.Id); } catch (Exception ex) { return(-1); } }
public ActionResult Delete(int?id) { var contact = db.Contacts.Find(id); if (id == null || contact == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } db.Contacts.Remove(contact); db.SaveChanges(); return(RedirectToAction("Index")); }
private static void ImportContactToDatabase(ContactDTO contactDTO) { if (contactDTO.Name == null) { throw new ArgumentException("Name is required"); } var newContact = new Contact() { Name = contactDTO.Name, Company = contactDTO.Company, Position = contactDTO.Position, Url = contactDTO.Site, Notes = contactDTO.Notes }; if (contactDTO.Emails != null) { newContact.Emails = contactDTO.Emails.Select(e => new Email() { EmailAddress = e }).ToList(); } if (contactDTO.Phones != null) { newContact.Phones = contactDTO.Phones.Select(p => new Phone() { PhoneNumber = p }).ToList(); } var context = new PhonebookContext(); context.Contacts.Add(newContact); context.SaveChanges(); }
private bool RemoveRecursively(string id) { bool succ = false; using (PhonebookContext db = new PhonebookContext(ConnectionStringBuilder.ConnectionString)) { using (var dbContextTransaction = db.Database.BeginTransaction()) { try { RemoveRecursivelyHelper(db, db.Categories.ToList(), db.Categories.Single(c => c.Id.ToString() == id)); int x = db.SaveChanges(); if (x > 0) { succ = true; dbContextTransaction.Commit(); } else { throw new Exception(); } } catch { dbContextTransaction.Rollback(); } } } return(succ); }
private static void ProcessMsg(MessagesDTO msg) { if (msg.Content == null) { throw new ArgumentException("Messages content is required"); } if (msg.DateTime == null) { throw new ArgumentException("Datetime is required"); } if (msg.Recipient == null) { throw new ArgumentException("Recipient is required"); } if (msg.Sender == null) { throw new ArgumentException("Sender is required"); } var context = new PhonebookContext(); var usMsg = new UserMessage() { Content = msg.Content, Date = msg.DateTime, Recipient = context.Users.FirstOrDefault(u => u.Username == msg.Recipient), Sender = context.Users.FirstOrDefault(u => u.Username == msg.Sender) }; context.UserMessages.Add(usMsg); context.SaveChanges(); Console.WriteLine("Message \"{0}\" imported", msg.Content); }
static void Main() { PhonebookContext contexgt = new PhonebookContext(); string jsonPath = @"C:\Users\Maika\Documents\Programming\Homework\Databases Fundamentals\Databases Advanced\ExamWarmup\Football-Author-Solution\Import-Contacts-from-JSON\contacts.json"; List <ContactDTO> contacts = JsonConvert.DeserializeObject <List <ContactDTO> >(File.ReadAllText(jsonPath)); foreach (var contactDto in contacts) { try { if (string.IsNullOrEmpty(contactDto.Name)) { throw new InvalidDataException("Name is required"); } Contact contact = InsertContactIntoDb(contactDto); contexgt.Contacts.Add(contact); contexgt.SaveChanges(); Console.WriteLine($"Contact {contact.Name} imported"); } catch (InvalidDataException e) { Console.WriteLine($"Error: {e.Message}"); } } }
public IHttpActionResult UpdateEntry([FromBody] Phonebook contact) { using (PhonebookContext db = new PhonebookContext()) { var matchNumber = db.Phonebooks.FirstOrDefault(p => p.Number.ToUpper() == contact.Number.ToUpper()); //var matchName = db.Phonebooks.FirstOrDefault(p => p.Name.ToUpper() == contact.Name.ToUpper()); if (matchNumber == null) //|| (matchName == null)) { return(BadRequest("Entry doesn't exist")); // might update but means wont be added to DB - this is a 400 } else //if (matchNumber != null) { matchNumber.Number = contact.Number; matchNumber.Name = contact.Name; matchNumber.Address = contact.Address; db.SaveChanges(); return(Ok()); } //else // (matchName == null)) //{ // matchName.Number = contact.Number; // matchName.Name = contact.Name; // matchName.Address = contact.Address; // db.SaveChanges(); // return Ok(); //} } }
static void Main() { using (StreamReader r = new StreamReader("../../contacts.json")) { var context = new PhonebookContext(); string json = r.ReadToEnd(); JArray googleSearch = JArray.Parse(json); context.Contacts.Count(); foreach (var var in googleSearch) { if (var["name"] != null) { var emailsExist = var["emails"] != null; var phonesExist = var["phones"] != null; var contact = context.Contacts.Add(new Contact { Name = var["name"].ToString(), Company = (var["company"] != null) ? var["company"].ToString() : null, Notes = (var["notes"] != null) ? var["notes"].ToString() : null, Position = (var["position"] != null) ? var["position"].ToString() : null, SiteUrl = (var["site"] != null) ? var["site"].ToString() : null }); if (emailsExist) { List <Email> emails = var["emails"].ToString().Split(',').Select(email => new Email { EmailAdress = email.Split('"')[1] }).ToList(); contact.Emails = new List <Email>(emails); } if (phonesExist) { List <Phone> phones = var["phones"].ToString().Split(',').Select(phone => new Phone { PhoneNumber = phone.Split('"')[1] }).ToList(); contact.Phones = new List <Phone>(phones); } } } context.SaveChanges(); Console.WriteLine("Contacts imported from JSON file!"); } }
static void Main(string[] args) { string text = File.ReadAllText("../../contacts.json"); var jsonSerializer = new JavaScriptSerializer(); var parsedContacts = jsonSerializer.Deserialize <ContactDTO[]>(text); foreach (var contactDTO in parsedContacts) { try { if (contactDTO.Name == null) { throw new ArgumentNullException("Name is required."); } var newContact = new Contact() { Name = contactDTO.Name, Company = contactDTO.Company, Position = contactDTO.Position, Url = contactDTO.Site, Notes = contactDTO.Notes }; if (contactDTO.Emails != null) { newContact.Emails = contactDTO.Emails .Select(e => new Email() { EmailAddress = e }).ToList(); } if (contactDTO.Phones != null) { newContact.Phones = contactDTO.Phones .Select(p => new Phone() { PhoneNumber = p }).ToList(); } var context = new PhonebookContext(); context.Contacts.Add(newContact); context.SaveChanges(); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); } } }
public IActionResult Create([FromBody] Person person) { if (person == null) { return(BadRequest()); } _context.PhonebookEntries.Add(person); _context.SaveChanges(); return(CreatedAtRoute("GetPerson", new { id = person.Id }, person)); }
public PhoneEntries RemoveContact(string searchName, string searchNumber, int phonebookId, int entryId) { _phonebookContext.ChangeTracker.LazyLoadingEnabled = false; var phoneEntry = _phonebookContext.PhoneBookEntries.Where(pe => pe.entry_id == entryId && pe.Phonebook_id == phonebookId).FirstOrDefault(); _phonebookContext.PhoneBookEntries.Remove(phoneEntry); var entry = _phonebookContext.Entries.Where(e => e.Id == entryId).FirstOrDefault(); _phonebookContext.Remove(entry); _phonebookContext.SaveChanges(); var phonebook = _phonebookContext.Phonebook.Where(ph => ph.Id == phonebookId).FirstOrDefault(); IEnumerable <Entry> phoneBookEntries = null; if (!string.IsNullOrEmpty(searchName) || !string.IsNullOrEmpty(searchNumber)) { phoneBookEntries = _phonebookContext.PhoneBookEntries.Where(pe => pe.Phonebook_id == phonebookId).Include(p => p.Entry) .Select(pe => pe.Entry).ToList().Where(e => e.Name.ToLower().Equals(searchName.ToLower()) || e.PhoneNumber.Equals(searchNumber)); } else { phoneBookEntries = _phonebookContext.PhoneBookEntries.Where(pe => pe.Phonebook_id == phonebookId).Include(p => p.Entry) .Select(pe => pe.Entry).ToList(); } var phoneEntries = new PhoneEntries { Id = phonebookId, Entries = phoneBookEntries, Name = phonebook.Name }; return(phoneEntries); }
public void InsertPhonebook(Phonebook _contact) { using (PhonebookContext db = new PhonebookContext()) { try { db.Phonebooks.Add(_contact); db.SaveChanges(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } }
public ActionResult AddContact(string firstName, string lastName, string phoneNumber) { using (PhonebookContext db = new PhonebookContext()) { var contact = new Phonebook(); contact.FirstName = firstName; contact.LastName = lastName; contact.PhoneNumber = phoneNumber; db.Phonebooks.Add(contact); db.SaveChanges(); return(RedirectToAction("Phonebook")); } }
public PhonebookController() : base() { Phonebook p1 = new Phonebook { Name = "Ronan", Number = "1111", Address = "1 Main Street" }; Phonebook p2 = new Phonebook { Name = "James", Number = "2222", Address = "2 Main Street" }; Phonebook p3 = new Phonebook { Name = "Pamela", Number = "3333" }; pCtx.Phonebooks.Add(p1); pCtx.Phonebooks.Add(p2); pCtx.Phonebooks.Add(p3); pCtx.SaveChanges(); }
[Route("DeleteEntry")] // http://localhost:51275/api/Phonebook/DeleteEntry?Number=1111 ** will Delete Ronan public IHttpActionResult DeleteEntry([FromBody] Phonebook contact) { using (PhonebookContext db = new PhonebookContext()) { var matchNumber = db.Phonebooks.FirstOrDefault(p => p.Number.ToUpper() == contact.Number.ToUpper()); if (matchNumber == null) { return(BadRequest("Number not in DB")); // might update but means wont be added to DB - this is a 400 } else { db.Phonebooks.Remove(matchNumber); db.SaveChanges(); return(Ok()); } } }
public PhonebookContext GetPhonebookContext() { var options = new DbContextOptionsBuilder <PhonebookContext>() .UseInMemoryDatabase(databaseName: "InMemoryPhonebookDatabase") .Options; var dbContext = new PhonebookContext(options); var userLogin = new UserLogin() { Username = "******", Password = "******", EmailAddress = "*****@*****.**" }; dbContext.Add(userLogin); dbContext.SaveChanges(); return(dbContext); }
public void UpdatePhonebookContact(Phonebook contact) { using (PhonebookContext db = new PhonebookContext()) { // Loop to look for a match based on name var found = db.Phonebooks.FirstOrDefault(c => c.Name.ToUpper() == contact.Name.ToUpper()); if (found == null) { throw new ArgumentException("No contact found"); } else { found.Number = contact.Number; found.Address = contact.Address; db.SaveChanges(); } } }
public IHttpActionResult AddEntry([FromBody] Phonebook contact) { using (PhonebookContext db = new PhonebookContext()) { var matchNumber = db.Phonebooks.FirstOrDefault(p => p.Number.ToUpper() == contact.Number.ToUpper()); var matchName = db.Phonebooks.FirstOrDefault(p => p.Name.ToUpper() == contact.Name.ToUpper()); if ((matchNumber != null) || (matchName != null)) { return(BadRequest()); // might update but means wont be added to DB - this is a 400 } else { db.Phonebooks.Add(contact); db.SaveChanges(); return(Ok()); } } }
private static void ImportMessageToDatabase(MessageDto messageDto) { if (string.IsNullOrWhiteSpace(messageDto.Content)) { throw new ArgumentException("Content is required"); } if (messageDto.DateTime == null) { throw new ArgumentException("DateTime is required"); } if (messageDto.Recipient == null) { throw new ArgumentException("Recipient is required"); } if (messageDto.Sender == null) { throw new ArgumentException("Sender is required"); } var context = new PhonebookContext(); var recipient = context.Users .Where(u => u.Username == messageDto.Recipient) .FirstOrDefault(); //extracting all info about the recipient var senderId = context.Users .Where(u => u.Username == messageDto.Sender) .Select(u => u.Id) //extracting only the neededd info (id) - CORRECT!!! .FirstOrDefault(); var newMessage = new UserMessage() { Content = messageDto.Content, DateAndTime = messageDto.DateTime, RecipientUserId = recipient.Id, SenderUserId = senderId }; context.UserMessages.Add(newMessage); context.SaveChanges(); }
public void DeleteContact(Phonebook contact) { using (PhonebookContext db = new PhonebookContext()) { try { var found = db.Phonebooks.FirstOrDefault(c => c.Name.ToUpper() == contact.Name.ToUpper()); //Loop to look for a match based on name if (found != null) { db.Phonebooks.Remove(found); Console.WriteLine("Deleting Contact: " + found.Name); db.SaveChanges(); //throw new ArgumentException("Contact could not be found"); } } catch (ArgumentException e) { Console.WriteLine(e.ToString()); } } }
private async void DataGrid1_RowEditEndingAsync(object sender, DataGridRowEditEndingEventArgs e) { progressBar.Visibility = Visibility.Visible; dataGrid1.IsReadOnly = true; GridRow oldItem = null; if (this.dataGrid1.SelectedItem != null) { oldItem = new GridRow(); oldItem.Id = (e.Row.Item as GridRow).Id; oldItem.Number = (e.Row.Item as GridRow).Number; oldItem.IsInternal = (e.Row.Item as GridRow).IsInternal; (sender as DataGrid).RowEditEnding -= DataGrid1_RowEditEndingAsync; (sender as DataGrid).CommitEdit(); (sender as DataGrid).Items.Refresh(); (sender as DataGrid).RowEditEnding += DataGrid1_RowEditEndingAsync; } else { return; } try { var newItem = e.Row.Item as GridRow; bool conn1 = string.IsNullOrWhiteSpace(newItem.Id) && newItem.Id == oldItem.Id; bool conn2 = ((newItem.Number != oldItem.Number) || (newItem.IsInternal != oldItem.IsInternal)) && newItem.Id == oldItem.Id && !string.IsNullOrWhiteSpace(newItem.Id); bool connNested1 = string.IsNullOrEmpty(newItem.Number) && !string.IsNullOrEmpty(oldItem.Number); string id = newItem.Id == null ? "" : newItem.Id.ToString(); string number = newItem.Number; bool isInternal = newItem.IsInternal; await Task.Run(async() => { try { PhonebookContext db = new PhonebookContext(ConnectionStringBuilder.ConnectionString); if (conn1)//insert { if (connNested1) { return; } PhoneNumber phn = new PhoneNumber() { Number = number, IsInternal = isInternal, }; int x = db.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.EnsureTransaction, SqlCammandHelper.CMD_INSERT_INTO_PHONENUMBER_UNDER_CONSTRAINTS , new SqlParameter("@Number", number), new SqlParameter("IsInternal", isInternal) ); if (x > 0) { await Dispatcher.InvokeAsync(() => { ReFillDataGrid(); }); } else { throw new Exception(); } } //update else if (conn2) { var phn = db.PhoneNumbers.SingleOrDefault(r => r.Id.ToString() == id); if (phn != null) { int x = 0; if (phn.Number == number && phn.IsInternal != isInternal) { phn.Number = number; phn.IsInternal = isInternal; x = db.SaveChanges(); } else if (phn.Number != number) { x = db.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.EnsureTransaction, SqlCammandHelper.CMD_UPDATE_INTO_PHONENUMBER_UNDER_CONSTRAINTS, new SqlParameter("@Id", id), new SqlParameter("@Number", number), new SqlParameter("IsInternal", isInternal) ); } if (x > 0) { } else { throw new Exception(); } } else { throw new Exception(); } } } catch { await Dispatcher.InvokeAsync(() => { if (string.IsNullOrWhiteSpace(oldItem.Id)) { newItem.Number = null; newItem.IsInternal = false; observableCollection.Remove(newItem); } else { newItem.Number = oldItem.Number; newItem.IsInternal = oldItem.IsInternal; } (sender as DataGrid).Items.Refresh(); }); } }); } catch { } progressBar.Visibility = Visibility.Collapsed; dataGrid1.IsReadOnly = false; }
public IHttpActionResult CreateContact(ContactModel contact) { context.Contacts.Add(contact); context.SaveChanges(); return(Ok(context.Contacts)); }
private async void btnUpdate_ClickAsync(object sender, RoutedEventArgs e) { treeCategory.IsEnabled = false; popupAlter.IsEnabled = false; bool saveSate = managerInsertOrDelete.CurrentStop; managerInsertOrDelete.CurrentStop = true; try { string txtIdText = txtId.Text; string txtTitleText = txtTitle.Text; //دفترچه تلفن را نباید بتوان تغییر داد if (txtIdText == "1") { throw new Exception(); } await Task.Run(async() => { try { PhonebookContext db = new PhonebookContext(ConnectionStringBuilder.ConnectionString); var cat = db.Categories.SingleOrDefault(r => r.Id.ToString() == txtIdText); if (cat != null) { cat.Title = txtTitleText; int x = db.SaveChanges(); var lastItemUpdated = db.ChangeTracingkInformations.Single(r => r.Action == "Update" && r.TableName == nameof(Category)); await Dispatcher.InvokeAsync(() => { TreeItem item = FindInTreeCategory(txtId.Text); item.Category.Title = cat.Title; txtBlockMsg.Text = ""; popupAlter.IsPopupOpen = false; }); managerInsertOrDelete.LastTimeUpdate = lastItemUpdated.LastTime; } else { throw new Exception(); } } catch { Dispatcher.Invoke(() => { txtBlockMsg.Text = "خطا"; }); } finally { } }); } catch { } finally { managerInsertOrDelete.CurrentStop = saveSate; } popupAlter.IsEnabled = true; treeCategory.IsEnabled = true; }
static void Main(string[] args) { var context = new PhonebookContext(); var json = File.ReadAllText(@"..\..\messages.json"); JavaScriptSerializer ser = new JavaScriptSerializer(); var messages = ser.Deserialize <MessageDto[]>(json); foreach (var messageDto in messages) { bool messagePassedValidation = true; List <string> errorMessages = new List <string>(); if (string.IsNullOrEmpty(messageDto.Content)) { messagePassedValidation = false; errorMessages.Add("Content is required"); } if (string.IsNullOrEmpty(messageDto.Datetime)) { messagePassedValidation = false; errorMessages.Add("Datetime is required"); } if (string.IsNullOrEmpty(messageDto.Recipient)) { messagePassedValidation = false; errorMessages.Add("Recipient is required"); } if (string.IsNullOrEmpty(messageDto.Sender)) { messagePassedValidation = false; errorMessages.Add("Sender is required"); } if (messagePassedValidation) { var userMessage = new UserMessage(); userMessage.Content = messageDto.Content; userMessage.Datetime = DateTime.Parse(messageDto.Datetime); userMessage.Sender = context.Users.FirstOrDefault(u => u.Username == messageDto.Sender); userMessage.Recepient = context.Users.FirstOrDefault(u => u.Username == messageDto.Recipient); context.UserMessages.Add(userMessage); context.SaveChanges(); Console.WriteLine(@"Message ""{0}"" imported", messageDto.Content); } else { // Print all messages foreach (var errorMessage in errorMessages) { Console.WriteLine("Error {0}", errorMessage); } // Print last message Console.WriteLine("Error {0}", errorMessages[errorMessages.Count - 1]); } } }
private async void DataGrid1_PreviewKeyDownAsync(object sender, KeyEventArgs e) { DataGrid dataGrid = sender as DataGrid; if (dataGrid != null) { DataGridRow dataGridRow = (DataGridRow)(dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex)); if (e.Key == Key.Delete && !dataGridRow.IsEditing) { var result = MessageBox.Show( "آیا می خواهید سطر (های) انتخاب شده حذف شوند؟", "حذف", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); if (result == MessageBoxResult.Yes) { try { progressBar.Visibility = Visibility.Visible; dataGrid.IsReadOnly = true; List <string> ids = new List <string>(); var selectedItmes = dataGrid.SelectedItems; foreach (var s in selectedItmes) { GridRow gridRow = (GridRow)s; ids.Add(gridRow.Id); } await Task.Run(() => { try { PhonebookContext db = new PhonebookContext(ConnectionStringBuilder.ConnectionString); var items = db.Employees.RemoveRange(db.Employees.Where(emp => ids.Any(id2 => id2 == emp.Id.ToString()))); int x = db.SaveChanges(); if (x > 0) { Dispatcher.Invoke(() => { ReFillDataGrid(); }); } else { throw new Exception(); } } catch (Exception ex) { Dispatcher.Invoke(() => { e.Handled = true; }); } }); } catch (Exception ex) { e.Handled = true; } finally { progressBar.Visibility = Visibility.Collapsed; dataGrid.IsReadOnly = false; } } else { e.Handled = true; } } } }
//TODO: This is just to easily populate some data in SQLEXPRESS for dev puposes, I have not gone with code first public void SeedData() { var count = _db.PhoneBook.Where(x => x.Id == 1).Count(); if (count == 0) { PhoneBook phoneBook1 = new PhoneBook() { Name = "Family" }; PhoneBook phoneBook2 = new PhoneBook() { Name = "Work" }; PhoneBook phoneBook3 = new PhoneBook() { Name = "Friends" }; List<PhoneBook> phoneBooks = new List<PhoneBook>() { phoneBook1, phoneBook2, phoneBook3 }; _db.PhoneBook.AddRange(phoneBooks); _db.SaveChanges(); List<Entry> entries = new List<Entry>() { new Entry() { Name = "Bob", PhoneBookId = phoneBook1.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Fred", PhoneBookId = phoneBook1.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Frank", PhoneBookId = phoneBook1.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Francesca", PhoneBookId = phoneBook1.Id, PhoneNumber = "0111231236" }, new Entry() { Name = "William", PhoneBookId = phoneBook1.Id, PhoneNumber = "0111231236" }, new Entry() { Name = "Kate", PhoneBookId = phoneBook2.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Catherine", PhoneBookId = phoneBook2.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Chelsea", PhoneBookId = phoneBook2.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Charles", PhoneBookId = phoneBook2.Id, PhoneNumber = "0111231236" }, new Entry() { Name = "Graham", PhoneBookId = phoneBook3.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Susan", PhoneBookId = phoneBook3.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Sheridan", PhoneBookId = phoneBook3.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "George", PhoneBookId = phoneBook3.Id, PhoneNumber = "0111231236" }, new Entry() { Name = "Gregory", PhoneBookId = phoneBook3.Id, PhoneNumber = "0111231236" } }; _db.Entry.AddRange(entries); _db.SaveChanges(); } }
public static void Main(string[] args) { var json = File.ReadAllText("../../contacts.json"); var contactsDto = JsonConvert.DeserializeObject <List <ContactDTO> >(json); var context = new PhonebookContext(); foreach (var contactDto in contactsDto) { try { var contact = new Contact(); if (contactDto.Name != null) { contact.Name = contactDto.Name; } else { contact.Name = contactDto.FirstName + " " + contactDto.LastName; } if (string.IsNullOrWhiteSpace(contact.Name)) { throw new Exception("Name is required"); } contact.Notes = contactDto.Notes; contact.Position = contactDto.Position; contact.Company = contactDto.Company; contact.Site = contactDto.Site; var emails = new List <Email>(); foreach (var email in contactDto.Emails) { emails.Add(new Email() { EmailAddress = email }); } var phones = new List <Phone>(); foreach (var phone in contactDto.Phones) { phones.Add(new Phone() { PhoneNumber = phone }); } contact.Phones = phones; contact.Emails = emails; context.Contacts.Add(contact); context.SaveChanges(); Console.WriteLine("Contact {0} imported", contact.Name); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } }
private async void DataGrid1_PreviewKeyDownAsync(object sender, KeyEventArgs e) { DataGrid dataGrid = sender as DataGrid; if (dataGrid != null) { DataGridRow dataGridRow = (DataGridRow)(dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex)); if (e.Key == Key.Delete && !dataGridRow.IsEditing) { // User is attempting to delete the row var result = MessageBox.Show( "آیا می خواهید سطر (های) انتخاب شده حذف شوند؟", "حذف", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); if (result == MessageBoxResult.Yes) { try { List <string> ids = new List <string>(); var selectedItmes = dataGrid.SelectedItems; foreach (var s in selectedItmes) { GridRow gridRow = (GridRow)s; ids.Add(gridRow.Id); } await Task.Run(() => { try { bool succ = false; using (PhonebookContext db = new PhonebookContext(ConnectionStringBuilder.ConnectionString)) { using (var dbContextTransaction = db.Database.BeginTransaction()) { try { var rows = db.Rows.Where(row => ids.Any(id2 => id2 == row.Id.ToString())).ToList(); rows.ForEach(r => { var employees = r.Employees.ToList(); var phones = r.PhoneNumbers.ToList(); employees.ForEach(emp => { r.Employees.Remove(emp); }); phones.ForEach(ph => { r.PhoneNumbers.Remove(ph); }); db.Rows.Remove(r); }); int x = db.SaveChanges(); if (x > 0) { succ = true; dbContextTransaction.Commit(); } else { throw new Exception(); } } catch { dbContextTransaction.Rollback(); } } } if (succ == false) { throw new Exception(); } } catch (Exception ex) { Dispatcher.Invoke(() => { e.Handled = true; }); } }); } catch (Exception ex) { e.Handled = true; } } else { e.Handled = true; } } } }
protected override void Seed(PhonebookContext context) { if (!context.Users.Any()) { var vGeorgiev = new User() { Username = "******", Fullname = "Vladimir Georgiev", Phonenumber = "0894545454" }; var nakov = new User() { Username = "******", Fullname = "Svetlin Nakov", Phonenumber = "0897878787" }; var ache = new User() { Username = "******", Fullname = "Angel Georgiev", Phonenumber = "0897121212" }; var alex = new User() { Username = "******", Fullname = "Alexandra Svilarova", Phonenumber = "0894151417" }; var petya = new User() { Username = "******", Fullname = "Petya Grozdarska", Phonenumber = "0895464646" }; context.Users.Add(vGeorgiev); context.Users.Add(nakov); context.Users.Add(ache); context.Users.Add(alex); context.Users.Add(petya); context.SaveChanges(); var malinki = new Channel() { Name = "Malinki" }; var softUni = new Channel() { Name = "SoftUni" }; var admins = new Channel() { Name = "Admins" }; var programmers = new Channel() { Name = "Programmers" }; var geeks = new Channel() { Name = "Geeks" }; context.Channels.Add(malinki); context.Channels.Add(softUni); context.Channels.Add(admins); context.Channels.Add(programmers); context.Channels.Add(geeks); context.SaveChanges(); var now = DateTime.Now; var message1 = new ChannelMessage() { ChannelId = malinki.Id, Content = "Hey dudes, are you ready for tonight?", Datetime = now, UserId = petya.Id }; var message2 = new ChannelMessage() { ChannelId = malinki.Id, Content = "Hey Petya, this is the SoftUni chat.", Datetime = now, UserId = vGeorgiev.Id }; var message3 = new ChannelMessage() { ChannelId = malinki.Id, Content = "Hahaha, we are ready!", Datetime = now, UserId = nakov.Id }; var message4 = new ChannelMessage() { ChannelId = malinki.Id, Content = "Oh my god. I mean for drinking beers!", Datetime = now, UserId = petya.Id }; var message5 = new ChannelMessage() { ChannelId = malinki.Id, Content = "We are sure!", Datetime = now, UserId = vGeorgiev.Id }; malinki.ChannelMessages.Add(message1); malinki.ChannelMessages.Add(message2); malinki.ChannelMessages.Add(message3); malinki.ChannelMessages.Add(message4); malinki.ChannelMessages.Add(message5); context.SaveChanges(); } }
private async void btnInsert_ClickAsync(object sender, RoutedEventArgs e) { treeCategory.IsEnabled = false; popupAlter.IsEnabled = false; try { bool saveSate = managerInsertOrDelete.CurrentStop; managerInsertOrDelete.CurrentStop = true; await Task.Run(async() => { Category category = null; Dispatcher.Invoke(() => { category = new Category() { Title = txtTitle.Text, ParentId = int.Parse(txtId.Text), }; }); PhonebookContext db = new PhonebookContext(ConnectionStringBuilder.ConnectionString); category = db.Categories.Add(category); int x = db.SaveChanges(); if (x > 0) { var lastItemInserted = db.ChangeTracingkInformations.Single(r => r.Action == "Insert" && r.TableName == nameof(Category)); await Dispatcher.InvokeAsync(() => { TreeItem item = FindInTreeCategory(txtId.Text); TreeItem newItem = new TreeItem() { Category = category, }; item.Items.Add(newItem); }); managerInsertOrDelete.LastTimeInsert = lastItemInserted.LastTime; managerInsertOrDelete.LastIdInserted = lastItemInserted.LastId; Dispatcher.Invoke(() => { txtBlockMsg.Text = ""; popupAlter.IsPopupOpen = false; }); } else { throw new Exception("خطا"); } }); managerInsertOrDelete.CurrentStop = saveSate; } catch { Dispatcher.Invoke(() => { txtBlockMsg.Text = "خطا"; }); } popupAlter.IsEnabled = true; treeCategory.IsEnabled = true; }
private static void SaveContactInDb(ContactDTO contact) { if (contact.Name == null) { throw new ArgumentException("Name is required"); } var ct = new Contact() { Name = contact.Name }; if (contact.Company != null) ct.Company = contact.Company; if (contact.Site != null) ct.Url = contact.Site; if (contact.Position != null) ct.Postion = contact.Position; if (contact.Notes != null) { ct.Notes = new HashSet<string>(); ct.Notes.Add(contact.Notes); } if (contact.Emails != null) { ct.Emails = new HashSet<Email>(); foreach (var em in contact.Emails.Select(email => new Email() {EmailAddress = email})) { ct.Emails.Add(em); } } if (contact.Phones != null) { ct.Phones = new HashSet<Phone>(); foreach (var ph in contact.Phones.Select(phone => new Phone() {PhoneNumber = phone})) { ct.Phones.Add(ph); } } var context = new PhonebookContext(); context.Contacts.Add(ct); context.SaveChanges(); }
//TODO: This is just to easily populate some data in SQLEXPRESS for dev puposes, I have not gone with code first public void SeedData() { var count = _db.PhoneBook.Where(x => x.Id == 1).Count(); if (count == 0) { PhoneBook phoneBook1 = new PhoneBook() { Name = "Gregory" }; PhoneBook phoneBook2 = new PhoneBook() { Name = "Fred" }; PhoneBook phoneBook3 = new PhoneBook() { Name = "George" }; PhoneBook phoneBook4 = new PhoneBook() { Name = "Gary" }; PhoneBook phoneBook5 = new PhoneBook() { Name = "Susan" }; PhoneBook phoneBook6 = new PhoneBook() { Name = "Adam" }; PhoneBook phoneBook7 = new PhoneBook() { Name = "Brian" }; PhoneBook phoneBook8 = new PhoneBook() { Name = "Bruce" }; PhoneBook phoneBook9 = new PhoneBook() { Name = "Catherine" }; PhoneBook phoneBook10 = new PhoneBook() { Name = "Charles" }; List <PhoneBook> phoneBooks = new List <PhoneBook>() { phoneBook1, phoneBook2, phoneBook3, phoneBook4, phoneBook5, phoneBook6, phoneBook7, phoneBook8, phoneBook9, phoneBook10, }; _db.PhoneBook.AddRange(phoneBooks); _db.SaveChanges(); List <Entry> entries = new List <Entry>() { new Entry() { Name = "Work", PhoneBookId = phoneBook1.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Home", PhoneBookId = phoneBook1.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Mobile", PhoneBookId = phoneBook1.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Home", PhoneBookId = phoneBook2.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Work", PhoneBookId = phoneBook2.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Mobile", PhoneBookId = phoneBook2.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Home", PhoneBookId = phoneBook3.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Work", PhoneBookId = phoneBook3.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Mobile", PhoneBookId = phoneBook3.Id, PhoneNumber = "0111231235" }, new Entry() { Name = "Home", PhoneBookId = phoneBook4.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Home", PhoneBookId = phoneBook5.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Home", PhoneBookId = phoneBook6.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Home", PhoneBookId = phoneBook7.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Home", PhoneBookId = phoneBook8.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Home", PhoneBookId = phoneBook9.Id, PhoneNumber = "0111231234" }, new Entry() { Name = "Home", PhoneBookId = phoneBook10.Id, PhoneNumber = "0111231234" }, }; _db.Entry.AddRange(entries); _db.SaveChanges(); } }