//подтверждение операции private void buttonOK_Click(object sender, EventArgs e) { if (CheckData()) { switch (mode) { case WindowsMode.ADD: currentLocation = new Location(); currentLocation.LocationName = textBoxLocation.Text.Trim(); context.Locations.Add(currentLocation); context.SaveChanges(); break; case WindowsMode.EDIT: currentLocation.LocationName = textBoxLocation.Text.Trim(); context.Entry(currentLocation).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); break; } this.DialogResult = DialogResult.OK; } else { switch (validateInput) { case LocationInputValidate.LocationEmpty: NotifyWarning("Location input is empty!"); break; case LocationInputValidate.LocationNotUnique: NotifyWarning("Location is not unique!"); break; } } }
//удаление устройства private void favoriteDeleteToolStripMenuItem_Click(object sender, EventArgs e) { if (treeViewFavorites.SelectedNode != null && listViewDetails.SelectedItems.Count != 0) { string category = treeViewFavorites.SelectedNode.Text; var item = listViewDetails.SelectedItems[0]; string favName = item.SubItems[0].Text; bool isChanged = false; using (context = new RconfigContext()) { var queryFavorite = (from c in context.Favorites where c.Hostname == favName select c).Single(); if (queryFavorite != null) { queryFavorite.Configs.Clear();//требуется очищать дочерние таблицы данных context.Favorites.Remove(queryFavorite); context.SaveChanges(); isChanged = true; } } //для избежания конфликта контекстов if (isChanged) { LoadCategoryData(category); } } else { NotifyInfo("Please select favorite to edit!"); } }
//подтверждение операции private void buttonOK_Click(object sender, EventArgs e) { if (CheckData()) { switch (mode) { case WindowsMode.ADD: currentCategory = new Category(); currentCategory.CategoryName = textBoxCategory.Text.Trim(); if (checkBoxEnableMode.CheckState == CheckState.Checked) { currentCategory.EnableModeRequired = true; } else { currentCategory.EnableModeRequired = false; } context.Categories.Add(currentCategory); context.SaveChanges(); break; case WindowsMode.EDIT: currentCategory.CategoryName = textBoxCategory.Text.Trim(); if (checkBoxEnableMode.CheckState == CheckState.Checked) { currentCategory.EnableModeRequired = true; } else { currentCategory.EnableModeRequired = false; } context.Entry(currentCategory).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); break; } this.DialogResult = DialogResult.OK; } else { switch (validateInput) { case CategoryInputValidate.CategoryEmpty: NotifyWarning("Category Name is empty!"); break; case CategoryInputValidate.CategoryNotUnique: NotifyWarning("Category Name is already exist!"); break; } } }
//подтверждение операции private void buttonOK_Click(object sender, EventArgs e) { if (CheckData()) { switch (mode) { case WindowsMode.ADD: currentCredential = new Credential(); currentCredential.CredentialName = textBoxCredName.Text.Trim(); currentCredential.Username = textBoxUsername.Text.Trim(); currentCredential.Domain = textBoxDomain.Text.Trim(); currentCredential.Password = textBoxPaassword.Text.Trim(); currentCredential.EnablePassword = textBoxEnablePassword.Text.Trim(); context.Credentials.Add(currentCredential); context.SaveChanges(); break; case WindowsMode.EDIT: currentCredential.CredentialName = textBoxCredName.Text.Trim(); currentCredential.Username = textBoxUsername.Text.Trim(); currentCredential.Domain = textBoxDomain.Text.Trim(); currentCredential.Password = textBoxPaassword.Text.Trim(); currentCredential.EnablePassword = textBoxEnablePassword.Text.Trim(); context.Entry(currentCredential).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); break; } this.DialogResult = DialogResult.OK; } else { switch (validateInput) { case CredentialInputValidate.CredentialNameEmpty: NotifyWarning("Credential name is empty!"); break; case CredentialInputValidate.CredentialNotUnique: NotifyWarning("Credential name is already exist!"); break; case CredentialInputValidate.UsernameEmpty: NotifyWarning("Username is empty!"); break; case CredentialInputValidate.PasswordEmpty: NotifyWarning("Password is empty!"); break; } } }
//проблема с многопоточностью //наверняка нужно создавать новый контекст для каждого потока //или опрашивать и сохранять данные локально с последующей выгрузкой в базу данных private void Connection(FavoriteConnect favConnect) { RemoteTask task = favConnect.task; List <string> commands = favConnect.commands; Favorite fav = favConnect.favorite; //данные для подключения к сетевому устройству ConnectionData data = new ConnectionData(); data.address = fav.Address; data.port = fav.Port; data.username = fav.Credential.Username; data.password = fav.Credential.Password; //по типу протоколу выбираем требуемое подключение string protocol = fav.Protocol.Name; Expect.Expect expect; switch (protocol) { case "Telnet": expect = new TelnetMintExpect(data); break; case "SSH": expect = new SshExpect(data); break; //по умолчанию для сетевых устройств протокол Telnet default: expect = new TelnetMintExpect(data); break; } //если объект expect успешно создан if (expect != null) { //выполняем список команд expect.ExecuteCommands(commands); string result = expect.GetResult(); bool success = expect.isSuccess; string error = expect.GetError(); //если успешно сохраняем конфигурацию устройства if (success) { Config config = new Config(); config.Current = result; config.Date = DateTime.Now; fav.Configs.Add(config); } //создаем отчет о проделанном задании Report report = new Report(); report.Date = DateTime.Now; report.Status = success; report.Info = error; report.Task = task; report.Favorite = fav; context.Reports.Add(report); context.SaveChanges(); } }
//добавить команду private void AddCommand() { currentCommand = new Command(); currentCommand.Name = textBoxName.Text.Trim(); currentCommand.Order = (int)comboBoxOrders.SelectedItem; HashSet <Category> currentCommandCategories = new HashSet <Category>(); foreach (string category in listBoxCurrent.Items) { var queryCategory = (from c in context.Categories where c.CategoryName == category select c).First(); if (queryCategory != null) { currentCommandCategories.Add(queryCategory); } } currentCommand.Categories = currentCommandCategories; context.Commands.Add(currentCommand); context.SaveChanges(); }
//изменяем избранное из базы private void FavoriteEdit() { using (RconfigContext context = new RconfigContext()) { context.Favorites.Attach(currentFavorite); //данные по категории string category = comboBoxCategory.SelectedValue.ToString(); var queryCategory = (from c in context.Categories where c.CategoryName == category select c).FirstOrDefault(); currentFavorite.Category = queryCategory; //----------------------------------------------------- currentFavorite.Hostname = textBoxHostname.Text.Trim(); currentFavorite.Address = textBoxAddress.Text.Trim(); currentFavorite.Port = (int)numericUpDownPort.Value; currentFavorite.Date = DateTime.UtcNow; //данные по местоположению string location = comboBoxLocation.SelectedValue.ToString(); var queryLocation = (from c in context.Locations where c.LocationName == location select c).FirstOrDefault(); if (queryLocation != null) { currentFavorite.Location = queryLocation; } //данные безопасности string credential = comboBoxCredential.SelectedValue.ToString(); var queryCredential = (from c in context.Credentials where c.CredentialName == credential select c).FirstOrDefault(); if (queryCredential != null) { currentFavorite.Credential = queryCredential; } //данные протокола string protocol = comboBoxProtocol.SelectedValue.ToString(); var queryProtocol = (from c in context.Protocols where c.Name == protocol select c).FirstOrDefault(); //проверка currentFavorite.Protocol = queryProtocol; // MessageBox.Show(queryCategory.CategoryName+ queryProtocol.Name+ queryCredential.CredentialName+ queryLocation.LocationName); // MessageBox.Show("RCONFIG"+currentFavorite.Category.CategoryName); //не изменяется проблема!!!! //сохраняем изменения context.Entry(currentFavorite).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } }
//удаление private void deleteCredentialToolStripMenuItem_Click(object sender, EventArgs e) { if (listBoxCredentials.SelectedItem != null) { string credential = listBoxCredentials.SelectedItem.ToString(); var queryCredential = (from c in context.Credentials where c.CredentialName == credential select c).FirstOrDefault(); if (queryCredential != null) { context.Credentials.Remove(queryCredential); context.SaveChanges(); } } }
//добавляем избранное в базу private void FavoriteAdd() { using (RconfigContext context = new RconfigContext()) { currentFavorite = new Favorite(); currentFavorite.Hostname = textBoxHostname.Text.Trim(); currentFavorite.Address = textBoxAddress.Text.Trim(); currentFavorite.Port = (int)numericUpDownPort.Value; currentFavorite.Date = DateTime.UtcNow; //данные по местоположению string location = comboBoxLocation.SelectedValue.ToString(); var queryLocation = (from c in context.Locations where c.LocationName == location select c).FirstOrDefault(); if (queryLocation != null) { currentFavorite.Location = queryLocation; } //данные безопасности string credential = comboBoxCredential.SelectedValue.ToString(); var queryCredential = (from c in context.Credentials where c.CredentialName == credential select c).FirstOrDefault(); if (queryCredential != null) { currentFavorite.Credential = queryCredential; } //данные протокола string protocol = comboBoxProtocol.SelectedValue.ToString(); var queryProtocol = (from c in context.Protocols where c.Name == protocol select c).FirstOrDefault(); currentFavorite.Protocol = queryProtocol; //данные категории string category = comboBoxCategory.SelectedValue.ToString(); var queryCategory = (from c in context.Categories where c.CategoryName == category select c).FirstOrDefault(); currentFavorite.Category = queryCategory; //добавляем избранное в базу данных context.Favorites.Add(currentFavorite); context.SaveChanges();//??? } }
//удаляем существующую категорию private void deleteCategoryToolStripMenuItem_Click(object sender, EventArgs e) { if (listBoxCategory.SelectedItem != null) { string category = listBoxCategory.SelectedItem.ToString(); var queryCategory = (from c in context.Categories where c.CategoryName == category select c).FirstOrDefault(); if (queryCategory != null) { context.Categories.Remove(queryCategory); context.SaveChanges(); LoadData(); } } }
//удаление private void deleteLocationToolStripMenuItem_Click(object sender, EventArgs e) { if (listBoxLocations.SelectedItem != null) { string location = listBoxLocations.SelectedItem.ToString(); var queryLocation = (from c in context.Locations where c.LocationName == location select c).FirstOrDefault(); if (queryLocation != null) { context.Locations.Remove(queryLocation); context.SaveChanges(); LoadData(); } } }
//удалить команду private void deleteCommandToolStripMenuItem_Click(object sender, EventArgs e) { if (listViewCommands.SelectedItems.Count != 0) { using (context = new RconfigContext()) { var item = listViewCommands.SelectedItems[0]; string command = item.SubItems[0].Text; // MessageBox.Show(listBoxCommands.SelectedItem.ToString()); var queryCommand = (from c in context.Commands where c.Name == command select c).FirstOrDefault(); if (queryCommand != null) { context.Commands.Remove(queryCommand); context.SaveChanges(); LoadData(); } } } }
//удаление задачи private void buttonDelete_Click(object sender, EventArgs e) { if (listViewDetails.SelectedItems.Count != 0) { var item = listViewDetails.SelectedItems[0]; int taskId = Int32.Parse(item.SubItems[0].Text); //MessageBox.Show(taskId.ToString()); using (context = new RconfigContext()) { var queryTask = (from c in context.RemoteTasks where c.Id == taskId select c).FirstOrDefault(); if (queryTask != null) { context.RemoteTasks.Remove(queryTask); context.SaveChanges(); listViewDetails.Items.Clear(); LoadData(); } } } }
//добавить задачу private void TaskAdd() { currentTask = new RemoteTask(); currentTask.TaskName = textBoxName.Text.Trim(); currentTask.Description = textBoxDesc.Text.Trim(); currentTask.Date = DateTime.UtcNow; HashSet <Favorite> favs = new HashSet <Favorite>(); //если устройства выбраны по устройствам if (byFavorite) { foreach (var item in checkedListBoxFavorites.CheckedItems) { string favorite = item.ToString(); var queryFav = (from c in context.Favorites where c.Hostname == favorite select c).FirstOrDefault(); if (queryFav != null) { favs.Add(queryFav); } } } //по категориям устройств else { foreach (var item in checkedListBoxFavorites.CheckedItems) { string category = item.ToString(); var queryCategory = (from c in context.Categories where c.CategoryName == category select c).FirstOrDefault(); if (queryCategory != null) { foreach (Favorite fav in queryCategory.Favorites) { favs.Add(fav); } } } } currentTask.Favorites = favs; HashSet <Command> commands = new HashSet <Command>(); foreach (var item in checkedListBoxCommands.CheckedItems) { string command = item.ToString(); var queryCommand = (from c in context.Commands where c.Name == command select c).FirstOrDefault(); if (queryCommand != null) { commands.Add(queryCommand); } } currentTask.Commands = commands; context.RemoteTasks.Add(currentTask); context.SaveChanges(); }
//вставка данных по умолчанию private void FirstInsert() { using (RconfigContext context = new RconfigContext()) { //проверяем данные в БД //если данных нет инициализируем их if (context.Protocols.Count <Protocol>() == 0) { //PROTOCOLS context.Protocols.Add(new Protocol { Name = "SSH", DefaultPort = 22 }); context.Protocols.Add(new Protocol { Name = "Telnet", DefaultPort = 23 }); //CATEGORIES Category routers = new Category { CategoryName = "Routers" }; Category switches = new Category { CategoryName = "Switches" }; Category servers = new Category { CategoryName = "Servers" }; context.Categories.Add(routers); context.Categories.Add(switches); context.Categories.Add(servers); //COMMANDS ICollection <Category> cisco = new HashSet <Category>(); cisco.Add(routers); cisco.Add(switches); context.Commands.Add(new Command { Name = "terminal length 0", Order = 0, Categories = cisco }); context.Commands.Add(new Command { Name = "show running-config", Order = 1, Categories = cisco }); ICollection <Category> vlan = new HashSet <Category>(); vlan.Add(switches); context.Commands.Add(new Command { Name = "show ip vlan brief", Order = 2, Categories = vlan }); //CREDENTIALS context.Credentials.Add(new Credential { CredentialName = "Default", Username = "******", Domain = "domain.com", Password = "******" }); //LOCATIONS context.Locations.Add(new Location { LocationName = "Syslocation" }); context.SaveChanges(); } } }
//исполнение команды для устройства private void Connection(FavoriteConnect favConnect) { RemoteTask task = favConnect.task; List <string> commands = favConnect.commands; Favorite fav = favConnect.favorite; //данные для подключения к сетевому устройству ConnectionData data = new ConnectionData(); data.address = fav.Address; data.port = fav.Port; data.username = fav.Credential.Username; data.password = fav.Credential.Password; data.enableMode = fav.Category.EnableModeRequired; data.enablePassword = fav.Credential.EnablePassword; //по типу протоколу выбираем требуемое подключение string protocol = fav.Protocol.Name; Expect.Expect expect; switch (protocol) { case "Telnet": expect = new TelnetMintExpect(data); break; case "SSH": expect = new SshExpect(data); break; //по умолчанию для сетевых устройств протокол Telnet default: expect = new TelnetMintExpect(data); break; } //если объект expect успешно создан if (expect != null) { //выполняем список команд expect.ExecuteCommands(commands); //если возвращает пустую строку, то выдает исключение string result = expect.GetResult(); bool success = expect.isSuccess; string error = expect.GetError(); //если успешно сохраняем конфигурацию устройства if (success) { Config config = new Config(); config.Current = result ?? "Empty";//если строка пустая, вернуть Empty config.Date = DateTime.Now; fav.Configs.Add(config); Logging(string.Format("TASK {0} : success connection for {0} {1}", taskId, fav.Hostname, fav.Address)); } else { Logging(string.Format("TASK {0} : failed connection for {0} {1}!!!", taskId, fav.Hostname, fav.Address)); } //создаем отчет о проделанном задании Report report = new Report(); report.Date = DateTime.Now; report.Status = success; report.Info = error; report.Task = task; report.Favorite = fav; context.Reports.Add(report); context.SaveChanges(); } }
//импорт в базу данных private void DataImport() { using (RconfigContext context = new RconfigContext()) { bool attributeLoadSuccess = true; //данные по местоположению string location = comboBoxLocations.SelectedValue.ToString(); var queryLocation = (from c in context.Locations where c.LocationName == location select c).FirstOrDefault(); if (queryLocation == null) { attributeLoadSuccess = false; } //данные безопасности string credential = comboBoxCredentials.SelectedValue.ToString(); var queryCredential = (from c in context.Credentials where c.CredentialName == credential select c).FirstOrDefault(); if (queryCredential == null) { attributeLoadSuccess = false; } //данные протокола string protocol = comboBoxProtocols.SelectedValue.ToString(); var queryProtocol = (from c in context.Protocols where c.Name == protocol select c).FirstOrDefault(); if (queryProtocol == null) { attributeLoadSuccess = false; } //данные категории string category = comboBoxCategories.SelectedValue.ToString(); var queryCategory = (from c in context.Categories where c.CategoryName == category select c).FirstOrDefault(); if (queryCategory == null) { attributeLoadSuccess = false; } int port = (int)numericUpDownPort.Value; //если успешно импортировать устройства if (attributeLoadSuccess) { foreach (string address in network.Keys) { string hostname = network[address].ToString(); Favorite fav = new Favorite(); fav.Hostname = hostname; fav.Address = address; fav.Port = port; fav.Protocol = queryProtocol; fav.Location = queryLocation; fav.Credential = queryCredential; fav.Category = queryCategory; fav.Date = DateTime.Now; context.Favorites.Add(fav); } context.SaveChanges(); } else { MessageBox.Show("Attributes load failed!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }