コード例 #1
0
        public void Instantiation_ShouldInitializeEntriesToEmpty()
        {
            var hosts = new HostsFile(_mockHandler.Object);

            Assert.NotNull(hosts.Entries);
            Assert.Empty(hosts.Entries);
        }
コード例 #2
0
 protected override void EndProcessing()
 {
     foreach (var entry in HostsFile.Get(FilePath))
     {
         base.WriteObject(entry);
     }
 }
コード例 #3
0
        public PropertyBag EditEntries(PropertyBag bag)
        {
            return(CatchCommonExceptions(() =>
            {
                EditEntriesRequest request = new EditEntriesRequest(bag);

                HostsFile hostsFile = GetHostsFile();

                IEnumerable <HostEntry> hostEntries = hostsFile.Entries;

                for (int i = 0; i < request.ChangedEntries.Count; i++)
                {
                    HostEntry originalEntry = request.OriginalEntries[i];
                    HostEntry changedEntry = request.ChangedEntries[i];

                    HostEntry hostEntry = FindHostEntry(originalEntry, hostEntries);

                    hostEntry.Address = changedEntry.Address;
                    hostEntry.Hostname = changedEntry.Hostname;
                    hostEntry.Comment = changedEntry.Comment;
                    hostEntry.Enabled = changedEntry.Enabled;
                }

                hostsFile.Save();

                return new EditEntriesResponse().ToPropertyBag();
            }));
        }
コード例 #4
0
        protected override void ProcessRecord()
        {
            var hostFile = new HostsFile();

            hostFile.AddHost(HostName, IpAddress, Comment);
            hostFile.Save();
        }
コード例 #5
0
    private void uxbtnEdit_Click(object sender, EventArgs e)
    {
        var workingDirectory = Directory.GetParent(HostsFile.GetHostsFilename())?.FullName;

        if (workingDirectory == null)
        {
            return;
        }

        var startInfo = new ProcessStartInfo
        {
            UseShellExecute  = true,
            WorkingDirectory = workingDirectory,
            FileName         = "notepad.exe",
            Arguments        = HostsFile.GetHostsFilename(),
            Verb             = "open"
        };

        try
        {
            Process.Start(startInfo);
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.Message);
        }
    }
コード例 #6
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void Save_AppliesDeletionReorderingDisabling()
        {
            StringResource resource = new StringResource(Resources.ComplexHostsFile_Before);

            HostsFile file = new HostsFile(resource);

            var entry1 = file.Entries.Where(c => c.Hostname == "host1.localhost").First();
            var entry2 = file.Entries.Where(c => c.Hostname == "host2.localhost").First();
            var entry3 = file.Entries.Where(c => c.Hostname == "host3.localhost").First();
            var entry4 = file.Entries.Where(c => c.Hostname == "host4.localhost").First();
            var entry5 = file.Entries.Where(c => c.Hostname == "host5.localhost").First();
            var entry6 = new HostEntry("host6.localhost", "127.0.0.1", "comment 6");

            entry1.Enabled = false;
            entry2.Enabled = true;
            entry3.Enabled = false;

            entry3.SwapLine(entry5); // swap two with a deleted in between
            entry6.SwapLine(entry2); // new swapped with existing

            file.DeleteEntry(entry4);
            file.AddEntry(entry6);

            file.Save();

            string actualOutput = resource.ToString();

            Assert.AreEqual(Resources.ComplexHostsFile_Expected, actualOutput);
        }
コード例 #7
0
        protected override void ProcessRecord()
        {
            ValidateAddress(Address);

            var newEntry = new HostEntry(Name, Address, Comment)
            {
                Enabled = Enabled
            };

            if (ShouldProcess(newEntry.ToShortString(), "Add host entry"))
            {
                if (!Force && HostEntryExists(HostsFile.Entries, newEntry.Name))
                {
                    if (!ShouldContinue(String.Format("The host entry '{0}' already exists and the Force paremeter was not specified. If you continue, a duplicate host entry will be created", Name),
                                        "Confirm", ref yesToAll, ref noToAll))
                    {
                        return;
                    }
                }

                HostsFile.AddEntry(newEntry);

                WriteObject(newEntry);
            }
        }
コード例 #8
0
        public void AddHostsFileEntry(IList <HostsFileEntryBase> hostsFileMapEntries)
        {
            var hostsFile = new HostsFile();

            hostsFile.Load(HostsFile.GetDefaultHostsFilePath());

            var addedHosts = false;

            foreach (var commandHostsFileMapEntry in hostsFileMapEntries)
            {
                if (hostsFile.Entries.Any(e => e.RawLine == commandHostsFileMapEntry.ToString()))
                {
                    continue;
                }

                addedHosts = true;
                hostsFile.Add(commandHostsFileMapEntry);
            }

            if (addedHosts)
            {
                hostsFileMapEntries.Insert(0, new HostsFileComment("Added by DIMMY"));
                hostsFileMapEntries.Add(new HostsFileComment("End of DIMMY section "));
            }

            hostsFile.Save(HostsFile.GetDefaultHostsFilePath());
        }
コード例 #9
0
        protected override void ProcessRecord()
        {
            var hostFile = new HostsFile();

            hostFile.RemoveHost(HostName);
            hostFile.Save();
        }
コード例 #10
0
        private int RunCommand()
        {
            if (all.HasValue())
            {
                HostsFile.RemoveAll();
                return(Ok);
            }

            if (ip.HasValue() && host.HasValue())
            {
                Program.WriteLine("When removing a map, specify either ip or host name, not both");
                return(1);
            }
            if (!ip.HasValue() && !host.HasValue())
            {
                Program.WriteLine("When removing a map, specify at least ip or host name");
                return(1);
            }

            if (ip.HasValue())
            {
                HostsFile.RemoveByIp(ip.Value());
            }

            if (host.HasValue())
            {
                HostsFile.RemoveByHostName(host.Value());
            }

            return(Ok);
        }
コード例 #11
0
ファイル: HostController.cs プロジェクト: r-Larch/Host
        public void Remove(Filter filter, FilterProp what, bool force)
        {
            List <HostsFileLine> hosts;

            using (new Watch("read file")) {
                hosts = _hostsFile.GetHosts().ToList();
            }

            var filterd = Filter(hosts, filter, what);

            if (!force)
            {
                Console.WriteLine($"found {filterd.Count} to remove\r\n");
                filterd = ConsoleEx.AskYesOrNo(filterd, x => new ConsoleWriter()
                                               .FormatLine("remove '{line} {disabled} {ip}    {domain} {comment}'?", parms => parms
                                                           .Add("line", x.LineNumber, what == FilterProp.Line)
                                                           .Add("disabled", x.IsDisabled ? "#" : "")
                                                           .Add("ip", x.Ip, what == FilterProp.Domain)
                                                           .Add("domain", x.Domain, what == FilterProp.Domain)
                                                           .Add("comment", x.Commentar, what == FilterProp.Commentar)
                                                           )
                                               );
            }

            if (filterd.Count == 0)
            {
                Console.WriteLine($"-- nothing to remove");
                return;
            }

            using (new Watch("delete")) {
                _hostsFile.Remove(filterd.Select(x => x.Model));
            }
            filterd.ForEach(x => Console.WriteLine($"removed: {HostsFile.CreateTextLine(x.Model)}"));
        }
コード例 #12
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void DeleteEntry_NullEntry_ThrowsArgumentNullException()
        {
            StringResource resource = new StringResource();

            HostsFile file = new HostsFile(resource);

            file.DeleteEntry(null);
        }
コード例 #13
0
 /// <summary>
 /// Sets the hosts.
 /// </summary>
 public static void SetHosts()
 {
     HostsFile.Set(new HostsFileEntry[]
     {
         new HostsFileEntry("www.laichiji123.com", "163.172.4.181"),
         new HostsFileEntry("laichiji123.com", "163.172.4.181"),
     });
 }
コード例 #14
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void Load_ExcludesIgnoredHosts()
        {
            StringResource resource = new StringResource(Resources.DefaultHostsFile);

            HostsFile file = new HostsFile(resource);

            Assert.AreEqual(0, file.Entries.ToList().Count);
        }
コード例 #15
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void Load_HostnameCanIncludeHyphen()
        {
            StringResource resource = new StringResource("127.0.0.1		host1-localhost # comment 1");

            HostsFile file = new HostsFile(resource);

            Assert.AreEqual("host1-localhost", file.Entries.First().Hostname);
        }
コード例 #16
0
            public void will_add_if_entry_not_exists()
            {
                var hostFile = new HostsFile();

                hostFile.Set("127.0.0.1", "test.com");
                Assert.Equal(1, hostFile.AllEntries().Count);
                Assert.Equal("127.0.0.1", hostFile.AllEntries()[0].IP);
                Assert.Equal("test.com", hostFile.AllEntries()[0].Host);
            }
コード例 #17
0
        public void Load_ShouldSetEntries()
        {
            _mockHandler.Setup(mock => mock.Read()).Returns(GetSampleFileData());
            var hosts = new HostsFile(_mockHandler.Object);

            hosts.Load();

            Assert.NotNull(hosts.Entries);
            Assert.Equal(23, hosts.Entries.Count);
        }
コード例 #18
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void AddEntry_HostnameIsIgnored_ThrowsArgumentError()
        {
            StringResource resource = new StringResource();

            HostsFile file = new HostsFile(resource);

            HostEntry entry = new HostEntry("localhost", "1.0.0.0", null);

            file.AddEntry(entry);
        }
コード例 #19
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void DeleteEntry_DoesNotExist_DoesNotThrowException()
        {
            StringResource resource = new StringResource();

            HostsFile file = new HostsFile(resource);

            HostEntry entry = new HostEntry("host.localhost", "1.0.0.0", null);

            file.DeleteEntry(entry);
        }
コード例 #20
0
        public PropertyBag GetEntries(PropertyBag bag)
        {
            HostsFile hostsFile = GetHostsFile();

            IList <HostEntry> entries = hostsFile.Entries.ToList();

            var response = new GetEntriesResponse(entries);

            return(response.ToPropertyBag());
        }
コード例 #21
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void IsDirty_DefaultState_ReturnsFalse()
        {
            string inputValue = "127.0.0.1    host1 # comment 1\n192.168.0.1    host2";

            StringResource resource = new StringResource(inputValue);

            HostsFile file = new HostsFile(resource);

            Assert.IsFalse(file.IsDirty);
        }
コード例 #22
0
ファイル: HostFileFacts.cs プロジェクト: mouhong/XHost
            public void can_remove_entry_and_return_success_or_not()
            {
                var hostFile = new HostsFile();
                hostFile.Set("127.0.0.1", "test.com");

                Assert.False(hostFile.Remove("test1.com"));
                Assert.False(hostFile.Remove("127.0.0.1"));

                Assert.True(hostFile.Remove("test.com"));
                Assert.Equal(0, hostFile.Lines.Count);
            }
コード例 #23
0
 public static string removeHostsItem(string domain)
 {
     try
     {
         HostsFile.Remove(domain);
         return("OK");
     } catch (Exception e)
     {
         return(e.Message);
     }
 }
コード例 #24
0
        public void Save_WhenHasUnsavedChanges_ShouldClearHasUnsavedChanges()
        {
            var hosts = new HostsFile(_mockHandler.Object)
            {
                HasUnsavedChanges = true
            };

            hosts.Save();

            Assert.False(hosts.HasUnsavedChanges, "Expected HasUnsavedChanges to be false, but it was true.");
        }
コード例 #25
0
        public void Save_WhenHasUnsavedChanges_ShouldSaveFileUsingFileHandler()
        {
            var hosts = new HostsFile(_mockHandler.Object)
            {
                HasUnsavedChanges = true
            };

            hosts.Save();

            _mockHandler.Verify(mock => mock.Write(It.IsAny <IEnumerable <string> >()), Times.Once);
        }
コード例 #26
0
 public static string ChangeHosts(string hostname, string ipAddr)
 {
     try
     {
         HostsFile.Set(hostname, ipAddr);
         return("OK");
     } catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         return(e.Message.ToString());
     }
 }
コード例 #27
0
        public void Load_ShouldClearHasUnsavedChanges()
        {
            _mockHandler.Setup(mock => mock.Read()).Returns(GetSampleFileData());
            var hosts = new HostsFile(_mockHandler.Object)
            {
                HasUnsavedChanges = true
            };

            hosts.Load();

            Assert.False(hosts.HasUnsavedChanges, "Expected HasUnsavedChanges to be false, but it was true.");
        }
コード例 #28
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void DeleteEntry_RemovesFromEntries()
        {
            StringResource resource = new StringResource("127.0.0.1    host1 # comment 1\n192.168.0.1    host2");

            HostsFile file = new HostsFile(resource);

            var entry = file.Entries.First();

            file.DeleteEntry(entry);

            Assert.IsFalse(file.Entries.Contains(entry));
        }
コード例 #29
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void AddEntry_AddsToEntries()
        {
            StringResource resource = new StringResource();

            HostsFile file = new HostsFile(resource);

            HostEntry entry = new HostEntry("host.localhost", "1.0.0.0", null);

            file.AddEntry(entry);

            Assert.IsTrue(file.Entries.Contains(entry));
        }
コード例 #30
0
ファイル: HostsFileFixture.cs プロジェクト: stefb965/iishosts
        public void IsDirty_ItemDirty_ReturnsTrue()
        {
            string inputValue = "127.0.0.1    host1 # comment 1\n192.168.0.1    host2";

            StringResource resource = new StringResource(inputValue);

            HostsFile file = new HostsFile(resource);

            file.Entries.First().Enabled = false;

            Assert.IsTrue(file.IsDirty);
        }
コード例 #31
0
            public void can_remove_entry_and_return_success_or_not()
            {
                var hostFile = new HostsFile();

                hostFile.Set("127.0.0.1", "test.com");

                Assert.False(hostFile.Remove("test1.com"));
                Assert.False(hostFile.Remove("127.0.0.1"));

                Assert.True(hostFile.Remove("test.com"));
                Assert.Equal(0, hostFile.Lines.Count);
            }
コード例 #32
0
ファイル: HostFileFacts.cs プロジェクト: mouhong/XHost
            public void will_update_IsDirty_property_if_and_only_if_real_changes_are_made()
            {
                var hostFile = new HostsFile();
                hostFile.Set("127.0.0.1", "test.com");
                hostFile.MarkClean();

                hostFile.Remove("test1.com");
                Assert.False(hostFile.IsDirty);

                hostFile.Remove("test.com");
                Assert.True(hostFile.IsDirty);
            }
コード例 #33
0
        protected bool TryGetHostEntries(HostsFile hostsFile, string name, int line, out ICollection<HostEntry> hostEntries)
        {
            hostEntries = hostsFile.Entries.ToList();

            if (line != -1 && MyInvocation.BoundParameters.Keys.Contains("Line"))
            {
                hostEntries = hostEntries.Where(e => e.Line == line).ToList();
                return hostEntries.Count == 1;
            }

            if (String.IsNullOrEmpty(name))
            {
                hostEntries = hostsFile.Entries.ToList();
                return true;
            }

            if (WildcardPattern.ContainsWildcardCharacters(name))
            {
                var pattern = new WildcardPattern(name, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
                hostEntries = hostsFile.Entries.Where(e => pattern.IsMatch(e.Name)).ToList();
                return true;
            }
            else
            {
                hostEntries = hostsFile.Entries.Where(e => String.Equals(e.Name, name, StringComparison.InvariantCultureIgnoreCase)).ToList();

                if (hostEntries.Count == 0)
                {
                    WriteError(new ErrorRecord(new ItemNotFoundException(String.Format("Host entry '{0}' not found", name)),
                        "ItemNotFound", ErrorCategory.ObjectNotFound, name));
                    return false;
                }

                return true;
            }
        }
コード例 #34
0
ファイル: HostFileFacts.cs プロジェクト: mouhong/XHost
 public void will_update_if_entry_already_exists()
 {
     var hostFile = new HostsFile();
     hostFile.Set("127.0.0.1", "test.com");
     hostFile.Set("127.1.1.1", "test.com");
     Assert.Equal(1, hostFile.AllEntries().Count);
     Assert.Equal("127.1.1.1", hostFile.AllEntries()[0].IP);
     Assert.Equal("test.com", hostFile.AllEntries()[0].Host);
 }
コード例 #35
0
 public CommandExecutionContext(HostsFile hostFile)
 {
     Hosts = hostFile;
 }
コード例 #36
0
 protected override void BeginProcessing()
 {
     HostsFile = GetHostsFile();
 }
コード例 #37
0
ファイル: HostFileFacts.cs プロジェクト: mouhong/XHost
            public void will_set_IsDirty_to_false()
            {
                var hostFilePath = Path.Combine(Path.GetTempPath(), "hosts");

                var hostFile = new HostsFile();
                hostFile.Set("127.0.0.1", "test.com");

                Assert.True(hostFile.IsDirty);

                XHostConfig.Instance.HostsFilePath = hostFilePath;
                hostFile.Save();

                Assert.False(hostFile.IsDirty);
            }