public void Should_ThrowOnUnknownHostEntry()
        {
            _powerShell.Commands.Clear();
            var mySM = new MockServiceManager();

            ServiceManager.Provider = () => mySM;

            var hfe = new HostFileEntry()
            {
                Address  = "127.0.0.2",
                Hostname = "abc.com"
            };

            mySM.SetupExistingHostList(new[] { hfe });

            PSCommand psCmd = new PSCommand();

            psCmd.AddCommand("Set-HfHostAddress");
            psCmd.AddParameter("Hostname", hfe.Hostname + "aa");
            psCmd.AddParameter("Address", hfe.Hostname + "11.11.11.11");

            try
            {
                _powerShell.Commands = psCmd;
                _powerShell.Invoke();
            }
            catch (CmdletInvocationException cex)
            {
                throw cex.InnerException ?? cex;
            }

            // END FUNCTION
        }
Exemple #2
0
        /// <summary>
        /// Execution the command invocation by attempting
        /// to add a new host entry.
        /// </summary>
        protected override void ProcessRecord()
        {
            var service = HostFileService;
            var entries = service.GetEntries();

            // can't add a duplicate. Throw error...
            if (entries.Any(x => x.Hostname.AreHostFileStringEqual(Hostname)))
            {
                throw new DuplicateHostException(Hostname);
            }

            var entry = new HostFileEntry();

            entry.Hostname = Hostname;
            entry.Address  = Address;
            entry.SetTypeFromAddress();

            var entryList = new List <HostFileEntry>();

            entryList.AddRange(entries);
            entryList.Add(entry);

            service.WriteEntries(entryList);
            WriteObject(entry);

            Log.WriteLog($"Added host to host file: {entry.ToString()}");

            // END FUNCTION
        }
        public void Should_UpdateEntry()
        {
            _powerShell.Commands.Clear();
            var mySM = new MockServiceManager();

            ServiceManager.Provider = () => mySM;

            var hfe = new HostFileEntry()
            {
                Address  = "127.0.0.2",
                Hostname = "abc.com"
            };

            mySM.SetupExistingHostList(new [] { hfe });

            PSCommand psCmd = new PSCommand();

            psCmd.AddCommand("Set-HfHostAddress");
            psCmd.AddParameter("Hostname", hfe.Hostname);
            psCmd.AddParameter("Address", "11.11.11.11");

            _powerShell.Commands = psCmd;
            _powerShell.Invoke();

            mySM.MockFileService.Verify(h => h.WriteEntries(
                                            It.Is <IEnumerable <HostFileEntry> >(en => en.Any(writeEntry =>
                                                                                              string.Compare(writeEntry.Hostname, hfe.Hostname) == 0 &&
                                                                                              string.Compare(writeEntry.Address, "11.11.11.11") == 0))));

            // END FUNCTION
        }
Exemple #4
0
        private string FormatHostEntry(HostFileEntry entry)
        {
            var hostName  = entry.HostName;
            var ipAddress = entry.IpAddress;

            return(string.IsNullOrEmpty(entry.Comment) ?
                   string.Concat(ipAddress, "\t", hostName) : string.Concat(ipAddress, "\t", hostName, "\t", "#", entry.Comment));
        }
        private string FormatHostEntry(HostFileEntry entry)
        {
            var hostName = entry.HostName;
            var ipAddress = entry.IpAddress;

            return string.IsNullOrEmpty(entry.Comment) ?
                string.Concat(ipAddress, "\t", hostName) : string.Concat(ipAddress, "\t", hostName, "\t", "#", entry.Comment);
        }
Exemple #6
0
        private void ParseHostFile()
        {
            for (int i = 0; i < hostFileLines.Count; i++)
            {
                string hostLine = hostFileLines[i];

                // Check for comment and empty lines
                if (!hostLine.Trim().StartsWith("#") && !String.IsNullOrEmpty(hostLine))
                {
                    bool addToList = false;

                    var newEntry = new HostFileEntry {
                        Index = i
                    };

                    var match1 = Regex.Match(hostLine, @"((?:[0-9]{1,3}\.){3}[0-9]{1,3})");
                    var match2 = Regex.Match(hostLine, @"(#(?:[0-9]{1,3}\.){3}[0-9]{1,3})");
                    var match3 = Regex.Match(hostLine, @"(#\W+(?:[0-9]{1,3}\.){3}[0-9]{1,3})");
                    var match4 = Regex.Match(hostLine, @"([a-zA-Z]+.\-?\w+.*)");

                    if (match1.Success)
                    {
                        newEntry.IpAddress = match1.ToString().Replace(" ", String.Empty).Replace("\t", String.Empty);
                        addToList          = true;
                    }
                    if (match2.Success)
                    {
                        newEntry.IpAddress = match2.ToString().Replace(" ", String.Empty).Replace("\t", String.Empty).Replace("#", String.Empty);
                        addToList          = true;
                    }
                    if (match3.Success)
                    {
                        newEntry.IpAddress = match3.ToString().Replace(" ", String.Empty).Replace("\t", String.Empty).Replace("#", String.Empty);
                        addToList          = true;
                    }

                    if (match4.Success)
                    {
                        var match5 = Regex.Match(match4.ToString(), @"(#.\w+.*)");
                        if (match5.Success)
                        {
                            newEntry.Comment  = match5.ToString().Replace("#", String.Empty).TrimStart(whiteSpaceDelimiter);
                            newEntry.HostName = match4.ToString().Replace(match5.ToString(), String.Empty).Replace(" ", String.Empty).Replace("\t", String.Empty).Replace("#", String.Empty);
                        }
                        else
                        {
                            newEntry.HostName = match4.ToString().Replace(" ", String.Empty).Replace("\t", String.Empty).Replace("#", String.Empty);
                        }
                    }

                    if (addToList)
                    {
                        entryList.Add(newEntry);
                    }
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Responds to the save command from the current (sub) view model.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _currentViewModel_OnSaved(object sender, System.EventArgs e)
        {
            if (CurrentViewModel is VirtualHostVM)
            {
                var vHost = ((VirtualHostVM)CurrentViewModel).SelectedVirtualHost;
                if (vHost == null)
                {
                    return;
                }

                var old = VirtualHosts.FirstOrDefault(p => p.Id == vHost.Id);

                if (old == null)
                {
                    VirtualHosts.Add(vHost);
                }
                else
                {
                    var idx = VirtualHosts.IndexOf(old);
                    VirtualHosts.Remove(old);
                    VirtualHosts.Insert(idx, vHost);
                }

                // This bypasses the INotify event.
                // Currently there doesn't seem much point firing the event, but this may change later.
                _selectedVirtualHost = vHost;
            }
            else if (CurrentViewModel is HostFileEntryVM)
            {
                var host = ((HostFileEntryVM)CurrentViewModel).CurrentHostFileEntry;
                if (host == null)
                {
                    return;
                }

                var old = HostFileEntries.FirstOrDefault(p => p.Id == host.Id);

                if (old == null)
                {
                    HostFileEntries.Add(host);
                }
                else
                {
                    var idx = HostFileEntries.IndexOf(old);
                    HostFileEntries.Remove(old);
                    HostFileEntries.Insert(idx, host);
                }

                // This bypasses the INotify event.
                // Currently there doesn't seem much point firing the event, but this may change later.
                _selectedHostFileEntry = host;
            }
        }
        public List <HostFileEntry> GetAllHosts()
        {
            if (!SysSettings.FileService.FileExists(SysSettings.AppSettings.HostFilePath))
            {
                return(null);
            }

            var text    = SysSettings.FileService.ReadAllText(SysSettings.AppSettings.HostFilePath);
            var matches = Regex.Matches(text, _regexHost);

            if (matches.Count == 0)
            {
                return(null);
            }

            var results = new List <HostFileEntry>();

            foreach (Match match in matches)
            {
                string url;
                string ip;
                bool   active;
                if (!string.IsNullOrEmpty(match.Groups[3].Value))
                {
                    active = !match.Groups[2].Value.Contains("#");
                    ip     = match?.Groups[3]?.Value?.Trim();
                    url    = match?.Groups[4]?.Value?.Trim();
                }
                else if (!string.IsNullOrEmpty(match.Groups[7].Value))
                {
                    active = !match.Groups[6].Value.Contains("#");
                    ip     = match?.Groups[7]?.Value?.Trim();
                    url    = match?.Groups[8]?.Value?.Trim();
                }
                else
                {
                    throw new Exception("Could not parse host file entry: " + match.Value);
                }

                if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(ip))
                {
                    HostFileEntry entry = new HostFileEntry(url, ip, active);
                    results.Add(entry);
                }
            }
            return(results);
        }
        public void AddOrUpdateEntry(string hostName, string ipAddress, string comment)
        {
            // Check if value already exists
            var originalEntry = entryList.FirstOrDefault(x => x.HostName == hostName);

            // Create the new value if neccesary
            if (originalEntry == null)
            {
                originalEntry = new HostFileEntry { Index = -1 };

                entryList.Add(originalEntry);
            }

            originalEntry.Comment = comment;
            originalEntry.HostName = hostName;
            originalEntry.IpAddress = ipAddress;
        }
Exemple #10
0
        public void AddOrUpdateEntry(string hostName, string ipAddress, string comment)
        {
            // Check if value already exists
            var originalEntry = entryList.FirstOrDefault(x => x.HostName == hostName);

            // Create the new value if neccesary
            if (originalEntry == null)
            {
                originalEntry = new HostFileEntry {
                    Index = -1
                };

                entryList.Add(originalEntry);
            }

            originalEntry.Comment   = comment;
            originalEntry.HostName  = hostName;
            originalEntry.IpAddress = ipAddress;
        }
Exemple #11
0
        /// <summary>
        /// Sets associated objects when required.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _objectViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e == null)
            {
                return;
            }

            object obj = null;

            switch (e.PropertyName)
            {
            case "CurrentHostFileEntry":
                // Set the backing value so we skip the actions that occur when assigning to the public property.
                _selectedVirtualHost = VirtualHosts.FirstOrDefault(
                    p => p.ServerName == SelectedHostFileEntry.Url ||
                    p.ServerAlias == SelectedHostFileEntry.Url);

                // Assign found value to obj, even if null as this will tell the viewmodel to clear the property.
                obj = _selectedVirtualHost;

                // Now we need to raise the property changed event on the changed property to allow UI to react.
                OnPropertyChanged("SelectedVirtualHost");
                break;

            case "SelectedVirtualHost":
                _selectedHostFileEntry = HostFileEntries.FirstOrDefault(
                    p => p.Url == SelectedVirtualHost.ServerName ||
                    p.Url == SelectedVirtualHost.ServerAlias);

                obj = _selectedHostFileEntry;

                OnPropertyChanged("SelectedHostFileEntry");
                break;

            default:
                // If not a property we want to act on we should return to prevent setting unwanted values.
                return;
            }
            CurrentViewModel.SetAssociatedObject(obj);
        }
        /// <summary>
        /// Executes command invocation depending on
        /// parameter set used.
        /// </summary>
        protected override void ProcessRecord()
        {
            var service = ServiceManager
                          .Get <IHostFileDataService>();

            var entries = service.GetEntries();

            // ensure host exists before updating.
            if (!entries.Any(x => x.Hostname.AreHostFileStringEqual(Hostname)))
            {
                throw new MissingHostException(Hostname);
            }

            // locate and update entry.
            var toChange = entries.Single(x => x.Hostname.AreHostFileStringEqual(Hostname));
            var oldState = new HostFileEntry()
            {
                Address  = toChange.Address,
                Hostname = toChange.Hostname,
                Type     = toChange.Type
            };

            // udpdate address...
            toChange.Address = Address;
            var unchanged = entries.Where(x => !x.Hostname.AreHostFileStringEqual(Hostname));

            var composite = new List <HostFileEntry>();

            composite.AddRange(unchanged);
            composite.Add(toChange);

            // write all back out to disk.
            service.WriteEntries(composite);

            Log.WriteLog($"Updated host file entry: {oldState.ToString()} to {toChange.ToString()}");

            // END FUNCTION
        }
        private void ParseHostFile()
        {
            for (int i = 0; i < hostFileLines.Count; i++)
            {
                string hostLine = hostFileLines[i];

                // Check for comment and empty lines
                if (!hostLine.Trim().StartsWith("#") && !String.IsNullOrEmpty(hostLine))
                {
                    bool addToList = false;

                    var newEntry = new HostFileEntry { Index = i };

                    var match1 = Regex.Match(hostLine, @"((?:[0-9]{1,3}\.){3}[0-9]{1,3})");
                    var match2 = Regex.Match(hostLine, @"(#(?:[0-9]{1,3}\.){3}[0-9]{1,3})");
                    var match3 = Regex.Match(hostLine, @"(#\W+(?:[0-9]{1,3}\.){3}[0-9]{1,3})");
                    var match4 = Regex.Match(hostLine, @"([a-zA-Z]+.\-?\w+.*)");

                    if (match1.Success)
                    {
                        newEntry.IpAddress = match1.ToString().Replace(" ", String.Empty).Replace("\t", String.Empty);
                        addToList = true;
                    }
                    if (match2.Success)
                    {
                        newEntry.IpAddress = match2.ToString().Replace(" ", String.Empty).Replace("\t", String.Empty).Replace("#", String.Empty);
                        addToList = true;
                    }
                    if (match3.Success)
                    {
                        newEntry.IpAddress = match3.ToString().Replace(" ", String.Empty).Replace("\t", String.Empty).Replace("#", String.Empty);
                        addToList = true;
                    }

                    if (match4.Success)
                    {
                        var match5 = Regex.Match(match4.ToString(), @"(#.\w+.*)");
                        if (match5.Success)
                        {
                            newEntry.Comment = match5.ToString().Replace("#", String.Empty).TrimStart(whiteSpaceDelimiter);
                            newEntry.HostName = match4.ToString().Replace(match5.ToString(), String.Empty).Replace(" ", String.Empty).Replace("\t", String.Empty).Replace("#", String.Empty);
                        }
                        else
                        {
                            newEntry.HostName = match4.ToString().Replace(" ", String.Empty).Replace("\t", String.Empty).Replace("#", String.Empty);
                        }
                    }

                    if (addToList)
                        entryList.Add(newEntry);
                }
            }
        }