Esempio n. 1
0
        public void Initialize(IScriptExecutorBase Executor)
        {
            DebugEx.WriteLine("Initializing PGTNetworkDiscovery CustomActionHandler... ", DebugLevel.Informational);
            _terminated   = false;
            local_dataset = new CDPDataSet();
            local_dataset.Clear();
            ScriptSettings = SettingsManager.GetCurrentScriptSettings();
            Guid engineID = Executor.EngineID;

            // search an existing inventory file and load. used later for checking domain boundary
            InventoryFileName = string.Format("{0}{1}{2}.xml", Helper.GetWorkingDirectory(), Options.Default.InventoryDBDirectory, engineID.ToString());
            DebugEx.WriteLine(string.Format("Checking for pre-existing inventory file {0}... ", InventoryFileName), DebugLevel.Informational);
            if (File.Exists(InventoryFileName))
            {
                try
                {
                    local_dataset.ReadXml(InventoryFileName);
                    InventoryPreProvisioned = true;
                    AllowRecursion          = local_dataset.Parameters.First()?.AllowRecursion ?? Options.Default.MRUActiveDiscovery;
                    DebugEx.WriteLine(string.Format("Inventory file loaded successfully. Active discovery is {0}.", AllowRecursion ? "enabled" : "disabled"), DebugLevel.Informational);
                }
                catch (Exception Ex)
                {
                    DebugEx.WriteLine(string.Format("Error loading inventory file : {0}", Ex.InnerExceptionsMessage()));
                }
            }
            else
            {
                AllowRecursion = Options.Default.MRUActiveDiscovery;
                DebugEx.WriteLine(string.Format("File {0} does not exist. Active discovery is {1}.", InventoryFileName, AllowRecursion ? "enabled" : "disabled"), DebugLevel.Informational);
            }
        }
 public bool Initialize(IScriptableSession session)
 {
     _session       = session;
     ScriptSettings = SettingsManager.GetCurrentScriptSettings();
     _versionInfo   = session.ExecCommand("show version");
     _hostName      = session.GetHostName();
     return(_versionInfo.ToLowerInvariant().Contains("junos"));
 }
 /// <summary>
 /// Open terminal connection to target currently selected
 /// </summary>
 /// <param name="TargetID"></param>
 private void ConnectToTarget()
 {
     if (lvTargets.SelectedItems.Count == 1)
     {
         int            TargetID = (int)lvTargets.SelectedItems[0].Tag;
         TerminalWindow term;
         string         host = string.Empty;
         try
         {
             ConfigDS.ConfigTargetsRow[] targets = configDS.ConfigTargets.Select(string.Format("ConfigTargetID = {0}", TargetID)) as ConfigDS.ConfigTargetsRow[];
             if (targets.Length > 0)
             {
                 ConfigDS.ConfigTargetsRow selectedTarget = targets[0];
                 host = selectedTarget.TargetIP;
                 PGTDataSet.ScriptSettingRow _localScriptSettings = PGT.Common.SettingsManager.GetCurrentScriptSettings(this.pgtDataSet);
                 ConnectionParameters        CP = new ConnectionParameters
                 {
                     DeviceIP       = selectedTarget.TargetIP,
                     Protocol       = (ConnectionProtocol)Enum.Parse(typeof(ConnectionProtocol), selectedTarget.Protocol, true),
                     Port           = selectedTarget.IsPortNull() ? 0 : selectedTarget.Port,
                     DeviceVendor   = selectedTarget.DeviceVendor,
                     JumpServer     = selectedTarget.JumpServerIP.Trim(),
                     LogonUserName  = _localScriptSettings.ScriptingUserName,
                     EnablePassword = _localScriptSettings.DeviceEnablePassword,
                     LogonPassword  = _localScriptSettings.ScriptingPassword,
                     AuthType       = (PGTTermAuthType)Enum.Parse(typeof(PGTTermAuthType), _localScriptSettings.TerminalAuthType),
                     LineFeedRule   = (LineFeedRule)Enum.Parse(typeof(LineFeedRule), _localScriptSettings.TerminalLineFeedRule),
                     EncodingType   = (EncodingType)Enum.Parse(typeof(EncodingType), _localScriptSettings.TerminalEncoding),
                     TerminalType   = (TerminalType)Enum.Parse(typeof(TerminalType), _localScriptSettings.TerminalType),
                     NewLine        = (NewLine)Enum.Parse(typeof(NewLine), _localScriptSettings.TerminalTransmitNL)
                 };
                 var t = from Form form in Application.OpenForms where form is TerminalWindow select form;
                 if (t.Count() > 0)
                 {
                     term = (TerminalWindow)t.ElementAt(0);
                 }
                 else
                 {
                     term = new TerminalWindow();
                 }
                 term.MdiParent = this.MdiParent;
                 term.Show();
                 term.BringToFront();
                 term.ConnectDisconnectTask(ConnectionTaskAction.Connect, true, CP);
             }
             else
             {
                 MessageBox.Show("Unable to open a terminal because the script target was not found.", "Cannot open terminal", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
             }
         }
         catch (Exception Ex)
         {
             MessageBox.Show(string.Format("An error occurred while opening connection to {0}. The error was : {1}", host, Ex.Message), "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Esempio n. 4
0
        public virtual void ProcessCDPResult(string command_result, CDPDataSet.DevicesRow parent_device, CDPDataSet ds)
        {
            if (command_result.IndexOf("CDP is not enabled") >= 0)
            {
                parent_device.CDP_status = false;
            }
            else
            {
                string[] cdp_lines = command_result.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                CDPDataSet.DevicesRow current_device = null; // As going through the CDP output lines, this is the actual neighbor
                string currentDeviceName             = "";
                string currentDeviceIP = "";
                CDPDataSet.NeighboursRow    new_neigbor    = null; // This is the neighbor created for current_device as a neighbor of parent_device
                PGTDataSet.ScriptSettingRow ScriptSettings = SettingsManager.GetCurrentScriptSettings();
                // As the ip address must be unique for each device, adding a device with ip address of nocdpip constant would fail for the second time
                // To overcome this issue, we do indexing for devices with no ip address (such as VMware ESX hosts)
                int nocdpip_index = 0;
                foreach (string line in cdp_lines)
                {
                    DebugEx.WriteLine(String.Format("CDP2VISIO : parsing cdp neighbor row [ {0} ]", line), DebugLevel.Full);
                    try
                    {
                        bool isVMWareESX = false;

                        #region Check for DeviceID line and set currentDeviceName accordingly
                        if (line.IndexOf(DeviceID()) >= 0)
                        {
                            try
                            {
                                if (new_neigbor != null)
                                {
                                    ds.Neighbours.AddNeighboursRow(new_neigbor);
                                }
                            }
                            catch (Exception Ex)
                            {
                                // Depending on discovery list, under special circumstances it can happen that we try to add a new neighbor row
                                // with the same connection parameters (same parent, neighbor and interfaces) that will violate unique key constraint
                                DebugEx.WriteLine(String.Format("CDP2VISIO : Error storing neighbor row : {0}", Ex.InnerExceptionsMessage()), DebugLevel.Warning);
                            }
                            new_neigbor = null;
                            string[] words = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                            currentDeviceName = words[2].Trim();;
                            currentDeviceIP   = "";
                            DebugEx.WriteLine(String.Format("CDP2VISIO : CDPParser found a new neighbor : {0}", currentDeviceName), DebugLevel.Informational);
                        }
                        #endregion

                        if (currentDeviceName == "")
                        {
                            continue;
                        }

                        #region Check for IPAddress line and set currentDeviceIP accordingly
                        if (line.IndexOf(IPAddress()) >= 0)
                        {
                            string[] words_in_line = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                            currentDeviceIP = words_in_line[2].Trim();
                            if (currentDeviceIP == "")
                            {
                                DebugEx.WriteLine(String.Format("CDP2VISIO : cdp is not reporting ip address for neighbor {0}", currentDeviceName), DebugLevel.Debug);
                                currentDeviceIP = string.Format("{0}_{1}", nocdpip, nocdpip_index);
                                nocdpip_index++;
                            }
                        }
                        #endregion

                        #region Check whether the Platform is VMware ESX
                        if (line.Trim().StartsWith("Platform:"))
                        {
                            string[] words = line.SplitByComma();
                            // words[0] should be PlatForm, words[1] is Capabilities
                            isVMWareESX = words[0].ToLowerInvariant().IndexOf("vmware esx") >= 0;
                            if (isVMWareESX)
                            {
                                DebugEx.WriteLine(String.Format("CDP2VISIO : neighbor {0} is an ESX host", currentDeviceName), DebugLevel.Debug);
                                currentDeviceIP = string.Format("{0}_{1}", nocdpip, nocdpip_index);
                                nocdpip_index++;
                            }
                        }
                        #endregion

                        if (currentDeviceIP == "")
                        {
                            continue;
                        }

                        #region Add current device as new device or select existing device from Devices table
                        // At this point we can identify the current device(cdp neighbor) by name and ip. This is also a new neighbor
                        // Two devices considered identical if :
                        // - have the same hostname, or
                        // - have the same IPAddress
                        string currentDeviceHostName = DottedNameSpace.TLD(currentDeviceName);
                        current_device = ds.Devices.FirstOrDefault(d =>
                                                                   currentDeviceIP != nocdpip && d.IP_Address.SplitBySemicolon().Any(thisIP => thisIP == currentDeviceIP) ||
                                                                   d.Name.SplitBySemicolon().Any(thisName => DottedNameSpace.CompateTLD(thisName, currentDeviceHostName))
                                                                   );
                        if (current_device == null)
                        {
                            DebugEx.WriteLine(String.Format("CDP2VISIO : neighbor {0} is a new device, adding to devices data table", currentDeviceName), DebugLevel.Informational);
                            // This device is not yet known. Add to device list and also to list of devices in script
                            current_device = ds.Devices.NewDevicesRow();
                            //if (current_device.Name != currentDeviceName) current_device.Name += ";" + currentDeviceName;
                            //else
                            current_device.Name = currentDeviceName;
                            if (current_device.IsIP_AddressNull() || current_device.IP_Address == "")
                            {
                                current_device.IP_Address = currentDeviceIP;
                            }
                            else if (current_device.IP_Address != currentDeviceIP)
                            {
                                current_device.IP_Address += ";" + currentDeviceIP;
                            }
                            ds.Devices.AddDevicesRow(current_device);
                            // Add a new entry for discovered device if has a valid neighbor ip, Recursion is allowed
                            // and this ip is not defined as discovery boundary
                            if (_AllowRecursion && !currentDeviceIP.StartsWith(nocdpip))
                            {
                                var includedAddresses = (from addressdefinition in ds.DomainBoundary where addressdefinition.Action == BoundaryAddressAction.Include.ToString() select addressdefinition.IP_Address)?.ToList();
                                var excludedAddresses = (from addressdefinition in ds.DomainBoundary where addressdefinition.Action == BoundaryAddressAction.Exclude.ToString() select addressdefinition.IP_Address)?.ToList();
                                if (IPOperations.IsIPAddressInNetworks(currentDeviceIP, includedAddresses, true) && !IPOperations.IsIPAddressInNetworks(currentDeviceIP, excludedAddresses, false))
                                {
                                    string[] newScriptLine = _ConnectionInfo.ScriptLine.Split(ScriptSettings.CSVSeparator.ToCharArray());
                                    newScriptLine[2] = currentDeviceIP;
                                    newScriptLine[3] = currentDeviceName;
                                    _Executor.AddScriptEntry(string.Join(ScriptSettings.CSVSeparator, newScriptLine));
                                    string msg = string.Format("Added device <{0}> to discovery list.", currentDeviceIP);
                                    DebugEx.WriteLine(msg, DebugLevel.Informational);
                                    _Executor.ShowActivity(msg);
                                }
                                else
                                {
                                    string msg = string.Format("Not adding device <{0}> to discovery list because it is either explicitly excluded or not included in discovery domain", currentDeviceIP);
                                    DebugEx.WriteLine(msg, DebugLevel.Full);
                                    _Executor.ShowActivity(msg);
                                }
                            }
                            else
                            {
                                string msg = "Not adding device a new neighbor to discovery list because Active Discovery is not allowed or the neighbor does not have a valid ip address detected.";
                                DebugEx.WriteLine(msg, DebugLevel.Full);
                            }
                        }
                        else
                        {
                            DebugEx.WriteLine(String.Format("CDP2VISIO : neighbor {0} is already a known device", currentDeviceName), DebugLevel.Full);
                        }
                        #endregion

                        if (current_device == null)
                        {
                            continue;
                        }

                        #region Create Neighbor for parent_device <-> current_device
                        if (new_neigbor == null)
                        {
                            new_neigbor             = ds.Neighbours.NewNeighboursRow();
                            new_neigbor.Neighbor_ID = current_device.ID;
                            new_neigbor.Parent_ID   = parent_device.ID;
                            new_neigbor.Name        = current_device.Name;
                            DebugEx.WriteLine(String.Format("CDP2VISIO : new neighbor {0} added for device {1}", currentDeviceName, parent_device.Name), DebugLevel.Full);
                        }
                        #endregion

                        #region  Get Platform/Interfaces info and update the neighbor

                        if (line.Trim().StartsWith("Platform") && new_neigbor != null)
                        {
                            string[] words = line.SplitByComma();
                            // words[0] should be PlatForm, words[1] is Capabilities
                            string[] platformWords = words[0].SplitBySpace();
                            string[] capabilities  = words[1].SplitBySpace();
                            current_device.Platform = string.Join(" ", platformWords.SkipWhile((string l, int i) => i < 1));
                            if (current_device.Type != "VSS" && current_device.Type != "ASA" && !current_device.Type.StartsWith("Stack"))
                            {
                                current_device.Type = string.Join(";", capabilities.SkipWhile((s, i) => i < 1));
                            }
                            DebugEx.WriteLine(String.Format("CDP2VISIO : Platform of neighbor {0} identified as {1}. Device type was set to {2}", currentDeviceName, current_device.Platform, current_device.Type), DebugLevel.Full);
                        }

                        if (line.IndexOf("Interface") >= 0 && new_neigbor != null)
                        {
                            string[] words_in_line        = line.SplitBySpace();
                            int      words_length         = words_in_line.Length;
                            string   neighbour_interfaces = words_in_line[words_length - 1];
                            neighbour_interfaces = Common.ConvInt(neighbour_interfaces);

                            string local_interfaces = words_in_line[1].Replace(",", "");
                            local_interfaces = Common.ConvInt(local_interfaces);

                            new_neigbor.Neighbour_Interface = neighbour_interfaces;
                            new_neigbor.Local_Interface     = local_interfaces;
                            DebugEx.WriteLine(String.Format("CDP2VISIO : connected interface added {0}::{1} connects to  {2}::{3}", currentDeviceName, local_interfaces, parent_device.Name, neighbour_interfaces), DebugLevel.Full);
                        }
                        #endregion
                    }
                    catch (Exception Ex)
                    {
                        DebugEx.WriteLine(String.Format("CDP2VISIO : Error while parsing cdp output line [{0}]. Error is : {1}", line, Ex.InnerExceptionsMessage()));
                    }
                }
                if (new_neigbor != null)
                {
                    ds.Neighbours.AddNeighboursRow(new_neigbor);
                }
            }
        }
        /// <summary>
        /// Import targets from CSV file
        /// </summary>
        private void ImportTargets()
        {
            string imputFileName = string.Empty;

            PGTDataSet.ScriptSettingRow scriptSettings = SettingsManager.GetCurrentScriptSettings(this.pgtDataSet);
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "CSV files|*.csv|All files|*.*";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                _workInProgress.Caption = "Please wait";
                _workInProgress.Text    = "Importing targets...";
                bool     importOK = true;
                int      dupCount = 0; // count of items marked ignored as duplicate ip detected
                int      errCount = 0; // count of items not elegible for import due to some invalid data
                string[] allLines;
                try
                {
                    try
                    {
                        imputFileName = openFileDialog.FileName;
                        allLines      = File.ReadAllLines(imputFileName);
                        if (allLines.Length > 0)
                        {
                            string          thisLine = allLines[0];
                            string[]        sections = thisLine.Split(scriptSettings.CSVSeparator.ToCharArray());
                            string          doNotImportColumnText = "< Do not import >";
                            CSVHeaderMapper mapper = new CSVHeaderMapper(sections, doNotImportColumnText);
                            if (mapper.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                if (mapper.GetTargetIPColumnIndex != -1)
                                {
                                    _workInProgress.Run();
                                    bool wasError = false;
                                    for (int i = 1; i < allLines.Length; i++)
                                    {
                                        try
                                        {
                                            thisLine = allLines[i];
                                            sections = thisLine.Split(scriptSettings.CSVSeparator.ToCharArray());
                                            string targetName   = "";
                                            string targetGroup  = "default";
                                            string targetIP     = "";
                                            string deviceVendor = "";
                                            string jumpServerIP = "";
                                            string protocol     = "SSH2";
                                            int?   port         = null;
                                            string note         = "";

                                            // Target IP
                                            targetIP = sections[mapper.GetTargetIPColumnIndex].Trim().Truncate(50);
                                            if (targetIP.IndexOf(":") > 0)
                                            {
                                                string[] targetIPPort = targetIP.Split(':');
                                                targetIP = targetIPPort[0];
                                                int p = -1;
                                                if (int.TryParse(targetIPPort[1], out p))
                                                {
                                                    port = p;
                                                }
                                            }
                                            // Target name
                                            if (mapper.GetTargetNameColumnIndex >= 0)
                                            {
                                                targetName = sections[mapper.GetTargetNameColumnIndex].Trim().Truncate(100);
                                            }
                                            else if (mapper.GetTargetNameColumnIndex == -1)
                                            {
                                                targetName = mapper.GetTargetNameText.Truncate(300);
                                            }
                                            // Target group name
                                            if (mapper.GetTargetGroupNameColumnIndex >= 0)
                                            {
                                                targetGroup = sections[mapper.GetTargetGroupNameColumnIndex].Trim().Truncate(100);
                                            }
                                            else if (mapper.GetTargetGroupNameColumnIndex == -1)
                                            {
                                                targetGroup = mapper.GetTargeGroupNameText.Truncate(300);
                                            }
                                            // Jump server ip
                                            if (mapper.GetJumpServerIPColumnIndex != -2)
                                            {
                                                jumpServerIP = sections[mapper.GetJumpServerIPColumnIndex].Trim().Truncate(15);
                                            }
                                            // Note
                                            if (mapper.GetNoteColumnIndex >= 0)
                                            {
                                                note = sections[mapper.GetNoteColumnIndex].Trim().Truncate(500);
                                            }
                                            else if (mapper.GetNoteColumnIndex == -1)
                                            {
                                                note = mapper.GetNoteText;
                                            }
                                            // Protocol
                                            if (mapper.GetProtocolColumnIndex != -2)
                                            {
                                                protocol = sections[mapper.GetProtocolColumnIndex].Trim().Truncate(15);
                                            }
                                            // Vendor
                                            if (mapper.GetVendorColumnIndex > -1)
                                            {
                                                deviceVendor = sections[mapper.GetVendorColumnIndex].Trim().Truncate(50);
                                            }
                                            else
                                            {
                                                deviceVendor = mapper.GetVendorText;
                                            }

                                            if (!string.IsNullOrEmpty(targetIP) && targetIP.IsValidIP() && !string.IsNullOrEmpty(targetName))
                                            {
                                                int?c = (int?)qTA.GetTargetCount(targetGroup, targetName, port);
                                                if (c > 0)
                                                {
                                                    dupCount++;
                                                }
                                                else
                                                {
                                                    this.configTargetsTA.Insert(targetName, targetIP, deviceVendor, jumpServerIP, protocol, port, note, targetGroup);
                                                }
                                            }
                                            else
                                            {
                                                errCount++;
                                                wasError = true;
                                            }
                                            _workInProgress.Text = string.Format("Importing items...{0}% done", i * 100 / allLines.Length);
                                        }
                                        catch
                                        {
                                            wasError = true;
                                        }
                                    }
                                    try
                                    {
                                        if (!wasError || MessageBox.Show("Not all input lines could be parsed. Do you want to submit partial import into database ?", "Input errors", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.Yes)
                                        {
                                            _workInProgress.Text = "Submitting items to database...";
                                            configTargetsTA.Update(this.configDS);
                                        }
                                        else
                                        {
                                            importOK = false;
                                        }
                                    }
                                    catch (ConstraintException)
                                    {
                                        importOK = false;
                                        _workInProgress.Cancel();
                                        string errorText = this.configDS.Tables["ConfigTargets"].Rows[0].RowError;
                                        MessageBox.Show(string.Format("There is a constraint problem here : {0}", errorText), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    }
                                    catch (Exception Ex)
                                    {
                                        importOK = false;
                                        _workInProgress.Cancel();
                                        MessageBox.Show(string.Format("An unexpected error occurred : {0}", Ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    _workInProgress.Cancel();
                                    if (importOK)
                                    {
                                        if (!wasError)
                                        {
                                            if (dupCount == 0)
                                            {
                                                MessageBox.Show(string.Format("{0} items processed successfully.", allLines.Length), "Import success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                            else
                                            {
                                                MessageBox.Show(string.Format("{0} items processed successfully : #Duplicate IP :{1} ", allLines.Length, dupCount), "Success, but duplicate IPs detected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                            }
                                        }
                                        else
                                        {
                                            MessageBox.Show(string.Format("Some lines could not be imported due to invalid data. #Imported : {0}, #Duplicate IP :{1} #Skipped : {2}", allLines.Length, dupCount, errCount), "Success with errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("The import failed, items were not added to Worklist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Device IP column must be specified for input. Cannot import items.", "Selection error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                }
                            }
                        }
                    }
                    catch (Exception Ex)
                    {
                        _workInProgress.Cancel();
                        MessageBox.Show(string.Format("Unfortunately an error occurred while importing : {0}", Ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                finally
                {
                    _workInProgress.Cancel();
                    UpdateConfigTargetList();
                    UpdateSetTargets();
                    UpdateTargetGroupFilterList();
                }
            }
        }
Esempio n. 6
0
 private void PullConfig()
 {
     _workInProgressCaption = "Please wait...";
     _workInProgressText    = "Generating script...";
     _workInProgress.Run();
     DisableControls();
     try
     {
         if (cbCreateNewSet.Checked)
         {
             DateTime d = DateTime.Now;
             object   o = qTA.CloneConfigSet(_configurationSetID, string.Format("{0}_{1}{2}{3}{4}{5}{6}", tbSelConfigSetName.Text, d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second));
             _configurationSetID = Convert.ToInt32(o);
         }
         PGTDataSet.ScriptSettingRow _scriptSettings = PGT.Common.SettingsManager.GetCurrentScriptSettings(this.pgtDataSet);
         string sepChar         = _scriptSettings.CSVSeparator;
         string sExtendedHeader = string.Join(sepChar, Enum.GetNames(typeof(InputFileHeader)));
         sExtendedHeader += "SetTargetID";
         PGT.PGTScriptManager _ScriptManager = ScriptingFormManager.OpenNewScriptingForm();
         if (_ScriptManager != null)
         {
             ScriptManagers.Add(_ScriptManager);
             _ScriptManager.UpdateHeader(sExtendedHeader.Split(sepChar.ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
             _ScriptManager.OnScriptAborted  += _ScriptManager_OnScriptAborted;
             _ScriptManager.OnScriptFinished += _ScriptManager_OnScriptFinished;
             string thisLine = string.Empty;
             _ScriptManager.BeginAddingEntries();
             try
             {
                 int lastConfigTargetID = -1;
                 int targetCount        = clbTargets.CheckedItems.Count;
                 int targetNum          = 1;
                 foreach (var target in configDS.SetTargets)
                 {
                     if (IsTargetSelected(target.ConfigTargetID))
                     {
                         if (lastConfigTargetID == -1)
                         {
                             lastConfigTargetID = target.ConfigTargetID;
                         }
                         // Open a new ScriptinForm if script needs to be generated per configuration target
                         if (target.ConfigTargetID != lastConfigTargetID && cbScriptPerHost.Checked && (targetNum % (numHostPerForm.Value + 1) == 0))
                         {
                             if (_ScriptManager != null)
                             {
                                 _ScriptManager.EndAddingEntries();
                                 _ScriptManager.ExecuteScript(null, false);
                             }
                             _ScriptManager = ScriptingFormManager.OpenNewScriptingForm();
                             if (_ScriptManager == null)
                             {
                                 break;
                             }
                             _ScriptManager.OnScriptAborted  += _ScriptManager_OnScriptAborted;
                             _ScriptManager.OnScriptFinished += _ScriptManager_OnScriptFinished;
                             ScriptManagers.Add(_ScriptManager);
                             _ScriptManager.UpdateHeader(sExtendedHeader.Split(sepChar.ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                             _ScriptManager.BeginAddingEntries();
                             lastConfigTargetID = target.ConfigTargetID;
                         }
                         int configSetTargetID = cbCreateNewSet.Checked ? (int)qTA.GetConfigSetTargetID(_configurationSetID, target.ConfigTargetID) : target.ConfigSetTargetID;
                         thisLine = "1," + string.Concat(target.IsJumpServerIPNull() ? "" : target.JumpServerIP.Trim()) + "," + target.DeviceVendor + "," + target.TargetIP + string.Concat(target.IsPortNull() ? "," : string.Format(":{0},", target.Port)) + "" + "," + target.Protocol + "," + "sh run" + ",yes,,,"
                                    + ",,," + configSetTargetID;
                         if (!string.IsNullOrEmpty(thisLine))
                         {
                             bool added = _ScriptManager.AddEntry(thisLine, false);
                             if (!added)
                             {
                                 if (MessageBox.Show("There was an error adding a script line. Do you want to continue ?", "Script generation error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No)
                                 {
                                     break;
                                 }
                             }
                         }
                         targetNum++;
                     }
                 }
             }
             finally
             {
                 if (_ScriptManager != null)
                 {
                     _ScriptManager.EndAddingEntries();
                     _ScriptManager.ExecuteScript(null, false);
                 }
             }
         }
     }
     finally
     {
         _workInProgress.Cancel();
         _workInProgressSupportCancellation = false;
         btnPullConfig.Enabled       = ScriptManagers.Count == 0;
         lblOperationInProgress.Text = "Pulling configuration...";
         pbPullProgress.Value        = 0;
         pbPullProgress.Maximum      = ScriptManagers.Count;
         pbPullProgress.Visible      = ScriptManagers.Count > 1;
         btnCancelPull.Visible       = !btnPullConfig.Enabled;
     }
 }
Esempio n. 7
0
 private void Deploy()
 {
     _workInProgress.Caption = "Please wait...";
     _workInProgress.Text    = "Generating script...";
     _workInProgress.Run();
     try
     {
         PGTDataSet.ScriptSettingRow _scriptSettings = PGT.Common.SettingsManager.GetCurrentScriptSettings(this.pgtDataSet);
         string sepChar         = _scriptSettings.CSVSeparator;
         string sExtendedHeader = string.Join(sepChar, Enum.GetNames(typeof(InputFileHeader)));
         sExtendedHeader += "ConfigLineID";
         PGT.PGTScriptManager _ScriptManager = ScriptingFormManager.OpenNewScriptingForm();
         if (_ScriptManager != null)
         {
             string thisLine = string.Empty;
             _ScriptManager.SetSavePrompt(false);
             _ScriptManager.BeginAddingEntries();
             try
             {
                 int lastConfigTargetID = (configDS.Deploy.Rows[0] as ConfigDS.DeployRow).ConfigTargetID;
                 int targetCount        = clbTargets.CheckedItems.Count;
                 int targetNum          = 0;
                 foreach (var configLine in configDS.Deploy)
                 {
                     if (IsTargetSelected(configLine.ConfigTargetID))
                     {
                         if (configLine.ConfigTargetID != lastConfigTargetID)
                         {
                             targetNum++;
                         }
                         // Open a new ScriptinForm if script needs to be generated per configuration target
                         if (configLine.ConfigTargetID != lastConfigTargetID && cbScriptPerHost.Checked && (targetNum > 0 && targetNum % numHostPerForm.Value == 0))
                         {
                             #region Open a new Scripting Form
                             if (_ScriptManager != null)
                             {
                                 _ScriptManager.EndAddingEntries();
                                 if (cbStartScripts.Checked)
                                 {
                                     _ScriptManager.ExecuteScript(null, false);
                                 }
                             }
                             _ScriptManager = ScriptingFormManager.OpenNewScriptingForm();
                             if (_ScriptManager == null)
                             {
                                 break;
                             }
                             _ScriptManager.SetSavePrompt(false);
                             _ScriptManager.BeginAddingEntries();
                             lastConfigTargetID = configLine.ConfigTargetID;
                             #endregion
                         }
                         thisLine = "1," + string.Concat(configLine.IsJumpServerIPNull() ? "" : configLine.JumpServerIP.Trim()) + "," + configLine.DeviceVendor + "," + configLine.TargetIP + string.Concat(configLine.IsPortNull() ? "," : string.Format(":{0},", configLine.Port)) + "" + "," + configLine.Protocol + "," + configLine.ConfigLine + ",yes,,,"
                                    + ",,,," + configLine.ConfigLineID;
                         if (!string.IsNullOrEmpty(thisLine))
                         {
                             bool added = _ScriptManager.AddEntry(thisLine, false);
                             if (!added)
                             {
                                 if (MessageBox.Show("There was an error adding a script line. Do you want to continue ?", "Script generation error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No)
                                 {
                                     break;
                                 }
                             }
                         }
                     }
                     if (configLine.ConfigTargetID != lastConfigTargetID)
                     {
                         lastConfigTargetID = configLine.ConfigTargetID;
                     }
                 }
             }
             finally
             {
                 if (_ScriptManager != null)
                 {
                     _ScriptManager.EndAddingEntries();
                     if (cbStartScripts.Checked)
                     {
                         _ScriptManager.ExecuteScript(null, false);
                     }
                 }
             }
         }
     }
     finally
     {
         _workInProgress.Cancel();
         _workInProgressSupportCancellation = false;
         DialogResult = DialogResult.OK;
     }
 }