Пример #1
0
        //подгрузка данных по задачам
        private async  void LoadData()
        {
            using (_context = new RconfigContext())
            {
                var queryTasks = await (from c in _context.RemoteTasks
                                        select c).ToListAsync();

                if (queryTasks != null)
                {

                    foreach (RemoteTask task in queryTasks)
                    {
                        var item = new ListViewItem(new[] { 
                    task.Id.ToString(),
                    task.TaskName,
                    task.Description,
                    task.Commands.Count.ToString(),
                    task.Favorites.Count.ToString(),
                    task.Date.ToString()});

                        listViewDetails.Items.Add(item);
                    }
                }
            }
        }
 //подгрузка требуемых данных
 private async void LoadData()
 {
     using (context = new RconfigContext())
     {
         var queryFavs = await (from c in context.Favorites
                         select c).ToListAsync();
         switch (filter)
         {
             case FavoriteFilter.ByHostname:
                 var queryHostname = from c in queryFavs
                                     select c.Hostname;
                 comboBoxFavs.DataSource = queryHostname.ToList();
                 break;
             case FavoriteFilter.ByIPAddress:
                 var queryAddresses = from c in queryFavs
                                     select c.Address;
                 comboBoxFavs.DataSource = queryAddresses.ToList();
                 break;
         }
     }          
     if (prevHostname != null)
     {
         comboBoxFavs.SelectedItem = prevHostname;
         LoadConfigurationData(prevHostname);
     }
 }
Пример #3
0
 //подгрузка данных
 private async void LoadData()
 {
     using(RconfigContext context=new RconfigContext())
     {
         var queryCategory=(from c in context.Categories
                           where c.CategoryName==_category
                           select c).Single();
         if (queryCategory != null)
         {
             var queryCommands = await (from c in context.Commands                                      
                                 select c).ToListAsync();
             //пробегаемся по списку команд отсортированну
             foreach (Command command in queryCommands.OrderBy(c=>c.Order))
             {
                 foreach (Category category in command.Categories)
                 {
                     if (category.CategoryName == this._category)
                     {
                         checkedListBoxCommand.Items.Add(command.Name);
                     }
                 }
             }                    
         }
     }
 }
Пример #4
0
 //проверка валидности идентификатора задачи
 private bool CheckTask(int taskId)
 {
     using (RconfigContext ctx = new RconfigContext())
     {
         var queryTask = (from c in ctx.RemoteTasks
                          where c.Id == taskId
                          select c).Single();
         if (queryTask != null)
             return true;
         else
             return false;
     }
 }
Пример #5
0
 //удалить команду
 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();
             }
         }
     }
 }
Пример #6
0
        private void LoadData()
        {
            using (RconfigContext context = new RconfigContext())
            {
                var queryCredentials = (from c in context.Credentials
                                        select c.CredentialName).ToList();
                comboBoxCredentials.DataSource = queryCredentials;

                var queryCategories = (from c in context.Categories
                                       select c.CategoryName).ToList();
                comboBoxCategories.DataSource = queryCategories;

                var queryProtocols = (from c in context.Protocols
                                      select c.Name).ToList();
                comboBoxProtocols.DataSource = queryProtocols;

                var queryLocations = (from c in context.Locations
                                      select c.LocationName).ToList();
                comboBoxLocations.DataSource = queryLocations;
            }
        }
Пример #7
0
        //подгружаем данные
        private async void LoadData()
        {
            using (context = new RconfigContext())
            {
                var queryCommands = await (from c in context.Commands
                                           select c).ToListAsync();

                if (queryCommands != null)
                {
                    listViewCommands.Items.Clear();
                    foreach (Command command in queryCommands)
                    {
                        var item = new ListViewItem(new[] {
                        command.Name,
                        command.Order.ToString()
                    });
                        listViewCommands.Items.Add(item);
                    }
                }
            }
        }
Пример #8
0
        //подгрузка данных о категории для отображения
        private async void LoadData()
        {
            using (context = new RconfigContext())
            {
                var queryCategory = await (from c in context.Categories
                                           select c).ToListAsync();

                foreach (Category category in queryCategory)
                {
                    TreeNode node = new TreeNode();
                    node.Name = category.CategoryName;
                    node.Text = category.CategoryName;
                    //foreach (Favorite favorite in category.Favorites)
                    //{
                    //    TreeNode childNode = new TreeNode();
                    //    childNode.Text = favorite.Hostname;
                    //}
                    treeViewFavorites.Nodes.Add(node);
                }
            }
            //подгружать будем только данные верхнего уровня каталоги
            //LoadChildData();
           
        }
Пример #9
0
        //подгружаем данные
        private async void LoadData()
        {
            using (RconfigContext context = new RconfigContext())
            {
                var queryCredentials = await (from c in context.Credentials
                                              select c.CredentialName).ToListAsync();
                comboBoxCredential.DataSource = queryCredentials;

                var queryCategories = await (from c in context.Categories
                                             select c.CategoryName).ToListAsync();
                comboBoxCategory.DataSource = queryCategories;

                var queryProtocols = await (from c in context.Protocols
                                            select c.Name).ToListAsync();
                comboBoxProtocol.DataSource = queryProtocols;

                var queryLocations = await (from c in context.Locations
                                            select c.LocationName).ToListAsync();
                comboBoxLocation.DataSource = queryLocations;
            }
            //если режим редактирования, подгрузить данные избранного
            if (mode == WindowsMode.EDIT)
                LoadPrevData();
        }
 //просмотр конфигурации устройства
 private void openConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (listViewConfig.SelectedItems.Count != 0)
     {
         var item = listViewConfig.SelectedItems[0];
         int configId = Int32.Parse(item.SubItems[0].Text);
         using (context = new RconfigContext())
         {
             var queryConfig = (from c in context.Configs
                                where c.Id == configId
                                select c).FirstOrDefault();
             if (queryConfig != null)
             {
                 Config_Watcher frm = new Config_Watcher(queryConfig);
                 DialogResult result = frm.ShowDialog();
                 if (result == DialogResult.OK)
                 {
                     //*******************************
                 }
             }
         }
     }            
 }
Пример #11
0
 //смена порта на порт по умолчанию для выбранного протокола
 private void comboBoxProtocol_SelectedIndexChanged(object sender, EventArgs e)
 {
     using (RconfigContext context = new RconfigContext())
     {
         //подгружаем данные о портах по умолчанию для выбранного протокола
         var queryPort = (from c in context.Protocols
                          where c.Name == comboBoxProtocols.SelectedValue.ToString()
                          select c).FirstOrDefault();
         if (queryPort != null)
             numericUpDownPort.Value = queryPort.DefaultPort;
     }
 }
Пример #12
0
        //импорт в базу данных
        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);
                }

            }
        }
Пример #13
0
        //подгружаем предыдущие данные для редактирования
        private void LoadPrevData()
        {
            using (RconfigContext context = new RconfigContext())
            {
                var queryPrevFavorite = (from c in context.Favorites
                                         where c.Hostname == prevFavName
                                         select c).FirstOrDefault();
                //если избранное было найдено подгружаем данные
                if (queryPrevFavorite != null)
                {
                    //сохраняем наше избранное 
                    currentFavorite = queryPrevFavorite;

                    //редактируем данные формы
                    textBoxHostname.Text = prevFavName;
                    textBoxAddress.Text = queryPrevFavorite.Address;
                    numericUpDownPort.Value = queryPrevFavorite.Port;
                    numericUpDownTimeOut.Value = queryPrevFavorite.TimeOut;

                    //проверить
                    var credential = queryPrevFavorite.Credential.CredentialName;
                    var location = queryPrevFavorite.Location.LocationName;
                    var protocol = queryPrevFavorite.Protocol.Name;
                    var category = queryPrevFavorite.Category.CategoryName;              

                    comboBoxCredential.SelectedItem = credential;
                    comboBoxLocation.SelectedItem = location;
                    comboBoxProtocol.SelectedItem = protocol;                   
                    comboBoxCategory.SelectedItem = category;
                  
                }
                else
                {
                    //если в базе данных не удалось обнаружить избранное с указанным именем, то оставляем форму без изменений
                    mode = WindowsMode.ADD;
                }
            }
        }
Пример #14
0
 //подгрузка данных при выборе избранного
 //!!! не используется
 private void LoadFavoriteData(string favorite)
 {
     using (context = new RconfigContext())
     {
         var queryFavorite = (from c in context.Favorites
                              where c.Hostname == favorite
                              select c).FirstOrDefault();
         if (queryFavorite != null)
         {
             listViewDetails.Items.Clear();
             var item = new ListViewItem(new[] { queryFavorite.Hostname,
             queryFavorite.Address,
             queryFavorite.Port.ToString(),
             queryFavorite.Protocol.Name,
             queryFavorite.Location.LocationName });
             listViewDetails.Items.Add(item);
         }
     }
 }
Пример #15
0
        //изменяем избранное из базы
        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 buttonCompare_Click(object sender, EventArgs e)
        {
            //чтобы сравнить необходимо выбрать две конфигурации
            if (listViewConfig.SelectedItems.Count >= 0)//==2
            {
                using (context = new RconfigContext())
                {
                    var item1 = listViewConfig.SelectedItems[0];
                    int configId1 = Int32.Parse(item1.SubItems[0].Text);
                    var queryConfig1 = (from c in context.Configs
                                        where c.Id == configId1
                                        select c).FirstOrDefault();

                    var item2 = listViewConfig.SelectedItems[1];
                    int configId2 = Int32.Parse(item2.SubItems[0].Text);

                    var queryConfig2 = (from c in context.Configs
                                        where c.Id == configId2
                                        select c).FirstOrDefault();
                    //если конфигурации успешно подгружены
                    if (queryConfig1 != null && queryConfig2 != null)
                    {
                        string config1 = queryConfig1.Current;
                        string date1 = queryConfig1.Date.ToString();
                        string config2 = queryConfig2.Current;
                        string date2 = queryConfig2.Date.ToString();
                        if (queryConfig1.Date < queryConfig2.Date)
                        {
                            //отправляем данные на форму                  
                            ConfigDiffer frm = new ConfigDiffer(config1, config2, date1, date2);
                            frm.ShowDialog();
                        }
                        else
                        {
                            //отправляем данные на форму                  
                            ConfigDiffer frm = new ConfigDiffer(config2, config1, date2, date1);
                            frm.ShowDialog();
                        }
                       
                    }
                }
            }
            else
            {
                NotifyInfo("Please choose 2 config for compare!");
            }
        }
Пример #17
0
        //проверка уникальности адреса
        //не используется!!!
        private bool isUniqueAddress()
        {
            bool uniqueAddress = true;
            string address = textBoxAddress.Text.Trim();
            using (RconfigContext context = new RconfigContext())
            {
                context.Favorites.ToList().ForEach(fav =>
                {
                    if (fav.Address == address)
                    {
                        uniqueAddress = false;
                        validateInput = FavoriteInputValidate.AddressNotUnique;
                    }

                });
            }
            return uniqueAddress;
        }
Пример #18
0
        //проблема с многопоточностью
        //создаем новый контекст для каждого потока
        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 LoadConfigurationData(string favorite)
 {            
     switch (filter)
     {
         case FavoriteFilter.ByHostname:
             using (context = new RconfigContext())
             {
                 var queryByHostname = (from c in context.Favorites
                                        where c.Hostname == favorite
                                        select c).FirstOrDefault();//если использовать Single, выкидывает исключение
                 if (queryByHostname != null)
                 {                            
                     listViewConfig.Items.Clear();
                     //пройтись по списку конфигураций устройства, отсортированный по ID
                     foreach (Config config in queryByHostname.Configs.OrderByDescending(p => p.Id)) 
                     {
                         //если используется фильтр по дате
                         if (useDateFilter)
                         {
                             if (config.Date.Value.Year == dateFilter.Year
                                 & config.Date.Value.Month == dateFilter.Month
                                 & config.Date.Value.Day == dateFilter.Day)
                             {
                                 var item = new ListViewItem(new[] { 
                             config.Id.ToString(),
                             config.Date.ToString()
                             });
                                 listViewConfig.Items.Add(item);
                             }
                         }
                         //если не используется фильтр по времени
                         else
                         {
                             var item = new ListViewItem(new[] { 
                             config.Id.ToString(),
                             config.Date.ToString()
                             });
                             listViewConfig.Items.Add(item);
                         }
                     }
                 }
                 else
                 {
                     NotifyInfo("Favorite not found!");
                 }
             }
             break;
         case FavoriteFilter.ByIPAddress:
             using (context = new RconfigContext())
             {
                 var queryByAddress = (from c in context.Favorites
                                       where c.Address == favorite
                                       select c).FirstOrDefault();
                 if (queryByAddress != null)
                 {
                     listViewConfig.Items.Clear();
                     //пройтись по списку конфигураций устройства, отсортированный по ID
                     foreach (Config config in queryByAddress.Configs.OrderByDescending(p => p.Id))
                     {
                         //если используется фильтр по дате
                         if (useDateFilter)
                         {
                             if (config.Date.Value.Year == dateFilter.Year
                                 & config.Date.Value.Month == dateFilter.Month
                                 & config.Date.Value.Day == dateFilter.Day)
                             {
                                 var item = new ListViewItem(new[] { 
                             config.Id.ToString(),
                             config.Date.ToString()
                             });
                                 listViewConfig.Items.Add(item);
                             }
                         }
                         //если не используется фильтр по времени
                         else
                         {
                             var item = new ListViewItem(new[] { 
                             config.Id.ToString(),
                             config.Date.ToString()
                             });
                             listViewConfig.Items.Add(item);
                         }
                     }
                 }
                 else
                 {
                     NotifyInfo("Favorite not found!");
                 }
             }
             break;
     }
 }
Пример #20
0
        //поиск по указанному паттерну
        #region SEARCH
        //поиск избранного устройства
        private void toolStripButtonSearch_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(toolStripComboBoxSearch.Text))
            {
                UseWaitCursor = true;
                //MessageBox.Show(toolStripComboBoxSearch.Text);
                using (RconfigContext context = new RconfigContext())
                {
                    bool isCleared = false;//для проверка очищался у нас listview
                    string pattern = toolStripComboBoxSearch.Text.Trim();
                    var queryFavorites = from c in context.Favorites
                                         select c;
                    //nested query
                    var filterQuery = queryFavorites;

                    if (byAddressToolStripMenuItem.CheckState == CheckState.Checked)//фильтр поиска
                    {
                        //ищем схожести по паттерну
                        filterQuery = from c in queryFavorites
                                      where c.Address.Contains(pattern) && c.Address.EndsWith(pattern)
                                      select c;
                        //если запрос не пустой
                        if (filterQuery != null)
                        {
                            //делаем проверку очищался у нас listview
                            if (!isCleared)
                            {
                                //если не очищался, очищаем
                                listViewDetails.Items.Clear();
                                isCleared = true;
                            }
                            //добавляем наши устройства
                            AddFavoritesFromQuery(filterQuery);
                        }
                    }
                    if (byHostnameToolStripMenuItem.CheckState == CheckState.Checked)//фильтр поиска
                    {
                        filterQuery = from c in queryFavorites
                                      where c.Hostname.Contains(pattern) && c.Hostname.EndsWith(pattern)
                                      select c;
                        if (filterQuery != null)
                        {
                            if (!isCleared)
                            {
                                listViewDetails.Items.Clear();
                                isCleared = true;
                            }
                            AddFavoritesFromQuery(filterQuery);
                        }
                    }
                    if (byLocationToolStripMenuItem.CheckState == CheckState.Checked)//фильтр поиска
                    {
                        filterQuery = from c in queryFavorites
                                      where c.Location.LocationName.Contains(pattern) && c.Location.LocationName.EndsWith(pattern)
                                      select c;
                        if (filterQuery != null)
                        {
                            if (!isCleared)
                            {
                                listViewDetails.Items.Clear();
                                isCleared = true;
                            }
                            AddFavoritesFromQuery(filterQuery);
                        }
                    }
                }
                UseWaitCursor = false;
            }
        }
Пример #21
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!");
     }
 }        
Пример #22
0
        //подгрузка данных при выборе категории
        private void LoadCategoryData(string category)
        {
            using (context = new RconfigContext())
            {
                var queryCategory = (from c in context.Categories
                                     where c.CategoryName == category
                                     select c).FirstOrDefault();

                if (queryCategory != null)
                {
                    listViewDetails.Items.Clear();
                    foreach (Favorite fav in queryCategory.Favorites)
                    {
                        var item = new ListViewItem(new[] { fav.Hostname,
                        fav.Address,
                        fav.Port.ToString(),
                        fav.Protocol.Name,
                        fav.Location.LocationName });
                        listViewDetails.Items.Add(item);
                    }

                }
            }
        }
Пример #23
0
 //подключение к сетевому устройству
 private string Connection(List<string> commands)
 {
     string resultStr = string.Empty;
     try
     {
         using (RconfigContext context = new RconfigContext())
         {
             var fav = (from c in context.Favorites
                 where c.Hostname == _favName
                 select c).Single();
             if (fav != null)
             {
                 //данные для подключения к сетевому устройству
                 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;
                 }
                 // richTextBoxConfig.Text += "Device configuration checked..."+Environment.NewLine;
                 //если объект expect успешно создан
                 if (expect != null)
                 {
                     //выполняем список команд
                     expect.ExecuteCommands(commands);
                     string result = expect.GetResult();
                     bool success = expect.isSuccess;
                     string error = expect.GetError();
                     //если успешно сохраняем конфигурацию устройства
                     if (success && !string.IsNullOrWhiteSpace(result))
                     {
                         //richTextBoxConfig.Text= "SUCCESS: " + result;
                         //DialogResult dialogResult = MessageBox.Show("Do you want to save this configuration to database?!","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();
                         //}
                         return result;
                     }
                     else if (success && string.IsNullOrWhiteSpace(result))
                     {
                         //richTextBoxConfig.Text= "Output is empty! Something wrong with device configuration. Please check!";
                         return "Output is empty! Something wrong with device configuration. Please check!";
                     }
                     else
                     {
                         //richTextBoxConfig.Text= "FAILED: " + error;
                         return "FAILED: " + error;
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         return e.StackTrace;
     }
     return resultStr;
 }
Пример #24
0
        //добавляем избранное в базу
        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();//???
            }
      
        }
Пример #25
0
        //удаление задачи
        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();
                    }
                }
            }
        }
Пример #26
0
 //!!! не используется
 //подгружаем дочерние данные избранные
 private void LoadChildData()
 {
     using (context = new RconfigContext())
     {
         foreach (TreeNode node in treeViewFavorites.Nodes)
         {
             // node.Nodes.Clear();//при использовании альтернативы
             string nodeGroup = node.Text;
             var queryGroup = (from category in context.Categories
                               where category.CategoryName == nodeGroup
                               select category).FirstOrDefault();
             if (queryGroup != null)
             {
                 foreach (Favorite fav in queryGroup.Favorites)
                 {
                     TreeNode childNode = new TreeNode();
                     childNode.Name = fav.Hostname;
                     childNode.Text = fav.Hostname;
                     node.Nodes.Add(childNode);
                 }
             }
         }
     }
     //treeViewFavorites.Refresh();
     //не срабатывает при добавлении устройства, при удалении срабатывает
 }               
Пример #27
0
        //вариант прохождения в цикле обхода и сбора конфигураций с устройств по задаче
        //проверяется корректность идентификатора задачи
        //затем собираются данные по командам доступные для устройства
        //затем запускается сбор конфигураций
        #region LOOP USAGE
        //метод опроса в цикле
        private void LoopMethod(int taskId)
        {
            _context = new RconfigContext();

            var queryTask = (from c in _context.RemoteTasks
                             where c.Id == taskId
                             select c).FirstOrDefault();
            //записать в логи операция началась
            if (queryTask != null)
            {
                Logging(string.Format("TASK {0} started... LOOP METHOD ", taskId));
                LoadConfiguration(queryTask);
                //записать в логи успешное завершение
                Logging(string.Format("TASK {0} finished...", taskId));
            }
            else
            {
                //записать в логи провал
                Logging(string.Format("TASK {0} failed!!! Not correct task ID!!!", taskId));
            }
        }
Пример #28
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();
                }
            }
        }  
Пример #29
0
        //многопоточный вариант обхода и сбора конфигураций с устройств по задаче
        #region TASK PARALLEL USAGE
        //возможен конфликт при параллельной вставке данных
        //требуется протестировать
        private void LoadConfigurationThread(int taskId)
        {
            using (RconfigContext context = new RconfigContext())
            {
                var task = (from c in context.RemoteTasks
                            where c.Id == taskId
                            select c).FirstOrDefault();

                if (task != null)
                {
                    List<Task> taskRunnerManager = new List<Task>();
                    //таймер
                    DateTime starTime = DateTime.Now;
                    try
                    {
                        Logging(string.Format("TASK {0} started... THREADING", taskId));
                        //если количество избранных равна нулю коэффициент ожидания равен 1
                        //int waiter = (task.Favorites.Count>0) ? task.Favorites.Count : 1;
                        foreach (Favorite fav in task.Favorites)
                        {                            
                            List<string> commands = new List<string>();
                            //проходим по списку команд, выявляем соответствие используемой команды и категории избранного               
                            foreach (Command command in task.Commands.OrderBy(c => c.Order))
                            {
                                foreach (Category category in command.Categories)
                                {
                                    if (fav.Category.CategoryName == category.CategoryName)
                                    {
                                        commands.Add(command.Name);
                                    }
                                }
                            }
                            //многопоточность
                            //устанавливаем соединение
                            FavoriteTask connect = new FavoriteTask();
                            connect.Commands = commands;
                            connect.FavoriteId = fav.Id;
                            connect.TaskId = task.Id;
                            
                            //создаем задачу и добавляем ее в менеджер
                            Task taskRunner = Task.Factory.StartNew(() =>
                                ConnectionThread(connect));
                            taskRunnerManager.Add(taskRunner);
                        }                        
                        //дожидаемся пока выполняться все задания                       
                        Task.WaitAll(taskRunnerManager.ToArray());
                    }
                    catch (Exception ex)
                    {
                        //логгирование
                        Logging(string.Format("TASK {0} failed!!! Exception: {1}", taskId, ex.StackTrace));
                    }
                    finally
                    {
                        //таймер
                        DateTime endTime = DateTime.Now;
                        TimeSpan diffSpan = endTime-starTime;
                        Logging(string.Format("TASK {0} finished in {1} seconds ", taskId, diffSpan.Seconds));
                        //************************************************************
                        //создаем событие и уведомляем о том, что все задачи выполнены
                        taskCompleted();
                    }
                }
                else
                {
                    //записать в логи провал
                    Logging(string.Format("TASK {0} failed!!! Not correct task ID!!!", taskId));
                }
            }
        }
Пример #30
0
        //проверка на уникальность хоста
        private bool IsUniqueHostname()
        {
            bool uniqueHostname = true;          
            string hostname = textBoxHostname.Text.Trim();
            using (RconfigContext context = new RconfigContext())
            {
                context.Favorites.ToList().ForEach(fav =>
                {
                    if (fav.Hostname == hostname)
                    {
                        uniqueHostname = false;
                        validateInput = FavoriteInputValidate.HostnameNotUnique;
                    }

                });
            }
            return uniqueHostname;
        }