diff --git a/Dependencies/SplitButton/Demo/app.config b/Dependencies/SplitButton/Demo/app.config
new file mode 100644
index 00000000..ff995010
--- /dev/null
+++ b/Dependencies/SplitButton/Demo/app.config
@@ -0,0 +1,3 @@
+
+
+
diff --git a/NLog.XmlLayout/Serialization.cs b/NLog.XmlLayout/Serialization.cs
index ba0650dd..4cab2aab 100644
--- a/NLog.XmlLayout/Serialization.cs
+++ b/NLog.XmlLayout/Serialization.cs
@@ -1,59 +1,57 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Xml;
using System.Collections;
+using System.Xml;
namespace NLog.XmlLayout
{
- public class Serialization
- {
- ///
- /// Serializes exception into XML. If exception or stream is null
- /// does nothing.
- ///
- ///
- ///
- public static void SerializeException(Exception currentException, XmlTextWriter writer)
- {
- if (currentException == null || writer == null)
- return;
+ public class Serialization
+ {
+ ///
+ /// Serializes exception into XML. If exception or stream is null
+ /// does nothing.
+ ///
+ ///
+ ///
+ public static void SerializeException(Exception currentException, XmlTextWriter writer)
+ {
+ if (currentException == null || writer == null)
+ return;
- writer.WriteStartElement("Exception");
+ writer.WriteStartElement("Exception");
- writer.WriteStartElement("Message");
- writer.WriteString(currentException.Message);
- writer.WriteEndElement();
+ writer.WriteStartElement("Message");
+ writer.WriteString(currentException.Message);
+ writer.WriteEndElement();
- writer.WriteStartElement("Source");
- writer.WriteString(currentException.Source);
- writer.WriteEndElement();
+ writer.WriteStartElement("Source");
+ writer.WriteString(currentException.Source);
+ writer.WriteEndElement();
- if (currentException.StackTrace != null)
- {
- writer.WriteStartElement("Stack");
- writer.WriteString(currentException.StackTrace);
- writer.WriteEndElement();
- }
- if (currentException.Data.Count > 0)
- {
- foreach (DictionaryEntry item in currentException.Data)
- {
- writer.WriteStartElement("Data");
- if (item.Key != null)
- XmlLayoutRenderer.WriteToAttribute(writer, "key", item.Key.ToString());
- if (item.Value != null)
- XmlLayoutRenderer.WriteToAttribute(writer, "value", item.Value.ToString());
- writer.WriteEndElement();
- }
- }
+ if (currentException.StackTrace != null)
+ {
+ writer.WriteStartElement("Stack");
+ writer.WriteString(currentException.StackTrace);
+ writer.WriteEndElement();
+ }
+ if (currentException.Data.Count > 0)
+ {
+ foreach (DictionaryEntry item in currentException.Data)
+ {
+ writer.WriteStartElement("Data");
+ if (item.Key != null)
+ XmlLayoutRenderer.WriteToAttribute(writer, "key", item.Key.ToString());
+ if (item.Value != null)
+ XmlLayoutRenderer.WriteToAttribute(writer, "value", item.Value.ToString());
+ writer.WriteEndElement();
+ }
+ }
- if (currentException.InnerException != null)
- {
- SerializeException(currentException.InnerException, writer);
- }
- writer.WriteEndElement();
- }
- }
+ if (currentException.InnerException != null)
+ {
+ SerializeException(currentException.InnerException, writer);
+ }
+ writer.WriteEndElement();
+ }
+ }
}
diff --git a/NLog.XmlLayout/XmlLayout.cs b/NLog.XmlLayout/XmlLayout.cs
index 24ee95e9..e5071371 100644
--- a/NLog.XmlLayout/XmlLayout.cs
+++ b/NLog.XmlLayout/XmlLayout.cs
@@ -1,98 +1,96 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
using System.Text;
-using NLog.LayoutRenderers;
using System.Xml;
-using System.Collections;
-using System.IO;
-using System.Globalization;
-
+using NLog.LayoutRenderers;
namespace NLog.XmlLayout
{
- [LayoutRenderer("xml")]
- public class XmlLayoutRenderer : LayoutRenderer
- {
- private string elementName;
+ [LayoutRenderer("xml")]
+ public class XmlLayoutRenderer : LayoutRenderer
+ {
+ private string elementName;
- public string ElementName
- {
- get { return elementName; }
- set { elementName = value; }
- }
+ public string ElementName
+ {
+ get { return elementName; }
+ set { elementName = value; }
+ }
- protected override void Append(StringBuilder builder, LogEventInfo logEvent)
- {
+ protected override void Append(StringBuilder builder, LogEventInfo logEvent)
+ {
using (StringWriter stringWriter = new UTF8StringWriter(builder))
- using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
- {
- writer.Formatting = Formatting.Indented;
- // Create the eventNode element
- writer.WriteStartElement((elementName == null ? logEvent.Level.ToString() : elementName));
-
- if (elementName != null)
- {
- WriteToAttribute(writer, "type", logEvent.Level.ToString());
- }
+ using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
+ {
+ writer.Formatting = Formatting.Indented;
+ // Create the eventNode element
+ writer.WriteStartElement((elementName == null ? logEvent.Level.ToString() : elementName));
+
+ if (elementName != null)
+ {
+ WriteToAttribute(writer, "type", logEvent.Level.ToString());
+ }
- WriteToAttribute(writer, "time", logEvent.TimeStamp.ToString("M/d/yyyy HH:mm:ss tt"));
- writer.WriteStartElement("Message");
- writer.WriteString(logEvent.Message);
- writer.WriteEndElement();
- if (logEvent.Parameters != null)
- {
- foreach (object obj in logEvent.Parameters)
- {
- writer.WriteStartElement("Parameter");
- if (obj is KeyValuePair)
- {
- KeyValuePair p = (KeyValuePair)obj;
- WriteToAttribute(writer, "name", p.Key);
- WriteToAttribute(writer, "value", p.Value);
- }
+ WriteToAttribute(writer, "time", logEvent.TimeStamp.ToString("M/d/yyyy HH:mm:ss tt"));
+ writer.WriteStartElement("Message");
+ writer.WriteString(logEvent.Message);
+ writer.WriteEndElement();
+ if (logEvent.Parameters != null)
+ {
+ foreach (object obj in logEvent.Parameters)
+ {
+ writer.WriteStartElement("Parameter");
+ if (obj is KeyValuePair)
+ {
+ KeyValuePair p = (KeyValuePair)obj;
+ WriteToAttribute(writer, "name", p.Key);
+ WriteToAttribute(writer, "value", p.Value);
+ }
else if (obj is Exception)
{
Exception ex = obj as Exception;
string msg = ex.GetType().ToString() + ex.StackTrace;
- WriteToAttribute(writer, "value", msg);
+ WriteToAttribute(writer, "value", msg);
+ }
+ else
+ {
+ WriteToAttribute(writer, "value", obj.ToString());
}
- else
- {
- WriteToAttribute(writer, "value", obj.ToString());
- }
- writer.WriteEndElement();
- }
- }
- if (logEvent.Exception != null)
- {
- Serialization.SerializeException(logEvent.Exception, writer);
- }
- writer.WriteEndElement();
- stringWriter.Flush();
- }
- }
+ writer.WriteEndElement();
+ }
+ }
+ if (logEvent.Exception != null)
+ {
+ Serialization.SerializeException(logEvent.Exception, writer);
+ }
+ writer.WriteEndElement();
+ stringWriter.Flush();
+ }
+ }
- internal static void WriteToAttribute(XmlTextWriter writer, string attribute, string value)
- {
- WriteToAttribute(writer, attribute, value, false);
- }
+ internal static void WriteToAttribute(XmlTextWriter writer, string attribute, string value)
+ {
+ WriteToAttribute(writer, attribute, value, false);
+ }
- internal static void WriteToAttribute(XmlTextWriter writer, string attribute, DateTime value)
- {
- WriteToAttribute(writer, attribute, value.ToString(DateTimeFormatInfo.InvariantInfo.ShortDatePattern + " " + DateTimeFormatInfo.InvariantInfo.ShortTimePattern), false);
- }
+ internal static void WriteToAttribute(XmlTextWriter writer, string attribute, DateTime value)
+ {
+ WriteToAttribute(writer, attribute, value.ToString(DateTimeFormatInfo.InvariantInfo.ShortDatePattern + " " + DateTimeFormatInfo.InvariantInfo.ShortTimePattern), false);
+ }
- internal static void WriteToAttribute(XmlTextWriter writer, string attribute, string value, bool writeIfEmptyValue)
- {
- if (writeIfEmptyValue || !string.IsNullOrEmpty(value))
- writer.WriteAttributeString(attribute, value);
- }
- }
+ internal static void WriteToAttribute(XmlTextWriter writer, string attribute, string value, bool writeIfEmptyValue)
+ {
+ if (writeIfEmptyValue || !string.IsNullOrEmpty(value))
+ writer.WriteAttributeString(attribute, value);
+ }
+ }
public class UTF8StringWriter : StringWriter
{
public UTF8StringWriter()
- :base()
+ : base()
{
}
diff --git a/Tests/BookmarkTest.cs b/Tests/BookmarkTest.cs
index d8623f69..50df5a55 100644
--- a/Tests/BookmarkTest.cs
+++ b/Tests/BookmarkTest.cs
@@ -1,23 +1,19 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
+using dnGREP.Common;
using Xunit;
-using dnGREP;
-using dnGREP.Common;
namespace Tests
-{
- public class BookmarkTest : TestBase
- {
- [Fact]
- public void TestBookmarks()
- {
- BookmarkLibrary.Instance.Bookmarks.Clear();
- BookmarkLibrary.Instance.Bookmarks.Add(new Bookmark("test1", "test2", "test3", "test4"));
- BookmarkLibrary.Save();
- BookmarkLibrary.Load();
- Assert.Equal(BookmarkLibrary.Instance.Bookmarks.Count, 1);
- Assert.Equal(BookmarkLibrary.Instance.Bookmarks[0].Description, "test4");
- }
- }
+{
+ public class BookmarkTest : TestBase
+ {
+ [Fact]
+ public void TestBookmarks()
+ {
+ BookmarkLibrary.Instance.Bookmarks.Clear();
+ BookmarkLibrary.Instance.Bookmarks.Add(new Bookmark("test1", "test2", "test3", "test4"));
+ BookmarkLibrary.Save();
+ BookmarkLibrary.Load();
+ Assert.Equal(BookmarkLibrary.Instance.Bookmarks.Count, 1);
+ Assert.Equal(BookmarkLibrary.Instance.Bookmarks[0].Description, "test4");
+ }
+ }
}
diff --git a/Tests/GrepCoreTest.cs b/Tests/GrepCoreTest.cs
index 4fece3d7..e17aa8ee 100644
--- a/Tests/GrepCoreTest.cs
+++ b/Tests/GrepCoreTest.cs
@@ -11,17 +11,17 @@
namespace Tests
{
- public class GrepCoreTest : TestBase, IDisposable
- {
- string sourceFolder;
- string destinationFolder;
+ public class GrepCoreTest : TestBase, IDisposable
+ {
+ string sourceFolder;
+ string destinationFolder;
public GrepCoreTest()
- {
- sourceFolder = GetDllPath() + "\\Files";
+ {
+ sourceFolder = GetDllPath() + "\\Files";
destinationFolder = Path.GetTempPath() + Guid.NewGuid().ToString();
Directory.CreateDirectory(destinationFolder);
- }
+ }
public void Dispose()
@@ -30,80 +30,80 @@ public void Dispose()
Utils.DeleteFolder(destinationFolder);
}
- [Fact]
- public void TestSearchRegexReturnsCorrectNumber()
- {
- Utils.CopyFiles(sourceFolder + "\\TestCase3", destinationFolder + "\\TestCase3", null, null);
- GrepCore core = new GrepCore();
- List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "dnGR\\wP", GrepSearchOption.CaseSensitive, -1);
- Assert.Equal(results.Count, 1);
+ [Fact]
+ public void TestSearchRegexReturnsCorrectNumber()
+ {
+ Utils.CopyFiles(sourceFolder + "\\TestCase3", destinationFolder + "\\TestCase3", null, null);
+ GrepCore core = new GrepCore();
+ List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "dnGR\\wP", GrepSearchOption.CaseSensitive, -1);
+ Assert.Equal(results.Count, 1);
- results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "dngr\\wp", GrepSearchOption.CaseSensitive, -1);
- Assert.Equal(results.Count, 0);
+ results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "dngr\\wp", GrepSearchOption.CaseSensitive, -1);
+ Assert.Equal(results.Count, 0);
- results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "dngr\\wp", GrepSearchOption.CaseSensitive | GrepSearchOption.Multiline, -1);
- Assert.Equal(results.Count, 0);
+ results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "dngr\\wp", GrepSearchOption.CaseSensitive | GrepSearchOption.Multiline, -1);
+ Assert.Equal(results.Count, 0);
- results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "dngr\\wp", GrepSearchOption.None, -1);
- Assert.Equal(results.Count, 1);
+ results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "dngr\\wp", GrepSearchOption.None, -1);
+ Assert.Equal(results.Count, 1);
- results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "string", GrepSearchOption.None, -1);
- Assert.Equal(results.Count, 2);
+ results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "string", GrepSearchOption.None, -1);
+ Assert.Equal(results.Count, 2);
Assert.Equal(results[0].Matches.Count, 3);
Assert.Equal(results[1].Matches.Count, 282);
- results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "string", GrepSearchOption.Multiline, -1);
- Assert.Equal(results.Count, 2);
+ results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "string", GrepSearchOption.Multiline, -1);
+ Assert.Equal(results.Count, 2);
Assert.Equal(results[0].Matches.Count, 3);
Assert.Equal(results[1].Matches.Count, 282);
results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.Regex, "string", GrepSearchOption.Multiline, -1);
- Assert.Equal(results.Count, 2);
+ Assert.Equal(results.Count, 2);
Assert.Equal(results[0].Matches.Count, 3);
- Assert.Equal(results[1].Matches.Count, 282);
+ Assert.Equal(results[1].Matches.Count, 282);
Assert.Empty(core.Search(null, SearchType.Regex, "string", GrepSearchOption.Multiline, -1));
- Assert.Empty(core.Search(new string[] { }, SearchType.Regex, "string", GrepSearchOption.Multiline, -1));
- }
+ Assert.Empty(core.Search(new string[] { }, SearchType.Regex, "string", GrepSearchOption.Multiline, -1));
+ }
- [Fact]
- public void TestSearchPlainReturnsCorrectNumber()
- {
- Utils.CopyFiles(sourceFolder + "\\TestCase3", destinationFolder + "\\TestCase3", null, null);
- GrepCore core = new GrepCore();
- List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "dnGREP", GrepSearchOption.CaseSensitive, -1);
- Assert.Equal(results.Count, 1);
+ [Fact]
+ public void TestSearchPlainReturnsCorrectNumber()
+ {
+ Utils.CopyFiles(sourceFolder + "\\TestCase3", destinationFolder + "\\TestCase3", null, null);
+ GrepCore core = new GrepCore();
+ List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "dnGREP", GrepSearchOption.CaseSensitive, -1);
+ Assert.Equal(results.Count, 1);
results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "dngrep", GrepSearchOption.CaseSensitive, -1);
- Assert.Equal(results.Count, 0);
+ Assert.Equal(results.Count, 0);
- results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "dngrep", GrepSearchOption.CaseSensitive | GrepSearchOption.Multiline, - 1);
- Assert.Equal(results.Count, 0);
+ results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "dngrep", GrepSearchOption.CaseSensitive | GrepSearchOption.Multiline, -1);
+ Assert.Equal(results.Count, 0);
results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "dngrep", GrepSearchOption.None, -1);
- Assert.Equal(results.Count, 1);
+ Assert.Equal(results.Count, 1);
results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "string", GrepSearchOption.None, -1);
- Assert.Equal(results.Count, 2);
- Assert.Equal(results[0].Matches.Count, 3);
+ Assert.Equal(results.Count, 2);
+ Assert.Equal(results[0].Matches.Count, 3);
Assert.Equal(results[1].Matches.Count, 282);
results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "string", GrepSearchOption.Multiline, -1);
- Assert.Equal(results.Count, 2);
+ Assert.Equal(results.Count, 2);
Assert.Equal(results[0].Matches.Count, 3);
Assert.Equal(results[1].Matches.Count, 282);
results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "string", GrepSearchOption.Multiline, -1);
- Assert.Equal(results.Count, 2);
+ Assert.Equal(results.Count, 2);
Assert.Equal(results[0].Matches.Count, 3);
Assert.Equal(results[1].Matches.Count, 282);
results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "dngrep", GrepSearchOption.CaseSensitive, -1);
- Assert.Equal(results.Count, 0);
+ Assert.Equal(results.Count, 0);
- Assert.Empty(core.Search(null, SearchType.PlainText, "string", GrepSearchOption.Multiline, -1));
- Assert.Empty(core.Search(new string[] { }, SearchType.PlainText, "string", GrepSearchOption.Multiline, -1));
- }
+ Assert.Empty(core.Search(null, SearchType.PlainText, "string", GrepSearchOption.Multiline, -1));
+ Assert.Empty(core.Search(new string[] { }, SearchType.PlainText, "string", GrepSearchOption.Multiline, -1));
+ }
[Fact]
public void TestSearchContainsValidPattern()
@@ -112,7 +112,7 @@ public void TestSearchContainsValidPattern()
GrepCore core = new GrepCore();
List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase3", "*.*"), SearchType.PlainText, "dnGREP", GrepSearchOption.CaseSensitive, -1);
Assert.Equal(results.Count, 1);
- Assert.Equal("dnGREP", results[0].Pattern);
+ Assert.Equal("dnGREP", results[0].Pattern);
}
[Fact]
@@ -147,15 +147,15 @@ public void TestResultSequence()
}
}
- [Fact]
- public void TestSearchXPathReturnsCorrectMatchCount()
- {
- Utils.CopyFiles(sourceFolder + "\\TestCase4", destinationFolder + "\\TestCase4", null, null);
- GrepCore core = new GrepCore();
- List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase4", "app.config"), SearchType.XPath, "//setting", GrepSearchOption.CaseSensitive | GrepSearchOption.Multiline, -1);
- Assert.Equal(results.Count, 1);
- Assert.Equal(results[0].Matches.Count, 28);
- }
+ [Fact]
+ public void TestSearchXPathReturnsCorrectMatchCount()
+ {
+ Utils.CopyFiles(sourceFolder + "\\TestCase4", destinationFolder + "\\TestCase4", null, null);
+ GrepCore core = new GrepCore();
+ List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase4", "app.config"), SearchType.XPath, "//setting", GrepSearchOption.CaseSensitive | GrepSearchOption.Multiline, -1);
+ Assert.Equal(results.Count, 1);
+ Assert.Equal(results[0].Matches.Count, 28);
+ }
[Fact]
public void TestSearchXPathReturnsCorrectResultsCount()
@@ -174,7 +174,7 @@ public void TestSearchWholeWord_Issue_114_Regex()
GrepCore core = new GrepCore();
List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase10", "issue-114.txt"), SearchType.Regex, "protected", GrepSearchOption.WholeWord, -1);
Assert.Equal(results.Count, 1);
- Assert.Equal(results[0].SearchResults.Count, 1);
+ Assert.Equal(results[0].SearchResults.Count, 1);
}
[Fact]
@@ -184,7 +184,7 @@ public void TestSearchWholeWord_Issue_114_Plain()
GrepCore core = new GrepCore();
List results = core.Search(Directory.GetFiles(destinationFolder + "\\TestCase10", "issue-114.txt"), SearchType.PlainText, "protected", GrepSearchOption.WholeWord, -1);
Assert.Equal(results.Count, 1);
- Assert.Equal(results[0].SearchResults.Count, 1);
+ Assert.Equal(results[0].SearchResults.Count, 1);
}
[Fact]
@@ -200,7 +200,7 @@ public void TestReplaceWithNewLineWorks()
}
private Regex guidPattern = new Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
-
+
[Theory]
[InlineData(SearchType.Regex)]
[InlineData(SearchType.PlainText)]
@@ -283,7 +283,7 @@ public void TestSearchLongLineWithManyMatches(SearchType type, GrepSearchOption
Assert.Equal(102456, results[1].Matches.Count);
Assert.True(sw.Elapsed < TimeSpan.FromSeconds(1.25));
}
-
+
[Fact]
public void TestRegexEolToken_Issue_210_SingleLine()
{
diff --git a/Tests/StorageTest.cs b/Tests/StorageTest.cs
index bf5bd97a..a3ce3eba 100644
--- a/Tests/StorageTest.cs
+++ b/Tests/StorageTest.cs
@@ -1,70 +1,65 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using Xunit;
-using dnGREP;
using System.IO;
using dnGREP.Common;
-using System.Xml.Serialization;
-using System.Collections.Specialized;
+using Xunit;
namespace Tests
{
public class StorageTest : TestBase, IDisposable
- {
- string sourceFolder;
+ {
+ string sourceFolder;
public StorageTest()
- {
- sourceFolder = Path.GetTempPath() + "TestFiles";
- }
+ {
+ sourceFolder = Path.GetTempPath() + "TestFiles";
+ }
public void Dispose()
{
Directory.Delete(sourceFolder, true);
}
- [Fact]
- public void TestSave()
- {
- GrepSettings storage = GrepSettings.Instance;
- storage.Clear();
- Assert.Empty(storage);
- storage["test"] = "hello";
- storage.Save(sourceFolder + "\\test.xml");
- Assert.True(File.Exists(sourceFolder + "\\test.xml"));
- Assert.True(new FileInfo(sourceFolder + "\\test.xml").Length > 10);
- }
+ [Fact]
+ public void TestSave()
+ {
+ GrepSettings storage = GrepSettings.Instance;
+ storage.Clear();
+ Assert.Empty(storage);
+ storage["test"] = "hello";
+ storage.Save(sourceFolder + "\\test.xml");
+ Assert.True(File.Exists(sourceFolder + "\\test.xml"));
+ Assert.True(new FileInfo(sourceFolder + "\\test.xml").Length > 10);
+ }
- [Fact]
- public void TestLoad()
- {
- GrepSettings storage = GrepSettings.Instance;
- storage.Clear();
- Assert.Empty(storage);
- storage["test"] = "hello";
- storage.Save(sourceFolder + "\\test.xml");
- storage.Clear();
- Assert.Empty(storage);
- storage.Load(sourceFolder + "\\test.xml");
- Assert.True(storage["test"] == "hello");
- }
+ [Fact]
+ public void TestLoad()
+ {
+ GrepSettings storage = GrepSettings.Instance;
+ storage.Clear();
+ Assert.Empty(storage);
+ storage["test"] = "hello";
+ storage.Save(sourceFolder + "\\test.xml");
+ storage.Clear();
+ Assert.Empty(storage);
+ storage.Load(sourceFolder + "\\test.xml");
+ Assert.True(storage["test"] == "hello");
+ }
- [Fact]
- public void TestDataTypes()
- {
- GrepSettings storage = GrepSettings.Instance;
- storage.Clear();
- Assert.Empty(storage);
- storage.Set("size", 10);
- storage.Set("isTrue", true);
- storage.Save(sourceFolder + "\\test.xml");
- storage.Clear();
- Assert.Empty(storage);
- storage.Load(sourceFolder + "\\test.xml");
- Assert.Equal(storage.Get("size"), 10);
- Assert.Equal(storage.Get("isTrue"), true);
- }
- }
+ [Fact]
+ public void TestDataTypes()
+ {
+ GrepSettings storage = GrepSettings.Instance;
+ storage.Clear();
+ Assert.Empty(storage);
+ storage.Set("size", 10);
+ storage.Set("isTrue", true);
+ storage.Save(sourceFolder + "\\test.xml");
+ storage.Clear();
+ Assert.Empty(storage);
+ storage.Load(sourceFolder + "\\test.xml");
+ Assert.Equal(storage.Get("size"), 10);
+ Assert.Equal(storage.Get("isTrue"), true);
+ }
+ }
}
diff --git a/Tests/TestBase.cs b/Tests/TestBase.cs
index f068782a..f1d58565 100644
--- a/Tests/TestBase.cs
+++ b/Tests/TestBase.cs
@@ -1,19 +1,15 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Reflection;
-using System.IO;
+using System.IO;
namespace Tests
{
- public class TestBase
- {
- public string GetDllPath()
- {
- //Assembly thisAssembly = Assembly.GetAssembly(typeof(TestBase));
- //return Path.GetDirectoryName(thisAssembly.Location);
+ public class TestBase
+ {
+ public string GetDllPath()
+ {
+ //Assembly thisAssembly = Assembly.GetAssembly(typeof(TestBase));
+ //return Path.GetDirectoryName(thisAssembly.Location);
//return @"D:\Sandbox\dnGrep\Tests";
return Directory.GetCurrentDirectory();
- }
- }
+ }
+ }
}
diff --git a/Tests/UITest.cs b/Tests/UITest.cs
index c2127e13..d0ad4dd0 100644
--- a/Tests/UITest.cs
+++ b/Tests/UITest.cs
@@ -7,7 +7,7 @@
namespace Tests
{
-
+
public class UITest
{
// No tests yet
diff --git a/dnGREP.ArchiveEngine/GrepEngineArchive.cs b/dnGREP.ArchiveEngine/GrepEngineArchive.cs
index e30a3cc1..d4e6f0a4 100644
--- a/dnGREP.ArchiveEngine/GrepEngineArchive.cs
+++ b/dnGREP.ArchiveEngine/GrepEngineArchive.cs
@@ -10,26 +10,26 @@
namespace dnGREP.Engines.Archive
{
- public class GrepEngineArchive : GrepEngineBase, IGrepEngine
- {
- private static Logger logger = LogManager.GetCurrentClassLogger();
+ public class GrepEngineArchive : GrepEngineBase, IGrepEngine
+ {
+ private static Logger logger = LogManager.GetCurrentClassLogger();
- public GrepEngineArchive() : base() { }
+ public GrepEngineArchive() : base() { }
- public GrepEngineArchive(GrepEngineInitParams param)
- : base(param)
- {}
+ public GrepEngineArchive(GrepEngineInitParams param)
+ : base(param)
+ { }
- public bool IsSearchOnly
- {
- get { return true; }
- }
+ public bool IsSearchOnly
+ {
+ get { return true; }
+ }
public List Search(string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
- {
- List searchResults = new List();
- SevenZipExtractor extractor = new SevenZipExtractor(file);
- string tempFolder = Utils.FixFolderName(Utils.GetTempFolder()) + "dnGREP-Archive\\" + Utils.GetHash(file) + "\\";
+ {
+ List searchResults = new List();
+ SevenZipExtractor extractor = new SevenZipExtractor(file);
+ string tempFolder = Utils.FixFolderName(Utils.GetTempFolder()) + "dnGREP-Archive\\" + Utils.GetHash(file) + "\\";
FileFilter filter = FileFilter.ChangePath(tempFolder);
// if the search pattern(s) only match archive files, need to include an 'any' file type to search inside the archive.
@@ -41,15 +41,15 @@ public List Search(string file, string searchPattern, SearchTy
patterns.Add(FileFilter.IsRegex ? ".*" : "*.*");
filter = filter.ChangeIncludePattern(string.Join(";", patterns.ToArray()));
}
-
- if (Directory.Exists(tempFolder))
- Utils.DeleteFolder(tempFolder);
- Directory.CreateDirectory(tempFolder);
- try
- {
- extractor.ExtractArchive(tempFolder);
+
+ if (Directory.Exists(tempFolder))
+ Utils.DeleteFolder(tempFolder);
+ Directory.CreateDirectory(tempFolder);
+ try
+ {
+ extractor.ExtractArchive(tempFolder);
foreach (var innerFileName in Utils.GetFileListEx(filter))
- {
+ {
IGrepEngine engine = GrepEngineFactory.GetSearchEngine(innerFileName, initParams, FileFilter);
var innerFileResults = engine.Search(innerFileName, searchPattern, searchType, searchOptions, encoding);
@@ -74,62 +74,62 @@ public List Search(string file, string searchPattern, SearchTy
break;
}
- foreach (GrepSearchResult result in searchResults)
- {
- result.FileNameDisplayed = file + "\\" + result.FileNameDisplayed.Substring(tempFolder.Length);
- result.FileNameReal = file;
- result.ReadOnly = true;
+ foreach (GrepSearchResult result in searchResults)
+ {
+ result.FileNameDisplayed = file + "\\" + result.FileNameDisplayed.Substring(tempFolder.Length);
+ result.FileNameReal = file;
+ result.ReadOnly = true;
}
- }
- catch (Exception ex)
- {
- logger.Log(LogLevel.Error, string.Format("Failed to search inside archive '{0}'", file), ex);
- }
- return searchResults;
- }
-
- public void Unload()
- {
- //Do nothing
- }
+ }
+ catch (Exception ex)
+ {
+ logger.Log(LogLevel.Error, string.Format("Failed to search inside archive '{0}'", file), ex);
+ }
+ return searchResults;
+ }
+
+ public void Unload()
+ {
+ //Do nothing
+ }
public bool Replace(string sourceFile, string destinationFile, string searchPattern, string replacePattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
- {
- throw new Exception("The method or operation is not supported.");
- }
-
- public Version FrameworkVersion
- {
- get
- {
+ {
+ throw new Exception("The method or operation is not supported.");
+ }
+
+ public Version FrameworkVersion
+ {
+ get
+ {
return Assembly.GetAssembly(typeof(IGrepEngine)).GetName().Version;
- }
- }
-
- public override void OpenFile(OpenFileArgs args)
- {
- SevenZipExtractor extractor = new SevenZipExtractor(args.SearchResult.FileNameReal);
-
- string tempFolder = Utils.FixFolderName(Utils.GetTempFolder()) + "dnGREP-Archive\\" + Utils.GetHash(args.SearchResult.FileNameReal) + "\\";
-
- if (!Directory.Exists(tempFolder))
- {
- Directory.CreateDirectory(tempFolder);
- try
- {
- extractor.ExtractArchive(tempFolder);
- }
- catch
- {
- args.UseBaseEngine = true;
- }
- }
- GrepSearchResult newResult = new GrepSearchResult();
- newResult.FileNameReal = args.SearchResult.FileNameReal;
- newResult.FileNameDisplayed = args.SearchResult.FileNameDisplayed;
- OpenFileArgs newArgs = new OpenFileArgs(newResult, args.Pattern, args.LineNumber, args.UseCustomEditor, args.CustomEditor, args.CustomEditorArgs);
- newArgs.SearchResult.FileNameDisplayed = tempFolder + args.SearchResult.FileNameDisplayed.Substring(args.SearchResult.FileNameReal.Length + 1);
- Utils.OpenFile(newArgs);
- }
- }
+ }
+ }
+
+ public override void OpenFile(OpenFileArgs args)
+ {
+ SevenZipExtractor extractor = new SevenZipExtractor(args.SearchResult.FileNameReal);
+
+ string tempFolder = Utils.FixFolderName(Utils.GetTempFolder()) + "dnGREP-Archive\\" + Utils.GetHash(args.SearchResult.FileNameReal) + "\\";
+
+ if (!Directory.Exists(tempFolder))
+ {
+ Directory.CreateDirectory(tempFolder);
+ try
+ {
+ extractor.ExtractArchive(tempFolder);
+ }
+ catch
+ {
+ args.UseBaseEngine = true;
+ }
+ }
+ GrepSearchResult newResult = new GrepSearchResult();
+ newResult.FileNameReal = args.SearchResult.FileNameReal;
+ newResult.FileNameDisplayed = args.SearchResult.FileNameDisplayed;
+ OpenFileArgs newArgs = new OpenFileArgs(newResult, args.Pattern, args.LineNumber, args.UseCustomEditor, args.CustomEditor, args.CustomEditorArgs);
+ newArgs.SearchResult.FileNameDisplayed = tempFolder + args.SearchResult.FileNameDisplayed.Substring(args.SearchResult.FileNameReal.Length + 1);
+ Utils.OpenFile(newArgs);
+ }
+ }
}
diff --git a/dnGREP.ArchiveEngine/app.config b/dnGREP.ArchiveEngine/app.config
index 6f934842..af399dd6 100644
--- a/dnGREP.ArchiveEngine/app.config
+++ b/dnGREP.ArchiveEngine/app.config
@@ -1,3 +1,6 @@
-
+
+
+
+
diff --git a/dnGREP.Common.UI/BookmarkDetails.cs b/dnGREP.Common.UI/BookmarkDetails.cs
index 412b0c23..aa32f829 100644
--- a/dnGREP.Common.UI/BookmarkDetails.cs
+++ b/dnGREP.Common.UI/BookmarkDetails.cs
@@ -1,77 +1,71 @@
using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Data;
-using System.Drawing;
-using System.Text;
using System.Windows.Forms;
-using dnGREP.Common;
namespace dnGREP.Common.UI
{
- public partial class BookmarkDetails : Form
- {
- private CreateOrEdit action = CreateOrEdit.Edit;
-
- private Bookmark bookmark = null;
- public Bookmark Bookmark
- {
- get { return bookmark; }
- set { bookmark = value; changeState(); }
- }
+ public partial class BookmarkDetails : Form
+ {
+ private CreateOrEdit action = CreateOrEdit.Edit;
- private void changeState()
- {
- if (action == CreateOrEdit.Create)
- {
- btnCreateOrEdit.Text = "Create";
- }
- else
- {
- btnCreateOrEdit.Text = "Edit";
- }
- if (bookmark != null)
- {
- tbDescription.Text = bookmark.Description;
- tbFileNames.Text = bookmark.FileNames;
- tbReplaceWith.Text = bookmark.ReplacePattern;
- tbSearchFor.Text = bookmark.SearchPattern;
- }
- }
+ private Bookmark bookmark = null;
+ public Bookmark Bookmark
+ {
+ get { return bookmark; }
+ set { bookmark = value; changeState(); }
+ }
- public BookmarkDetails(CreateOrEdit action)
- {
- InitializeComponent();
- this.action = action;
- }
+ private void changeState()
+ {
+ if (action == CreateOrEdit.Create)
+ {
+ btnCreateOrEdit.Text = "Create";
+ }
+ else
+ {
+ btnCreateOrEdit.Text = "Edit";
+ }
+ if (bookmark != null)
+ {
+ tbDescription.Text = bookmark.Description;
+ tbFileNames.Text = bookmark.FileNames;
+ tbReplaceWith.Text = bookmark.ReplacePattern;
+ tbSearchFor.Text = bookmark.SearchPattern;
+ }
+ }
- private void BookmarkDetails_Load(object sender, EventArgs e)
- {
- changeState();
- }
+ public BookmarkDetails(CreateOrEdit action)
+ {
+ InitializeComponent();
+ this.action = action;
+ }
- private void btnCreateOrEdit_Click(object sender, EventArgs e)
- {
- if (bookmark == null)
- bookmark = new Bookmark();
- bookmark.Description = tbDescription.Text;
- bookmark.FileNames = tbFileNames.Text;
- bookmark.SearchPattern = tbSearchFor.Text;
- bookmark.ReplacePattern = tbReplaceWith.Text;
- DialogResult = DialogResult.OK;
- Close();
- }
+ private void BookmarkDetails_Load(object sender, EventArgs e)
+ {
+ changeState();
+ }
- private void formKeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode == Keys.Escape)
- Close();
- }
- }
+ private void btnCreateOrEdit_Click(object sender, EventArgs e)
+ {
+ if (bookmark == null)
+ bookmark = new Bookmark();
+ bookmark.Description = tbDescription.Text;
+ bookmark.FileNames = tbFileNames.Text;
+ bookmark.SearchPattern = tbSearchFor.Text;
+ bookmark.ReplacePattern = tbReplaceWith.Text;
+ DialogResult = DialogResult.OK;
+ Close();
+ }
- public enum CreateOrEdit
- {
- Create,
- Edit
- }
+ private void formKeyDown(object sender, KeyEventArgs e)
+ {
+ if (e.KeyCode == Keys.Escape)
+ Close();
+ }
+ }
+
+ public enum CreateOrEdit
+ {
+ Create,
+ Edit
+ }
}
\ No newline at end of file
diff --git a/dnGREP.Common.UI/BookmarksForm.cs b/dnGREP.Common.UI/BookmarksForm.cs
index 45265e2a..8975ae57 100644
--- a/dnGREP.Common.UI/BookmarksForm.cs
+++ b/dnGREP.Common.UI/BookmarksForm.cs
@@ -1,11 +1,7 @@
using System;
-using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
-using System.Drawing;
-using System.Text;
using System.Windows.Forms;
-using dnGREP.Common;
namespace dnGREP.Common.UI
{
@@ -66,7 +62,7 @@ private void refreshGrid()
gridBookmarks.Refresh();
}
- Action ClearStar;
+ Action ClearStar;
public BookmarksForm(Action clearStar)
{
@@ -172,7 +168,7 @@ private void btnUse_Click(object sender, EventArgs e)
private void doSearch(object sender, EventArgs e)
{
typeTimer.Stop();
-
+
if (string.IsNullOrEmpty(textSearch.Text.Trim()))
{
refreshGrid();
@@ -180,7 +176,7 @@ private void doSearch(object sender, EventArgs e)
}
copyOfBookmarks = BookmarkLibrary.Instance.GetDataTable();
-
+
for (int i = copyOfBookmarks.Rows.Count - 1; i >= 0; i--)
{
DataRow row = copyOfBookmarks.Rows[i];
diff --git a/dnGREP.Common.UI/FileFolderDialog.Win32.cs b/dnGREP.Common.UI/FileFolderDialog.Win32.cs
index 95017722..493e723d 100644
--- a/dnGREP.Common.UI/FileFolderDialog.Win32.cs
+++ b/dnGREP.Common.UI/FileFolderDialog.Win32.cs
@@ -1,132 +1,131 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Runtime.InteropServices;
-using System.Reflection;
using System.IO;
+using System.Text;
using Microsoft.Win32;
namespace dnGREP.Common.UI
{
- public class FileFolderDialogWin32 : CommonDialog
- {
- private OpenFileDialog dialog = new OpenFileDialog();
+ public class FileFolderDialogWin32 : CommonDialog
+ {
+ private OpenFileDialog dialog = new OpenFileDialog();
+
+ public OpenFileDialog Dialog
+ {
+ get { return dialog; }
+ set { dialog = value; }
+ }
- public OpenFileDialog Dialog
- {
- get { return dialog; }
- set { dialog = value; }
- }
+ public override bool? ShowDialog()
+ {
+ return this.ShowDialog(null);
+ }
- public override bool? ShowDialog()
- {
- return this.ShowDialog(null);
- }
+ public new bool? ShowDialog(System.Windows.Window owner)
+ {
+ // Set validate names to false otherwise windows will not let you select "Folder Selection."
+ dialog.ValidateNames = false;
+ dialog.CheckFileExists = false;
+ dialog.CheckPathExists = true;
- public new bool? ShowDialog(System.Windows.Window owner)
- {
- // Set validate names to false otherwise windows will not let you select "Folder Selection."
- dialog.ValidateNames = false;
- dialog.CheckFileExists = false;
- dialog.CheckPathExists = true;
-
- try
- {
- // Set initial directory (used when dialog.FileName is set from outside)
- if (dialog.FileName != null && dialog.FileName != "")
- {
- if (Directory.Exists(dialog.FileName))
- dialog.InitialDirectory = dialog.FileName;
- else
- dialog.InitialDirectory = Utils.GetBaseFolder(dialog.FileName);
- }
- }
- catch
- {
- // Do nothing
- }
+ try
+ {
+ // Set initial directory (used when dialog.FileName is set from outside)
+ if (dialog.FileName != null && dialog.FileName != "")
+ {
+ if (Directory.Exists(dialog.FileName))
+ dialog.InitialDirectory = dialog.FileName;
+ else
+ dialog.InitialDirectory = Utils.GetBaseFolder(dialog.FileName);
+ }
+ }
+ catch
+ {
+ // Do nothing
+ }
- // Always default to Folder Selection.
- dialog.FileName = "Folder Selection.";
+ // Always default to Folder Selection.
+ dialog.FileName = "Folder Selection.";
- if (owner == null)
- return dialog.ShowDialog();
- else
- return dialog.ShowDialog(owner);
- }
+ if (owner == null)
+ return dialog.ShowDialog();
+ else
+ return dialog.ShowDialog(owner);
+ }
- ///
- // Helper property. Parses FilePath into either folder path (if Folder Selection. is set)
- // or returns file path
- ///
- public string SelectedPath
- {
- get {
- try
- {
- if (dialog.FileName != null &&
- (dialog.FileName.EndsWith("Folder Selection.") || !File.Exists(dialog.FileName)) &&
- !Directory.Exists(dialog.FileName))
- {
- return Path.GetDirectoryName(dialog.FileName);
- }
- else
- {
- return dialog.FileName;
- }
- }
- catch
- {
- return dialog.FileName;
- }
- }
- set
- {
- if (value != null && value != "")
- {
- dialog.FileName = value;
- }
- }
- }
+ ///
+ // Helper property. Parses FilePath into either folder path (if Folder Selection. is set)
+ // or returns file path
+ ///
+ public string SelectedPath
+ {
+ get
+ {
+ try
+ {
+ if (dialog.FileName != null &&
+ (dialog.FileName.EndsWith("Folder Selection.") || !File.Exists(dialog.FileName)) &&
+ !Directory.Exists(dialog.FileName))
+ {
+ return Path.GetDirectoryName(dialog.FileName);
+ }
+ else
+ {
+ return dialog.FileName;
+ }
+ }
+ catch
+ {
+ return dialog.FileName;
+ }
+ }
+ set
+ {
+ if (value != null && value != "")
+ {
+ dialog.FileName = value;
+ }
+ }
+ }
- ///
- /// When multiple files are selected returns them as semi-colon seprated string
- ///
- public string SelectedPaths
- {
- get {
- if (dialog.FileNames != null && dialog.FileNames.Length > 1)
- {
- StringBuilder sb = new StringBuilder();
- foreach (string fileName in dialog.FileNames)
- {
- try
- {
- if (File.Exists(fileName))
- sb.Append(fileName + ";");
- }
- catch
- {
- // Go to next
- }
- }
- return sb.ToString();
- }
- else
- {
- return null;
- }
- }
- }
+ ///
+ /// When multiple files are selected returns them as semi-colon seprated string
+ ///
+ public string SelectedPaths
+ {
+ get
+ {
+ if (dialog.FileNames != null && dialog.FileNames.Length > 1)
+ {
+ StringBuilder sb = new StringBuilder();
+ foreach (string fileName in dialog.FileNames)
+ {
+ try
+ {
+ if (File.Exists(fileName))
+ sb.Append(fileName + ";");
+ }
+ catch
+ {
+ // Go to next
+ }
+ }
+ return sb.ToString();
+ }
+ else
+ {
+ return null;
+ }
+ }
+ }
- public override void Reset()
- {
- dialog.Reset();
- }
+ public override void Reset()
+ {
+ dialog.Reset();
+ }
- protected override bool RunDialog(IntPtr hwndOwner)
- {
- return true;
- }
- }
+ protected override bool RunDialog(IntPtr hwndOwner)
+ {
+ return true;
+ }
+ }
}
diff --git a/dnGREP.Common.UI/FileFolderDialog.cs b/dnGREP.Common.UI/FileFolderDialog.cs
index c1cf45db..8075cb95 100644
--- a/dnGREP.Common.UI/FileFolderDialog.cs
+++ b/dnGREP.Common.UI/FileFolderDialog.cs
@@ -1,132 +1,131 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Runtime.InteropServices;
-using System.Reflection;
using System.IO;
+using System.Text;
using System.Windows.Forms;
namespace dnGREP.Common.UI
{
- public class FileFolderDialog : CommonDialog
- {
- private OpenFileDialog dialog = new OpenFileDialog();
+ public class FileFolderDialog : CommonDialog
+ {
+ private OpenFileDialog dialog = new OpenFileDialog();
+
+ public OpenFileDialog Dialog
+ {
+ get { return dialog; }
+ set { dialog = value; }
+ }
- public OpenFileDialog Dialog
- {
- get { return dialog; }
- set { dialog = value; }
- }
+ public new DialogResult ShowDialog()
+ {
+ return this.ShowDialog(null);
+ }
- public new DialogResult ShowDialog()
- {
- return this.ShowDialog(null);
- }
+ public new DialogResult ShowDialog(IWin32Window owner)
+ {
+ // Set validate names to false otherwise windows will not let you select "Folder Selection."
+ dialog.ValidateNames = false;
+ dialog.CheckFileExists = false;
+ dialog.CheckPathExists = true;
- public new DialogResult ShowDialog(IWin32Window owner)
- {
- // Set validate names to false otherwise windows will not let you select "Folder Selection."
- dialog.ValidateNames = false;
- dialog.CheckFileExists = false;
- dialog.CheckPathExists = true;
-
- try
- {
- // Set initial directory (used when dialog.FileName is set from outside)
- if (dialog.FileName != null && dialog.FileName != "")
- {
- if (Directory.Exists(dialog.FileName))
- dialog.InitialDirectory = dialog.FileName;
- else
- dialog.InitialDirectory = Utils.GetBaseFolder(dialog.FileName);
- }
- }
- catch
- {
- // Do nothing
- }
+ try
+ {
+ // Set initial directory (used when dialog.FileName is set from outside)
+ if (dialog.FileName != null && dialog.FileName != "")
+ {
+ if (Directory.Exists(dialog.FileName))
+ dialog.InitialDirectory = dialog.FileName;
+ else
+ dialog.InitialDirectory = Utils.GetBaseFolder(dialog.FileName);
+ }
+ }
+ catch
+ {
+ // Do nothing
+ }
- // Always default to Folder Selection.
- dialog.FileName = "Folder Selection.";
+ // Always default to Folder Selection.
+ dialog.FileName = "Folder Selection.";
- if (owner == null)
- return dialog.ShowDialog();
- else
- return dialog.ShowDialog(owner);
- }
+ if (owner == null)
+ return dialog.ShowDialog();
+ else
+ return dialog.ShowDialog(owner);
+ }
- ///
- // Helper property. Parses FilePath into either folder path (if Folder Selection. is set)
- // or returns file path
- ///
- public string SelectedPath
- {
- get {
- try
- {
- if (dialog.FileName != null &&
- (dialog.FileName.EndsWith("Folder Selection.") || !File.Exists(dialog.FileName)) &&
- !Directory.Exists(dialog.FileName))
- {
- return Path.GetDirectoryName(dialog.FileName);
- }
- else
- {
- return dialog.FileName;
- }
- }
- catch
- {
- return dialog.FileName;
- }
- }
- set
- {
- if (value != null && value != "")
- {
- dialog.FileName = value;
- }
- }
- }
+ ///
+ // Helper property. Parses FilePath into either folder path (if Folder Selection. is set)
+ // or returns file path
+ ///
+ public string SelectedPath
+ {
+ get
+ {
+ try
+ {
+ if (dialog.FileName != null &&
+ (dialog.FileName.EndsWith("Folder Selection.") || !File.Exists(dialog.FileName)) &&
+ !Directory.Exists(dialog.FileName))
+ {
+ return Path.GetDirectoryName(dialog.FileName);
+ }
+ else
+ {
+ return dialog.FileName;
+ }
+ }
+ catch
+ {
+ return dialog.FileName;
+ }
+ }
+ set
+ {
+ if (value != null && value != "")
+ {
+ dialog.FileName = value;
+ }
+ }
+ }
- ///
- /// When multiple files are selected returns them as semi-colon seprated string
- ///
- public string SelectedPaths
- {
- get {
- if (dialog.FileNames != null && dialog.FileNames.Length > 1)
- {
- StringBuilder sb = new StringBuilder();
- foreach (string fileName in dialog.FileNames)
- {
- try
- {
- if (File.Exists(fileName))
- sb.Append(fileName + ";");
- }
- catch
- {
- // Go to next
- }
- }
- return sb.ToString();
- }
- else
- {
- return null;
- }
- }
- }
+ ///
+ /// When multiple files are selected returns them as semi-colon seprated string
+ ///
+ public string SelectedPaths
+ {
+ get
+ {
+ if (dialog.FileNames != null && dialog.FileNames.Length > 1)
+ {
+ StringBuilder sb = new StringBuilder();
+ foreach (string fileName in dialog.FileNames)
+ {
+ try
+ {
+ if (File.Exists(fileName))
+ sb.Append(fileName + ";");
+ }
+ catch
+ {
+ // Go to next
+ }
+ }
+ return sb.ToString();
+ }
+ else
+ {
+ return null;
+ }
+ }
+ }
- public override void Reset()
- {
- dialog.Reset();
- }
+ public override void Reset()
+ {
+ dialog.Reset();
+ }
- protected override bool RunDialog(IntPtr hwndOwner)
- {
- return true;
- }
- }
+ protected override bool RunDialog(IntPtr hwndOwner)
+ {
+ return true;
+ }
+ }
}
diff --git a/dnGREP.Common.UI/FileIcons.cs b/dnGREP.Common.UI/FileIcons.cs
index c21e8a07..175872dc 100644
--- a/dnGREP.Common.UI/FileIcons.cs
+++ b/dnGREP.Common.UI/FileIcons.cs
@@ -1,53 +1,51 @@
using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Windows.Forms;
using System.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Reflection;
using System.Runtime.InteropServices;
+using System.Windows.Forms;
using Microsoft.Win32;
-using System.Reflection;
-using System.IO;
-using System.Drawing.Imaging;
using NLog;
namespace dnGREP.Common.UI
{
- public class FileIcons
- {
- private static ImageList smallIconList = new ImageList();
+ public class FileIcons
+ {
+ private static ImageList smallIconList = new ImageList();
private static Logger logger = LogManager.GetCurrentClassLogger();
- public static ImageList SmallIconList
- {
- get { return smallIconList; }
- }
-
- public static void LoadImageList(string[] extensions)
- {
- try
- {
- smallIconList.ImageSize = new Size(16, 16);
- smallIconList.ColorDepth = ColorDepth.Depth32Bit;
- foreach (string extension in extensions)
- {
- if (!FileIcons.SmallIconList.Images.ContainsKey(extension))
- {
- Bitmap smallIcon = IconHandler.IconFromExtension(extension, IconSize.Small);
+ public static ImageList SmallIconList
+ {
+ get { return smallIconList; }
+ }
+
+ public static void LoadImageList(string[] extensions)
+ {
+ try
+ {
+ smallIconList.ImageSize = new Size(16, 16);
+ smallIconList.ColorDepth = ColorDepth.Depth32Bit;
+ foreach (string extension in extensions)
+ {
+ if (!FileIcons.SmallIconList.Images.ContainsKey(extension))
+ {
+ Bitmap smallIcon = IconHandler.IconFromExtension(extension, IconSize.Small);
if (smallIcon == null)
smallIcon = Properties.Resources.na_icon;
FileIcons.SmallIconList.Images.Add(extension, smallIcon);
- }
-
- }
- smallIconList.Images.Add("%line%", Properties.Resources.line_icon);
- }
- catch
- {
- // DO NOTHING
- }
- }
-
- public static void StoreIcon(string extension, string path)
+ }
+
+ }
+ smallIconList.Images.Add("%line%", Properties.Resources.line_icon);
+ }
+ catch
+ {
+ // DO NOTHING
+ }
+ }
+
+ public static void StoreIcon(string extension, string path)
{
StoreIcon(extension, path, getMimeType(Path.GetExtension(path)));
}
@@ -100,194 +98,194 @@ private static string getMimeType(string sExtension)
}
return "";
}
- }
-
- struct SHFILEINFO
- {
- public IntPtr hIcon;
- public IntPtr iIcon;
- public uint dwAttributes;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
- public string szDisplayName;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
- public string szTypeName;
- };
-
- public enum IconSize : uint
- {
- Large = 0x0, //32x32
- Small = 0x1 //16x16
- }
-
-
-
- //the function that will extract the icons from a file
- public class IconHandler
- {
- const uint SHGFI_ICON = 0x100;
- const uint SHGFI_USEFILEATTRIBUTES = 0x10;
-
- [DllImport("Shell32", CharSet = CharSet.Auto)]
- internal extern static int ExtractIconEx(
- [MarshalAs(UnmanagedType.LPTStr)]
+ }
+
+ struct SHFILEINFO
+ {
+ public IntPtr hIcon;
+ public IntPtr iIcon;
+ public uint dwAttributes;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
+ public string szDisplayName;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
+ public string szTypeName;
+ };
+
+ public enum IconSize : uint
+ {
+ Large = 0x0, //32x32
+ Small = 0x1 //16x16
+ }
+
+
+
+ //the function that will extract the icons from a file
+ public class IconHandler
+ {
+ const uint SHGFI_ICON = 0x100;
+ const uint SHGFI_USEFILEATTRIBUTES = 0x10;
+
+ [DllImport("Shell32", CharSet = CharSet.Auto)]
+ internal extern static int ExtractIconEx(
+ [MarshalAs(UnmanagedType.LPTStr)]
string lpszFile, //size of the icon
- int nIconIndex, //index of the icon
- // (in case we have more
- // then 1 icon in the file
- IntPtr[] phIconLarge, //32x32 icon
- IntPtr[] phIconSmall, //16x16 icon
- int nIcons); //how many to get
-
- [DllImport("shell32.dll")]
- static extern IntPtr SHGetFileInfo(
- string pszPath, //path
- uint dwFileAttributes, //attributes
- ref SHFILEINFO psfi, //struct pointer
- uint cbSizeFileInfo, //size
- uint uFlags); //flags
-
- [DllImport("User32.dll")]
- private static extern int
- DestroyIcon(System.IntPtr hIcon);
- // free up the icon pointers.
-
- //will return an array of icons
- public static Icon[] IconsFromFile(string Filename, IconSize Size)
- {
- int IconCount = ExtractIconEx(Filename, -1,
- null, null, 0); //checks how many icons.
- IntPtr[] IconPtr = new IntPtr[IconCount];
-
- //extracts the icons by the size that was selected.
- if (Size == IconSize.Small)
- ExtractIconEx(Filename, 0, null, IconPtr, IconCount);
- else
- ExtractIconEx(Filename, 0, IconPtr, null, IconCount);
-
- Icon[] IconList = new Icon[IconCount];
-
- //gets the icons in a list.
- for (int i = 0; i < IconCount; i++)
- {
- IconList[i] = (Icon)Icon.FromHandle(IconPtr[i]).Clone();
- DestroyIcon(IconPtr[i]);
- }
-
- return IconList;
- }
-
- //extract one selected by index icon from a file.
- public static Icon IconFromFile(string Filename, IconSize Size, int Index)
- {
- int IconCount = ExtractIconEx(Filename, -1,
- null, null, 0); //checks how many icons.
- if (IconCount < Index) return null; // no icons was found.
-
- IntPtr[] IconPtr = new IntPtr[1];
-
- //extracts the icon that we want in the selected size.
- if (Size == IconSize.Small)
- ExtractIconEx(Filename, Index, null, IconPtr, 1);
- else
- ExtractIconEx(Filename, Index, IconPtr, null, 1);
-
- return GetManagedIcon(IconPtr[0]);
- }
-
- //this will look throw the registry to find if the Extension have an icon.
- public static Bitmap IconFromExtension(string Extension, IconSize Size)
- {
- try
- {
- //add '.' if nessesry
- if (Extension[0] != '.') Extension = '.' + Extension;
-
- //opens the registry for the wanted key.
- RegistryKey Root = Registry.ClassesRoot;
- RegistryKey ExtensionKey = Root.OpenSubKey(Extension);
- ExtensionKey.GetValueNames();
- RegistryKey ApplicationKey =
- Root.OpenSubKey(ExtensionKey.GetValue("").ToString());
-
- //gets the name of the file that have the icon.
- string IconLocation =
- ApplicationKey.OpenSubKey("DefaultIcon").GetValue("").ToString();
- string[] IconPath = IconLocation.Split(',');
-
- if (IconPath[1] == null) IconPath[1] = "0";
- IntPtr[] Large = new IntPtr[1], Small = new IntPtr[1];
-
- //extracts the icon from the file.
- ExtractIconEx(IconPath[0],
- Convert.ToInt16(IconPath[1]), Large, Small, 1);
+ int nIconIndex, //index of the icon
+ // (in case we have more
+ // then 1 icon in the file
+ IntPtr[] phIconLarge, //32x32 icon
+ IntPtr[] phIconSmall, //16x16 icon
+ int nIcons); //how many to get
+
+ [DllImport("shell32.dll")]
+ static extern IntPtr SHGetFileInfo(
+ string pszPath, //path
+ uint dwFileAttributes, //attributes
+ ref SHFILEINFO psfi, //struct pointer
+ uint cbSizeFileInfo, //size
+ uint uFlags); //flags
+
+ [DllImport("User32.dll")]
+ private static extern int
+ DestroyIcon(System.IntPtr hIcon);
+ // free up the icon pointers.
+
+ //will return an array of icons
+ public static Icon[] IconsFromFile(string Filename, IconSize Size)
+ {
+ int IconCount = ExtractIconEx(Filename, -1,
+ null, null, 0); //checks how many icons.
+ IntPtr[] IconPtr = new IntPtr[IconCount];
+
+ //extracts the icons by the size that was selected.
+ if (Size == IconSize.Small)
+ ExtractIconEx(Filename, 0, null, IconPtr, IconCount);
+ else
+ ExtractIconEx(Filename, 0, IconPtr, null, IconCount);
+
+ Icon[] IconList = new Icon[IconCount];
+
+ //gets the icons in a list.
+ for (int i = 0; i < IconCount; i++)
+ {
+ IconList[i] = (Icon)Icon.FromHandle(IconPtr[i]).Clone();
+ DestroyIcon(IconPtr[i]);
+ }
+
+ return IconList;
+ }
+
+ //extract one selected by index icon from a file.
+ public static Icon IconFromFile(string Filename, IconSize Size, int Index)
+ {
+ int IconCount = ExtractIconEx(Filename, -1,
+ null, null, 0); //checks how many icons.
+ if (IconCount < Index) return null; // no icons was found.
+
+ IntPtr[] IconPtr = new IntPtr[1];
+
+ //extracts the icon that we want in the selected size.
+ if (Size == IconSize.Small)
+ ExtractIconEx(Filename, Index, null, IconPtr, 1);
+ else
+ ExtractIconEx(Filename, Index, IconPtr, null, 1);
+
+ return GetManagedIcon(IconPtr[0]);
+ }
+
+ //this will look throw the registry to find if the Extension have an icon.
+ public static Bitmap IconFromExtension(string Extension, IconSize Size)
+ {
+ try
+ {
+ //add '.' if nessesry
+ if (Extension[0] != '.') Extension = '.' + Extension;
+
+ //opens the registry for the wanted key.
+ RegistryKey Root = Registry.ClassesRoot;
+ RegistryKey ExtensionKey = Root.OpenSubKey(Extension);
+ ExtensionKey.GetValueNames();
+ RegistryKey ApplicationKey =
+ Root.OpenSubKey(ExtensionKey.GetValue("").ToString());
+
+ //gets the name of the file that have the icon.
+ string IconLocation =
+ ApplicationKey.OpenSubKey("DefaultIcon").GetValue("").ToString();
+ string[] IconPath = IconLocation.Split(',');
+
+ if (IconPath[1] == null) IconPath[1] = "0";
+ IntPtr[] Large = new IntPtr[1], Small = new IntPtr[1];
+
+ //extracts the icon from the file.
+ ExtractIconEx(IconPath[0],
+ Convert.ToInt16(IconPath[1]), Large, Small, 1);
return GetManagedIcon(Size == IconSize.Large ? Large[0] : Small[0]).ToBitmap();
- }
- catch (Exception e)
- {
- System.Diagnostics.Debug.WriteLine("error while" +
- " trying to get icon for " +
- Extension + " :" + e.Message);
- return null;
- }
- }
- public static Bitmap IconFromExtensionShell(string Extension, IconSize Size)
- {
- try
- {
- //add '.' if nessesry
- if (Extension[0] != '.') Extension = '.' + Extension;
-
- //temp struct for getting file shell info
- SHFILEINFO TempFileInfo = new SHFILEINFO();
-
- SHGetFileInfo(
- Extension,
- 0,
- ref TempFileInfo,
- (uint)Marshal.SizeOf(TempFileInfo),
- SHGFI_ICON | SHGFI_USEFILEATTRIBUTES | (uint)Size);
-
- return GetManagedIcon(TempFileInfo.hIcon).ToBitmap();
- }
- catch (Exception e)
- {
- System.Diagnostics.Debug.WriteLine("error while" +
- " trying to get icon for " + Extension +
- " :" + e.Message);
- return null;
- }
- }
- public static Icon IconFromResource(string ResourceName)
- {
- Assembly TempAssembly = Assembly.GetCallingAssembly();
-
- return new Icon(TempAssembly.GetManifestResourceStream(ResourceName));
- }
-
- public static void SaveIconFromImage(Image SourceImage,
- string IconFilename, IconSize DestenationIconSize)
- {
- Size NewIconSize = DestenationIconSize ==
- IconSize.Large ? new Size(32, 32) : new Size(16, 16);
-
- Bitmap RawImage = new Bitmap(SourceImage, NewIconSize);
- Icon TempIcon = Icon.FromHandle(RawImage.GetHicon());
- FileStream NewIconStream = new FileStream(IconFilename,
- FileMode.Create);
-
- TempIcon.Save(NewIconStream);
-
- NewIconStream.Close();
- }
-
- private static Icon GetManagedIcon(IntPtr hIcon)
- {
- Icon Clone = (Icon)Icon.FromHandle(hIcon).Clone();
-
- DestroyIcon(hIcon);
-
- return Clone;
- }
- }
+ }
+ catch (Exception e)
+ {
+ System.Diagnostics.Debug.WriteLine("error while" +
+ " trying to get icon for " +
+ Extension + " :" + e.Message);
+ return null;
+ }
+ }
+ public static Bitmap IconFromExtensionShell(string Extension, IconSize Size)
+ {
+ try
+ {
+ //add '.' if nessesry
+ if (Extension[0] != '.') Extension = '.' + Extension;
+
+ //temp struct for getting file shell info
+ SHFILEINFO TempFileInfo = new SHFILEINFO();
+
+ SHGetFileInfo(
+ Extension,
+ 0,
+ ref TempFileInfo,
+ (uint)Marshal.SizeOf(TempFileInfo),
+ SHGFI_ICON | SHGFI_USEFILEATTRIBUTES | (uint)Size);
+
+ return GetManagedIcon(TempFileInfo.hIcon).ToBitmap();
+ }
+ catch (Exception e)
+ {
+ System.Diagnostics.Debug.WriteLine("error while" +
+ " trying to get icon for " + Extension +
+ " :" + e.Message);
+ return null;
+ }
+ }
+ public static Icon IconFromResource(string ResourceName)
+ {
+ Assembly TempAssembly = Assembly.GetCallingAssembly();
+
+ return new Icon(TempAssembly.GetManifestResourceStream(ResourceName));
+ }
+
+ public static void SaveIconFromImage(Image SourceImage,
+ string IconFilename, IconSize DestenationIconSize)
+ {
+ Size NewIconSize = DestenationIconSize ==
+ IconSize.Large ? new Size(32, 32) : new Size(16, 16);
+
+ Bitmap RawImage = new Bitmap(SourceImage, NewIconSize);
+ Icon TempIcon = Icon.FromHandle(RawImage.GetHicon());
+ FileStream NewIconStream = new FileStream(IconFilename,
+ FileMode.Create);
+
+ TempIcon.Save(NewIconStream);
+
+ NewIconStream.Close();
+ }
+
+ private static Icon GetManagedIcon(IntPtr hIcon)
+ {
+ Icon Clone = (Icon)Icon.FromHandle(hIcon).Clone();
+
+ DestroyIcon(hIcon);
+
+ return Clone;
+ }
+ }
}
diff --git a/dnGREP.Common/BookmarkLibrary.cs b/dnGREP.Common/BookmarkLibrary.cs
index 209731e3..c0b7d8ef 100644
--- a/dnGREP.Common/BookmarkLibrary.cs
+++ b/dnGREP.Common/BookmarkLibrary.cs
@@ -1,183 +1,180 @@
using System;
using System.Collections.Generic;
-using System.Text;
-using System.Runtime.Serialization;
+using System.Data;
using System.IO;
-using System.IO.IsolatedStorage;
using System.Xml.Serialization;
-using System.Xml;
using NLog;
-using System.Data;
namespace dnGREP.Common
{
- public class BookmarkLibrary
- {
- private static Logger logger = LogManager.GetCurrentClassLogger();
-
- private static BookmarkEntity bookmarks;
-
- public static BookmarkEntity Instance
- {
- get {
- if (bookmarks == null)
- Load();
- return bookmarks;
- }
- }
-
- private BookmarkLibrary() { }
-
- private const string storageFileName = "Bookmarks";
-
- public static void Load()
- {
- try
- {
- BookmarkEntity bookmarkLib;
- XmlSerializer serializer = new XmlSerializer(typeof(BookmarkEntity));
- if (!File.Exists(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
- {
- bookmarks = new BookmarkEntity();
- }
- else
- {
- using (TextReader reader = new StreamReader(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
- {
- bookmarkLib = (BookmarkEntity)serializer.Deserialize(reader);
- bookmarks = bookmarkLib;
- }
- }
- }
- catch
- {
- bookmarks = new BookmarkEntity();
- }
- }
-
- public static void Save()
- {
- try
- {
- XmlSerializer serializer = new XmlSerializer(typeof(BookmarkEntity));
- using (TextWriter writer = new StreamWriter(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
- {
- serializer.Serialize(writer, bookmarks);
- }
- }
- catch (Exception ex)
- {
- logger.Log(LogLevel.Error, ex.Message, ex);
- }
- }
- }
-
- [Serializable]
- public class BookmarkEntity
- {
- private static Logger logger = LogManager.GetCurrentClassLogger();
-
- private List bookmarks = new List();
-
- public List Bookmarks
- {
- get { return bookmarks; }
- set { bookmarks = value; }
- }
-
- public DataTable GetDataTable()
- {
- DataTable bookmarkTable = new DataTable();
- bookmarkTable.Columns.Add("Description", typeof(String));
- bookmarkTable.Columns.Add("SearchPattern", typeof(String));
- bookmarkTable.Columns.Add("ReplacePattern", typeof(String));
- bookmarkTable.Columns.Add("FileNames", typeof(String));
- bookmarks.Sort(new BookmarkComparer());
- foreach (Bookmark b in bookmarks)
- {
- bookmarkTable.LoadDataRow(new string[] {b.Description, b.SearchPattern,
- b.ReplacePattern, b.FileNames}, true);
- }
- return bookmarkTable;
- }
-
- public BookmarkEntity() { }
- }
-
- [Serializable]
- public class Bookmark
- {
- public Bookmark() { }
- public Bookmark(string pattern, string replacement, string files, string desc)
- {
- searchPattern = pattern;
- replacePattern = replacement;
- fileNames = files;
- description = desc;
- }
-
- private string searchPattern;
-
- public string SearchPattern
- {
- get { return searchPattern; }
- set { searchPattern = value; }
- }
- private string replacePattern;
-
- public string ReplacePattern
- {
- get { return replacePattern; }
- set { replacePattern = value; }
- }
- private string fileNames;
-
- public string FileNames
- {
- get { return fileNames; }
- set { fileNames = value; }
- }
- private string description;
-
- public string Description
- {
- get { return description; }
- set { description = value; }
- }
-
- public override bool Equals(object obj)
- {
- if (obj == null || !(obj is Bookmark))
- {
- return false;
- }
- else
- {
- Bookmark otherBookmark = (Bookmark)obj;
- if (this.FileNames == otherBookmark.FileNames &&
- this.ReplacePattern == otherBookmark.ReplacePattern &&
- this.SearchPattern == otherBookmark.SearchPattern)
- return true;
- else
- return false;
- }
- }
- public override int GetHashCode()
- {
- return (FileNames + ReplacePattern + SearchPattern).GetHashCode();
- }
- }
-
- public class BookmarkComparer : IComparer
- {
-
- #region IComparer Members
-
- public int Compare(Bookmark x, Bookmark y)
- {
- return x.SearchPattern.CompareTo(y.SearchPattern);
- }
-
- #endregion
- }
+ public class BookmarkLibrary
+ {
+ private static Logger logger = LogManager.GetCurrentClassLogger();
+
+ private static BookmarkEntity bookmarks;
+
+ public static BookmarkEntity Instance
+ {
+ get
+ {
+ if (bookmarks == null)
+ Load();
+ return bookmarks;
+ }
+ }
+
+ private BookmarkLibrary() { }
+
+ private const string storageFileName = "Bookmarks";
+
+ public static void Load()
+ {
+ try
+ {
+ BookmarkEntity bookmarkLib;
+ XmlSerializer serializer = new XmlSerializer(typeof(BookmarkEntity));
+ if (!File.Exists(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
+ {
+ bookmarks = new BookmarkEntity();
+ }
+ else
+ {
+ using (TextReader reader = new StreamReader(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
+ {
+ bookmarkLib = (BookmarkEntity)serializer.Deserialize(reader);
+ bookmarks = bookmarkLib;
+ }
+ }
+ }
+ catch
+ {
+ bookmarks = new BookmarkEntity();
+ }
+ }
+
+ public static void Save()
+ {
+ try
+ {
+ XmlSerializer serializer = new XmlSerializer(typeof(BookmarkEntity));
+ using (TextWriter writer = new StreamWriter(Utils.GetDataFolderPath() + "\\bookmarks.xml"))
+ {
+ serializer.Serialize(writer, bookmarks);
+ }
+ }
+ catch (Exception ex)
+ {
+ logger.Log(LogLevel.Error, ex.Message, ex);
+ }
+ }
+ }
+
+ [Serializable]
+ public class BookmarkEntity
+ {
+ private static Logger logger = LogManager.GetCurrentClassLogger();
+
+ private List bookmarks = new List();
+
+ public List Bookmarks
+ {
+ get { return bookmarks; }
+ set { bookmarks = value; }
+ }
+
+ public DataTable GetDataTable()
+ {
+ DataTable bookmarkTable = new DataTable();
+ bookmarkTable.Columns.Add("Description", typeof(String));
+ bookmarkTable.Columns.Add("SearchPattern", typeof(String));
+ bookmarkTable.Columns.Add("ReplacePattern", typeof(String));
+ bookmarkTable.Columns.Add("FileNames", typeof(String));
+ bookmarks.Sort(new BookmarkComparer());
+ foreach (Bookmark b in bookmarks)
+ {
+ bookmarkTable.LoadDataRow(new string[] {b.Description, b.SearchPattern,
+ b.ReplacePattern, b.FileNames}, true);
+ }
+ return bookmarkTable;
+ }
+
+ public BookmarkEntity() { }
+ }
+
+ [Serializable]
+ public class Bookmark
+ {
+ public Bookmark() { }
+ public Bookmark(string pattern, string replacement, string files, string desc)
+ {
+ searchPattern = pattern;
+ replacePattern = replacement;
+ fileNames = files;
+ description = desc;
+ }
+
+ private string searchPattern;
+
+ public string SearchPattern
+ {
+ get { return searchPattern; }
+ set { searchPattern = value; }
+ }
+ private string replacePattern;
+
+ public string ReplacePattern
+ {
+ get { return replacePattern; }
+ set { replacePattern = value; }
+ }
+ private string fileNames;
+
+ public string FileNames
+ {
+ get { return fileNames; }
+ set { fileNames = value; }
+ }
+ private string description;
+
+ public string Description
+ {
+ get { return description; }
+ set { description = value; }
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj == null || !(obj is Bookmark))
+ {
+ return false;
+ }
+ else
+ {
+ Bookmark otherBookmark = (Bookmark)obj;
+ if (this.FileNames == otherBookmark.FileNames &&
+ this.ReplacePattern == otherBookmark.ReplacePattern &&
+ this.SearchPattern == otherBookmark.SearchPattern)
+ return true;
+ else
+ return false;
+ }
+ }
+ public override int GetHashCode()
+ {
+ return (FileNames + ReplacePattern + SearchPattern).GetHashCode();
+ }
+ }
+
+ public class BookmarkComparer : IComparer
+ {
+
+ #region IComparer Members
+
+ public int Compare(Bookmark x, Bookmark y)
+ {
+ return x.SearchPattern.CompareTo(y.SearchPattern);
+ }
+
+ #endregion
+ }
}
diff --git a/dnGREP.Common/Enums.cs b/dnGREP.Common/Enums.cs
index 404a6294..26910fbb 100644
--- a/dnGREP.Common/Enums.cs
+++ b/dnGREP.Common/Enums.cs
@@ -1,16 +1,14 @@
using System;
-using System.Collections.Generic;
-using System.Text;
namespace dnGREP.Common
{
- public enum SearchType
- {
- PlainText,
- Regex,
- XPath,
- Soundex
- }
+ public enum SearchType
+ {
+ PlainText,
+ Regex,
+ XPath,
+ Soundex
+ }
public enum FileOpenEditor
{
@@ -18,18 +16,18 @@ public enum FileOpenEditor
Custom
}
- public enum FileSearchType
- {
- Asterisk,
- Regex
- }
+ public enum FileSearchType
+ {
+ Asterisk,
+ Regex
+ }
- public enum FileSizeFilter
- {
+ public enum FileSizeFilter
+ {
None,
- Yes,
- No
- }
+ Yes,
+ No
+ }
[Flags]
public enum GrepSearchOption
@@ -38,17 +36,17 @@ public enum GrepSearchOption
CaseSensitive = 1,
Multiline = 2,
SingleLine = 4,
- WholeWord = 8,
+ WholeWord = 8,
StopAfterFirstMatch = 16
}
- public enum GrepOperation
- {
- Search,
- SearchInResults,
- Replace,
- None
- }
+ public enum GrepOperation
+ {
+ Search,
+ SearchInResults,
+ Replace,
+ None
+ }
public enum FileDateFilter
{
diff --git a/dnGREP.Common/GrepApplicationSettings.cs b/dnGREP.Common/GrepApplicationSettings.cs
index 7560d294..2de05c06 100644
--- a/dnGREP.Common/GrepApplicationSettings.cs
+++ b/dnGREP.Common/GrepApplicationSettings.cs
@@ -1,85 +1,82 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.ComponentModel;
using System.IO;
-using NLog;
-using System.Xml.Serialization;
-using System.Xml;
+using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
-using System.ComponentModel;
-using System.Reflection;
-using System.Windows.Media;
+using System.Xml;
+using System.Xml.Serialization;
+using NLog;
namespace dnGREP.Common
{
- ///
- /// Singleton class used to maintain and persist application settings
- ///
- public class GrepSettings : SerializableDictionary
- {
- public static class Key
- {
- public const string SearchFolder = "SearchFolder";
- public const string SearchFor = "SearchFor";
- public const string ReplaceWith = "ReplaceWith";
+ ///
+ /// Singleton class used to maintain and persist application settings
+ ///
+ public class GrepSettings : SerializableDictionary
+ {
+ public static class Key
+ {
+ public const string SearchFolder = "SearchFolder";
+ public const string SearchFor = "SearchFor";
+ public const string ReplaceWith = "ReplaceWith";
[DefaultValue(true)]
- public const string IncludeHidden = "IncludeHidden";
+ public const string IncludeHidden = "IncludeHidden";
[DefaultValue(true)]
- public const string IncludeBinary = "IncludeBinary";
+ public const string IncludeBinary = "IncludeBinary";
[DefaultValue(true)]
- public const string IncludeSubfolder = "IncludeSubfolder";
+ public const string IncludeSubfolder = "IncludeSubfolder";
[DefaultValue(SearchType.Regex)]
- public const string TypeOfSearch = "TypeOfSearch";
+ public const string TypeOfSearch = "TypeOfSearch";
[DefaultValue(FileSearchType.Asterisk)]
- public const string TypeOfFileSearch = "TypeOfFileSearch";
+ public const string TypeOfFileSearch = "TypeOfFileSearch";
[DefaultValue(-1)]
public const string CodePage = "CodePage";
[DefaultValue("*.*")]
- public const string FilePattern = "FilePattern";
- public const string FilePatternIgnore = "FilePatternIgnore";
+ public const string FilePattern = "FilePattern";
+ public const string FilePatternIgnore = "FilePatternIgnore";
[DefaultValue(FileSizeFilter.No)]
- public const string UseFileSizeFilter = "UseFileSizeFilter";
+ public const string UseFileSizeFilter = "UseFileSizeFilter";
public const string CaseSensitive = "CaseSensitive";
public const string PreviewFileContent = "PreviewFileContent";
- public const string Multiline = "Multiline";
- public const string Singleline = "Singleline";
+ public const string Multiline = "Multiline";
+ public const string Singleline = "Singleline";
public const string StopAfterFirstMatch = "StopAfterFirstMatch";
- public const string WholeWord = "WholeWord";
- public const string SizeFrom = "SizeFrom";
+ public const string WholeWord = "WholeWord";
+ public const string SizeFrom = "SizeFrom";
[DefaultValue(100)]
- public const string SizeTo = "SizeTo";
+ public const string SizeTo = "SizeTo";
[DefaultValue(0.5)]
- public const string FuzzyMatchThreshold = "FuzzyMatchThreshold";
+ public const string FuzzyMatchThreshold = "FuzzyMatchThreshold";
[DefaultValue(true)]
public const string ShowLinesInContext = "ShowLinesInContext";
[DefaultValue(2)]
- public const string ContextLinesBefore = "ContextLinesBefore";
+ public const string ContextLinesBefore = "ContextLinesBefore";
[DefaultValue(3)]
- public const string ContextLinesAfter = "ContextLinesAfter";
- [DefaultValue(true)]
- public const string EnableUpdateChecking = "EnableUpdateChecking";
+ public const string ContextLinesAfter = "ContextLinesAfter";
+ [DefaultValue(true)]
+ public const string EnableUpdateChecking = "EnableUpdateChecking";
[DefaultValue(10)]
public const string UpdateCheckInterval = "UpdateCheckInterval";
public const string LastCheckedVersion = "LastCheckedVersion";
[DefaultValue(true)]
- public const string ShowFilePathInResults = "ShowFilePathInResults";
+ public const string ShowFilePathInResults = "ShowFilePathInResults";
[DefaultValue(true)]
- public const string AllowSearchingForFileNamePattern = "AllowSearchingForFileNamePattern";
- public const string CustomEditor = "CustomEditor";
- public const string CustomEditorArgs = "CustomEditorArgs";
+ public const string AllowSearchingForFileNamePattern = "AllowSearchingForFileNamePattern";
+ public const string CustomEditor = "CustomEditor";
+ public const string CustomEditorArgs = "CustomEditorArgs";
public const string ExpandResults = "ExpandResults";
[DefaultValue(true)]
public const string ShowVerboseMatchCount = "ShowVerboseMatchCount";
[DefaultValue(false)]
public const string IsFiltersExpanded = "IsFiltersExpanded";
public const string FileFilters = "FileFilters";
- public const string FastSearchBookmarks = "FastSearchBookmarks";
- public const string FastReplaceBookmarks = "FastReplaceBookmarks";
- public const string FastFileMatchBookmarks = "FastFileMatchBookmarks";
- public const string FastFileNotMatchBookmarks = "FastFileNotMatchBookmarks";
- public const string FastPathBookmarks = "FastPathBookmarks";
+ public const string FastSearchBookmarks = "FastSearchBookmarks";
+ public const string FastReplaceBookmarks = "FastReplaceBookmarks";
+ public const string FastFileMatchBookmarks = "FastFileMatchBookmarks";
+ public const string FastFileNotMatchBookmarks = "FastFileNotMatchBookmarks";
+ public const string FastPathBookmarks = "FastPathBookmarks";
[DefaultValue(12)]
public const string PreviewWindowFont = "PreviewWindowFont";
[DefaultValue(false)]
@@ -103,150 +100,150 @@ public static class Key
public const string HoursFrom = "HoursFrom";
[DefaultValue(8)]
public const string HoursTo = "HoursTo";
- }
-
- private static GrepSettings instance;
- private static Logger logger = LogManager.GetCurrentClassLogger();
- private const string storageFileName = "dnGREP.Settings.dat";
-
- private GrepSettings() { }
-
- public static GrepSettings Instance
- {
- get
- {
- if (instance == null)
- {
- instance = new GrepSettings();
- instance.Load();
- }
- return instance;
- }
- }
-
- ///
- /// Loads settings from default location - baseFolder\\dnGREP.Settings.dat
- ///
- public void Load()
- {
- Load(Utils.GetDataFolderPath() + "\\" + storageFileName);
- }
-
- ///
- /// Load settings from location specified
- ///
- /// Path to settings file
- public void Load(string path)
- {
- try
- {
- if (!File.Exists(path))
- return;
+ }
+
+ private static GrepSettings instance;
+ private static Logger logger = LogManager.GetCurrentClassLogger();
+ private const string storageFileName = "dnGREP.Settings.dat";
+
+ private GrepSettings() { }
+
+ public static GrepSettings Instance
+ {
+ get
+ {
+ if (instance == null)
+ {
+ instance = new GrepSettings();
+ instance.Load();
+ }
+ return instance;
+ }
+ }
+
+ ///
+ /// Loads settings from default location - baseFolder\\dnGREP.Settings.dat
+ ///
+ public void Load()
+ {
+ Load(Utils.GetDataFolderPath() + "\\" + storageFileName);
+ }
+
+ ///
+ /// Load settings from location specified
+ ///
+ /// Path to settings file
+ public void Load(string path)
+ {
+ try
+ {
+ if (!File.Exists(path))
+ return;
using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- {
- if (stream == null)
- return;
- XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary));
- this.Clear();
- SerializableDictionary appData = (SerializableDictionary)serializer.Deserialize(stream);
- foreach (KeyValuePair pair in appData)
- this[pair.Key] = pair.Value;
- }
- }
- catch (Exception ex)
- {
- logger.Log(LogLevel.Error, "Failed to load settings", ex);
- }
- }
-
- ///
- /// Saves settings to default location - baseFolder\\dnGREP.Settings.dat
- ///
- public void Save()
- {
- Save(Utils.GetDataFolderPath() + "\\" + storageFileName);
- }
-
- ///
- /// Saves settings to location specified
- ///
- /// Path to settings file
- public void Save(string path)
- {
- try
- {
- if (!Directory.Exists(Path.GetDirectoryName(path)))
- Directory.CreateDirectory(Path.GetDirectoryName(path));
-
- lock (this)
- {
- // Create temp file in case save crashes
+ {
+ if (stream == null)
+ return;
+ XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary));
+ this.Clear();
+ SerializableDictionary appData = (SerializableDictionary)serializer.Deserialize(stream);
+ foreach (KeyValuePair pair in appData)
+ this[pair.Key] = pair.Value;
+ }
+ }
+ catch (Exception ex)
+ {
+ logger.Log(LogLevel.Error, "Failed to load settings", ex);
+ }
+ }
+
+ ///
+ /// Saves settings to default location - baseFolder\\dnGREP.Settings.dat
+ ///
+ public void Save()
+ {
+ Save(Utils.GetDataFolderPath() + "\\" + storageFileName);
+ }
+
+ ///
+ /// Saves settings to location specified
+ ///
+ /// Path to settings file
+ public void Save(string path)
+ {
+ try
+ {
+ if (!Directory.Exists(Path.GetDirectoryName(path)))
+ Directory.CreateDirectory(Path.GetDirectoryName(path));
+
+ lock (this)
+ {
+ // Create temp file in case save crashes
using (FileStream stream = File.OpenWrite(path + "~"))
using (XmlWriter xmlStream = XmlWriter.Create(stream, new XmlWriterSettings { Indent = false }))
- {
+ {
if (xmlStream == null)
- return;
- XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary));
+ return;
+ XmlSerializer serializer = new XmlSerializer(typeof(SerializableDictionary));
serializer.Serialize(xmlStream, this);
- }
- File.Copy(path + "~", path, true);
- Utils.DeleteFile(path + "~");
- }
- }
- catch (Exception ex)
- {
- logger.Log(LogLevel.Error, "Failed to load settings", ex);
- }
- }
-
- public new string this[string key]
- {
- get { return ContainsKey(key) ? base[key] : null; }
- set { base[key] = value; }
- }
-
- ///
- /// Gets value of object in dictionary and deserializes it to specified type
- ///
- /// Type of object to deserialize from
- /// Key
- ///
- public T Get(string key)
- {
- string value = this[key];
-
- if (value == null)
+ }
+ File.Copy(path + "~", path, true);
+ Utils.DeleteFile(path + "~");
+ }
+ }
+ catch (Exception ex)
+ {
+ logger.Log(LogLevel.Error, "Failed to load settings", ex);
+ }
+ }
+
+ public new string this[string key]
+ {
+ get { return ContainsKey(key) ? base[key] : null; }
+ set { base[key] = value; }
+ }
+
+ ///
+ /// Gets value of object in dictionary and deserializes it to specified type
+ ///
+ /// Type of object to deserialize from
+ /// Key
+ ///
+ public T Get(string key)
+ {
+ string value = this[key];
+
+ if (value == null)
return getDefaultValue(key);
- try
- {
- if (typeof(T) == typeof(string))
- {
+ try
+ {
+ if (typeof(T) == typeof(string))
+ {
return (T)Convert.ChangeType(value.Replace("
", "\n").Replace("
", "\r"), typeof(string));
- }
- else if (typeof(T).IsEnum)
- {
- return (T)Enum.Parse(typeof(T), value);
- }
- else if (!typeof(T).IsPrimitive)
- {
- using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(value)))
- {
- IFormatter formatter = new BinaryFormatter();
- return (T)formatter.Deserialize(stream);
- }
- }
- else
- {
- return (T)Convert.ChangeType(value, typeof(T));
- }
- }
- catch
- {
+ }
+ else if (typeof(T).IsEnum)
+ {
+ return (T)Enum.Parse(typeof(T), value);
+ }
+ else if (!typeof(T).IsPrimitive)
+ {
+ using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(value)))
+ {
+ IFormatter formatter = new BinaryFormatter();
+ return (T)formatter.Deserialize(stream);
+ }
+ }
+ else
+ {
+ return (T)Convert.ChangeType(value, typeof(T));
+ }
+ }
+ catch
+ {
return getDefaultValue(key);
- }
- }
+ }
+ }
///
/// Special handling for nullable value
@@ -282,43 +279,43 @@ public bool IsSet(string key)
return true;
}
- ///
- /// Sets value of object in dictionary and serializes it to specified type
- ///
- /// Type of object to serialize into
- ///
- ///
- public void Set(string key, T value)
- {
- if (value == null)
- return;
-
- if (typeof(T) == typeof(string))
- {
- this[key] = value.ToString().Replace("\n", "
").Replace("\r", "
");
- }
- else if (typeof(T).IsEnum)
- {
- this[key] = value.ToString();
- }
- else if (!typeof(T).IsPrimitive)
- {
- using (MemoryStream stream = new MemoryStream())
- {
- IFormatter formatter = new BinaryFormatter();
- formatter.Serialize(stream, value);
- stream.Position = 0;
- this[key] = Convert.ToBase64String(stream.ToArray());
- }
- }
- else
- {
- this[key] = value.ToString();
- }
- }
+ ///
+ /// Sets value of object in dictionary and serializes it to specified type
+ ///
+ /// Type of object to serialize into
+ ///
+ ///
+ public void Set(string key, T value)
+ {
+ if (value == null)
+ return;
+
+ if (typeof(T) == typeof(string))
+ {
+ this[key] = value.ToString().Replace("\n", "
").Replace("\r", "
");
+ }
+ else if (typeof(T).IsEnum)
+ {
+ this[key] = value.ToString();
+ }
+ else if (!typeof(T).IsPrimitive)
+ {
+ using (MemoryStream stream = new MemoryStream())
+ {
+ IFormatter formatter = new BinaryFormatter();
+ formatter.Serialize(stream, value);
+ stream.Position = 0;
+ this[key] = Convert.ToBase64String(stream.ToArray());
+ }
+ }
+ else
+ {
+ this[key] = value.ToString();
+ }
+ }
private List constantKeys;
- private T getDefaultValue(string key)
+ private T getDefaultValue(string key)
{
if (constantKeys == null)
{
@@ -342,54 +339,54 @@ private T getDefaultValue(string key)
return default(T);
}
- }
-
-
-
- ///
- /// Serializable generic dictionary
- ///
- ///
- ///
- [XmlRoot("dictionary")]
- public class SerializableDictionary: Dictionary, IXmlSerializable
- {
- #region IXmlSerializable Members
- public System.Xml.Schema.XmlSchema GetSchema()
- {
- return null;
- }
-
- public void ReadXml(System.Xml.XmlReader reader)
- {
- bool wasEmpty = reader.IsEmptyElement;
-
- if (wasEmpty)
- return;
+ }
+
+
+
+ ///
+ /// Serializable generic dictionary
+ ///
+ ///
+ ///
+ [XmlRoot("dictionary")]
+ public class SerializableDictionary : Dictionary, IXmlSerializable
+ {
+ #region IXmlSerializable Members
+ public System.Xml.Schema.XmlSchema GetSchema()
+ {
+ return null;
+ }
+
+ public void ReadXml(System.Xml.XmlReader reader)
+ {
+ bool wasEmpty = reader.IsEmptyElement;
+
+ if (wasEmpty)
+ return;
reader.Read();
while (reader.NodeType == XmlNodeType.Element)
- {
- string key = reader.GetAttribute("key");
+ {
+ string key = reader.GetAttribute("key");
string value = reader.ReadElementContentAsString();
this[key] = value;
- }
- reader.ReadEndElement();
- }
+ }
+ reader.ReadEndElement();
+ }
- public void WriteXml(System.Xml.XmlWriter writer)
- {
- foreach (var key in this.Keys)
- {
- writer.WriteStartElement("item");
+ public void WriteXml(System.Xml.XmlWriter writer)
+ {
+ foreach (var key in this.Keys)
+ {
+ writer.WriteStartElement("item");
writer.WriteAttributeString("key", key);
- string value = this[key];
+ string value = this[key];
writer.WriteString(value);
- writer.WriteEndElement();
- }
- }
- #endregion
- }
+ writer.WriteEndElement();
+ }
+ }
+ #endregion
+ }
}
diff --git a/dnGREP.Common/GrepSearchResult.cs b/dnGREP.Common/GrepSearchResult.cs
index 4c7526ca..5391d3ba 100644
--- a/dnGREP.Common/GrepSearchResult.cs
+++ b/dnGREP.Common/GrepSearchResult.cs
@@ -5,17 +5,17 @@
namespace dnGREP.Common
{
- public class GrepSearchResult
- {
- public GrepSearchResult()
- {
+ public class GrepSearchResult
+ {
+ public GrepSearchResult()
+ {
isSuccess = true;
}
public GrepSearchResult(string file, string pattern, List matches, Encoding encoding)
: this(file, pattern, matches, encoding, true)
- {
- }
+ {
+ }
public GrepSearchResult(string file, string pattern, List matches, Encoding encoding, bool success)
{
@@ -38,13 +38,13 @@ public GrepSearchResult(string file, string pattern, string errorMessage, bool s
public Encoding Encoding { get; private set; }
- private string fileName;
+ private string fileName;
- public string FileNameDisplayed
- {
- get { return fileName; }
- set { fileName = value; }
- }
+ public string FileNameDisplayed
+ {
+ get { return fileName; }
+ set { fileName = value; }
+ }
private string pattern;
@@ -54,34 +54,35 @@ public string Pattern
set { pattern = value; }
}
- private string fileNameToOpen = null;
-
- ///
- /// Use this property if FileNameDisplayed is not the same as FileNameReal.
- /// If null, FileNameDisplayed is used.
- ///
- ///
- /// Files in archive have the following FileNameDisplayed "c:\path-to-archive\archive.zip\file1.txt" while
- /// FileNameReal is ""c:\path-to-archive\archive.zip".
- ///
- public string FileNameReal
- {
- get {
- if (fileNameToOpen == null)
- return fileName;
- else
- return fileNameToOpen;
- }
- set { fileNameToOpen = value; }
- }
-
- private bool readOnly = false;
-
- public bool ReadOnly
- {
- get { return readOnly; }
- set { readOnly = value; }
- }
+ private string fileNameToOpen = null;
+
+ ///
+ /// Use this property if FileNameDisplayed is not the same as FileNameReal.
+ /// If null, FileNameDisplayed is used.
+ ///
+ ///
+ /// Files in archive have the following FileNameDisplayed "c:\path-to-archive\archive.zip\file1.txt" while
+ /// FileNameReal is ""c:\path-to-archive\archive.zip".
+ ///
+ public string FileNameReal
+ {
+ get
+ {
+ if (fileNameToOpen == null)
+ return fileName;
+ else
+ return fileNameToOpen;
+ }
+ set { fileNameToOpen = value; }
+ }
+
+ private bool readOnly = false;
+
+ public bool ReadOnly
+ {
+ get { return readOnly; }
+ set { readOnly = value; }
+ }
private List searchResults;
@@ -90,9 +91,9 @@ public bool HasSearchResults
get { return searchResults != null; }
}
- public List SearchResults
- {
- get
+ public List SearchResults
+ {
+ get
{
return GetLinesWithContext(GrepSettings.Instance.Get(GrepSettings.Key.ContextLinesBefore),
GrepSettings.Instance.Get(GrepSettings.Key.ContextLinesAfter));
@@ -101,7 +102,7 @@ public List SearchResults
{
searchResults = value;
}
- }
+ }
public List GetLinesWithContext(int linesBefore, int linesAfter)
@@ -138,38 +139,38 @@ public bool IsSuccess
get { return isSuccess; }
}
- public class GrepLine : IComparable, IComparable
- {
- public GrepLine(int number, string text, bool context, List matches)
- {
- lineNumber = number;
- lineText = text;
- isContext = context;
+ public class GrepLine : IComparable, IComparable
+ {
+ public GrepLine(int number, string text, bool context, List matches)
+ {
+ lineNumber = number;
+ lineText = text;
+ isContext = context;
if (matches == null)
this.matches = new List();
else
this.matches = matches;
- }
+ }
- private int lineNumber;
+ private int lineNumber;
- public int LineNumber
- {
- get { return lineNumber; }
- set { lineNumber = value; }
- }
- private string lineText;
+ public int LineNumber
+ {
+ get { return lineNumber; }
+ set { lineNumber = value; }
+ }
+ private string lineText;
- public string LineText
- {
- get { return lineText; }
- }
- private bool isContext = false;
+ public string LineText
+ {
+ get { return lineText; }
+ }
+ private bool isContext = false;
- public bool IsContext
- {
- get { return isContext; }
- }
+ public bool IsContext
+ {
+ get { return isContext; }
+ }
private List matches;
@@ -178,37 +179,37 @@ public List Matches
get { return matches; }
}
- public override string ToString()
- {
- return string.Format("{0}. {1} ({2})", lineNumber, lineText, isContext);
- }
+ public override string ToString()
+ {
+ return string.Format("{0}. {1} ({2})", lineNumber, lineText, isContext);
+ }
- #region IComparable Members
+ #region IComparable Members
- public int CompareTo(GrepLine other)
- {
- if (other == null)
- return 1;
- else
- return lineNumber.CompareTo(other.LineNumber);
- }
+ public int CompareTo(GrepLine other)
+ {
+ if (other == null)
+ return 1;
+ else
+ return lineNumber.CompareTo(other.LineNumber);
+ }
- #endregion
+ #endregion
- #region IComparable Members
+ #region IComparable Members
- public int CompareTo(object obj)
- {
- if (obj == null)
- return 1;
- if (obj is GrepLine)
- return lineNumber.CompareTo(((GrepLine)obj).LineNumber);
- else
- return 1;
- }
+ public int CompareTo(object obj)
+ {
+ if (obj == null)
+ return 1;
+ if (obj is GrepLine)
+ return lineNumber.CompareTo(((GrepLine)obj).LineNumber);
+ else
+ return 1;
+ }
- #endregion
- }
+ #endregion
+ }
public enum GrepMatchTails
{
@@ -217,7 +218,7 @@ public enum GrepMatchTails
EndOfLineOrFile
}
- public class GrepMatch : IComparable, IComparable
+ public class GrepMatch : IComparable, IComparable
{
public GrepMatch(int line, int start, int length)
{
@@ -253,36 +254,37 @@ public int EndPosition
{
return startLocation + length;
}
- set {
- length = value - startLocation;
+ set
+ {
+ length = value - startLocation;
}
}
- #region IComparable Members
+ #region IComparable Members
- public int CompareTo(GrepMatch other)
- {
- if (other == null)
- return 1;
- else
- return startLocation.CompareTo(other.StartLocation);
- }
+ public int CompareTo(GrepMatch other)
+ {
+ if (other == null)
+ return 1;
+ else
+ return startLocation.CompareTo(other.StartLocation);
+ }
- #endregion
+ #endregion
- #region IComparable Members
+ #region IComparable Members
- public int CompareTo(object obj)
- {
- if (obj == null)
- return 1;
- if (obj is GrepMatch)
- return startLocation.CompareTo(((GrepMatch)obj).StartLocation);
- else
- return 1;
- }
+ public int CompareTo(object obj)
+ {
+ if (obj == null)
+ return 1;
+ if (obj is GrepMatch)
+ return startLocation.CompareTo(((GrepMatch)obj).StartLocation);
+ else
+ return 1;
+ }
- #endregion
+ #endregion
}
- }
+ }
}
diff --git a/dnGREP.Common/OpenFileArgs.cs b/dnGREP.Common/OpenFileArgs.cs
index dfa67da6..86909b6a 100644
--- a/dnGREP.Common/OpenFileArgs.cs
+++ b/dnGREP.Common/OpenFileArgs.cs
@@ -1,20 +1,18 @@
using System;
-using System.Collections.Generic;
-using System.Text;
namespace dnGREP.Common
{
- public class OpenFileArgs : EventArgs
- {
- private GrepSearchResult searchResult;
- ///
- /// Search result containing file name
- ///
- public GrepSearchResult SearchResult
- {
- get { return searchResult; }
- set { searchResult = value; }
- }
+ public class OpenFileArgs : EventArgs
+ {
+ private GrepSearchResult searchResult;
+ ///
+ /// Search result containing file name
+ ///
+ public GrepSearchResult SearchResult
+ {
+ get { return searchResult; }
+ set { searchResult = value; }
+ }
private string pattern;
///
@@ -25,72 +23,72 @@ public string Pattern
get { return pattern; }
set { pattern = value; }
}
- private int lineNumber;
+ private int lineNumber;
- ///
- /// Line number
- ///
- public int LineNumber
- {
- get { return lineNumber; }
- set { lineNumber = value; }
- }
- private bool useCustomEditor;
+ ///
+ /// Line number
+ ///
+ public int LineNumber
+ {
+ get { return lineNumber; }
+ set { lineNumber = value; }
+ }
+ private bool useCustomEditor;
- ///
- /// If true, CustomEditor is used to open the file
- ///
- public bool UseCustomEditor
- {
- get { return useCustomEditor; }
- set { useCustomEditor = value; }
- }
- private string customEditor;
+ ///
+ /// If true, CustomEditor is used to open the file
+ ///
+ public bool UseCustomEditor
+ {
+ get { return useCustomEditor; }
+ set { useCustomEditor = value; }
+ }
+ private string customEditor;
- ///
- /// Path to custom editor (if UseCustomEditor is true)
- ///
- public string CustomEditor
- {
- get { return customEditor; }
- set { customEditor = value; }
- }
- private string customEditorArgs;
+ ///
+ /// Path to custom editor (if UseCustomEditor is true)
+ ///
+ public string CustomEditor
+ {
+ get { return customEditor; }
+ set { customEditor = value; }
+ }
+ private string customEditorArgs;
- ///
- /// Command line arguments for custom editor
- ///
- public string CustomEditorArgs
- {
- get { return customEditorArgs; }
- set { customEditorArgs = value; }
- }
+ ///
+ /// Command line arguments for custom editor
+ ///
+ public string CustomEditorArgs
+ {
+ get { return customEditorArgs; }
+ set { customEditorArgs = value; }
+ }
- private bool useBaseEngine;
+ private bool useBaseEngine;
- ///
- /// Set to true to have base engine handle the request
- ///
- public bool UseBaseEngine
- {
- get { return useBaseEngine; }
- set { useBaseEngine = value; }
- }
+ ///
+ /// Set to true to have base engine handle the request
+ ///
+ public bool UseBaseEngine
+ {
+ get { return useBaseEngine; }
+ set { useBaseEngine = value; }
+ }
- public OpenFileArgs(GrepSearchResult searchResult, string pattern, int line, bool useCustomEditor, string customEditor, string customEditorArgs)
- : base()
- {
- this.searchResult = searchResult;
- this.lineNumber = line;
- this.useCustomEditor = useCustomEditor;
- this.customEditor = customEditor;
- this.customEditorArgs = customEditorArgs;
- this.useBaseEngine = false;
+ public OpenFileArgs(GrepSearchResult searchResult, string pattern, int line, bool useCustomEditor, string customEditor, string customEditorArgs)
+ : base()
+ {
+ this.searchResult = searchResult;
+ this.lineNumber = line;
+ this.useCustomEditor = useCustomEditor;
+ this.customEditor = customEditor;
+ this.customEditorArgs = customEditorArgs;
+ this.useBaseEngine = false;
this.pattern = pattern;
- }
-
- public OpenFileArgs()
- : this(null, null, -1, false, null, null)
- { }
- }
+ }
+
+ public OpenFileArgs()
+ : this(null, null, -1, false, null, null)
+ { }
+ }
}
diff --git a/dnGREP.Common/SearchDelegates.cs b/dnGREP.Common/SearchDelegates.cs
index f1cd0dfd..78419b49 100644
--- a/dnGREP.Common/SearchDelegates.cs
+++ b/dnGREP.Common/SearchDelegates.cs
@@ -1,12 +1,10 @@
-using System;
using System.Collections.Generic;
-using System.Text;
namespace dnGREP.Common
{
- public class SearchDelegates
- {
+ public class SearchDelegates
+ {
public delegate List DoSearch(int lineNumber, string text, string searchPattern, GrepSearchOption searchOptions, bool includeContext);
public delegate string DoReplace(string text, string searchPattern, string replacePattern, GrepSearchOption searchOptions);
- }
+ }
}
diff --git a/dnGREP.Common/Ude/CharsetDetector.cs b/dnGREP.Common/Ude/CharsetDetector.cs
index 0d85e71d..bac99862 100644
--- a/dnGREP.Common/Ude/CharsetDetector.cs
+++ b/dnGREP.Common/Ude/CharsetDetector.cs
@@ -36,7 +36,6 @@
*
* ***** END LICENSE BLOCK ***** */
-using System;
using System.IO;
using Ude.Core;
@@ -72,18 +71,19 @@ namespace Ude
public class CharsetDetector : UniversalDetector, ICharsetDetector
{
private string charset;
-
+
private float confidence;
-
+
//public event DetectorFinished Finished;
-
- public CharsetDetector() : base(FILTER_ALL)
+
+ public CharsetDetector()
+ : base(FILTER_ALL)
{
-
+
}
public void Feed(Stream stream)
- {
+ {
byte[] buff = new byte[1024];
int read;
while ((read = stream.Read(buff, 0, buff.Length)) > 0 && !done)
@@ -91,37 +91,39 @@ public void Feed(Stream stream)
Feed(buff, 0, read);
}
}
-
- public bool IsDone()
+
+ public bool IsDone()
{
return done;
}
-
+
public override void Reset()
{
this.charset = null;
this.confidence = 0.0f;
base.Reset();
}
-
- public string Charset {
+
+ public string Charset
+ {
get { return charset; }
}
- public float Confidence {
+ public float Confidence
+ {
get { return confidence; }
}
-
+
protected override void Report(string charset, float confidence)
{
this.charset = charset;
this.confidence = confidence;
-// if (Finished != null) {
-// Finished(charset, confidence);
-// }
+ // if (Finished != null) {
+ // Finished(charset, confidence);
+ // }
}
}
-
+
//public delegate void DetectorFinished(string charset, float confidence);
}
diff --git a/dnGREP.Common/Ude/DetectionConfidence.cs b/dnGREP.Common/Ude/DetectionConfidence.cs
index 9c30e0bd..4537a887 100644
--- a/dnGREP.Common/Ude/DetectionConfidence.cs
+++ b/dnGREP.Common/Ude/DetectionConfidence.cs
@@ -35,7 +35,6 @@
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
-using System;
namespace Ude
{
diff --git a/dnGREP.Common/Ude/ICharsetDetector.cs b/dnGREP.Common/Ude/ICharsetDetector.cs
index d53da894..cc1bb518 100644
--- a/dnGREP.Common/Ude/ICharsetDetector.cs
+++ b/dnGREP.Common/Ude/ICharsetDetector.cs
@@ -47,12 +47,12 @@ public interface ICharsetDetector
/// The detected charset. It can be null.
///
string Charset { get; }
-
+
///
/// The confidence of the detected charset, if any
///
float Confidence { get; }
-
+
///
/// Feed a block of bytes to the detector.
///
@@ -60,7 +60,7 @@ public interface ICharsetDetector
/// offset into buffer
/// number of available bytes
void Feed(byte[] buf, int offset, int len);
-
+
///
/// Feed a bytes stream to the detector.
///
@@ -71,7 +71,7 @@ public interface ICharsetDetector
/// Resets the state of the detector.
///
void Reset();
-
+
///
/// Returns true if the detector has found a result and it is sure about it.
///
@@ -83,6 +83,6 @@ public interface ICharsetDetector
/// decision.
///
void DataEnd();
-
+
}
}
diff --git a/dnGREP.Common/Utils.cs b/dnGREP.Common/Utils.cs
index 04732c23..61c50fbf 100644
--- a/dnGREP.Common/Utils.cs
+++ b/dnGREP.Common/Utils.cs
@@ -412,7 +412,7 @@ public static bool IsArchive(string srcFile)
}
return false;
}
-
+
///
/// Returns true if the parameter is a recognized archive file format file extension.
///
diff --git a/dnGREP.Engines/GoogleMatch.cs b/dnGREP.Engines/GoogleMatch.cs
index 46e9da1a..289c94a5 100644
--- a/dnGREP.Engines/GoogleMatch.cs
+++ b/dnGREP.Engines/GoogleMatch.cs
@@ -21,9 +21,6 @@
using System;
using System.Collections.Generic;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Web;
using dnGREP.Common;
namespace dnGREP.Engines
@@ -43,7 +40,7 @@ public class GoogleMatch
// A match this many characters away from the expected location will add
// 1.0 to the score (0.0 is a perfect match).
public int Match_Distance = 1000;
-
+
// MATCH FUNCTIONS
@@ -83,48 +80,48 @@ public int match_main(string text, string pattern, int loc)
public int match_length(string text, string pattern, int loc, bool isWholeWord, double threashold)
{
- // Case 0: pattern.length = 0 or text.length = 0
- if (text == null || pattern == null || text.Length == 0 || pattern.Length == 0)
- return 0;
- // Case 1: exact match
- if (loc + pattern.Length < text.Length &&
- text.Substring(loc, pattern.Length).ToLower() == pattern.ToLower())
- {
- if (!(isWholeWord && loc + pattern.Length < text.Length && !Utils.IsValidEndText(text.Substring(loc, pattern.Length + 1))))
- return pattern.Length;
- }
- // Case 2: not exact match
- int counter = 0;
- double matchIndex = 0;
- string matchWord = "";
- NeedlemanWunch nw = new NeedlemanWunch();
- while (counter < pattern.Length * 2)
- {
- if (counter + loc < text.Length)
- {
- counter++;
- string tempMatchWord = text.Substring(loc, counter);
- if (isWholeWord && counter + loc < text.Length && !Utils.IsValidEndText(text.Substring(loc + counter)))
- {
- continue;
- }
+ // Case 0: pattern.length = 0 or text.length = 0
+ if (text == null || pattern == null || text.Length == 0 || pattern.Length == 0)
+ return 0;
+ // Case 1: exact match
+ if (loc + pattern.Length < text.Length &&
+ text.Substring(loc, pattern.Length).ToLower() == pattern.ToLower())
+ {
+ if (!(isWholeWord && loc + pattern.Length < text.Length && !Utils.IsValidEndText(text.Substring(loc, pattern.Length + 1))))
+ return pattern.Length;
+ }
+ // Case 2: not exact match
+ int counter = 0;
+ double matchIndex = 0;
+ string matchWord = "";
+ NeedlemanWunch nw = new NeedlemanWunch();
+ while (counter < pattern.Length * 2)
+ {
+ if (counter + loc < text.Length)
+ {
+ counter++;
+ string tempMatchWord = text.Substring(loc, counter);
+ if (isWholeWord && counter + loc < text.Length && !Utils.IsValidEndText(text.Substring(loc + counter)))
+ {
+ continue;
+ }
- double tempMatchIndex = nw.GetSimilarity(pattern, tempMatchWord);
- if (tempMatchIndex > matchIndex)
- {
- matchIndex = tempMatchIndex;
- matchWord = tempMatchWord;
- }
- }
- else
- {
- break;
- }
- }
- if (matchIndex < threashold)
- return -1;
- else
- return matchWord.Length;
+ double tempMatchIndex = nw.GetSimilarity(pattern, tempMatchWord);
+ if (tempMatchIndex > matchIndex)
+ {
+ matchIndex = tempMatchIndex;
+ matchWord = tempMatchWord;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ if (matchIndex < threashold)
+ return -1;
+ else
+ return matchWord.Length;
}
/**
@@ -297,6 +294,6 @@ private double match_bitapScore(int e, int x, int loc, string pattern)
i++;
}
return s;
- }
+ }
}
}
diff --git a/dnGREP.Engines/GrepEngineBase.cs b/dnGREP.Engines/GrepEngineBase.cs
index 1121e610..25fce9c3 100644
--- a/dnGREP.Engines/GrepEngineBase.cs
+++ b/dnGREP.Engines/GrepEngineBase.cs
@@ -9,23 +9,23 @@
namespace dnGREP.Engines
{
- public class GrepEngineBase
- {
+ public class GrepEngineBase
+ {
private string KEYWORD_GUID_LOWER = "$(guid)";
private string KEYWORD_GUID_UPPER = "$(GUID)";
private string KEYWORD_GUIDX = "$(guidx)";
protected GrepEngineInitParams initParams = new GrepEngineInitParams();
private GoogleMatch fuzzyMatchEngine = new GoogleMatch();
- public GrepEngineBase()
+ public GrepEngineBase()
{
FileFilter = new FileFilter();
}
- public GrepEngineBase(GrepEngineInitParams param)
- {
+ public GrepEngineBase(GrepEngineInitParams param)
+ {
initParams = param;
- }
+ }
public virtual bool Initialize(GrepEngineInitParams param, FileFilter filter)
{
@@ -36,10 +36,10 @@ public virtual bool Initialize(GrepEngineInitParams param, FileFilter filter)
public FileFilter FileFilter { get; protected set; }
- public virtual void OpenFile(OpenFileArgs args)
- {
- Utils.OpenFile(args);
- }
+ public virtual void OpenFile(OpenFileArgs args)
+ {
+ Utils.OpenFile(args);
+ }
protected List doFuzzySearchMultiline(int lineNumber, string text, string searchPattern, GrepSearchOption searchOptions, bool includeContext)
{
@@ -47,7 +47,7 @@ protected List doFuzzySearchMultiline(int lineNumber
int counter = 0;
fuzzyMatchEngine.Match_Threshold = initParams.FuzzyMatchThreshold;
- bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
+ bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
List globalMatches = new List();
while (counter < text.Length)
{
@@ -55,36 +55,36 @@ protected List doFuzzySearchMultiline(int lineNumber
if (matchLocation == -1)
break;
- if (isWholeWord && !Utils.IsValidBeginText(text.Substring(counter).Substring(0, matchLocation)))
- {
- counter = counter + matchLocation + searchPattern.Length;
- continue;
- }
+ if (isWholeWord && !Utils.IsValidBeginText(text.Substring(counter).Substring(0, matchLocation)))
+ {
+ counter = counter + matchLocation + searchPattern.Length;
+ continue;
+ }
int matchLength = fuzzyMatchEngine.match_length(text.Substring(counter), searchPattern, matchLocation, isWholeWord, initParams.FuzzyMatchThreshold);
- if (matchLength == -1)
- {
- counter = counter + matchLocation + searchPattern.Length;
- continue;
- }
+ if (matchLength == -1)
+ {
+ counter = counter + matchLocation + searchPattern.Length;
+ continue;
+ }
if (initParams.VerboseMatchCount && lineEndIndexes.Count > 0)
lineNumber = lineEndIndexes.FindIndex(i => i > matchLocation + counter) + 1;
globalMatches.Add(new GrepSearchResult.GrepMatch(lineNumber, matchLocation + counter, matchLength));
-
+
counter = counter + matchLocation + matchLength;
}
return globalMatches;
}
protected List doXPathSearch(int lineNumber, string text, string searchXPath, GrepSearchOption searchOptions, bool includeContext)
- {
+ {
List results = new List();
- // Check if file is an XML file
- if (text.Length > 5 && text.Substring(0, 5).ToLower() == " 5 && text.Substring(0, 5).ToLower() == " positions = new List();
using (StringReader reader = new StringReader(text))
{
@@ -118,12 +118,12 @@ protected List doXPathSearch(int lineNumber, string
positions.Add(xpathPositions);
}
}
-
+
results.AddRange(getFilePositions(text, positions));
- }
+ }
- return results;
- }
+ return results;
+ }
#region XPath helper functions
public class XPathPosition
@@ -196,7 +196,7 @@ public GrepSearchResult.GrepMatch[] getFilePositions(string text, List currPos = new List();
-
+
try
{
IXmlLineInfo lineInfo = ((IXmlLineInfo)reader);
@@ -218,7 +218,7 @@ public GrepSearchResult.GrepMatch[] getFilePositions(string text, List GetLineEndIndexes(string text)
}
protected List doRegexSearch(int lineNumber, string text, string searchPattern, GrepSearchOption searchOptions, bool includeContext)
- {
+ {
RegexOptions regexOptions = RegexOptions.None;
if ((searchOptions & GrepSearchOption.CaseSensitive) != GrepSearchOption.CaseSensitive)
regexOptions |= RegexOptions.IgnoreCase;
@@ -357,15 +357,15 @@ protected List doRegexSearch(int lineNumber, string
if ((searchOptions & GrepSearchOption.SingleLine) == GrepSearchOption.SingleLine)
regexOptions |= RegexOptions.Singleline;
- bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
+ bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
- if (isWholeWord)
- {
- if (!searchPattern.Trim().StartsWith("\\b"))
- searchPattern = "\\b" + searchPattern.Trim();
- if (!searchPattern.Trim().EndsWith("\\b"))
- searchPattern = searchPattern.Trim() + "\\b";
- }
+ if (isWholeWord)
+ {
+ if (!searchPattern.Trim().StartsWith("\\b"))
+ searchPattern = "\\b" + searchPattern.Trim();
+ if (!searchPattern.Trim().EndsWith("\\b"))
+ searchPattern = searchPattern.Trim() + "\\b";
+ }
// Issue #210 .net regex will only match the $ end of line token with a \n, not \r\n or \r
// see https://msdn.microsoft.com/en-us/library/yd1hzczs.aspx#Multiline
@@ -379,11 +379,11 @@ protected List doRegexSearch(int lineNumber, string
var lineEndIndexes = GetLineEndIndexes(initParams.VerboseMatchCount && lineNumber == -1 ? text : null);
- List results = new List();
+ List results = new List();
List globalMatches = new List();
var matches = Regex.Matches(text, searchPattern, regexOptions);
foreach (Match match in matches)
- {
+ {
if (initParams.VerboseMatchCount && lineEndIndexes.Count > 0)
lineNumber = lineEndIndexes.FindIndex(i => i > match.Index) + 1;
@@ -391,10 +391,10 @@ protected List doRegexSearch(int lineNumber, string
if (Utils.CancelSearch)
break;
- }
+ }
return globalMatches;
- }
+ }
protected string doPatternReplacement(string replaceText)
{
@@ -409,140 +409,140 @@ protected string doPatternReplacement(string replaceText)
}
protected List doTextSearchCaseInsensitive(int lineNumber, string text, string searchText, GrepSearchOption searchOptions, bool includeContext)
- {
+ {
var lineEndIndexes = GetLineEndIndexes(initParams.VerboseMatchCount && lineNumber == -1 ? text : null);
-
+
int index = 0;
- bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
+ bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
List globalMatches = new List();
- while (index >= 0)
- {
- index = text.IndexOf(searchText, index, StringComparison.InvariantCultureIgnoreCase);
- if (index >= 0)
- {
- if (isWholeWord && (!Utils.IsValidBeginText(text.Substring(0, index)) ||
- !Utils.IsValidEndText(text.Substring(index + searchText.Length))))
- {
- index++;
- continue;
- }
+ while (index >= 0)
+ {
+ index = text.IndexOf(searchText, index, StringComparison.InvariantCultureIgnoreCase);
+ if (index >= 0)
+ {
+ if (isWholeWord && (!Utils.IsValidBeginText(text.Substring(0, index)) ||
+ !Utils.IsValidEndText(text.Substring(index + searchText.Length))))
+ {
+ index++;
+ continue;
+ }
if (initParams.VerboseMatchCount && lineEndIndexes.Count > 0)
lineNumber = lineEndIndexes.FindIndex(i => i > index) + 1;
globalMatches.Add(new GrepSearchResult.GrepMatch(lineNumber, index, searchText.Length));
- index++;
- }
+ index++;
+ }
if (Utils.CancelSearch)
break;
}
return globalMatches;
- }
+ }
protected List doTextSearchCaseSensitive(int lineNumber, string text, string searchText, GrepSearchOption searchOptions, bool includeContext)
- {
+ {
var lineEndIndexes = GetLineEndIndexes(initParams.VerboseMatchCount && lineNumber == -1 ? text : null);
-
+
List results = new List();
- int index = 0;
- bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
+ int index = 0;
+ bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
List globalMatches = new List();
- while (index >= 0)
- {
- index = text.IndexOf(searchText, index, StringComparison.InvariantCulture);
- if (index >= 0)
- {
- if (isWholeWord && (!Utils.IsValidBeginText(text.Substring(0, index)) ||
- !Utils.IsValidEndText(text.Substring(index + searchText.Length))))
- {
- index++;
- continue;
- }
+ while (index >= 0)
+ {
+ index = text.IndexOf(searchText, index, StringComparison.InvariantCulture);
+ if (index >= 0)
+ {
+ if (isWholeWord && (!Utils.IsValidBeginText(text.Substring(0, index)) ||
+ !Utils.IsValidEndText(text.Substring(index + searchText.Length))))
+ {
+ index++;
+ continue;
+ }
if (initParams.VerboseMatchCount && lineEndIndexes.Count > 0)
lineNumber = lineEndIndexes.FindIndex(i => i > index) + 1;
globalMatches.Add(new GrepSearchResult.GrepMatch(lineNumber, index, searchText.Length));
- index++;
- }
+ index++;
+ }
if (Utils.CancelSearch)
break;
}
return globalMatches;
- }
+ }
protected string doTextReplaceCaseSensitive(string text, string searchText, string replaceText, GrepSearchOption searchOptions)
- {
- StringBuilder sb = new StringBuilder();
- int index = 0;
- int counter = 0;
- bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
- while (index >= 0)
- {
- index = text.IndexOf(searchText, index, StringComparison.InvariantCulture);
- if (index >= 0)
- {
- if (isWholeWord && (!Utils.IsValidBeginText(text.Substring(0, index)) ||
- !Utils.IsValidEndText(text.Substring(index + searchText.Length))))
- {
- index++;
- continue;
- }
+ {
+ StringBuilder sb = new StringBuilder();
+ int index = 0;
+ int counter = 0;
+ bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
+ while (index >= 0)
+ {
+ index = text.IndexOf(searchText, index, StringComparison.InvariantCulture);
+ if (index >= 0)
+ {
+ if (isWholeWord && (!Utils.IsValidBeginText(text.Substring(0, index)) ||
+ !Utils.IsValidEndText(text.Substring(index + searchText.Length))))
+ {
+ index++;
+ continue;
+ }
sb.Append(text.Substring(counter, index - counter));
sb.Append(doPatternReplacement(replaceText));
- counter = index + searchText.Length;
-
- index++;
- }
+ counter = index + searchText.Length;
+
+ index++;
+ }
if (Utils.CancelSearch)
break;
}
- sb.Append(text.Substring(counter));
- return sb.ToString();
- }
+ sb.Append(text.Substring(counter));
+ return sb.ToString();
+ }
protected string doTextReplaceCaseInsensitive(string text, string searchText, string replaceText, GrepSearchOption searchOptions)
- {
- StringBuilder sb = new StringBuilder();
- int index = 0;
- int counter = 0;
- bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
- while (index >= 0)
- {
- index = text.ToLowerInvariant().IndexOf(searchText.ToLowerInvariant(), index, StringComparison.InvariantCulture);
- if (index >= 0)
- {
- if (isWholeWord && (!Utils.IsValidBeginText(text.Substring(0, index)) ||
- !Utils.IsValidEndText(text.Substring(index + searchText.Length))))
- {
- index++;
- continue;
- }
+ {
+ StringBuilder sb = new StringBuilder();
+ int index = 0;
+ int counter = 0;
+ bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
+ while (index >= 0)
+ {
+ index = text.ToLowerInvariant().IndexOf(searchText.ToLowerInvariant(), index, StringComparison.InvariantCulture);
+ if (index >= 0)
+ {
+ if (isWholeWord && (!Utils.IsValidBeginText(text.Substring(0, index)) ||
+ !Utils.IsValidEndText(text.Substring(index + searchText.Length))))
+ {
+ index++;
+ continue;
+ }
sb.Append(text.Substring(counter, index - counter));
sb.Append(doPatternReplacement(replaceText));
- counter = index + searchText.Length;
+ counter = index + searchText.Length;
- index++;
- }
+ index++;
+ }
if (Utils.CancelSearch)
break;
}
- sb.Append(text.Substring(counter));
- return sb.ToString();
- }
+ sb.Append(text.Substring(counter));
+ return sb.ToString();
+ }
protected string doRegexReplace(string text, string searchPattern, string replacePattern, GrepSearchOption searchOptions)
- {
+ {
RegexOptions regexOptions = RegexOptions.None;
if ((searchOptions & GrepSearchOption.CaseSensitive) != GrepSearchOption.CaseSensitive)
regexOptions |= RegexOptions.IgnoreCase;
@@ -551,25 +551,25 @@ protected string doRegexReplace(string text, string searchPattern, string replac
if ((searchOptions & GrepSearchOption.SingleLine) == GrepSearchOption.SingleLine)
regexOptions |= RegexOptions.Singleline;
- bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
+ bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
- if (isWholeWord)
- {
- if (!searchPattern.Trim().StartsWith("\\b"))
- searchPattern = "\\b" + searchPattern.Trim();
- if (!searchPattern.Trim().EndsWith("\\b"))
- searchPattern = searchPattern.Trim() + "\\b";
- }
+ if (isWholeWord)
+ {
+ if (!searchPattern.Trim().StartsWith("\\b"))
+ searchPattern = "\\b" + searchPattern.Trim();
+ if (!searchPattern.Trim().EndsWith("\\b"))
+ searchPattern = searchPattern.Trim() + "\\b";
+ }
return Regex.Replace(text, searchPattern, doPatternReplacement(replacePattern), regexOptions);
- }
+ }
public string doFuzzyReplace(string text, string searchPattern, string replacePattern, GrepSearchOption searchOptions)
{
int counter = 0;
StringBuilder result = new StringBuilder();
fuzzyMatchEngine.Match_Threshold = initParams.FuzzyMatchThreshold;
- bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
+ bool isWholeWord = (searchOptions & GrepSearchOption.WholeWord) == GrepSearchOption.WholeWord;
while (counter < text.Length)
{
int matchLocation = fuzzyMatchEngine.match_main(text.Substring(counter), searchPattern, counter);
@@ -579,21 +579,21 @@ public string doFuzzyReplace(string text, string searchPattern, string replacePa
break;
}
- if (isWholeWord && !Utils.IsValidBeginText(text.Substring(counter).Substring(0, matchLocation + counter)))
- {
- result.Append(text.Substring(counter));
- counter = counter + matchLocation + searchPattern.Length;
- continue;
- }
+ if (isWholeWord && !Utils.IsValidBeginText(text.Substring(counter).Substring(0, matchLocation + counter)))
+ {
+ result.Append(text.Substring(counter));
+ counter = counter + matchLocation + searchPattern.Length;
+ continue;
+ }
int matchLength = fuzzyMatchEngine.match_length(text.Substring(counter), searchPattern, matchLocation, isWholeWord, initParams.FuzzyMatchThreshold);
- if (matchLength == -1)
- {
- result.Append(text.Substring(counter));
- counter = counter + matchLocation + searchPattern.Length;
- continue;
- }
+ if (matchLength == -1)
+ {
+ result.Append(text.Substring(counter));
+ counter = counter + matchLocation + searchPattern.Length;
+ continue;
+ }
// Text before match
result.Append(text.Substring(counter, matchLocation));
@@ -606,35 +606,35 @@ public string doFuzzyReplace(string text, string searchPattern, string replacePa
}
protected string doXPathReplace(string text, string searchXPath, string replaceText, GrepSearchOption searchOptions)
- {
- if (text.Length > 5 && text.Substring(0, 5).ToLower() == " 5 && text.Substring(0, 5).ToLower() == " failedEngines = new Dictionary();
private static Logger logger = LogManager.GetCurrentClassLogger();
- private static void loadPlugins()
+ private static void loadPlugins()
{
if (plugings == null)
{
@@ -53,7 +53,7 @@ public static IGrepEngine GetSearchEngine(string fileName, GrepEngineInitParams
if (fileExtension.Length > 1)
fileExtension = fileExtension.Substring(1);
- if (!fileTypeEngines.ContainsKey(fileExtension))
+ if (!fileTypeEngines.ContainsKey(fileExtension))
{
foreach (GrepPlugin plugin in plugings)
{
@@ -95,7 +95,7 @@ public static IGrepEngine GetSearchEngine(string fileName, GrepEngineInitParams
///
private static bool FrameworkVersionsAreCompatible(Version version1, Version version2)
{
- return ( version1.Major == version2.Major );
+ return (version1.Major == version2.Major);
}
public static IGrepEngine GetReplaceEngine(string fileName, GrepEngineInitParams param, FileFilter filter)
@@ -121,7 +121,7 @@ public static IGrepEngine GetReplaceEngine(string fileName, GrepEngineInitParams
if (fileTypeEngines.ContainsKey(fileExtension) && fileTypeEngines[fileExtension].Enabled && !fileTypeEngines[fileExtension].Engine.IsSearchOnly)
{
- if (FrameworkVersionsAreCompatible(fileTypeEngines[fileExtension].Engine.FrameworkVersion, plainTextEngine.FrameworkVersion) )
+ if (FrameworkVersionsAreCompatible(fileTypeEngines[fileExtension].Engine.FrameworkVersion, plainTextEngine.FrameworkVersion))
{
if (fileTypeEngines[fileExtension].Engine.Initialize(param, filter))
{
diff --git a/dnGREP.Engines/GrepPlugin.cs b/dnGREP.Engines/GrepPlugin.cs
index 7d9124de..f511bb7e 100644
--- a/dnGREP.Engines/GrepPlugin.cs
+++ b/dnGREP.Engines/GrepPlugin.cs
@@ -1,121 +1,121 @@
using System;
using System.Collections.Generic;
-using System.Text;
using System.IO;
-using dnGREP.Common;
using System.Reflection;
+using System.Text;
+using dnGREP.Common;
namespace dnGREP.Engines
{
- public class GrepPlugin
- {
- private IGrepEngine engine;
-
- public IGrepEngine Engine
- {
- get { return engine; }
- set { engine = value; }
- }
- private List extensions = new List();
-
- public List Extensions
- {
- get { return extensions; }
- }
- private string dllFilePath;
-
- ///
- /// Relative path to DLL file
- ///
- public string DllFilePath
- {
- get { return dllFilePath; }
- set { dllFilePath = value; }
- }
- private string pluginFilePath;
-
- ///
- /// Absolute path to plugin file
- ///
- public string PluginFilePath
- {
- get { return pluginFilePath; }
- set { pluginFilePath = value; }
- }
-
- private bool enabled = true;
-
- public bool Enabled
- {
- get { return enabled; }
- set { enabled = value; }
- }
-
- public GrepPlugin(string pluginFilePath)
- {
- PluginFilePath = pluginFilePath;
+ public class GrepPlugin
+ {
+ private IGrepEngine engine;
+
+ public IGrepEngine Engine
+ {
+ get { return engine; }
+ set { engine = value; }
+ }
+ private List extensions = new List();
+
+ public List Extensions
+ {
+ get { return extensions; }
+ }
+ private string dllFilePath;
+
+ ///
+ /// Relative path to DLL file
+ ///
+ public string DllFilePath
+ {
+ get { return dllFilePath; }
+ set { dllFilePath = value; }
+ }
+ private string pluginFilePath;
+
+ ///
+ /// Absolute path to plugin file
+ ///
+ public string PluginFilePath
+ {
+ get { return pluginFilePath; }
+ set { pluginFilePath = value; }
+ }
+
+ private bool enabled = true;
+
+ public bool Enabled
+ {
+ get { return enabled; }
+ set { enabled = value; }
+ }
+
+ public GrepPlugin(string pluginFilePath)
+ {
+ PluginFilePath = pluginFilePath;
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
- }
-
- public bool LoadPluginSettings()
- {
- if (pluginFilePath != null && File.Exists(pluginFilePath))
- {
- try
- {
- foreach (string line in File.ReadAllLines(pluginFilePath))
- {
- string[] tokens = line.Split('=');
- if (tokens.Length != 2)
- continue;
-
- switch (tokens[0].Trim().ToUpper())
- {
- case "FILE":
- DllFilePath = tokens[1].Trim();
- break;
- case "ENABLED":
- Enabled = Utils.ParseBoolean(tokens[1].Trim(), true);
- break;
- case "EXTENSIONS":
- Extensions.Clear();
- foreach (string extension in tokens[1].Trim().Split(','))
- {
- Extensions.Add(extension.Trim().ToLower());
- }
- break;
- }
- }
-
- string tempDllFilePath = DllFilePath;
- if (!File.Exists(tempDllFilePath))
- tempDllFilePath = Path.GetDirectoryName(pluginFilePath) + "\\" + tempDllFilePath;
-
- if (File.Exists(tempDllFilePath))
- {
- Assembly assembly = Assembly.LoadFile(tempDllFilePath);
- Type[] types = assembly.GetTypes();
- foreach (Type type in types)
- {
- if (type.GetInterface("IGrepEngine") != null)
- {
- IGrepEngine engine = (IGrepEngine)Activator.CreateInstance(type);
- Engine = engine;
- break;
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- if (Engine != null)
- return true;
- else
- return false;
- }
+ }
+
+ public bool LoadPluginSettings()
+ {
+ if (pluginFilePath != null && File.Exists(pluginFilePath))
+ {
+ try
+ {
+ foreach (string line in File.ReadAllLines(pluginFilePath))
+ {
+ string[] tokens = line.Split('=');
+ if (tokens.Length != 2)
+ continue;
+
+ switch (tokens[0].Trim().ToUpper())
+ {
+ case "FILE":
+ DllFilePath = tokens[1].Trim();
+ break;
+ case "ENABLED":
+ Enabled = Utils.ParseBoolean(tokens[1].Trim(), true);
+ break;
+ case "EXTENSIONS":
+ Extensions.Clear();
+ foreach (string extension in tokens[1].Trim().Split(','))
+ {
+ Extensions.Add(extension.Trim().ToLower());
+ }
+ break;
+ }
+ }
+
+ string tempDllFilePath = DllFilePath;
+ if (!File.Exists(tempDllFilePath))
+ tempDllFilePath = Path.GetDirectoryName(pluginFilePath) + "\\" + tempDllFilePath;
+
+ if (File.Exists(tempDllFilePath))
+ {
+ Assembly assembly = Assembly.LoadFile(tempDllFilePath);
+ Type[] types = assembly.GetTypes();
+ foreach (Type type in types)
+ {
+ if (type.GetInterface("IGrepEngine") != null)
+ {
+ IGrepEngine engine = (IGrepEngine)Activator.CreateInstance(type);
+ Engine = engine;
+ break;
+ }
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ throw ex;
+ }
+ }
+ if (Engine != null)
+ return true;
+ else
+ return false;
+ }
private readonly IDictionary loadedAssemblies = new Dictionary();
@@ -144,29 +144,29 @@ private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs a
return assembly;
}
- public void PersistPluginSettings()
- {
- if (pluginFilePath != null && File.Exists(pluginFilePath))
- {
- try
- {
- StringBuilder sb = new StringBuilder();
- sb.AppendLine("File=" + DllFilePath);
- sb.AppendLine("Enabled=" + Enabled.ToString());
- sb.Append("Extensions=");
- foreach (string ext in Extensions)
- {
- sb.Append(ext + ",");
- }
- Utils.DeleteFile(pluginFilePath);
- File.WriteAllText(pluginFilePath, sb.ToString());
-
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
+ public void PersistPluginSettings()
+ {
+ if (pluginFilePath != null && File.Exists(pluginFilePath))
+ {
+ try
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.AppendLine("File=" + DllFilePath);
+ sb.AppendLine("Enabled=" + Enabled.ToString());
+ sb.Append("Extensions=");
+ foreach (string ext in Extensions)
+ {
+ sb.Append(ext + ",");
+ }
+ Utils.DeleteFile(pluginFilePath);
+ File.WriteAllText(pluginFilePath, sb.ToString());
+
+ }
+ catch (Exception ex)
+ {
+ throw ex;
+ }
+ }
+ }
+ }
}
diff --git a/dnGREP.Engines/IGrepEngine.cs b/dnGREP.Engines/IGrepEngine.cs
index 6b2c8521..0cab03f4 100644
--- a/dnGREP.Engines/IGrepEngine.cs
+++ b/dnGREP.Engines/IGrepEngine.cs
@@ -5,45 +5,45 @@
namespace dnGREP.Engines
{
- public interface IGrepEngine
- {
- bool Initialize(GrepEngineInitParams param, FileFilter filter);
+ public interface IGrepEngine
+ {
+ bool Initialize(GrepEngineInitParams param, FileFilter filter);
- ///
- /// Return true if engine supports search only. Return false is engine supports replace as well.
- ///
- bool IsSearchOnly { get;}
+ ///
+ /// Return true if engine supports search only. Return false is engine supports replace as well.
+ ///
+ bool IsSearchOnly { get; }
FileFilter FileFilter { get; }
- ///
- /// Searches folder for files whose content matches regex
- ///
- /// File to search in
- ///
- ///
- ///
- ///
- ///
- /// List of results. If nothing is found returns empty list
- List Search(string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding);
+ ///
+ /// Searches folder for files whose content matches regex
+ ///
+ /// File to search in
+ ///
+ ///
+ ///
+ ///
+ ///
+ /// List of results. If nothing is found returns empty list
+ List Search(string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding);
bool Replace(string sourceFile, string destinationFile, string searchPattern, string replacePattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding);
-
- ///
- /// Method gets called when search/replace process is complete
- ///
- void Unload();
-
- ///
- /// Return version of the framework (dgGREP.Engines.dll) that the plugin was compiled against
- ///
- Version FrameworkVersion { get; }
-
- ///
- /// Can be used to provide custom file opening functionality
- ///
- ///
- void OpenFile(OpenFileArgs args);
- }
+
+ ///
+ /// Method gets called when search/replace process is complete
+ ///
+ void Unload();
+
+ ///
+ /// Return version of the framework (dgGREP.Engines.dll) that the plugin was compiled against
+ ///
+ Version FrameworkVersion { get; }
+
+ ///
+ /// Can be used to provide custom file opening functionality
+ ///
+ ///
+ void OpenFile(OpenFileArgs args);
+ }
}
diff --git a/dnGREP.Engines/SimMetrics.cs b/dnGREP.Engines/SimMetrics.cs
index 926f500d..85de2bfd 100644
--- a/dnGREP.Engines/SimMetrics.cs
+++ b/dnGREP.Engines/SimMetrics.cs
@@ -51,552 +51,550 @@
*/
using System;
-using System.Collections.Generic;
-using System.Text;
namespace dnGREP.Engines
{
- ///
- /// needlemanwunch implements an edit distance function
- ///
- [Serializable]
- sealed public class NeedlemanWunch : AbstractStringMetric
- {
- const double defaultGapCost = 2.0;
- const double defaultMismatchScore = 0.0;
- const double defaultPerfectMatchScore = 1.0;
-
- ///
- /// constructor
- ///
- public NeedlemanWunch() : this(defaultGapCost, new SubCostRange0To1()) { }
-
- ///
- /// constructor
- ///
- /// the cost of a gap
- public NeedlemanWunch(double costG) : this(costG, new SubCostRange0To1()) { }
-
- ///
- /// constructor
- ///
- /// the cost of a gap
- /// the cost function to use
- public NeedlemanWunch(double costG, AbstractSubstitutionCost costFunction)
- {
- gapCost = costG;
- dCostFunction = costFunction;
- }
-
- ///
- /// constructor
- ///
- /// the cost function to use
- public NeedlemanWunch(AbstractSubstitutionCost costFunction) : this(defaultGapCost, costFunction) { }
-
- ///
- /// the private cost function used in the levenstein distance.
- ///
- AbstractSubstitutionCost dCostFunction;
- ///
- /// a constant for calculating the estimated timing cost.
- ///
- double estimatedTimingConstant = 0.0001842F;
- ///
- /// the cost of a gap.
- ///
- double gapCost;
-
- ///
- /// gets the similarity of the two strings using Needleman Wunch distance.
- ///
- ///
- ///
- /// a value between 0-1 of the similarity
- public override double GetSimilarity(string firstWord, string secondWord)
- {
- if ((firstWord != null) && (secondWord != null))
- {
- double needlemanWunch = GetUnnormalisedSimilarity(firstWord, secondWord);
- double maxValue = Math.Max(firstWord.Length, secondWord.Length);
- double minValue = maxValue;
- if (dCostFunction.MaxCost > gapCost)
- {
- maxValue *= dCostFunction.MaxCost;
- }
- else
- {
- maxValue *= gapCost;
- }
- if (dCostFunction.MinCost < gapCost)
- {
- minValue *= dCostFunction.MinCost;
- }
- else
- {
- minValue *= gapCost;
- }
- if (minValue < defaultMismatchScore)
- {
- maxValue -= minValue;
- needlemanWunch -= minValue;
- }
- if (maxValue == defaultMismatchScore)
- {
- return defaultPerfectMatchScore;
- }
- else
- {
- return defaultPerfectMatchScore - needlemanWunch / maxValue;
- }
- }
- return defaultMismatchScore;
- }
-
- /// gets a div class xhtml similarity explaining the operation of the metric.
- /// string 1
- /// string 2
- /// a div class html section detailing the metric operation.
- public override string GetSimilarityExplained(string firstWord, string secondWord)
- {
- throw new NotImplementedException();
- }
-
- ///
- /// gets the estimated time in milliseconds it takes to perform a similarity timing.
- ///
- ///
- ///
- /// the estimated time in milliseconds taken to perform the similarity measure
- public override double GetSimilarityTimingEstimated(string firstWord, string secondWord)
- {
- if ((firstWord != null) && (secondWord != null))
- {
- double firstLength = firstWord.Length;
- double secondLength = secondWord.Length;
- return firstLength * secondLength * estimatedTimingConstant;
- }
- return defaultMismatchScore;
- }
-
- ///
- /// gets the un-normalised similarity measure of the metric for the given strings.
- ///
- ///
- /// returns the score of the similarity measure (un-normalised)
- public override double GetUnnormalisedSimilarity(string firstWord, string secondWord)
- {
- if ((firstWord != null) && (secondWord != null))
- {
- int n = firstWord.Length;
- int m = secondWord.Length;
- if (n == 0)
- {
- return m;
- }
- if (m == 0)
- {
- return n;
- }
- double[][] d = new double[n + 1][];
- for (int i = 0; i < n + 1; i++)
- {
- d[i] = new double[m + 1];
- }
- for (int i = 0; i <= n; i++)
- {
- d[i][0] = i;
- }
-
- for (int j = 0; j <= m; j++)
- {
- d[0][j] = j;
- }
-
- for (int i = 1; i <= n; i++)
- {
- for (int j = 1; j <= m; j++)
- {
- double cost = dCostFunction.GetCost(firstWord, i - 1, secondWord, j - 1);
- d[i][j] = MathFunctions.MinOf3(d[i - 1][j] + gapCost, d[i][j - 1] + gapCost, d[i - 1][j - 1] + cost);
- }
- }
-
- return d[n][m];
- }
- return 0.0;
- }
-
- ///
- /// set/get the d(i,j) cost function.
- ///
- public AbstractSubstitutionCost DCostFunction { get { return dCostFunction; } set { dCostFunction = value; } }
-
- ///
- /// sets/gets the gap cost for the distance function.
- ///
- public double GapCost { get { return gapCost; } set { gapCost = value; } }
-
- ///
- /// returns the long string identifier for the metric.
- ///
- public override string LongDescriptionString
- {
- get
- {
- return
- "Implements the Needleman-Wunch algorithm providing an edit distance based similarity measure between two strings";
- }
- }
-
- ///
- /// returns the string identifier for the metric.
- ///
- public override string ShortDescriptionString { get { return "NeedlemanWunch"; } }
- }
-
- ///
- /// base class which all metrics inherit from.
- ///
- /// This class implemented a few basic methods and then leaves the others to
- /// be implemented by the similarity metric itself.
- [Serializable]
- abstract public class AbstractStringMetric : IStringMetric
- {
- ///
- /// does a batch comparison of the set of strings with the given
- /// comparator string returning an array of results equal in length
- /// to the size of the given set of strings to test.
- ///
- /// an array of strings to test against the comparator string
- /// the comparator string to test the array against
- /// an array of results equal in length to the size of the given set of strings to test.
- public double[] BatchCompareSet(string[] setRenamed, string comparator)
- {
- if ((setRenamed != null) && (comparator != null))
- {
- double[] results = new double[setRenamed.Length];
- for (int strNum = 0; strNum < setRenamed.Length; strNum++)
- {
- results[strNum] = GetSimilarity(setRenamed[strNum], comparator);
- }
- return results;
- }
- return null;
- }
-
- ///
- /// does a batch comparison of one set of strings against another set
- /// of strings returning an array of results equal in length
- /// to the minimum size of the given sets of strings to test.
- ///
- /// an array of strings to test
- /// an array of strings to test the first array against
- /// an array of results equal in length to the minimum size of the given sets of strings to test.
- public double[] BatchCompareSets(string[] firstSet, string[] secondSet)
- {
- if ((firstSet != null) && (secondSet != null))
- {
- double[] results;
- if (firstSet.Length <= secondSet.Length)
- {
- results = new double[firstSet.Length];
- }
- else
- {
- results = new double[secondSet.Length];
- }
- for (int strNum = 0; strNum < results.Length; strNum++)
- {
- results[strNum] = GetSimilarity(firstSet[strNum], secondSet[strNum]);
- }
- return results;
- }
- return null;
- }
-
- ///
- /// gets the similarity measure of the metric for the given strings.
- ///
- ///
- ///
- /// implemented version will return score between 0 and 1
- abstract public double GetSimilarity(string firstWord, string secondWord);
-
- /// gets a div class xhtml similarity explaining the operation of the metric.
- /// string 1
- /// string 2
- /// a div class html section detailing the metric operation.
- abstract public string GetSimilarityExplained(string firstWord, string secondWord);
-
- ///
- /// gets the actual time in milliseconds it takes to perform a similarity timing.
- /// This call takes as long as the similarity metric to perform so should not be done in normal circumstances.
- ///
- ///
- ///
- /// the actual time in milliseconds taken to perform the similarity measure
- public long GetSimilarityTimingActual(string firstWord, string secondWord)
- {
- long timeBefore = (DateTime.Now.Ticks - 621355968000000000) / 10000;
- GetSimilarity(firstWord, secondWord);
- long timeAfter = (DateTime.Now.Ticks - 621355968000000000) / 10000;
- return timeAfter - timeBefore;
- }
-
- ///
- /// gets the estimated time in milliseconds it takes to perform a similarity timing.
- ///
- ///
- ///
- /// the estimated time in milliseconds taken to perform the similarity measure
- abstract public double GetSimilarityTimingEstimated(string firstWord, string secondWord);
-
- ///
- /// gets the un-normalised similarity measure of the metric for the given strings.
- ///
- ///
- /// returns the score of the similarity measure (un-normalised)
- abstract public double GetUnnormalisedSimilarity(string firstWord, string secondWord);
-
- ///
- /// reports the metric type.
- ///
- abstract public string LongDescriptionString { get; }
-
- ///
- /// reports the metric type.
- ///
- abstract public string ShortDescriptionString { get; }
- }
-
- ///
- /// implements an interface for the string metrics
- ///
- public interface IStringMetric
- {
- ///
- /// returns a similarity measure of the string comparison.
- ///
- ///
- ///
- /// a double between zero to one (zero = no similarity, one = matching strings)
- double GetSimilarity(string firstWord, string secondWord);
-
- /// gets a div class xhtml similarity explaining the operation of the metric.
- ///
- ///
- /// string 1
- ///
- /// string 2
- ///
- ///
- /// a div class html section detailing the metric operation.
- ///
- string GetSimilarityExplained(string firstWord, string secondWord);
-
- ///
- /// gets the actual time in milliseconds it takes to perform a similarity timing.
- ///
- ///
- ///
- /// the actual time in milliseconds taken to perform the similarity measure
- /// This call takes as long as the similarity metric to perform so should not be done in normal cercumstances.
- long GetSimilarityTimingActual(string firstWord, string secondWord);
-
- ///
- /// gets the estimated time in milliseconds it takes to perform a similarity timing.
- ///
- ///
- ///
- /// the estimated time in milliseconds taken to perform the similarity measure
- double GetSimilarityTimingEstimated(string firstWord, string secondWord);
-
- ///
- /// gets the un-normalised similarity measure of the metric for the given strings.
- ///
- ///
- ///
- /// returns the score of the similarity measure (un-normalised)
- double GetUnnormalisedSimilarity(string firstWord, string secondWord);
-
- ///
- /// returns a long string of the string metric description.
- ///
- string LongDescriptionString { get; }
-
- ///
- /// returns a string of the string metric name.
- ///
- string ShortDescriptionString { get; }
- }
-
- static public class MathFunctions
- {
- ///
- /// returns the max of three numbers.
- ///
- /// first number to test
- /// second number to test
- /// third number to test
- /// the max of three numbers.
- static public double MaxOf3(double firstNumber, double secondNumber, double thirdNumber)
- {
- return Math.Max(firstNumber, Math.Max(secondNumber, thirdNumber));
- }
-
- ///
- /// returns the max of three numbers.
- ///
- /// first number to test
- /// second number to test
- /// third number to test
- /// the max of three numbers.
- static public int MaxOf3(int firstNumber, int secondNumber, int thirdNumber)
- {
- return Math.Max(firstNumber, Math.Max(secondNumber, thirdNumber));
- }
-
- ///
- /// returns the max of four numbers.
- ///
- /// first number to test
- /// second number to test
- /// third number to test
- /// fourth number to test
- /// the max of four numbers.
- static public double MaxOf4(double firstNumber, double secondNumber, double thirdNumber, double fourthNumber)
- {
- return Math.Max(Math.Max(firstNumber, secondNumber), Math.Max(thirdNumber, fourthNumber));
- }
-
- ///
- /// returns the min of three numbers.
- ///
- /// first number to test
- /// second number to test
- /// third number to test
- /// the min of three numbers.
- static public double MinOf3(double firstNumber, double secondNumber, double thirdNumber)
- {
- return Math.Min(firstNumber, Math.Min(secondNumber, thirdNumber));
- }
-
- ///
- /// returns the min of three numbers.
- ///
- /// first number to test
- /// second number to test
- /// third number to test
- /// the min of three numbers.
- static public int MinOf3(int firstNumber, int secondNumber, int thirdNumber)
- {
- return Math.Min(firstNumber, Math.Min(secondNumber, thirdNumber));
- }
- }
-
- ///
- /// implements a substitution cost function where d(i,j) = 1 if idoes not equal j, 0 if i equals j.
- ///
- [Serializable]
- sealed public class SubCostRange0To1 : AbstractSubstitutionCost
- {
- const int charExactMatchScore = 1;
- const int charMismatchMatchScore = 0;
-
- ///
- /// get cost between characters where d(i,j) = 1 if i does not equals j, 0 if i equals j.
- ///
- /// the string1 to evaluate the cost
- /// the index within the string1 to test
- /// the string2 to evaluate the cost
- /// the index within the string2 to test
- /// the cost of a given subsitution d(i,j) where d(i,j) = 1 if i!=j, 0 if i==j
- public override double GetCost(string firstWord, int firstWordIndex, string secondWord, int secondWordIndex)
- {
- if ((firstWord != null) && (secondWord != null))
- {
- return firstWord[firstWordIndex] != secondWord[secondWordIndex] ? charExactMatchScore : charMismatchMatchScore;
- }
- return 0.0;
- }
-
- ///
- /// returns the maximum possible cost.
- ///
- public override double MaxCost { get { return charExactMatchScore; } }
-
- ///
- /// returns the minimum possible cost.
- ///
- public override double MinCost { get { return charMismatchMatchScore; } }
-
- ///
- /// returns the name of the cost function.
- ///
- public override string ShortDescriptionString { get { return "SubCostRange0To1"; } }
- }
-
- ///
- /// AbstractSubstitutionCost implements a abstract class for substiution costs
- ///
- [Serializable]
- abstract public class AbstractSubstitutionCost : ISubstitutionCost
- {
- ///
- /// get cost between characters.
- ///
- /// the firstWord to evaluate the cost
- /// the index within the firstWord to test
- /// the secondWord to evaluate the cost
- /// the index within the string2 to test
- ///
- abstract public double GetCost(string firstWord, int firstWordIndex, string secondWord, int secondWordIndex);
-
- ///
- /// returns the maximum possible cost.
- ///
- abstract public double MaxCost { get; }
-
- ///
- /// returns the minimum possible cost.
- ///
- abstract public double MinCost { get; }
-
- ///
- /// returns the name of the cost function.
- ///
- abstract public string ShortDescriptionString { get; }
- }
-
- ///
- /// is an interface for a cost function d(i,j).
- ///
- public interface ISubstitutionCost
- {
- ///
- /// get cost between characters.
- ///
- /// the firstWord to evaluate the cost
- /// the index within the firstWord to test
- /// the secondWord to evaluate the cost
- /// the index within the secondWord to test
- ///
- double GetCost(string firstWord, int firstWordIndex, string secondWord, int secondWordIndex);
-
- ///
- /// returns the maximum possible cost.
- ///
- double MaxCost { get; }
-
- ///
- /// returns the minimum possible cost.
- ///
- double MinCost { get; }
-
- ///
- /// returns the name of the cost function.
- ///
- string ShortDescriptionString { get; }
- }
+ ///
+ /// needlemanwunch implements an edit distance function
+ ///
+ [Serializable]
+ sealed public class NeedlemanWunch : AbstractStringMetric
+ {
+ const double defaultGapCost = 2.0;
+ const double defaultMismatchScore = 0.0;
+ const double defaultPerfectMatchScore = 1.0;
+
+ ///
+ /// constructor
+ ///
+ public NeedlemanWunch() : this(defaultGapCost, new SubCostRange0To1()) { }
+
+ ///
+ /// constructor
+ ///
+ /// the cost of a gap
+ public NeedlemanWunch(double costG) : this(costG, new SubCostRange0To1()) { }
+
+ ///
+ /// constructor
+ ///
+ /// the cost of a gap
+ /// the cost function to use
+ public NeedlemanWunch(double costG, AbstractSubstitutionCost costFunction)
+ {
+ gapCost = costG;
+ dCostFunction = costFunction;
+ }
+
+ ///
+ /// constructor
+ ///
+ /// the cost function to use
+ public NeedlemanWunch(AbstractSubstitutionCost costFunction) : this(defaultGapCost, costFunction) { }
+
+ ///
+ /// the private cost function used in the levenstein distance.
+ ///
+ AbstractSubstitutionCost dCostFunction;
+ ///
+ /// a constant for calculating the estimated timing cost.
+ ///
+ double estimatedTimingConstant = 0.0001842F;
+ ///
+ /// the cost of a gap.
+ ///
+ double gapCost;
+
+ ///
+ /// gets the similarity of the two strings using Needleman Wunch distance.
+ ///
+ ///
+ ///
+ /// a value between 0-1 of the similarity
+ public override double GetSimilarity(string firstWord, string secondWord)
+ {
+ if ((firstWord != null) && (secondWord != null))
+ {
+ double needlemanWunch = GetUnnormalisedSimilarity(firstWord, secondWord);
+ double maxValue = Math.Max(firstWord.Length, secondWord.Length);
+ double minValue = maxValue;
+ if (dCostFunction.MaxCost > gapCost)
+ {
+ maxValue *= dCostFunction.MaxCost;
+ }
+ else
+ {
+ maxValue *= gapCost;
+ }
+ if (dCostFunction.MinCost < gapCost)
+ {
+ minValue *= dCostFunction.MinCost;
+ }
+ else
+ {
+ minValue *= gapCost;
+ }
+ if (minValue < defaultMismatchScore)
+ {
+ maxValue -= minValue;
+ needlemanWunch -= minValue;
+ }
+ if (maxValue == defaultMismatchScore)
+ {
+ return defaultPerfectMatchScore;
+ }
+ else
+ {
+ return defaultPerfectMatchScore - needlemanWunch / maxValue;
+ }
+ }
+ return defaultMismatchScore;
+ }
+
+ /// gets a div class xhtml similarity explaining the operation of the metric.
+ /// string 1
+ /// string 2
+ /// a div class html section detailing the metric operation.
+ public override string GetSimilarityExplained(string firstWord, string secondWord)
+ {
+ throw new NotImplementedException();
+ }
+
+ ///
+ /// gets the estimated time in milliseconds it takes to perform a similarity timing.
+ ///
+ ///
+ ///
+ /// the estimated time in milliseconds taken to perform the similarity measure
+ public override double GetSimilarityTimingEstimated(string firstWord, string secondWord)
+ {
+ if ((firstWord != null) && (secondWord != null))
+ {
+ double firstLength = firstWord.Length;
+ double secondLength = secondWord.Length;
+ return firstLength * secondLength * estimatedTimingConstant;
+ }
+ return defaultMismatchScore;
+ }
+
+ ///
+ /// gets the un-normalised similarity measure of the metric for the given strings.
+ ///
+ ///
+ /// returns the score of the similarity measure (un-normalised)
+ public override double GetUnnormalisedSimilarity(string firstWord, string secondWord)
+ {
+ if ((firstWord != null) && (secondWord != null))
+ {
+ int n = firstWord.Length;
+ int m = secondWord.Length;
+ if (n == 0)
+ {
+ return m;
+ }
+ if (m == 0)
+ {
+ return n;
+ }
+ double[][] d = new double[n + 1][];
+ for (int i = 0; i < n + 1; i++)
+ {
+ d[i] = new double[m + 1];
+ }
+ for (int i = 0; i <= n; i++)
+ {
+ d[i][0] = i;
+ }
+
+ for (int j = 0; j <= m; j++)
+ {
+ d[0][j] = j;
+ }
+
+ for (int i = 1; i <= n; i++)
+ {
+ for (int j = 1; j <= m; j++)
+ {
+ double cost = dCostFunction.GetCost(firstWord, i - 1, secondWord, j - 1);
+ d[i][j] = MathFunctions.MinOf3(d[i - 1][j] + gapCost, d[i][j - 1] + gapCost, d[i - 1][j - 1] + cost);
+ }
+ }
+
+ return d[n][m];
+ }
+ return 0.0;
+ }
+
+ ///
+ /// set/get the d(i,j) cost function.
+ ///
+ public AbstractSubstitutionCost DCostFunction { get { return dCostFunction; } set { dCostFunction = value; } }
+
+ ///
+ /// sets/gets the gap cost for the distance function.
+ ///
+ public double GapCost { get { return gapCost; } set { gapCost = value; } }
+
+ ///
+ /// returns the long string identifier for the metric.
+ ///
+ public override string LongDescriptionString
+ {
+ get
+ {
+ return
+ "Implements the Needleman-Wunch algorithm providing an edit distance based similarity measure between two strings";
+ }
+ }
+
+ ///
+ /// returns the string identifier for the metric.
+ ///
+ public override string ShortDescriptionString { get { return "NeedlemanWunch"; } }
+ }
+
+ ///
+ /// base class which all metrics inherit from.
+ ///
+ /// This class implemented a few basic methods and then leaves the others to
+ /// be implemented by the similarity metric itself.
+ [Serializable]
+ abstract public class AbstractStringMetric : IStringMetric
+ {
+ ///
+ /// does a batch comparison of the set of strings with the given
+ /// comparator string returning an array of results equal in length
+ /// to the size of the given set of strings to test.
+ ///
+ /// an array of strings to test against the comparator string
+ /// the comparator string to test the array against
+ /// an array of results equal in length to the size of the given set of strings to test.
+ public double[] BatchCompareSet(string[] setRenamed, string comparator)
+ {
+ if ((setRenamed != null) && (comparator != null))
+ {
+ double[] results = new double[setRenamed.Length];
+ for (int strNum = 0; strNum < setRenamed.Length; strNum++)
+ {
+ results[strNum] = GetSimilarity(setRenamed[strNum], comparator);
+ }
+ return results;
+ }
+ return null;
+ }
+
+ ///
+ /// does a batch comparison of one set of strings against another set
+ /// of strings returning an array of results equal in length
+ /// to the minimum size of the given sets of strings to test.
+ ///
+ /// an array of strings to test
+ /// an array of strings to test the first array against
+ /// an array of results equal in length to the minimum size of the given sets of strings to test.
+ public double[] BatchCompareSets(string[] firstSet, string[] secondSet)
+ {
+ if ((firstSet != null) && (secondSet != null))
+ {
+ double[] results;
+ if (firstSet.Length <= secondSet.Length)
+ {
+ results = new double[firstSet.Length];
+ }
+ else
+ {
+ results = new double[secondSet.Length];
+ }
+ for (int strNum = 0; strNum < results.Length; strNum++)
+ {
+ results[strNum] = GetSimilarity(firstSet[strNum], secondSet[strNum]);
+ }
+ return results;
+ }
+ return null;
+ }
+
+ ///
+ /// gets the similarity measure of the metric for the given strings.
+ ///
+ ///
+ ///
+ /// implemented version will return score between 0 and 1
+ abstract public double GetSimilarity(string firstWord, string secondWord);
+
+ /// gets a div class xhtml similarity explaining the operation of the metric.
+ /// string 1
+ /// string 2
+ /// a div class html section detailing the metric operation.
+ abstract public string GetSimilarityExplained(string firstWord, string secondWord);
+
+ ///
+ /// gets the actual time in milliseconds it takes to perform a similarity timing.
+ /// This call takes as long as the similarity metric to perform so should not be done in normal circumstances.
+ ///
+ ///
+ ///
+ /// the actual time in milliseconds taken to perform the similarity measure
+ public long GetSimilarityTimingActual(string firstWord, string secondWord)
+ {
+ long timeBefore = (DateTime.Now.Ticks - 621355968000000000) / 10000;
+ GetSimilarity(firstWord, secondWord);
+ long timeAfter = (DateTime.Now.Ticks - 621355968000000000) / 10000;
+ return timeAfter - timeBefore;
+ }
+
+ ///
+ /// gets the estimated time in milliseconds it takes to perform a similarity timing.
+ ///
+ ///
+ ///
+ /// the estimated time in milliseconds taken to perform the similarity measure
+ abstract public double GetSimilarityTimingEstimated(string firstWord, string secondWord);
+
+ ///
+ /// gets the un-normalised similarity measure of the metric for the given strings.
+ ///
+ ///
+ /// returns the score of the similarity measure (un-normalised)
+ abstract public double GetUnnormalisedSimilarity(string firstWord, string secondWord);
+
+ ///
+ /// reports the metric type.
+ ///
+ abstract public string LongDescriptionString { get; }
+
+ ///
+ /// reports the metric type.
+ ///
+ abstract public string ShortDescriptionString { get; }
+ }
+
+ ///
+ /// implements an interface for the string metrics
+ ///
+ public interface IStringMetric
+ {
+ ///
+ /// returns a similarity measure of the string comparison.
+ ///
+ ///
+ ///
+ /// a double between zero to one (zero = no similarity, one = matching strings)
+ double GetSimilarity(string firstWord, string secondWord);
+
+ /// gets a div class xhtml similarity explaining the operation of the metric.
+ ///
+ ///
+ /// string 1
+ ///
+ /// string 2
+ ///
+ ///
+ /// a div class html section detailing the metric operation.
+ ///
+ string GetSimilarityExplained(string firstWord, string secondWord);
+
+ ///
+ /// gets the actual time in milliseconds it takes to perform a similarity timing.
+ ///
+ ///
+ ///
+ /// the actual time in milliseconds taken to perform the similarity measure
+ /// This call takes as long as the similarity metric to perform so should not be done in normal cercumstances.
+ long GetSimilarityTimingActual(string firstWord, string secondWord);
+
+ ///
+ /// gets the estimated time in milliseconds it takes to perform a similarity timing.
+ ///
+ ///
+ ///
+ /// the estimated time in milliseconds taken to perform the similarity measure
+ double GetSimilarityTimingEstimated(string firstWord, string secondWord);
+
+ ///
+ /// gets the un-normalised similarity measure of the metric for the given strings.
+ ///
+ ///
+ ///
+ /// returns the score of the similarity measure (un-normalised)
+ double GetUnnormalisedSimilarity(string firstWord, string secondWord);
+
+ ///
+ /// returns a long string of the string metric description.
+ ///
+ string LongDescriptionString { get; }
+
+ ///
+ /// returns a string of the string metric name.
+ ///
+ string ShortDescriptionString { get; }
+ }
+
+ static public class MathFunctions
+ {
+ ///
+ /// returns the max of three numbers.
+ ///
+ /// first number to test
+ /// second number to test
+ /// third number to test
+ /// the max of three numbers.
+ static public double MaxOf3(double firstNumber, double secondNumber, double thirdNumber)
+ {
+ return Math.Max(firstNumber, Math.Max(secondNumber, thirdNumber));
+ }
+
+ ///
+ /// returns the max of three numbers.
+ ///
+ /// first number to test
+ /// second number to test
+ /// third number to test
+ /// the max of three numbers.
+ static public int MaxOf3(int firstNumber, int secondNumber, int thirdNumber)
+ {
+ return Math.Max(firstNumber, Math.Max(secondNumber, thirdNumber));
+ }
+
+ ///
+ /// returns the max of four numbers.
+ ///
+ /// first number to test
+ /// second number to test
+ /// third number to test
+ /// fourth number to test
+ /// the max of four numbers.
+ static public double MaxOf4(double firstNumber, double secondNumber, double thirdNumber, double fourthNumber)
+ {
+ return Math.Max(Math.Max(firstNumber, secondNumber), Math.Max(thirdNumber, fourthNumber));
+ }
+
+ ///
+ /// returns the min of three numbers.
+ ///
+ /// first number to test
+ /// second number to test
+ /// third number to test
+ /// the min of three numbers.
+ static public double MinOf3(double firstNumber, double secondNumber, double thirdNumber)
+ {
+ return Math.Min(firstNumber, Math.Min(secondNumber, thirdNumber));
+ }
+
+ ///
+ /// returns the min of three numbers.
+ ///
+ /// first number to test
+ /// second number to test
+ /// third number to test
+ /// the min of three numbers.
+ static public int MinOf3(int firstNumber, int secondNumber, int thirdNumber)
+ {
+ return Math.Min(firstNumber, Math.Min(secondNumber, thirdNumber));
+ }
+ }
+
+ ///
+ /// implements a substitution cost function where d(i,j) = 1 if idoes not equal j, 0 if i equals j.
+ ///
+ [Serializable]
+ sealed public class SubCostRange0To1 : AbstractSubstitutionCost
+ {
+ const int charExactMatchScore = 1;
+ const int charMismatchMatchScore = 0;
+
+ ///
+ /// get cost between characters where d(i,j) = 1 if i does not equals j, 0 if i equals j.
+ ///
+ /// the string1 to evaluate the cost
+ /// the index within the string1 to test
+ /// the string2 to evaluate the cost
+ /// the index within the string2 to test
+ /// the cost of a given subsitution d(i,j) where d(i,j) = 1 if i!=j, 0 if i==j
+ public override double GetCost(string firstWord, int firstWordIndex, string secondWord, int secondWordIndex)
+ {
+ if ((firstWord != null) && (secondWord != null))
+ {
+ return firstWord[firstWordIndex] != secondWord[secondWordIndex] ? charExactMatchScore : charMismatchMatchScore;
+ }
+ return 0.0;
+ }
+
+ ///
+ /// returns the maximum possible cost.
+ ///
+ public override double MaxCost { get { return charExactMatchScore; } }
+
+ ///
+ /// returns the minimum possible cost.
+ ///
+ public override double MinCost { get { return charMismatchMatchScore; } }
+
+ ///
+ /// returns the name of the cost function.
+ ///
+ public override string ShortDescriptionString { get { return "SubCostRange0To1"; } }
+ }
+
+ ///
+ /// AbstractSubstitutionCost implements a abstract class for substiution costs
+ ///
+ [Serializable]
+ abstract public class AbstractSubstitutionCost : ISubstitutionCost
+ {
+ ///
+ /// get cost between characters.
+ ///
+ /// the firstWord to evaluate the cost
+ /// the index within the firstWord to test
+ /// the secondWord to evaluate the cost
+ /// the index within the string2 to test
+ ///
+ abstract public double GetCost(string firstWord, int firstWordIndex, string secondWord, int secondWordIndex);
+
+ ///
+ /// returns the maximum possible cost.
+ ///
+ abstract public double MaxCost { get; }
+
+ ///
+ /// returns the minimum possible cost.
+ ///
+ abstract public double MinCost { get; }
+
+ ///
+ /// returns the name of the cost function.
+ ///
+ abstract public string ShortDescriptionString { get; }
+ }
+
+ ///
+ /// is an interface for a cost function d(i,j).
+ ///
+ public interface ISubstitutionCost
+ {
+ ///
+ /// get cost between characters.
+ ///
+ /// the firstWord to evaluate the cost
+ /// the index within the firstWord to test
+ /// the secondWord to evaluate the cost
+ /// the index within the secondWord to test
+ ///
+ double GetCost(string firstWord, int firstWordIndex, string secondWord, int secondWordIndex);
+
+ ///
+ /// returns the maximum possible cost.
+ ///
+ double MaxCost { get; }
+
+ ///
+ /// returns the minimum possible cost.
+ ///
+ double MinCost { get; }
+
+ ///
+ /// returns the name of the cost function.
+ ///
+ string ShortDescriptionString { get; }
+ }
}
diff --git a/dnGREP.PdfEngine/GrepEnginePdf.cs b/dnGREP.PdfEngine/GrepEnginePdf.cs
index 55d663ad..993c1e5a 100644
--- a/dnGREP.PdfEngine/GrepEnginePdf.cs
+++ b/dnGREP.PdfEngine/GrepEnginePdf.cs
@@ -9,52 +9,52 @@
namespace dnGREP.Engines.Pdf
{
- ///
- /// Based on a MicrosoftWordPlugin class for AstroGrep by Curtis Beard. Thank you!
- ///
- public class GrepEnginePdf : GrepEngineBase, IGrepEngine
- {
- private static Logger logger = LogManager.GetCurrentClassLogger();
- private string pathToPdfToText = "";
-
- #region Initialization and disposal
- public override bool Initialize(GrepEngineInitParams param, FileFilter filter)
- {
+ ///
+ /// Based on a MicrosoftWordPlugin class for AstroGrep by Curtis Beard. Thank you!
+ ///
+ public class GrepEnginePdf : GrepEngineBase, IGrepEngine
+ {
+ private static Logger logger = LogManager.GetCurrentClassLogger();
+ private string pathToPdfToText = "";
+
+ #region Initialization and disposal
+ public override bool Initialize(GrepEngineInitParams param, FileFilter filter)
+ {
base.Initialize(param, filter);
- try
- {
- // Make sure pdftotext.exe exists
- pathToPdfToText = Utils.GetCurrentPath(typeof(GrepEnginePdf)) + "\\pdftotext.exe";
- if (File.Exists(pathToPdfToText))
- return true;
- else
- return false;
- }
- catch (Exception ex)
- {
- logger.Log(LogLevel.Error, "Failed to find pdftotext.exe.", ex);
- return false;
- }
- }
-
- #endregion
-
- public bool IsSearchOnly
- {
- get { return true; }
- }
+ try
+ {
+ // Make sure pdftotext.exe exists
+ pathToPdfToText = Utils.GetCurrentPath(typeof(GrepEnginePdf)) + "\\pdftotext.exe";
+ if (File.Exists(pathToPdfToText))
+ return true;
+ else
+ return false;
+ }
+ catch (Exception ex)
+ {
+ logger.Log(LogLevel.Error, "Failed to find pdftotext.exe.", ex);
+ return false;
+ }
+ }
+
+ #endregion
+
+ public bool IsSearchOnly
+ {
+ get { return true; }
+ }
public List Search(string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
- {
- try
- {
- // Extract text
- string tempFile = extractText(file);
- if (!File.Exists(tempFile))
- throw new ApplicationException("pdftotext failed to create text file.");
+ {
+ try
+ {
+ // Extract text
+ string tempFile = extractText(file);
+ if (!File.Exists(tempFile))
+ throw new ApplicationException("pdftotext failed to create text file.");
IGrepEngine engine = GrepEngineFactory.GetSearchEngine(tempFile, initParams, FileFilter);
- List results = engine.Search(tempFile, searchPattern, searchType, searchOptions, encoding);
+ List results = engine.Search(tempFile, searchPattern, searchType, searchOptions, encoding);
if (results.Count > 0)
{
@@ -75,70 +75,70 @@ public List Search(string file, string searchPattern, SearchTy
}
}
- return results;
- }
- catch (Exception ex)
- {
- logger.Log(LogLevel.Error, "Failed to search inside Pdf file", ex);
- return new List();
- }
- }
-
- private string extractText(string pdfFilePath)
- {
- string tempFolder = Utils.GetTempFolder() + "dnGREP-PDF\\";
- if (!Directory.Exists(tempFolder))
- Directory.CreateDirectory(tempFolder);
- string tempFileName = tempFolder + Path.GetFileNameWithoutExtension(pdfFilePath) + ".txt";
-
- using (Process process = new Process())
- {
- try
- {
- // use command prompt
- process.StartInfo.FileName = pathToPdfToText;
- process.StartInfo.Arguments = string.Format("-layout \"{0}\" \"{1}\"", pdfFilePath, tempFileName);
- process.StartInfo.UseShellExecute = false;
- process.StartInfo.WorkingDirectory = Utils.GetCurrentPath(typeof(GrepEnginePdf));
- process.StartInfo.CreateNoWindow = true;
- // start cmd prompt, execute command
- process.Start();
- process.WaitForExit();
-
- if (process.ExitCode == 0)
- return tempFileName;
- else
- throw new Exception("pdftotext process exited with error code.");
- }
- catch
- {
- throw;
- }
- }
- }
+ return results;
+ }
+ catch (Exception ex)
+ {
+ logger.Log(LogLevel.Error, "Failed to search inside Pdf file", ex);
+ return new List();
+ }
+ }
+
+ private string extractText(string pdfFilePath)
+ {
+ string tempFolder = Utils.GetTempFolder() + "dnGREP-PDF\\";
+ if (!Directory.Exists(tempFolder))
+ Directory.CreateDirectory(tempFolder);
+ string tempFileName = tempFolder + Path.GetFileNameWithoutExtension(pdfFilePath) + ".txt";
+
+ using (Process process = new Process())
+ {
+ try
+ {
+ // use command prompt
+ process.StartInfo.FileName = pathToPdfToText;
+ process.StartInfo.Arguments = string.Format("-layout \"{0}\" \"{1}\"", pdfFilePath, tempFileName);
+ process.StartInfo.UseShellExecute = false;
+ process.StartInfo.WorkingDirectory = Utils.GetCurrentPath(typeof(GrepEnginePdf));
+ process.StartInfo.CreateNoWindow = true;
+ // start cmd prompt, execute command
+ process.Start();
+ process.WaitForExit();
+
+ if (process.ExitCode == 0)
+ return tempFileName;
+ else
+ throw new Exception("pdftotext process exited with error code.");
+ }
+ catch
+ {
+ throw;
+ }
+ }
+ }
public bool Replace(string sourceFile, string destinationFile, string searchPattern, string replacePattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding)
- {
- throw new Exception("The method or operation is not implemented.");
- }
-
- public Version FrameworkVersion
- {
- get
- {
+ {
+ throw new Exception("The method or operation is not implemented.");
+ }
+
+ public Version FrameworkVersion
+ {
+ get
+ {
return Assembly.GetAssembly(typeof(IGrepEngine)).GetName().Version;
- }
- }
-
- public void Unload()
- {
- //Do nothing
- }
-
- public override void OpenFile(OpenFileArgs args)
- {
- args.UseCustomEditor = false;
- Utils.OpenFile(args);
- }
- }
+ }
+ }
+
+ public void Unload()
+ {
+ //Do nothing
+ }
+
+ public override void OpenFile(OpenFileArgs args)
+ {
+ args.UseCustomEditor = false;
+ Utils.OpenFile(args);
+ }
+ }
}
diff --git a/dnGREP.PdfEngine/app.config b/dnGREP.PdfEngine/app.config
index 6f934842..af399dd6 100644
--- a/dnGREP.PdfEngine/app.config
+++ b/dnGREP.PdfEngine/app.config
@@ -1,3 +1,6 @@
-
+
+
+
+
diff --git a/dnGREP.WPF/AboutForm.cs b/dnGREP.WPF/AboutForm.cs
index ec264f6d..eee91ad3 100644
--- a/dnGREP.WPF/AboutForm.cs
+++ b/dnGREP.WPF/AboutForm.cs
@@ -1,122 +1,119 @@
using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Drawing;
-using System.Windows.Forms;
+using System.Globalization;
using System.Reflection;
+using System.Windows.Forms;
using dnGREP.Common.UI;
-using System.Globalization;
namespace dnGREP.WPF
{
- partial class AboutForm : Form
- {
- public AboutForm()
- {
- InitializeComponent();
+ partial class AboutForm : Form
+ {
+ public AboutForm()
+ {
+ InitializeComponent();
- // Initialize the AboutBox to display the product information from the assembly information.
- // Change assembly information settings for your application through either:
- // - Project->Properties->Application->Assembly Information
- // - AssemblyInfo.cs
- this.Text = String.Format("About {0}", AssemblyTitle);
- this.labelProductName.Text = AssemblyProduct;
- this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion);
- this.labelBuildDate.Text = String.Format("Built on {0}", AssemblyBuildDate.ToString(CultureInfo.CurrentUICulture));
+ // Initialize the AboutBox to display the product information from the assembly information.
+ // Change assembly information settings for your application through either:
+ // - Project->Properties->Application->Assembly Information
+ // - AssemblyInfo.cs
+ this.Text = String.Format("About {0}", AssemblyTitle);
+ this.labelProductName.Text = AssemblyProduct;
+ this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion);
+ this.labelBuildDate.Text = String.Format("Built on {0}", AssemblyBuildDate.ToString(CultureInfo.CurrentUICulture));
this.labelCopyright.Text = AssemblyCopyright;
this.textBoxDescription.Text = AssemblyDescription;
- }
+ }
- #region Assembly Attribute Accessors
+ #region Assembly Attribute Accessors
- public string AssemblyTitle
- {
- get
- {
- // Get all Title attributes on this assembly
- object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
- // If there is at least one Title attribute
- if (attributes.Length > 0)
- {
- // Select the first one
- AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
- // If it is not an empty string, return it
- if (titleAttribute.Title != "")
- return titleAttribute.Title;
- }
- // If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name
- return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
- }
- }
+ public string AssemblyTitle
+ {
+ get
+ {
+ // Get all Title attributes on this assembly
+ object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
+ // If there is at least one Title attribute
+ if (attributes.Length > 0)
+ {
+ // Select the first one
+ AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
+ // If it is not an empty string, return it
+ if (titleAttribute.Title != "")
+ return titleAttribute.Title;
+ }
+ // If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name
+ return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
+ }
+ }
- public string AssemblyVersion
- {
- get
- {
- return Assembly.GetExecutingAssembly().GetName().Version.ToString();
- }
- }
+ public string AssemblyVersion
+ {
+ get
+ {
+ return Assembly.GetExecutingAssembly().GetName().Version.ToString();
+ }
+ }
- public string AssemblyDescription
- {
- get
- {
- // Get all Description attributes on this assembly
- object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
- // If there aren't any Description attributes, return an empty string
- if (attributes.Length == 0)
- return "";
- // If there is a Description attribute, return its value
- return ((AssemblyDescriptionAttribute)attributes[0]).Description;
- }
- }
+ public string AssemblyDescription
+ {
+ get
+ {
+ // Get all Description attributes on this assembly
+ object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
+ // If there aren't any Description attributes, return an empty string
+ if (attributes.Length == 0)
+ return "";
+ // If there is a Description attribute, return its value
+ return ((AssemblyDescriptionAttribute)attributes[0]).Description;
+ }
+ }
- public string AssemblyProduct
- {
- get
- {
- // Get all Product attributes on this assembly
- object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
- // If there aren't any Product attributes, return an empty string
- if (attributes.Length == 0)
- return "";
- // If there is a Product attribute, return its value
- return ((AssemblyProductAttribute)attributes[0]).Product;
- }
- }
+ public string AssemblyProduct
+ {
+ get
+ {
+ // Get all Product attributes on this assembly
+ object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
+ // If there aren't any Product attributes, return an empty string
+ if (attributes.Length == 0)
+ return "";
+ // If there is a Product attribute, return its value
+ return ((AssemblyProductAttribute)attributes[0]).Product;
+ }
+ }
- public string AssemblyCopyright
- {
- get
- {
- // Get all Copyright attributes on this assembly
- object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
- // If there aren't any Copyright attributes, return an empty string
- if (attributes.Length == 0)
- return "";
- // If there is a Copyright attribute, return its value
- return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
- }
- }
+ public string AssemblyCopyright
+ {
+ get
+ {
+ // Get all Copyright attributes on this assembly
+ object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
+ // If there aren't any Copyright attributes, return an empty string
+ if (attributes.Length == 0)
+ return "";
+ // If there is a Copyright attribute, return its value
+ return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
+ }
+ }
- public string AssemblyCompany
- {
- get
- {
- // Get all Company attributes on this assembly
- object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
- // If there aren't any Company attributes, return an empty string
- if (attributes.Length == 0)
- return "";
- // If there is a Company attribute, return its value
- return ((AssemblyCompanyAttribute)attributes[0]).Company;
- }
- }
+ public string AssemblyCompany
+ {
+ get
+ {
+ // Get all Company attributes on this assembly
+ object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
+ // If there aren't any Company attributes, return an empty string
+ if (attributes.Length == 0)
+ return "";
+ // If there is a Company attribute, return its value
+ return ((AssemblyCompanyAttribute)attributes[0]).Company;
+ }
+ }
public DateTime AssemblyBuildDate
{
get { return Assembly.GetExecutingAssembly().GetLinkerTime(); }
}
- #endregion
- }
+ #endregion
+ }
}
diff --git a/dnGREP.WPF/App.xaml.cs b/dnGREP.WPF/App.xaml.cs
index ab60553f..6568d2c8 100644
--- a/dnGREP.WPF/App.xaml.cs
+++ b/dnGREP.WPF/App.xaml.cs
@@ -1,8 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Configuration;
-using System.Data;
-using System.Linq;
using System.Windows;
using dnGREP.Common;
using NLog;
diff --git a/dnGREP.WPF/DesignTimeData/DesignTimeData.cs b/dnGREP.WPF/DesignTimeData/DesignTimeData.cs
index 99108cd7..89877676 100644
--- a/dnGREP.WPF/DesignTimeData/DesignTimeData.cs
+++ b/dnGREP.WPF/DesignTimeData/DesignTimeData.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
-using System.Linq;
using System.Text;
namespace dnGREP.WPF.DesignTimeData
diff --git a/dnGREP.WPF/Dictionaries/CustomTemplates.xaml b/dnGREP.WPF/Dictionaries/CustomTemplates.xaml
index 47138273..664cb226 100644
--- a/dnGREP.WPF/Dictionaries/CustomTemplates.xaml
+++ b/dnGREP.WPF/Dictionaries/CustomTemplates.xaml
@@ -154,9 +154,9 @@
+
+
+
-
+
-
+
\ No newline at end of file
diff --git a/dnGREP.WPF/HelpProvider.cs b/dnGREP.WPF/HelpProvider.cs
index 19c0c3af..61318f2a 100644
--- a/dnGREP.WPF/HelpProvider.cs
+++ b/dnGREP.WPF/HelpProvider.cs
@@ -10,7 +10,6 @@ namespace dnGREP.WPF
///
public static class DiginesisHelpProvider
{
-
#region Fields
private static string mHelpNamespace = null;
@@ -241,7 +240,7 @@ private static void OnHelpExecuted(object sender, ExecutedRoutedEventArgs e)
if (!string.IsNullOrEmpty(parameter))
{
- if (HelpNamespace.StartsWith("http"))
+ if (HelpNamespace.StartsWith("http"))
Help.ShowHelp(null, HelpNamespace + parameter, command);
else
Help.ShowHelp(null, HelpNamespace, command, parameter);
@@ -301,7 +300,5 @@ private static void OnHelpExecuted(object sender, ExecutedRoutedEventArgs e)
}
#endregion
-
}
-
}
\ No newline at end of file
diff --git a/dnGREP.WPF/Launcher.cs b/dnGREP.WPF/Launcher.cs
deleted file mode 100644
index 50b10d43..00000000
--- a/dnGREP.WPF/Launcher.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-using System;
-using System.Linq;
-using Microsoft.VisualBasic.ApplicationServices;
-
-namespace dnGREP.WPF
-{
- public class Launcher
- {
- [STAThread]
- public static void Main(string[] args)
- {
- dnGrepApp app = new dnGrepApp();
- app.Run();
- }
- }
-}
diff --git a/dnGREP.WPF/MVHelpers/CodeSnippet.cs b/dnGREP.WPF/MVHelpers/CodeSnippet.cs
index 78c6eac7..4bb0f310 100644
--- a/dnGREP.WPF/MVHelpers/CodeSnippet.cs
+++ b/dnGREP.WPF/MVHelpers/CodeSnippet.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Linq;
-using System.Text;
+using System.ComponentModel;
using dnGREP.Common;
namespace dnGREP.WPF
diff --git a/dnGREP.WPF/MVHelpers/EnumBooleanConverter.cs b/dnGREP.WPF/MVHelpers/EnumBooleanConverter.cs
index 5b31c1a5..e66ab8e5 100644
--- a/dnGREP.WPF/MVHelpers/EnumBooleanConverter.cs
+++ b/dnGREP.WPF/MVHelpers/EnumBooleanConverter.cs
@@ -1,38 +1,35 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.Globalization;
using System.Windows;
using System.Windows.Data;
-using System.Globalization;
namespace dnGREP.WPF
{
- public class EnumBooleanConverter : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- var ParameterString = parameter as string;
- if (ParameterString == null)
- return DependencyProperty.UnsetValue;
+ public class EnumBooleanConverter : IValueConverter
+ {
+ public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ var ParameterString = parameter as string;
+ if (ParameterString == null)
+ return DependencyProperty.UnsetValue;
- if (Enum.IsDefined(value.GetType(), value) == false)
- return DependencyProperty.UnsetValue;
+ if (Enum.IsDefined(value.GetType(), value) == false)
+ return DependencyProperty.UnsetValue;
- object paramvalue = Enum.Parse(value.GetType(), ParameterString);
- if (paramvalue.Equals(value))
- return true;
- else
- return false;
- }
+ object paramvalue = Enum.Parse(value.GetType(), ParameterString);
+ if (paramvalue.Equals(value))
+ return true;
+ else
+ return false;
+ }
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
+ public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+ {
var ParameterString = parameter as string;
- if (ParameterString == null || value.Equals(false))
- return DependencyProperty.UnsetValue;
+ if (ParameterString == null || value.Equals(false))
+ return DependencyProperty.UnsetValue;
- return Enum.Parse(targetType, ParameterString);
- }
- }
+ return Enum.Parse(targetType, ParameterString);
+ }
+ }
}
diff --git a/dnGREP.WPF/MVHelpers/InlineTextBlock.cs b/dnGREP.WPF/MVHelpers/InlineTextBlock.cs
index ac6ecf15..0971ccbc 100644
--- a/dnGREP.WPF/MVHelpers/InlineTextBlock.cs
+++ b/dnGREP.WPF/MVHelpers/InlineTextBlock.cs
@@ -1,46 +1,44 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
using System.Linq;
-using System.Text;
-using System.Windows.Documents;
using System.Windows;
using System.Windows.Controls;
+using System.Windows.Documents;
namespace dnGREP.WPF
{
- public class InlineTextBlock : TextBlock
- {
- public InlineCollection InlineCollection
- {
- get
- {
- return (InlineCollection)GetValue(InlineCollectionProperty);
- }
- set
- {
- SetValue(InlineCollectionProperty, value);
- }
- }
+ public class InlineTextBlock : TextBlock
+ {
+ public InlineCollection InlineCollection
+ {
+ get
+ {
+ return (InlineCollection)GetValue(InlineCollectionProperty);
+ }
+ set
+ {
+ SetValue(InlineCollectionProperty, value);
+ }
+ }
- public static readonly DependencyProperty InlineCollectionProperty = DependencyProperty.Register(
- "InlineCollection",
- typeof(InlineCollection),
- typeof(InlineTextBlock),
- new UIPropertyMetadata((PropertyChangedCallback)((sender, args) =>
- {
- InlineTextBlock textBlock = sender as InlineTextBlock;
+ public static readonly DependencyProperty InlineCollectionProperty = DependencyProperty.Register(
+ "InlineCollection",
+ typeof(InlineCollection),
+ typeof(InlineTextBlock),
+ new UIPropertyMetadata((PropertyChangedCallback)((sender, args) =>
+ {
+ InlineTextBlock textBlock = sender as InlineTextBlock;
- if (textBlock != null)
- {
- textBlock.Inlines.Clear();
+ if (textBlock != null)
+ {
+ textBlock.Inlines.Clear();
- InlineCollection inlines = args.NewValue as InlineCollection;
+ InlineCollection inlines = args.NewValue as InlineCollection;
- if (inlines != null)
- textBlock.Inlines.AddRange(inlines.ToList());
- }
- })));
- }
+ if (inlines != null)
+ textBlock.Inlines.AddRange(inlines.ToList());
+ }
+ })));
+ }
public class RichTextBlock : System.Windows.Controls.TextBlock
{
diff --git a/dnGREP.WPF/MVHelpers/InverseBooleanConverter.cs b/dnGREP.WPF/MVHelpers/InverseBooleanConverter.cs
index bd98fa0b..d44428ef 100644
--- a/dnGREP.WPF/MVHelpers/InverseBooleanConverter.cs
+++ b/dnGREP.WPF/MVHelpers/InverseBooleanConverter.cs
@@ -1,7 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using System.Windows.Data;
namespace dnGREP.WPF
@@ -9,8 +6,6 @@ namespace dnGREP.WPF
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
- #region IValueConverter Members
-
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
@@ -25,7 +20,5 @@ public class InverseBooleanConverter : IValueConverter
{
throw new NotSupportedException();
}
-
- #endregion
}
}
diff --git a/dnGREP.WPF/MVHelpers/PixelBasedScrollingBehavior.cs b/dnGREP.WPF/MVHelpers/PixelBasedScrollingBehavior.cs
index 5f17edfe..d5651e9d 100644
--- a/dnGREP.WPF/MVHelpers/PixelBasedScrollingBehavior.cs
+++ b/dnGREP.WPF/MVHelpers/PixelBasedScrollingBehavior.cs
@@ -1,19 +1,10 @@
-// -----------------------------------------------------------------------
-//
-// TODO: Update copyright text.
-//
-// -----------------------------------------------------------------------
+using System;
+using System.Reflection;
+using System.Windows;
+using System.Windows.Controls;
namespace dnGREP.WPF
{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- using System.Reflection;
-
public static class PixelBasedScrollingBehavior
{
public static bool GetIsEnabled(DependencyObject obj)
@@ -41,7 +32,7 @@ private static void HandleIsEnabledChanged(DependencyObject d, DependencyPropert
if (property == null)
{
- throw new InvalidOperationException("Pixel-based scrolling behaviour hack no longer works!");
+ throw new InvalidOperationException("Pixel-based scrolling behavior hack no longer works!");
}
if ((bool)e.NewValue == true)
@@ -54,5 +45,4 @@ private static void HandleIsEnabledChanged(DependencyObject d, DependencyPropert
}
}
}
-
}
diff --git a/dnGREP.WPF/MVHelpers/PreviewHighlighter.cs b/dnGREP.WPF/MVHelpers/PreviewHighlighter.cs
index 81366402..eef6e233 100644
--- a/dnGREP.WPF/MVHelpers/PreviewHighlighter.cs
+++ b/dnGREP.WPF/MVHelpers/PreviewHighlighter.cs
@@ -1,12 +1,7 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using ICSharpCode.AvalonEdit.Rendering;
-using System.Windows.Media;
-using System.Windows;
-using ICSharpCode.AvalonEdit.Document;
+using System.Windows.Media;
using dnGREP.Common;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
namespace dnGREP.WPF
{
diff --git a/dnGREP.WPF/MVHelpers/ResultEventArgs.cs b/dnGREP.WPF/MVHelpers/ResultEventArgs.cs
index ff88c3d2..ac3106e1 100644
--- a/dnGREP.WPF/MVHelpers/ResultEventArgs.cs
+++ b/dnGREP.WPF/MVHelpers/ResultEventArgs.cs
@@ -1,8 +1,5 @@
using System;
-using System.Collections.Generic;
using System.Drawing;
-using System.Linq;
-using System.Text;
namespace dnGREP.WPF.MVHelpers
{
diff --git a/dnGREP.WPF/MVHelpers/SnippetLineNumber.cs b/dnGREP.WPF/MVHelpers/SnippetLineNumber.cs
index 98d66a6d..27432925 100644
--- a/dnGREP.WPF/MVHelpers/SnippetLineNumber.cs
+++ b/dnGREP.WPF/MVHelpers/SnippetLineNumber.cs
@@ -1,15 +1,11 @@
using System;
-using System.Collections.Generic;
using System.Globalization;
-using System.Linq;
-using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Rendering;
-using ICSharpCode.AvalonEdit.Utils;
namespace dnGREP.WPF
{
@@ -61,7 +57,7 @@ protected override void OnRender(System.Windows.Media.DrawingContext drawingCont
typeface, emSize, gray
);
double y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
- drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset));
+ drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset));
}
}
}
@@ -70,7 +66,7 @@ protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument
{
base.OnDocumentChanged(oldDocument, newDocument);
- int documentLineCount = (lineNumbers == null? Document.LineCount : lineNumbers[lineNumbers.Length - 1]);
+ int documentLineCount = (lineNumbers == null ? Document.LineCount : lineNumbers[lineNumbers.Length - 1]);
if (documentLineCount <= 0)
documentLineCount = lineNumbers[lineNumbers.Length - 2];
diff --git a/dnGREP.WPF/MVHelpers/TotalValueConverter.cs b/dnGREP.WPF/MVHelpers/TotalValueConverter.cs
index 7c022fe8..160bfa0f 100644
--- a/dnGREP.WPF/MVHelpers/TotalValueConverter.cs
+++ b/dnGREP.WPF/MVHelpers/TotalValueConverter.cs
@@ -1,10 +1,7 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Windows.Data;
using System.Globalization;
using System.Windows;
+using System.Windows.Data;
namespace dnGREP.WPF
{
@@ -22,7 +19,7 @@ public object Convert(object[] values, Type targetType, object parameter, Cultur
total += i;
}
}
-
+
return new GridLength(total);
}
diff --git a/dnGREP.WPF/Properties/AssemblyInfo.cs b/dnGREP.WPF/Properties/AssemblyInfo.cs
index 759ea1a2..58c17ea4 100644
--- a/dnGREP.WPF/Properties/AssemblyInfo.cs
+++ b/dnGREP.WPF/Properties/AssemblyInfo.cs
@@ -1,6 +1,4 @@
using System.Reflection;
-using System.Resources;
-using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
diff --git a/dnGREP.WPF/RelayCommand.cs b/dnGREP.WPF/RelayCommand.cs
index 47c6fd17..a4f25ac9 100644
--- a/dnGREP.WPF/RelayCommand.cs
+++ b/dnGREP.WPF/RelayCommand.cs
@@ -1,5 +1,4 @@
using System;
-using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Input;
diff --git a/dnGREP.WPF/ShellIntegration.cs b/dnGREP.WPF/ShellIntegration.cs
index f656e24f..0f22b3b6 100644
--- a/dnGREP.WPF/ShellIntegration.cs
+++ b/dnGREP.WPF/ShellIntegration.cs
@@ -1,64 +1,60 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using System.Runtime.InteropServices;
-using System.IO;
namespace dnGREP.WPF
{
- class ShellIntegration
- {
- public static void ShowFileProperties(string filename)
- {
- SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
- info.Size = System.Runtime.InteropServices.Marshal.SizeOf(info);
- info.Verb = "properties";
- info.File = filename;
- info.Show = SW_SHOW;
- info.Mask = SEE_MASK_INVOKEIDLIST;
- ShellExecuteEx(ref info);
- }
+ class ShellIntegration
+ {
+ public static void ShowFileProperties(string filename)
+ {
+ SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
+ info.Size = System.Runtime.InteropServices.Marshal.SizeOf(info);
+ info.Verb = "properties";
+ info.File = filename;
+ info.Show = SW_SHOW;
+ info.Mask = SEE_MASK_INVOKEIDLIST;
+ ShellExecuteEx(ref info);
+ }
- //public static void OpenFolder(string filename)
- //{
- // SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
- // info.Size = System.Runtime.InteropServices.Marshal.SizeOf(info);
- // info.Verb = "explore";
- // info.File = filename;
- // info.Show = SW_SHOWNORMAL;
- // info.Class = "folder";
- // info.Mask = SEE_MASK_IDLIST | SEE_MASK_CLASSNAME;
- // ShellExecuteEx(ref info);
- //}
+ //public static void OpenFolder(string filename)
+ //{
+ // SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
+ // info.Size = System.Runtime.InteropServices.Marshal.SizeOf(info);
+ // info.Verb = "explore";
+ // info.File = filename;
+ // info.Show = SW_SHOWNORMAL;
+ // info.Class = "folder";
+ // info.Mask = SEE_MASK_IDLIST | SEE_MASK_CLASSNAME;
+ // ShellExecuteEx(ref info);
+ //}
- private const int SW_SHOW = 5;
- private const int SW_SHOWNORMAL = 1;
- private const uint SEE_MASK_INVOKEIDLIST = 12;
- private const uint SEE_MASK_IDLIST = 4;
- private const uint SEE_MASK_CLASSNAME = 1;
+ private const int SW_SHOW = 5;
+ private const int SW_SHOWNORMAL = 1;
+ private const uint SEE_MASK_INVOKEIDLIST = 12;
+ private const uint SEE_MASK_IDLIST = 4;
+ private const uint SEE_MASK_CLASSNAME = 1;
- [DllImport("shell32.dll")]
- public static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
+ [DllImport("shell32.dll")]
+ public static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
- [Serializable]
- public struct SHELLEXECUTEINFO
- {
- public int Size;
- public uint Mask;
- public IntPtr hwnd;
- public string Verb;
- public string File;
- public string Parameters;
- public string Directory;
- public uint Show;
- public IntPtr InstApp;
- public IntPtr IDList;
- public string Class;
- public IntPtr hkeyClass;
- public uint HotKey;
- public IntPtr Icon;
- public IntPtr Monitor;
- }
- }
+ [Serializable]
+ public struct SHELLEXECUTEINFO
+ {
+ public int Size;
+ public uint Mask;
+ public IntPtr hwnd;
+ public string Verb;
+ public string File;
+ public string Parameters;
+ public string Directory;
+ public uint Show;
+ public IntPtr InstApp;
+ public IntPtr IDList;
+ public string Class;
+ public IntPtr hkeyClass;
+ public uint HotKey;
+ public IntPtr Icon;
+ public IntPtr Monitor;
+ }
+ }
}
diff --git a/dnGREP.WPF/UserControls/BusyIndicator.xaml b/dnGREP.WPF/UserControls/BusyIndicator.xaml
index c4d9ac2a..cfb4829b 100644
--- a/dnGREP.WPF/UserControls/BusyIndicator.xaml
+++ b/dnGREP.WPF/UserControls/BusyIndicator.xaml
@@ -3,10 +3,10 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="400" Width="400">
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Regex
- XPath
- Text
- Phonetic
-
-
-
-
-
-
-
- Options
-
-
-
-
- Case sensitive
- Multiline (slower)
- Whole word
- Match dot as newline
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- . matches all characters
-
- \w matches alpha-numerics
-
- \d matches digits
-
- \s matches space
-
- * matches any number of characters
-
- {1,3} matches 1 to 3 characters
-
- For more Regex patterns hit F1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- File filters
-
-
-
-
-
-
-
-
-
-
-
-
- Search in all files and subfolders
-
- All sizes
-
- Size is
-
-
-
-
-
-
-
-
-
- to
-
-
-
-
-
-
-
-
-
- KB
-
- Include subfolders
- Include hidden folders
- Include binary files
-
-
-
-
-
-
-
-
-
-
-
-
- Paths that match:
-
- Paths to ignore:
-
-
-
- Regex
- Asterisk pattern
-
-
- Encoding:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Preview file
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/dnGREP.WPF/Views/MainView.xaml.cs b/dnGREP.WPF/Views/MainView.xaml.cs
deleted file mode 100644
index f97cbd79..00000000
--- a/dnGREP.WPF/Views/MainView.xaml.cs
+++ /dev/null
@@ -1,427 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.ComponentModel;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using dnGREP.Common;
-using dnGREP.Engines;
-using NLog;
-using System.IO;
-using System.Reflection;
-using System.Collections.ObjectModel;
-using System.Collections.Specialized;
-using dnGREP.Common.UI;
-using System.Text.RegularExpressions;
-using System.Runtime.InteropServices;
-using System.Windows.Interop;
-using Blue.Windows;
-
-namespace dnGREP.WPF
-{
- ///
- /// Interaction logic for MainForm.xaml
- ///
- public partial class MainForm : Window
- {
- private static Logger logger = LogManager.GetCurrentClassLogger();
- private MainViewModel inputData;
- private bool isVisible = true;
-
- public MainForm()
- : this (true)
- {
- }
-
- public MainForm(bool isVisible)
- {
- InitializeComponent();
- this.Width = Properties.Settings.Default.Width;
- this.Height = Properties.Settings.Default.Height;
- this.Top = Properties.Settings.Default.Top;
- this.Left = Properties.Settings.Default.Left;
- if (!UiUtils.IsOnScreen(this))
- UiUtils.CenterWindow(this);
- this.isVisible = isVisible;
- inputData = new MainViewModel();
- this.DataContext = inputData;
- }
-
- [DllImport("user32.dll")]
- static extern IntPtr SetParent(IntPtr hwnd, IntPtr hwndNewParent);
-
- private const int HWND_MESSAGE = -3;
-
- private IntPtr hwnd;
- private IntPtr oldParent;
-
- protected override void OnSourceInitialized(EventArgs e)
- {
- base.OnSourceInitialized(e);
- if (!isVisible)
- {
- HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
-
- if (hwndSource != null)
- {
- hwnd = hwndSource.Handle;
- oldParent = SetParent(hwnd, (IntPtr)HWND_MESSAGE);
- Visibility = Visibility.Hidden;
- }
- }
- }
-
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- inputData.StickyWindow = new StickyWindow(this);
- inputData.StickyWindow.StickToScreen = true;
- inputData.StickyWindow.StickToOther = true;
- inputData.StickyWindow.StickOnResize = true;
- inputData.StickyWindow.StickOnMove = true;
- gridMain.RowDefinitions[1].Height = new GridLength(1, GridUnitType.Auto);
- gridMain.RowDefinitions[3].Height = new GridLength(1, GridUnitType.Star);
- }
-
- private void MainForm_Closing(object sender, CancelEventArgs e)
- {
- Properties.Settings.Default.Width = (int)this.ActualWidth;
- Properties.Settings.Default.Height = (int)this.ActualHeight;
- Properties.Settings.Default.Top = (int)this.Top;
- Properties.Settings.Default.Left = (int)this.Left;
- Properties.Settings.Default.Save();
- inputData.CloseCommand.Execute(null);
- }
-
- #region Tree right click events
-
- private void tvContexMenuOpening(object sender, RoutedEventArgs e)
- {
- if (tvSearchResult.SelectedItem is FormattedGrepLine)
- {
- btnCopyTreeItemClipboard.Header = "Line of text to clipboard";
- btnCopyFileNameClipboard.Visibility = Visibility.Collapsed;
- }
- else if (tvSearchResult.SelectedItem is FormattedGrepResult)
- {
- btnCopyTreeItemClipboard.Header = "Full file path to clipboard";
- btnCopyFileNameClipboard.Visibility = Visibility.Visible;
- }
- }
-
- private void btnOpenFile_Click(object sender, RoutedEventArgs e)
- {
- if (tvSearchResult.SelectedItem is FormattedGrepLine)
- inputData.OpenFile(tvSearchResult.SelectedItem as FormattedGrepLine, false);
- else if (tvSearchResult.SelectedItem is FormattedGrepResult)
- inputData.OpenFile(tvSearchResult.SelectedItem as FormattedGrepResult, false);
- }
-
- private void btnOpenFileCustomEditor_Click(object sender, RoutedEventArgs e)
- {
- if (tvSearchResult.SelectedItem is FormattedGrepLine)
- inputData.OpenFile(tvSearchResult.SelectedItem as FormattedGrepLine, true);
- else if (tvSearchResult.SelectedItem is FormattedGrepResult)
- inputData.OpenFile(tvSearchResult.SelectedItem as FormattedGrepResult, true);
- }
-
- private void btnOpenContainingFolder_Click(object sender, RoutedEventArgs e)
- {
- if (tvSearchResult.SelectedItem is FormattedGrepLine)
- {
- FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
- //ShellIntegration.OpenFolder(selectedNode.Parent.GrepResult.FileNameReal);
- Utils.OpenContainingFolder(selectedNode.Parent.GrepResult.FileNameReal, selectedNode.GrepLine.LineNumber);
- }
- else if (tvSearchResult.SelectedItem is FormattedGrepResult)
- {
- FormattedGrepResult selectedNode = (FormattedGrepResult)tvSearchResult.SelectedItem;
- //ShellIntegration.OpenFolder(selectedNode.GrepResult.FileNameReal);
- Utils.OpenContainingFolder(selectedNode.GrepResult.FileNameReal, -1);
- }
- }
-
- private void btnShowFileProperties_Click(object sender, RoutedEventArgs e)
- {
- string fileName = "";
- if (tvSearchResult.SelectedItem is FormattedGrepLine)
- {
- FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
- fileName = selectedNode.Parent.GrepResult.FileNameReal;
- }
- else if (tvSearchResult.SelectedItem is FormattedGrepResult)
- {
- FormattedGrepResult selectedNode = (FormattedGrepResult)tvSearchResult.SelectedItem;
- fileName = selectedNode.GrepResult.FileNameReal;
- }
-
- if (fileName != "" && File.Exists(fileName))
- ShellIntegration.ShowFileProperties(fileName);
- }
-
- private void btnExpandAll_Click(object sender, RoutedEventArgs e)
- {
- foreach (FormattedGrepResult result in tvSearchResult.Items)
- {
- result.IsExpanded = true;
- }
- }
-
- private void btnCollapseAll_Click(object sender, RoutedEventArgs e)
- {
- foreach (FormattedGrepResult result in tvSearchResult.Items)
- {
- result.IsExpanded = false;
- }
- }
-
- private void btnExclude_Click(object sender, RoutedEventArgs e)
- {
- if (tvSearchResult.SelectedItem is FormattedGrepLine)
- {
- FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
- inputData.SearchResults.Remove(selectedNode.Parent);
- }
- else if (tvSearchResult.SelectedItem is FormattedGrepResult)
- {
- FormattedGrepResult selectedNode = (FormattedGrepResult)tvSearchResult.SelectedItem;
- inputData.SearchResults.Remove(selectedNode);
- }
- }
-
- private void copyToClipboard()
- {
- if (tvSearchResult.SelectedItem is FormattedGrepLine)
- {
- FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
- Clipboard.SetText(selectedNode.GrepLine.LineText);
- }
- else if (tvSearchResult.SelectedItem is FormattedGrepResult)
- {
- FormattedGrepResult result = (FormattedGrepResult)tvSearchResult.SelectedItem;
- Clipboard.SetText(result.GrepResult.FileNameDisplayed);
- }
- }
-
- private void treeKeyDown(object sender, KeyEventArgs e)
- {
- if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
- {
- copyToClipboard();
- }
- }
-
- private void btnCopyTreeItemToClipboard_Click(object sender, RoutedEventArgs e)
- {
- copyToClipboard();
- }
-
- private void btnCopyNameToClipboard_Click(object sender, RoutedEventArgs e)
- {
- if (tvSearchResult.SelectedItem is FormattedGrepLine)
- {
- FormattedGrepLine selectedNode = (FormattedGrepLine)tvSearchResult.SelectedItem;
- Clipboard.SetText(System.IO.Path.GetFileName(selectedNode.Parent.GrepResult.FileNameDisplayed));
- }
- else if (tvSearchResult.SelectedItem is FormattedGrepResult)
- {
- FormattedGrepResult result = (FormattedGrepResult)tvSearchResult.SelectedItem;
- Clipboard.SetText(System.IO.Path.GetFileName(result.GrepResult.FileNameDisplayed));
- }
- }
-
- private void tvSearchResult_MouseDown(object sender, MouseButtonEventArgs e)
- {
- TreeViewItem item = sender as TreeViewItem;
- if (item != null)
- {
- item.Focus();
- e.Handled = true;
- }
- }
-
- private void tvSearchResult_MouseDoubleClick(object sender, MouseButtonEventArgs e)
- {
- if (tvSearchResult.SelectedItem is FormattedGrepLine &&
- e.OriginalSource is TextBlock || e.OriginalSource is Run)
- {
- inputData.OpenFile(tvSearchResult.SelectedItem as FormattedGrepLine, GrepSettings.Instance.IsSet(GrepSettings.Key.CustomEditor));
- }
- }
-
- private void tvSearchResults_SelectedChanged(object sender, RoutedPropertyChangedEventArgs