//удаление задачи
        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 ConnectionThread(FavoriteTask favConnect)
        {
            try
            {
                using (RconfigContext ctx = new RconfigContext())
                {
                    var task = (from c in ctx.RemoteTasks
                        where c.Id == favConnect.TaskId
                        select c).Single();

                    List<string> commands = favConnect.Commands;

                    Favorite fav = (from c in ctx.Favorites
                        where c.Id == favConnect.FavoriteId
                        select c).Single();


                    //данные для подключения к сетевому устройству
                    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;
                    data.anonymousLogin = fav.Category.AnonymousLogin;
                    data.timeOut = fav.TimeOut;
                    //по типу протоколу выбираем требуемое подключение
                    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";
                            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;
                        ctx.Reports.Add(report);
                        ctx.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                //логгирование
                Logging(string.Format("TASK {0} failed!!! Exception: {1}", _taskId, ex.StackTrace));
            }

        }
        //изменяем избранное из базы
        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.TimeOut = (int) numericUpDownTimeOut.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 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);
                }

            }
        }
        //добавляем избранное в базу
        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.TimeOut=(int)numericUpDownTimeOut.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();//???
            }
      
        }
示例#6
0
        //вставка данных по умолчанию
        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();
                }
            }
        }  
示例#7
0
 //удаление устройства
 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!");
     }
 }        
示例#8
0
 //метод для сохранения конфигурации
 private void SaveConfiguration()
 {
     try
     {
         using (RconfigContext context = new RconfigContext())
         {
             var fav = (from c in context.Favorites
                 where c.Hostname == _favName
                 select c).Single();
             if (fav != null)
             {
                 DialogResult dialogResult =
                     MessageBox.Show("Do you want to save output to database as configuration?!", "Confirmation",
                         MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                 //предупредить пользователя, что единовременный сбор конфигурации не будет храниться в базе данных
                 //затем сделать сбор конфигурации
                 if (dialogResult == DialogResult.OK)
                 {
                     Config config = new Config();
                     config.Current = _result ?? "Empty";
                     config.Date = DateTime.Now;
                     fav.Configs.Add(config);
                     context.SaveChanges();
                 }
             }
         }
     }
     catch (Exception e)
     {
         richTextBoxConfig.Text = e.StackTrace;
     }
 }
 //удалить команду
 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();
             }
         }
     }
 }