diff --git a/Bld/_init.mak.lnx b/Bld/_init.mak.lnx
index e203117631..4adba00be8 100644
--- a/Bld/_init.mak.lnx
+++ b/Bld/_init.mak.lnx
@@ -62,24 +62,20 @@ include $(BUILD_ROOT)/Bld/_rule.mak.lnx
DEBUGPROCS_OBJ = $(OBJ_DIR)/$(BUILD_CONFIG)/$(DEBUGPROCS_NAME)
GENERIC_OBJ = $(OBJ_DIR)/$(BUILD_CONFIG)/$(GENERIC_NAME)
KERNEL_OBJ = $(OBJ_DIR)/$(BUILD_CONFIG)/$(KERNEL_NAME)
-LANGUAGE_OBJ= $(OBJ_DIR)/$(BUILD_CONFIG)/$(LANGUAGE_NAME)
APPCORE_OBJ= $(OBJ_DIR)/$(BUILD_CONFIG)/$(APPCORE_NAME)
TEXT_OBJ= $(OBJ_DIR)/$(BUILD_CONFIG)/$(TEXT_NAME)
CELLAR_OBJ= $(OBJ_DIR)/$(BUILD_CONFIG)/$(CELLAR_NAME)
GRENGINE_OBJ= $(OBJ_DIR)/$(BUILD_CONFIG)/$(GRENGINE_NAME)
VIEWS_OBJ= $(OBJ_DIR)/$(BUILD_CONFIG)/$(VIEWS_NAME)
-DBACCESS_OBJ= $(OBJ_DIR)/$(BUILD_CONFIG)/$(DBACCESS_NAME)
DEBUGPROCS_SRC = $(SRC)/$(DEBUGPROCS_NAME)
GENERIC_SRC = $(SRC)/$(GENERIC_NAME)
KERNEL_SRC = $(SRC)/$(KERNEL_NAME)
-LANGUAGE_SRC = $(SRC)/$(LANGUAGE_NAME)
APPCORE_SRC = $(SRC)/$(APPCORE_NAME)
TEXT_SRC = $(SRC)/$(TEXT_NAME)
CELLAR_SRC = $(SRC)/$(CELLAR_NAME)
GRENGINE_SRC = $(SRC)/Graphite/$(GRENGINE_NAME)
VIEWS_SRC = $(SRC)/$(VIEWS_NAME)
-DBACCESS_SRC = $(SRC)/$(DBACCESS_NAME)
# Include user specific settings
-include $(BUILD_ROOT)/Bld/_user.mak.lnx
diff --git a/Bld/_names.mak b/Bld/_names.mak
index 768ba7e8ac..29f296c3d0 100644
--- a/Bld/_names.mak
+++ b/Bld/_names.mak
@@ -7,7 +7,6 @@ KERNEL_NAME =Kernel
GENERIC_NAME =Generic
GRENGINE_NAME =GrEngine
FDO_NAME =FDO
-LANGUAGE_NAME =Language
FWRESOURCES_NAME =FwResources
TEXT_NAME =Text
VIEWS_NAME =views
diff --git a/Build/FwBuildTasks.dll b/Build/FwBuildTasks.dll
index 818bac80c7..6e526b4d95 100755
Binary files a/Build/FwBuildTasks.dll and b/Build/FwBuildTasks.dll differ
diff --git a/Build/Linux.targets b/Build/Linux.targets
index 568f025ffb..fe60c48b1c 100644
--- a/Build/Linux.targets
+++ b/Build/Linux.targets
@@ -8,7 +8,7 @@
-
-
-
-
+
+
@@ -161,7 +160,6 @@
-
@@ -233,4 +231,16 @@
SecondLine="8856396c-63a9-4bc7-ad47-87ec8b6ef5a4 libManagedComBridge.so"/>
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Build/RegFree.targets b/Build/RegFree.targets
index 88ee3c37c1..c3566f9801 100644
--- a/Build/RegFree.targets
+++ b/Build/RegFree.targets
@@ -7,17 +7,15 @@
This allows our programs to run without registering our COM DLLs, which in turn allows different
versions of FieldWorks to coexist on the same computer. This is only relevant for Windows.-->
-
-
-
-
+
+
+
-
-
+
+
diff --git a/Build/Src/FwBuildTasks/RegFree.cs b/Build/Src/FwBuildTasks/RegFree.cs
index 265507b971..26cb4af371 100644
--- a/Build/Src/FwBuildTasks/RegFree.cs
+++ b/Build/Src/FwBuildTasks/RegFree.cs
@@ -15,7 +15,8 @@
//
// ---------------------------------------------------------------------------------------------
using System;
-using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;
@@ -103,6 +104,12 @@ public RegFree()
/// ------------------------------------------------------------------------------------
public ITaskItem[] AsIs { get; set; }
+ ///
+ /// Gets or sets the dependent assemblies. Currently, this only accepts paths to assembly
+ /// manifests.
+ ///
+ public ITaskItem[] DependentAssemblies { get; set; }
+
private bool? m_IsAdmin;
private bool UserIsAdmin
{
@@ -128,7 +135,14 @@ public override bool Execute()
Log.LogMessage(MessageImportance.Normal, "RegFree processing {0}",
Path.GetFileName(Executable));
- var manifestFile = string.IsNullOrEmpty(Output) ? Executable + ".manifest" : Output;
+ StringCollection dllPaths = IdlImp.GetFilesFrom(Dlls);
+ if (dllPaths.Count == 0)
+ {
+ string ext = Path.GetExtension(Executable);
+ if (ext != null && ext.Equals(".dll", StringComparison.InvariantCultureIgnoreCase))
+ dllPaths.Add(Executable);
+ }
+ string manifestFile = string.IsNullOrEmpty(Output) ? Executable + ".manifest" : Output;
try
{
@@ -145,7 +159,6 @@ public override bool Execute()
{
regHelper.RedirectRegistry(!UserIsAdmin);
var creator = new RegFreeCreator(doc, Log);
- var dllPaths = IdlImp.GetFilesFrom(Dlls);
var filesToRemove = dllPaths.Cast().Where(fileName => !File.Exists(fileName)).ToList();
foreach (var file in filesToRemove)
dllPaths.Remove(file);
@@ -164,7 +177,23 @@ public override bool Execute()
}
}
- XmlElement root = creator.CreateExeInfo(Executable);
+ string assemblyName = Path.GetFileNameWithoutExtension(manifestFile);
+ Debug.Assert(assemblyName != null);
+ // The C++ test programs won't run if an assemblyIdentity element exists.
+ //if (assemblyName.StartsWith("test"))
+ // assemblyName = null;
+ string assemblyVersion = null;
+ try
+ {
+ assemblyVersion = FileVersionInfo.GetVersionInfo(Executable).FileVersion;
+ }
+ catch
+ {
+ // just ignore
+ }
+ if (string.IsNullOrEmpty(assemblyVersion))
+ assemblyVersion = "1.0.0.0";
+ XmlElement root = creator.CreateExeInfo(assemblyName, assemblyVersion);
foreach (string fileName in dllPaths)
{
if (NoTypeLib.Count(f => f.ItemSpec == fileName) != 0)
@@ -187,6 +216,12 @@ public override bool Execute()
creator.AddAsIs(root, fragmentName);
}
+ foreach (string assemblyFileName in IdlImp.GetFilesFrom(DependentAssemblies))
+ {
+ Log.LogMessage(MessageImportance.Low, "\tAdding dependent assembly {0}", Path.GetFileName(assemblyFileName));
+ creator.AddDependentAssembly(root, assemblyFileName);
+ }
+
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = false,
diff --git a/Build/Src/FwBuildTasks/RegFreeCreator.cs b/Build/Src/FwBuildTasks/RegFreeCreator.cs
index c0ed9527d0..d9c38133bc 100644
--- a/Build/Src/FwBuildTasks/RegFreeCreator.cs
+++ b/Build/Src/FwBuildTasks/RegFreeCreator.cs
@@ -17,6 +17,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
@@ -52,6 +53,7 @@ public class RegFreeCreator
private readonly Dictionary _interfaceProxies = new Dictionary();
private readonly Dictionary _tlbGuids = new Dictionary();
private readonly List _nonExistingServers = new List();
+ private readonly XmlNamespaceManager _nsManager;
private const string UrnSchema = "http://www.w3.org/2001/XMLSchema-instance";
private const string UrnAsmv1 = "urn:schemas-microsoft-com:asm.v1";
@@ -69,6 +71,7 @@ public class RegFreeCreator
public RegFreeCreator(XmlDocument doc)
{
_doc = doc;
+ _nsManager = CreateNamespaceManager(_doc);
}
/// ------------------------------------------------------------------------------------
@@ -76,29 +79,37 @@ public RegFreeCreator(XmlDocument doc)
/// Initializes a new instance of the class.
///
/// The XML document.
- /// set to true to display warnings, otherwise
- /// false.
+ ///
/// ------------------------------------------------------------------------------------
- public RegFreeCreator(XmlDocument doc, TaskLoggingHelper Log): this(doc)
+ public RegFreeCreator(XmlDocument doc, TaskLoggingHelper log): this(doc)
{
- this._log = Log;
+ _log = log;
}
#endregion
- /// ------------------------------------------------------------------------------------
- ///
- /// Creates the info for the executable. The info consist of:
- ///
- /// - name (from file name)
- /// - version info (from assembly)
- /// - type (hard coded as "win32" for now)
- ///
- /// This method also adds the root element with all necessary namespaces.
- ///
- /// pathname of the file.
- /// ------------------------------------------------------------------------------------
- public XmlElement CreateExeInfo(string pathName)
+ private static XmlNamespaceManager CreateNamespaceManager(XmlDocument doc)
+ {
+ var namespaceManager = new XmlNamespaceManager(doc.NameTable);
+ namespaceManager.AddNamespace("asmv1", UrnAsmv1);
+ namespaceManager.AddNamespace("asmv2", UrnAsmv2);
+ namespaceManager.AddNamespace("dsig", UrnDsig);
+ namespaceManager.AddNamespace("xsi", UrnSchema);
+ return namespaceManager;
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Creates the info for the executable. The info consist of:
+ ///
+ /// - name (from file name)
+ /// - version info (from assembly)
+ /// - type (hard coded as "win32" for now)
+ ///
+ /// This method also adds the root element with all necessary namespaces.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public XmlElement CreateExeInfo(string assemblyName, string assemblyVersion)
{
XmlElement elem = _doc.CreateElement("assembly", UrnAsmv1);
elem.SetAttribute("manifestVersion", "1.0");
@@ -108,33 +119,21 @@ public XmlElement CreateExeInfo(string pathName)
elem.SetAttribute("xmlns:xsi", UrnSchema);
elem.SetAttribute("schemaLocation", UrnSchema, UrnAsmv1 + " assembly.adaptive.xsd");
- XmlNode oldChild = _doc.SelectSingleNode("assembly");
+ XmlNode oldChild = _doc.SelectSingleNode("asmv1:assembly", _nsManager);
if (oldChild != null)
_doc.ReplaceChild(elem, oldChild);
else
_doc.AppendChild(elem);
- // The C++ test programs won't run if an assemblyIdentity element exists.
- string fileName = Path.GetFileName(pathName);
- if (!fileName.StartsWith("test"))
+ if (!string.IsNullOrEmpty(assemblyName))
{
//
XmlElement assemblyIdentity = _doc.CreateElement("assemblyIdentity", UrnAsmv1);
- assemblyIdentity.SetAttribute("name", fileName);
- // ReSharper disable EmptyGeneralCatchClause
- try
- {
- FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(pathName);
- assemblyIdentity.SetAttribute("version", versionInfo.FileVersion);
- }
- catch
- {
- // just ignore
- }
- // ReSharper restore EmptyGeneralCatchClause
+ assemblyIdentity.SetAttribute("name", assemblyName);
+ assemblyIdentity.SetAttribute("version", assemblyVersion);
assemblyIdentity.SetAttribute("type", "win32");
- oldChild = elem.SelectSingleNode("assemblyIdentity");
+ oldChild = elem.SelectSingleNode("asmv1:assemblyIdentity", _nsManager);
if (oldChild != null)
elem.ReplaceChild(assemblyIdentity, oldChild);
else
@@ -194,16 +193,16 @@ public void ProcessTypeLibrary(XmlElement parent, string fileName)
elem.SetAttribute("helpdir", string.Empty);
elem.SetAttribute("resourceid", "0");
elem.SetAttribute("flags", flags);
- oldChild = file.SelectSingleNode(string.Format("typelib[tlbid='{0}']",
- libAttr.guid.ToString("B")));
+ oldChild = file.SelectSingleNode(string.Format("asmv1:typelib[asmv1:tlbid='{0}']",
+ libAttr.guid.ToString("B")), _nsManager);
if (oldChild != null)
file.ReplaceChild(elem, oldChild);
else
file.AppendChild(elem);
}
- Debug.WriteLine(string.Format(@"typelib tlbid=""{0}"" version=""{1}.{2}"" helpdir="""" resourceid=""0"" flags=""{3}""",
- libAttr.guid, libAttr.wMajorVerNum, libAttr.wMinorVerNum, flags));
+ Debug.WriteLine(@"typelib tlbid=""{0}"" version=""{1}.{2}"" helpdir="""" resourceid=""0"" flags=""{3}""",
+ libAttr.guid, libAttr.wMajorVerNum, libAttr.wMinorVerNum, flags);
int count = typeLib.GetTypeInfoCount();
_log.LogMessage(MessageImportance.Low, "\t\tTypelib has {0} types", count);
@@ -215,8 +214,8 @@ public void ProcessTypeLibrary(XmlElement parent, string fileName)
ProcessTypeInfo(parent, libAttr.guid, typeInfo);
}
- oldChild = parent.SelectSingleNode(string.Format("file[name='{0}']",
- Path.GetFileName(fileName)));
+ oldChild = parent.SelectSingleNode(string.Format("asmv1:file[asmv1:name='{0}']",
+ Path.GetFileName(fileName)), _nsManager);
if (oldChild != null)
parent.ReplaceChild(file, oldChild);
else
@@ -258,7 +257,7 @@ private static string GetDefaultValueForKey(RegistryKey parentKey, string keyNam
/// ------------------------------------------------------------------------------------
public void ProcessClasses(XmlElement parent)
{
- using (var regKeyClsid = Registry.CurrentUser.OpenSubKey(Tasks.RegHelper.TmpRegistryKeyHKCR + @"\CLSID"))
+ using (var regKeyClsid = Registry.CurrentUser.OpenSubKey(RegHelper.TmpRegistryKeyHKCR + @"\CLSID"))
{
if (regKeyClsid == null)
{
@@ -274,7 +273,7 @@ public void ProcessClasses(XmlElement parent)
if (_coClasses.ContainsKey(clsId.ToLower()))
continue;
- using (var regKeyClass = regKeyClsid.OpenSubKey(clsId))
+ using (RegistryKey regKeyClass = regKeyClsid.OpenSubKey(clsId))
{
var className = (string)regKeyClass.GetValue(string.Empty, string.Empty);
using (var regKeyInProcServer = regKeyClass.OpenSubKey("InProcServer32"))
@@ -301,7 +300,7 @@ public void ProcessClasses(XmlElement parent)
/// ------------------------------------------------------------------------------------
public void ProcessInterfaces(XmlElement root)
{
- using (var regKeyBase = Registry.CurrentUser.OpenSubKey(Tasks.RegHelper.TmpRegistryKeyHKCR))
+ using (var regKeyBase = Registry.CurrentUser.OpenSubKey(RegHelper.TmpRegistryKeyHKCR))
using (var regKeyInterfaces = regKeyBase.OpenSubKey("Interface"))
{
if (regKeyInterfaces == null)
@@ -320,8 +319,7 @@ public void ProcessInterfaces(XmlElement root)
_log.LogError("no proxyStubClsid32 set for interface with iid {0}", interfaceIid);
continue;
}
- Debug.WriteLine(string.Format("Interface {0} is {1}: {2} methods, proxy: {3}", interfaceIid,
- interfaceName, numMethods, proxyStubClsId));
+ Debug.WriteLine("Interface {0} is {1}: {2} methods, proxy: {3}", interfaceIid, interfaceName, numMethods, proxyStubClsId);
if (!_coClasses.ContainsKey(proxyStubClsId))
{
@@ -357,21 +355,6 @@ public void ProcessInterfaces(XmlElement root)
}
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the child node. This is similar to XmlNode.SelectSingleNode which has the draw-
- /// back that it doesn't work "live".
- ///
- /// The parent node.
- /// Name of the child.
- /// The child node, or null if no child with name
- /// exists.
- /// ------------------------------------------------------------------------------------
- private static XmlNode GetChildNode(XmlNode parentNode, string childName)
- {
- return parentNode.ChildNodes.Cast().FirstOrDefault(child => child.Name == childName);
- }
-
/// ------------------------------------------------------------------------------------
///
/// Gets the child node with name which has an
@@ -478,6 +461,34 @@ public void AddAsIs(XmlElement parent, string fileName)
AddFragmentInternal(parent, fileName, null);
}
+ public void AddDependentAssembly(XmlElement parent, string fileName)
+ {
+ var depAsmElem = (XmlElement) parent.SelectSingleNode(string.Format("asmv1:dependency/asmv1:dependentAssembly[@asmv2:codebase = '{0}']", Path.GetFileName(fileName)), _nsManager);
+ if (depAsmElem == null)
+ {
+ var depElem = _doc.CreateElement("dependency", UrnAsmv1);
+ parent.AppendChild(depElem);
+ depAsmElem = _doc.CreateElement("dependentAssembly", UrnAsmv1);
+ depElem.AppendChild(depAsmElem);
+ depAsmElem.SetAttribute("codebase", UrnAsmv2, Path.GetFileName(fileName));
+ }
+ var asmIdElem = (XmlElement) depAsmElem.SelectSingleNode("asmv1:assemblyIdentity", _nsManager);
+ if (asmIdElem == null)
+ {
+ asmIdElem = _doc.CreateElement("assemblyIdentity", UrnAsmv1);
+ depAsmElem.AppendChild(asmIdElem);
+ }
+
+ var depAsmManifestDoc = new XmlDocument();
+ depAsmManifestDoc.Load(fileName);
+ var depAsmNsManager = CreateNamespaceManager(depAsmManifestDoc);
+ var manifestAsmIdElem = (XmlElement) depAsmManifestDoc.SelectSingleNode("/asmv1:assembly/asmv1:assemblyIdentity", depAsmNsManager);
+ Debug.Assert(manifestAsmIdElem != null);
+ asmIdElem.SetAttribute("name", manifestAsmIdElem.GetAttribute("name"));
+ asmIdElem.SetAttribute("version", manifestAsmIdElem.GetAttribute("version"));
+ asmIdElem.SetAttribute("type", manifestAsmIdElem.GetAttribute("type"));
+ }
+
/// ------------------------------------------------------------------------------------
///
/// Processes one type info. We get the necessary information from the type library
@@ -509,7 +520,7 @@ private void ProcessTypeInfo(XmlNode parent, Guid tlbGuid, ITypeInfo typeInfo)
// Try to get the file element for the server
var bldr = new StringBuilder(255);
- Tasks.RegHelper.GetLongPathName((string)inprocServer.GetValue(null), bldr, 255);
+ RegHelper.GetLongPathName((string)inprocServer.GetValue(null), bldr, 255);
string serverFullPath = bldr.ToString();
string server = Path.GetFileName(serverFullPath);
if (!File.Exists(serverFullPath) &&
@@ -595,6 +606,7 @@ private void AddOrReplaceCoClass(XmlElement parent, string clsId, string threadi
private XmlElement GetOrCreateFileNode(XmlNode parent, string filePath)
{
string fileName = Path.GetFileName(filePath);
+ Debug.Assert(fileName != null);
if (_files.ContainsKey(fileName))
return _files[fileName];
@@ -606,7 +618,7 @@ private XmlElement GetOrCreateFileNode(XmlNode parent, string filePath)
if (fileInfo.Exists)
{
parent.AppendChild(file);
- file.SetAttribute("size", "urn:schemas-microsoft-com:asm.v2", fileInfo.Length.ToString());
+ file.SetAttribute("size", "urn:schemas-microsoft-com:asm.v2", fileInfo.Length.ToString(CultureInfo.InvariantCulture));
}
_files.Add(fileName, file);
return file;
diff --git a/Build/Windows.targets b/Build/Windows.targets
index 8574610ea9..4eca312d03 100644
--- a/Build/Windows.targets
+++ b/Build/Windows.targets
@@ -2,10 +2,11 @@
+
+ DependsOnTargets="Initialize;EncConvertersDlls;CopyOtherDlls;BuildWindowsXslAssemblies">
@@ -99,5 +100,13 @@
-->
-
+
+
+ ..\Src\Transforms\Application
+ ..\Src\Transforms\Presentation
+
+
+
+
+
diff --git a/Build/mkall.targets b/Build/mkall.targets
index d1107df9a5..a06c25dc66 100644
--- a/Build/mkall.targets
+++ b/Build/mkall.targets
@@ -4,6 +4,7 @@
+
@@ -14,13 +15,13 @@
-
+
-
+
@@ -30,10 +31,10 @@
-
+
@@ -65,7 +66,7 @@
-
+
@@ -103,10 +103,12 @@
Configuration="$(config-capital)" Target="$(make-target)"
BuildRoot="$(fwrt)"
WorkingDirectory="$(fwrt)/Src/Graphite/GrEngine"/>
+
-
+
+
-
+
@@ -162,52 +164,7 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
+
@@ -288,12 +245,6 @@
-
http://build.palaso.org/guestAuth/repository/download/bt278/.lastSuccessful
http://build.palaso.org/guestAuth/repository/download/bt279/.lastSuccessful
+ https://protobuf-net.googlecode.com/files/protobuf-net%20r668.zip
+ https://drive.google.com/uc?export=download&id=
dll.mdb
pdb
@@ -402,6 +355,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -441,6 +408,15 @@
+
+
+
+
+
+
+
+
+
@@ -463,9 +439,6 @@
SkipUnchangedFiles="true" OverwriteReadOnlyFiles="true" Condition="'$(OS)'=='Windows_NT'"/>
-
-
@@ -475,15 +448,6 @@
SkipUnchangedFiles="true" OverwriteReadOnlyFiles="true" Condition="'$(OS)'=='Windows_NT'"/>
-
-
-
-
-
diff --git a/DistFiles/FormattedEditor.dll b/DistFiles/FormattedEditor.dll
deleted file mode 100644
index d52e4f82ae..0000000000
Binary files a/DistFiles/FormattedEditor.dll and /dev/null differ
diff --git a/DistFiles/HelpSystem.dll b/DistFiles/HelpSystem.dll
deleted file mode 100644
index 3c40d5e136..0000000000
Binary files a/DistFiles/HelpSystem.dll and /dev/null differ
diff --git a/DistFiles/HtmlEditor.dll b/DistFiles/HtmlEditor.dll
deleted file mode 100644
index 8711ce9338..0000000000
Binary files a/DistFiles/HtmlEditor.dll and /dev/null differ
diff --git a/DistFiles/Language Explorer/Configuration/Grammar/Edit/toolConfiguration.xml b/DistFiles/Language Explorer/Configuration/Grammar/Edit/toolConfiguration.xml
index 826d54ddeb..3e80dac5a3 100644
--- a/DistFiles/Language Explorer/Configuration/Grammar/Edit/toolConfiguration.xml
+++ b/DistFiles/Language Explorer/Configuration/Grammar/Edit/toolConfiguration.xml
@@ -401,7 +401,7 @@
-
+
@@ -419,7 +419,7 @@
-
+
diff --git a/DistFiles/Language Explorer/Transforms/XLingPaperForXXE.xsl b/DistFiles/Language Explorer/Export Templates/XLingPaperForXXE.xsl
similarity index 100%
rename from DistFiles/Language Explorer/Transforms/XLingPaperForXXE.xsl
rename to DistFiles/Language Explorer/Export Templates/XLingPaperForXXE.xsl
diff --git a/DistFiles/NetLoc.dll b/DistFiles/NetLoc.dll
deleted file mode 100644
index 32d9b148fe..0000000000
Binary files a/DistFiles/NetLoc.dll and /dev/null differ
diff --git a/DistFiles/ParatextShared.dll b/DistFiles/ParatextShared.dll
deleted file mode 100644
index f02882beaf..0000000000
Binary files a/DistFiles/ParatextShared.dll and /dev/null differ
diff --git a/DistFiles/Utilities.dll b/DistFiles/Utilities.dll
deleted file mode 100644
index 27c4ef21de..0000000000
Binary files a/DistFiles/Utilities.dll and /dev/null differ
diff --git a/Lib/debug/SIL.Collections.dll b/Lib/debug/SIL.Collections.dll
index 376a32c006..c810910247 100644
Binary files a/Lib/debug/SIL.Collections.dll and b/Lib/debug/SIL.Collections.dll differ
diff --git a/Lib/debug/SIL.Collections.pdb b/Lib/debug/SIL.Collections.pdb
index fc9634651b..9b94257cd1 100644
Binary files a/Lib/debug/SIL.Collections.pdb and b/Lib/debug/SIL.Collections.pdb differ
diff --git a/Lib/debug/SIL.Machine.dll b/Lib/debug/SIL.Machine.dll
index 704ad6aad6..c498f521df 100644
Binary files a/Lib/debug/SIL.Machine.dll and b/Lib/debug/SIL.Machine.dll differ
diff --git a/Lib/debug/SIL.Machine.pdb b/Lib/debug/SIL.Machine.pdb
index dc96f5e191..ce55ef491c 100644
Binary files a/Lib/debug/SIL.Machine.pdb and b/Lib/debug/SIL.Machine.pdb differ
diff --git a/Lib/linux/Common/FwKernelTlb.h b/Lib/linux/Common/FwKernelTlb.h
index 44bf793ce4..b2f4a07fd7 100644
--- a/Lib/linux/Common/FwKernelTlb.h
+++ b/Lib/linux/Common/FwKernelTlb.h
@@ -4,7 +4,7 @@
/* File created by MIDL compiler version 7.00.0555 */
-/* at Tue Sep 10 15:51:54 2013
+/* at Thu Jan 23 11:04:42 2014
*/
/* Compiler settings for C:\fwrepo\fw\Output\Common\FwKernelTlb.idl:
Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 7.00.0555
diff --git a/Lib/linux/Common/FwKernelTlb.idl b/Lib/linux/Common/FwKernelTlb.idl
index 63a8827ba3..9de379b284 100644
--- a/Lib/linux/Common/FwKernelTlb.idl
+++ b/Lib/linux/Common/FwKernelTlb.idl
@@ -10,7 +10,6 @@
-
import "oaidl.idl";
import "ocidl.idl";
import "objidl.idl";
@@ -79,7 +78,6 @@ import "objidl.idl";
-
cpp_quote("")
@@ -119,7 +117,7 @@ cpp_quote("// This is for code that uses a 64-bit integer for SilTime.")
cpp_quote("typedef __int64 SilTime;")
cpp_quote("#endif")
cpp_quote("")
-#line 18 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
+#line 17 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("F1EF76E0-BE04-11d3-8D9A-005004DEFEC4") cpp_quote(",") cpp_quote("FwKernelLib") cpp_quote(");") [ uuid(F1EF76E0-BE04-11d3-8D9A-005004DEFEC4), version(1.0), helpstring("FieldWorks Kernel") ] library FwKernelLib
{
@@ -137,7 +135,6 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("F1EF76E0-BE04-11d3-8D9A-0050
-
interface ITsString;
interface IUndoGrouper;
interface IFwMetaDataCache;
@@ -442,7 +439,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("6A46D810-7F14-4151-80F5-0B13
{
interface IActionHandler;
};
-#line 320 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
+#line 319 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
@@ -829,9 +826,9 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("24636FD1-DB8D-4b2c-B4C0-44C2
{
interface IDebugReport;
};
-#line 707 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
+#line 706 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
-#line 709 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
+#line 708 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
@@ -872,7 +869,7 @@ cpp_quote("GENERIC_DECLARE_SMART_INTERFACE_PTR(") cpp_quote("IUndoGrouper") cpp_
-#line 750 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
+#line 749 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
@@ -893,9 +890,9 @@ cpp_quote("GENERIC_DECLARE_SMART_INTERFACE_PTR(") cpp_quote("IComDisposable") cp
-#line 771 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
+#line 770 "c:\\fwrepo\\fw\\src\\kernel\\FwKernel.idh"
-#line 22 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
+#line 21 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
#line 1 "c:\\fwrepo\\fw\\src\\kernel\\TextServ.idh"
@@ -932,7 +929,6 @@ cpp_quote("GENERIC_DECLARE_SMART_INTERFACE_PTR(") cpp_quote("IComDisposable") cp
-
interface ITsString;
@@ -2373,11 +2369,10 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("7A1B89C0-C2D6-11d3-9BB7-0040
{
interface ITsMultiString;
};
-#line 1478 "c:\\fwrepo\\fw\\src\\kernel\\TextServ.idh"
-
-#line 23 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
- #line 1 "C:\\fwrepo\\fw\\src\\Language\\Render.idh"
+#line 1477 "c:\\fwrepo\\fw\\src\\kernel\\TextServ.idh"
+#line 22 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
+ #line 1 "c:\\fwrepo\\fw\\src\\kernel\\Render.idh"
@@ -2867,7 +2862,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("7A1B89C0-C2D6-11d3-9BB7-0040
{
interface IVwGraphicsWin32;
};
- #line 492 "C:\\fwrepo\\fw\\src\\Language\\Render.idh"
+ #line 491 "c:\\fwrepo\\fw\\src\\kernel\\Render.idh"
@@ -3020,7 +3015,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("7A1B89C0-C2D6-11d3-9BB7-0040
{
interface IVwJustifier;
};
- #line 645 "C:\\fwrepo\\fw\\src\\Language\\Render.idh"
+ #line 644 "c:\\fwrepo\\fw\\src\\kernel\\Render.idh"
@@ -3493,7 +3488,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("7A1B89C0-C2D6-11d3-9BB7-0040
{
interface IRenderEngine;
};
- #line 1118 "C:\\fwrepo\\fw\\src\\Language\\Render.idh"
+ #line 1117 "c:\\fwrepo\\fw\\src\\kernel\\Render.idh"
@@ -3579,8 +3574,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("7A1B89C0-C2D6-11d3-9BB7-0040
{
interface IJustifyingRenderer;
};
- #line 1204 "C:\\fwrepo\\fw\\src\\Language\\Render.idh"
-
+ #line 1203 "c:\\fwrepo\\fw\\src\\kernel\\Render.idh"
@@ -3627,11 +3621,11 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("7A1B89C0-C2D6-11d3-9BB7-0040
-#line 1252 "C:\\fwrepo\\fw\\src\\Language\\Render.idh"
-#line 24 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
- #line 1 "C:\\fwrepo\\fw\\src\\Language\\Language.idh"
+#line 1251 "c:\\fwrepo\\fw\\src\\kernel\\Render.idh"
+#line 23 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
+ #line 1 "c:\\fwrepo\\fw\\src\\kernel\\Language.idh"
@@ -5461,7 +5455,7 @@ cpp_quote("GENERIC_DECLARE_SMART_INTERFACE_PTR(") cpp_quote("IRegexMatcher") cpp
{
interface ILgIcuLocaleEnumerator;
};
-#line 1832 "C:\\fwrepo\\fw\\src\\Language\\Language.idh"
+#line 1831 "c:\\fwrepo\\fw\\src\\kernel\\Language.idh"
-#line 25 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
+#line 24 "C:\\fwrepo\\fw\\src\\Kernel\\FwKernelTlb.idl"
};
diff --git a/Lib/linux/Common/FwKernelTlb.tlb b/Lib/linux/Common/FwKernelTlb.tlb
index 3bcde46556..9fa1ed4a38 100644
Binary files a/Lib/linux/Common/FwKernelTlb.tlb and b/Lib/linux/Common/FwKernelTlb.tlb differ
diff --git a/Lib/linux/Common/ViewsTlb.h b/Lib/linux/Common/ViewsTlb.h
index a856b4b653..8c4da04eff 100644
--- a/Lib/linux/Common/ViewsTlb.h
+++ b/Lib/linux/Common/ViewsTlb.h
@@ -4,7 +4,7 @@
/* File created by MIDL compiler version 7.00.0555 */
-/* at Tue Sep 10 15:51:55 2013
+/* at Thu Jan 23 11:04:44 2014
*/
/* Compiler settings for C:\fwrepo\fw\Output\Common\ViewsTlb.idl:
Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 7.00.0555
diff --git a/Lib/linux/Common/ViewsTlb.idl b/Lib/linux/Common/ViewsTlb.idl
index bac77d9218..3a750a7838 100644
--- a/Lib/linux/Common/ViewsTlb.idl
+++ b/Lib/linux/Common/ViewsTlb.idl
@@ -13,7 +13,6 @@
-
import "oaidl.idl";
import "ocidl.idl";
import "objidl.idl";
@@ -82,7 +81,6 @@ import "objidl.idl";
-
cpp_quote("")
@@ -122,10 +120,10 @@ cpp_quote("// This is for code that uses a 64-bit integer for SilTime.")
cpp_quote("typedef __int64 SilTime;")
cpp_quote("#endif")
cpp_quote("")
-#line 21 "C:\\fwrepo\\fw\\Src\\Views\\ViewsTlb.idl"
+#line 20 "C:\\fwrepo\\fw\\Src\\Views\\ViewsTlb.idl"
cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000c0fb81b5") cpp_quote(",") cpp_quote("Views") cpp_quote(");") [ uuid(f6d10640-c00c-11d2-8078-0000c0fb81b5), version(1.0), helpstring("Views 1.0 Type Library") ] library Views
-#line 24 "C:\\fwrepo\\fw\\Src\\Views\\ViewsTlb.idl"
+#line 23 "C:\\fwrepo\\fw\\Src\\Views\\ViewsTlb.idl"
{
importlib("FwKernelTlb.tlb");
@@ -150,7 +148,6 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
-
@@ -1514,7 +1511,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
interface IVwCacheDa;
interface IStructuredTextDataAccess;
};
- #line 1385 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 1384 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -1728,7 +1725,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
-#line 1599 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+#line 1598 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -2530,7 +2527,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
{
interface IVwRootBox;
};
-#line 2401 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+#line 2400 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -4376,14 +4373,14 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
-#line 4247 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+#line 4246 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
};
cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("CCE2A7ED-464C-4ec7-A0B0-E3C1F6B94C5A") cpp_quote(",") cpp_quote("VwStylesheet") cpp_quote(");") [ uuid(CCE2A7ED-464C-4ec7-A0B0-E3C1F6B94C5A) ] coclass VwStylesheet
{
interface IVwStylesheet;
};
-#line 4254 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+#line 4253 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -4460,7 +4457,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
{
interface IVwPropertyStore;
};
- #line 4331 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 4330 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
typedef [v1_enum] enum VwOverlayFlags
@@ -4744,7 +4741,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
{
interface IVwOverlay;
};
- #line 4615 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 4614 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -4956,7 +4953,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
{
interface IVwPrintContext;
};
- #line 4827 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 4826 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -5267,7 +5264,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
{
interface IVwPattern;
};
- #line 5138 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 5137 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -5301,7 +5298,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
interface IVwTxtSrcInit2;
interface IVwTextSource;
};
- #line 5172 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 5171 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -5333,7 +5330,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
interface IVwTxtSrcInit;
interface IVwTextSource;
};
- #line 5204 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 5203 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -5375,7 +5372,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
{
interface IVwSearchKiller;
};
- #line 5246 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 5245 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -5455,7 +5452,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
{
interface IVwDrawRootBuffered;
};
- #line 5326 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 5325 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -5503,7 +5500,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("f6d10640-c00c-11d2-8078-0000
{
interface IVwSynchronizer;
};
- #line 5374 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 5373 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -5672,7 +5669,7 @@ cpp_quote("ATTACH_GUID_TO_CLASS(class,") cpp_quote("1CD09E06-6978-4969-A1FC-4627
{
interface IVwLayoutStream;
};
-#line 5543 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+#line 5542 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -5785,7 +5782,7 @@ cpp_quote("GENERIC_DECLARE_SMART_INTERFACE_PTR(") cpp_quote("IVwLayoutManager")
{
interface IPictureFactory;
};
-#line 5656 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+#line 5655 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
@@ -6019,7 +6016,7 @@ cpp_quote("GENERIC_DECLARE_SMART_INTERFACE_PTR(") cpp_quote("IVwLayoutManager")
{
interface IVwWindow;
};
- #line 5890 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
+ #line 5889 "c:\\fwrepo\\fw\\src\\views\\Views.idh"
typedef [v1_enum] enum VwMouseEvent
@@ -6088,6 +6085,6 @@ cpp_quote("GENERIC_DECLARE_SMART_INTERFACE_PTR(") cpp_quote("IViewInputMgr") cpp
HRESULT OnTextChange();
}
-#line 29 "C:\\fwrepo\\fw\\Src\\Views\\ViewsTlb.idl"
+#line 28 "C:\\fwrepo\\fw\\Src\\Views\\ViewsTlb.idl"
};
diff --git a/Lib/linux/Common/ViewsTlb.tlb b/Lib/linux/Common/ViewsTlb.tlb
index 0e8bd01012..3ea4c3e5ae 100644
Binary files a/Lib/linux/Common/ViewsTlb.tlb and b/Lib/linux/Common/ViewsTlb.tlb differ
diff --git a/Lib/linux/Common/idhfiles.MD5 b/Lib/linux/Common/idhfiles.MD5
index 3091832506..1ae0185143 100644
--- a/Lib/linux/Common/idhfiles.MD5
+++ b/Lib/linux/Common/idhfiles.MD5
@@ -1 +1 @@
-b1342b26fd1307740812278bc500d5dd
\ No newline at end of file
+326b264da2b700e4cccb0fdfd40269bd
\ No newline at end of file
diff --git a/Lib/release/SIL.Collections.dll b/Lib/release/SIL.Collections.dll
index bd76f6b4ec..6c6dd14eb7 100644
Binary files a/Lib/release/SIL.Collections.dll and b/Lib/release/SIL.Collections.dll differ
diff --git a/Lib/release/SIL.Collections.pdb b/Lib/release/SIL.Collections.pdb
index cbe3d291ac..6ffc217c7e 100644
Binary files a/Lib/release/SIL.Collections.pdb and b/Lib/release/SIL.Collections.pdb differ
diff --git a/Lib/release/SIL.Machine.dll b/Lib/release/SIL.Machine.dll
index a9da1ea30d..7cf3a7effd 100644
Binary files a/Lib/release/SIL.Machine.dll and b/Lib/release/SIL.Machine.dll differ
diff --git a/Lib/release/SIL.Machine.pdb b/Lib/release/SIL.Machine.pdb
index 37fe090cd4..8eddb57687 100644
Binary files a/Lib/release/SIL.Machine.pdb and b/Lib/release/SIL.Machine.pdb differ
diff --git a/Lib/src/Machine b/Lib/src/Machine
index a1165c9405..49a53b057a 160000
--- a/Lib/src/Machine
+++ b/Lib/src/Machine
@@ -1 +1 @@
-Subproject commit a1165c9405973d5c6bd4bc0d56a051f9d587f346
+Subproject commit 49a53b057aab5a2e67f86fb5bba7e377ccb5ab69
diff --git a/Src/AppCore/Makefile b/Src/AppCore/Makefile
index 6857f943e6..21651c4d83 100644
--- a/Src/AppCore/Makefile
+++ b/Src/AppCore/Makefile
@@ -13,7 +13,11 @@ BUILD_PRODUCT = $(APPCORE_NAME)
include $(BUILD_ROOT)/Bld/_init.mak.lnx
AFLIB_SRC = $(APPCORE_SRC)/AfLib
-CELLAR_SRC = $(SRC)/Cellar
+GRAPHITE_SRC = $(SRC)/Graphite
+GRFW_SRC = $(GRAPHITE_SRC)/FwOnly
+GRUTIL_LIB = $(GRAPHITE_SRC)/lib
+TTFUTIL_LIB = $(GRAPHITE_SRC)/TtfUtil
+VIEWS_LIB = $(VIEWS_SRC)/lib
PACKAGES = glib-2.0 gtk+-2.0 glibmm-2.4 gtkmm-2.4 cairomm-1.0
@@ -22,12 +26,12 @@ ifeq ($(BUILD_CONFIG),Debug)
DEFINES := $(DEFINES) -D_DEBUG
endif
-
# Make sure AfLib is first, as we want to get the Main.h from there,
# not any of the others (e.g., in Views)
INCLUDES := -I$(AFLIB_SRC) -I$(GENERIC_SRC) -I$(APPCORE_SRC) -I$(TEXT_SRC) -I$(DEBUGPROCS_SRC)
-INCLUDES := $(INCLUDES) -I$(KERNEL_SRC) -I$(DBACCESS_SRC)
+INCLUDES := $(INCLUDES) -I$(KERNEL_SRC)
+INCLUDES := $(INCLUDES) -I$(GRUTIL_LIB) -I$(TTFUTIL_LIB) -I$(VIEWS_SRC) -I$(VIEWS_LIB) -I$(GRFW_SRC)
INCLUDES := $(INCLUDES) \
-I$(FWINCLUDE) \
diff --git a/Src/Common/COMInterfaces/BuildInclude.targets b/Src/Common/COMInterfaces/BuildInclude.targets
index ff8fde0277..e1187676be 100644
--- a/Src/Common/COMInterfaces/BuildInclude.targets
+++ b/Src/Common/COMInterfaces/BuildInclude.targets
@@ -12,8 +12,8 @@
-
-
+
+
diff --git a/Src/Common/COMInterfaces/IcuWrappers.cs b/Src/Common/COMInterfaces/IcuWrappers.cs
index a473e10cd0..3e6633558e 100644
--- a/Src/Common/COMInterfaces/IcuWrappers.cs
+++ b/Src/Common/COMInterfaces/IcuWrappers.cs
@@ -14,8 +14,6 @@
using System.Globalization;
using System.Text;
using System.Windows.Forms;
-using Microsoft.Win32;
-
using SIL.Utils;
namespace SIL.FieldWorks.Common.COMInterfaces
@@ -132,8 +130,10 @@ private static bool IsInRange(string codepoint, CharacterRange[] rangesToCheck)
return false;
}
- private static readonly CharacterRange[] s_validCodepointRanges = new[] {
- new CharacterRange {Start = "0000", End = "10FFFD"} };
+ private static readonly CharacterRange[] s_validCodepointRanges =
+ {
+ new CharacterRange {Start = "0000", End = "10FFFD"}
+ };
/// ------------------------------------------------------------------------------------
///
@@ -147,11 +147,12 @@ public static bool IsValidCodepoint(string codepoint)
}
// List of the ranges that are acceptable
- private static readonly CharacterRange[] s_puaRanges = new[] {
- new CharacterRange { Start = "E000", End = "F8FF" },
- new CharacterRange { Start = "F0000", End = "FFFFD" },
- new CharacterRange { Start = "100000", End = "10FFFD" }
- };
+ private static readonly CharacterRange[] s_puaRanges =
+ {
+ new CharacterRange { Start = "E000", End = "F8FF" },
+ new CharacterRange { Start = "F0000", End = "FFFFD" },
+ new CharacterRange { Start = "100000", End = "10FFFD" }
+ };
/// ------------------------------------------------------------------------------------
///
@@ -174,11 +175,12 @@ public static bool IsPrivateUse(string codepoint)
// but that's not clear, so we're adding plane 16 as of September 15, 2005. If
// there's really a reason why plane 16 was not included here, remove it and
// document the reason!
- private static readonly CharacterRange[] s_customPuaRanges = new[] {
- new CharacterRange { Start = "E000", End = "EFFF" },
- new CharacterRange { Start = "F0000", End = "FFFFD" },
- new CharacterRange { Start = "100000", End = "10FFFD"}
- };
+ private static readonly CharacterRange[] s_customPuaRanges =
+ {
+ new CharacterRange { Start = "E000", End = "EFFF" },
+ new CharacterRange { Start = "F0000", End = "FFFFD" },
+ new CharacterRange { Start = "100000", End = "10FFFD"}
+ };
/// ------------------------------------------------------------------------------------
///
@@ -192,8 +194,10 @@ public static bool IsCustomUse(string codepoint)
}
// List of the ranges that are set aside for surrogates
- private static readonly CharacterRange[] s_surrogateRanges = new[] {
- new CharacterRange {Start = "D800", End = "DFFF"} };
+ private static readonly CharacterRange[] s_surrogateRanges =
+ {
+ new CharacterRange {Start = "D800", End = "DFFF"}
+ };
/// ------------------------------------------------------------------------------------
///
@@ -215,7 +219,7 @@ public static bool IsSurrogate(string codepoint)
/// ------------------------------------------------------------------------------------
public static void InitIcuDataDir()
{
- System.Diagnostics.Debug.Assert(kIcuVersion == "_50", "Yo developers! We are using a different version of ICU. " +
+ Debug.Assert(kIcuVersion == "_50", "Yo developers! We are using a different version of ICU. " +
"Change UnicodeVersion to return the correct version, and then change this assertion so that it checks for the new version of kIcuVersion." +
"We had to do it this way because ICU can't tell us which version of Unicode it supports. " +
"If they add a method to do this in the future, then we can just make UnicodeVersion work by calling that method." +
@@ -646,7 +650,7 @@ public static bool IsControl(int characterCode)
/// ------------------------------------------------------------------------------------
public static bool IsControl(string chr)
{
- return (string.IsNullOrEmpty(chr) || chr.Length != 1 ? false : IsControl(chr[0]));
+ return (!string.IsNullOrEmpty(chr) && chr.Length == 1 && IsControl(chr[0]));
}
/// ------------------------------------------------------------------------------------
@@ -687,7 +691,7 @@ public static bool IsSpace(int characterCode)
/// ------------------------------------------------------------------------------------
public static bool IsSpace(string chr)
{
- return (string.IsNullOrEmpty(chr) || chr.Length != 1 ? false : IsSpace(chr[0]));
+ return (!string.IsNullOrEmpty(chr) && chr.Length == 1 && IsSpace(chr[0]));
}
/// ------------------------------------------------------------------------------------
@@ -746,7 +750,7 @@ public static string GetCharName(int code)
string name;
UErrorCode error;
if (u_CharName(code, UCharNameChoice.U_UNICODE_CHAR_NAME, out name, out error) > 0 &&
- error == UErrorCode.U_ZERO_ERROR)
+ IsSuccess(error))
{
return name;
}
@@ -889,20 +893,14 @@ public static int GetLanguageCode(string localeID, out string language, out UErr
///
/// the locale to get the language code with
/// the language code for the locale.
- /// Thrown if ICU method fails with an error.
- ///
/// ------------------------------------------------------------------------------------
public static string GetLanguageCode(string locale)
{
string languageCode;
UErrorCode err;
GetLanguageCode(locale, out languageCode, out err);
- if (err != UErrorCode.U_ZERO_ERROR)
- {
- throw new ArgumentException(
- string.Format("ICU uloc_getLanguage with argument '{0}' failed with error {1}", locale, err),
- "locale");
- }
+ if (IsFailure(err))
+ throw new IcuException(string.Format("uloc_getLanguage() with argument '{0}' failed with error {1}", locale, err), err);
return languageCode;
}
@@ -998,20 +996,14 @@ public static int GetCountryCode(string localeID, out string country, out UError
///
/// the locale to get the country code with
/// The country code for the locale.
- /// Thrown if ICU method fails with an error.
- ///
/// ------------------------------------------------------------------------------------
public static string GetCountryCode(string locale)
{
string countryCode;
UErrorCode err;
GetCountryCode(locale, out countryCode, out err);
- if (err != UErrorCode.U_ZERO_ERROR)
- {
- throw new ArgumentException(
- string.Format("ICU uloc_getCountry with argument '{0}' failed with error {1}", locale, err),
- "locale");
- }
+ if (IsFailure(err))
+ throw new IcuException(string.Format("uloc_getCountry() with argument '{0}' failed with error {1}", locale, err), err);
return countryCode;
}
@@ -1138,7 +1130,7 @@ public static string GetDisplayName(string localeID)
string displayName;
UErrorCode uerr;
GetDisplayName(localeID, uilocale, out displayName, out uerr);
- if (uerr == UErrorCode.U_ZERO_ERROR)
+ if (IsSuccess(uerr))
return displayName;
return string.Empty;
}
@@ -1266,15 +1258,20 @@ private static extern int uloc_getName(string localeID, IntPtr name,
///
/// Gets the name of the locale (e.g. en_US).
///
- public static int GetName(string localeID, out string localeName, out UErrorCode err)
+ public static string GetName(string localeID)
{
+ if (string.IsNullOrEmpty(localeID))
+ return string.Empty;
+
const int nSize = 255;
IntPtr resPtr = Marshal.AllocCoTaskMem(nSize);
try
{
- int nResult = uloc_getName(localeID, resPtr, nSize, out err);
- localeName = Marshal.PtrToStringAnsi(resPtr);
- return nResult;
+ UErrorCode err;
+ uloc_getName(localeID, resPtr, nSize, out err);
+ if (IsFailure(err))
+ throw new IcuException("uloc_getName() failed with code " + err, err);
+ return Marshal.PtrToStringAnsi(resPtr);
}
finally
{
@@ -1324,18 +1321,17 @@ public static string ToLower(string src, string locale)
{
UErrorCode err;
int outLength = u_strToLower(resPtr, length, src, src.Length, locale, out err);
- if (err > 0 && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
- throw new Exception("Icu.ToLower() failed with code " + err);
+ if (IsFailure(err) && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
+ throw new IcuException("u_strToLower() failed with code " + err, err);
if (outLength > length)
{
- err = UErrorCode.U_ZERO_ERROR; // ignore possible U_BUFFER_OVERFLOW_ERROR
Marshal.FreeCoTaskMem(resPtr);
length = outLength + 1;
resPtr = Marshal.AllocCoTaskMem(length * 2);
u_strToLower(resPtr, length, src, src.Length, locale, out err);
}
- if (err > 0)
- throw new Exception("Icu.ToLower() failed with code " + err);
+ if (IsFailure(err))
+ throw new IcuException("u_strToLower() failed with code " + err, err);
string result = Marshal.PtrToStringUni(resPtr);
// Strip any garbage left over at the end of the string.
@@ -1360,13 +1356,17 @@ private static extern IntPtr ucol_open(
out UErrorCode err);
///
- public static IntPtr ucol_Open(byte[] loc, out UErrorCode err)
+ public static IntPtr OpenCollator(string locale)
{
- return ucol_open(loc, out err);
+ UErrorCode err;
+ IntPtr collator = ucol_open(string.IsNullOrEmpty(locale) ? null : Encoding.UTF8.GetBytes(locale), out err);
+ if (IsFailure(err))
+ throw new IcuException("ucol_open() failed with code " + err, err);
+ return collator;
}
///
- public static void ucol_Close(IntPtr collator)
+ public static void CloseCollator(IntPtr collator)
{
ucol_close(collator);
}
@@ -1379,9 +1379,25 @@ public static void ucol_Close(IntPtr collator)
private static extern int ucol_getSortKey(IntPtr col1, string source, int sourceLength, byte[] result, int resultLength);
///
- public static int ucol_GetSortKey(IntPtr col1, string source, int sourceLength, ref byte[] result, int resultLength)
+ public static byte[] GetSortKey(IntPtr collator, string source)
{
- return ucol_getSortKey(col1, source, sourceLength, result, resultLength);
+ const int keyLength = 1024;
+ var key = new byte[keyLength + 1];
+ var len = ucol_getSortKey(collator, source, source.Length, key, keyLength);
+ if (len > keyLength)
+ {
+ key = new byte[len + 1];
+ len = ucol_getSortKey(collator, source, source.Length, key, len);
+ }
+ // Ensure that the byte array is truncated to its actual data length.
+ Debug.Assert(len <= key.Length);
+ if (len < key.Length)
+ {
+ var result = new byte[len];
+ Array.Copy(key, result, len);
+ return result;
+ }
+ return key;
}
@@ -1424,21 +1440,20 @@ private static extern IntPtr ucol_openRules(string rules, int rulesLength, UColA
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void ucol_close(IntPtr coll);
- /// ------------------------------------------------------------------------------------
///
- /// Simple class to allow passing collation error info back to the caller of CheckRules.
+ /// Opens the specified collation rules as a collator.
///
- /// ------------------------------------------------------------------------------------
- public class CollationRuleErrorInfo
+ /// The rules.
+ ///
+ public static IntPtr OpenRuleBasedCollator(string rules)
{
- /// Line number (1-based) containing the error
- public int Line;
- /// Character offset (1-based) on Line where the error was detected
- public int Offset;
- /// Characters preceding the the error
- public String PreContext;
- /// Characters following the the error
- public String PostContext;
+ UErrorCode err;
+ UParseError parseError;
+ IntPtr collator = ucol_openRules(rules, rules.Length, UColAttributeValue.UCOL_DEFAULT,
+ UColAttributeValue.UCOL_DEFAULT_STRENGTH, out parseError, out err);
+ if (IsSuccess(err))
+ return collator;
+ throw new CollationRuleException(err, new CollationRuleErrorInfo(parseError));
}
/// ------------------------------------------------------------------------------------
@@ -1459,16 +1474,10 @@ public static CollationRuleErrorInfo CheckRules(string rules)
UColAttributeValue.UCOL_DEFAULT_STRENGTH, out parseError, out err);
try
{
- if (err == UErrorCode.U_ZERO_ERROR)
+ if (IsSuccess(err))
return null;
- return new CollationRuleErrorInfo
- {
- Line = parseError.line + 1,
- Offset = parseError.offset + 1,
- PreContext = parseError.preContext,
- PostContext = parseError.postContext
- };
+ return new CollationRuleErrorInfo(parseError);
}
finally
{
@@ -1545,17 +1554,33 @@ public static void GetSortKeyBound(byte[] sortKey, UColBoundMode boundType, ref
{
UErrorCode err;
int size = ucol_getBound(sortKey, sortKey.Length, boundType, 1, result, result.Length, out err);
- if (err > 0 && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
- throw new Exception("Icu.GetSortKeyBound() failed with code " + err);
+ if (IsFailure(err) && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
+ throw new IcuException("ucol_getBound() failed with code " + err, err);
if (size > result.Length)
{
result = new byte[size + 1];
ucol_getBound(sortKey, sortKey.Length, boundType, 1, result, result.Length, out err);
- if (err > 0)
- throw new Exception("Icu.GetSortKeyBound() failed with code " + err);
+ if (IsFailure(err))
+ throw new IcuException("ucol_getBound() failed with code " + err, err);
}
}
+ [DllImport(kIcuinDllName, EntryPoint = "ucol_strcoll" + kIcuVersion,
+ CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
+ private static extern int ucol_strcoll(IntPtr coll, string source, int sourceLength, string target, int targetLength);
+
+ ///
+ /// Compares strings using the specified collator.
+ ///
+ /// The collator.
+ /// The source.
+ /// The target.
+ ///
+ public static int Compare(IntPtr coll, string source, string target)
+ {
+ return ucol_strcoll(coll, source, source.Length, target, target.Length);
+ }
+
///
/// Convert the string to title case, using the convention of the specified locale.
/// This may be null for the universal locale, or "" for a 'root' locale (whatever that means).
@@ -1580,18 +1605,17 @@ public static string ToTitle(string src, string locale)
{
UErrorCode err;
int outLength = u_strToTitle(resPtr, length, src, src.Length, IntPtr.Zero, locale, out err);
- if (err > 0 && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
- throw new Exception("Icu.ToTitle() failed with code " + err);
+ if (IsFailure(err) && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
+ throw new IcuException("u_strToTitle() failed with code " + err, err);
if (outLength > length)
{
- err = UErrorCode.U_ZERO_ERROR; // ignore possible U_BUFFER_OVERFLOW_ERROR
Marshal.FreeCoTaskMem(resPtr);
length = outLength + 1;
resPtr = Marshal.AllocCoTaskMem(length * 2);
u_strToTitle(resPtr, length, src, src.Length, IntPtr.Zero, locale, out err);
}
- if (err > 0)
- throw new Exception("Icu.ToTitle() failed with code " + err);
+ if (IsFailure(err))
+ throw new IcuException("u_strToTitle() failed with code " + err, err);
string result = Marshal.PtrToStringUni(resPtr);
if (result != null)
@@ -1628,8 +1652,8 @@ public static string ToUpper(string src, string locale)
{
UErrorCode err;
int outLength = u_strToUpper(resPtr, length, src, src.Length, locale, out err);
- if (err > 0 && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
- throw new Exception("Icu.ToUpper() failed with code " + err);
+ if (IsFailure(err) && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
+ throw new IcuException("u_strToUpper() failed with code " + err, err);
if (outLength > length)
{
err = UErrorCode.U_ZERO_ERROR; // ignore possible U_BUFFER_OVERFLOW_ERROR
@@ -1638,8 +1662,8 @@ public static string ToUpper(string src, string locale)
resPtr = Marshal.AllocCoTaskMem(length * 2);
u_strToUpper(resPtr, length, src, src.Length, locale, out err);
}
- if (err > 0)
- throw new Exception("Icu.ToUpper() failed with code " + err);
+ if (IsFailure(err))
+ throw new IcuException("u_strToUpper() failed with code " + err, err);
string result = Marshal.PtrToStringUni(resPtr);
// Strip any garbage left over at the end of the string.
@@ -1712,8 +1736,8 @@ public static string Normalize(string src, UNormalizationMode mode)
{
UErrorCode err;
int outLength = unorm_normalize(src, src.Length, mode, 0, resPtr, length, out err);
- if (err > 0 && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
- throw new Exception("Icu.Normalize() failed with code " + err);
+ if (IsFailure(err) && err != UErrorCode.U_BUFFER_OVERFLOW_ERROR)
+ throw new IcuException("unorm_normalize() failed with code " + err, err);
if (outLength >= length)
{
err = UErrorCode.U_ZERO_ERROR; // ignore possible U_BUFFER_OVERFLOW_ERROR
@@ -1722,8 +1746,8 @@ public static string Normalize(string src, UNormalizationMode mode)
resPtr = Marshal.AllocCoTaskMem(length * 2);
unorm_normalize(src, src.Length, mode, 0, resPtr, length, out err);
}
- if (err > 0)
- throw new Exception("Icu.Normalize() failed with code " + err);
+ if (IsFailure(err))
+ throw new IcuException("unorm_normalize() failed with code " + err, err);
string result = Marshal.PtrToStringUni(resPtr);
// Strip any garbage left over at the end of the string.
@@ -1752,8 +1776,8 @@ public static bool IsNormalized(string src, UNormalizationMode mode)
UErrorCode err;
byte fIsNorm = unorm_isNormalize(src, src.Length, mode, out err);
- if (err > 0)
- throw new Exception("Icu.IsNormalized() failed with code " + err);
+ if (IsFailure(err))
+ throw new IcuException("unorm_isNormalize() failed with code " + err, err);
return fIsNorm != 0;
}
@@ -1867,8 +1891,8 @@ public static IEnumerable Split(UBreakIteratorType type, string locale,
UErrorCode err;
IntPtr bi = ubrk_open(type, locale, text, text.Length, out err);
- if (err > 0)
- throw new Exception("Icu.Split() failed with code " + err);
+ if (IsFailure(err))
+ throw new IcuException("ubrk_open() failed with code " + err, err);
var tokens = new List();
int cur = ubrk_first(bi);
while (cur != UBRK_DONE)
@@ -1885,6 +1909,16 @@ public static IEnumerable Split(UBreakIteratorType type, string locale,
#endregion Break iterator
+ private static bool IsSuccess(UErrorCode errorCode)
+ {
+ return errorCode <= 0;
+ }
+
+ private static bool IsFailure(UErrorCode errorCode)
+ {
+ return errorCode > 0;
+ }
+
/**
* Selector constants for u_charName().
* u_charName() returns the "modern" name of a
@@ -2564,4 +2598,84 @@ public enum UCharCategory
}
// JT notes on how to pass arguments
// const char *: pass string.
+
+
+ ///
+ /// General ICU exception
+ ///
+ public class IcuException : Exception
+ {
+ private readonly Icu.UErrorCode m_errorCode;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The message.
+ /// The error code.
+ public IcuException(string message, Icu.UErrorCode errorCode)
+ : base(message)
+ {
+ m_errorCode = errorCode;
+ }
+
+ ///
+ /// Gets the ICU error code.
+ ///
+ public Icu.UErrorCode ErrorCode
+ {
+ get { return m_errorCode; }
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Simple class to allow passing collation error info back to the caller of CheckRules.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public class CollationRuleErrorInfo
+ {
+ internal CollationRuleErrorInfo(Icu.UParseError parseError)
+ {
+ Line = parseError.line + 1;
+ Offset = parseError.offset + 1;
+ PreContext = parseError.preContext;
+ PostContext = parseError.postContext;
+ }
+
+ /// Line number (1-based) containing the error
+ public int Line { get; private set; }
+ /// Character offset (1-based) on Line where the error was detected
+ public int Offset { get; private set; }
+ /// Characters preceding the the error
+ public String PreContext { get; private set; }
+ /// Characters following the the error
+ public String PostContext { get; private set; }
+ }
+
+ ///
+ /// Collation rule exception
+ ///
+ public class CollationRuleException : IcuException
+ {
+ private readonly CollationRuleErrorInfo m_errorInfo;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The ICU error code.
+ /// The error information.
+ public CollationRuleException(Icu.UErrorCode errorCode, CollationRuleErrorInfo errorInfo)
+ : base("Failed to parse collation rules.", errorCode)
+ {
+ m_errorInfo = errorInfo;
+ }
+
+ ///
+ /// Gets the parse error information.
+ ///
+ public CollationRuleErrorInfo ErrorInfo
+ {
+ get { return m_errorInfo; }
+ }
+ }
}
diff --git a/Src/Common/Controls/DetailControls/BasicTypeSlices.cs b/Src/Common/Controls/DetailControls/BasicTypeSlices.cs
index 865eb5ce7e..7fd2471ab6 100644
--- a/Src/Common/Controls/DetailControls/BasicTypeSlices.cs
+++ b/Src/Common/Controls/DetailControls/BasicTypeSlices.cs
@@ -12,6 +12,7 @@
using System;
using System.Windows.Forms;
using System.Xml;
+using SIL.CoreImpl;
using SIL.FieldWorks.Common.Controls;
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.Application;
@@ -70,7 +71,6 @@ private void SetToggleValue(XmlNode node)
/// "reused" (e.g. refresh or new target object)
///
///
- ///
public override void Install(DataTree parent)
{
CheckDisposed();
@@ -378,7 +378,7 @@ protected override void Dispose(bool disposing)
protected override void UpdateDisplayFromDatabase()
{
RichTextBox rtb = ((RichTextBox)this.Control);
- DateTime dt = FwUtils.SilTime.GetTimeProperty(m_cache.DomainDataByFlid, Object.Hvo, m_flid);
+ DateTime dt = SilTime.GetTimeProperty(m_cache.DomainDataByFlid, Object.Hvo, m_flid);
if (dt == DateTime.MinValue)
{
rtb.Text = "Date/Time not set";
diff --git a/Src/Common/Controls/DetailControls/DataTree.cs b/Src/Common/Controls/DetailControls/DataTree.cs
index fdd72be826..99043d97cd 100644
--- a/Src/Common/Controls/DetailControls/DataTree.cs
+++ b/Src/Common/Controls/DetailControls/DataTree.cs
@@ -19,6 +19,7 @@
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
+using SIL.FieldWorks.Resources;
using SIL.Utils;
using XCore;
@@ -510,7 +511,7 @@ public FwStyleSheet StyleSheet
{
m_styleSheet = new FwStyleSheet();
m_styleSheet.Init(m_cache, m_cache.LanguageProject.Hvo,
- LangProjectTags.kflidStyles);
+ LangProjectTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
}
return m_styleSheet;
}
diff --git a/Src/Common/Controls/DetailControls/DetailControlsTests/DataTreeTests.cs b/Src/Common/Controls/DetailControls/DetailControlsTests/DataTreeTests.cs
index b9b757b84b..f9eca42b74 100644
--- a/Src/Common/Controls/DetailControls/DetailControlsTests/DataTreeTests.cs
+++ b/Src/Common/Controls/DetailControls/DetailControlsTests/DataTreeTests.cs
@@ -32,7 +32,7 @@ public class DataTreeTests : MemoryOnlyBackendProviderRestoredForEachTestTestBas
#region Fixture Setup and Teardown
internal static StringTable GenerateStringTable()
{
- string configurationDir = Path.Combine(DirectoryFinder.FWCodeDirectory,
+ string configurationDir = Path.Combine(FwDirectoryFinder.CodeDirectory,
@"Language Explorer/Configuration");
var stringTable = new SIL.Utils.StringTable(configurationDir);
@@ -41,7 +41,7 @@ internal static StringTable GenerateStringTable()
internal static Inventory GenerateParts()
{
- string partDirectory = Path.Combine(DirectoryFinder.FwSourceDirectory,
+ string partDirectory = Path.Combine(FwDirectoryFinder.SourceDirectory,
@"Common/Controls/DetailControls/DetailControlsTests");
var keyAttrs = new Dictionary();
@@ -55,7 +55,7 @@ internal static Inventory GenerateParts()
internal static Inventory GenerateLayouts()
{
- string partDirectory = Path.Combine(DirectoryFinder.FwSourceDirectory,
+ string partDirectory = Path.Combine(FwDirectoryFinder.SourceDirectory,
@"Common/Controls/DetailControls/DetailControlsTests");
Dictionary keyAttrs = new Dictionary();
diff --git a/Src/Common/Controls/DetailControls/DetailControlsTests/DetailControlsMainWnd.cs b/Src/Common/Controls/DetailControls/DetailControlsTests/DetailControlsMainWnd.cs
index 39abfb8da5..d60a105543 100644
--- a/Src/Common/Controls/DetailControls/DetailControlsTests/DetailControlsMainWnd.cs
+++ b/Src/Common/Controls/DetailControls/DetailControlsTests/DetailControlsMainWnd.cs
@@ -159,7 +159,7 @@ public void InitAndShowClient()
m_dataEntryForm = new DataTree();
SuspendLayout();
- string partDirectory = Path.Combine(DirectoryFinder.FWCodeDirectory,
+ string partDirectory = Path.Combine(FwDirectoryFinder.CodeDirectory,
@"Language Explorer\Configuration\Parts");
Dictionary keyAttrs = new Dictionary();
keyAttrs["layout"] = new string[] {"class", "type", "mode", "name" };
diff --git a/Src/Common/Controls/DetailControls/GenDateChooserDlg.cs b/Src/Common/Controls/DetailControls/GenDateChooserDlg.cs
index 93a977c99f..5291471bf5 100644
--- a/Src/Common/Controls/DetailControls/GenDateChooserDlg.cs
+++ b/Src/Common/Controls/DetailControls/GenDateChooserDlg.cs
@@ -3,7 +3,7 @@
using System.Linq;
using System.Text;
using System.Windows.Forms;
-
+using SIL.CoreImpl;
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.Common.Framework.DetailControls.Resources;
using SIL.FieldWorks.Common.FwUtils;
diff --git a/Src/Common/Controls/DetailControls/GenDateLauncher.cs b/Src/Common/Controls/DetailControls/GenDateLauncher.cs
index 63e2a0f3d0..c4b22734c1 100644
--- a/Src/Common/Controls/DetailControls/GenDateLauncher.cs
+++ b/Src/Common/Controls/DetailControls/GenDateLauncher.cs
@@ -3,7 +3,7 @@
using System.Linq;
using System.Text;
using System.Windows.Forms;
-
+using SIL.CoreImpl;
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.Application;
using SIL.FieldWorks.FDO.Infrastructure;
diff --git a/Src/Common/Controls/DetailControls/PossibilityAutoComplete.cs b/Src/Common/Controls/DetailControls/PossibilityAutoComplete.cs
index d52f6505e4..644e8e28c7 100644
--- a/Src/Common/Controls/DetailControls/PossibilityAutoComplete.cs
+++ b/Src/Common/Controls/DetailControls/PossibilityAutoComplete.cs
@@ -2,9 +2,9 @@
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
+using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.Common.Controls;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.Widgets;
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.DomainServices;
diff --git a/Src/Common/Controls/DetailControls/SliceFactory.cs b/Src/Common/Controls/DetailControls/SliceFactory.cs
index 92dd4456eb..7ea86dcada 100644
--- a/Src/Common/Controls/DetailControls/SliceFactory.cs
+++ b/Src/Common/Controls/DetailControls/SliceFactory.cs
@@ -230,7 +230,7 @@ public static Slice Create(FdoCache cache, string editor, int flid, XmlNode node
{
try
{
- slice = new ImageSlice(DirectoryFinder.FWCodeDirectory, XmlUtils.GetManditoryAttributeValue(node, "param1"));
+ slice = new ImageSlice(FwDirectoryFinder.CodeDirectory, XmlUtils.GetManditoryAttributeValue(node, "param1"));
}
catch (Exception error)
{
@@ -379,7 +379,7 @@ public static Slice Create(FdoCache cache, string editor, int flid, XmlNode node
//Since the editor has not been implemented yet,
//is there a bitmap file that we can show for this editor?
//Such bitmaps belong in the distFiles xde directory
- string fwCodeDir = DirectoryFinder.FWCodeDirectory;
+ string fwCodeDir = FwDirectoryFinder.CodeDirectory;
string editorBitmapRelativePath = "xde/" + editor + ".bmp";
if(File.Exists(Path.Combine(fwCodeDir, editorBitmapRelativePath)))
slice = new ImageSlice(fwCodeDir, editorBitmapRelativePath);
diff --git a/Src/Common/Controls/DetailControls/StringSlice.cs b/Src/Common/Controls/DetailControls/StringSlice.cs
index f366509aa8..ff8ac8ba6d 100644
--- a/Src/Common/Controls/DetailControls/StringSlice.cs
+++ b/Src/Common/Controls/DetailControls/StringSlice.cs
@@ -263,7 +263,7 @@ private ITsString NameOfWs(int ws)
m_wsLabel = ws;
var sWs = m_cache.WritingSystemFactory.GetStrFromWs(ws);
IWritingSystem wsys;
- WritingSystemServices.FindOrCreateWritingSystem(m_cache, sWs, false, false, out wsys);
+ WritingSystemServices.FindOrCreateWritingSystem(m_cache, FwDirectoryFinder.TemplateDirectory, sWs, false, false, out wsys);
var result = wsys.Abbreviation;
if (string.IsNullOrEmpty(result))
result = "??";
diff --git a/Src/Common/Controls/FwControls/FilterAllTextsDialog.cs b/Src/Common/Controls/FwControls/FilterAllTextsDialog.cs
index ea42796943..879cd8cc1f 100644
--- a/Src/Common/Controls/FwControls/FilterAllTextsDialog.cs
+++ b/Src/Common/Controls/FwControls/FilterAllTextsDialog.cs
@@ -253,9 +253,9 @@ protected override void OnHandleCreated(EventArgs e)
{
// Selecting node(s) changed something, so save it so that the UI doesn't become
// unresponsive
- using (var progressDlg = new ProgressDialogWithTask(this, m_cache.ThreadHelper))
+ using (var progressDlg = new ProgressDialogWithTask(this))
{
- progressDlg.ProgressBarStyle = ProgressBarStyle.Marquee;
+ progressDlg.IsIndeterminate = true;
progressDlg.Title = Text;
progressDlg.Message = ResourceHelper.GetResourceString("kstidSavingChanges");
progressDlg.RunTask((progDlg, parms) =>
@@ -276,7 +276,7 @@ protected override void OnHandleCreated(EventArgs e)
///
///
/// ------------------------------------------------------------------------------------
- protected override void m_btnHelp_Click(object sender, System.EventArgs e)
+ protected override void m_btnHelp_Click(object sender, EventArgs e)
{
ShowHelp.ShowHelpTopic(m_helpTopicProvider, m_helpTopicId);
}
diff --git a/Src/Common/Controls/FwControls/FwControls.csproj b/Src/Common/Controls/FwControls/FwControls.csproj
index 6823a44abe..4df5638cd6 100644
--- a/Src/Common/Controls/FwControls/FwControls.csproj
+++ b/Src/Common/Controls/FwControls/FwControls.csproj
@@ -95,11 +95,23 @@
False
+
+ False
+ ..\..\..\..\Output\Debug\FwUtils.dll
+
False
..\..\..\..\Output\Debug\ManagedLgIcuCollator.dll
+
+ False
+ ..\..\..\..\Output\Debug\ParatextShared.dll
+
+
+ False
+ ..\..\..\..\Output\Debug\ScriptureUtils.dll
+
System
@@ -127,18 +139,12 @@
..\..\..\..\Output\Debug\FwResources.dll
-
- ..\..\..\..\Output\Debug\FwUtils.dll
-
..\..\..\..\Output\Debug\SilUtils.dll
..\..\..\..\Downloads\Palaso.dll
-
- ..\..\..\..\DistFiles\ParatextShared.dll
-
..\..\..\..\Output\Debug\ScrUtilsInterfaces.dll
diff --git a/Src/Common/Controls/FwControls/FwControlsTests/ProgressDlgTests.cs b/Src/Common/Controls/FwControls/FwControlsTests/ProgressDlgTests.cs
index 8769ce4bda..80cbdb1270 100644
--- a/Src/Common/Controls/FwControls/FwControlsTests/ProgressDlgTests.cs
+++ b/Src/Common/Controls/FwControls/FwControlsTests/ProgressDlgTests.cs
@@ -5,10 +5,10 @@
// File: ProgressDlgTests.cs
using System;
+using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using NUnit.Framework;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
@@ -27,21 +27,11 @@ public class DummyProgressDlg : ProgressDialogWithTask
/// Initializes a new instance of the class.
///
/// ------------------------------------------------------------------------------------
- public DummyProgressDlg() : base(null, new ThreadHelper())
+ public DummyProgressDlg(ISynchronizeInvoke synchronizeInvoke)
+ : base(synchronizeInvoke)
{
}
- ///
- protected override void Dispose(bool disposing)
- {
- if (disposing && !IsDisposed)
- {
- if (ThreadHelper != null)
- ThreadHelper.Dispose();
- }
- base.Dispose(disposing);
- }
-
/// ------------------------------------------------------------------------------------
///
/// Gets a value indicating wether or not the cancel button is visible.
@@ -79,6 +69,7 @@ public void SimulatePressCancel()
Justification="Unit test, object is disposed in TearDown method")]
public class ProgressDlgTests : BaseTest
{
+ private ThreadHelper m_threadHelper;
private DummyProgressDlg m_dlg;
private Timer m_timer;
@@ -92,7 +83,8 @@ public class ProgressDlgTests : BaseTest
Justification="Unit test, object is disposed in TearDown method")]
public void Setup()
{
- m_dlg = new DummyProgressDlg {Maximum = 10};
+ m_threadHelper = new ThreadHelper();
+ m_dlg = new DummyProgressDlg(m_threadHelper) {Maximum = 10};
}
/// ------------------------------------------------------------------------------------
@@ -115,6 +107,12 @@ public void Teardown()
m_dlg = null;
}
+ if (m_threadHelper != null)
+ {
+ m_threadHelper.Dispose();
+ m_threadHelper = null;
+ }
+
}
/// ------------------------------------------------------------------------------------
@@ -175,7 +173,7 @@ private static object BackgroundTask(IThreadedProgress progressDlg, object[] par
///
/// ------------------------------------------------------------------------------------
[Test]
- [Category("DesktopRequired")]
+ [NUnit.Framework.Category("DesktopRequired")]
public void TestWithCancel()
{
StartTimer(2500);
@@ -193,7 +191,7 @@ public void TestWithCancel()
///
/// ------------------------------------------------------------------------------------
[Test]
- [Category("DesktopRequired")]
+ [NUnit.Framework.Category("DesktopRequired")]
public void TestWithoutCancel()
{
var nProgress = (int) m_dlg.RunTask(false, BackgroundTask);
diff --git a/Src/Common/Controls/FwControls/ObtainProjectMethod.cs b/Src/Common/Controls/FwControls/ObtainProjectMethod.cs
index 60989ec91b..fdfd858bcf 100644
--- a/Src/Common/Controls/FwControls/ObtainProjectMethod.cs
+++ b/Src/Common/Controls/FwControls/ObtainProjectMethod.cs
@@ -1,4 +1,5 @@
using System.Collections.Generic;
+using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
@@ -25,12 +26,11 @@ public static class ObtainProjectMethod
/// The repo may be a lift or full FW repo, but it can be from any source source, as long as the code can create an FW project from it.
///
/// Null if the operation was cancelled or otherwise did not work. The full pathname of an fwdata file, if it did work.
- public static string ObtainProjectFromAnySource(Form parent, IHelpTopicProvider helpTopicProvider,
- out ObtainedProjectType obtainedProjectType)
+ public static string ObtainProjectFromAnySource(Form parent, IHelpTopicProvider helpTopicProvider, out ObtainedProjectType obtainedProjectType)
{
bool dummy;
string fwdataFileFullPathname;
- var success = FLExBridgeHelper.LaunchFieldworksBridge(DirectoryFinder.ProjectsDirectory, null, FLExBridgeHelper.Obtain, null,
+ var success = FLExBridgeHelper.LaunchFieldworksBridge(FwDirectoryFinder.ProjectsDirectory, null, FLExBridgeHelper.Obtain, null,
FDOBackendProvider.ModelVersion, "0.13", null, out dummy, out fwdataFileFullPathname);
if (!success)
{
@@ -95,34 +95,25 @@ private static string CreateProjectFromLift(Form parent, IHelpTopicProvider help
var anthroListFile = ReflectionHelper.CallStaticMethod(@"FwCoreDlgs.dll", @"SIL.FieldWorks.FwCoreDlgs.FwCheckAnthroListDlg",
@"PickAnthroList", parent, null, helpTopicProvider);
- // Do NOT dispose of the thread helper until we dispose of the cache...
- // CreateProjectTask makes it the thread helper of the FdoCache that it creates and returns,
- // and we must NOT dispose of the cache's thread helper until after we import the lexicon.
- // We will actually dispose it twice, most likely, since disposing the cache will dispose it;
- // but this is harmless.
- using (var helper = new ThreadHelper())
+ using (var progressDlg = new ProgressDialogWithTask(parent))
{
- using (var progressDlg = new ProgressDialogWithTask(parent, helper))
- {
- progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous;
- progressDlg.Title = FwControls.ksCreatingLiftProject;
- var cacheReceiver = new FdoCache[1]; // a clumsy way of handling an out parameter, consistent with RunTask
- projectPath = (string)progressDlg.RunTask(true, CreateProjectTask,
- new object[] { liftPath, helper, anthroListFile, cacheReceiver });
- cache = cacheReceiver[0];
- }
+ progressDlg.Title = FwControls.ksCreatingLiftProject;
+ var cacheReceiver = new FdoCache[1]; // a clumsy way of handling an out parameter, consistent with RunTask
+ projectPath = (string)progressDlg.RunTask(true, CreateProjectTask,
+ new[] { liftPath, parent, anthroListFile, cacheReceiver });
+ cache = cacheReceiver[0];
+ }
- // this is a horrible way to invoke this, but the current project organization does not allow us to reference
- // the LexEdDll project, nor is there any straightforward way to move the code we need into some project we can
- // reference, or any obviously suitable project to move it to without creating other References loops.
- // One nasty reflection call seems less technical debt than creating an otherwise unnecessary project.
- // (It puts up its own progress dialog.)
- ReflectionHelper.CallStaticMethod(@"LexEdDll.dll", @"SIL.FieldWorks.XWorks.LexEd.FLExBridgeListener",
- @"ImportObtainedLexicon", cache, liftPath, parent);
+ // this is a horrible way to invoke this, but the current project organization does not allow us to reference
+ // the LexEdDll project, nor is there any straightforward way to move the code we need into some project we can
+ // reference, or any obviously suitable project to move it to without creating other References loops.
+ // One nasty reflection call seems less technical debt than creating an otherwise unnecessary project.
+ // (It puts up its own progress dialog.)
+ ReflectionHelper.CallStaticMethod(@"LexEdDll.dll", @"SIL.FieldWorks.XWorks.LexEd.FLExBridgeListener",
+ @"ImportObtainedLexicon", cache, liftPath, parent);
- ProjectLockingService.UnlockCurrentProject(cache); // finish all saves and completely write the file so we can proceed to open it
- cache.Dispose();
- }
+ ProjectLockingService.UnlockCurrentProject(cache); // finish all saves and completely write the file so we can proceed to open it
+ cache.Dispose();
return projectPath;
}
@@ -137,21 +128,21 @@ private static string CreateProjectFromLift(Form parent, IHelpTopicProvider help
private static object CreateProjectTask(IThreadedProgress progress, object[] parameters)
{
// Get required parameters. Ideally these would just be the signature of the method, but RunTask requires object[].
- var liftPathname = (string)parameters[0];
- var helper = (ThreadHelper)parameters[1];
- var anthroFile = (string)parameters[2];
- var cacheReceiver = (FdoCache[])parameters[3];
+ var liftPathname = (string) parameters[0];
+ var synchronizeInvoke = (ISynchronizeInvoke) parameters[1];
+ var anthroFile = (string) parameters[2];
+ var cacheReceiver = (FdoCache[]) parameters[3];
IWritingSystem wsVern, wsAnalysis;
RetrieveDefaultWritingSystemsFromLift(liftPathname, out wsVern, out wsAnalysis);
string projectPath = FdoCache.CreateNewLangProj(progress,
Directory.GetParent(Path.GetDirectoryName(liftPathname)).Parent.Name, // Get the new Flex project name from the Lift pathname.
- helper, wsAnalysis, wsVern, null, null, null, anthroFile);
+ FwDirectoryFinder.FdoDirectories, synchronizeInvoke, wsAnalysis, wsVern, null, null, null, anthroFile);
// This is a temporary cache, just to do the import, and AFAIK we have no access to the current
// user WS. So create it as "English". Put it in the array to return to the caller.
- cacheReceiver[0] = FdoCache.CreateCacheFromLocalProjectFile(projectPath, "en", progress);
+ cacheReceiver[0] = FdoCache.CreateCacheFromLocalProjectFile(projectPath, "en", new SilentFdoUI(synchronizeInvoke), FwDirectoryFinder.FdoDirectories, progress);
return projectPath;
}
@@ -163,8 +154,7 @@ private static void RetrieveDefaultWritingSystemsFromLift(string liftPath, out I
string vernWsId, analysisWsId;
using (var reader = XmlReader.Create(liftReader))
RetrieveDefaultWritingSystemIdsFromLift(reader, out vernWsId, out analysisWsId);
- var wsManager = new PalasoWritingSystemManager(
- new GlobalFileWritingSystemStore(DirectoryFinder.GlobalWritingSystemStoreDirectory));
+ var wsManager = new PalasoWritingSystemManager(new GlobalFileWritingSystemStore());
wsManager.GetOrSet(vernWsId, out wsVern);
wsManager.GetOrSet(analysisWsId, out wsAnalysis);
}
diff --git a/Src/Common/Controls/FwControls/ProgressDialogImpl.Designer.cs b/Src/Common/Controls/FwControls/ProgressDialogImpl.Designer.cs
index 264bb1968e..76919f0a7c 100644
--- a/Src/Common/Controls/FwControls/ProgressDialogImpl.Designer.cs
+++ b/Src/Common/Controls/FwControls/ProgressDialogImpl.Designer.cs
@@ -49,29 +49,30 @@ private void InitializeComponent()
this.progressBar = new System.Windows.Forms.ProgressBar();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
- //
+ //
// lblStatusMessage
- //
+ //
this.lblStatusMessage.AutoEllipsis = true;
resources.ApplyResources(this.lblStatusMessage, "lblStatusMessage");
this.lblStatusMessage.Name = "lblStatusMessage";
- //
+ //
// progressBar
- //
+ //
resources.ApplyResources(this.progressBar, "progressBar");
this.progressBar.Name = "progressBar";
this.progressBar.Step = 1;
- //
+ this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
+ //
// btnCancel
- //
+ //
this.btnCancel.Cursor = System.Windows.Forms.Cursors.Arrow;
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
- //
+ //
// ProgressDialogImpl
- //
+ //
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
diff --git a/Src/Common/Controls/FwControls/ProgressDialogImpl.cs b/Src/Common/Controls/FwControls/ProgressDialogImpl.cs
index 5a2acafd1c..bea351d6dc 100644
--- a/Src/Common/Controls/FwControls/ProgressDialogImpl.cs
+++ b/Src/Common/Controls/FwControls/ProgressDialogImpl.cs
@@ -274,6 +274,15 @@ public string CancelButtonText
}
}
+ ///
+ /// Gets an object to be used for ensuring that required tasks are invoked on the main
+ /// UI thread.
+ ///
+ public ISynchronizeInvoke SynchronizeInvoke
+ {
+ get { return this; }
+ }
+
/// ------------------------------------------------------------------------------------
///
/// Gets the form displaying the progress (used for message box owners, etc).
@@ -284,15 +293,13 @@ public Form Form
get { return this; }
}
- /// ------------------------------------------------------------------------------------
///
- /// Gets or sets the style of the ProgressBar.
+ /// Gets or sets a value indicating whether this progress is indeterminate.
///
- /// ------------------------------------------------------------------------------------
- public ProgressBarStyle ProgressBarStyle
+ public bool IsIndeterminate
{
- get { return progressBar.Style; }
- set { progressBar.Style = value; }
+ get { return progressBar.Style == ProgressBarStyle.Marquee; }
+ set { progressBar.Style = value ? ProgressBarStyle.Marquee : ProgressBarStyle.Continuous; }
}
#endregion
diff --git a/Src/Common/Controls/FwControls/ProgressDialogImpl.resx b/Src/Common/Controls/FwControls/ProgressDialogImpl.resx
index 136760a418..3e83cd4d6c 100644
--- a/Src/Common/Controls/FwControls/ProgressDialogImpl.resx
+++ b/Src/Common/Controls/FwControls/ProgressDialogImpl.resx
@@ -1,231 +1,231 @@
-
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- text/microsoft-resx
+ text/microsoft-resx
- 2.0
+ 2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
+
- NoControl
+ NoControl
-
+
- 15, 12
+ 15, 12
- 388, 13
+ 388, 13
-
+
- 5
+ 5
- #
+ #
- lblStatusMessage
+ lblStatusMessage
- System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- $this
+ $this
- 0
+ 0
- Top, Left, Right
+ Top, Left, Right
- NoControl
+ NoControl
- 15, 32
+ 15, 32
- 388, 20
+ 388, 20
- 4
+ 4
- progressBar
+ progressBar
- System.Windows.Forms.ProgressBar, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Windows.Forms.ProgressBar, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- $this
+ $this
- 1
+ 1
- System
+ System
- NoControl
+ NoControl
- 145, 68
+ 145, 68
- 133, 23
+ 133, 23
- 3
+ 3
- Cancel
+ Cancel
- btnCancel
+ btnCancel
- System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- $this
+ $this
- 2
+ 2
-
- True
+
+ True
- ProgressDialogImp
+ ProgressDialogImp
- 6, 13
+ 6, 13
- 422, 102
+ 422, 102
- Manual
+ Manual
- Progress Dialog
+ Progress Dialog
- ProgressDialogImpl
+ ProgressDialogImpl
- System.Windows.Forms.Form, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Windows.Forms.Form, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
\ No newline at end of file
diff --git a/Src/Common/Controls/FwControls/ProgressDialogWithTask.cs b/Src/Common/Controls/FwControls/ProgressDialogWithTask.cs
index 77de1546f0..8a536192f5 100644
--- a/Src/Common/Controls/FwControls/ProgressDialogWithTask.cs
+++ b/Src/Common/Controls/FwControls/ProgressDialogWithTask.cs
@@ -34,89 +34,77 @@ public class ProgressDialogWithTask : IThreadedProgress, IFWDisposable
#region Member variables
/// The form that actually displays the progress
- protected IProgress m_progressDialog;
+ internal ProgressDialogWithTaskDlgImpl m_progressDialog;
private readonly bool m_fCreatedProgressDlg;
private volatile bool m_fDisposed;
+ private readonly Form m_owner;
private Func m_backgroundTask;
private object[] m_parameters;
private object m_RetValue;
private Exception m_Exception;
- private ThreadHelper m_threadHelper;
private bool m_fOwnerWasTopMost;
private BackgroundWorker m_worker;
- private readonly ISynchronizeInvoke m_synchInvoke;
+ private readonly ISynchronizeInvoke m_synchronizeInvoke;
#endregion
#region Constructors
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes a new instance of the class that
- /// uses an externally supplied object to track the progress.
- ///
- /// The object that will be used to track the progress.
- /// ------------------------------------------------------------------------------------
- public ProgressDialogWithTask(IProgress progress) :
- this(progress, null, progress.Form)
- {
- }
- /// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class that
+ /// Initializes a new instance of the class that
/// will create an actual progress dialog box to track the progress.
///
/// The form to use as the owner when creating the actual progress
/// dialog.
- /// The thread helper (must been created on the UI thread).
- /// ------------------------------------------------------------------------------------
- public ProgressDialogWithTask(Form owner, ThreadHelper threadHelper) :
- this(null, owner, (ISynchronizeInvoke)owner ?? threadHelper)
+ public ProgressDialogWithTask(Form owner)
+ : this(owner, owner)
{
- m_threadHelper = threadHelper;
- m_fCreatedProgressDlg = true;
}
- /// ------------------------------------------------------------------------------------
///
/// Initializes a new instance of the class.
///
- /// An external implementation of IProgress that should be
- /// used to report progress. If this is null, then this class will create a generic
- /// progress dialog for the purpose of running tasks.
+ ///
+ public ProgressDialogWithTask(ISynchronizeInvoke synchronizeInvoke)
+ : this(null, synchronizeInvoke)
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
/// The "owning" form (can be null if progressDlg is specified or if
/// there is no suitable form available to own the progress dialog)
- /// Object that can ensure that certain operations are
- /// invoked on the UI thread.
- /// ------------------------------------------------------------------------------------
- private ProgressDialogWithTask(IProgress progress, Form owner, ISynchronizeInvoke synchInvoke)
+ /// The synchronize invoke.
+ private ProgressDialogWithTask(Form owner, ISynchronizeInvoke synchronizeInvoke)
{
- m_synchInvoke = synchInvoke;
- m_progressDialog = progress;
- InitOnOwnerThread(owner);
+ m_owner = owner;
+ m_synchronizeInvoke = synchronizeInvoke;
+ m_fCreatedProgressDlg = true;
+ InitOnOwnerThread();
+ if (m_synchronizeInvoke == null)
+ m_synchronizeInvoke = m_progressDialog.SynchronizeInvoke;
m_progressDialog.Canceling += m_progressDialog_Canceling;
- m_progressDialog.Form.FormClosing += m_progressDialog_FormClosing;
+ m_progressDialog.FormClosing += m_progressDialog_FormClosing;
m_worker.DoWork += RunBackgroundTask;
m_worker.RunWorkerCompleted += m_worker_RunWorkerCompleted;
}
[SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
Justification="m_worker gets disposed in Dispose()")]
- private void InitOnOwnerThread(Form owner)
+ private void InitOnOwnerThread()
{
- if (m_synchInvoke != null && m_synchInvoke.InvokeRequired)
+ if (m_synchronizeInvoke != null && m_synchronizeInvoke.InvokeRequired)
{
- m_synchInvoke.Invoke((Action
-
../../../../DistFiles
-
+
\ No newline at end of file
diff --git a/Src/Common/Controls/XMLViews/XMLViewsTests/TestColumnConfigureDialog.cs b/Src/Common/Controls/XMLViews/XMLViewsTests/TestColumnConfigureDialog.cs
index 42c085fb3f..b767746a00 100644
--- a/Src/Common/Controls/XMLViews/XMLViewsTests/TestColumnConfigureDialog.cs
+++ b/Src/Common/Controls/XMLViews/XMLViewsTests/TestColumnConfigureDialog.cs
@@ -11,6 +11,7 @@
using SIL.FieldWorks.Common.Controls;
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO;
+using SIL.FieldWorks.FDO.FDOTests;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
using XCore;
@@ -30,7 +31,7 @@ public void SetUp()
m_mediator = new Mediator();
m_mediator.StringTbl = new StringTable("../../DistFiles/Language Explorer/Configuration");
m_cache = FdoCache.CreateCacheWithNewBlankLangProj(
- new TestProjectId(FDOBackendProviderType.kMemoryOnly, null), "en", "en", "en", new ThreadHelper());
+ new TestProjectId(FDOBackendProviderType.kMemoryOnly, null), "en", "en", "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories);
m_mediator.PropertyTable.SetProperty("cache", m_cache);
}
@@ -38,7 +39,6 @@ public void SetUp()
public void TearDown()
{
m_mediator.Dispose();
- m_cache.ThreadHelper.Dispose();
m_cache.Dispose();
}
diff --git a/Src/Common/Controls/XMLViews/XMLViewsTests/TestManyOneBrowse.cs b/Src/Common/Controls/XMLViews/XMLViewsTests/TestManyOneBrowse.cs
index 1131b51125..9cb2be616e 100644
--- a/Src/Common/Controls/XMLViews/XMLViewsTests/TestManyOneBrowse.cs
+++ b/Src/Common/Controls/XMLViews/XMLViewsTests/TestManyOneBrowse.cs
@@ -60,7 +60,7 @@ public void Setup()
// - MoMorphSynAnalysis
// - MoStemMsa
// - MoDerivationalMsa
- string m_sTestPath = Path.Combine(DirectoryFinder.FwSourceDirectory,
+ string m_sTestPath = Path.Combine(FwDirectoryFinder.SourceDirectory,
Path.Combine("Common",
Path.Combine("Controls",
Path.Combine("XMLViews",
@@ -82,7 +82,7 @@ public void Setup()
m_sda.WritingSystemFactory = m_wsManager;
var parser = new SimpleDataParser(m_mdc, m_cda);
- parser.Parse(Path.Combine(DirectoryFinder.FwSourceDirectory,
+ parser.Parse(Path.Combine(FwDirectoryFinder.SourceDirectory,
Path.Combine("Common",
Path.Combine("Controls",
Path.Combine("XMLViews",
@@ -102,7 +102,7 @@ public void Setup()
// - Semantic domains (pair of strings in para in seq in seq, using layout refs)
// - MSAs (simplified, but polymorphic with one having and one to CmPossibility
XmlDocument docColumns = new XmlDocument();
- docColumns.Load(Path.Combine(DirectoryFinder.FwSourceDirectory,
+ docColumns.Load(Path.Combine(FwDirectoryFinder.SourceDirectory,
Path.Combine("Common",
Path.Combine("Controls",
Path.Combine("XMLViews",
@@ -110,7 +110,7 @@ public void Setup()
m_columnList = docColumns.DocumentElement.ChildNodes;
// Parts just has what those columns need.
- string partDirectory = Path.Combine(DirectoryFinder.FwSourceDirectory,
+ string partDirectory = Path.Combine(FwDirectoryFinder.SourceDirectory,
Path.Combine("Common",
Path.Combine("Controls",
Path.Combine("XMLViews", "XMLViewsTests"))));
diff --git a/Src/Common/Controls/XMLViews/XMLViewsTests/XMLViewsTests.csproj b/Src/Common/Controls/XMLViews/XMLViewsTests/XMLViewsTests.csproj
index e8e2a399b7..b10234b971 100644
--- a/Src/Common/Controls/XMLViews/XMLViewsTests/XMLViewsTests.csproj
+++ b/Src/Common/Controls/XMLViews/XMLViewsTests/XMLViewsTests.csproj
@@ -1,4 +1,4 @@
-
+
Local
@@ -233,7 +233,9 @@
-
+
+ UserControl
+
diff --git a/Src/Common/Controls/XMLViews/XmlVc.cs b/Src/Common/Controls/XMLViews/XmlVc.cs
index 7054085857..1f27450099 100644
--- a/Src/Common/Controls/XMLViews/XmlVc.cs
+++ b/Src/Common/Controls/XMLViews/XmlVc.cs
@@ -181,7 +181,7 @@ public class XmlVc : FwBaseVc
// This is the new constructor, where we find parts in the master inventory.
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The string table.
/// Name of the root layout.
@@ -199,7 +199,7 @@ public XmlVc(StringTable stringTable, string rootLayoutName, bool fEditable,
// This is a variant which can take a condition element to control which items in a list display.
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The string table.
/// Name of the root layout.
@@ -223,7 +223,7 @@ public XmlVc(StringTable stringTable, string rootLayoutName, bool fEditable,
///
/// This is another new constructor, for using the new approach without a single
/// top-level layout name, such as browse view.
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The string table.
/// ------------------------------------------------------------------------------------
@@ -1528,7 +1528,7 @@ public virtual void ProcessFrag(XmlNode frag, IVwEnv vwenv, int hvo, bool fEdita
CellarPropertyType itype = (CellarPropertyType)m_sda.MetaDataCache.GetFieldType(flid);
if (itype == CellarPropertyType.Time)
{
- DateTime dt = FwUtils.SilTime.GetTimeProperty(m_sda, hvo, flid);
+ DateTime dt = SilTime.GetTimeProperty(m_sda, hvo, flid);
XmlNode dtNode = XmlViewsUtils.CopyWithParamDefaults(frag);
string format;
if (vwenv is SortCollectorEnv)
@@ -4951,7 +4951,7 @@ public class NodeDisplayCommand : DisplayCommand
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The node.
/// ------------------------------------------------------------------------------------
@@ -5031,7 +5031,7 @@ public class NodeChildrenDisplayCommand : NodeDisplayCommand
{
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The node.
/// ------------------------------------------------------------------------------------
@@ -5657,7 +5657,7 @@ public class PropWs
{
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The xflid.
/// The XWS.
@@ -5734,12 +5734,12 @@ public int Compare(int x, int y)
string ws = xobj.SortKeyWs;
if (string.IsNullOrEmpty(ws))
ws = yobj.SortKeyWs;
- Icu.UErrorCode err;
- m_col = Icu.ucol_Open(Encoding.UTF8.GetBytes(ws), out err);
+ string icuLocale = Icu.GetName(ws);
+ m_col = Icu.OpenCollator(icuLocale);
}
- byte[] xkey = GetSortKey(m_col, xkeyStr);
- byte[] ykey = GetSortKey(m_col, ykeyStr);
+ byte[] xkey = Icu.GetSortKey(m_col, xkeyStr);
+ byte[] ykey = Icu.GetSortKey(m_col, ykeyStr);
// Simulate strcmp on the two NUL-terminated byte strings.
// This avoids marshalling back and forth.
// JohnT: but apparently the strings are not null-terminated if the input was empty.
@@ -5769,33 +5769,11 @@ public int Compare(int x, int y)
return nVal;
}
- internal static byte[] GetSortKey(IntPtr collater, string keyStr)
- {
- const int keyLength = 1024;
- var key = new byte[keyLength+1];
- var len = Icu.ucol_GetSortKey(collater, keyStr, keyStr.Length, ref key, keyLength);
- if (len > keyLength)
- {
- key = new byte[len + 1];
- len = Icu.ucol_GetSortKey(collater, keyStr, keyStr.Length, ref key, len);
- }
- // Ensure that the byte array is truncated to its actual data length.
- Debug.Assert(len <= key.Length);
- if (len < key.Length)
- {
- var result = new byte[len];
- for (int i = 0; i < len; ++i)
- result[i] = key[i];
- return result;
- }
- return key;
- }
-
protected override void DisposeUnmanagedResources()
{
if (m_col != IntPtr.Zero)
{
- Icu.ucol_Close(m_col);
+ Icu.CloseCollator(m_col);
m_col = IntPtr.Zero;
}
}
diff --git a/Src/Common/Controls/XMLViews/XmlViewsUtils.cs b/Src/Common/Controls/XMLViews/XmlViewsUtils.cs
index 30da878cb4..5b0768c576 100644
--- a/Src/Common/Controls/XMLViews/XmlViewsUtils.cs
+++ b/Src/Common/Controls/XMLViews/XmlViewsUtils.cs
@@ -959,7 +959,7 @@ static public string[] StringsFor(FdoCache fdoCache, ISilDataAccess sda, XmlNode
CellarPropertyType itype = (CellarPropertyType)sda.MetaDataCache.GetFieldType(flid);
if (itype == CellarPropertyType.Time)
{
- DateTime dt = FwUtils.SilTime.GetTimeProperty(sda, hvo, flid);
+ DateTime dt = SilTime.GetTimeProperty(sda, hvo, flid);
return new[] {DateTimeCompString(dt)};
}
else
diff --git a/Src/Common/FwUtils/CaseFunctions.cs b/Src/Common/CoreImpl/CaseFunctions.cs
similarity index 98%
rename from Src/Common/FwUtils/CaseFunctions.cs
rename to Src/Common/CoreImpl/CaseFunctions.cs
index d25a597d5b..89a01ca485 100644
--- a/Src/Common/FwUtils/CaseFunctions.cs
+++ b/Src/Common/CoreImpl/CaseFunctions.cs
@@ -7,7 +7,7 @@
// ---------------------------------------------------------------------------------------------
using SIL.FieldWorks.Common.COMInterfaces;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
///
/// CaseFunctions provides a set of case conversion functions derived from the ICU
diff --git a/Src/Common/CoreImpl/CoreImpl.csproj b/Src/Common/CoreImpl/CoreImpl.csproj
index 674455805c..eb3f4caaf5 100644
--- a/Src/Common/CoreImpl/CoreImpl.csproj
+++ b/Src/Common/CoreImpl/CoreImpl.csproj
@@ -99,7 +99,14 @@
CommonAssemblyInfo.cs
+
+
+
+
+
+
+
@@ -132,6 +139,9 @@
+
+
+
diff --git a/Src/Common/CoreImpl/CoreImplStrings.Designer.cs b/Src/Common/CoreImpl/CoreImplStrings.Designer.cs
index 13c195dfcc..ee90a048b7 100644
--- a/Src/Common/CoreImpl/CoreImplStrings.Designer.cs
+++ b/Src/Common/CoreImpl/CoreImplStrings.Designer.cs
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
-// Runtime Version:4.0.30319.296
+// Runtime Version:4.0.30319.18052
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -61,7 +61,7 @@ internal CoreImplStrings() {
}
///
- /// Looks up a localized string similar to FieldWorks is unable to save some writing system settings because access to {0} is not authorized. This may cause unexpected behavior, and may be indicative of a wider problem with access permissions that could cause program crashes..
+ /// Looks up a localized string similar to Unable to save some writing system settings because access to {0} is not authorized. This may cause unexpected behavior, and may be indicative of a wider problem with access permissions that could cause program crashes..
///
internal static string ksCannotWriteWritingSystemInfo {
get {
@@ -69,6 +69,87 @@ internal static string ksCannotWriteWritingSystemInfo {
}
}
+ ///
+ /// Looks up a localized string similar to AD.
+ ///
+ internal static string ksGenDateAD {
+ get {
+ return ResourceManager.GetString("ksGenDateAD", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to After.
+ ///
+ internal static string ksGenDateAfter {
+ get {
+ return ResourceManager.GetString("ksGenDateAfter", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to About.
+ ///
+ internal static string ksGenDateApprox {
+ get {
+ return ResourceManager.GetString("ksGenDateApprox", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to BC.
+ ///
+ internal static string ksGenDateBC {
+ get {
+ return ResourceManager.GetString("ksGenDateBC", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Before.
+ ///
+ internal static string ksGenDateBefore {
+ get {
+ return ResourceManager.GetString("ksGenDateBefore", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Version: {0} {1} {2}.
+ ///
+ internal static string kstidAppVersionFmt {
+ get {
+ return ResourceManager.GetString("kstidAppVersionFmt", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to This software is licensed under the MIT License.
+ ///
+ internal static string kstidLicense {
+ get {
+ return ResourceManager.GetString("kstidLicense", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to (http://opensource.org/licenses/MIT).
+ ///
+ internal static string kstidLicenseURL {
+ get {
+ return ResourceManager.GetString("kstidLicenseURL", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Version: {0}.
+ ///
+ internal static string kstidMajorVersionFmt {
+ get {
+ return ResourceManager.GetString("kstidMajorVersionFmt", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Warning.
///
@@ -96,8 +177,7 @@ internal static string ksWarning {
///AQ 2005-10-16 Antarctica
///AR 2005-10-16 Argentina
///AS 2005-10-16 American Samoa
- ///AT 2005-10-16 Austria
- ///AU 2005-10 [rest of string was truncated]";.
+ ///AT 2005-10-16 A [rest of string was truncated]";.
///
internal static string regions {
get {
@@ -114,8 +194,7 @@ internal static string regions {
///1694acad 2007-03-20 Early Modern French fr
///1901 2005-10-16 Traditional German orthography de
///1959acad 2008-09-30 "Academic" ("governmental") variant of Belarusian as codified in 1959 be
- ///1994 2007-07-28 Standardized Resian orthography sl-rozaj / sl-rozaj-biske / sl-rozaj-njiva / sl-rozaj-osojs / sl-rozaj-solba
- ///1996 20 [rest of string was truncated]";.
+ ///1994 2007-07-28 Standardized Resian orthography sl-rozaj / sl-rozaj-biske / sl-rozaj-njiva / sl-rozaj-osojs / sl-rozaj-solba [rest of string was truncated]";.
///
internal static string variants {
get {
diff --git a/Src/Common/CoreImpl/CoreImplStrings.resx b/Src/Common/CoreImpl/CoreImplStrings.resx
index 026e43da47..995ede0202 100644
--- a/Src/Common/CoreImpl/CoreImplStrings.resx
+++ b/Src/Common/CoreImpl/CoreImplStrings.resx
@@ -118,7 +118,38 @@
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- FieldWorks is unable to save some writing system settings because access to {0} is not authorized. This may cause unexpected behavior, and may be indicative of a wider problem with access permissions that could cause program crashes.
+ Unable to save some writing system settings because access to {0} is not authorized. This may cause unexpected behavior, and may be indicative of a wider problem with access permissions that could cause program crashes.
+
+
+ AD
+
+
+ After
+
+
+ About
+
+
+ BC
+
+
+ Before
+
+
+ Version: {0} {1} {2}
+ Displays in the Help/About box and the splash screen
+
+
+ Version: {0}
+ Displays in the Help/About box and the splash screen
+
+
+ This software is licensed under the LGPL, version 2.1 or later
+ Displays in the Help/About box and the splash screen
+
+
+ (http://www.gnu.org/licenses/lgpl-2.1.html)
+ Displays in the Help/About box
Warning
diff --git a/Src/Common/CoreImpl/CoreImplTests/CoreImplTests.csproj b/Src/Common/CoreImpl/CoreImplTests/CoreImplTests.csproj
index 4fdd3f52b9..ae2a29e712 100644
--- a/Src/Common/CoreImpl/CoreImplTests/CoreImplTests.csproj
+++ b/Src/Common/CoreImpl/CoreImplTests/CoreImplTests.csproj
@@ -1,4 +1,4 @@
-
+
Debug
@@ -110,12 +110,15 @@
AssemblyInfoForTests.cs
+
+
+
@@ -143,8 +146,7 @@
-
../../../../DistFiles
-
+
\ No newline at end of file
diff --git a/Src/Common/CoreImpl/CoreImplTests/DirectoryFinderTests.cs b/Src/Common/CoreImpl/CoreImplTests/DirectoryFinderTests.cs
new file mode 100644
index 0000000000..4b8974a8fa
--- /dev/null
+++ b/Src/Common/CoreImpl/CoreImplTests/DirectoryFinderTests.cs
@@ -0,0 +1,62 @@
+using System;
+using NUnit.Framework;
+
+namespace SIL.CoreImpl
+{
+ [TestFixture]
+ public class DirectoryFinderTests
+ {
+ private string m_previousEnvironment;
+
+ private void SetupEnvironment(string path)
+ {
+ m_previousEnvironment = Environment.GetEnvironmentVariable("FW_CommonAppData");
+ DirectoryFinder.ResetStaticVars();
+ Environment.SetEnvironmentVariable("FW_CommonAppData", path);
+ }
+
+ private void ResetEnvironment()
+ {
+ Environment.SetEnvironmentVariable("FW_CommonAppData", m_previousEnvironment);
+ }
+
+ [Test]
+ public void GetFolderPath_NoEnvVariableSet()
+ {
+ try
+ {
+ SetupEnvironment(null);
+ string path = DirectoryFinder.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
+#if __MonoCS__
+ Assert.That(path, Is.EqualTo("/var/lib/fieldworks"));
+#else
+ Assert.That(path, Is.EqualTo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)));
+#endif
+ }
+ finally
+ {
+ ResetEnvironment();
+ }
+ }
+
+ [Test]
+ public void GetFolderPath_EnvVariableSet()
+ {
+ try
+ {
+ SetupEnvironment("/bla");
+ string path = DirectoryFinder.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
+#if __MonoCS__
+ Assert.That(path, Is.EqualTo("/bla"));
+#else
+ Assert.That(path, Is.EqualTo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)));
+#endif
+ }
+ finally
+ {
+ ResetEnvironment();
+ }
+ }
+
+ }
+}
diff --git a/Src/Common/CoreImpl/CoreImplTests/PalasoWritingSystemManagerTests.cs b/Src/Common/CoreImpl/CoreImplTests/PalasoWritingSystemManagerTests.cs
index ca7566611b..45ae10a9db 100644
--- a/Src/Common/CoreImpl/CoreImplTests/PalasoWritingSystemManagerTests.cs
+++ b/Src/Common/CoreImpl/CoreImplTests/PalasoWritingSystemManagerTests.cs
@@ -102,6 +102,8 @@ public void SerializeDeserialize()
///
/// Tests to make sure that the special fw extensions of ldml aren't duplicated when round tripping.
///
+ [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
+ Justification = "In .NET 4.5 XmlNodeList implements IDisposable, but not in 4.0.")]
[Test]
[SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
Justification = "In .NET 4.5 XmlNodeList implements IDisposable, but not in 4.0.")]
diff --git a/Src/Common/FwUtils/FwUtilsTests/SpellingHelperTests.cs b/Src/Common/CoreImpl/CoreImplTests/SpellingHelperTests.cs
similarity index 99%
rename from Src/Common/FwUtils/FwUtilsTests/SpellingHelperTests.cs
rename to Src/Common/CoreImpl/CoreImplTests/SpellingHelperTests.cs
index 4e8c7df279..8ce5bf316e 100644
--- a/Src/Common/FwUtils/FwUtilsTests/SpellingHelperTests.cs
+++ b/Src/Common/CoreImpl/CoreImplTests/SpellingHelperTests.cs
@@ -1,12 +1,11 @@
using System;
-using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using SIL.Utils;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
///
/// Tests (for now pretty incomplete) of the SpellingHelper class.
diff --git a/Src/Common/FwUtils/FwUtilsTests/StringSearcherTests.cs b/Src/Common/CoreImpl/CoreImplTests/StringSearcherTests.cs
similarity index 94%
rename from Src/Common/FwUtils/FwUtilsTests/StringSearcherTests.cs
rename to Src/Common/CoreImpl/CoreImplTests/StringSearcherTests.cs
index 216450f465..f995d16e0e 100644
--- a/Src/Common/FwUtils/FwUtilsTests/StringSearcherTests.cs
+++ b/Src/Common/CoreImpl/CoreImplTests/StringSearcherTests.cs
@@ -1,16 +1,14 @@
-using System.Linq;
+using System.Linq;
using NUnit.Framework;
-using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Test.TestUtils;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
///
/// StringSearcher tests
///
[TestFixture]
- public class StringSearcherTests: BaseTest
+ public class StringSearcherTests
{
private IWritingSystemManager m_wsManager;
private int m_enWs;
@@ -21,10 +19,8 @@ public class StringSearcherTests: BaseTest
/// Setup the test fixture.
///
[TestFixtureSetUp]
- public override void FixtureSetup()
+ public void FixtureSetup()
{
- base.FixtureSetup();
-
m_wsManager = new PalasoWritingSystemManager();
IWritingSystem enWs;
m_wsManager.GetOrSet("en", out enWs);
diff --git a/Src/Common/CoreImpl/DirectoryFinder.cs b/Src/Common/CoreImpl/DirectoryFinder.cs
new file mode 100644
index 0000000000..31fcfc40f3
--- /dev/null
+++ b/Src/Common/CoreImpl/DirectoryFinder.cs
@@ -0,0 +1,124 @@
+using System;
+using System.IO;
+using System.Reflection;
+using SIL.Utils;
+
+namespace SIL.CoreImpl
+{
+ ///
+ /// This class is used to find files and directories for an SIL app.
+ ///
+ public static class DirectoryFinder
+ {
+ private static string s_CommonAppDataFolder;
+
+ ///
+ /// Resets the static variables. Used for unit tests.
+ ///
+ internal static void ResetStaticVars()
+ {
+ s_CommonAppDataFolder = null;
+ }
+
+
+ ///
+ /// Gets the company name (should be SIL).
+ ///
+ public static string CompanyName
+ {
+ get
+ {
+ return ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(
+ Assembly.GetExecutingAssembly(), typeof(AssemblyCompanyAttribute), false))
+ .Company;
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path for storing user-specific application data.
+ ///
+ /// Name of the application.
+ /// ------------------------------------------------------------------------------------
+ public static string UserAppDataFolder(string appName)
+ {
+ string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
+ return Path.Combine(Path.Combine(path, CompanyName), appName);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path for storing common application data that might be shared between
+ /// multiple applications and multiple users on the same machine.
+ ///
+ /// On Windows this returns Environment.SpecialFolder.CommonApplicationData
+ /// (C:\ProgramData),on Linux /var/lib/fieldworks.
+ ///
+ /// ------------------------------------------------------------------------------------
+ private static string CommonApplicationData
+ {
+ get
+ {
+ if (s_CommonAppDataFolder == null)
+ {
+ if (MiscUtils.IsUnix)
+ {
+ // allow to override the /var/lib/fieldworks path by setting the
+ // environment variable FW_CommonAppData. Is this is needed on our CI
+ // build machines.
+ s_CommonAppDataFolder =
+ Environment.GetEnvironmentVariable("FW_CommonAppData") ??
+ "/var/lib/fieldworks";
+ }
+ else
+ {
+ s_CommonAppDataFolder =
+ Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
+ }
+ }
+ return s_CommonAppDataFolder;
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets a special folder, very similar to Environment.GetFolderPath. The main
+ /// difference is that this method works cross-platform and does some translations.
+ /// For example CommonApplicationData (/usr/share) is not writeable on Linux, so we
+ /// translate that to /var/lib/fieldworks instead.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string GetFolderPath(Environment.SpecialFolder folder)
+ {
+ if (folder == Environment.SpecialFolder.CommonApplicationData)
+ return CommonApplicationData;
+ return Environment.GetFolderPath(folder);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path for storing common application data that might be shared between
+ /// multiple applications and multiple users on the same machine.
+ ///
+ /// On Windows this returns a subdirectory of
+ /// Environment.SpecialFolder.CommonApplicationData (C:\ProgramData),on Linux
+ /// /var/lib/fieldworks.
+ ///
+ /// Name of the application.
+ /// ------------------------------------------------------------------------------------
+ public static string CommonAppDataFolder(string appName)
+ {
+ return Path.Combine(Path.Combine(CommonApplicationData, CompanyName), appName);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the global writing system store directory. The directory is guaranteed to exist.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string GlobalWritingSystemStoreDirectory
+ {
+ get { return CommonAppDataFolder("WritingSystemStore"); }
+ }
+ }
+}
diff --git a/Src/Common/FwUtils/GenDate.cs b/Src/Common/CoreImpl/GenDate.cs
similarity index 92%
rename from Src/Common/FwUtils/GenDate.cs
rename to Src/Common/CoreImpl/GenDate.cs
index 1d5ac08d34..db34f706f6 100644
--- a/Src/Common/FwUtils/GenDate.cs
+++ b/Src/Common/CoreImpl/GenDate.cs
@@ -1,9 +1,8 @@
-using System;
-using System.Text;
-using System.Globalization;
+using System;
using System.Collections.Generic;
+using System.Text;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
///
/// This class encapsulates the generic (vague) date type. This type can store dates
@@ -215,15 +214,15 @@ public string ToLongString()
switch (m_precision)
{
case PrecisionType.Approximate:
- sb.Append(FwUtilsStrings.ksGenDateApprox);
+ sb.Append(CoreImplStrings.ksGenDateApprox);
sb.Append(" ");
break;
case PrecisionType.After:
- sb.Append(FwUtilsStrings.ksGenDateAfter);
+ sb.Append(CoreImplStrings.ksGenDateAfter);
sb.Append(" ");
break;
case PrecisionType.Before:
- sb.Append(FwUtilsStrings.ksGenDateBefore);
+ sb.Append(CoreImplStrings.ksGenDateBefore);
sb.Append(" ");
break;
}
@@ -247,7 +246,7 @@ public string ToLongString()
}
else if (m_year != UnknownYear && m_ad)
{
- sb.Append(FwUtilsStrings.ksGenDateAD);
+ sb.Append(CoreImplStrings.ksGenDateAD);
sb.Append(" ");
}
@@ -257,7 +256,7 @@ public string ToLongString()
if (!m_ad)
{
sb.Append(" ");
- sb.Append(FwUtilsStrings.ksGenDateBC);
+ sb.Append(CoreImplStrings.ksGenDateBC);
}
}
return sb.ToString();
@@ -279,15 +278,15 @@ public string ToXMLExportShortString()
switch (m_precision)
{
case PrecisionType.Approximate:
- sb.Append(FwUtilsStrings.ksGenDateApprox);
+ sb.Append(CoreImplStrings.ksGenDateApprox);
sb.Append(" ");
break;
case PrecisionType.After:
- sb.Append(FwUtilsStrings.ksGenDateAfter);
+ sb.Append(CoreImplStrings.ksGenDateAfter);
sb.Append(" ");
break;
case PrecisionType.Before:
- sb.Append(FwUtilsStrings.ksGenDateBefore);
+ sb.Append(CoreImplStrings.ksGenDateBefore);
sb.Append(" ");
break;
}
@@ -316,15 +315,15 @@ public string ToShortString()
switch (m_precision)
{
case PrecisionType.Approximate:
- sb.Append(FwUtilsStrings.ksGenDateApprox);
+ sb.Append(CoreImplStrings.ksGenDateApprox);
sb.Append(" ");
break;
case PrecisionType.After:
- sb.Append(FwUtilsStrings.ksGenDateAfter);
+ sb.Append(CoreImplStrings.ksGenDateAfter);
sb.Append(" ");
break;
case PrecisionType.Before:
- sb.Append(FwUtilsStrings.ksGenDateBefore);
+ sb.Append(CoreImplStrings.ksGenDateBefore);
sb.Append(" ");
break;
}
@@ -380,30 +379,30 @@ public static bool TryParse(string date, out GenDate gen)
bool fAD = true;
date = date.Trim();
- if (date.StartsWith(FwUtilsStrings.ksGenDateApprox))
+ if (date.StartsWith(CoreImplStrings.ksGenDateApprox))
{
precision = PrecisionType.Approximate;
- date = date.Substring(FwUtilsStrings.ksGenDateApprox.Length + 1);
+ date = date.Substring(CoreImplStrings.ksGenDateApprox.Length + 1);
}
- else if (date.StartsWith(FwUtilsStrings.ksGenDateAfter))
+ else if (date.StartsWith(CoreImplStrings.ksGenDateAfter))
{
precision = PrecisionType.After;
- date = date.Substring(FwUtilsStrings.ksGenDateAfter.Length + 1);
+ date = date.Substring(CoreImplStrings.ksGenDateAfter.Length + 1);
}
- else if (date.StartsWith(FwUtilsStrings.ksGenDateBefore))
+ else if (date.StartsWith(CoreImplStrings.ksGenDateBefore))
{
precision = PrecisionType.Before;
- date = date.Substring(FwUtilsStrings.ksGenDateBefore.Length + 1);
+ date = date.Substring(CoreImplStrings.ksGenDateBefore.Length + 1);
}
- if (date.Contains(FwUtilsStrings.ksGenDateAD + " "))
+ if (date.Contains(CoreImplStrings.ksGenDateAD + " "))
{
fAD = true;
- date = date.Replace(FwUtilsStrings.ksGenDateAD + " ", "");
+ date = date.Replace(CoreImplStrings.ksGenDateAD + " ", "");
}
- else if (date.EndsWith(FwUtilsStrings.ksGenDateBC))
+ else if (date.EndsWith(CoreImplStrings.ksGenDateBC))
{
fAD = false;
- date = date.Substring(0, date.Length - (FwUtilsStrings.ksGenDateBC.Length + 1));
+ date = date.Substring(0, date.Length - (CoreImplStrings.ksGenDateBC.Length + 1));
}
int nDay = UnknownDay;
int nMonth = UnknownMonth;
diff --git a/Src/Common/CoreImpl/GlobalFileWritingSystemStore.cs b/Src/Common/CoreImpl/GlobalFileWritingSystemStore.cs
index 914349f7ea..dcae8cba80 100644
--- a/Src/Common/CoreImpl/GlobalFileWritingSystemStore.cs
+++ b/Src/Common/CoreImpl/GlobalFileWritingSystemStore.cs
@@ -3,13 +3,11 @@
using System.Globalization;
using System.IO;
using System.Linq;
-using System.Runtime.InteropServices;
+using System.Security.AccessControl;
+using System.Security.Principal;
using System.Threading;
-using System.Xml;
using System.Collections.Generic;
-using System.Xml.Linq;
using Palaso.WritingSystems;
-using SIL.FieldWorks.Common.COMInterfaces;
using SIL.Utils;
namespace SIL.CoreImpl
@@ -25,14 +23,49 @@ public class GlobalFileWritingSystemStore : IFwWritingSystemStore
/// Reference to a mutex. The owner of the mutex is the SingletonContainer
private readonly Mutex m_mutex;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GlobalFileWritingSystemStore()
+ : this(DirectoryFinder.GlobalWritingSystemStoreDirectory)
+ {
+ }
+
///
/// Initializes a new instance of the class.
///
/// The path.
- public GlobalFileWritingSystemStore(string path)
+ [SuppressMessage("Gendarme.Rules.Portability", "MonoCompatibilityReviewRule",
+ Justification="Offending code is not executed on Linux")]
+ internal GlobalFileWritingSystemStore(string path)
{
m_path = path;
- Directory.CreateDirectory(m_path);
+ if (!Directory.Exists(m_path))
+ {
+ DirectoryInfo di;
+
+ // Provides FW on Linux multi-user access. Overrides the system
+ // umask and creates the directory with the permissions "775".
+ // The "fieldworks" group was created outside the app during
+ // configuration of the package which allows group access.
+ using(new FileModeOverride())
+ {
+ di = Directory.CreateDirectory(m_path);
+ }
+
+ if (!MiscUtils.IsUnix)
+ {
+ // NOTE: GetAccessControl/ModifyAccessRule/SetAccessControl is not implemented in Mono
+ DirectorySecurity ds = di.GetAccessControl();
+ var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
+ AccessRule rule = new FileSystemAccessRule(sid, FileSystemRights.Write | FileSystemRights.ReadAndExecute
+ | FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
+ PropagationFlags.InheritOnly, AccessControlType.Allow);
+ bool modified;
+ ds.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
+ di.SetAccessControl(ds);
+ }
+ }
m_mutex = SingletonsContainer.Get(typeof(Mutex).FullName + m_path,
() => new Mutex(false, m_path.Replace('\\', '_').Replace('/', '_')));
}
diff --git a/Src/Common/FwUtils/ISpellEngine.cs b/Src/Common/CoreImpl/ISpellEngine.cs
similarity index 92%
rename from Src/Common/FwUtils/ISpellEngine.cs
rename to Src/Common/CoreImpl/ISpellEngine.cs
index 8e868a0b24..690b8f6c9f 100644
--- a/Src/Common/FwUtils/ISpellEngine.cs
+++ b/Src/Common/CoreImpl/ISpellEngine.cs
@@ -1,7 +1,7 @@
-using System.Collections.Generic;
+using System.Collections.Generic;
using SIL.FieldWorks.Common.COMInterfaces;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
///
/// This is our wrapper for Hunspell, currently. It hides everything we don't use in case we want to change again!
diff --git a/Src/Common/FwUtils/SilTime.cs b/Src/Common/CoreImpl/SilTime.cs
similarity index 96%
rename from Src/Common/FwUtils/SilTime.cs
rename to Src/Common/CoreImpl/SilTime.cs
index 1c245336b8..894711479f 100644
--- a/Src/Common/FwUtils/SilTime.cs
+++ b/Src/Common/CoreImpl/SilTime.cs
@@ -8,13 +8,11 @@
//
//
-using System;
-using System.Collections.Generic;
-using System.Text;
+using System;
using SIL.FieldWorks.Common.COMInterfaces;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
/// ----------------------------------------------------------------------------------------
///
diff --git a/Src/Common/FwUtils/SpellEngine.cs b/Src/Common/CoreImpl/SpellEngine.cs
similarity index 99%
rename from Src/Common/FwUtils/SpellEngine.cs
rename to Src/Common/CoreImpl/SpellEngine.cs
index aa4dac108c..82399e007c 100644
--- a/Src/Common/FwUtils/SpellEngine.cs
+++ b/Src/Common/CoreImpl/SpellEngine.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
@@ -6,7 +6,7 @@
using System.Text;
using SIL.FieldWorks.Common.COMInterfaces;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
internal class SpellEngine : ISpellEngine, IDisposable
{
diff --git a/Src/Common/FwUtils/SpellingHelper.cs b/Src/Common/CoreImpl/SpellingHelper.cs
similarity index 99%
rename from Src/Common/FwUtils/SpellingHelper.cs
rename to Src/Common/CoreImpl/SpellingHelper.cs
index bfe3127791..361278570d 100644
--- a/Src/Common/FwUtils/SpellingHelper.cs
+++ b/Src/Common/CoreImpl/SpellingHelper.cs
@@ -1,16 +1,14 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
-using System.Windows.Forms;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.Utils;
-using XCore;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
///
/// This class manages a dictionary of (currently) Hunspell objects so that we can do spell checking.
diff --git a/Src/Common/FwUtils/FwStartupException.cs b/Src/Common/CoreImpl/StartupException.cs
similarity index 69%
rename from Src/Common/FwUtils/FwStartupException.cs
rename to Src/Common/CoreImpl/StartupException.cs
index d109d8369c..3b46e2dd70 100644
--- a/Src/Common/FwUtils/FwStartupException.cs
+++ b/Src/Common/CoreImpl/StartupException.cs
@@ -2,7 +2,7 @@
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
//
-// File: FwStartupException.cs
+// File: StartupException.cs
// Responsibility: TE Team
//
//
@@ -10,83 +10,83 @@
using System;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
/// ----------------------------------------------------------------------------------------
///
/// Exception thrown during FieldWorks startup if something goes wrong
///
/// ----------------------------------------------------------------------------------------
- public class FwStartupException : Exception
+ public class StartupException : Exception
{
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The message.
/// ------------------------------------------------------------------------------------
- public FwStartupException(string message) : this(message, null)
+ public StartupException(string message) : this(message, null)
{
}
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The message.
/// The inner exception.
/// ------------------------------------------------------------------------------------
- public FwStartupException(string message, Exception innerException) :
+ public StartupException(string message, Exception innerException) :
this(message, innerException, true)
{
}
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The message.
/// True to report this error to the user, false otherwise
///
/// ------------------------------------------------------------------------------------
- public FwStartupException(string message, bool fReportToUser) :
+ public StartupException(string message, bool fReportToUser) :
this(message, null, fReportToUser)
{
}
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The inner exception.
/// ------------------------------------------------------------------------------------
- public FwStartupException(Exception innerException) : this(innerException, true)
+ public StartupException(Exception innerException) : this(innerException, true)
{
}
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The inner exception.
/// True to report this error to the user, false otherwise
///
/// ------------------------------------------------------------------------------------
- public FwStartupException(Exception innerException, bool fReportToUser) :
+ public StartupException(Exception innerException, bool fReportToUser) :
this(null, innerException, fReportToUser)
{
}
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The message.
/// The inner exception.
/// True to report this error to the user, false otherwise
///
/// ------------------------------------------------------------------------------------
- public FwStartupException(string message, Exception innerException, bool fReportToUser) :
+ public StartupException(string message, Exception innerException, bool fReportToUser) :
base(message, innerException)
{
ReportToUser = fReportToUser;
@@ -103,17 +103,4 @@ public bool ReportToUser
private set;
}
}
-
- ///
- /// Exception thrown when we try to open a project that belongs to a newer version of FieldWorks than this.
- ///
- public class FwNewerVersionException : FwStartupException
- {
- ///
- /// Make one.
- ///
- public FwNewerVersionException(string message) : base(message)
- {
- }
- }
}
diff --git a/Src/Common/FwUtils/StringSearcher.cs b/Src/Common/CoreImpl/StringSearcher.cs
similarity index 57%
rename from Src/Common/FwUtils/StringSearcher.cs
rename to Src/Common/CoreImpl/StringSearcher.cs
index 9311a3afdf..fefdb9f74e 100644
--- a/Src/Common/FwUtils/StringSearcher.cs
+++ b/Src/Common/CoreImpl/StringSearcher.cs
@@ -2,12 +2,10 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
-using Palaso.WritingSystems.Collation;
-using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.Utils;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
///
/// Type of string searching.
@@ -116,7 +114,8 @@ public IEnumerable GetItems(byte[] lower, byte[] upper)
private readonly Dictionary, SortKeyIndex> m_indices = new Dictionary, SortKeyIndex>();
private readonly SearchType m_type;
- private readonly IWritingSystemManager m_wsManager;
+ private readonly Func m_sortKeySelector;
+ private readonly Func> m_tokenizer;
///
/// Initializes a new instance of the class.
@@ -125,8 +124,30 @@ public IEnumerable GetItems(byte[] lower, byte[] upper)
/// The writing system store.
public StringSearcher(SearchType type, IWritingSystemManager wsManager)
{
+ if (wsManager == null)
+ throw new ArgumentNullException("wsManager");
+
m_type = type;
- m_wsManager = wsManager;
+ m_sortKeySelector = (ws, text) => wsManager.Get(ws).Collator.GetSortKey(text).KeyData;
+ m_tokenizer = (ws, text) => Icu.Split(Icu.UBreakIteratorType.UBRK_WORD, wsManager.Get(ws).IcuLocale, text);
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The type.
+ /// The sort key selector.
+ /// The text tokenizer
+ public StringSearcher(SearchType type, Func sortKeySelector, Func> tokenizer)
+ {
+ if (sortKeySelector == null)
+ throw new ArgumentNullException("sortKeySelector");
+ if (type == SearchType.FullText && tokenizer == null)
+ throw new ArgumentNullException("tokenizer");
+
+ m_type = type;
+ m_sortKeySelector = sortKeySelector;
+ m_tokenizer = tokenizer;
}
///
@@ -136,33 +157,35 @@ public void Add(T item, int indexId, ITsString tss)
{
if (tss.RunCount == 1) // VERY common special case
{
- Add(indexId, tss.get_WritingSystemAt(0), tss.Text, item);
- return;
+ Add(item, indexId, tss.get_WritingSystemAt(0), tss.Text);
}
-
- foreach (Tuple wsStr in GetWsStrings(tss))
+ else
{
- var wsId = wsStr.Item1;
- var text = wsStr.Item2;
- Add(indexId, wsId, text, item);
+ foreach (Tuple wsStr in GetWsStrings(tss))
+ {
+ var wsId = wsStr.Item1;
+ var text = wsStr.Item2;
+ Add(item, indexId, wsId, text);
+ }
}
}
- private void Add(int indexId, int wsId, string text, T item)
+ ///
+ /// Adds the specified item to an index using the specified string.
+ ///
+ public void Add(T item, int indexId, int wsId, string text)
{
SortKeyIndex index = GetIndex(indexId, wsId);
- IWritingSystem ws = m_wsManager.Get(wsId);
- ICollator collator = ws.Collator;
switch (m_type)
{
case SearchType.Exact:
case SearchType.Prefix:
- index.Add(collator.GetSortKey(text).KeyData, item);
+ index.Add(m_sortKeySelector(wsId, text), item);
break;
case SearchType.FullText:
- foreach (string token in Icu.Split(Icu.UBreakIteratorType.UBRK_WORD, ws.IcuLocale, text))
- index.Add(collator.GetSortKey(token).KeyData, item);
+ foreach (string token in m_tokenizer(wsId, text))
+ index.Add(m_sortKeySelector(wsId, token), item);
break;
}
}
@@ -178,57 +201,76 @@ public IEnumerable Search(int indexId, ITsString tss)
if (tss == null || string.IsNullOrEmpty(tss.Text))
return Enumerable.Empty();
- HashSet results = null;
+ if (tss.RunCount == 1) // VERY common special case
+ return Search(indexId, tss.get_WritingSystemAt(0), tss.Text);
+
+ IEnumerable results = null;
foreach (Tuple wsStr in GetWsStrings(tss))
{
- SortKeyIndex index = GetIndex(indexId, wsStr.Item1);
- ICollator collator = m_wsManager.Get(wsStr.Item1).Collator;
- switch (m_type)
- {
- case SearchType.Exact:
- case SearchType.Prefix:
- {
- byte[] sortKey = collator.GetSortKey(wsStr.Item2).KeyData;
- var lower = new byte[wsStr.Item2.Length * SortKeyFactor];
- Icu.GetSortKeyBound(sortKey, Icu.UColBoundMode.UCOL_BOUND_LOWER, ref lower);
- var upper = new byte[wsStr.Item2.Length * SortKeyFactor];
- Icu.GetSortKeyBound(sortKey,
- m_type == SearchType.Exact
- ? Icu.UColBoundMode.UCOL_BOUND_UPPER
- : Icu.UColBoundMode.UCOL_BOUND_UPPER_LONG, ref upper);
- IEnumerable items = index.GetItems(lower, upper);
- if (results == null)
- results = new HashSet(items);
- else
- results.IntersectWith(items);
- break;
- }
-
- case SearchType.FullText:
- string locale = m_wsManager.GetStrFromWs(wsStr.Item1);
- string[] tokens = Icu.Split(Icu.UBreakIteratorType.UBRK_WORD, locale, wsStr.Item2).ToArray();
- for (int i = 0; i < tokens.Length; i++)
- {
- byte[] sortKey = collator.GetSortKey(tokens[i]).KeyData;
- var lower = new byte[tokens[i].Length*SortKeyFactor];
- Icu.GetSortKeyBound(sortKey, Icu.UColBoundMode.UCOL_BOUND_LOWER, ref lower);
- var upper = new byte[tokens[i].Length*SortKeyFactor];
- Icu.GetSortKeyBound(sortKey,
- i < tokens.Length - 1
- ? Icu.UColBoundMode.UCOL_BOUND_UPPER
- : Icu.UColBoundMode.UCOL_BOUND_UPPER_LONG, ref upper);
- IEnumerable items = index.GetItems(lower, upper);
- if (results == null)
- results = new HashSet(items);
- else
- results.IntersectWith(items);
- }
- break;
- }
+ IEnumerable items = Search(indexId, wsStr.Item1, wsStr.Item2);
+ if (results == null)
+ results = items;
+ else
+ results = results.Intersect(items);
}
return results ?? Enumerable.Empty();
}
+ ///
+ /// Searches an index for the specified string.
+ ///
+ /// The index id.
+ /// The ws id.
+ /// The text.
+ /// The search results.
+ public IEnumerable Search(int indexId, int wsId, string text)
+ {
+ if (string.IsNullOrEmpty(text))
+ return Enumerable.Empty();
+
+ SortKeyIndex index = GetIndex(indexId, wsId);
+ switch (m_type)
+ {
+ case SearchType.Exact:
+ case SearchType.Prefix:
+ {
+ byte[] sortKey = m_sortKeySelector(wsId, text);
+ var lower = new byte[text.Length * SortKeyFactor];
+ Icu.GetSortKeyBound(sortKey, Icu.UColBoundMode.UCOL_BOUND_LOWER, ref lower);
+ var upper = new byte[text.Length * SortKeyFactor];
+ Icu.GetSortKeyBound(sortKey,
+ m_type == SearchType.Exact
+ ? Icu.UColBoundMode.UCOL_BOUND_UPPER
+ : Icu.UColBoundMode.UCOL_BOUND_UPPER_LONG, ref upper);
+
+ return index.GetItems(lower, upper);
+ }
+
+ case SearchType.FullText:
+ IEnumerable results = null;
+ string[] tokens = m_tokenizer(wsId, text).ToArray();
+ for (int i = 0; i < tokens.Length; i++)
+ {
+ byte[] sortKey = m_sortKeySelector(wsId, tokens[i]);
+ var lower = new byte[tokens[i].Length*SortKeyFactor];
+ Icu.GetSortKeyBound(sortKey, Icu.UColBoundMode.UCOL_BOUND_LOWER, ref lower);
+ var upper = new byte[tokens[i].Length*SortKeyFactor];
+ Icu.GetSortKeyBound(sortKey,
+ i < tokens.Length - 1
+ ? Icu.UColBoundMode.UCOL_BOUND_UPPER
+ : Icu.UColBoundMode.UCOL_BOUND_UPPER_LONG, ref upper);
+ IEnumerable items = index.GetItems(lower, upper);
+ if (results == null)
+ results = items;
+ else
+ results = results.Intersect(items);
+ }
+ return results;
+ }
+
+ return null;
+ }
+
///
/// Clears all of the indices.
///
diff --git a/Src/Common/FwUtils/FwVersionInfoProvider.cs b/Src/Common/CoreImpl/VersionInfoProvider.cs
similarity index 87%
rename from Src/Common/FwUtils/FwVersionInfoProvider.cs
rename to Src/Common/CoreImpl/VersionInfoProvider.cs
index ab2fedf0ae..c3f58bb6c7 100644
--- a/Src/Common/FwUtils/FwVersionInfoProvider.cs
+++ b/Src/Common/CoreImpl/VersionInfoProvider.cs
@@ -1,8 +1,8 @@
-// Copyright (c) 2010-2013 SIL International
+// Copyright (c) 2010-2013 SIL International
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
//
-// File: FwVersionInfoProvider.cs
+// File: VersionInfoProvider.cs
// Responsibility: FW Team
using System;
@@ -10,14 +10,14 @@
using System.Reflection;
using System.Windows.Forms;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.CoreImpl
{
/// ----------------------------------------------------------------------------------------
///
- /// Class for getting version information out of a FieldWorks assembly
+ /// Class for getting version information out of an assembly
///
/// ----------------------------------------------------------------------------------------
- public class FwVersionInfoProvider
+ public class VersionInfoProvider
{
/// Default copyright string if no assembly could be found
public const string kDefaultCopyrightString = "Copyright (c) 2002-2013 SIL International";
@@ -30,13 +30,13 @@ public class FwVersionInfoProvider
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The assembly used to get the information.
/// if set to false, any SIL-identifying information
/// will be hidden.
/// ------------------------------------------------------------------------------------
- public FwVersionInfoProvider(Assembly assembly, bool fShowSILInfo)
+ public VersionInfoProvider(Assembly assembly, bool fShowSILInfo)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
@@ -122,9 +122,9 @@ public string ApplicationVersion
}
}
#if DEBUG
- return string.Format(FwUtilsStrings.kstidAppVersionFmt, appVersion, productDate, "(Debug version)");
+ return string.Format(CoreImplStrings.kstidAppVersionFmt, appVersion, productDate, "(Debug version)");
#else
- return string.Format(FwUtilsStrings.kstidAppVersionFmt, appVersion, productDate, "");
+ return string.Format(CoreImplStrings.kstidAppVersionFmt, appVersion, productDate, "");
#endif
}
}
@@ -134,17 +134,17 @@ public string ApplicationVersion
/// Gets the version of FieldWorks.
///
/// ------------------------------------------------------------------------------------
- public string FieldWorksVersion
+ public string MajorVersion
{
get
{
// Set the Fieldworks version text
object[] attributes = m_assembly.GetCustomAttributes(
typeof(AssemblyInformationalVersionAttribute), false);
- string fwVersion = (attributes != null && attributes.Length > 0) ?
+ string version = (attributes != null && attributes.Length > 0) ?
((AssemblyInformationalVersionAttribute)attributes[0]).InformationalVersion :
Application.ProductVersion;
- return string.Format(FwUtilsStrings.kstidFwVersionFmt, fwVersion);
+ return string.Format(CoreImplStrings.kstidMajorVersionFmt, version);
}
}
@@ -174,7 +174,7 @@ public string CopyrightString
copyRight = kDefaultCopyrightString;
}
}
- return copyRight.Replace("(c)", "©");
+ return copyRight.Replace("(c)", "");
}
}
@@ -185,7 +185,7 @@ public string LicenseString
{
get
{
- return FwUtilsStrings.kstidLicense;
+ return CoreImplStrings.kstidLicense;
}
}
@@ -194,7 +194,7 @@ public string LicenseURL
{
get
{
- return FwUtilsStrings.kstidLicenseURL;
+ return CoreImplStrings.kstidLicenseURL;
}
}
}
diff --git a/Src/Common/CoreImpl/gendarme-CoreImpl.ignore b/Src/Common/CoreImpl/gendarme-CoreImpl.ignore
index 7b653475d4..ef6495d129 100644
--- a/Src/Common/CoreImpl/gendarme-CoreImpl.ignore
+++ b/Src/Common/CoreImpl/gendarme-CoreImpl.ignore
@@ -7,3 +7,5 @@ R: Gendarme.Rules.Correctness.EnsureLocalDisposalRule
M: System.Collections.IEnumerator SIL.CoreImpl.KernelExtensions/*::System.Collections.IEnumerable.GetEnumerator()
M: System.Collections.IEnumerator SIL.CoreImpl.KernelExtensions/*::System.Collections.IEnumerable.GetEnumerator()
M: System.Collections.IEnumerator SIL.CoreImpl.TsRunPart/*::System.Collections.IEnumerable.GetEnumerator()
+M: System.Collections.IEnumerator SIL.CoreImpl.StringSearcher`1/SortKeyIndex/*::System.Collections.IEnumerable.GetEnumerator()
+M: System.Collections.IEnumerator SIL.CoreImpl.StringSearcher`1/*::System.Collections.IEnumerable.GetEnumerator()
diff --git a/Src/Common/FieldWorks/FieldWorks.cs b/Src/Common/FieldWorks/FieldWorks.cs
index d9a09cba07..8b54fe2054 100644
--- a/Src/Common/FieldWorks/FieldWorks.cs
+++ b/Src/Common/FieldWorks/FieldWorks.cs
@@ -32,16 +32,19 @@
using SIL.FieldWorks.Common.Framework;
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.RootSites;
+using SIL.FieldWorks.Common.ScriptureUtils;
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.DomainServices.BackupRestore;
+using SIL.FieldWorks.FDO.DomainServices.DataMigration;
using SIL.FieldWorks.FDO.Infrastructure;
+using SIL.FieldWorks.FdoUi;
using SIL.FieldWorks.FwCoreDlgs;
using SIL.FieldWorks.FwCoreDlgs.BackupRestore;
using SIL.FieldWorks.PaObjects;
using SIL.FieldWorks.Resources;
-using SIL.FieldWorks.LexicalProvider;
using SIL.Utils;
+using SIL.Utils.FileDialog;
using XCore;
using SIL.CoreImpl;
using ConfigurationException = SIL.Utils.ConfigurationException;
@@ -53,6 +56,7 @@
using Gecko;
#else
using NetSparkle;
+
#endif
[assembly:SuppressMessage("Gendarme.Rules.Portability", "ExitCodeIsLimitedOnUnixRule",
@@ -122,6 +126,7 @@ private enum StartupStatus
// true if we have no previous reporting settings, typically the first time a version of FLEx that
// supports usage reporting has been run.
private static bool s_noPreviousReportingSettings;
+ private static IFdoUI s_ui;
#endregion
#region Main Method and Initialization Methods
@@ -232,6 +237,8 @@ static int Main(string[] rgArgs)
s_noUserInterface = appArgs.NoUserInterface;
s_appServerMode = appArgs.AppServerMode;
+ s_ui = new FwFdoUI(GetHelpTopicProvider(appArgs.AppAbbrev), s_threadHelper);
+
if (Settings.Default.CallUpgrade)
{
Settings.Default.Upgrade();
@@ -275,6 +282,10 @@ static int Main(string[] rgArgs)
// from HKCU/Software/SIL/FieldWorks/7.0 -> FieldWorks/8.
FwRegistryHelper.UpgradeUserSettingsIfNeeded();
+ // initialize client-server services to use Db4O backend
+ ClientServerServices.SetCurrentToDb4OBackend(s_ui, FwDirectoryFinder.FdoDirectories,
+ () => FwDirectoryFinder.ProjectsDirectory == FwDirectoryFinder.ProjectsDirectoryLocalMachine);
+
if (appArgs.ShowHelp)
{
ShowCommandLineHelp();
@@ -328,9 +339,6 @@ static int Main(string[] rgArgs)
else if (!LaunchApplicationFromCommandLine(appArgs))
return 0; // Didn't launch, but probably not a serious error
- // Create a listener for this project for applications using FLEx as a LexicalProvider.
- LexicalProviderManager.StartLexicalServiceProvider(s_projectId, s_cache);
-
#if __MonoCS__
UglyHackForXkbIndicator();
#endif
@@ -411,6 +419,9 @@ private static bool LaunchApplicationFromCommandLine(FwAppArgs appArgs)
// Get the project the user wants to open and attempt to launch it.
ProjectId projectId = DetermineProject(appArgs);
+ if (projectId != null && IsSharedXmlBackendNeeded(projectId))
+ projectId.Type = FDOBackendProviderType.kSharedXML;
+
// s_projectId can be non-null if the user decided to restore a project from
// the Welcome to Fieldworks dialog. (FWR-2146)
if (s_projectId == null && !LaunchProject(appArgs, ref projectId))
@@ -430,6 +441,11 @@ private static bool LaunchApplicationFromCommandLine(FwAppArgs appArgs)
return true;
}
+ private static bool IsSharedXmlBackendNeeded(ProjectId projectId)
+ {
+ return projectId.Type == FDOBackendProviderType.kXML && ParatextHelper.GetAssociatedProject(projectId) != null;
+ }
+
/// ------------------------------------------------------------------------------------
///
/// Creates the application requested on the command line.
@@ -468,7 +484,7 @@ private static void LaunchRestoreFromCommandLine(FwAppArgs appArgs)
// There is no need to re-show the dialog since the user has already chosen
// the options and confirmed to overwrite any existing database.
Logger.WriteEvent("Restoring project: " + appArgs.BackupFile);
- RestoreProjectSettings restoreSettings = new RestoreProjectSettings(appArgs.Database,
+ RestoreProjectSettings restoreSettings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory, appArgs.Database,
appArgs.BackupFile, appArgs.RestoreOptions);
RestoreCurrentProject(new FwRestoreProjectSettings(appArgs.AppAbbrev, restoreSettings), null);
}
@@ -792,15 +808,62 @@ private static FdoCache CreateCache(ProjectId projectId)
WriteSplashScreen(string.Format(Properties.Resources.kstidLoadingProject, projectId.UiName));
Form owner = s_splashScreen != null ? s_splashScreen.Form : Form.ActiveForm;
- using (var progressDlg = new ProgressDialogWithTask(owner, s_threadHelper))
+ using (var progressDlg = new ProgressDialogWithTask(owner))
{
- FdoCache cache = FdoCache.CreateCacheFromExistingData(projectId, s_sWsUser, progressDlg);
- cache.ProjectNameChanged += ProjectNameChanged;
- cache.ServiceLocator.GetInstance().OnSave += FieldWorks_OnSave;
+ FdoCache cache = FdoCache.CreateCacheFromExistingData(projectId, s_sWsUser, s_ui, FwDirectoryFinder.FdoDirectories, progressDlg);
+ EnsureValidLinkedFilesFolder(cache);
+ cache.ProjectNameChanged += ProjectNameChanged;
+ cache.ServiceLocator.GetInstance().OnSave += FieldWorks_OnSave;
+
+ SetupErrorPropertiesNeedingCache(cache);
+ return cache;
+ }
+ }
- SetupErrorPropertiesNeedingCache(cache);
- return cache;
+ ///
+ /// Ensure a valid folder for LangProject.LinkedFilesRootDir. When moving projects
+ /// between systems, the stored value may become hopelessly invalid. See FWNX-1005
+ /// for an example of the havoc than can ensue.
+ ///
+ /// This method gets called when we open the FDO cache.
+ private static void EnsureValidLinkedFilesFolder(FdoCache cache)
+ {
+ if (MiscUtils.RunningTests)
+ return;
+
+ var linkedFilesFolder = cache.LangProject.LinkedFilesRootDir;
+ var defaultFolder = FdoFileHelper.GetDefaultLinkedFilesDir(cache.ProjectId.ProjectFolder);
+ EnsureValidLinkedFilesFolderCore(linkedFilesFolder, defaultFolder);
+
+ if (!Directory.Exists(linkedFilesFolder))
+ {
+ if (!Directory.Exists(defaultFolder))
+ defaultFolder = cache.ProjectId.ProjectFolder;
+ MessageBox.Show(String.Format(Properties.Resources.ksInvalidLinkedFilesFolder, linkedFilesFolder), Properties.Resources.ksErrorCaption);
+ while (!Directory.Exists(linkedFilesFolder))
+ {
+ using (var folderBrowserDlg = new FolderBrowserDialogAdapter())
+ {
+ folderBrowserDlg.Description = Properties.Resources.ksLinkedFilesFolder;
+ folderBrowserDlg.RootFolder = Environment.SpecialFolder.Desktop;
+ folderBrowserDlg.SelectedPath = defaultFolder;
+ if (folderBrowserDlg.ShowDialog() == DialogResult.OK)
+ linkedFilesFolder = folderBrowserDlg.SelectedPath;
+ }
+ }
+ NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(cache.ActionHandlerAccessor, () =>
+ { cache.LangProject.LinkedFilesRootDir = linkedFilesFolder; });
+ }
}
+
+ ///
+ /// Just make the directory if it's the default.
+ /// See FWNX-1092, LT-14491.
+ ///
+ internal static void EnsureValidLinkedFilesFolderCore(string linkedFilesFolder, string defaultLinkedFilesFolder)
+ {
+ if (linkedFilesFolder == defaultLinkedFilesFolder)
+ FileUtils.EnsureDirectoryExists(defaultLinkedFilesFolder);
}
/// ------------------------------------------------------------------------------------
@@ -1187,7 +1250,7 @@ private static ProjectId DetermineProject(FwAppArgs args)
// If we try to use command-line arguments and it fails, we will use the Welcome dialog
// to help the user figure out what to do next.
var projId = new ProjectId(args.DatabaseType, args.Database, args.Server);
- FwStartupException projectOpenError;
+ StartupException projectOpenError;
if (TryCommandLineOption(projId, out projectOpenError))
return projId;
@@ -1210,7 +1273,7 @@ private static ProjectId DetermineProject(FwAppArgs args)
else if (previousStartupStatus == StartupStatus.Failed && !string.IsNullOrEmpty(latestProject))
{
// The previous project failed to open, so notify the user.
- projectOpenError = new FwStartupException(String.Format(
+ projectOpenError = new StartupException(String.Format(
Properties.Resources.kstidUnableToOpenLastProject, app.ApplicationName,
latestProject));
}
@@ -1244,10 +1307,10 @@ private static ProjectId GetBestGuessProjectId(string latestProject, string late
if (!File.Exists(projId.Path))
{
string altProject;
- if (Path.GetExtension(latestProject) == FwFileExtensions.ksFwDataXmlFileExtension)
- altProject = Path.ChangeExtension(latestProject, FwFileExtensions.ksFwDataDb4oFileExtension);
+ if (Path.GetExtension(latestProject) == FdoFileHelper.ksFwDataXmlFileExtension)
+ altProject = Path.ChangeExtension(latestProject, FdoFileHelper.ksFwDataDb4oFileExtension);
else
- altProject = Path.ChangeExtension(latestProject, FwFileExtensions.ksFwDataXmlFileExtension);
+ altProject = Path.ChangeExtension(latestProject, FdoFileHelper.ksFwDataXmlFileExtension);
projId = new ProjectId(altProject, latestServer);
}
}
@@ -1262,15 +1325,15 @@ private static ProjectId GetBestGuessProjectId(string latestProject, string late
///
///
///
- private static bool TryCommandLineOption(ProjectId projId, out FwStartupException exception)
+ private static bool TryCommandLineOption(ProjectId projId, out StartupException exception)
{
exception = null;
if (string.IsNullOrEmpty(projId.Name))
return false;
var ex = projId.GetExceptionIfInvalid();
- if (ex is FwStartupException)
+ if (ex is StartupException)
{
- exception = (FwStartupException) ex;
+ exception = (StartupException) ex;
return false; // Invalid command-line arguments supplied.
}
if (ex == null)
@@ -1321,7 +1384,7 @@ private static bool LaunchProject(FwAppArgs args, ref ProjectId projectId)
{
return InitializeFirstApp(app, projectId);
}
- catch (FwStartupException e)
+ catch (StartupException e)
{
if (s_cache != null)
{
@@ -1525,7 +1588,7 @@ private static void ProjectNameChanged(FdoCache sender)
/// ------------------------------------------------------------------------------------
[SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
Justification="startingApp is a reference")]
- private static ProjectId ShowWelcomeDialog(FwAppArgs args, FwApp startingApp, ProjectId lastProjectId, FwStartupException exception)
+ private static ProjectId ShowWelcomeDialog(FwAppArgs args, FwApp startingApp, ProjectId lastProjectId, StartupException exception)
{
CloseSplashScreen();
@@ -1614,7 +1677,7 @@ private static ProjectId ShowWelcomeDialog(FwAppArgs args, FwApp startingApp, Pr
if (projectToTry != null)
projectToTry.AssertValid();
}
- catch (FwStartupException e)
+ catch (StartupException e)
{
exception = e;
}
@@ -1727,7 +1790,16 @@ internal static ProjectId ChooseLangProject(Form dialogOwner, IHelpTopicProvider
PropertyTable.SettingsGroup.LocalSettings);
}
}
- return dlg.DialogResult != DialogResult.OK ? null : new ProjectId(dlg.Project, dlg.Server);
+
+ if (dlg.DialogResult == DialogResult.OK)
+ {
+ var projId = new ProjectId(dlg.Project, dlg.Server);
+ if (IsSharedXmlBackendNeeded(projId))
+ projId.Type = FDOBackendProviderType.kSharedXML;
+ return projId;
+ }
+
+ return null;
}
}
@@ -1835,7 +1907,7 @@ internal static string BackupProject(Form dialogOwner, FwApp fwApp)
internal static void RestoreProject(Form dialogOwner, string backupFile)
{
BackupFileSettings settings = null;
- if (!ProjectRestoreService.HandleRestoreFileErrors(null, FwUtils.ksSuiteName, backupFile,
+ if (!RestoreProjectDlg.HandleRestoreFileErrors(null, FwUtils.ksSuiteName, backupFile,
() => settings = new BackupFileSettings(backupFile, true)))
{
return;
@@ -1913,7 +1985,7 @@ internal static void FileProjectSharingLocation(Form dialogOwner, FwApp fwApp)
return;
string projectPath = fwApp.Cache.ProjectId.Path;
string parentDirectory = Path.GetDirectoryName(fwApp.Cache.ProjectId.ProjectFolder);
- string projectsDirectory = DirectoryFinder.ProjectsDirectory;
+ string projectsDirectory = FwDirectoryFinder.ProjectsDirectory;
if (!MiscUtils.IsUnix)
{
parentDirectory = parentDirectory.ToLowerInvariant();
@@ -1927,7 +1999,7 @@ internal static void FileProjectSharingLocation(Form dialogOwner, FwApp fwApp)
if (!ClientServerServices.Current.Local.ShareMyProjects)
UpdateProjectsLocation(dlg.ProjectsFolder, fwApp, projectPath);
if (!MiscUtils.IsUnix)
- projectsDirectory = DirectoryFinder.ProjectsDirectory.ToLowerInvariant();
+ projectsDirectory = FwDirectoryFinder.ProjectsDirectory.ToLowerInvariant();
if (UpdateProjectsSharing(true, dialogOwner, fwApp, projectPath, parentDirectory, projectsDirectory))
{
using (var dlgShare = new ShareProjectsFolderDlg())
@@ -1973,7 +2045,7 @@ private static bool UpdateProjectsSharing(bool fShareProjects, Form dialogOwner
{
// We aren't going to convert this one, so no complication to just switching it.
// Both these setters check and do nothing if not changed.
- using (var progressDlg = new ProgressDialogWithTask(null, s_threadHelper))
+ using (var progressDlg = new ProgressDialogWithTask(s_threadHelper))
{
return ClientServerServices.Current.Local.SetProjectSharing(fShareProjects, progressDlg);
}
@@ -1982,7 +2054,7 @@ private static bool UpdateProjectsSharing(bool fShareProjects, Form dialogOwner
bool fSuccess = false;
ExecuteWithAllFwProcessesShutDown(GetCommandLineAbbrevForAppName(fwApp.ApplicationName), () =>
{
- using (var progressDlg = new ProgressDialogWithTask(null, s_threadHelper))
+ using (var progressDlg = new ProgressDialogWithTask(s_threadHelper))
{
fSuccess = ClientServerServices.Current.Local.SetProjectSharing(fShareProjects, progressDlg);
}
@@ -2002,7 +2074,7 @@ private static bool UpdateProjectsSharing(bool fShareProjects, Form dialogOwner
private static void UpdateProjectsLocation(string newFolderForProjects, FwApp fwApp,
string projectPath)
{
- if (newFolderForProjects == null || newFolderForProjects == DirectoryFinder.ProjectsDirectory ||
+ if (newFolderForProjects == null || newFolderForProjects == FwDirectoryFinder.ProjectsDirectory ||
!FileUtils.EnsureDirectoryExists(newFolderForProjects))
return;
@@ -2011,10 +2083,10 @@ private static void UpdateProjectsLocation(string newFolderForProjects, FwApp fw
{
fMoveFiles = dlg.ShowDialog(fwApp.ActiveMainWindow) == DialogResult.Yes;
}
- string oldFolderForProjects = DirectoryFinder.ProjectsDirectory;
+ string oldFolderForProjects = FwDirectoryFinder.ProjectsDirectory;
try
{
- DirectoryFinder.ProjectsDirectory = newFolderForProjects;
+ FwDirectoryFinder.ProjectsDirectory = newFolderForProjects;
}
catch (Exception)
{
@@ -2130,7 +2202,7 @@ private static ProjectId MoveProjectFolders(string oldFolderForProjects, string
{
List rgErrors = new List();
bool fCopy = MustCopyFoldersAndFiles(oldFolderForProjects, newFolderForProjects);
- using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(null, s_threadHelper))
+ using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(s_threadHelper))
{
string[] subDirs = Directory.GetDirectories(oldFolderForProjects);
progressDlg.Maximum = subDirs.Length;
@@ -2219,7 +2291,7 @@ private static ProjectId MoveProjectFolders(string oldFolderForProjects, string
{
if (projectPath.StartsWith(oldFolderForProjects))
{
- // This is perhaps a temporary workaround. On Linux, DirectoryFinder.ProjectsDirectory
+ // This is perhaps a temporary workaround. On Linux, FwDirectoryFinder.ProjectsDirectory
// isn't returning the updated value, but rather the original value. This seems to
// last for the duration of the program, but if you exit and restart the program, it
// gets the correct (updated) value!?
@@ -2250,12 +2322,12 @@ private static bool IsFieldWorksProjectFolder(string projectFolder)
{
var projectName = Path.GetFileName(projectFolder);
// If it contains a matching fwdata file it is a project folder.
- var projectFileName = Path.ChangeExtension(Path.Combine(projectFolder, projectName), FwFileExtensions.ksFwDataXmlFileExtension);
+ var projectFileName = Path.ChangeExtension(Path.Combine(projectFolder, projectName), FdoFileHelper.ksFwDataXmlFileExtension);
if(File.Exists(projectFileName))
return true;
// Just in case some project didn't get converted back to fwdata before we ask this question,
// allow folders containing fwdb files, too.
- projectFileName = Path.ChangeExtension(projectFileName, FwFileExtensions.ksFwDataDb4oFileExtension);
+ projectFileName = Path.ChangeExtension(projectFileName, FdoFileHelper.ksFwDataDb4oFileExtension);
if (File.Exists(projectFileName))
return true;
return false;
@@ -2263,7 +2335,7 @@ private static bool IsFieldWorksProjectFolder(string projectFolder)
private static bool IsFieldWorksSettingsFolder(string projectFolder)
{
- var settingsDir = Path.Combine(projectFolder, DirectoryFinder.ksConfigurationSettingsDir);
+ var settingsDir = Path.Combine(projectFolder, FdoFileHelper.ksConfigurationSettingsDir);
if (Directory.Exists(settingsDir))
return true;
return false;
@@ -2325,7 +2397,7 @@ private static bool MigrateProjectsTo70()
// TODO (TimS): We should probably put FW into single process mode for these
// migrations. It would probably be very bad to have two processes attempting to
// do migrations at the same time.
- ProcessStartInfo info = new ProcessStartInfo(DirectoryFinder.MigrateSqlDbsExe);
+ ProcessStartInfo info = new ProcessStartInfo(FwDirectoryFinder.MigrateSqlDbsExe);
info.UseShellExecute = false;
using (Process proc = Process.Start(info))
{
@@ -2447,10 +2519,9 @@ private static void RestoreCurrentProject(FwRestoreProjectSettings restoreSettin
retry = false;
try
{
- ProjectRestoreService restoreService = new ProjectRestoreService(restoreSettings.Settings,
- GetHelpTopicProvider(restoreSettings.FwAppCommandLineAbbrev));
+ var restoreService = new ProjectRestoreService(restoreSettings.Settings, s_ui, FwDirectoryFinder.ConverterConsoleExe, FwDirectoryFinder.DbExe);
Logger.WriteEvent("Restoring from " + restoreSettings.Settings.Backup.File);
- if (ProjectRestoreService.HandleRestoreFileErrors(null, ResourceHelper.GetResourceString("ksRestoreFailed"),
+ if (RestoreProjectDlg.HandleRestoreFileErrors(null, ResourceHelper.GetResourceString("ksRestoreFailed"),
restoreSettings.Settings.Backup.File, () => DoRestore(restoreService)))
{
s_LinkDirChangedTo = restoreService.LinkDirChangedTo;
@@ -2458,6 +2529,10 @@ private static void RestoreCurrentProject(FwRestoreProjectSettings restoreSettin
new ProjectId(ClientServerServices.Current.Local.IdForLocalProject(restoreSettings.Settings.ProjectName), null);
}
}
+ catch (CannotConvertException e)
+ {
+ MessageBoxUtils.Show(e.Message, ResourceHelper.GetResourceString("ksRestoreFailed"));
+ }
catch (MissingOldFwException e)
{
using (var dlg = new MissingOldFieldWorksDlg(restoreSettings.Settings,
@@ -2468,6 +2543,7 @@ private static void RestoreCurrentProject(FwRestoreProjectSettings restoreSettin
}
catch (FailedFwRestoreException e)
{
+ MessageBoxUtils.Show(Properties.Resources.ksRestoringOldFwBackupFailed, Properties.Resources.ksFailed);
}
}
while (retry);
@@ -2484,7 +2560,7 @@ private static void RestoreCurrentProject(FwRestoreProjectSettings restoreSettin
/// ------------------------------------------------------------------------------------
private static void DoRestore(ProjectRestoreService restoreService)
{
- using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(null, s_threadHelper))
+ using (var progressDlg = new ProgressDialogWithTask(s_threadHelper))
restoreService.RestoreProject(progressDlg);
}
@@ -2505,20 +2581,26 @@ private static void DoRestore(ProjectRestoreService restoreService)
private static bool BackupProjectForRestore(FwRestoreProjectSettings restoreSettings,
FdoCache existingCache, Form dialogOwner)
{
- using (var progressDlg = new ProgressDialogWithTask(dialogOwner, s_threadHelper))
+ using (var progressDlg = new ProgressDialogWithTask(dialogOwner))
{
FdoCache cache = existingCache ?? FdoCache.CreateCacheFromExistingData(
new ProjectId(restoreSettings.Settings.FullProjectPath, null),
- s_sWsUser, progressDlg);
+ s_sWsUser, s_ui, FwDirectoryFinder.FdoDirectories, progressDlg);
try
{
- BackupProjectSettings settings = new BackupProjectSettings(cache, restoreSettings.Settings);
- settings.DestinationFolder = DirectoryFinder.DefaultBackupDirectory;
+ BackupProjectSettings settings = new BackupProjectSettings(cache, restoreSettings.Settings, FwDirectoryFinder.DefaultBackupDirectory);
+ settings.DestinationFolder = FwDirectoryFinder.DefaultBackupDirectory;
settings.AppAbbrev = restoreSettings.FwAppCommandLineAbbrev;
ProjectBackupService backupService = new ProjectBackupService(cache, settings);
- backupService.BackupProject(progressDlg);
+ string backupFile;
+ if (!backupService.BackupProject(progressDlg, out backupFile))
+ {
+ string msg = string.Format(FwCoreDlgs.FwCoreDlgs.ksCouldNotBackupSomeFiles, backupService.FailedFiles.ToString(", ", Path.GetFileName));
+ if (MessageBox.Show(msg, FwCoreDlgs.FwCoreDlgs.ksWarning, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
+ File.Delete(backupFile);
+ }
}
catch (FwBackupException e)
{
@@ -2681,7 +2763,7 @@ private static void CheckForMovingExternalLinkDirectory(FwApp app)
if (oldDir == null)
{
// e.g. "C:\\ProgramData\\SIL\\FieldWorks"
- oldDir = DirectoryFinder.CommonAppDataFolder("SIL/FieldWorks");
+ oldDir = DirectoryFinder.CommonAppDataFolder("FieldWorks");
}
oldDir = oldDir.TrimEnd(new [] {Path.PathSeparator});
var newDir = app.Cache.LangProject.LinkedFilesRootDir;
@@ -2725,7 +2807,7 @@ private static void MoveExternalLinkDirectoryAndFiles(FwApp app)
var sLinkedFilesRootDir = app.Cache.LangProject.LinkedFilesRootDir;
NonUndoableUnitOfWorkHelper.Do(app.Cache.ActionHandlerAccessor, () =>
{
- app.Cache.LangProject.LinkedFilesRootDir = DirectoryFinder.GetDefaultLinkedFilesDir(
+ app.Cache.LangProject.LinkedFilesRootDir = FdoFileHelper.GetDefaultLinkedFilesDir(
app.Cache.ProjectId.ProjectFolder);
});
app.UpdateExternalLinks(sLinkedFilesRootDir);
@@ -2798,7 +2880,7 @@ internal static bool CreateAndInitNewMainWindow(FwApp app, bool fNewCache, Form
// so just record it now as the active one.
s_activeMainWnd = (IFwMainWnd)fwMainWindow;
}
- catch (FwStartupException ex)
+ catch (StartupException ex)
{
// REVIEW: Can this actually happen when just creating a new main window?
CloseSplashScreen();
@@ -2877,7 +2959,7 @@ internal static void KickOffAppFromOtherProcess(FwAppArgs args)
if (s_appServerMode)
{
// Make sure the cache is initialized for the application.
- using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(null, s_threadHelper))
+ using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(s_threadHelper))
InitializeApp(app, dlg);
return;
}
@@ -2905,7 +2987,7 @@ internal static void KickOffAppFromOtherProcess(FwAppArgs args)
else
{
// Make sure the cache is initialized for the application
- using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(otherApp.ActiveMainWindow, s_threadHelper))
+ using (var dlg = new ProgressDialogWithTask(otherApp.ActiveMainWindow))
InitializeApp(app, dlg);
}
});
@@ -2933,7 +3015,7 @@ private static FwApp GetOrCreateApplication(FwAppArgs args)
{
if (s_teApp == null)
{
- s_teApp = (FwApp)DynamicLoader.CreateObject(DirectoryFinder.TeDll,
+ s_teApp = (FwApp)DynamicLoader.CreateObject(FwDirectoryFinder.TeDll,
FwUtils.ksFullTeAppObjectName, s_fwManager, GetHelpTopicProvider(appAbbrev), args);
s_teAppKey = s_teApp.SettingsKey;
}
@@ -2946,7 +3028,7 @@ private static FwApp GetOrCreateApplication(FwAppArgs args)
{
if (s_flexApp == null)
{
- s_flexApp = (FwApp)DynamicLoader.CreateObject(DirectoryFinder.FlexDll,
+ s_flexApp = (FwApp)DynamicLoader.CreateObject(FwDirectoryFinder.FlexDll,
FwUtils.ksFullFlexAppObjectName, s_fwManager, GetHelpTopicProvider(appAbbrev), args);
s_flexAppKey = s_flexApp.SettingsKey;
}
@@ -3032,7 +3114,7 @@ private static bool InitializeFirstApp(FwApp app, ProjectId projectId)
sparkle.AboutToExitForInstallerRun += delegate(object sender, CancelEventArgs args)
{
CloseAllMainWindows();
- if(app.ActiveMainWindow != null)
+ if (app.ActiveMainWindow != null)
{
args.Cancel = true;
}
@@ -3043,6 +3125,21 @@ private static bool InitializeFirstApp(FwApp app, ProjectId projectId)
return true;
}
}
+ catch (UnauthorizedAccessException uae)
+ {
+ if (MiscUtils.IsUnix)
+ {
+ // Tell Mono user he/she needs to logout and log back in
+ MessageBox.Show(ResourceHelper.GetResourceString("ksNeedToJoinFwGroup"));
+ }
+ throw;
+ }
+ catch (FdoDataMigrationForbiddenException)
+ {
+ // tell the user to close all other applications using this project
+ MessageBox.Show(ResourceHelper.GetResourceString("kstidDataMigrationProhibitedText"),
+ ResourceHelper.GetResourceString("kstidDataMigrationProhibitedCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
+ }
finally
{
CloseSplashScreen();
@@ -3060,7 +3157,7 @@ private static bool InitializeFirstApp(FwApp app, ProjectId projectId)
/// The progress dialog.
/// True if the application was started successfully, false otherwise
/// ------------------------------------------------------------------------------------
- private static bool InitializeApp(FwApp app, IProgress progressDlg)
+ private static bool InitializeApp(FwApp app, IThreadedProgress progressDlg)
{
using (new DataUpdateMonitor(null, "Application Initialization"))
app.DoApplicationInitialization(progressDlg);
@@ -3074,13 +3171,13 @@ private static bool InitializeApp(FwApp app, IProgress progressDlg)
try
{
if (!app.InitCacheForApp(progressDlg))
- throw new FwStartupException(Properties.Resources.kstidCacheInitFailure);
+ throw new StartupException(Properties.Resources.kstidCacheInitFailure);
}
catch (Exception e)
{
- if (e is FwStartupException)
+ if (e is StartupException)
throw;
- throw new FwStartupException(Properties.Resources.kstidCacheInitFailure, e, true);
+ throw new StartupException(Properties.Resources.kstidCacheInitFailure, e, true);
}
undoHelper.RollBack = false;
}
@@ -3090,11 +3187,11 @@ private static bool InitializeApp(FwApp app, IProgress progressDlg)
if (progressDlg != null)
{
progressDlg.Message = String.Format(Properties.Resources.kstidSaving, s_cache.ProjectId.UiName);
- progressDlg.ProgressBarStyle = ProgressBarStyle.Marquee;
+ progressDlg.IsIndeterminate = true;
}
s_cache.ServiceLocator.GetInstance().Save();
if (progressDlg != null)
- progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous;
+ progressDlg.IsIndeterminate = false;
}
return CreateAndInitNewMainWindow(app, true, null, false);
@@ -3193,7 +3290,7 @@ private static string GetDefaultApp(FwAppArgs args)
if (!Directory.Exists(projectFolder))
return FwUtils.ksFlexAbbrev; // got to do something
- var settingsFolder = Path.Combine(projectFolder, DirectoryFinder.ksConfigurationSettingsDir);
+ var settingsFolder = Path.Combine(projectFolder, FdoFileHelper.ksConfigurationSettingsDir);
if (!Directory.Exists(settingsFolder))
return FwUtils.ksFlexAbbrev; // no settings at all, take the default.
@@ -3217,7 +3314,7 @@ private static void RecordLastAppForProject()
if (s_flexApp != null && s_teApp != null)
return; // this isn't the last one to shut down, not time to record.
- var settingsFolder = Path.Combine(Cache.ProjectId.ProjectFolder, DirectoryFinder.ksConfigurationSettingsDir);
+ var settingsFolder = Path.Combine(Cache.ProjectId.ProjectFolder, FdoFileHelper.ksConfigurationSettingsDir);
var teMarkerPath = Path.Combine(settingsFolder, ksTeOpenMarkerFileName);
try
{
@@ -3480,7 +3577,6 @@ private static RemoteRequest CreateRequestor(int port, string requestType)
private static void StaticDispose()
{
s_appServerMode = false; // Make sure the cache can be cleaned up
- LexicalProviderManager.StaticDispose(); // Must be done before disposing the cache
if (s_serviceChannel != null)
{
ChannelServices.UnregisterChannel(s_serviceChannel);
@@ -3536,10 +3632,10 @@ internal static IHelpTopicProvider GetHelpTopicProvider(string appAbbrev)
if ((appAbbrev.Equals(FwUtils.ksTeAbbrev, StringComparison.InvariantCultureIgnoreCase) && FwUtils.IsTEInstalled) ||
!FwUtils.IsFlexInstalled)
{
- return s_teApp ?? (IHelpTopicProvider)DynamicLoader.CreateObject(DirectoryFinder.TeDll,
+ return s_teApp ?? (IHelpTopicProvider)DynamicLoader.CreateObject(FwDirectoryFinder.TeDll,
"SIL.FieldWorks.TE.TeHelpTopicProvider");
}
- return s_flexApp ?? (IHelpTopicProvider)DynamicLoader.CreateObject(DirectoryFinder.FlexDll,
+ return s_flexApp ?? (IHelpTopicProvider)DynamicLoader.CreateObject(FwDirectoryFinder.FlexDll,
"SIL.FieldWorks.XWorks.LexText.FlexHelpTopicProvider");
}
@@ -3844,12 +3940,12 @@ private static void ExitCleanly()
{
DataUpdateMonitor.ClearSemaphore();
- using (var progressDlg = new ProgressDialogWithTask(null, s_threadHelper))
+ using (var progressDlg = new ProgressDialogWithTask(s_threadHelper))
{
progressDlg.Title = string.Format(ResourceHelper.GetResourceString("kstidShutdownCaption"),
s_cache.ProjectId.UiName);
progressDlg.AllowCancel = false;
- progressDlg.ProgressBarStyle = ProgressBarStyle.Marquee;
+ progressDlg.IsIndeterminate = true;
var stackMgr = s_cache.ServiceLocator.GetInstance();
if (stackMgr.HasUnsavedChanges)
progressDlg.RunTask(true, CommitAndDisposeCache);
diff --git a/Src/Common/FieldWorks/FieldWorks.csproj b/Src/Common/FieldWorks/FieldWorks.csproj
index 65ae5049c2..5f66aade27 100644
--- a/Src/Common/FieldWorks/FieldWorks.csproj
+++ b/Src/Common/FieldWorks/FieldWorks.csproj
@@ -127,6 +127,10 @@
False
..\..\..\Downloads\PalasoUIWindowsForms.dll
+
+ False
+ ..\..\..\Output\Debug\ParatextShared.dll
+
False
..\..\..\DistFiles\PaToFdoInterfaces.dll
@@ -139,6 +143,10 @@
False
..\..\..\Output\Debug\RootSite.dll
+
+ False
+ ..\..\..\Output\Debug\ScriptureUtils.dll
+
False
..\..\..\Output\Debug\SilUtils.dll
@@ -200,9 +208,6 @@
-
-
-
Form
@@ -221,7 +226,6 @@
-
diff --git a/Src/Common/FieldWorks/FieldWorksManager.cs b/Src/Common/FieldWorks/FieldWorksManager.cs
index 818d9f734e..91698d8eae 100644
--- a/Src/Common/FieldWorks/FieldWorksManager.cs
+++ b/Src/Common/FieldWorks/FieldWorksManager.cs
@@ -12,7 +12,7 @@
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO;
using System.Windows.Forms;
-using XCore;
+using SIL.Utils;
namespace SIL.FieldWorks
{
diff --git a/Src/Common/FieldWorks/FieldWorksTests/FieldWorksTests.cs b/Src/Common/FieldWorks/FieldWorksTests/FieldWorksTests.cs
index 71fe5d7943..25a7115cec 100644
--- a/Src/Common/FieldWorks/FieldWorksTests/FieldWorksTests.cs
+++ b/Src/Common/FieldWorks/FieldWorksTests/FieldWorksTests.cs
@@ -5,8 +5,10 @@
// File: FieldWorksTests.cs
// Responsibility: FW Team
// ---------------------------------------------------------------------------------------------
+using System;
using NUnit.Framework;
-using SIL.FieldWorks.Common.FwUtils;
+using SIL.FieldWorks.FDO;
+using SIL.FieldWorks.FDO.FDOTests;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
@@ -20,6 +22,14 @@ namespace SIL.FieldWorks
[TestFixture]
public class FieldWorksTests : BaseTest
{
+ /// Setup for FieldWorks tests.
+ public override void FixtureSetup()
+ {
+ base.FixtureSetup();
+
+ FdoTestHelper.SetupClientServerServices();
+ }
+
#region GetProjectMatchStatus tests
/// ------------------------------------------------------------------------------------
///
@@ -114,5 +124,83 @@ public void GetProjectMatchStatus_SingleProcessMode()
#endregion
+ ///
+ [Test]
+ public void EnsureValidLinkedFilesFolderCore_IfUsingDefaultDir_CreatesDirIfNotExist()
+ {
+ EnsureValidLinkedFilesFolderCore_TestHelper(defaultFolder => {
+ var configuredFolder = defaultFolder;
+ Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.False, "Unit test not testing what it's supposed to");
+ FieldWorks.EnsureValidLinkedFilesFolderCore(configuredFolder, defaultFolder);
+ Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.True, "Should have created directory");
+ });
+ }
+
+ ///
+ [Test]
+ public void EnsureValidLinkedFilesFolderCore_IfUsingDefaultDirAndItExists_DoesntCrashOrAnything()
+ {
+ EnsureValidLinkedFilesFolderCore_TestHelper(defaultFolder => {
+ // Make default linked files directory already exist
+ FileUtils.EnsureDirectoryExists(defaultFolder);
+
+ // Not crash or anything
+ Assert.DoesNotThrow(() => FieldWorks.EnsureValidLinkedFilesFolderCore(defaultFolder, defaultFolder));
+ });
+ }
+
+ ///
+ [Test]
+ public void EnsureValidLinkedFilesFolderCore_NonDefaultLocation_NotCreateNonExistentDir()
+ {
+ EnsureValidLinkedFilesFolderCore_TestHelper(defaultFolder => {
+ var configuredFolder = FileUtils.ChangePathToPlatform("/nondefaultAndNonexistentPath");
+
+ Assert.That(defaultFolder, Is.Not.EqualTo(configuredFolder), "Unit test not set up right");
+ Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.False, "Unit test not testing what it's supposed to");
+
+ FieldWorks.EnsureValidLinkedFilesFolderCore(configuredFolder, defaultFolder);
+ Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.False, "Shouldn't have just made the nondefault directory");
+ });
+ }
+
+ ///
+ [Test]
+ public void EnsureValidLinkedFilesFolderCore_NonDefaultLocationAndExists_DoesntCrashOrAnything()
+ {
+ EnsureValidLinkedFilesFolderCore_TestHelper(defaultFolder => {
+ var configuredFolder = FileUtils.ChangePathToPlatform("/nondefaultPath");
+
+ // Make linked files directory already exist
+ FileUtils.EnsureDirectoryExists(configuredFolder);
+
+ Assert.That(defaultFolder, Is.Not.EqualTo(configuredFolder), "Unit test not set up right");
+ Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.True, "Unit test not testing what it's supposed to");
+
+ // Not crash or anything
+ FieldWorks.EnsureValidLinkedFilesFolderCore(configuredFolder, defaultFolder);
+ });
+ }
+
+ ///
+ /// Unit test helper to set up environment in which to test EnsureValidLinkedFilesFolderCore.
+ /// testToExecute takes (string defaultFolder, FdoCache cache).
+ ///
+ public void EnsureValidLinkedFilesFolderCore_TestHelper(Action testToExecute)
+ {
+ var defaultFolder = FileUtils.ChangePathToPlatform("/ProjectDir/LinkedFiles");
+
+ var fileOs = new MockFileOS();
+ try
+ {
+ FileUtils.Manager.SetFileAdapter(fileOs);
+
+ testToExecute(defaultFolder);
+ }
+ finally
+ {
+ FileUtils.Manager.Reset();
+ }
+ }
}
}
diff --git a/Src/Common/FieldWorks/FieldWorksTests/FieldWorksTests.csproj b/Src/Common/FieldWorks/FieldWorksTests/FieldWorksTests.csproj
index 881ee50095..78a577aed8 100644
--- a/Src/Common/FieldWorks/FieldWorksTests/FieldWorksTests.csproj
+++ b/Src/Common/FieldWorks/FieldWorksTests/FieldWorksTests.csproj
@@ -72,10 +72,18 @@
False
..\..\..\..\Output\Debug\COMInterfacesTests.dll
+
+ False
+ ..\..\..\..\Output\Debug\CoreImpl.dll
+
False
..\..\..\..\Output\Debug\FDO.dll
+
+ False
+ ..\..\..\..\Output\Debug\FDOTests.dll
+
False
.exe
diff --git a/Src/Common/FieldWorks/FieldWorksTests/ProjectIDTests.cs b/Src/Common/FieldWorks/FieldWorksTests/ProjectIDTests.cs
index dcd19691fa..b7d9147aaf 100644
--- a/Src/Common/FieldWorks/FieldWorksTests/ProjectIDTests.cs
+++ b/Src/Common/FieldWorks/FieldWorksTests/ProjectIDTests.cs
@@ -9,7 +9,9 @@
using System.IO;
using NUnit.Framework;
using Rhino.Mocks;
+using SIL.CoreImpl;
using SIL.FieldWorks.Common.FwUtils;
+using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
@@ -46,17 +48,6 @@ public override void FixtureSetup()
m_localCsSvcs.Stub(cs => cs.DefaultBackendType).Do(new Func( () => m_defaultBepType));
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Fixture teardown.
- ///
- /// ------------------------------------------------------------------------------------
- public override void FixtureTeardown()
- {
- base.FixtureTeardown();
- ReflectionHelper.CallMethod(typeof(ClientServerServices), "SetCurrentToDefaultBackend");
- }
-
/// ------------------------------------------------------------------------------------
///
/// Sets up default member values for each test.
@@ -119,7 +110,7 @@ public void IsValid_BogusType()
public void IsValid_NullType()
{
const string sProjectName = "monkey";
- string sFile = DirectoryFinder.GetXmlDataFileName(sProjectName);
+ string sFile = FdoFileHelper.GetXmlDataFileName(sProjectName);
m_mockFileOs.AddExistingFile(GetXmlProjectFilename(sProjectName));
ProjectId proj = new ProjectId(null, sFile, null);
Assert.AreEqual(FDOBackendProviderType.kXML, proj.Type);
@@ -147,7 +138,7 @@ public void IsValid_XML_False()
public void IsValid_XML_True()
{
const string sProjectName = "monkey";
- string sFile = DirectoryFinder.GetXmlDataFileName(sProjectName);
+ string sFile = FdoFileHelper.GetXmlDataFileName(sProjectName);
m_mockFileOs.AddExistingFile(GetXmlProjectFilename(sProjectName));
ProjectId proj = new ProjectId("xml", sFile, null);
Assert.IsTrue(proj.IsValid);
@@ -193,8 +184,8 @@ public void CleanUpNameForType_EmptyName()
public void CleanUpNameForType_Default_onlyName()
{
m_defaultBepType = FDOBackendProviderType.kDb4oClientServer;
- string expectedPath = Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, "ape"),
- DirectoryFinder.GetDb4oDataFileName("ape"));
+ string expectedPath = Path.Combine(Path.Combine(FwDirectoryFinder.ProjectsDirectory, "ape"),
+ FdoFileHelper.GetDb4oDataFileName("ape"));
m_localCsSvcs.Stub(cs => cs.IdForLocalProject("ape")).Return(expectedPath);
m_mockFileOs.AddExistingFile(expectedPath);
@@ -214,7 +205,7 @@ public void CleanUpNameForType_Default_onlyName()
[Test]
public void CleanUpNameForType_Default_NameWithPeriod_Exists()
{
- string expectedPath = Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, "my.monkey"), "my.monkey");
+ string expectedPath = Path.Combine(Path.Combine(FwDirectoryFinder.ProjectsDirectory, "my.monkey"), "my.monkey");
m_localCsSvcs.Stub(cs => cs.IdForLocalProject("my.monkey")).Return(expectedPath);
m_mockFileOs.AddExistingFile(expectedPath);
@@ -234,8 +225,8 @@ public void CleanUpNameForType_Default_NameWithPeriod_Exists()
[Test]
public void CleanUpNameForType_XML_NameWithPeriod_FilesWithAndWithoutExtensionExist()
{
- string myMonkeyProjectFolder = Path.Combine(DirectoryFinder.ProjectsDirectory, "my.monkey");
- string expectedPath = Path.Combine(myMonkeyProjectFolder, DirectoryFinder.GetXmlDataFileName("my.monkey"));
+ string myMonkeyProjectFolder = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "my.monkey");
+ string expectedPath = Path.Combine(myMonkeyProjectFolder, FdoFileHelper.GetXmlDataFileName("my.monkey"));
m_mockFileOs.AddExistingFile(expectedPath);
m_mockFileOs.AddExistingFile(Path.Combine(myMonkeyProjectFolder, "my.monkey"));
@@ -259,7 +250,7 @@ public void CleanUpNameForType_XML_NameWithPeriod_WithXmlExtension()
string expectedPath = GetXmlProjectFilename(projectName);
m_mockFileOs.AddExistingFile(expectedPath);
- var proj = new ProjectId(DirectoryFinder.GetXmlDataFileName(projectName), null);
+ var proj = new ProjectId(FdoFileHelper.GetXmlDataFileName(projectName), null);
Assert.AreEqual(expectedPath, proj.Path);
Assert.AreEqual(FDOBackendProviderType.kXML, proj.Type);
Assert.IsTrue(proj.IsValid);
@@ -295,7 +286,7 @@ public void CleanUpNameForType_XML_onlyNameWithExtension()
string expectedPath = GetXmlProjectFilename("monkey");
m_mockFileOs.AddExistingFile(expectedPath);
- var proj = new ProjectId(DirectoryFinder.GetXmlDataFileName("monkey"), null);
+ var proj = new ProjectId(FdoFileHelper.GetXmlDataFileName("monkey"), null);
Assert.AreEqual(expectedPath, proj.Path);
Assert.AreEqual(FDOBackendProviderType.kXML, proj.Type);
Assert.IsTrue(proj.IsValid);
@@ -310,7 +301,7 @@ public void CleanUpNameForType_XML_onlyNameWithExtension()
[Test]
public void CleanUpNameForType_XML_FullPath()
{
- string expectedPath = Path.Combine(DirectoryFinder.ProjectsDirectory, DirectoryFinder.GetXmlDataFileName("monkey"));
+ string expectedPath = Path.Combine(FwDirectoryFinder.ProjectsDirectory, FdoFileHelper.GetXmlDataFileName("monkey"));
m_mockFileOs.AddExistingFile(expectedPath);
var proj = new ProjectId(expectedPath, null);
@@ -329,8 +320,8 @@ public void CleanUpNameForType_XML_FullPath()
[Ignore("Not sure what this would be useful for or if this would be the desired behavior.")]
public void CleanUpNameForType_XML_RelativePath()
{
- string relativePath = Path.Combine("primate", DirectoryFinder.GetXmlDataFileName("monkey"));
- string expectedPath = Path.Combine(DirectoryFinder.ProjectsDirectory, relativePath);
+ string relativePath = Path.Combine("primate", FdoFileHelper.GetXmlDataFileName("monkey"));
+ string expectedPath = Path.Combine(FwDirectoryFinder.ProjectsDirectory, relativePath);
m_mockFileOs.AddExistingFile(expectedPath);
ProjectId proj = new ProjectId(relativePath, null);
@@ -352,7 +343,7 @@ public void AssertValid_Valid()
string projFile = GetXmlProjectFilename("monkey");
m_mockFileOs.AddExistingFile(projFile);
- var proj = new ProjectId(DirectoryFinder.GetXmlDataFileName("monkey"), null);
+ var proj = new ProjectId(FdoFileHelper.GetXmlDataFileName("monkey"), null);
proj.AssertValid(); // no exception should be thrown here for a valid project.
}
@@ -371,7 +362,7 @@ public void AssertValid_Invalid_NoName()
proj.AssertValid();
Assert.Fail("FwStartupException expected");
}
- catch (FwStartupException exception)
+ catch (StartupException exception)
{
Assert.IsFalse(exception.ReportToUser);
}
@@ -386,13 +377,13 @@ public void AssertValid_Invalid_NoName()
[Test]
public void AssertValid_Invalid_FileNotFound()
{
- var proj = new ProjectId(DirectoryFinder.GetXmlDataFileName("notfound"), null);
+ var proj = new ProjectId(FdoFileHelper.GetXmlDataFileName("notfound"), null);
try
{
proj.AssertValid();
Assert.Fail("FwStartupException expected");
}
- catch (FwStartupException exception)
+ catch (StartupException exception)
{
Assert.IsTrue(exception.ReportToUser);
}
@@ -407,13 +398,13 @@ public void AssertValid_Invalid_FileNotFound()
[Test]
public void AssertValid_InvalidProjectType()
{
- var proj = new ProjectId(FDOBackendProviderType.kInvalid, DirectoryFinder.GetXmlDataFileName("invalid"), null);
+ var proj = new ProjectId(FDOBackendProviderType.kInvalid, FdoFileHelper.GetXmlDataFileName("invalid"), null);
try
{
proj.AssertValid();
Assert.Fail("FwStartupException expected");
}
- catch (FwStartupException exception)
+ catch (StartupException exception)
{
Assert.IsTrue(exception.ReportToUser);
}
@@ -428,13 +419,13 @@ public void AssertValid_InvalidProjectType()
[Test]
public void AssertValid_Invalid_SharedFolderNotFound()
{
- var proj = new ProjectId(DirectoryFinder.GetDb4oDataFileName("monkey"), FwLinkArgs.kLocalHost);
+ var proj = new ProjectId(FdoFileHelper.GetDb4oDataFileName("monkey"), FwLinkArgs.kLocalHost);
try
{
proj.AssertValid();
Assert.Fail("FwStartupException expected");
}
- catch (FwStartupException exception)
+ catch (StartupException exception)
{
Assert.IsTrue(exception.ReportToUser);
}
@@ -451,12 +442,12 @@ public void AssertValid_Invalid_SharedFolderNotFound()
[Test]
public void CheckProperties()
{
- string expectedProjectDir = Path.Combine(DirectoryFinder.ProjectsDirectory, "SomeTest");
+ string expectedProjectDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "SomeTest");
m_mockFileOs.ExistingDirectories.Add(expectedProjectDir);
const string type = "db4ocs";
const string host = "127.0.0.1";
- string filename = DirectoryFinder.GetDb4oDataFileName("SomeTest");
+ string filename = FdoFileHelper.GetDb4oDataFileName("SomeTest");
var proj = new ProjectId(type, filename, host);
proj.AssertValid();
@@ -475,13 +466,13 @@ public void CheckProperties()
[Test]
public void NameAndPath()
{
- string myProjectFolder = Path.Combine(DirectoryFinder.ProjectsDirectory, "My.Project");
+ string myProjectFolder = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "My.Project");
ProjectId projId = new ProjectId(FDOBackendProviderType.kXML, "My.Project", null);
- Assert.AreEqual(Path.Combine(myProjectFolder, DirectoryFinder.GetXmlDataFileName("My.Project")), projId.Path);
+ Assert.AreEqual(Path.Combine(myProjectFolder, FdoFileHelper.GetXmlDataFileName("My.Project")), projId.Path);
Assert.AreEqual("My.Project", projId.Name);
projId = new ProjectId(FDOBackendProviderType.kDb4oClientServer, "My.Project", null);
- Assert.AreEqual(Path.Combine(myProjectFolder, DirectoryFinder.GetDb4oDataFileName("My.Project")), projId.Path);
+ Assert.AreEqual(Path.Combine(myProjectFolder, FdoFileHelper.GetDb4oDataFileName("My.Project")), projId.Path);
Assert.AreEqual("My.Project", projId.Name);
}
@@ -497,8 +488,8 @@ public void NameAndPath()
/// ------------------------------------------------------------------------------------
public static string GetXmlProjectFilename(string projectName)
{
- return Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, projectName),
- DirectoryFinder.GetXmlDataFileName(projectName));
+ return Path.Combine(Path.Combine(FwDirectoryFinder.ProjectsDirectory, projectName),
+ FdoFileHelper.GetXmlDataFileName(projectName));
}
#endregion
}
diff --git a/Src/Common/FieldWorks/LexicalProvider/ILexicalProvider.cs b/Src/Common/FieldWorks/LexicalProvider/ILexicalProvider.cs
deleted file mode 100644
index 132516e556..0000000000
--- a/Src/Common/FieldWorks/LexicalProvider/ILexicalProvider.cs
+++ /dev/null
@@ -1,321 +0,0 @@
-// Copyright (c) 2011-2013 SIL International
-// This software is licensed under the LGPL, version 2.1 or later
-// (http://www.gnu.org/licenses/lgpl-2.1.html)
-//
-// File: ILexicalProvider.cs
-// Responsibility: FW Team
-//
-//
-//
-
-using System;
-using System.Collections.Generic;
-using System.Runtime.Serialization;
-using System.ServiceModel;
-
-namespace SIL.FieldWorks.LexicalProvider
-{
- #region ILexicalServiceProvider interface
- /// ----------------------------------------------------------------------------------------
- ///
- /// Provides a service contract for getting a lexical provider from an application.
- /// WARNING: Paratext contains its own identical definition of these interfaces.
- /// Any change must be coordinated (both in corresponding source files and in terms
- /// of product release schedules.
- ///
- /// ----------------------------------------------------------------------------------------
- [ServiceContract]
- public interface ILexicalServiceProvider
- {
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the location for the provider for the specified project and
- /// provider type. If the providerType is not supported, return null for the Uri.
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- Uri GetProviderLocation(string projhandle, string providerType);
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the version of the specified provider that the server supports. If the
- /// providerType is not supported, return 0 for the version.
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- int GetSupportedVersion(string providerType);
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Unlike a normal ping method that gets a response, we just use this ping method
- /// to determine if the service provider is actually valid since no exception is
- /// thrown until a method is called.
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- void Ping();
- }
- #endregion
-
- #region ILexicalProvider interface
- /// ----------------------------------------------------------------------------------------
- ///
- /// Provides a service contract for accessing lexical data from other applications.
- ///
- /// ----------------------------------------------------------------------------------------
- [ServiceContract]
- public interface ILexicalProvider
- {
- /// ------------------------------------------------------------------------------------
- ///
- /// Displays the specified entry using the application with the lexical data.
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- void ShowEntry(string entry, EntryType entryType);
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Displays the related words using the application with the lexical data.
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- void ShowRelatedWords(string entry, EntryType entryType);
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets all lexemes in the Lexicon
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- IEnumerable Lexemes();
-
- ///
- /// Looks up an lexeme in the lexicon
- ///
- [OperationContract]
- LexicalEntry GetLexeme(LexemeType type, string lexicalForm, int homograph);
-
- ///
- /// Adds the lexeme to the lexicon.
- ///
- /// if matching lexeme is already in lexicon
- [OperationContract]
- void AddLexeme(LexicalEntry lexeme);
-
- ///
- /// Adds a new sense to the lexeme with the specified information
- ///
- [OperationContract]
- LexSense AddSenseToEntry(LexemeType type, string lexicalForm, int homograph);
-
- ///
- /// Adds a new gloss to the sense with the specified information
- ///
- [OperationContract]
- LexGloss AddGlossToSense(LexemeType type, string lexicalForm, int homograph, string senseId, string language, string text);
-
- ///
- /// Removes the gloss with the specified language form the sense with the specified information
- ///
- [OperationContract]
- void RemoveGloss(LexemeType type, string lexicalForm, int homograph, string senseId, string language);
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Forces a save of lexicon
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- void Save();
-
- /// ------------------------------------------------------------------------------------
- ///
- /// This must be called before entries are changed to ensure that
- /// it is saved to disk. Since the lexicon is a complex structure
- /// and other features depend on knowing when it is changed,
- /// all work done with the lexicon is marked with a begin and
- /// end change.
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- void BeginChange();
-
- /// ------------------------------------------------------------------------------------
- ///
- /// This must be called after entries are changed to ensure that
- /// other features dependent on the lexicon are made aware of the
- /// change.
- ///
- /// ------------------------------------------------------------------------------------
- [OperationContract]
- void EndChange();
- }
- #endregion
-
- #region EntryType enumeration
- /// ----------------------------------------------------------------------------------------
- ///
- /// Types of lexical entries that can be requested by a client of a LexicalProvider
- ///
- /// ----------------------------------------------------------------------------------------
- public enum EntryType
- {
- /// entry represents a word
- Word
- }
- #endregion
-
- #region LexemeType enumeration
- /// ----------------------------------------------------------------------------------------
- ///
- /// All known lexeme types
- ///
- /// ----------------------------------------------------------------------------------------
- public enum LexemeType
- {
- ///
- Phrase,
- ///
- Word,
- ///
- Lemma,
- ///
- Stem,
- ///
- Prefix,
- ///
- Suffix
- };
- #endregion
-
- #region LexicalEntry class
- /// ----------------------------------------------------------------------------------------
- ///
- /// Data contract used by WCF for holding information about a Lexeme
- ///
- /// ----------------------------------------------------------------------------------------
- [DataContract(Namespace = "LexicalData")]
- public sealed class LexicalEntry
- {
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes a new instance of the class.
- ///
- /// ------------------------------------------------------------------------------------
- public LexicalEntry(LexemeType type, string form, int homograph)
- {
- Type = type;
- LexicalForm = form;
- Homograph = homograph;
- Senses = new List();
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the type.
- ///
- /// ------------------------------------------------------------------------------------
- [DataMember]
- public LexemeType Type { get; private set; }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the lexical form.
- ///
- /// ------------------------------------------------------------------------------------
- [DataMember]
- public string LexicalForm { get; private set; }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the homograph.
- ///
- /// ------------------------------------------------------------------------------------
- [DataMember]
- public int Homograph { get; private set; }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the senses.
- ///
- /// ------------------------------------------------------------------------------------
- [DataMember]
- public IList Senses { get; set; }
- }
- #endregion
-
- #region LexSense class
- /// ----------------------------------------------------------------------------------------
- ///
- /// Data contract used by WCF for holding information about a Sense
- ///
- /// ----------------------------------------------------------------------------------------
- [DataContract(Namespace = "LexicalData")]
- public sealed class LexSense
- {
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes a new instance of the class.
- ///
- /// ------------------------------------------------------------------------------------
- public LexSense(string id)
- {
- Id = id;
- Glosses = new List();
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the id.
- ///
- /// ------------------------------------------------------------------------------------
- [DataMember]
- public string Id { get; private set; }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the glosses.
- ///
- /// ------------------------------------------------------------------------------------
- [DataMember]
- public IList Glosses { get; set; }
- }
- #endregion
-
- #region LexGloss class
- ///
- /// Data contract used by WCF for holding information about a Gloss
- ///
- [DataContract(Namespace = "LexicalData")]
- public sealed class LexGloss
- {
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes a new instance of the class.
- ///
- /// ------------------------------------------------------------------------------------
- public LexGloss(string language, string text)
- {
- Language = language;
- Text = text;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the language.
- ///
- /// ------------------------------------------------------------------------------------
- [DataMember]
- public string Language { get; private set; }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the text.
- ///
- /// ------------------------------------------------------------------------------------
- [DataMember]
- public string Text { get; private set; }
- }
- #endregion
-}
diff --git a/Src/Common/FieldWorks/LexicalProvider/LexicalProviderImpl.cs b/Src/Common/FieldWorks/LexicalProvider/LexicalProviderImpl.cs
deleted file mode 100644
index d34f56251f..0000000000
--- a/Src/Common/FieldWorks/LexicalProvider/LexicalProviderImpl.cs
+++ /dev/null
@@ -1,595 +0,0 @@
-// Copyright (c) 2011-2013 SIL International
-// This software is licensed under the LGPL, version 2.1 or later
-// (http://www.gnu.org/licenses/lgpl-2.1.html)
-//
-// File: LexicalProviderImpl.cs
-// Responsibility: FW Team
-//
-//
-//
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.ServiceModel;
-using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.CoreImpl;
-using SIL.FieldWorks.FDO;
-using SIL.FieldWorks.FDO.DomainServices;
-using SIL.FieldWorks.FDO.Infrastructure;
-using SIL.FieldWorks.FdoUi;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.Utils;
-using XCore;
-
-namespace SIL.FieldWorks.LexicalProvider
-{
- /// ----------------------------------------------------------------------------------------
- ///
- /// This class implements the ILexicalProvider
- ///
- /// ----------------------------------------------------------------------------------------
- [ServiceBehavior(IncludeExceptionDetailInFaults = true,
- InstanceContextMode = InstanceContextMode.Single,
- MaxItemsInObjectGraph = 2147483647)]
- [SuppressMessage("Gendarme.Rules.Design", "TypesWithDisposableFieldsShouldBeDisposableRule",
- Justification="m_cache is a reference")]
- public sealed class LexicalProviderImpl : ILexicalProvider
- {
- private const string kAnalysisPrefix = "Analysis:";
- private readonly FdoCache m_cache;
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes a new instance of the class for the
- /// specified cache.
- ///
- /// ------------------------------------------------------------------------------------
- public LexicalProviderImpl(FdoCache cache)
- {
- m_cache = cache;
- }
-
- #region ILexicalProvider Members
- /// ------------------------------------------------------------------------------------
- ///
- /// Displays the specified entry using the application with the lexical data.
- ///
- /// ------------------------------------------------------------------------------------
- public void ShowEntry(string entry, EntryType entryType)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
- Logger.WriteEvent("Showing entry from external application for the " + entryType + " " + entry);
-
- if (entryType != EntryType.Word)
- throw new ArgumentException("Unknown entry type specified.");
-
- // An asynchronous call is necessary because the WCF server (FieldWorks) will not
- // respond until this method returns. This also allows methods that show dialogs on the
- // WCF server to not be OneWay. (Otherwise, time-out exceptions occur.)
- FieldWorks.ThreadHelper.InvokeAsync(() =>
- {
- ITsString tss = TsStringUtils.MakeTss(entry, FieldWorks.Cache.DefaultVernWs);
- Mediator mediator = new Mediator();
- mediator.HelpTopicProvider = FieldWorks.GetHelpTopicProvider(FwUtils.ksFlexAbbrev);
- mediator.FeedbackInfoProvider = FieldWorks.GetOrCreateFlexApp();
- mediator.PropertyTable.SetProperty("App", FieldWorks.GetOrCreateFlexApp());
-
- LexEntryUi.DisplayEntry(FieldWorks.Cache, mediator, mediator.HelpTopicProvider,
- "UserHelpFile", tss, null);
- });
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Displays the related words to the specified entry using the application with the
- /// lexical data.
- ///
- /// ------------------------------------------------------------------------------------
- public void ShowRelatedWords(string entry, EntryType entryType)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
- Logger.WriteEvent("Showing related word from external application for the " + entryType + " " + entry);
-
- if (entryType != EntryType.Word)
- throw new ArgumentException("Unknown entry type specified.");
-
- // An asynchronous call is necessary because the WCF server (FieldWorks) will not
- // respond until this method returns. This also allows methods that show dialogs on the
- // WCF server to not be OneWay. (Otherwise, time-out exceptions occur.)
- FieldWorks.ThreadHelper.InvokeAsync(() =>
- {
- ITsString tss = TsStringUtils.MakeTss(entry, FieldWorks.Cache.DefaultVernWs);
- Mediator mediator = new Mediator();
- mediator.HelpTopicProvider = FieldWorks.GetHelpTopicProvider(FwUtils.ksFlexAbbrev);
- mediator.FeedbackInfoProvider = FieldWorks.GetOrCreateFlexApp();
- mediator.PropertyTable.SetProperty("App", FieldWorks.GetOrCreateFlexApp());
-
- LexEntryUi.DisplayRelatedEntries(FieldWorks.Cache, mediator, mediator.HelpTopicProvider,
- "UserHelpFile", tss);
- });
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets all lexemes in the Lexicon
- ///
- /// ------------------------------------------------------------------------------------
- public IEnumerable Lexemes()
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
-
- List entries = new List();
- // Get all of the lexical entries in the database
- foreach (ILexEntry dbEntry in m_cache.ServiceLocator.GetInstance().AllInstances())
- {
- IMoMorphType morphType = dbEntry.PrimaryMorphType;
- if (morphType != null)
- entries.Add(CreateEntryFromDbEntry(GetLexemeTypeForMorphType(morphType), dbEntry));
- }
-
- // Get all the wordforms in the database
- foreach (IWfiWordform wordform in m_cache.ServiceLocator.GetInstance().AllInstances())
- entries.Add(CreateEntryFromDbWordform(wordform));
-
- return entries;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Looks up an lexeme
- ///
- /// ------------------------------------------------------------------------------------
- public LexicalEntry GetLexeme(LexemeType type, string lexicalForm, int homograph)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
-
- switch (type)
- {
- case LexemeType.Word:
- IWfiWordform wf = GetDbWordform(lexicalForm);
- return (wf != null) ? CreateEntryFromDbWordform(wf) : null;
- default:
- ILexEntry dbEntry = GetDbLexeme(type, lexicalForm, homograph);
- return (dbEntry != null) ? CreateEntryFromDbEntry(type, dbEntry) : null;
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Adds the lexeme to the lexicon.
- ///
- /// if matching lexeme is already in lexicon
- /// ------------------------------------------------------------------------------------
- public void AddLexeme(LexicalEntry lexeme)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
- Logger.WriteEvent("Adding new lexeme from an external application: " + lexeme.LexicalForm);
-
- NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
- {
- string sForm = lexeme.LexicalForm;
- switch(lexeme.Type)
- {
- case LexemeType.Word:
- ITsString tss = TsStringUtils.MakeTss(lexeme.LexicalForm, m_cache.DefaultVernWs);
- m_cache.ServiceLocator.GetInstance().Create(tss);
- break;
- default:
- {
- SandboxGenericMSA msa = new SandboxGenericMSA();
- msa.MsaType = (lexeme.Type == LexemeType.Stem) ? MsaType.kStem : MsaType.kUnclassified;
-
- IMoMorphType morphType = GetMorphTypeForLexemeType(lexeme.Type);
- ITsString tssForm = TsStringUtils.MakeTss(sForm, m_cache.DefaultVernWs);
- m_cache.ServiceLocator.GetInstance().Create(morphType, tssForm, (ITsString)null, msa);
- break;
- }
- }
- });
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Adds a new sense to the lexeme with the specified information
- ///
- /// ------------------------------------------------------------------------------------
- public LexSense AddSenseToEntry(LexemeType type, string lexicalForm, int homograph)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
- Logger.WriteEvent("Adding new sense to lexeme '" + lexicalForm + "' from an external application");
-
- return NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
- {
- string guid = string.Empty;
- switch (type)
- {
- case LexemeType.Word:
- {
- IWfiWordform dbWordform = GetDbWordform(lexicalForm);
- if (dbWordform == null)
- throw new ArgumentException("Entry in the lexicon not found for the specified information");
-
- // For wordforms, our "senses" could be new meanings of an analysis for the word
- // or it could be a brand new analysis. Because we have no idea what the user actually
- // wanted, we just assume the worst (they want to create a new analysis for the word
- // with a new meaning).
- IWfiAnalysis dbAnalysis = m_cache.ServiceLocator.GetInstance().Create();
- dbWordform.AnalysesOC.Add(dbAnalysis);
- guid = kAnalysisPrefix + dbAnalysis.Guid;
- break;
- }
- default:
- {
- ILexEntry dbEntry = GetDbLexeme(type, lexicalForm, homograph);
- if (dbEntry == null)
- throw new ArgumentException("Entry in the lexicon not found for the specified information");
-
- if (dbEntry.SensesOS.Count == 1 && dbEntry.SensesOS[0].Gloss.StringCount == 0)
- {
- // An empty sense exists (probably was created during a call to AddLexeme)
- guid = dbEntry.SensesOS[0].Guid.ToString();
- break;
- }
-
- ILexSense newSense = m_cache.ServiceLocator.GetInstance().Create(
- dbEntry, new SandboxGenericMSA(), (ITsString)null);
- guid = newSense.Guid.ToString();
- break;
- }
- }
- return new LexSense(guid);
- });
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Adds a new gloss to the sense with the specified information
- ///
- /// ------------------------------------------------------------------------------------
- public LexGloss AddGlossToSense(LexemeType type, string lexicalForm, int homograph,
- string senseId, string language, string text)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
- Logger.WriteEvent("Adding new gloss to lexeme '" + lexicalForm + "' from an external application");
-
- return NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
- {
- IMultiUnicode dbGlosses;
- if (senseId.StartsWith(kAnalysisPrefix))
- {
- // The "sense" is actually an analysis for a wordform and our new
- // gloss is a new meaning for that analysis.
- Guid analysisGuid = new Guid(senseId.Substring(kAnalysisPrefix.Length));
- IWfiAnalysis dbAnalysis = m_cache.ServiceLocator.GetInstance().GetObject(analysisGuid);
- IWfiGloss dbGloss = dbAnalysis.MeaningsOC.FirstOrDefault();
- if (dbGloss == null)
- {
- dbGloss = m_cache.ServiceLocator.GetInstance().Create();
- dbAnalysis.MeaningsOC.Add(dbGloss);
- }
- dbGlosses = dbGloss.Form;
- dbAnalysis.ApprovalStatusIcon = 1; // Assume the analysis from the external application is user approved
- }
- else
- {
- Guid senseGuid = new Guid(senseId);
- ILexSense dbSense = m_cache.ServiceLocator.GetInstance().GetObject(senseGuid);
- dbGlosses = dbSense.Gloss;
- }
-
- // Add the new gloss to the list of glosses for the sense
- ILgWritingSystem writingSystem = m_cache.WritingSystemFactory.get_Engine(language);
- dbGlosses.set_String(writingSystem.Handle, TsStringUtils.MakeTss(text, writingSystem.Handle));
-
- return new LexGloss(language, text);
- });
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Removes the gloss with the specified language form the sense with the specified information
- ///
- /// ------------------------------------------------------------------------------------
- public void RemoveGloss(LexemeType type, string lexicalForm, int homograph,
- string senseId, string language)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
- Logger.WriteEvent("Removing gloss from lexeme '" + lexicalForm + "' from an external application");
-
- NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
- {
- IMultiUnicode dbGlosses;
- Guid guid;
- if (senseId.StartsWith(kAnalysisPrefix))
- {
- // The "sense" is actually an analysis for a wordform and the gloss
- // we want to delete is a meaning for that analysis.
- guid = new Guid(senseId.Substring(kAnalysisPrefix.Length));
- IWfiAnalysis dbAnalysis = m_cache.ServiceLocator.GetInstance().GetObject(guid);
- IWfiGloss dbGloss = dbAnalysis.MeaningsOC.First();
- dbGlosses = dbGloss.Form;
- }
- else
- {
- guid = new Guid(senseId);
- ILexSense dbSense = m_cache.ServiceLocator.GetInstance().GetObject(guid);
- dbGlosses = dbSense.Gloss;
- }
- // Remove the gloss from the list of glosses for the sense
- int wsId = m_cache.WritingSystemFactory.GetWsFromStr(language);
- dbGlosses.set_String(wsId, (ITsString)null);
-
- // Delete the sense if there are no more glosses for it
- if (dbGlosses.StringCount == 0)
- RemoveSense(senseId, guid);
- });
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Forces a save of lexicon
- ///
- /// ------------------------------------------------------------------------------------
- public void Save()
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
-
- // ENHANCE: We could do a save on the cache here. It doesn't seem really important
- // since the cache will be saved automatically with 10 seconds of inactivity anyways.
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// This must be called before entries are changed to ensure that
- /// it is saved to disk. Since the lexicon is a complex structure
- /// and other features depend on knowing when it is changed,
- /// all work done with the lexicon is marked with a begin and
- /// end change.
- ///
- /// ------------------------------------------------------------------------------------
- public void BeginChange()
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
-
- // Ideally, we would like to be able to begin an undo task here and then end it in
- // EndChange(). However, because there is no guarantee that EndChange() will ever
- // get called (and to keep the data in a consistant state), we need to wrap
- // each individual change in it's own undo task.
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// This must be called after entries are changed to ensure that
- /// other features dependent on the lexicon are made aware of the
- /// change.
- ///
- /// ------------------------------------------------------------------------------------
- public void EndChange()
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
- }
- #endregion
-
- #region Private helper methods
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the DB LexEntry for the specified type and form (homograph currently ignored) or
- /// null if none could be found.
- ///
- /// ------------------------------------------------------------------------------------
- private ILexEntry GetDbLexeme(LexemeType type, string lexicalForm, int homograph)
- {
- if (type == LexemeType.Word)
- throw new ArgumentException("LexEntry can not be found for the Lexeme type specified");
-
- // ENHANCE: We may have to do something with the homograph number eventually, but
- // currently there is no correlation between the homograph number in the DB and
- // the homograph number passed from the external application.
- return m_cache.ServiceLocator.GetInstance().GetHomographs(lexicalForm).FirstOrDefault(
- dbEntry => LexemeTypeAndMorphTypeMatch(type, dbEntry.PrimaryMorphType));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the DB Wordform for the form or null if none could be found.
- ///
- /// ------------------------------------------------------------------------------------
- private IWfiWordform GetDbWordform(string lexicalForm)
- {
- IWfiWordform wf;
- m_cache.ServiceLocator.GetInstance().TryGetObject(
- TsStringUtils.MakeTss(lexicalForm, m_cache.DefaultVernWs), true, out wf);
- return wf;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Creates a new LexicalEntry from the specified lexical entry in the DB
- ///
- /// ------------------------------------------------------------------------------------
- private LexicalEntry CreateEntryFromDbEntry(LexemeType type, ILexEntry dbEntry)
- {
- if (type == LexemeType.Word)
- throw new ArgumentException("Lexeme type specified can not be created from a LexEntry");
-
- // A homograph number of zero in the DB means there is only one entry for the wordform.
- // However, the interface requires there be an entry with a homograph of one even if
- // there is only one entry.
- LexicalEntry entry = new LexicalEntry(type, dbEntry.HomographForm,
- dbEntry.HomographNumber > 0 ? dbEntry.HomographNumber : 1);
-
- // Add the senses to the interface (non-DB) entry
- foreach (ILexSense dbSense in dbEntry.SensesOS)
- {
- LexSense sense = new LexSense(dbSense.Guid.ToString());
- AddDbGlossesToSense(sense, dbSense.Gloss);
- entry.Senses.Add(sense); // Add the sense to the list of senses
- }
- return entry;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Creates a new LexicalEntry from the specified word form in the DB
- ///
- /// ------------------------------------------------------------------------------------
- private LexicalEntry CreateEntryFromDbWordform(IWfiWordform wordform)
- {
- const int homograph = 1;
- LexicalEntry entry = new LexicalEntry(LexemeType.Word, wordform.Form.VernacularDefaultWritingSystem.Text, homograph);
- foreach (IWfiAnalysis dbAnalysis in wordform.AnalysesOC)
- {
- // Since our "sense" is really an analysis for a wordform, assume that any meanings
- // for that analysis are glosses for the same "sense".
- LexSense sense = new LexSense(kAnalysisPrefix + dbAnalysis.Guid.ToString());
- foreach (IWfiGloss gloss in dbAnalysis.MeaningsOC)
- AddDbGlossesToSense(sense, gloss.Form);
- entry.Senses.Add(sense);
- }
- return entry;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Adds the glosses in all available writing systems to the specified sense.
- ///
- /// ------------------------------------------------------------------------------------
- private void AddDbGlossesToSense(LexSense sense, IMultiUnicode glosses)
- {
- for (int i = 0; i < glosses.StringCount; i++)
- {
- int ws;
- ITsString tssGloss = glosses.GetStringFromIndex(i, out ws);
- string icuLocale = m_cache.WritingSystemFactory.GetStrFromWs(ws);
- sense.Glosses.Add(new LexGloss(icuLocale, tssGloss.Text));
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Removes the sense with the specified ID and guid from the DB.
- ///
- /// ------------------------------------------------------------------------------------
- private void RemoveSense(string senseId, Guid guid)
- {
- if (senseId.StartsWith(kAnalysisPrefix))
- {
- IWfiAnalysis dbAnalysis = m_cache.ServiceLocator.GetInstance().GetObject(guid);
- IWfiWordform dbWordform = (IWfiWordform)dbAnalysis.Owner;
- dbWordform.AnalysesOC.Remove(dbAnalysis);
- }
- else
- {
- ILexSense dbSense = m_cache.ServiceLocator.GetInstance().GetObject(guid);
- ILexEntry dbEntry = (ILexEntry)dbSense.Owner;
-
- // Make sure we keep at least one sense around. This seems to be required.
- if (dbEntry.SensesOS.Count > 1)
- dbEntry.SensesOS.Remove(dbSense);
- }
- }
- #endregion
-
- #region LexemeType and MorphType matching methods
- /// ------------------------------------------------------------------------------------
- ///
- /// Determines if the specified lexeme type matches the specified morph type
- ///
- /// ------------------------------------------------------------------------------------
- private static bool LexemeTypeAndMorphTypeMatch(LexemeType type, IMoMorphType morphType)
- {
- if (type == LexemeType.Word || type == LexemeType.Lemma)
- throw new ArgumentException("Morph type can never be of the specified lexeme type");
-
- switch (type)
- {
- case LexemeType.Prefix: return morphType.IsPrefixishType;
- case LexemeType.Suffix: return morphType.IsSuffixishType;
- case LexemeType.Stem: return morphType.IsStemType &&
- morphType.Guid != MoMorphTypeTags.kguidMorphPhrase &&
- morphType.Guid != MoMorphTypeTags.kguidMorphDiscontiguousPhrase;
- case LexemeType.Phrase:
- return morphType.Guid == MoMorphTypeTags.kguidMorphPhrase ||
- morphType.Guid == MoMorphTypeTags.kguidMorphDiscontiguousPhrase;
- }
- return false;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the morph type for the specified lexeme type.
- ///
- /// ------------------------------------------------------------------------------------
- private IMoMorphType GetMorphTypeForLexemeType(LexemeType type)
- {
- if (type == LexemeType.Word || type == LexemeType.Lemma)
- throw new ArgumentException("Morph type can never be of the specified lexeme type");
-
- IMoMorphTypeRepository repo = m_cache.ServiceLocator.GetInstance();
- switch (type)
- {
- case LexemeType.Prefix: return repo.GetObject(MoMorphTypeTags.kguidMorphPrefix);
- case LexemeType.Suffix: return repo.GetObject(MoMorphTypeTags.kguidMorphSuffix);
- case LexemeType.Phrase: return repo.GetObject(MoMorphTypeTags.kguidMorphPhrase);
- case LexemeType.Stem: return repo.GetObject(MoMorphTypeTags.kguidMorphStem);
- }
- return null;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the lexeme type that most closely represents the specified morph type.
- ///
- /// This method attempts to do it's best to get the correct lexeme type.
- /// However, the FW database contains many more morph types then can be represented with
- /// the few lexeme types. This creates some ambiguous mappings which are commented
- /// inside this method body.
- /// ------------------------------------------------------------------------------------
- private LexemeType GetLexemeTypeForMorphType(IMoMorphType type)
- {
- switch (type.Guid.ToString())
- {
- case MoMorphTypeTags.kMorphCircumfix:
- case MoMorphTypeTags.kMorphInfix:
- case MoMorphTypeTags.kMorphInfixingInterfix:
- case MoMorphTypeTags.kMorphSimulfix:
- case MoMorphTypeTags.kMorphSuprafix:
- case MoMorphTypeTags.kMorphClitic:
- case MoMorphTypeTags.kMorphProclitic:
- // These don't map neatly to a lexeme type, so we just return prefix
- return LexemeType.Prefix;
-
- case MoMorphTypeTags.kMorphEnclitic:
- // This one also isn't a great match, but there is no better choice
- return LexemeType.Suffix;
-
- case MoMorphTypeTags.kMorphPrefix:
- case MoMorphTypeTags.kMorphPrefixingInterfix:
- return LexemeType.Prefix;
-
- case MoMorphTypeTags.kMorphSuffix:
- case MoMorphTypeTags.kMorphSuffixingInterfix:
- return LexemeType.Suffix;
-
- case MoMorphTypeTags.kMorphPhrase:
- case MoMorphTypeTags.kMorphDiscontiguousPhrase:
- return LexemeType.Phrase;
-
- case MoMorphTypeTags.kMorphStem:
- case MoMorphTypeTags.kMorphRoot:
- case MoMorphTypeTags.kMorphBoundRoot:
- case MoMorphTypeTags.kMorphBoundStem:
- case MoMorphTypeTags.kMorphParticle:
- return LexemeType.Stem;
- }
-
- // Shouldn't ever get here, but since we don't know what type it is just return
- // a random default and hope for the best.
- return LexemeType.Stem;
- }
- #endregion
- }
-}
diff --git a/Src/Common/FieldWorks/LexicalProvider/LexicalProviderManager.cs b/Src/Common/FieldWorks/LexicalProvider/LexicalProviderManager.cs
deleted file mode 100644
index 534e004469..0000000000
--- a/Src/Common/FieldWorks/LexicalProvider/LexicalProviderManager.cs
+++ /dev/null
@@ -1,185 +0,0 @@
-// Copyright (c) 2011-2013 SIL International
-// This software is licensed under the LGPL, version 2.1 or later
-// (http://www.gnu.org/licenses/lgpl-2.1.html)
-//
-// File: LexicalProviderManager.cs
-// Responsibility: FW Team
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Diagnostics.CodeAnalysis;
-using System.ServiceModel;
-using System.Threading;
-using System.Windows.Forms;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.FDO;
-using SIL.Utils;
-using Timer = System.Threading.Timer;
-
-namespace SIL.FieldWorks.LexicalProvider
-{
-
- /// ----------------------------------------------------------------------------------------
- ///
- /// Manages FieldWorks's lexical service provider for access by external applications.
- ///
- /// ----------------------------------------------------------------------------------------
- internal static class LexicalProviderManager
- {
- private const int kInactivityTimeout = 1800000; // 30 minutes in msec
-
- private static Timer s_lexicalProviderTimer;
- private static readonly Dictionary s_runningProviders = new Dictionary();
-
- private static string PtCommunicationProbTitle = "Paratext Communication Problem";
- private static string PtCommunicationProb =
- "The project you are opening will not communicate with Paratext because a project with the same name is " +
- "already open. If you want to use Paratext with this project, make a change in this project" +
- " (so that it will start first), close both projects, then restart Flex.";
-
- // The different URL prefixes that are required for Windows named pipes and Linux basic http binding.
- #if __MonoCS__
- // Just in case port 40001 is in use for something else on a particular system, we allow the user to configure both
- // programs to use a different port.
- internal static string UrlPrefix = "http://127.0.0.1:" + (Environment.GetEnvironmentVariable("LEXICAL_PROVIDER_PORT") ?? "40001") + "/";
- #else
- internal const string UrlPrefix = "net.pipe://localhost/";
- #endif
-
- // Mono requires the pipe handle to use slashes instead of colons.
- // We could put this conditional code somewhere in the routines that generate the pipe handles,
- // but it seemed cleaner to keep all the conditional code for different kinds of pipe more-or-less in one place.
- internal static string FixPipeHandle(string pipeHandle)
- {
- #if __MonoCS__
- return pipeHandle.Replace (":", "/");
- #else
- return pipeHandle;
- #endif
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Creates a LexicalServiceProvider listener for the specified project.
- ///
- /// ------------------------------------------------------------------------------------
- internal static void StartLexicalServiceProvider(ProjectId projectId, FdoCache cache)
- {
- if (projectId == null)
- throw new InvalidOperationException("Project identity must be known before creating the lexical provider listener");
- var url = UrlPrefix + FixPipeHandle(projectId.PipeHandle);
- StartProvider(new Uri(url),
- new LexicalServiceProvider(cache), typeof(ILexicalServiceProvider));
-
- s_lexicalProviderTimer = new Timer(s_timeSinceLexicalProviderUsed_Tick, null,
- kInactivityTimeout, Timeout.Infinite);
- Logger.WriteEvent("Started listening for lexical service provider requests.");
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Starts the provider.
- ///
- /// The provider location.
- /// The provider.
- /// Type of the provider.
- /// ------------------------------------------------------------------------------------
- [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
- Justification="See review comment")]
- [SuppressMessage("Gendarme.Rules.Portability", "MonoCompatibilityReviewRule",
- Justification="See TODO-Linux comment")]
- internal static void StartProvider(Uri providerLocation, object provider, Type providerType)
- {
- if (s_runningProviders.ContainsKey(providerType))
- return;
-
- string sNamedPipe = providerLocation.ToString();
- // REVIEW: we don't dispose ServiceHost. It might be better to add it to the
- // SingletonsContainer
- ServiceHost providerHost = null;
- try
- {
- providerHost = new ServiceHost(provider);
- // Named pipes are better for Windows...don't tie up a dedicated port and perform better.
- // However, Mono does not yet support them, so on Mono we use a different binding.
- // Note that any attempt to unify these will require parallel changes in Paratext
- // and some sort of coordinated release of the new versions.
-#if __MonoCS__
- BasicHttpBinding binding = new BasicHttpBinding();
-#else
- NetNamedPipeBinding binding = new NetNamedPipeBinding();
- binding.Security.Mode = NetNamedPipeSecurityMode.None;
-#endif
- binding.MaxBufferSize *= 4;
- binding.MaxReceivedMessageSize *= 4;
- binding.MaxBufferPoolSize *= 2;
- binding.ReaderQuotas.MaxBytesPerRead *= 4;
- binding.ReaderQuotas.MaxArrayLength *= 4;
- binding.ReaderQuotas.MaxDepth *= 4;
- binding.ReaderQuotas.MaxNameTableCharCount *= 4;
- binding.ReaderQuotas.MaxStringContentLength *= 4;
-
- providerHost.AddServiceEndpoint(providerType, binding, sNamedPipe);
- providerHost.Open();
- }
- catch (Exception e)
- {
- Logger.WriteError(e);
- providerHost = null;
- var paratextInstalled = FwRegistryHelper.Paratext7orLaterInstalled();
- if (paratextInstalled)
- {
- MessageBox.Show(PtCommunicationProb, PtCommunicationProbTitle,
- MessageBoxButtons.OK, MessageBoxIcon.Information);
- }
- return;
- }
- Logger.WriteEvent("Started provider " + providerLocation + " for type " + providerType + ".");
- s_runningProviders.Add(providerType, providerHost);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Resets the lexical provider timer.
- ///
- /// ------------------------------------------------------------------------------------
- internal static void ResetLexicalProviderTimer()
- {
- s_lexicalProviderTimer.Change(kInactivityTimeout, Timeout.Infinite);
- FieldWorks.InAppServerMode = true;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Releases unmanaged and - optionally - managed resources
- ///
- /// ------------------------------------------------------------------------------------
- internal static void StaticDispose()
- {
- Logger.WriteEvent("Closing service hosts");
-
- if (s_lexicalProviderTimer != null)
- s_lexicalProviderTimer.Dispose();
- s_lexicalProviderTimer = null;
-
- foreach (ServiceHost host in s_runningProviders.Values)
- host.Close();
- s_runningProviders.Clear();
- FieldWorks.InAppServerMode = false; // Make sure FW can shut down
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Handles the Tick event of the s_timeSinceLexicalProviderUsed control.
- ///
- /// The source of the event.
- /// ------------------------------------------------------------------------------------
- private static void s_timeSinceLexicalProviderUsed_Tick(object sender)
- {
- FieldWorks.InAppServerMode = false;
- if (FieldWorks.ProcessCanBeAutoShutDown)
- FieldWorks.GracefullyShutDown();
- }
- }
-}
diff --git a/Src/Common/FieldWorks/LexicalProvider/LexicalServiceProvider.cs b/Src/Common/FieldWorks/LexicalProvider/LexicalServiceProvider.cs
deleted file mode 100644
index ffe189a08b..0000000000
--- a/Src/Common/FieldWorks/LexicalProvider/LexicalServiceProvider.cs
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright (c) 2011-2013 SIL International
-// This software is licensed under the LGPL, version 2.1 or later
-// (http://www.gnu.org/licenses/lgpl-2.1.html)
-//
-// File: LexicalServiceProvider.cs
-// Responsibility: FW Team
-
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.ServiceModel;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.FDO;
-
-namespace SIL.FieldWorks.LexicalProvider
-{
- /// ----------------------------------------------------------------------------------------
- ///
- /// Provides a service contract for getting a lexical provider from an application.
- ///
- /// ----------------------------------------------------------------------------------------
- [ServiceBehavior(IncludeExceptionDetailInFaults = true,
- InstanceContextMode = InstanceContextMode.Single,
- MaxItemsInObjectGraph = 2147483647)]
- [SuppressMessage("Gendarme.Rules.Design", "TypesWithDisposableFieldsShouldBeDisposableRule",
- Justification="m_cache is a reference")]
- public sealed class LexicalServiceProvider : ILexicalServiceProvider
- {
- /// String representing the type of the LexicalProvider
- public const string kLexicalProviderType = "LexicalProvider";
- private const int kSupportedLexicalProviderVersion = 3;
-
- private FdoCache m_cache;
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes a new instance of the class.
- ///
- /// ------------------------------------------------------------------------------------
- public LexicalServiceProvider(FdoCache cache)
- {
- m_cache = cache;
- }
-
- #region ILexicalServiceProvider Members
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the location for the provider for the specified project and provider type.
- /// If the providerType is not supported, return null for the Uri.
- ///
- /// ------------------------------------------------------------------------------------
- public Uri GetProviderLocation(string projhandle, string providerType)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
-
- if (providerType == kLexicalProviderType)
- {
- var url = LexicalProviderManager.UrlPrefix + LexicalProviderManager.FixPipeHandle(FwUtils.GeneratePipeHandle(projhandle + ":LP"));
- Uri projUri = new Uri(url);
- LexicalProviderManager.StartProvider(projUri, new LexicalProviderImpl(m_cache), typeof(ILexicalProvider));
- return projUri;
- }
-
- return null;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the version of the specified provider that the server supports. If the
- /// providerType is not supported, return 0 for the version.
- ///
- /// ------------------------------------------------------------------------------------
- public int GetSupportedVersion(string providerType)
- {
- LexicalProviderManager.ResetLexicalProviderTimer();
- if (providerType == kLexicalProviderType)
- return kSupportedLexicalProviderVersion;
- return 0;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Unlike a normal ping method that gets a response, we just use this ping method
- /// to determine if the service provider is actually valid since no exception is
- /// thrown until a method is called.
- ///
- /// ------------------------------------------------------------------------------------
- public void Ping()
- {
- // Nothing to do for this method except reset our timer for the life of the LexicalProvider.
- // See comment for this method.
- LexicalProviderManager.ResetLexicalProviderTimer();
- }
-
- #endregion
- }
-}
diff --git a/Src/Common/FieldWorks/PaObjects/PaLexicalInfo.cs b/Src/Common/FieldWorks/PaObjects/PaLexicalInfo.cs
index 503dc25f09..d784ce0505 100644
--- a/Src/Common/FieldWorks/PaObjects/PaLexicalInfo.cs
+++ b/Src/Common/FieldWorks/PaObjects/PaLexicalInfo.cs
@@ -13,7 +13,6 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
-using System.Linq;
using System.Threading;
using System.Windows.Forms;
using SIL.PaToFdoInterfaces;
@@ -52,7 +51,7 @@ public void Dispose()
///
protected virtual void Dispose(bool fDisposing)
{
- System.Diagnostics.Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType().ToString() + " *******");
+ Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType() + " *******");
if (fDisposing && !IsDisposed)
{
// dispose managed and unmanaged objects
@@ -240,7 +239,7 @@ private bool LoadFwDataForPa(PaRemoteRequest requestor, string name, string serv
/// ------------------------------------------------------------------------------------
public IEnumerable LexEntries
{
- get { return m_lexEntries.Cast(); }
+ get { return m_lexEntries; }
}
/// ------------------------------------------------------------------------------------
@@ -250,7 +249,7 @@ public IEnumerable LexEntries
/// ------------------------------------------------------------------------------------
public IEnumerable WritingSystems
{
- get { return m_writingSystems.Cast(); }
+ get { return m_writingSystems; }
}
#endregion
diff --git a/Src/Common/FieldWorks/ProjectId.cs b/Src/Common/FieldWorks/ProjectId.cs
index f9758c0848..f8ab610fc3 100644
--- a/Src/Common/FieldWorks/ProjectId.cs
+++ b/Src/Common/FieldWorks/ProjectId.cs
@@ -8,10 +8,9 @@
using System;
using System.Diagnostics;
using System.Net;
+using SIL.CoreImpl;
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.DomainServices;
-using SIL.FieldWorks.FDO.Infrastructure;
-using SIL.FieldWorks.Resources;
using SIL.Utils;
using System.Runtime.Serialization;
using SIL.FieldWorks.Common.FwUtils;
@@ -39,7 +38,7 @@ public class ProjectId : ISerializable, IProjectIdentifier
#region Member variables
private string m_path;
- private readonly FDOBackendProviderType m_type;
+ private FDOBackendProviderType m_type;
private readonly string m_serverName;
#endregion
@@ -147,6 +146,7 @@ private static string LocalHostName
public FDOBackendProviderType Type
{
get { return m_type; }
+ set { m_type = value; }
}
/// ------------------------------------------------------------------------------------
@@ -193,7 +193,7 @@ public string Handle
{
get
{
- return !IsLocal || (DirectoryFinder.IsSubFolderOfProjectsDirectory(ProjectFolder) &&
+ return !IsLocal || (FwDirectoryFinder.IsSubFolderOfProjectsDirectory(ProjectFolder) &&
SysPath.GetExtension(m_path) == ClientServerServices.Current.Local.DefaultBackendType.GetExtension()) ?
Name : m_path;
}
@@ -241,7 +241,7 @@ public string ProjectFolder
get
{
return IsLocal ? SysPath.GetDirectoryName(m_path) :
- SysPath.Combine(SysPath.Combine(DirectoryFinder.ProjectsDirectory, ServerName), Name);
+ SysPath.Combine(SysPath.Combine(FwDirectoryFinder.ProjectsDirectory, ServerName), Name);
}
}
@@ -259,7 +259,7 @@ public string SharedProjectFolder
return ProjectFolder;
// TODO-Linux FWNX-446: Implement alternative way of getting path to shared folder
// Currently assumes projects also exist in the local Project Directory.
- string baseDir = (MiscUtils.IsUnix) ? DirectoryFinder.ProjectsDirectory :
+ string baseDir = (MiscUtils.IsUnix) ? FwDirectoryFinder.ProjectsDirectory :
@"\\" + ServerName + @"\Projects";
return SysPath.Combine(baseDir, Name);
}
@@ -315,7 +315,8 @@ public string UiName
}
return string.Format(Properties.Resources.ksProjectNameAndServerFmt, Name, hostName);
case FDOBackendProviderType.kXML:
- return (SysPath.GetExtension(Path) != FwFileExtensions.ksFwDataXmlFileExtension) ?
+ case FDOBackendProviderType.kSharedXML:
+ return (SysPath.GetExtension(Path) != FdoFileHelper.ksFwDataXmlFileExtension) ?
SysPath.GetFileName(Path) : Name;
case FDOBackendProviderType.kInvalid:
return string.Empty;
@@ -339,7 +340,7 @@ public bool IsValid
var ex = GetExceptionIfInvalid();
if (ex == null)
return true;
- if (ex is FwStartupException)
+ if (ex is StartupException)
return false;
// something totally unexpected that we don't know how to handle happened.
// Don't suppress it.
@@ -375,7 +376,7 @@ public string TypeString
///
/// here.
///
- /// If invalid (e.g., project Name is not set, the
+ /// If invalid (e.g., project Name is not set, the
/// XML file can not be found, etc.)
/// ------------------------------------------------------------------------------------
public void AssertValid()
@@ -396,7 +397,7 @@ public void AssertValid()
internal Exception GetExceptionIfInvalid()
{
if (string.IsNullOrEmpty(Name))
- return new FwStartupException(Properties.Resources.kstidNoProjectName, false);
+ return new StartupException(Properties.Resources.kstidNoProjectName, false);
switch (Type)
{
@@ -407,7 +408,7 @@ internal Exception GetExceptionIfInvalid()
}
catch (SocketException e)
{
- return new FwStartupException(String.Format(Properties.Resources.kstidInvalidServer, ServerName, e.Message), e);
+ return new StartupException(String.Format(Properties.Resources.kstidInvalidServer, ServerName, e.Message), e);
}
catch (Exception ex)
{
@@ -415,11 +416,12 @@ internal Exception GetExceptionIfInvalid()
}
break;
case FDOBackendProviderType.kXML:
+ case FDOBackendProviderType.kSharedXML:
if (!FileUtils.SimilarFileExists(Path))
- return new FwStartupException(string.Format(Properties.Resources.kstidFileNotFound, Path));
+ return new StartupException(string.Format(Properties.Resources.kstidFileNotFound, Path));
break;
case FDOBackendProviderType.kInvalid:
- return new FwStartupException(Properties.Resources.kstidInvalidFwProjType);
+ return new StartupException(Properties.Resources.kstidInvalidFwProjType);
default:
return new NotImplementedException("Unknown type of project.");
}
@@ -427,7 +429,7 @@ internal Exception GetExceptionIfInvalid()
// Check this after checking for other valid information (e.g. if the server is
// not available, we want to show that error, not this error).
if (!FileUtils.DirectoryExists(SharedProjectFolder))
- return new FwStartupException(String.Format(Properties.Resources.kstidCannotAccessProjectPath, SharedProjectFolder));
+ return new StartupException(String.Format(Properties.Resources.kstidCannotAccessProjectPath, SharedProjectFolder));
return null; // valid
}
@@ -524,12 +526,12 @@ private static string CleanUpNameForType(FDOBackendProviderType type, string nam
switch (type)
{
case FDOBackendProviderType.kXML:
- ext = FwFileExtensions.ksFwDataXmlFileExtension;
+ ext = FdoFileHelper.ksFwDataXmlFileExtension;
break;
case FDOBackendProviderType.kDb4oClientServer:
if (!IsServerLocal(server))
return name;
- ext = FwFileExtensions.ksFwDataDb4oFileExtension;
+ ext = FdoFileHelper.ksFwDataDb4oFileExtension;
break;
default:
return name;
@@ -538,7 +540,7 @@ private static string CleanUpNameForType(FDOBackendProviderType type, string nam
if (!SysPath.IsPathRooted(name))
{
string sProjName = (SysPath.GetExtension(name) == ext) ? SysPath.GetFileNameWithoutExtension(name) : name;
- name = SysPath.Combine(SysPath.Combine(DirectoryFinder.ProjectsDirectory, sProjName), name);
+ name = SysPath.Combine(SysPath.Combine(FwDirectoryFinder.ProjectsDirectory, sProjName), name);
}
// If the file doesn't have the expected extension and exists with the extension or
// does not exist without it, we add the expected extension.
@@ -578,9 +580,9 @@ private static FDOBackendProviderType GetType(string type, string pathname, stri
switch (ext) // Includes period.
{
case ".db4o": // for historical purposes
- case FwFileExtensions.ksFwDataDb4oFileExtension:
+ case FdoFileHelper.ksFwDataDb4oFileExtension:
return FDOBackendProviderType.kDb4oClientServer;
- case FwFileExtensions.ksFwDataXmlFileExtension:
+ case FdoFileHelper.ksFwDataXmlFileExtension:
return FDOBackendProviderType.kXML;
}
}
diff --git a/Src/Common/FieldWorks/Properties/Resources.Designer.cs b/Src/Common/FieldWorks/Properties/Resources.Designer.cs
index 5b79962ab0..cc4579cf6c 100644
--- a/Src/Common/FieldWorks/Properties/Resources.Designer.cs
+++ b/Src/Common/FieldWorks/Properties/Resources.Designer.cs
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
-// Runtime Version:4.0.30319.296
+// Runtime Version:4.0.30319.18052
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -60,6 +60,9 @@ internal Resources() {
}
}
+ ///
+ /// Looks up a localized resource of type System.Drawing.Bitmap.
+ ///
internal static System.Drawing.Bitmap DatabaseNew {
get {
object obj = ResourceManager.GetObject("DatabaseNew", resourceCulture);
@@ -67,6 +70,9 @@ internal static System.Drawing.Bitmap DatabaseNew {
}
}
+ ///
+ /// Looks up a localized resource of type System.Drawing.Bitmap.
+ ///
internal static System.Drawing.Bitmap Download {
get {
object obj = ResourceManager.GetObject("Download", resourceCulture);
@@ -74,6 +80,9 @@ internal static System.Drawing.Bitmap Download {
}
}
+ ///
+ /// Looks up a localized resource of type System.Drawing.Bitmap.
+ ///
internal static System.Drawing.Bitmap Import {
get {
object obj = ResourceManager.GetObject("Import", resourceCulture);
@@ -81,6 +90,9 @@ internal static System.Drawing.Bitmap Import {
}
}
+ ///
+ /// Looks up a localized resource of type System.Drawing.Bitmap.
+ ///
internal static System.Drawing.Bitmap Info {
get {
object obj = ResourceManager.GetObject("Info", resourceCulture);
@@ -198,6 +210,24 @@ internal static string ksInsufficientPrivilegesToUpdateProjectLocationText {
}
}
+ ///
+ /// Looks up a localized string similar to {0} is not a valid directory for linked files. Please select a valid directory..
+ ///
+ internal static string ksInvalidLinkedFilesFolder {
+ get {
+ return ResourceManager.GetString("ksInvalidLinkedFilesFolder", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Linked Files Folder.
+ ///
+ internal static string ksLinkedFilesFolder {
+ get {
+ return ResourceManager.GetString("ksLinkedFilesFolder", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Migrate projects.
///
@@ -566,6 +596,9 @@ internal static string ksYouCanTryToMoveProjects {
}
}
+ ///
+ /// Looks up a localized resource of type System.Drawing.Bitmap.
+ ///
internal static System.Drawing.Bitmap OpenFile {
get {
object obj = ResourceManager.GetObject("OpenFile", resourceCulture);
@@ -573,6 +606,9 @@ internal static System.Drawing.Bitmap OpenFile {
}
}
+ ///
+ /// Looks up a localized resource of type System.Drawing.Bitmap.
+ ///
internal static System.Drawing.Bitmap Receive {
get {
object obj = ResourceManager.GetObject("Receive", resourceCulture);
@@ -580,6 +616,9 @@ internal static System.Drawing.Bitmap Receive {
}
}
+ ///
+ /// Looks up a localized resource of type System.Drawing.Bitmap.
+ ///
internal static System.Drawing.Bitmap SendReceiveGetArrow32x32 {
get {
object obj = ResourceManager.GetObject("SendReceiveGetArrow32x32", resourceCulture);
diff --git a/Src/Common/FieldWorks/Properties/Resources.resx b/Src/Common/FieldWorks/Properties/Resources.resx
index 2fe644bee5..44c45ac29a 100644
--- a/Src/Common/FieldWorks/Properties/Resources.resx
+++ b/Src/Common/FieldWorks/Properties/Resources.resx
@@ -327,4 +327,12 @@ We have sometimes seen cases where installing other software leaves the machine
We don't know why this happens. If you have any idea what recently changed on your computer to cause it, please pass this on to the developers.
This message should never be seen. Some users however have gotten into a weird state we don't understand where they have to run-as-administrator in order to access required local-machine keys.
+
+ {0} is not a valid directory for linked files. Please select a valid directory.
+ Error message for accessing an invalid LangProject.LinkedFilesRootDir value
+
+
+ Linked Files Folder
+ Caption for folder dialog, when setting a new LangProject.LinkedFilesRootDir value
+
\ No newline at end of file
diff --git a/Src/Common/FieldWorks/ShareProjectsFolderDlg.cs b/Src/Common/FieldWorks/ShareProjectsFolderDlg.cs
index e0e629590e..f0bede8546 100644
--- a/Src/Common/FieldWorks/ShareProjectsFolderDlg.cs
+++ b/Src/Common/FieldWorks/ShareProjectsFolderDlg.cs
@@ -28,7 +28,7 @@ public partial class ShareProjectsFolderDlg : Form
{
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// ------------------------------------------------------------------------------------
public ShareProjectsFolderDlg()
@@ -39,7 +39,7 @@ public ShareProjectsFolderDlg()
private void m_btnViewFolder_Click(object sender, EventArgs e)
{
// This fires up Windows Explorer, showing the owner of the projects folder.
- using (Process.Start(Path.GetDirectoryName(DirectoryFinder.ProjectsDirectory)))
+ using (Process.Start(Path.GetDirectoryName(FwDirectoryFinder.ProjectsDirectory)))
{
}
}
diff --git a/Src/Common/FieldWorks/WelcomeToFieldWorksDlg.cs b/Src/Common/FieldWorks/WelcomeToFieldWorksDlg.cs
index fe9fb1ad2f..3d92f6169c 100644
--- a/Src/Common/FieldWorks/WelcomeToFieldWorksDlg.cs
+++ b/Src/Common/FieldWorks/WelcomeToFieldWorksDlg.cs
@@ -8,9 +8,9 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
-using Palaso.Reporting;
-using SIL.CoreImpl.Properties;
+using SIL.CoreImpl;
using SIL.FieldWorks.Common.FwUtils;
+using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.Utils;
using XCore;
@@ -71,7 +71,7 @@ public enum ButtonPress
/// True (usually only on the first run) when we want to show the first-time warning about
/// sending google analytics information
/// ------------------------------------------------------------------------------------
- public WelcomeToFieldWorksDlg(IHelpTopicProvider helpTopicProvider, string appAbbrev, FwStartupException exception, bool showReportingRow)
+ public WelcomeToFieldWorksDlg(IHelpTopicProvider helpTopicProvider, string appAbbrev, StartupException exception, bool showReportingRow)
{
m_appAbbrev = appAbbrev;
InitializeComponent();
@@ -102,7 +102,7 @@ public WelcomeToFieldWorksDlg(IHelpTopicProvider helpTopicProvider, string appAb
m_helpTopicProvider = helpTopicProvider;
helpProvider = new HelpProvider();
- helpProvider.HelpNamespace = DirectoryFinder.FWCodeDirectory + m_helpTopicProvider.GetHelpString("UserHelpFile");
+ helpProvider.HelpNamespace = FwDirectoryFinder.CodeDirectory + m_helpTopicProvider.GetHelpString("UserHelpFile");
helpProvider.SetHelpKeyword(this, m_helpTopicProvider.GetHelpString(m_helpTopic));
helpProvider.SetHelpNavigator(this, HelpNavigator.Topic);
receiveButton.Enabled =
diff --git a/Src/Common/Filters/DateTimeMatcher.cs b/Src/Common/Filters/DateTimeMatcher.cs
index 0dc553ce5f..d9d2957b4f 100644
--- a/Src/Common/Filters/DateTimeMatcher.cs
+++ b/Src/Common/Filters/DateTimeMatcher.cs
@@ -2,7 +2,7 @@
using System.Collections.Generic;
using System.Text;
using System.Globalization;
-
+using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.Utils;
using SIL.FieldWorks.Common.FwUtils;
diff --git a/Src/Common/Framework/ExternalSettingsAccessorBase.cs b/Src/Common/Framework/ExternalSettingsAccessorBase.cs
index 07790fb7f8..327b06c4bb 100644
--- a/Src/Common/Framework/ExternalSettingsAccessorBase.cs
+++ b/Src/Common/Framework/ExternalSettingsAccessorBase.cs
@@ -148,7 +148,7 @@ static protected void ReportInvalidInstallation(string message, Exception e)
///
/// The progress dialog if one is already up.
/// ------------------------------------------------------------------------------------
- public void EnsureCurrentResource(IProgress progressDlg)
+ public void EnsureCurrentResource(IThreadedProgress progressDlg)
{
var doc = LoadDoc();
Guid newVersion;
@@ -166,13 +166,7 @@ public void EnsureCurrentResource(IProgress progressDlg)
// Re-load the factory settings if they are not at current version.
if (IsResourceOutdated(ResourceName, newVersion))
{
- if (progressDlg is IThreadedProgress)
- ProcessResources((IThreadedProgress)progressDlg, doc);
- else
- {
- using (var dlg = new ProgressDialogWithTask(progressDlg))
- ProcessResources(dlg, doc);
- }
+ ProcessResources(progressDlg, doc);
#if DEBUG
Debug.Assert(m_fVersionUpdated);
#endif
@@ -188,7 +182,7 @@ public void EnsureCurrentResource(IProgress progressDlg)
/// (i.e., IsResourceOutdated returns false for ResourceName.
///
/// ------------------------------------------------------------------------------------
- protected virtual void EnsureCurrentLocalizations(IProgress progressDlg)
+ protected virtual void EnsureCurrentLocalizations(IThreadedProgress progressDlg)
{
// Default is a no-op
}
diff --git a/Src/Common/Framework/Framework.csproj b/Src/Common/Framework/Framework.csproj
index 1bd34cd8b7..7759329535 100644
--- a/Src/Common/Framework/Framework.csproj
+++ b/Src/Common/Framework/Framework.csproj
@@ -244,7 +244,9 @@
Code
-
+
+ UserControl
+
diff --git a/Src/Common/Framework/FrameworkTests/MainWindowDelegateTests.cs b/Src/Common/Framework/FrameworkTests/MainWindowDelegateTests.cs
index e5fc9ec1de..b25988d753 100644
--- a/Src/Common/Framework/FrameworkTests/MainWindowDelegateTests.cs
+++ b/Src/Common/Framework/FrameworkTests/MainWindowDelegateTests.cs
@@ -151,7 +151,7 @@ public DummyFwApp() : base(null, null)
#region abstract members of SIL.FieldWorks.Common.Framework.FwApp
///
- public override bool InitCacheForApp(IProgress progressDlg)
+ public override bool InitCacheForApp(IThreadedProgress progressDlg)
{
throw new System.NotImplementedException();
}
diff --git a/Src/Common/Framework/FwApp.cs b/Src/Common/Framework/FwApp.cs
index 1f905a168a..f2f0851eaa 100644
--- a/Src/Common/Framework/FwApp.cs
+++ b/Src/Common/Framework/FwApp.cs
@@ -263,7 +263,7 @@ public virtual void DoApplicationInitialization(IProgress progressDlg)
/// The progress dialog.
/// True if the initialization was successful, false otherwise
/// ------------------------------------------------------------------------------------
- public abstract bool InitCacheForApp(IProgress progressDlg);
+ public abstract bool InitCacheForApp(IThreadedProgress progressDlg);
/// ------------------------------------------------------------------------------------
diff --git a/Src/Common/Framework/FwMainWnd.cs b/Src/Common/Framework/FwMainWnd.cs
index 462ca07ae5..e396a7aaa3 100644
--- a/Src/Common/Framework/FwMainWnd.cs
+++ b/Src/Common/Framework/FwMainWnd.cs
@@ -334,7 +334,7 @@ protected void InitStyleSheet(int hvoStylesOwner, int tagStylesList)
if (m_cache == null)
throw new Exception("Cache not yet intialized.");
- StyleSheet.Init(m_cache, hvoStylesOwner, tagStylesList);
+ StyleSheet.Init(m_cache, hvoStylesOwner, tagStylesList, ResourceHelper.DefaultParaCharsStyleName);
InitStyleComboBox();
}
@@ -347,7 +347,7 @@ protected void InitStyleSheet(int hvoStylesOwner, int tagStylesList)
protected void ReSynchStyleSheet()
{
Debug.Assert(StyleSheet != null);
- StyleSheet.Init(m_cache, StyleSheet.RootObjectHvo, StyleSheet.StyleListTag);
+ StyleSheet.Init(m_cache, StyleSheet.RootObjectHvo, StyleSheet.StyleListTag, ResourceHelper.DefaultParaCharsStyleName);
InitStyleComboBox();
}
#endregion
@@ -409,7 +409,7 @@ protected virtual void CreateMenusAndToolBars()
// Use this to initialize combo box items.
m_tmAdapter.InitializeComboItem += InitializeToolBarCombos;
- string sMenuToolBarDefinition = Path.Combine(DirectoryFinder.FWCodeDirectory, "FwTMDefinition.xml");
+ string sMenuToolBarDefinition = Path.Combine(FwDirectoryFinder.CodeDirectory, "FwTMDefinition.xml");
m_tmAdapter.Initialize(this, AdapterContentControl, m_mediator, m_app.ProjectSpecificSettingsKey.ToString(),
new string[] { sMenuToolBarDefinition, GetAppSpecificMenuToolBarDefinition() });
diff --git a/Src/Common/Framework/FwRegistrySettings.cs b/Src/Common/Framework/FwRegistrySettings.cs
index ad086fd2fa..958804608c 100644
--- a/Src/Common/Framework/FwRegistrySettings.cs
+++ b/Src/Common/Framework/FwRegistrySettings.cs
@@ -334,7 +334,7 @@ public void AddErrorReportingInfo()
ErrorReporter.AddProperty("AutoOpenLastEditedProjectSetting", AutoOpenLastEditedProject.ToString());
ErrorReporter.AddProperty("DisableSplashScreenSetting", DisableSplashScreenSetting.ToString());
ErrorReporter.AddProperty("MeasurementUnitSetting", ((MsrSysType)MeasurementUnitSetting).ToString());
- ErrorReporter.AddProperty("BackupDirectorySetting", DirectoryFinder.DefaultBackupDirectory);
+ ErrorReporter.AddProperty("BackupDirectorySetting", FwDirectoryFinder.DefaultBackupDirectory);
}
}
}
diff --git a/Src/Common/Framework/HelpTopicProviderBase.cs b/Src/Common/Framework/HelpTopicProviderBase.cs
index 186d2fe9eb..c651fbf53c 100644
--- a/Src/Common/Framework/HelpTopicProviderBase.cs
+++ b/Src/Common/Framework/HelpTopicProviderBase.cs
@@ -40,7 +40,7 @@ public string HelpFile
{
get
{
- return DirectoryFinder.FWCodeDirectory + GetHelpString("UserHelpFile");
+ return FwDirectoryFinder.CodeDirectory + GetHelpString("UserHelpFile");
}
}
#endregion
diff --git a/Src/Common/Framework/SettingsXmlAccessorBase.cs b/Src/Common/Framework/SettingsXmlAccessorBase.cs
index 88d82aecf4..16ad3ac67f 100644
--- a/Src/Common/Framework/SettingsXmlAccessorBase.cs
+++ b/Src/Common/Framework/SettingsXmlAccessorBase.cs
@@ -83,7 +83,7 @@ protected override Guid GetVersion(XmlNode baseNode)
Justification = "TODO-Linux: XmlReaderSettings.DtdProcessing is missing from Mono")]
protected override XmlNode LoadDoc()
{
- string sXmlFilePath = DirectoryFinder.FWCodeDirectory + ResourceFilePathFromFwInstall;
+ string sXmlFilePath = FwDirectoryFinder.CodeDirectory + ResourceFilePathFromFwInstall;
try
{
XmlReaderSettings settings = new XmlReaderSettings();
diff --git a/Src/Common/Framework/StatusBarProgressHandler.cs b/Src/Common/Framework/StatusBarProgressHandler.cs
index 2a1d6c6330..58406675b6 100644
--- a/Src/Common/Framework/StatusBarProgressHandler.cs
+++ b/Src/Common/Framework/StatusBarProgressHandler.cs
@@ -188,6 +188,15 @@ public bool Canceled
get { return false; }
}
+ ///
+ /// Gets an object to be used for ensuring that required tasks are invoked on the main
+ /// UI thread.
+ ///
+ public ISynchronizeInvoke SynchronizeInvoke
+ {
+ get { return m_progressBar.Control; }
+ }
+
/// ------------------------------------------------------------------------------------
///
/// Gets the progress as a form (used for message box owners, etc).
@@ -200,15 +209,13 @@ public Form Form
get { return m_progressBar.Control.FindForm(); }
}
- /// ------------------------------------------------------------------------------------
///
- /// Gets or sets the progress bar style.
+ /// Gets or sets a value indicating whether this progress is indeterminate.
///
- /// ------------------------------------------------------------------------------------
- public ProgressBarStyle ProgressBarStyle
+ public bool IsIndeterminate
{
- get { return m_progressBar.Style; }
- set { m_progressBar.Style = value; }
+ get { return m_progressBar.Style == ProgressBarStyle.Marquee; }
+ set { m_progressBar.Style = value ? ProgressBarStyle.Marquee : ProgressBarStyle.Blocks; }
}
/// ------------------------------------------------------------------------------------
diff --git a/Src/Common/Framework/StylesXmlAccessor.cs b/Src/Common/Framework/StylesXmlAccessor.cs
index fd6b003a44..c539cb9778 100644
--- a/Src/Common/Framework/StylesXmlAccessor.cs
+++ b/Src/Common/Framework/StylesXmlAccessor.cs
@@ -12,7 +12,6 @@
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
-using System.Linq;
using System.Xml;
using SIL.FieldWorks.Common.FwUtils;
@@ -457,14 +456,14 @@ private void CreateAndUpdateStyles(XmlNodeList tagList)
}
SetFontProperties(styleName, styleTag,
- ((tpt, nVar, nVal) => m_cache.ThreadHelper.Invoke(() => propsBldr.SetIntPropValues(tpt, nVar, nVal))),
- ((tpt, sVal) => m_cache.ThreadHelper.Invoke(() => propsBldr.SetStrPropValue(tpt, sVal))),
+ ((tpt, nVar, nVal) => m_progressDlg.SynchronizeInvoke.Invoke(() => propsBldr.SetIntPropValues(tpt, nVar, nVal))),
+ ((tpt, sVal) => m_progressDlg.SynchronizeInvoke.Invoke(() => propsBldr.SetStrPropValue(tpt, sVal))),
option);
// Get paragraph properties
if (style.Type == StyleType.kstParagraph)
SetParagraphProperties(styleName, styleTag,
- ((tpt, nVar, nVal) => m_cache.ThreadHelper.Invoke(() => propsBldr.SetIntPropValues(tpt, nVar, nVal))),
+ ((tpt, nVar, nVal) => m_progressDlg.SynchronizeInvoke.Invoke(() => propsBldr.SetIntPropValues(tpt, nVar, nVal))),
option);
style.Rules = propsBldr.GetTextProps();
diff --git a/Src/Common/FwRemoteDatabaseConnectorService/FwRemoteDatabaseConnectorService.csproj b/Src/Common/FwRemoteDatabaseConnectorService/FwRemoteDatabaseConnectorService.csproj
index 45d854a45f..c7c8ee46c5 100644
--- a/Src/Common/FwRemoteDatabaseConnectorService/FwRemoteDatabaseConnectorService.csproj
+++ b/Src/Common/FwRemoteDatabaseConnectorService/FwRemoteDatabaseConnectorService.csproj
@@ -12,11 +12,14 @@
FwRemoteDatabaseConnectorService
v4.0
512
-
-
+
+
+
+
-
+
+
3.5
@@ -70,6 +73,14 @@
..\..\..\Output\Debug\FDO.dll
+
+ False
+ ..\..\..\Output\Debug\FwUtils.dll
+
+
+ False
+ ..\..\..\Output\Debug\SilUtils.dll
+
diff --git a/Src/Common/FwRemoteDatabaseConnectorService/Program.cs b/Src/Common/FwRemoteDatabaseConnectorService/Program.cs
index 0ae61801fa..922ab04f87 100644
--- a/Src/Common/FwRemoteDatabaseConnectorService/Program.cs
+++ b/Src/Common/FwRemoteDatabaseConnectorService/Program.cs
@@ -1,4 +1,8 @@
using System.ServiceProcess;
+using SIL.FieldWorks.Common.FwUtils;
+using SIL.FieldWorks.FDO;
+using SIL.FieldWorks.FDO.DomainServices;
+using SIL.Utils;
namespace FwRemoteDatabaseConnectorService
{
@@ -9,6 +13,14 @@ static class Program
///
static void Main()
{
+ // We need FieldWorks here to get the correct registry key HKLM\Software\SIL\FieldWorks.
+ // The default without this would be HKLM\Software\SIL\SIL FieldWorks,
+ // which breaks FwRemoteDatabaseConnectorService.exe.
+ RegistryHelper.ProductName = "FieldWorks";
+
+ ClientServerServices.SetCurrentToDb4OBackend(new SilentFdoUI(new SingleThreadedSynchronizeInvoke()),
+ FwDirectoryFinder.FdoDirectories, () => FwDirectoryFinder.ProjectsDirectory == FwDirectoryFinder.ProjectsDirectoryLocalMachine);
+
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
diff --git a/Src/Common/FwRemoteDatabaseConnectorService/Service1.cs b/Src/Common/FwRemoteDatabaseConnectorService/Service1.cs
index fade05db75..811b1d67ed 100644
--- a/Src/Common/FwRemoteDatabaseConnectorService/Service1.cs
+++ b/Src/Common/FwRemoteDatabaseConnectorService/Service1.cs
@@ -4,12 +4,15 @@
using System.ServiceProcess;
using System.Threading;
using FwRemoteDatabaseConnector;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices;
namespace FwRemoteDatabaseConnectorService
{
public partial class FwRemoteDatabaseConnectorService : ServiceBase
{
+ private const string ksSharedProjectKey = "ProjectShared";
+
private Thread m_clientListenerThread;
private Socket m_clientListenerSocket;
@@ -55,7 +58,7 @@ protected override void OnStart(string[] args)
{
try
{
- RemotingServer.Start();
+ RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, GetSharedProject, SetSharedProject);
}
catch (Exception e)
{
@@ -67,6 +70,19 @@ protected override void OnStart(string[] args)
m_clientListenerThread.Start();
}
+ private static bool GetSharedProject()
+ {
+ bool result;
+ FwRegistryHelper.MigrateVersion7ValueIfNeeded();
+ var value = FwRegistryHelper.FieldWorksRegistryKey.GetValue(ksSharedProjectKey, "false");
+ return (bool.TryParse((string)value, out result) && result);
+ }
+
+ private static void SetSharedProject(bool v)
+ {
+ FwRegistryHelper.FieldWorksRegistryKey.SetValue(ksSharedProjectKey, v);
+ }
+
protected override void OnStop()
{
if (m_clientListenerSocket != null)
diff --git a/Src/Common/FwUtils/ConsoleProgress.cs b/Src/Common/FwUtils/ConsoleProgress.cs
index 7646dfc492..4c2aa5beae 100644
--- a/Src/Common/FwUtils/ConsoleProgress.cs
+++ b/Src/Common/FwUtils/ConsoleProgress.cs
@@ -6,6 +6,8 @@
// Responsibility: mcconnel
using System;
+using System.ComponentModel;
+using SIL.Utils;
namespace SIL.FieldWorks.Common.FwUtils
{
@@ -18,6 +20,7 @@ namespace SIL.FieldWorks.Common.FwUtils
/// ----------------------------------------------------------------------------------------
public class ConsoleProgress : IProgress
{
+ private readonly SingleThreadedSynchronizeInvoke m_sychronizeInvoke = new SingleThreadedSynchronizeInvoke();
int m_min;
int m_max = 100;
string m_message;
@@ -35,6 +38,15 @@ public bool DotsWritten
#region IProgress Members
+ ///
+ /// Gets an object to be used for ensuring that required tasks are invoked on the main
+ /// UI thread.
+ ///
+ public ISynchronizeInvoke SynchronizeInvoke
+ {
+ get { return m_sychronizeInvoke; }
+ }
+
///
/// Gets the form displaying the progress (used for message box owners, etc). If the progress
/// is not associated with a visible Form, then this returns its owning form, if any.
@@ -44,6 +56,15 @@ public System.Windows.Forms.Form Form
get { return null; }
}
+ ///
+ /// Gets or sets a value indicating whether this progress is indeterminate.
+ ///
+ public bool IsIndeterminate
+ {
+ get { return false; }
+ set { }
+ }
+
///
/// Gets or sets the maximum value of the progress bar.
///
@@ -164,15 +185,6 @@ public bool AllowCancel
///
public event System.ComponentModel.CancelEventHandler Canceling;
- ///
- /// Gets or sets the progress bar style.
- ///
- public System.Windows.Forms.ProgressBarStyle ProgressBarStyle
- {
- get { return System.Windows.Forms.ProgressBarStyle.Continuous; }
- set { }
- }
-
#endregion
}
}
diff --git a/Src/Common/FwUtils/DirectoryFinder.cs b/Src/Common/FwUtils/DirectoryFinder.cs
deleted file mode 100644
index 45e03c3f59..0000000000
--- a/Src/Common/FwUtils/DirectoryFinder.cs
+++ /dev/null
@@ -1,1296 +0,0 @@
-// Copyright (c) 2003-2013 SIL International
-// This software is licensed under the LGPL, version 2.1 or later
-// (http://www.gnu.org/licenses/lgpl-2.1.html)
-//
-// File: DirectoryFinder.cs
-//
-//
-// To find the current user's "My Documents" folder, use something like:
-// string sMyDocs = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
-// See the MSDN documentation for the System.Environment.SpecialFolder enumeration for details.
-//
-
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.IO;
-using System.Diagnostics;
-using System.Reflection;
-using System.Security;
-using System.Security.AccessControl;
-using System.Security.Principal;
-using System.Text;
-using System.Windows.Forms;
-using Microsoft.Win32;
-using SIL.FieldWorks.Resources;
-using SIL.Utils;
-
-namespace SIL.FieldWorks.Common.FwUtils
-{
- ///
- /// Summary description for DirectoryFinder.
- ///
- public static class DirectoryFinder
- {
- private static string s_CommonAppDataFolder;
-
- ///
- /// The name of the Translation Editor folder (Even though this is the same as
- /// FwUtils.ksTeAppName and FwSubKey.TE, PLEASE do not use them interchangeably. Use
- /// the one that is correct for your context, in case they need to be changed later.)
- ///
- public const string ksTeFolderName = FwUtils.ksTeAppName;
- ///
- /// The name of the Language Explorer folder (Even though this is the same as
- /// FwUtils.ksFlexAppName and FwSubKey.LexText, PLEASE do not use them interchangeably.
- /// Use the one that is correct for your context, in case they need to be changed later.)
- ///
- public const string ksFlexFolderName = FwUtils.ksFlexAppName;
-
- /// The name of the folder containing FLEx configuration settings
- public const string ksConfigurationSettingsDir = "ConfigurationSettings";
- /// The name of the folder containing FLEx backup settings
- public const string ksBackupSettingsDir = "BackupSettings";
- /// The name of the folder where the user can copy files for backup such as fonts and keyboards
- public const string ksSupportingFilesDir = "SupportingFiles";
- /// The default name of the folder containing LinkedFiles (media, pictures, etc) for a project
- public const string ksLinkedFilesDir = "LinkedFiles";
- /// The name of the subfolder containing media for a project
- public const string ksMediaDir = "AudioVisual";
- /// The name of the subfolder containing pictures for a project
- public const string ksPicturesDir = "Pictures";
- /// The name of the subfolder containing other LinkedFiles for a project
- public const string ksOtherLinkedFilesDir = "Others";
- /// The name of the folder containing writing systems for a project
- public const string ksWritingSystemsDir = "WritingSystemStore";
- /// The name of the folder containing temporary persisted sort sequence info for a project
- public const string ksSortSequenceTempDir = "Temp";
- /// The Scripture-specific stylesheet (ideally, this would be in a TE-specific place, but FDO needs it)
- public const string kTeStylesFilename = "TeStyles.xml";
- /// The filename of the backup settings file
- public const string kBackupSettingsFilename = "BackupSettings.xml";
-
- private const string ksBiblicaltermsLocFilePrefix = "BiblicalTerms-";
- private const string ksBiblicaltermsLocFileExtension = ".xml";
- private const string ksProjectsDir = "ProjectsDir";
-
- ///
- /// Resets the static variables. Used for unit tests.
- ///
- internal static void ResetStaticVars()
- {
- s_CommonAppDataFolder = null;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the Scripture-specific stylesheet.
- /// This should NOT be in the TE folder, because it is used by the SE edition, when
- /// doing minimal scripture initialization in order to include Paratext texts.
- ///
- /// ------------------------------------------------------------------------------------
- public static string TeStylesPath
- {
- get { return Path.Combine(FWCodeDirectory, kTeStylesFilename); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the folder where TE-specific files are installed.
- ///
- /// ------------------------------------------------------------------------------------
- public static string TeFolder
- {
- get { return GetFWCodeSubDirectory(ksTeFolderName); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the folder where FLEx-specific files are installed.
- ///
- /// ------------------------------------------------------------------------------------
- public static string FlexFolder
- {
- get { return GetFWCodeSubDirectory(ksFlexFolderName); }
- }
-
- ///
- /// Return the folder in which FlexBridge resides, or empty string if it is not installed.
- ///
- public static string FlexBridgeFolder
- {
- get { return GetFLExBridgeFolderPath(); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path for storing user-specific application data.
- ///
- /// Name of the application.
- /// ------------------------------------------------------------------------------------
- public static string UserAppDataFolder(string appName)
- {
- string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- return Path.Combine(Path.Combine(path, CompanyName), appName);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path for storing common application data that might be shared between
- /// multiple applications and multiple users on the same machine.
- ///
- /// On Windows this returns Environment.SpecialFolder.CommonApplicationData
- /// (C:\ProgramData),on Linux /var/lib/fieldworks.
- ///
- /// ------------------------------------------------------------------------------------
- private static string CommonApplicationData
- {
- get
- {
- if (s_CommonAppDataFolder == null)
- {
- if (MiscUtils.IsUnix)
- {
- // allow to override the /var/lib/fieldworks path by setting the
- // environment variable FW_CommonAppData. Is this is needed on our CI
- // build machines.
- s_CommonAppDataFolder =
- Environment.GetEnvironmentVariable("FW_CommonAppData") ??
- "/var/lib/fieldworks";
- }
- else
- {
- s_CommonAppDataFolder =
- Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
- }
- }
- return s_CommonAppDataFolder;
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets a special folder, very similar to Environment.GetFolderPath. The main
- /// difference is that this method works cross-platform and does some translations.
- /// For example CommonApplicationData (/usr/share) is not writeable on Linux, so we
- /// translate that to /var/lib/fieldworks instead.
- ///
- /// ------------------------------------------------------------------------------------
- public static string GetFolderPath(Environment.SpecialFolder folder)
- {
- if (folder == Environment.SpecialFolder.CommonApplicationData)
- return CommonApplicationData;
- return Environment.GetFolderPath(folder);
- }
-
- static string s_companyName = Application.CompanyName; // default for real use; tests may override.
- /// ------------------------------------------------------------------------------------
- ///
- /// Sets the name of the company used for registry settings (replaces
- /// Application.CompanyName)
- /// NOTE: THIS SHOULD ONLY BE SET IN TESTS AS THE DEFAULT Application.CompanyName IN
- /// TESTS WILL BE "nunit.org" or jetbrains.something!!!
- ///
- /// ------------------------------------------------------------------------------------
- public static string CompanyName
- {
- set { s_companyName = value; }
- private get
- {
- // This might be a good idea but will require all unit tests that depend on these functions to set one. Many of them
- // don't seem to affected by using an NUnit or JetBrains application name.
- //if (s_companyName.IndexOf("nunit", StringComparison.InvariantCultureIgnoreCase) >= 0 || s_companyName.IndexOf("jetbrains", StringComparison.InvariantCultureIgnoreCase) >= 0)
- // throw new ArgumentException("CompanyName can not be NUnit.org or some variant of NUnit or jetbrains!" +
- // " Make sure the test is overriding this property in RegistryHelper");
- return s_companyName;
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path for storing common application data that might be shared between
- /// multiple applications and multiple users on the same machine.
- ///
- /// On Windows this returns a subdirectory of
- /// Environment.SpecialFolder.CommonApplicationData (C:\ProgramData),on Linux
- /// /var/lib/fieldworks.
- ///
- /// Name of the application.
- /// ------------------------------------------------------------------------------------
- public static string CommonAppDataFolder(string appName)
- {
- return Path.Combine(Path.Combine(CommonApplicationData, CompanyName), appName);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the Translation Editor executable.
- ///
- /// ------------------------------------------------------------------------------------
- public static string TeExe
- {
- get { return ExeOrDllPath("TE.exe"); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the Translation Editor dynamic load library.
- ///
- /// ------------------------------------------------------------------------------------
- public static string TeDll
- {
- get { return ExeOrDllPath("TeDll.dll"); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the FW Language Explorer executable.
- ///
- /// ------------------------------------------------------------------------------------
- public static string FlexExe
- {
- get { return ExeOrDllPath("Flex.exe"); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the FW Language Explorer dynamic load library.
- ///
- /// ------------------------------------------------------------------------------------
- public static string FlexDll
- {
- get { return ExeOrDllPath("LexTextDll.dll"); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the Migrate SQL databases executable.
- ///
- /// ------------------------------------------------------------------------------------
- public static string MigrateSqlDbsExe
- {
- get { return ExeOrDllPath("MigrateSqlDbs.exe"); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the config file
- ///
- /// ------------------------------------------------------------------------------------
- public static string RemotingTcpServerConfigFile
- {
- get
- {
- if (MiscUtils.RunningTests)
- return ExeOrDllPath("remoting_tcp_server_tests.config");
- return ExeOrDllPath("remoting_tcp_server.config");
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path of the requested executable/dll file in the folder from which FW
- /// is being executed.
- ///
- /// Name of the file (case-sensistive, with the extension)
- /// ------------------------------------------------------------------------------------
- private static string ExeOrDllPath(string file)
- {
- if (file == null)
- throw new ArgumentNullException("file");
-
- if (Assembly.GetEntryAssembly() == null)
- {
- // This seems to happen when tests call this method when run from NUnit
- // for some reason.
-
- // The following code should only run by unittests.
-#if DEBUG
- const string arch = "Debug";
-#else
- const string arch = "Release";
-#endif
- return Path.Combine(Path.Combine(Path.Combine(Path.GetDirectoryName(FwSourceDirectory), "Output"), arch), file);
- }
-
- return Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), file);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Get a sub directory of the given ,
- /// or return a tidied up version of the original path,
- /// if it is not in the FW code folder structure.
- ///
- /// Base directory.
- /// examples: "WW\XAMPLE or \WW\XAMPLE"
- ///
- /// ------------------------------------------------------------------------------------
- private static string GetSubDirectory(string directory, string subDirectory)
- {
- Debug.Assert(subDirectory != null);
-
- string retval = subDirectory.Trim();
- if (retval.Length > 0 && (retval[0] == Path.DirectorySeparatorChar
- || retval[0] == Path.AltDirectorySeparatorChar))
- {
- // remove leading directory separator from subdirectory
- retval = retval.Substring(1);
- }
- string possiblePath = Path.Combine(directory, retval);
- if (Directory.Exists(possiblePath))
- retval = possiblePath;
- // Implicit 'else' assumes it to be a full path,
- // but not in the code folder structure.
- // Sure hope the caller can handle it.
-
-#if __MonoCS__
- else if (!Directory.Exists(retval)) // previous Substring(1) causes problem for 'full path' in Linux
- return subDirectory;
-#endif
-
- return retval;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Get a sub directory of the FW code directory,
- /// or return a tidied up version of the original path,
- /// if it is not in the FW code folder structure.
- ///
- /// examples: "WW\XAMPLE or \WW\XAMPLE"
- ///
- /// ------------------------------------------------------------------------------------
- public static string GetFWCodeSubDirectory(string subDirectory)
- {
- return GetSubDirectory(FWCodeDirectory, subDirectory);
- }
-
- private static string GetFLExBridgeFolderPath()
- {
- // Setting a Local Machine registry value is problematic for Linux/Mono. (FWNX-1180)
- // Try an alternative way of finding FLExBridge first.
- var dir = Environment.GetEnvironmentVariable("FLEXBRIDGEDIR");
- if (!String.IsNullOrEmpty(dir) && Directory.Exists(dir))
- return dir;
- var key = FwRegistryHelper.FieldWorksBridgeRegistryKeyLocalMachine;
- if (key != null)
- return GetDirectory(key, "InstallationDir", "");
- return "";
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Get a sub directory of the FW data directory,
- /// or return a tidied up version of the original path,
- /// if it is not in the FW data folder structure.
- ///
- /// examples: "Languages or \Languages"
- ///
- /// ------------------------------------------------------------------------------------
- public static string GetFWDataSubDirectory(string subDirectory)
- {
- return GetSubDirectory(FWDataDirectory, subDirectory);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Get a file in the FW code directory.
- ///
- /// examples: "iso-8859-1.tec"
- ///
- /// ------------------------------------------------------------------------------------
- public static string GetFWCodeFile(string filename)
- {
- return Path.Combine(FWCodeDirectory, filename);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the configuration settings for the specified project.
- ///
- /// The path to the project folder.
- /// ------------------------------------------------------------------------------------
- public static string GetConfigSettingsDir(string projectFolder)
- {
- return Path.Combine(projectFolder, ksConfigurationSettingsDir);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the backup settings for the specified project
- ///
- /// The path to the project folder.
- /// ------------------------------------------------------------------------------------
- public static string GetBackupSettingsDir(string projectFolder)
- {
- return Path.Combine(projectFolder, ksBackupSettingsDir);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the fonts for the specified project.
- ///
- /// The path to the project folder.
- /// ------------------------------------------------------------------------------------
- public static string GetSupportingFilesDir(string projectFolder)
- {
- return Path.Combine(projectFolder, ksSupportingFilesDir);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the writing systems for the specified project.
- ///
- /// The path to the project folder.
- /// ------------------------------------------------------------------------------------
- public static string GetWritingSystemDir(string projectFolder)
- {
- return Path.Combine(projectFolder, ksWritingSystemsDir);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path without the root directory (i.e. make it un-rooted).
- ///
- /// ------------------------------------------------------------------------------------
- public static string GetPathWithoutRoot(string pathWithRoot)
- {
- string pathRoot = Path.GetPathRoot(pathWithRoot);
- return pathWithRoot.Substring(pathRoot.Length);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Takes a windows path and returns it in the format which our backup zip files
- /// stores them in.
- ///
- /// ------------------------------------------------------------------------------------
- public static string GetZipfileFormattedPath(string path)
- {
- StringBuilder strBldr = new StringBuilder(path);
- string pathRoot = Path.GetPathRoot(path);
- strBldr.Remove(0, pathRoot.Length);
- // replace back slashes with forward slashes (for Windows)
- if (!MiscUtils.IsUnix && !MiscUtils.IsMac)
- strBldr.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
- return strBldr.ToString();
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the name of the XML data file, given a project name (basically just adds the
- /// FW data XML file extension).
- ///
- /// Name of the project (not a filename).
- /// ------------------------------------------------------------------------------------
- public static string GetXmlDataFileName(string projectName)
- {
- Debug.Assert(Path.GetExtension(projectName) != FwFileExtensions.ksFwDataXmlFileExtension,
- String.Format("There is a faint chance the user might have specified a real project name ending in {0} (in which case, sorry, but we're going to trim it off), but probably this is a programming error", FwFileExtensions.ksFwDataXmlFileExtension));
- // Do not use Path.ChangeExtension because it will strip off anything following a period in the project name!
- return projectName.EndsWith(FwFileExtensions.ksFwDataXmlFileExtension) ? projectName :
- projectName + FwFileExtensions.ksFwDataXmlFileExtension;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the name of the DB4O data file, given a project name (basically just adds the
- /// FW db4o file extension).
- ///
- /// Name of the project (not a filename).
- /// ------------------------------------------------------------------------------------
- public static string GetDb4oDataFileName(string projectName)
- {
- Debug.Assert(Path.GetExtension(projectName) != FwFileExtensions.ksFwDataDb4oFileExtension,
- String.Format("There is a faint chance the user might have specified a real project name ending in {0} (in which case, sorry, but we're going to trim it off), but probably this is a programming error", FwFileExtensions.ksFwDataDb4oFileExtension));
- // Do not use Path.ChangeExtension because it will strip off anything following a period in the project name!
- return projectName.EndsWith(FwFileExtensions.ksFwDataDb4oFileExtension) ? projectName :
- projectName + FwFileExtensions.ksFwDataDb4oFileExtension;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets a subdirectory of FieldWorks either by reading the
- /// or by getting .
- /// Will not return null.
- ///
- /// The name of the registry value to read from the FW root
- /// key in HKLM.
- /// The default directory to use if there is no value in the
- /// registry.
- ///
- /// The desired subdirectory of FieldWorks (without trailing directory separator).
- ///
- /// ------------------------------------------------------------------------------------
- private static string GetDirectory(string registryValue, string defaultDir)
- {
- using (var userKey = FwRegistryHelper.FieldWorksRegistryKey)
- using (var machineKey = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine)
- {
- var registryKey = userKey;
- if (userKey == null || userKey.GetValue(registryValue) == null)
- {
- registryKey = machineKey;
- }
-
- return GetDirectory(registryKey, registryValue, defaultDir);
- }
- }
-
- ///
- /// Get a directory for a particular key ignoring current user settings.
- ///
- ///
- ///
- ///
- private static string GetDirectoryLocalMachine(string registryValue, string defaultDir)
- {
- using (RegistryKey machineKey = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine)
- {
- return GetDirectory(machineKey, registryValue, defaultDir);
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets a subdirectory of FieldWorks either by reading the
- /// or by getting .
- /// Will not return null.
- ///
- /// The registry key where the value is stored.
- /// The name of the registry value under the given key that
- /// contains the desired directory.
- /// The default directory to use if there is no value in the
- /// registry.
- ///
- /// The desired subdirectory of FieldWorks (without trailing directory separator).
- ///
- /// If the desired directory could not be found.
- ///
- /// ------------------------------------------------------------------------------------
- private static string GetDirectory(RegistryKey registryKey, string registryValue,
- string defaultDir)
- {
- string rootDir = (registryKey == null) ? null : registryKey.GetValue(registryValue, null) as string;
-
- if (string.IsNullOrEmpty(rootDir) && !string.IsNullOrEmpty(defaultDir))
- rootDir = defaultDir;
- if (string.IsNullOrEmpty(rootDir))
- {
- throw new ApplicationException(
- ResourceHelper.GetResourceString("kstidInvalidInstallation"));
- }
- // Hundreds of callers of this method are using Path.Combine with the results.
- // Combine only works with a root directory if it is followed by \ (e.g., c:\)
- // so we don't want to trim the \ in this situation.
- string dir = rootDir.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
- return dir.Length > 2 ? dir : dir + Path.DirectorySeparatorChar;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the directory where FieldWorks code was installed (usually
- /// C:\Program Files\SIL\FieldWorks n).
- /// Will not return null.
- ///
- /// If an installation directory could not be
- /// found.
- /// ------------------------------------------------------------------------------------
- public static string FWCodeDirectory
- {
- get
- {
- string defaultDir = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), CompanyName),
- string.Format("FieldWorks {0}", FwUtils.SuiteVersion));
- return GetDirectory("RootCodeDir", defaultDir);
- }
- }
-
- private const string ksRootDataDir = "RootDataDir";
- private const string ksFieldWorks = "FieldWorks";
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the directory where FieldWorks data was installed (i.e. under AppData).
- ///
- /// If an installation directory could not be
- /// found.
- /// ------------------------------------------------------------------------------------
- public static string FWDataDirectory
- {
- get { return GetDirectory(ksRootDataDir, CommonAppDataFolder(ksFieldWorks)); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the directory where FieldWorks data was installed (i.e. under AppData),
- /// as it would be determined ignoring current user registry settings.
- ///
- /// If an installation directory could not be
- /// found.
- /// ------------------------------------------------------------------------------------
- public static string FWDataDirectoryLocalMachine
- {
- get { return GetDirectoryLocalMachine(ksRootDataDir, CommonAppDataFolder(ksFieldWorks)); }
- }
-
- private static string m_srcdir;
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the src dir (for running tests)
- ///
- /// ------------------------------------------------------------------------------------
- public static string FwSourceDirectory
- {
- get
- {
- if (!String.IsNullOrEmpty(m_srcdir))
- return m_srcdir;
- if (MiscUtils.IsUnix)
- {
- // Linux doesn't have the registry setting, at least while running tests,
- // so we'll assume the executing assembly is $FW/Output/Debug/FwUtils.dll,
- // and the source dir is $FW/Src.
- Uri uriBase = new Uri(Assembly.GetExecutingAssembly().CodeBase);
- var dir = Path.GetDirectoryName(Uri.UnescapeDataString(uriBase.AbsolutePath));
- dir = Path.GetDirectoryName(dir); // strip the parent directory name (Debug)
- dir = Path.GetDirectoryName(dir); // strip the parent directory again (Output)
- dir = Path.Combine(dir, "Src");
- if (!Directory.Exists(dir))
- throw new ApplicationException("Could not find the Src directory. Was expecting it at: " + dir);
- m_srcdir = dir;
- }
- else
- {
- string rootDir = null;
- if (FwRegistryHelper.FieldWorksRegistryKey != null)
- {
- rootDir = FwRegistryHelper.FieldWorksRegistryKey.GetValue("RootCodeDir") as string;
- }
- else if (FwRegistryHelper.FieldWorksRegistryKeyLocalMachine != null)
- {
- rootDir = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine.GetValue("RootCodeDir") as string;
- }
- if (string.IsNullOrEmpty(rootDir))
- {
- throw new ApplicationException(
- string.Format(@"You need to have the registry key {0}\RootCodeDir pointing at your DistFiles dir.",
- FwRegistryHelper.FieldWorksRegistryKeyLocalMachine.Name));
- }
- string fw = Directory.GetParent(rootDir).FullName;
- string src = Path.Combine(fw, "Src");
- if (!Directory.Exists(src))
- throw new ApplicationException(@"Could not find the Src directory. Was expecting it at: " + src);
- m_srcdir = src;
- }
- return m_srcdir;
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the full path name of the editorial checks directory.
- ///
- /// ------------------------------------------------------------------------------------
- public static string EditorialChecksDirectory
- {
- get
- {
- string directory = GetFWCodeSubDirectory(@"Editorial Checks");
- if (!Directory.Exists(directory))
- {
- string msg = ResourceHelper.GetResourceString("kstidUnableToFindEditorialChecks");
- throw new ApplicationException(string.Format(msg, directory));
- }
- return directory;
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the basic editorial checks DLL. Note that this is currently the ScrChecks DLL,
- /// but if we ever split this DLL to separate Scripture-specific checks from more
- /// generic checks that are really based on the WS and could be used to check any text,
- /// then this property should be made to return the DLL containing the punctuation
- /// patterns and characters checks.
- ///
- /// ------------------------------------------------------------------------------------
- public static string BasicEditorialChecksDll
- {
- get
- {
-#if RELEASE
- try
- {
-#endif
- string directory = EditorialChecksDirectory;
- string checksDll = Path.Combine(directory, "ScrChecks.dll");
- if (!File.Exists(checksDll))
- {
- string msg = ResourceHelper.GetResourceString("kstidUnableToFindEditorialChecks");
- throw new ApplicationException(string.Format(msg, directory));
- }
- return checksDll;
-#if RELEASE
- }
- catch (ApplicationException e)
- {
- throw new InstallationException(e);
- }
-#endif
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the dir where templates are installed
- ///
- /// ------------------------------------------------------------------------------------
- public static string TemplateDirectory
- {
- get { return GetFWCodeSubDirectory("Templates"); }
- }
-
- private const string ksProjects = "Projects";
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets or sets the dir where projects are stored. Setting to null will delete the HKCU
- /// key, so that the HKLM key (system default) will be used for this user.
- ///
- /// If user does not have permission to write to HKLM
- ///
- /// ------------------------------------------------------------------------------------
- public static string ProjectsDirectory
- {
- get { return GetDirectory(ksProjectsDir, Path.Combine(FWDataDirectory, ksProjects)); }
- set
- {
- if (ProjectsDirectory == value)
- return; // no change.
-
- using (var registryKey = FwRegistryHelper.FieldWorksRegistryKey)
- {
- if (value == null)
- {
- registryKey.DeleteValue(ksProjectsDir);
- }
- else
- {
- registryKey.SetValue(ksProjectsDir, value);
- }
- }
- }
- }
-
- ///
- /// The project directory that would be identified if we didn't have any current user registry settings.
- ///
- public static string ProjectsDirectoryLocalMachine
- {
- get { return GetDirectoryLocalMachine(ksProjectsDir, Path.Combine(FWDataDirectoryLocalMachine, ksProjects)); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Determines whether the given path is a direct sub folder of the projects directory.
- /// (This is typically true for the a project-specific folder.)
- ///
- /// The path.
- /// ------------------------------------------------------------------------------------
- public static bool IsSubFolderOfProjectsDirectory(string path)
- {
- return !string.IsNullOrEmpty(path) && Path.GetDirectoryName(path) == ProjectsDirectory;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the default directory for Backup files. This is per-user.
- ///
- /// If setting this value and the user does not have
- /// permission to write to HKCU (probably can never happen)
- /// ------------------------------------------------------------------------------------
- public static string DefaultBackupDirectory
- {
- get
- {
- // NOTE: SpecialFolder.MyDocuments returns $HOME on Linux
- string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
- // FWNX-501: use slightly different default path on Linux
- string defaultDir = MiscUtils.IsUnix ?
- Path.Combine(myDocs, "Documents/fieldworks/backups") :
- Path.Combine(Path.Combine(myDocs, "My FieldWorks"), "Backups");
-
- using (RegistryKey registryKey = FwRegistryHelper.FieldWorksRegistryKey.OpenSubKey("ProjectBackup"))
- return GetDirectory(registryKey, "DefaultBackupDirectory", defaultDir);
- }
- set
- {
- using (RegistryKey key = FwRegistryHelper.FieldWorksRegistryKey.CreateSubKey("ProjectBackup"))
- {
- if (key != null)
- key.SetValue("DefaultBackupDirectory", value);
- }
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the global writing system store directory. The directory is guaranteed to exist.
- ///
- /// ------------------------------------------------------------------------------------
- [SuppressMessage("Gendarme.Rules.Portability", "MonoCompatibilityReviewRule",
- Justification="Offending code is not executed on Linux")]
- public static string GlobalWritingSystemStoreDirectory
- {
- get
- {
- string path = CommonAppDataFolder(ksWritingSystemsDir);
- if (!Directory.Exists(path))
- {
- DirectoryInfo di;
-
- // Provides FW on Linux multi-user access. Overrides the system
- // umask and creates the directory with the permissions "775".
- // The "fieldworks" group was created outside the app during
- // configuration of the package which allows group access.
- using(new FileModeOverride())
- {
- di = Directory.CreateDirectory(path);
- }
-
- if (!MiscUtils.IsUnix)
- {
- // NOTE: GetAccessControl/ModifyAccessRule/SetAccessControl is not implemented in Mono
- DirectorySecurity ds = di.GetAccessControl();
- var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
- AccessRule rule = new FileSystemAccessRule(sid, FileSystemRights.Write | FileSystemRights.ReadAndExecute
- | FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
- PropagationFlags.InheritOnly, AccessControlType.Allow);
- bool modified;
- ds.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
- di.SetAccessControl(ds);
- }
- }
- return path;
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the biblical key terms localization files.
- ///
- /// ------------------------------------------------------------------------------------
- static public string[] KeyTermsLocalizationFiles
- {
- get
- {
- // SE version doesn't install the TE folder.
- if (!Directory.Exists(TeFolder))
- return new string[]{""};
- return Directory.GetFiles(TeFolder, ksBiblicaltermsLocFilePrefix + "*" +
- ksBiblicaltermsLocFileExtension, SearchOption.TopDirectoryOnly);
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Returns the file name containing the localization of the key terms list for the
- /// given ICU locale.
- ///
- /// ------------------------------------------------------------------------------------
- static public string GetKeyTermsLocFilename(string locale)
- {
- return Path.Combine(TeFolder, ksBiblicaltermsLocFilePrefix + locale +
- ksBiblicaltermsLocFileExtension);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Extracts the locale identifier (string) from a key terms localization file name.
- ///
- /// ------------------------------------------------------------------------------------
- static public string GetLocaleFromKeyTermsLocFile(string locFilename)
- {
- return Path.GetFileName(locFilename).Replace(ksBiblicaltermsLocFilePrefix,
- String.Empty).Replace(ksBiblicaltermsLocFileExtension, String.Empty);
- }
-
- #region ExternalLinks folders
- //This region has all methods which return the values for the ExternalLinks files associated with a project.
- //This includes .../ProjectName/LinkedFiles and all subfolders. i.e. Pictures, AudioVisual and Others.
-
-
- ///
- /// Gets the path to the standard eternal linked files directory for the specified project.
- ///
- /// The path to the project.
- ///
- public static string GetDefaultLinkedFilesDir(string projectPath)
- {
- return Path.Combine(projectPath, ksLinkedFilesDir);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the standard media files directory for the specified project. Note
- /// that if this project keepes its externally linked files in a separate folder from
- /// the rest of the project files (such as a shared folder common to multiple projects
- /// on a server), the directory returned by this method will not actually contain any
- /// files.
- ///
- /// The path to the project.
- /// ------------------------------------------------------------------------------------
- public static string GetDefaultMediaDir(string projectPath)
- {
- return Path.Combine(projectPath, Path.Combine(ksLinkedFilesDir, ksMediaDir));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the standard pictures directory for the specified project. Note
- /// that if this project keepes its externally linked files in a separate folder from
- /// the rest of the project files (such as a shared folder common to multiple projects
- /// on a server), the directory returned by this method will not actually contain any
- /// files.
- ///
- /// The path to the project.
- /// ------------------------------------------------------------------------------------
- public static string GetDefaultPicturesDir(string projectPath)
- {
- return Path.Combine(projectPath, Path.Combine(ksLinkedFilesDir, ksPicturesDir));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the standard directory for other externally linked project files.
- /// Note that if this project keepes its externally linked files in a separate folder
- /// from the rest of the project files (such as a shared folder common to multiple
- /// projects on a server), the directory returned by this method will not actually
- /// contain any files.
- ///
- /// The path to the project.
- /// ------------------------------------------------------------------------------------
- public static string GetDefaultOtherExternalFilesDir(string projectPath)
- {
- return Path.Combine(projectPath, Path.Combine(ksLinkedFilesDir, ksOtherLinkedFilesDir));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the media files directory for the project.
- ///
- /// The project's LinkedFiles path. (eg. m_cache.LangProject.LinkedFilesRootDir)
- /// ------------------------------------------------------------------------------------
- public static string GetMediaDir(string projectLinkedFilesPath)
- {
- return Path.Combine(projectLinkedFilesPath, ksMediaDir);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the pictures directory for the project.
- ///
- /// The project's LinkedFiles path. (eg. m_cache.LangProject.LinkedFilesRootDir)
- /// ------------------------------------------------------------------------------------
- public static string GetPicturesDir(string projectLinkedFilesPath)
- {
- return Path.Combine(projectLinkedFilesPath, ksPicturesDir);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the path to the directory for other externally linked project files.
- ///
- /// The project's LinkedFiles path. (eg. m_cache.LangProject.LinkedFilesRootDir)
- /// ------------------------------------------------------------------------------------
- public static string GetOtherExternalFilesDir(string projectLinkedFilesPath)
- {
- return Path.Combine(projectLinkedFilesPath, ksOtherLinkedFilesDir);
- }
-
- #endregion
- }
-
- ///
- /// This class is designed for converting between relative paths and full paths for the LinkedFiles of a FW project
- ///
- public class DirectoryFinderRelativePaths
- {
- /// Substitution string for a path that is under the LinkedFiles directory.
- public const string ksLFrelPath = "%lf%";
- /// Substitution string for a path that is under the project's directory.
- public const string ksProjectRelPath = "%proj%";
- /// Substitution string for a path that is under the default directory for projects.
- public const string ksProjectsRelPath = "%Projects%";
- /// Substitution string for a path that is under the My Documents directory.
- public const string ksMyDocsRelPath = "%MyDocuments%";
- /// Substitution string for a path that is under the Shared Application Data directory.
- public const string ksCommonAppDataRelPath = "%CommonApplicationData%";
-
- #region Methods to covert between RelativePaths and FullPaths
-
- ///
- /// If a filePath is stored in the format %lf%\path\filename then this method returns the full path.
- /// Otherwise return null
- ///
- ///
- ///
- ///
- public static String GetFullFilePathFromRelativeLFPath(string relativePath, string projectLinkedFilesPath)
- {
- String fullfilePath = null;
- fullfilePath = GetFullPathForRelativePath(relativePath, ksLFrelPath, projectLinkedFilesPath);
-
- if (String.IsNullOrEmpty(fullfilePath))
- return null;
- return FixPathSlashesIfNeeded(fullfilePath);
- }
-
- ///
- /// If a file path is non rooted then return combination of the linkedFiledRootDir and the relative
- /// path. Otherwise just return the full path passed in as an arguement.
- ///
- ///
- ///
- ///
- public static String GetFullPathFromRelativeLFPath(string relativeLFPath, string linkedFilesRootDir)
- {
- // We could just catch the exception that IsPathRooted throws if there are invalid characters,
- // or use Path.GetInvalidPathChars(). But that would pass things on Linux that will fail on Windows,
- // which both makes unit testing difficult, and also may hide from Linux users the fact that their
- // paths will cause problems on Windows.
- var invalidChars = MiscUtils.GetInvalidProjectNameChars(MiscUtils.FilenameFilterStrength.kFilterProjName);
- // relativeLFPath is allowed to include directories. And it MAY be rooted, meaning on Windows it could start X:
- invalidChars = invalidChars.Replace(@"\", "").Replace("/", "").Replace(":", "");
- // colon is allowed only as second character--such a path is probably no good on Linux, but will just be not found, not cause a crash
- int indexOfColon = relativeLFPath.IndexOf(':');
- if (relativeLFPath.IndexOfAny(invalidChars.ToCharArray()) != -1
- || (indexOfColon != -1 && indexOfColon != 1))
- {
- // This is a fairly clumsy solution, designed as a last-resort way to avoid crashing the program.
- // Hopefully most paths for entering path names into the relevant fields do something nicer to
- // avoid getting illegal characters there.
- return FixPathSlashesIfNeeded(Path.Combine(linkedFilesRootDir, "__ILLEGALCHARS__"));
- }
- if (Path.IsPathRooted(relativeLFPath))
- return FixPathSlashesIfNeeded(relativeLFPath);
- else
- return FixPathSlashesIfNeeded(Path.Combine(linkedFilesRootDir, relativeLFPath));
- }
-
- ///
- /// If a path gets stored with embedded \, fix it to work away from Windows. (FWNX-882)
- ///
- public static string FixPathSlashesIfNeeded(string path)
- {
- if (string.IsNullOrEmpty(path))
- return string.Empty;
- if (MiscUtils.IsUnix || MiscUtils.IsMac)
- {
- if (path.Contains("\\"))
- return path.Replace('\\', '/');
- }
- return path;
- }
-
- ///
- /// If the path is relative to the project's linkedFiles path then substitute %lf%
- /// and return it. Otherwise return an empty string
- ///
- ///
- ///
- ///
- public static string GetRelativeLFPathFromFullFilePath(string filePath,
- string projectLinkedFilesPath)
- {
- if (string.IsNullOrEmpty(projectLinkedFilesPath))
- return string.Empty;
-
- var linkedFilesPathLowercaseRoot = GetPathWithLowercaseRoot(filePath);
-
- var relativePath = GetRelativePathIfExists(ksLFrelPath, linkedFilesPathLowercaseRoot,
- projectLinkedFilesPath);
- if (!string.IsNullOrEmpty(relativePath))
- return FixPathSlashesIfNeeded(relativePath);
- //Just return an empty path if we cannot find a relative path.
- return string.Empty;
- }
-
- ///
- /// If the specified path starts with the LinkedFiles root directory then return
- /// the part after the linkedFilesRootDir;
- /// otherwise if it is a file path at all convert it to the current platform and return it;
- /// otherwise (it's a URL, determined by containing a colon after more than one initial character)
- /// return null to indicate no change made.
- ///
- ///
- ///
- ///
- public static string GetRelativeLinkedFilesPath(string filePath,
- string linkedFilesRootDir)
- {
- if (filePath.IndexOf(':') > 1)
- {
- // It's a URL, not a path at all; don't mess with it.
- return null;
- }
- string directory = FileUtils.ChangePathToPlatform(linkedFilesRootDir);
- string relativePath = FileUtils.ChangePathToPlatform(filePath);
-
- // Does the specified path start with the LinkedFiles root directory?
- if (relativePath.StartsWith(directory, true, System.Globalization.CultureInfo.InvariantCulture) &&
- relativePath.Length > directory.Length + 1)
- {
- // Keep the portion of the specified path that is a subfolder of
- // the LinkedFiles folder and make sure to strip off an initial
- // path separator if there is one.
- relativePath = relativePath.Substring(directory.Length);
- if (relativePath[0] == Path.DirectorySeparatorChar)
- relativePath = relativePath.Substring(1);
- }
- return FixPathSlashesIfNeeded(relativePath);
- }
-
-
- ///
- /// Return the fullPath for a project's LinkedFiles based on the relative path that was persisted.
- /// If no match on a relativePath match is made then return the relativePath passed in assuming it
- /// is actually a full path.
- ///
- ///
- ///
- ///
- public static String GetLinkedFilesFullPathFromRelativePath(string relativePath, String projectPath)
- {
- String fullPath = null;
- fullPath = GetFullPathForRelativePath(relativePath, ksProjectRelPath, projectPath);
-
- if (String.IsNullOrEmpty(fullPath))
- fullPath = GetFullPathForRelativePath(relativePath, ksProjectsRelPath,
- DirectoryFinder.ProjectsDirectory);
- if (String.IsNullOrEmpty(fullPath))
- fullPath = GetFullPathForRelativePath(relativePath, ksCommonAppDataRelPath,
- DirectoryFinder.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
- if (String.IsNullOrEmpty(fullPath))
- fullPath = GetFullPathForRelativePath(relativePath, ksMyDocsRelPath,
- DirectoryFinder.GetFolderPath(Environment.SpecialFolder.MyDocuments));
- if (String.IsNullOrEmpty(fullPath))
- return FixPathSlashesIfNeeded(relativePath);
- return FixPathSlashesIfNeeded(fullPath);
- }
-
- private static String GetFullPathForRelativePath(String relativePath, String relativePart, String fullPathReplacement)
- {
- if (relativePath.StartsWith(relativePart))
- {
- var length = relativePart.Length;
- var restOfPath = relativePath.Substring(length, relativePath.Length - length);
- return fullPathReplacement + restOfPath;
- }
- else
- {
- return string.Empty;
- }
- }
-
- ///
- /// Get a relative path for the LinkedFilesPath which we will persist to be used when
- /// restoring a project.
- ///
- ///
- ///
- ///
- ///
- public static string GetLinkedFilesRelativePathFromFullPath(string linkedFilesFullPath,
- string projectPath, string projectName)
- {
- var linkedFilesPathLowercaseRoot = GetPathWithLowercaseRoot(linkedFilesFullPath);
- // Case where the ExternalLinks folder is located somewhere under the project folder.
- // This is the default location.
- var relativePath = GetRelativePathIfExists(ksProjectRelPath, linkedFilesPathLowercaseRoot,
- projectPath);
- if (!string.IsNullOrEmpty(relativePath))
- return FixPathSlashesIfNeeded(relativePath);
- // GetRelativePathIfExists may miss a case where, say, projectPath is
- // \\ls-thomson-0910.dallas.sil.org\Projects\MyProj, and linkedFilesFullPath is
- // C:\Documents and settings\All Users\SIL\FieldWorks\Projects\MyProj\LinkedFiles
- // Even though the MyProj directory in both paths is the same directory.
- // It's important to catch this case and return a relative path.
- var projectFolderName = Path.GetFileName(projectPath);
- var projectsPath = Path.GetDirectoryName(projectPath);
- var allProjectsName = Path.GetFileName(projectsPath);
- var match = Path.Combine(allProjectsName, projectFolderName);
- int index = linkedFilesFullPath.IndexOf(match, StringComparison.InvariantCultureIgnoreCase);
- if (index >= 0)
- {
- // There's a very good chance these are the same folders!
- var alternateProjectPath = linkedFilesFullPath.Substring(0, index + match.Length);
- if (Directory.Exists(alternateProjectPath) &&
- Directory.GetLastWriteTime(alternateProjectPath) == Directory.GetLastWriteTime(projectPath))
- {
- // They ARE the same directory! (I suppose we could miss if someone wrote to it at the
- // exact wrong moment, but we shouldn't be changing this setting while shared, anyway.)
- return FixPathSlashesIfNeeded(ksProjectRelPath + linkedFilesFullPath.Substring(index + match.Length));
- }
- }
-
- //See if linkedFilesPath begins with one of the other standard paths.
-
- // Case where user is presumably having a LinkedFiles folder shared among a number
- // of projects under the Projects folder. That would be a good reason to put it in
- // the projects folder common to all projects.
- relativePath = GetRelativePathIfExists(ksProjectsRelPath, linkedFilesPathLowercaseRoot,
- DirectoryFinder.ProjectsDirectory);
- if (!String.IsNullOrEmpty(relativePath))
- return FixPathSlashesIfNeeded(relativePath);
-
- // Case where the user has the LinkedFiles folder in a shared folder.
- relativePath = GetRelativePathIfExists(ksCommonAppDataRelPath,
- linkedFilesPathLowercaseRoot, DirectoryFinder.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
- if (!string.IsNullOrEmpty(relativePath))
- return FixPathSlashesIfNeeded(relativePath);
-
- // Case where the user has the LinkedFiles folder in their MyDocuments folder
- relativePath = GetRelativePathIfExists(ksMyDocsRelPath,
- linkedFilesPathLowercaseRoot,
- DirectoryFinder.GetFolderPath(Environment.SpecialFolder.MyDocuments));
- if (!string.IsNullOrEmpty(relativePath))
- return FixPathSlashesIfNeeded(relativePath);
-
- //Just return the complete path if we cannot find a relative path.
- return FixPathSlashesIfNeeded(linkedFilesFullPath);
- }
-
- private static string GetRelativePathIfExists(string relativePart, string fullPath,
- string parentPath)
- {
- var parentPathLowerCaseRoot = GetPathWithLowercaseRoot(parentPath);
- if (!string.IsNullOrEmpty(parentPathLowerCaseRoot) &&
- fullPath.StartsWith(parentPathLowerCaseRoot))
- {
- var length = parentPath.Length;
- var restOfPath = fullPath.Substring(length, fullPath.Length - length);
- return relativePart + restOfPath;
- }
- return string.Empty;
- }
-
- private static string GetPathWithLowercaseRoot(string path)
- {
- try
- {
- var rootOfPath = Path.GetPathRoot(path);
- return rootOfPath.ToLowerInvariant() +
- path.Substring(rootOfPath.Length, path.Length - rootOfPath.Length);
- }
- catch (ArgumentException e)
- {
- return path.ToLowerInvariant();
- }
- }
-
-
- #endregion
- }
-}
diff --git a/Src/Common/FwUtils/FLExBridgeHelper.cs b/Src/Common/FwUtils/FLExBridgeHelper.cs
index 48073140e1..4b388bb388 100644
--- a/Src/Common/FwUtils/FLExBridgeHelper.cs
+++ b/Src/Common/FwUtils/FLExBridgeHelper.cs
@@ -120,13 +120,9 @@ public class FLExBridgeHelper
#endregion End of available '-v' parameter options:
- // The two paths of a path that locate the Lift repository within a FLEx project.
///
- /// constant for locating the nested lift repository (part 1 of 2)
- ///
- public const string OtherRepositories = @"OtherRepositories";
- ///
- /// constant for locating the nested lift repository (part 2 of 2)
+ /// constant for locating the nested lift repository (within the "OtherRepositories" path of a project).
+ /// See also SIL.FieldWorks.FDO.FdoFileHelper.OtherRepositories
///
public const string LIFT = @"LIFT";
@@ -195,7 +191,7 @@ public static bool LaunchFieldworksBridge(string projectFolder, string userName,
if (!String.IsNullOrEmpty(projectFolder))
{ // can S/R multiple projects simultaneously
AddArg(ref args, "-p", projectFolder);
- if (projectFolder != DirectoryFinder.ProjectsDirectory)
+ if (projectFolder != FwDirectoryFinder.ProjectsDirectory)
_sFwProjectName = Path.GetFileNameWithoutExtension(projectFolder); // REVIEW (Hasso) 2014.01: this variable is never read
}
@@ -212,7 +208,7 @@ public static bool LaunchFieldworksBridge(string projectFolder, string userName,
}
// Add two paths: to FW projDir & FW apps folder. Then, FB won't have to look in a zillion registry entries
- AddArg(ref args, "-projDir", DirectoryFinder.ProjectsDirectory);
+ AddArg(ref args, "-projDir", FwDirectoryFinder.ProjectsDirectory);
AddArg(ref args, "-fwAppsDir", FieldWorksAppsDir);
// Tell Flex Bridge which model version of data are expected by FLEx.
AddArg(ref args, "-fwmodel", fwmodelVersionNumber.ToString());
@@ -350,7 +346,7 @@ private static void AddArg(ref string extant, string flag, string value)
///
public static string FullFieldWorksBridgePath()
{
- return Path.Combine(DirectoryFinder.FlexBridgeFolder, FLExBridgeName);
+ return Path.Combine(FwDirectoryFinder.FlexBridgeFolder, FLExBridgeName);
}
///
diff --git a/Src/Common/FwUtils/FwDirectoryFinder.cs b/Src/Common/FwUtils/FwDirectoryFinder.cs
new file mode 100644
index 0000000000..1551201c08
--- /dev/null
+++ b/Src/Common/FwUtils/FwDirectoryFinder.cs
@@ -0,0 +1,698 @@
+// Copyright (c) 2003-2014 SIL International
+// This software is licensed under the LGPL, version 2.1 or later
+// (http://www.gnu.org/licenses/lgpl-2.1.html)
+//
+// File: FwDirectoryFinder.cs
+//
+//
+// To find the current user's "My Documents" folder, use something like:
+// string sMyDocs = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
+// See the MSDN documentation for the System.Environment.SpecialFolder enumeration for details.
+//
+
+using System;
+using System.IO;
+using System.Diagnostics;
+using System.Reflection;
+using System.Security;
+using Microsoft.Win32;
+using SIL.CoreImpl;
+using SIL.FieldWorks.FDO;
+using SIL.FieldWorks.Resources;
+using SIL.Utils;
+
+namespace SIL.FieldWorks.Common.FwUtils
+{
+ ///
+ /// This class is used to find files and directories for FW apps.
+ ///
+ public static class FwDirectoryFinder
+ {
+ ///
+ /// The name of the Translation Editor folder (Even though this is the same as
+ /// FwUtils.ksTeAppName and FwSubKey.TE, PLEASE do not use them interchangeably. Use
+ /// the one that is correct for your context, in case they need to be changed later.)
+ ///
+ public const string ksTeFolderName = FwUtils.ksTeAppName;
+ ///
+ /// The name of the Language Explorer folder (Even though this is the same as
+ /// FwUtils.ksFlexAppName and FwSubKey.LexText, PLEASE do not use them interchangeably.
+ /// Use the one that is correct for your context, in case they need to be changed later.)
+ ///
+ public const string ksFlexFolderName = FwUtils.ksFlexAppName;
+
+ /// The Scripture-specific stylesheet (ideally, this would be in a TE-specific place, but FDO needs it)
+ public const string kTeStylesFilename = "TeStyles.xml";
+
+ /// The name of the folder containing global writing systems.
+ /// Also see SIL.FieldWorks.FDO.FdoFileHelper.ksWritingSystemsDir
+ /// for the project-level directory.
+ private const string ksWritingSystemsDir = "WritingSystemStore";
+
+ private const string ksBiblicaltermsLocFilePrefix = "BiblicalTerms-";
+ private const string ksBiblicaltermsLocFileExtension = ".xml";
+ private const string ksProjectsDir = "ProjectsDir";
+
+ private static readonly IFdoDirectories s_fdoDirs = new FwFdoDirectories();
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the Scripture-specific stylesheet.
+ /// This should NOT be in the TE folder, because it is used by the SE edition, when
+ /// doing minimal scripture initialization in order to include Paratext texts.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string TeStylesPath
+ {
+ get { return Path.Combine(CodeDirectory, kTeStylesFilename); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the folder where TE-specific files are installed.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string TeFolder
+ {
+ get { return GetCodeSubDirectory(ksTeFolderName); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the folder where FLEx-specific files are installed.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string FlexFolder
+ {
+ get { return GetCodeSubDirectory(ksFlexFolderName); }
+ }
+
+ ///
+ /// Return the folder in which FlexBridge resides, or empty string if it is not installed.
+ ///
+ public static string FlexBridgeFolder
+ {
+ get { return GetFLExBridgeFolderPath(); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the Translation Editor executable.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string TeExe
+ {
+ get { return ExeOrDllPath("TE.exe"); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the Translation Editor dynamic load library.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string TeDll
+ {
+ get { return ExeOrDllPath("TeDll.dll"); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the FW Language Explorer executable.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string FlexExe
+ {
+ get { return ExeOrDllPath("Flex.exe"); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the FW Language Explorer dynamic load library.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string FlexDll
+ {
+ get { return ExeOrDllPath("LexTextDll.dll"); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the Migrate SQL databases executable.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string MigrateSqlDbsExe
+ {
+ get { return ExeOrDllPath("MigrateSqlDbs.exe"); }
+ }
+
+ ///
+ /// Gets the path to MSSQLMigration\Db.exe.
+ ///
+ public static string DbExe
+ {
+ get { return Path.Combine(GetCodeSubDirectory("MSSQLMigration"), "db.exe"); }
+ }
+
+ ///
+ /// Gets the converter console executable.
+ ///
+ public static string ConverterConsoleExe
+ {
+ get { return ExeOrDllPath("ConverterConsole.exe"); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the config file
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string RemotingTcpServerConfigFile
+ {
+ get
+ {
+ if (MiscUtils.RunningTests)
+ return ExeOrDllPath("remoting_tcp_server_tests.config");
+ return ExeOrDllPath("remoting_tcp_server.config");
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path of the requested executable/dll file in the folder from which FW
+ /// is being executed.
+ ///
+ /// Name of the file (case-sensistive, with the extension)
+ /// ------------------------------------------------------------------------------------
+ private static string ExeOrDllPath(string file)
+ {
+ if (file == null)
+ throw new ArgumentNullException("file");
+
+ if (Assembly.GetEntryAssembly() == null)
+ {
+ // This seems to happen when tests call this method when run from NUnit
+ // for some reason.
+
+ // The following code should only run by unittests.
+#if DEBUG
+ const string arch = "Debug";
+#else
+ const string arch = "Release";
+#endif
+ return Path.Combine(Path.Combine(Path.Combine(Path.GetDirectoryName(SourceDirectory), "Output"), arch), file);
+ }
+
+ return Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), file);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Get a sub directory of the given ,
+ /// or return a tidied up version of the original path,
+ /// if it is not in the FW code folder structure.
+ ///
+ /// Base directory.
+ /// examples: "WW\XAMPLE or \WW\XAMPLE"
+ ///
+ /// ------------------------------------------------------------------------------------
+ private static string GetSubDirectory(string directory, string subDirectory)
+ {
+ Debug.Assert(subDirectory != null);
+
+ string retval = subDirectory.Trim();
+ if (retval.Length > 0 && (retval[0] == Path.DirectorySeparatorChar
+ || retval[0] == Path.AltDirectorySeparatorChar))
+ {
+ // remove leading directory separator from subdirectory
+ retval = retval.Substring(1);
+ }
+ string possiblePath = Path.Combine(directory, retval);
+ if (Directory.Exists(possiblePath))
+ retval = possiblePath;
+ // Implicit 'else' assumes it to be a full path,
+ // but not in the code folder structure.
+ // Sure hope the caller can handle it.
+
+#if __MonoCS__
+ else if (!Directory.Exists(retval)) // previous Substring(1) causes problem for 'full path' in Linux
+ return subDirectory;
+#endif
+
+ return retval;
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Get a sub directory of the FW code directory,
+ /// or return a tidied up version of the original path,
+ /// if it is not in the FW code folder structure.
+ ///
+ /// examples: "WW\XAMPLE or \WW\XAMPLE"
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string GetCodeSubDirectory(string subDirectory)
+ {
+ return GetSubDirectory(CodeDirectory, subDirectory);
+ }
+
+ private static string GetFLExBridgeFolderPath()
+ {
+ // Setting a Local Machine registry value is problematic for Linux/Mono. (FWNX-1180)
+ // Try an alternative way of finding FLExBridge first.
+ var dir = Environment.GetEnvironmentVariable("FLEXBRIDGEDIR");
+ if (!String.IsNullOrEmpty(dir) && Directory.Exists(dir))
+ return dir;
+ var key = FwRegistryHelper.FieldWorksBridgeRegistryKeyLocalMachine;
+ if (key != null)
+ return GetDirectory(key, "InstallationDir", "");
+ return "";
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Get a sub directory of the FW data directory,
+ /// or return a tidied up version of the original path,
+ /// if it is not in the FW data folder structure.
+ ///
+ /// examples: "Languages or \Languages"
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string GetDataSubDirectory(string subDirectory)
+ {
+ return GetSubDirectory(DataDirectory, subDirectory);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Get a file in the FW code directory.
+ ///
+ /// examples: "iso-8859-1.tec"
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string GetCodeFile(string filename)
+ {
+ return Path.Combine(CodeDirectory, filename);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets a subdirectory of FieldWorks either by reading the
+ /// or by getting .
+ /// Will not return null.
+ ///
+ /// The name of the registry value to read from the FW root
+ /// key in HKLM.
+ /// The default directory to use if there is no value in the
+ /// registry.
+ ///
+ /// The desired subdirectory of FieldWorks (without trailing directory separator).
+ ///
+ /// ------------------------------------------------------------------------------------
+ private static string GetDirectory(string registryValue, string defaultDir)
+ {
+ using (var userKey = FwRegistryHelper.FieldWorksRegistryKey)
+ using (var machineKey = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine)
+ {
+ var registryKey = userKey;
+ if (userKey == null || userKey.GetValue(registryValue) == null)
+ {
+ registryKey = machineKey;
+ }
+
+ return GetDirectory(registryKey, registryValue, defaultDir);
+ }
+ }
+
+ ///
+ /// Get a directory for a particular key ignoring current user settings.
+ ///
+ ///
+ ///
+ ///
+ private static string GetDirectoryLocalMachine(string registryValue, string defaultDir)
+ {
+ using (RegistryKey machineKey = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine)
+ {
+ return GetDirectory(machineKey, registryValue, defaultDir);
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets a subdirectory of FieldWorks either by reading the
+ /// or by getting .
+ /// Will not return null.
+ ///
+ /// The registry key where the value is stored.
+ /// The name of the registry value under the given key that
+ /// contains the desired directory.
+ /// The default directory to use if there is no value in the
+ /// registry.
+ ///
+ /// The desired subdirectory of FieldWorks (without trailing directory separator).
+ ///
+ /// If the desired directory could not be found.
+ ///
+ /// ------------------------------------------------------------------------------------
+ private static string GetDirectory(RegistryKey registryKey, string registryValue,
+ string defaultDir)
+ {
+ string rootDir = (registryKey == null) ? null : registryKey.GetValue(registryValue, null) as string;
+
+ if (string.IsNullOrEmpty(rootDir) && !string.IsNullOrEmpty(defaultDir))
+ rootDir = defaultDir;
+ if (string.IsNullOrEmpty(rootDir))
+ {
+ throw new ApplicationException(
+ ResourceHelper.GetResourceString("kstidInvalidInstallation"));
+ }
+ // Hundreds of callers of this method are using Path.Combine with the results.
+ // Combine only works with a root directory if it is followed by \ (e.g., c:\)
+ // so we don't want to trim the \ in this situation.
+ string dir = rootDir.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
+ return dir.Length > 2 ? dir : dir + Path.DirectorySeparatorChar;
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the directory where FieldWorks code was installed (usually
+ /// C:\Program Files\SIL\FieldWorks n).
+ /// Will not return null.
+ ///
+ /// If an installation directory could not be
+ /// found.
+ /// ------------------------------------------------------------------------------------
+ public static string CodeDirectory
+ {
+ get
+ {
+ string defaultDir = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), DirectoryFinder.CompanyName),
+ string.Format("FieldWorks {0}", FwUtils.SuiteVersion));
+ return GetDirectory("RootCodeDir", defaultDir);
+ }
+ }
+
+ private const string ksRootDataDir = "RootDataDir";
+ private const string ksFieldWorks = "FieldWorks";
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the directory where FieldWorks data was installed (i.e. under AppData).
+ ///
+ /// If an installation directory could not be
+ /// found.
+ /// ------------------------------------------------------------------------------------
+ public static string DataDirectory
+ {
+ get { return GetDirectory(ksRootDataDir, DirectoryFinder.CommonAppDataFolder(ksFieldWorks)); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the directory where FieldWorks data was installed (i.e. under AppData),
+ /// as it would be determined ignoring current user registry settings.
+ ///
+ /// If an installation directory could not be
+ /// found.
+ /// ------------------------------------------------------------------------------------
+ public static string DataDirectoryLocalMachine
+ {
+ get { return GetDirectoryLocalMachine(ksRootDataDir, DirectoryFinder.CommonAppDataFolder(ksFieldWorks)); }
+ }
+
+ private static string m_srcdir;
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the src dir (for running tests)
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string SourceDirectory
+ {
+ get
+ {
+ if (!String.IsNullOrEmpty(m_srcdir))
+ return m_srcdir;
+ if (MiscUtils.IsUnix)
+ {
+ // Linux doesn't have the registry setting, at least while running tests,
+ // so we'll assume the executing assembly is $FW/Output/Debug/FwUtils.dll,
+ // and the source dir is $FW/Src.
+ Uri uriBase = new Uri(Assembly.GetExecutingAssembly().CodeBase);
+ var dir = Path.GetDirectoryName(Uri.UnescapeDataString(uriBase.AbsolutePath));
+ dir = Path.GetDirectoryName(dir); // strip the parent directory name (Debug)
+ dir = Path.GetDirectoryName(dir); // strip the parent directory again (Output)
+ dir = Path.Combine(dir, "Src");
+ if (!Directory.Exists(dir))
+ throw new ApplicationException("Could not find the Src directory. Was expecting it at: " + dir);
+ m_srcdir = dir;
+ }
+ else
+ {
+ string rootDir = null;
+ if (FwRegistryHelper.FieldWorksRegistryKey != null)
+ {
+ rootDir = FwRegistryHelper.FieldWorksRegistryKey.GetValue("RootCodeDir") as string;
+ }
+ else if (FwRegistryHelper.FieldWorksRegistryKeyLocalMachine != null)
+ {
+ rootDir = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine.GetValue("RootCodeDir") as string;
+ }
+ if (string.IsNullOrEmpty(rootDir))
+ {
+ throw new ApplicationException(
+ string.Format(@"You need to have the registry key {0}\RootCodeDir pointing at your DistFiles dir.",
+ FwRegistryHelper.FieldWorksRegistryKeyLocalMachine.Name));
+ }
+ string fw = Directory.GetParent(rootDir).FullName;
+ string src = Path.Combine(fw, "Src");
+ if (!Directory.Exists(src))
+ throw new ApplicationException(@"Could not find the Src directory. Was expecting it at: " + src);
+ m_srcdir = src;
+ }
+ return m_srcdir;
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the full path name of the editorial checks directory.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string EditorialChecksDirectory
+ {
+ get
+ {
+ string directory = GetCodeSubDirectory(@"Editorial Checks");
+ if (!Directory.Exists(directory))
+ {
+ string msg = ResourceHelper.GetResourceString("kstidUnableToFindEditorialChecks");
+ throw new ApplicationException(string.Format(msg, directory));
+ }
+ return directory;
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the basic editorial checks DLL. Note that this is currently the ScrChecks DLL,
+ /// but if we ever split this DLL to separate Scripture-specific checks from more
+ /// generic checks that are really based on the WS and could be used to check any text,
+ /// then this property should be made to return the DLL containing the punctuation
+ /// patterns and characters checks.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string BasicEditorialChecksDll
+ {
+ get
+ {
+#if RELEASE
+ try
+ {
+#endif
+ string directory = EditorialChecksDirectory;
+ string checksDll = Path.Combine(directory, "ScrChecks.dll");
+ if (!File.Exists(checksDll))
+ {
+ string msg = ResourceHelper.GetResourceString("kstidUnableToFindEditorialChecks");
+ throw new ApplicationException(string.Format(msg, directory));
+ }
+ return checksDll;
+#if RELEASE
+ }
+ catch (ApplicationException e)
+ {
+ throw new InstallationException(e);
+ }
+#endif
+ }
+ }
+
+ ///
+ /// Gets the legacy wordforming character overrides file.
+ ///
+ public static string LegacyWordformingCharOverridesFile
+ {
+ get
+ {
+ return Path.Combine(CodeDirectory, "WordFormingCharOverrides.xml");
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the dir where templates are installed
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string TemplateDirectory
+ {
+ get { return GetCodeSubDirectory("Templates"); }
+ }
+
+ private const string ksProjects = "Projects";
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets or sets the dir where projects are stored. Setting to null will delete the HKCU
+ /// key, so that the HKLM key (system default) will be used for this user.
+ ///
+ /// If user does not have permission to write to HKLM
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string ProjectsDirectory
+ {
+ get { return GetDirectory(ksProjectsDir, Path.Combine(DataDirectory, ksProjects)); }
+ set
+ {
+ if (ProjectsDirectory == value)
+ return; // no change.
+
+ using (var registryKey = FwRegistryHelper.FieldWorksRegistryKey)
+ {
+ if (value == null)
+ {
+ registryKey.DeleteValue(ksProjectsDir);
+ }
+ else
+ {
+ registryKey.SetValue(ksProjectsDir, value);
+ }
+ }
+ }
+ }
+
+ ///
+ /// The project directory that would be identified if we didn't have any current user registry settings.
+ ///
+ public static string ProjectsDirectoryLocalMachine
+ {
+ get { return GetDirectoryLocalMachine(ksProjectsDir, Path.Combine(DataDirectoryLocalMachine, ksProjects)); }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Determines whether the given path is a direct sub folder of the projects directory.
+ /// (This is typically true for the a project-specific folder.)
+ ///
+ /// The path.
+ /// ------------------------------------------------------------------------------------
+ public static bool IsSubFolderOfProjectsDirectory(string path)
+ {
+ return !string.IsNullOrEmpty(path) && Path.GetDirectoryName(path) == ProjectsDirectory;
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the default directory for Backup files. This is per-user.
+ ///
+ /// If setting this value and the user does not have
+ /// permission to write to HKCU (probably can never happen)
+ /// ------------------------------------------------------------------------------------
+ public static string DefaultBackupDirectory
+ {
+ get
+ {
+ // NOTE: SpecialFolder.MyDocuments returns $HOME on Linux
+ string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
+ // FWNX-501: use slightly different default path on Linux
+ string defaultDir = MiscUtils.IsUnix ?
+ Path.Combine(myDocs, "Documents/fieldworks/backups") :
+ Path.Combine(Path.Combine(myDocs, "My FieldWorks"), "Backups");
+
+ using (RegistryKey registryKey = FwRegistryHelper.FieldWorksRegistryKey.OpenSubKey("ProjectBackup"))
+ return GetDirectory(registryKey, "DefaultBackupDirectory", defaultDir);
+ }
+ set
+ {
+ using (RegistryKey key = FwRegistryHelper.FieldWorksRegistryKey.CreateSubKey("ProjectBackup"))
+ {
+ if (key != null)
+ key.SetValue("DefaultBackupDirectory", value);
+ }
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the biblical key terms localization files.
+ ///
+ /// ------------------------------------------------------------------------------------
+ static public string[] KeyTermsLocalizationFiles
+ {
+ get
+ {
+ // SE version doesn't install the TE folder.
+ if (!Directory.Exists(TeFolder))
+ return new string[]{""};
+ return Directory.GetFiles(TeFolder, ksBiblicaltermsLocFilePrefix + "*" +
+ ksBiblicaltermsLocFileExtension, SearchOption.TopDirectoryOnly);
+ }
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Returns the file name containing the localization of the key terms list for the
+ /// given ICU locale.
+ ///
+ /// ------------------------------------------------------------------------------------
+ static public string GetKeyTermsLocFilename(string locale)
+ {
+ return Path.Combine(TeFolder, ksBiblicaltermsLocFilePrefix + locale +
+ ksBiblicaltermsLocFileExtension);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Extracts the locale identifier (string) from a key terms localization file name.
+ ///
+ /// ------------------------------------------------------------------------------------
+ static public string GetLocaleFromKeyTermsLocFile(string locFilename)
+ {
+ return Path.GetFileName(locFilename).Replace(ksBiblicaltermsLocFilePrefix,
+ String.Empty).Replace(ksBiblicaltermsLocFileExtension, String.Empty);
+ }
+
+ ///
+ /// Gets the FDO directories service.
+ ///
+ public static IFdoDirectories FdoDirectories
+ {
+ get { return s_fdoDirs; }
+ }
+
+ private class FwFdoDirectories : IFdoDirectories
+ {
+ ///
+ /// Gets the projects directory.
+ ///
+ public string ProjectsDirectory
+ {
+ get { return FwDirectoryFinder.ProjectsDirectory; }
+ }
+
+ public string TemplateDirectory
+ {
+ get { return FwDirectoryFinder.TemplateDirectory; }
+ }
+ }
+ }
+}
diff --git a/Src/Common/FwUtils/FwLinkArgs.cs b/Src/Common/FwUtils/FwLinkArgs.cs
index 192eefef45..c170be9ca6 100644
--- a/Src/Common/FwUtils/FwLinkArgs.cs
+++ b/Src/Common/FwUtils/FwLinkArgs.cs
@@ -10,6 +10,7 @@
using System.Text;
using System.Collections.Generic;
using System.Web;
+using SIL.FieldWorks.FDO;
using SIL.FieldWorks.Resources;
using SIL.Utils;
using XCore;
@@ -829,7 +830,7 @@ private static Dictionary ParseCommandLine(string[] rgArgs)
// There may not be a key, if this is the first argument, as when opening a file directly.
if (sKey.Length == 0)
{
- sKey = (Path.GetExtension(value) == FwFileExtensions.ksFwBackupFileExtension) ? kRestoreFile : kProject;
+ sKey = (Path.GetExtension(value) == FdoFileHelper.ksFwBackupFileExtension) ? kRestoreFile : kProject;
}
}
}
diff --git a/Src/Common/FwUtils/FwRegistryHelper.cs b/Src/Common/FwUtils/FwRegistryHelper.cs
index 68a970d0de..922232f7b9 100644
--- a/Src/Common/FwUtils/FwRegistryHelper.cs
+++ b/Src/Common/FwUtils/FwRegistryHelper.cs
@@ -197,35 +197,6 @@ public bool Paratext7orLaterInstalled()
return false;
}
}
-
- ///
- /// LT-14787 Database displays error about inaccessible Paratext projects
- /// If there is a registry value for this but the folder is not there we need to return false because
- /// paratext is not installed correctly. Also if there is no registry entry for this then return false.
- ///
- public bool ParatextSettingsDirectoryExists()
- {
- var regValue = ParatextSettingsDirectory();
- return !String.IsNullOrEmpty(regValue) && Directory.Exists(regValue);
- }
-
- ///
- /// Returns the path to the Paratext settings (projects) directory as specified in the registry
- /// ENHANCE (Hasso) 2013.09: added this to expose the directory for Unix users, because trying to get it from ScrTextCollections
- /// always returns null on Unix. This is really a Paratext problem, and this method may have no benefit.
- ///
- public string ParatextSettingsDirectory()
- {
- using (var paratextKey = Registry.LocalMachine.OpenSubKey("Software\\ScrChecks\\1.0\\Settings_Directory"))
- {
- if (paratextKey != null)
- {
- var keyName = paratextKey.ToString();
- return Registry.GetValue(keyName, "", "") as string;
- }
- }
- return null;
- }
}
/// ------------------------------------------------------------------------------------
@@ -389,29 +360,9 @@ public static bool Paratext7orLaterInstalled()
return RegistryHelperImpl.Paratext7orLaterInstalled();
}
- ///
- /// If there is a registry value for this but the folder is not there we need to return false because
- /// paratext is not installed correctly. Also if there is no registry entry for this then return false.
- ///
- public static bool ParatextSettingsDirectoryExists()
- {
- return RegistryHelperImpl.ParatextSettingsDirectoryExists();
- }
-
- ///
- /// Returns the path to the Paratext settings (projects) directory as specified in the registry
- /// ENHANCE (Hasso) 2013.09: added this to expose the directory for Unix users, because trying to get it from ScrTextCollections
- /// always returns null on Unix. This is really a Paratext problem, and this method may have no benefit.
- ///
- public static string ParatextSettingsDirectory()
- {
- return RegistryHelperImpl.ParatextSettingsDirectory();
- }
-
///
/// E.g. the first time the user runs FW8, we need to copy a bunch of registry keys
/// from HKCU/Software/SIL/FieldWorks/7.0 -> FieldWorks/8.
- /// Also copy HKEY_LOCAL_MACHINE\SOFTWARE\SIL\FieldWorks\7.0 ProjectShared (LT-15154).
///
public static void UpgradeUserSettingsIfNeeded()
{
@@ -433,7 +384,6 @@ public static void UpgradeUserSettingsIfNeeded()
// After copying everything delete the old key
FieldWorksVersionlessRegistryKey.DeleteSubKeyTree(OldFieldWorksRegistryKeyNameVersion7);
- // Don't delete old ProjectShared since it is in HKLM and we would need admin privileges.
}
catch (SecurityException se)
{
@@ -441,6 +391,30 @@ public static void UpgradeUserSettingsIfNeeded()
}
}
+ ///
+ /// Migrate the ProjectShared value stored in HKLM in version 7 into the HKCU (.Default since this will be run as system)
+ ///
+ ///
+ public static void MigrateVersion7ValueIfNeeded()
+ {
+ // Guard for some broken Windows machines having trouble accessing HKLM (LT-15158).
+ var hklm = LocalMachineHive;
+ if (hklm != null)
+ {
+ using (var oldProjectSharedSettingLocation = hklm.OpenSubKey(@"SOFTWARE\SIL\FieldWorks\7.0"))
+ using (var newProjectSharedSettingLocation = FieldWorksRegistryKey)
+ {
+ object projectSharedValue;
+ if (oldProjectSharedSettingLocation != null &&
+ RegistryHelper.RegEntryExists(oldProjectSharedSettingLocation, string.Empty, @"ProjectShared",
+ out projectSharedValue))
+ {
+ FieldWorksRegistryKey.SetValue(@"ProjectShared", projectSharedValue);
+ }
+ }
+ }
+ }
+
private static void CopySubKeyTree(RegistryKey srcSubKey, RegistryKey destSubKey)
{
// Copies all keys and values from src to dest subKey recursively
diff --git a/Src/Common/FwUtils/FwSubKey.cs b/Src/Common/FwUtils/FwSubKey.cs
index 3da7a7a32b..72ef5eeb54 100644
--- a/Src/Common/FwUtils/FwSubKey.cs
+++ b/Src/Common/FwUtils/FwSubKey.cs
@@ -17,13 +17,13 @@ public class FwSubKey
{
///
/// The name of the Translation Editor registry subkey (Even though this is the same as
- /// DirectoryFinder.ksTeFolderName and FwUtils.ksTeAppName, PLEASE do not use them interchangeably.
+ /// FwDirectoryFinder.ksTeFolderName and FwUtils.ksTeAppName, PLEASE do not use them interchangeably.
/// Use the one that is correct for your context, in case they need to be changed later.)
///
public const string TE = FwUtils.ksTeAppName;
///
/// The name of the Language Explorer registry subkey (Even though this is the same as
- /// DirectoryFinder.ksFlexFolderName and FwUtils.ksFlexAppName, PLEASE do not use them interchangeably.
+ /// FwDirectoryFinder.ksFlexFolderName and FwUtils.ksFlexAppName, PLEASE do not use them interchangeably.
/// Use the one that is correct for your context, in case they need to be changed later.)
///
public const string LexText = FwUtils.ksFlexAppName;
diff --git a/Src/Common/FwUtils/FwUtils.cs b/Src/Common/FwUtils/FwUtils.cs
index 11859118c5..4189bbd077 100644
--- a/Src/Common/FwUtils/FwUtils.cs
+++ b/Src/Common/FwUtils/FwUtils.cs
@@ -30,7 +30,7 @@ public static class FwUtils
public const string ksSuiteName = "FieldWorks";
///
/// The name of the Translation Editor folder (Even though this is the same as
- /// DirectoryFinder.ksTeFolderName and FwSubKey.TE, PLEASE do not use them interchangeably.
+ /// FwDirectoryFinder.ksTeFolderName and FwSubKey.TE, PLEASE do not use them interchangeably.
/// Use the one that is correct for your context, in case they need to be changed later.)
///
public const string ksTeAppName = "Translation Editor";
@@ -42,7 +42,7 @@ public static class FwUtils
public const string ksFullTeAppObjectName = "SIL.FieldWorks.TE.TeApp";
///
/// The name of the Language Explorer folder (Even though this is the same as
- /// DirectoryFinder.ksFlexFolderName and FwSubKey.LexText, PLEASE do not use them interchangeably.
+ /// FwDirectoryFinder.ksFlexFolderName and FwSubKey.LexText, PLEASE do not use them interchangeably.
/// Use the one that is correct for your context, in case they need to be changed later.)
///
public const string ksFlexAppName = "Language Explorer";
@@ -70,7 +70,7 @@ public static bool IsTEInstalled
get
{
if (s_fIsTEInstalled == null)
- s_fIsTEInstalled = File.Exists(DirectoryFinder.TeExe);
+ s_fIsTEInstalled = File.Exists(FwDirectoryFinder.TeExe);
return (bool)s_fIsTEInstalled;
}
}
@@ -97,7 +97,7 @@ public static bool IsOkToDisplayScriptureIfPresent
/// ------------------------------------------------------------------------------------
public static bool IsFlexInstalled
{
- get { return File.Exists(DirectoryFinder.FlexExe); }
+ get { return File.Exists(FwDirectoryFinder.FlexExe); }
}
/// ------------------------------------------------------------------------------------
@@ -206,13 +206,13 @@ public static string GetFontNameForLanguage(string lang)
///
/// Whenever possible use this in place of new PalasoWritingSystemManager.
/// It sets the TemplateFolder, which unfortunately the constructor cannot do because
- /// the direction of our dependencies does not allow it to reference FwUtils and access DirectoryFinder.
+ /// the direction of our dependencies does not allow it to reference FwUtils and access FwDirectoryFinder.
///
///
public static PalasoWritingSystemManager CreateWritingSystemManager()
{
var result = new PalasoWritingSystemManager();
- result.TemplateFolder = DirectoryFinder.TemplateDirectory;
+ result.TemplateFolder = FwDirectoryFinder.TemplateDirectory;
return result;
}
diff --git a/Src/Common/FwUtils/FwUtils.csproj b/Src/Common/FwUtils/FwUtils.csproj
index 9b731f79d1..e0f9bd534e 100644
--- a/Src/Common/FwUtils/FwUtils.csproj
+++ b/Src/Common/FwUtils/FwUtils.csproj
@@ -114,6 +114,10 @@
False
..\..\..\Output\Debug\CoreImpl.dll
+
+ False
+ ..\..\..\Output\Debug\FDO.dll
+
FwResources
..\..\..\Output\Debug\FwResources.dll
@@ -122,10 +126,6 @@
False
..\..\..\Downloads\IPCFramework.dll
-
- False
- ..\..\..\DistFiles\Microsoft.Practices.ServiceLocation.dll
-
False
..\..\..\Downloads\Palaso.dll
@@ -134,10 +134,6 @@
False
..\..\..\Downloads\Palaso.Lift.dll
-
- False
- ..\..\..\DistFiles\ParatextShared.dll
-
False
..\..\..\Output\Debug\SharedScrUtils.dll
@@ -174,17 +170,12 @@
CommonAssemblyInfo.cs
-
-
-
-
-
+
-
@@ -192,31 +183,19 @@
True
FwUtilsStrings.resx
-
-
-
-
-
- Code
-
Code
-
-
-
-
-
diff --git a/Src/Common/FwUtils/FwUtilsStrings.Designer.cs b/Src/Common/FwUtils/FwUtilsStrings.Designer.cs
index 2bc4fc95a0..8778805662 100644
--- a/Src/Common/FwUtils/FwUtilsStrings.Designer.cs
+++ b/Src/Common/FwUtils/FwUtilsStrings.Designer.cs
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
-// Runtime Version:4.0.30319.239
+// Runtime Version:4.0.30319.18052
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -9,255 +9,219 @@
//------------------------------------------------------------------------------
namespace SIL.FieldWorks.Common.FwUtils {
- using System;
-
-
- ///
- /// A strongly-typed resource class, for looking up localized strings, etc.
- ///
- // This class was auto-generated by the StronglyTypedResourceBuilder
- // class via a tool like ResGen or Visual Studio.
- // To add or remove a member, edit your .ResX file then rerun ResGen
- // with the /str option, or rebuild your VS project.
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- internal class FwUtilsStrings {
-
- private static global::System.Resources.ResourceManager resourceMan;
-
- private static global::System.Globalization.CultureInfo resourceCulture;
-
- [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal FwUtilsStrings() {
- }
-
- ///
- /// Returns the cached ResourceManager instance used by this class.
- ///
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Resources.ResourceManager ResourceManager {
- get {
- if (object.ReferenceEquals(resourceMan, null)) {
- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SIL.FieldWorks.Common.FwUtils.FwUtilsStrings", typeof(FwUtilsStrings).Assembly);
- resourceMan = temp;
- }
- return resourceMan;
- }
- }
-
- ///
- /// Overrides the current thread's CurrentUICulture property for all
- /// resource lookups using this strongly typed resource class.
- ///
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Globalization.CultureInfo Culture {
- get {
- return resourceCulture;
- }
- set {
- resourceCulture = value;
- }
- }
-
- ///
- /// Looks up a localized string similar to The help file could not be located..
- ///
- internal static string ksCannotFindHelp {
- get {
- return ResourceManager.GetString("ksCannotFindHelp", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to Change Failed.
- ///
- internal static string ksChangeFailed {
- get {
- return ResourceManager.GetString("ksChangeFailed", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to AD.
- ///
- internal static string ksGenDateAD {
- get {
- return ResourceManager.GetString("ksGenDateAD", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to After.
- ///
- internal static string ksGenDateAfter {
- get {
- return ResourceManager.GetString("ksGenDateAfter", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to About.
- ///
- internal static string ksGenDateApprox {
- get {
- return ResourceManager.GetString("ksGenDateApprox", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to BC.
- ///
- internal static string ksGenDateBC {
- get {
- return ResourceManager.GetString("ksGenDateBC", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to Before.
- ///
- internal static string ksGenDateBefore {
- get {
- return ResourceManager.GetString("ksGenDateBefore", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to The help topic is not available for topic: {0}.
- ///
- internal static string ksNoHelpTopicX {
- get {
- return ResourceManager.GetString("ksNoHelpTopicX", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to The project you are opening will not communicate with Paratext
- ///because a project with the same name is already open.
- ///If you want to use Paratext with this project, make a change in this project (so that it will start first), close both projects, then restart Flex..
- ///
- internal static string ksPtCommunicationProblem {
- get {
- return ResourceManager.GetString("ksPtCommunicationProblem", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to You do not have permission to change the setting "{0}". Administrator privileges are required to make changes affecting all users of this computer..
- ///
- internal static string ksRegChangeFailed {
- get {
- return ResourceManager.GetString("ksRegChangeFailed", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to Version: {0} {1} {2}.
- ///
- internal static string kstidAppVersionFmt {
- get {
- return ResourceManager.GetString("kstidAppVersionFmt", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to FieldWorks has unexpectedly timed out trying to determine whether the spelling dictionary {0} exists. FieldWorks will assume there is no such dictionary, which may affect spell-checking. If you think this dictionary should exist, we recommend restarting your computer. If you see this message regularly, please report it as a bug..
- ///
- internal static string kstIdCantDoDictExists {
- get {
- return ResourceManager.GetString("kstIdCantDoDictExists", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to Spelling Dictionary Problem.
- ///
- internal static string kstidCantDoDictExistsCaption {
- get {
- return ResourceManager.GetString("kstidCantDoDictExistsCaption", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to cm.
- ///
- internal static string kstidCm {
- get {
- return ResourceManager.GetString("kstidCm", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string
- ///
- internal static string kstidLicense {
- get {
- return ResourceManager.GetString("kstidLicense", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string
- ///
- internal static string kstidLicenseURL {
- get {
- return ResourceManager.GetString("kstidLicenseURL", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to Version: {0}.
- ///
- internal static string kstidFwVersionFmt {
- get {
- return ResourceManager.GetString("kstidFwVersionFmt", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to in.
- ///
- internal static string kstidIn {
- get {
- return ResourceManager.GetString("kstidIn", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to ".
- ///
- internal static string kstidInches {
- get {
- return ResourceManager.GetString("kstidInches", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to The writing system {0} specifies an invalid spelling dictionary ({1}). Valid spelling dictionary IDs must only contain ASCII alphanumeric characters or underline. Spell checking will not work for this writing system until you correct this in the Writing System Properties dialog..
- ///
- internal static string kstidInvalidDictId {
- get {
- return ResourceManager.GetString("kstidInvalidDictId", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to mm.
- ///
- internal static string kstidMm {
- get {
- return ResourceManager.GetString("kstidMm", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to pt.
- ///
- internal static string kstidPt {
- get {
- return ResourceManager.GetString("kstidPt", resourceCulture);
- }
- }
- }
+ using System;
+
+
+ ///
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ ///
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class FwUtilsStrings {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal FwUtilsStrings() {
+ }
+
+ ///
+ /// Returns the cached ResourceManager instance used by this class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SIL.FieldWorks.Common.FwUtils.FwUtilsStrings", typeof(FwUtilsStrings).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to The help file could not be located..
+ ///
+ internal static string ksCannotFindHelp {
+ get {
+ return ResourceManager.GetString("ksCannotFindHelp", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Change Failed.
+ ///
+ internal static string ksChangeFailed {
+ get {
+ return ResourceManager.GetString("ksChangeFailed", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to AD.
+ ///
+ internal static string ksGenDateAD {
+ get {
+ return ResourceManager.GetString("ksGenDateAD", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to After.
+ ///
+ internal static string ksGenDateAfter {
+ get {
+ return ResourceManager.GetString("ksGenDateAfter", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to About.
+ ///
+ internal static string ksGenDateApprox {
+ get {
+ return ResourceManager.GetString("ksGenDateApprox", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to BC.
+ ///
+ internal static string ksGenDateBC {
+ get {
+ return ResourceManager.GetString("ksGenDateBC", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Before.
+ ///
+ internal static string ksGenDateBefore {
+ get {
+ return ResourceManager.GetString("ksGenDateBefore", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to The help topic is not available for topic: {0}.
+ ///
+ internal static string ksNoHelpTopicX {
+ get {
+ return ResourceManager.GetString("ksNoHelpTopicX", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to The project you are opening will not communicate with Paratext
+ ///because a project with the same name is already open.
+ ///If you want to use Paratext with this project, make a change in this project (so that it will start first), close both projects, then restart FLEx..
+ ///
+ internal static string ksPtCommunicationProblem {
+ get {
+ return ResourceManager.GetString("ksPtCommunicationProblem", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to You do not have permission to change the setting "{0}". Administrator privileges are required to make changes affecting all users of this computer..
+ ///
+ internal static string ksRegChangeFailed {
+ get {
+ return ResourceManager.GetString("ksRegChangeFailed", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to FieldWorks has unexpectedly timed out trying to determine whether the spelling dictionary {0} exists. FieldWorks will assume there is no such dictionary, which may affect spell-checking. If you think this dictionary should exist, we recommend restarting your computer. If you see this message regularly, please report it as a bug..
+ ///
+ internal static string kstIdCantDoDictExists {
+ get {
+ return ResourceManager.GetString("kstIdCantDoDictExists", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Spelling Dictionary Problem.
+ ///
+ internal static string kstidCantDoDictExistsCaption {
+ get {
+ return ResourceManager.GetString("kstidCantDoDictExistsCaption", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to cm.
+ ///
+ internal static string kstidCm {
+ get {
+ return ResourceManager.GetString("kstidCm", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to in.
+ ///
+ internal static string kstidIn {
+ get {
+ return ResourceManager.GetString("kstidIn", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to ".
+ ///
+ internal static string kstidInches {
+ get {
+ return ResourceManager.GetString("kstidInches", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to The writing system {0} specifies an invalid spelling dictionary ({1}). Valid spelling dictionary IDs must only contain ASCII alphanumeric characters or underline. Spell checking will not work for this writing system until you correct this in the Writing System Properties dialog..
+ ///
+ internal static string kstidInvalidDictId {
+ get {
+ return ResourceManager.GetString("kstidInvalidDictId", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to mm.
+ ///
+ internal static string kstidMm {
+ get {
+ return ResourceManager.GetString("kstidMm", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to pt.
+ ///
+ internal static string kstidPt {
+ get {
+ return ResourceManager.GetString("kstidPt", resourceCulture);
+ }
+ }
+ }
}
diff --git a/Src/Common/FwUtils/FwUtilsStrings.resx b/Src/Common/FwUtils/FwUtilsStrings.resx
index 7ba7ff2218..2d65e11b8e 100644
--- a/Src/Common/FwUtils/FwUtilsStrings.resx
+++ b/Src/Common/FwUtils/FwUtilsStrings.resx
@@ -1,200 +1,184 @@
-
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- text/microsoft-resx
+ text/microsoft-resx
- 2.0
+ 2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- The help file could not be located.
+ The help file could not be located.
- The help topic is not available for topic: {0}
+ The help topic is not available for topic: {0}
- AD
+ AD
- After
+ After
- About
+ About
- BC
+ BC
- Before
+ Before
- cm
- Measurement unit abbreviation for Centimeters (Localized string should preserve leading space if needed in formatted display.)
+ cm
+ Measurement unit abbreviation for Centimeters (Localized string should preserve leading space if needed in formatted display.)
- in
- Measurement unit abbreviation for Inches (Localized string should preserve leading space if needed in formatted display.)
+ in
+ Measurement unit abbreviation for Inches (Localized string should preserve leading space if needed in formatted display.)
- "
- Measurement unit symbol for Inches (If culture doesn't have a separate symbol for specifying inches, localized value for this string should be set to match value of kstidIn.)
+ "
+ Measurement unit symbol for Inches (If culture doesn't have a separate symbol for specifying inches, localized value for this string should be set to match value of kstidIn.)
- mm
- Measurement unit abbreviation for Millimeters (Localized string should preserve leading space if needed in formatted display.)
+ mm
+ Measurement unit abbreviation for Millimeters (Localized string should preserve leading space if needed in formatted display.)
- pt
- Measurement unit abbreviation for Points (Localized string should preserve leading space if needed in formatted display.)
-
-
- Version: {0} {1} {2}
- Displays in the Help/About box and the splash screen
-
-
- This software is licensed under the LGPL, version 2.1 or later
- Displays in the Help/About box and the splash screen
-
-
- (http://www.gnu.org/licenses/lgpl-2.1.html)
- Displays in the Help/About box
-
-
- Version: {0}
- Displays in the Help/About box and the splash screen
+ pt
+ Measurement unit abbreviation for Points (Localized string should preserve leading space if needed in formatted display.)
- Change Failed
- Caption for dialog reporting failure to update.
+ Change Failed
+ Caption for dialog reporting failure to update.
- You do not have permission to change the setting "{0}". Administrator privileges are required to make changes affecting all users of this computer.
- Error message when writing a registry setting for "local machine" fails.
+ You do not have permission to change the setting "{0}". Administrator privileges are required to make changes affecting all users of this computer.
+ Error message when writing a registry setting for "local machine" fails.
- FieldWorks has unexpectedly timed out trying to determine whether the spelling dictionary {0} exists. FieldWorks will assume there is no such dictionary, which may affect spell-checking. If you think this dictionary should exist, we recommend restarting your computer. If you see this message regularly, please report it as a bug.
+ FieldWorks has unexpectedly timed out trying to determine whether the spelling dictionary {0} exists. FieldWorks will assume there is no such dictionary, which may affect spell-checking. If you think this dictionary should exist, we recommend restarting your computer. If you see this message regularly, please report it as a bug.
- Spelling Dictionary Problem
+ Spelling Dictionary Problem
- The writing system {0} specifies an invalid spelling dictionary ({1}). Valid spelling dictionary IDs must only contain ASCII alphanumeric characters or underline. Spell checking will not work for this writing system until you correct this in the Writing System Properties dialog.
- Error message. {0} might be a code like "fr" and {1} a bad ID, typically a short string like "frn[".
+ The writing system {0} specifies an invalid spelling dictionary ({1}). Valid spelling dictionary IDs must only contain ASCII alphanumeric characters or underline. Spell checking will not work for this writing system until you correct this in the Writing System Properties dialog.
+ Error message. {0} might be a code like "fr" and {1} a bad ID, typically a short string like "frn[".
- The project you are opening will not communicate with Paratext
+ The project you are opening will not communicate with Paratext
because a project with the same name is already open.
If you want to use Paratext with this project, make a change in this project (so that it will start first), close both projects, then restart FLEx.
-
+
\ No newline at end of file
diff --git a/Src/Common/FwUtils/FwUtilsTests/CaseFunctionsTest.cs b/Src/Common/FwUtils/FwUtilsTests/CaseFunctionsTest.cs
index 8cd8a11c57..8b55177725 100644
--- a/Src/Common/FwUtils/FwUtilsTests/CaseFunctionsTest.cs
+++ b/Src/Common/FwUtils/FwUtilsTests/CaseFunctionsTest.cs
@@ -5,9 +5,8 @@
// File: CaseFunctionsTest.cs
// Responsibility:
-using System;
using NUnit.Framework;
-using SIL.FieldWorks.Common.COMInterfaces;
+using SIL.CoreImpl;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
diff --git a/Src/Common/FwUtils/FwUtilsTests/DirectoryFinderTests.cs b/Src/Common/FwUtils/FwUtilsTests/DirectoryFinderTests.cs
deleted file mode 100644
index 0e41e45d94..0000000000
--- a/Src/Common/FwUtils/FwUtilsTests/DirectoryFinderTests.cs
+++ /dev/null
@@ -1,459 +0,0 @@
-// Copyright (c) 2008-2013 SIL International
-// This software is licensed under the LGPL, version 2.1 or later
-// (http://www.gnu.org/licenses/lgpl-2.1.html)
-//
-// File: DirectoryFinderTests.cs
-// Responsibility: Eberhard Beilharz
-// Last reviewed:
-
-using System;
-using System.IO;
-using NUnit.Framework;
-using SIL.FieldWorks.Test.TestUtils;
-using SIL.Utils;
-
-namespace SIL.FieldWorks.Common.FwUtils
-{
-
- ///-----------------------------------------------------------------------------------------
- ///
- /// Tests for the DirectoryFinder class
- ///
- ///-----------------------------------------------------------------------------------------
- [TestFixture]
- public class DirectoryFinderTests : BaseTest
- {
- ///
- /// Resets the registry helper
- ///
- [TestFixtureTearDown]
- public void TearDown()
- {
- FwRegistryHelper.Manager.Reset();
- }
-
- ///
- /// Fixture setup
- ///
- [TestFixtureSetUp]
- public void TestFixtureSetup()
- {
- DirectoryFinder.CompanyName = "SIL";
- FwRegistryHelper.Manager.SetRegistryHelper(new DummyFwRegistryHelper());
- FwRegistryHelper.FieldWorksRegistryKey.SetValue("RootDataDir", Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../DistFiles")));
- FwRegistryHelper.FieldWorksRegistryKey.SetValue("RootCodeDir", Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../DistFiles")));
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Gets the directory where the Utils assembly is
- ///
- ///-------------------------------------------------------------------------------------
- private string UtilsAssemblyDir
- {
- get
- {
- return Path.GetDirectoryName(typeof(DirectoryFinder).Assembly.CodeBase
- .Substring(MiscUtils.IsUnix ? 7 : 8));
- }
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the FWCodeDirectory property. This should return the DistFiles directory.
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void FWCodeDirectory()
- {
- var currentDir = Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../DistFiles"));
- Assert.That(DirectoryFinder.FWCodeDirectory, Is.SamePath(currentDir));
- }
-
- ///
- /// Verify that the user project key falls back to the local machine.
- ///
- [Test]
- public void GettingProjectDirWithEmptyUserKeyReturnsLocalMachineKey()
- {
- using (var fwHKCU = FwRegistryHelper.FieldWorksRegistryKey)
- using (var fwHKLM = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine)
- {
- if (fwHKCU.GetValue("ProjectsDir") != null)
- {
- fwHKCU.DeleteValue("ProjectsDir");
- }
- fwHKLM.SetValue("ProjectsDir", "HKLM_TEST");
- Assert.That(DirectoryFinder.ProjectsDirectory, Is.EqualTo(DirectoryFinder.ProjectsDirectoryLocalMachine));
- Assert.That(DirectoryFinder.ProjectsDirectory, Is.EqualTo("HKLM_TEST"));
- }
- }
-
- ///
- /// Verify that the user project key overrides the local machine.
- ///
- [Test]
- public void GettingProjectDirWithUserDifferentFromLMReturnsUser()
- {
- DirectoryFinder.ProjectsDirectory = "NewHKCU_TEST_Value";
- Assert.That(DirectoryFinder.ProjectsDirectory, Is.Not.EqualTo(DirectoryFinder.ProjectsDirectoryLocalMachine));
- Assert.That(DirectoryFinder.ProjectsDirectory, Is.EqualTo("NewHKCU_TEST_Value"));
- }
-
- ///
- /// Verify that setting the user key to null deletes the user setting and falls back to local machine.
- ///
- [Test]
- public void SettingProjectDirToNullDeletesUserKey()
- {
- DirectoryFinder.ProjectsDirectory = null;
- Assert.That(DirectoryFinder.ProjectsDirectory, Is.EqualTo(DirectoryFinder.ProjectsDirectoryLocalMachine));
-
- using (var fwHKCU = FwRegistryHelper.FieldWorksRegistryKey)
- using (var fwHKLM = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine)
- {
- Assert.Null(fwHKCU.GetValue("ProjectsDir"));
- Assert.NotNull(fwHKLM.GetValue("ProjectsDir"));
- }
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the FWDataDirectory property. This should return the DistFiles directory.
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void FWDataDirectory()
- {
- var currentDir = Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../DistFiles"));
- Assert.That(DirectoryFinder.FWDataDirectory, Is.SamePath(currentDir));
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the FwSourceDirectory property. This should return the DistFiles directory.
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void FwSourceDirectory()
- {
- string expectedDir = Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../Src"));
- Assert.That(DirectoryFinder.FwSourceDirectory, Is.SamePath(expectedDir));
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the GetFWCodeSubDirectory method when we pass a subdirectory without a
- /// leading directory separator
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void GetFWCodeSubDirectory_NoLeadingSlash()
- {
- Assert.That(DirectoryFinder.GetFWCodeSubDirectory("Translation Editor/Configuration"),
- Is.SamePath(Path.Combine(DirectoryFinder.FWCodeDirectory, "Translation Editor/Configuration")));
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the GetFWCodeSubDirectory method when we pass a subdirectory with a
- /// leading directory separator
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void GetFWCodeSubDirectory_LeadingSlash()
- {
- Assert.That(DirectoryFinder.GetFWCodeSubDirectory("/Translation Editor/Configuration"),
- Is.SamePath(Path.Combine(DirectoryFinder.FWCodeDirectory, "Translation Editor/Configuration")));
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the GetFWCodeSubDirectory method when we pass an invalid subdirectory
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void GetFWCodeSubDirectory_InvalidDir()
- {
- Assert.That(DirectoryFinder.GetFWCodeSubDirectory("NotExisting"),
- Is.SamePath("NotExisting"));
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the GetFWDataSubDirectory method when we pass a subdirectory without a
- /// leading directory separator
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void GetFWDataSubDirectory_NoLeadingSlash()
- {
- Assert.That(DirectoryFinder.GetFWDataSubDirectory("Translation Editor/Configuration"),
- Is.SamePath(Path.Combine(DirectoryFinder.FWDataDirectory, "Translation Editor/Configuration")));
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the GetFWDataSubDirectory method when we pass a subdirectory with a
- /// leading directory separator
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void GetFWDataSubDirectory_LeadingSlash()
- {
- Assert.That(DirectoryFinder.GetFWDataSubDirectory("/Translation Editor/Configuration"),
- Is.SamePath(Path.Combine(DirectoryFinder.FWDataDirectory, "Translation Editor/Configuration")));
- }
-
- ///-------------------------------------------------------------------------------------
- ///
- /// Tests the GetFWDataSubDirectory method when we pass an invalid subdirectory
- ///
- ///-------------------------------------------------------------------------------------
- [Test]
- public void GetFWDataSubDirectory_InvalidDir()
- {
- Assert.That(DirectoryFinder.GetFWDataSubDirectory("NotExisting"),
- Is.SamePath("NotExisting"));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Tests the GetLinkedFilesRelativePathFromFullPath method
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void GetLinkedFilesRelativePathFromFullPath()
- {
- Assert.AreEqual(String.Format("%proj%{0}LinkedFiles", Path.DirectorySeparatorChar),
- DirectoryFinderRelativePaths.GetLinkedFilesRelativePathFromFullPath(String.Format("%proj%{0}LinkedFiles", Path.DirectorySeparatorChar),
- Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/BackupRestore/Project"),
- "Project"));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Tests the GetLinkedFilesFullPathFromRelativePath method
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void GetLinkedFilesFullPathFromRelativePath()
- {
- var projectPath = Path.Combine(DirectoryFinder.ProjectsDirectory, "TestProject");
- var linkedFilesRootDir = Path.Combine(projectPath, "LinkedFiles");
- var linkedFilesPath =
- DirectoryFinderRelativePaths.GetLinkedFilesFullPathFromRelativePath(String.Format("%proj%{0}LinkedFiles", Path.DirectorySeparatorChar), projectPath);
-
- Assert.AreEqual(linkedFilesRootDir, linkedFilesPath);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Tests the GetFullFilePathFromRelativeLFPath method
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void GetFullFilePathFromRelativeLFPath()
- {
- var linkedFilesRootDir = Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, "TestProject"), "LinkedFiles");
- var fullLFPath = DirectoryFinderRelativePaths.GetFullFilePathFromRelativeLFPath(String.Format("%lf%{0}AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar), linkedFilesRootDir);
- var audioVisualFile = Path.Combine(Path.Combine(linkedFilesRootDir, "AudioVisual"), "StarWars.mvi");
- Assert.AreEqual(audioVisualFile, fullLFPath);
-
- //if a fully rooted path is passed in the return value should be null.
- var projectRootDir = DirectoryFinder.FWDataDirectory;
- fullLFPath = DirectoryFinderRelativePaths.GetFullFilePathFromRelativeLFPath(projectRootDir, linkedFilesRootDir);
- Assert.True(string.IsNullOrEmpty(fullLFPath));
-
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Tests the GetRelativeLFPathFromFullFilePath method
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void GetRelativeLFPathFromFullFilePath()
- {
- var linkedFilesRootDir = Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, "TestProject"), "LinkedFiles");
- var audioVisualFile = Path.Combine(Path.Combine(linkedFilesRootDir, "AudioVisual"), "StarWars.mvi");
- var relativeLFPath = DirectoryFinderRelativePaths.GetRelativeLFPathFromFullFilePath(audioVisualFile, linkedFilesRootDir);
- Assert.AreEqual(String.Format("%lf%{0}AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar), relativeLFPath);
-
- //Ensure empty string is returned when the path is not relative to the LinkedFiles directory.
- var pathNotUnderLinkedFiles = Path.Combine(DirectoryFinder.FWDataDirectory, "LordOfTheRings.mvi");
- relativeLFPath = DirectoryFinderRelativePaths.GetRelativeLFPathFromFullFilePath(pathNotUnderLinkedFiles, linkedFilesRootDir);
- Assert.True(string.IsNullOrEmpty(relativeLFPath));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Tests the GetRelativeLinkedFilesPath method
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void GetRelativeLinkedFilesPath()
- {
- var linkedFilesRootDir = Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, "TestProject"), "LinkedFiles");
- var audioVisualFile = Path.Combine(Path.Combine(linkedFilesRootDir, "AudioVisual"), "StarWars.mvi");
- var relativeLFPath = DirectoryFinderRelativePaths.GetRelativeLinkedFilesPath(audioVisualFile, linkedFilesRootDir);
- Assert.True(String.Equals(String.Format("AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar), relativeLFPath));
-
- //Ensure ORIGINAL path is returned when the path is not relative to the LinkedFiles directory.
- var pathNotUnderLinkedFiles = Path.Combine(DirectoryFinder.FWDataDirectory, "LordOfTheRings.mvi");
- relativeLFPath = DirectoryFinderRelativePaths.GetRelativeLinkedFilesPath(pathNotUnderLinkedFiles, linkedFilesRootDir);
- Assert.True(String.Equals(pathNotUnderLinkedFiles,relativeLFPath));
- Assert.That(DirectoryFinderRelativePaths.GetRelativeLinkedFilesPath(
- "silfw:\\localhost\\link?app%3dflex%26database%3dc%3a%5cTestLangProj%5cTestLangProj.fwdata%26server%3d%26tool%3dnaturalClassedit%26guid%3d43c9ba97-2883-4f95-aa5d-ef9309e85025%26tag%3d",
- relativeLFPath), Is.Null, "hyperlinks should be left well alone!!");
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Tests the GetFullPathFromRelativeLFPath method
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void GetFullPathFromRelativeLFPath()
- {
- var linkedFilesRootDir = Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, "TestProject"), "LinkedFiles");
- var fullLFPath = DirectoryFinderRelativePaths.GetFullPathFromRelativeLFPath(String.Format("AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar), linkedFilesRootDir);
- var audioVisualFile = Path.Combine(Path.Combine(linkedFilesRootDir, "AudioVisual"), "StarWars.mvi");
- Assert.AreEqual(audioVisualFile, fullLFPath);
-
- //if a fully rooted path is passed in the return value should be the path that was passed in.
- var fileUnderProjectRootDir = String.Format("{1}{0}AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar, DirectoryFinder.FWDataDirectory);
- fullLFPath = DirectoryFinderRelativePaths.GetFullPathFromRelativeLFPath(fileUnderProjectRootDir, linkedFilesRootDir);
- Assert.AreEqual(fullLFPath, fileUnderProjectRootDir);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Tests the GetFullPathFromRelativeLFPath method with illegal characters
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void GetFullPathFromRelativeLFPath_WithIllegalCharacters_ReturnsSpecialPath()
- {
- var linkedFilesRootDir = Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, "TestProject"), "LinkedFiles");
- var fullLFPath = DirectoryFinderRelativePaths.GetFullPathFromRelativeLFPath("1\";1\"", linkedFilesRootDir);
- Assert.That(fullLFPath, Is.EqualTo(Path.Combine(linkedFilesRootDir,"__ILLEGALCHARS__")));
- }
-
- ///
- /// Tests the DefaultBackupDirectory property for use on Windows.
- ///
- [Test]
- [Platform(Exclude="Linux", Reason="Test is Windows specific")]
- public void DefaultBackupDirectory_Windows()
- {
- Assert.AreEqual(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
- Path.Combine("My FieldWorks", "Backups")), DirectoryFinder.DefaultBackupDirectory);
- }
-
- ///
- /// Tests the DefaultBackupDirectory property for use on Linux
- ///
- [Test]
- [Platform(Include="Linux", Reason="Test is Linux specific")]
- public void DefaultBackupDirectory_Linux()
- {
- // SpecialFolder.MyDocuments returns $HOME on Linux!
- Assert.AreEqual(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
- "Documents/fieldworks/backups"), DirectoryFinder.DefaultBackupDirectory);
- }
-
- ///
- /// Base class for testing CommonApplicationData. This base class deals with setting
- /// and resetting the environment variable.
- ///
- public class GetCommonAppDataBaseTest: BaseTest
- {
- private string PreviousEnvironment;
-
- ///
- /// Setup the tests.
- ///
- public override void FixtureSetup()
- {
- base.FixtureSetup();
-
- DirectoryFinder.ResetStaticVars();
- PreviousEnvironment = Environment.GetEnvironmentVariable("FW_CommonAppData");
- var properties = (PropertyAttribute[])GetType().GetCustomAttributes(typeof(PropertyAttribute), true);
- Assert.That(properties.Length, Is.GreaterThan(0));
- Environment.SetEnvironmentVariable("FW_CommonAppData", (string)properties[0].Properties["Value"]);
- }
-
- ///
- /// Reset environment variable to previous value
- ///
- public override void FixtureTeardown()
- {
- Environment.SetEnvironmentVariable("FW_CommonAppData", PreviousEnvironment);
-
- base.FixtureTeardown();
- }
- }
-
- ///
- /// Tests the GetFolderPath method for CommonApplicationData when no environment variable
- /// is set.
- ///
- [TestFixture]
- [Property("Value", null)]
- public class GetCommonAppDataNormalTests: GetCommonAppDataBaseTest
- {
- /// Tests the GetFolderPath method for CommonApplicationData when no environment
- /// variable is set
- [Test]
- [Platform(Include="Linux", Reason="Test is Linux specific")]
- public void Linux()
- {
- Assert.AreEqual("/var/lib/fieldworks",
- DirectoryFinder.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
- }
-
- /// Tests the GetFolderPath method for CommonApplicationData when no environment
- /// variable is set
- [Test]
- [Platform(Exclude="Linux", Reason="Test is Windows specific")]
- public void Windows()
- {
- Assert.AreEqual(
- Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
- DirectoryFinder.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
- }
- }
-
- ///
- /// Tests the GetFolderPath method for CommonApplicationData when the environment variable
- /// is set.
- ///
- [TestFixture]
- [Property("Value", "/bla")]
- public class GetCommonAppDataOverrideTests: GetCommonAppDataBaseTest
- {
- /// Tests the GetFolderPath method for CommonApplicationData when the environment
- /// variable is set
- [Test]
- [Platform(Include="Linux", Reason="Test is Linux specific")]
- public void Linux()
- {
- Assert.AreEqual("/bla",
- DirectoryFinder.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
- }
-
- /// Tests the GetFolderPath method for CommonApplicationData when the environment
- /// variable is set
- [Test]
- [Platform(Exclude="Linux", Reason="Test is Windows specific")]
- public void Windows()
- {
- Assert.AreEqual(
- Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
- DirectoryFinder.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
- }
- }
- }
-}
diff --git a/Src/Common/FwUtils/FwUtilsTests/FwDirectoryFinderTests.cs b/Src/Common/FwUtils/FwUtilsTests/FwDirectoryFinderTests.cs
new file mode 100644
index 0000000000..f6f8f5406e
--- /dev/null
+++ b/Src/Common/FwUtils/FwUtilsTests/FwDirectoryFinderTests.cs
@@ -0,0 +1,243 @@
+// Copyright (c) 2008-2014 SIL International
+// This software is licensed under the LGPL, version 2.1 or later
+// (http://www.gnu.org/licenses/lgpl-2.1.html)
+//
+// File: FwDirectoryFinderTests.cs
+// Responsibility: Eberhard Beilharz
+
+using System;
+using System.IO;
+using NUnit.Framework;
+using SIL.FieldWorks.FDO;
+using SIL.FieldWorks.Test.TestUtils;
+using SIL.Utils;
+
+namespace SIL.FieldWorks.Common.FwUtils
+{
+
+ ///-----------------------------------------------------------------------------------------
+ ///
+ /// Tests for the FwDirectoryFinder class
+ ///
+ ///-----------------------------------------------------------------------------------------
+ [TestFixture]
+ public class FwDirectoryFinderTests : BaseTest
+ {
+ ///
+ /// Resets the registry helper
+ ///
+ [TestFixtureTearDown]
+ public void TearDown()
+ {
+ FwRegistryHelper.Manager.Reset();
+ }
+
+ ///
+ /// Fixture setup
+ ///
+ [TestFixtureSetUp]
+ public void TestFixtureSetup()
+ {
+ //FwDirectoryFinder.CompanyName = "SIL";
+ FwRegistryHelper.Manager.SetRegistryHelper(new DummyFwRegistryHelper());
+ FwRegistryHelper.FieldWorksRegistryKey.SetValue("RootDataDir", Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../DistFiles")));
+ FwRegistryHelper.FieldWorksRegistryKey.SetValue("RootCodeDir", Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../DistFiles")));
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Gets the directory where the Utils assembly is
+ ///
+ ///-------------------------------------------------------------------------------------
+ private string UtilsAssemblyDir
+ {
+ get
+ {
+ return Path.GetDirectoryName(typeof(FwDirectoryFinder).Assembly.CodeBase
+ .Substring(MiscUtils.IsUnix ? 7 : 8));
+ }
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the CodeDirectory property. This should return the DistFiles directory.
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void CodeDirectory()
+ {
+ var currentDir = Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../DistFiles"));
+ Assert.That(FwDirectoryFinder.CodeDirectory, Is.SamePath(currentDir));
+ }
+
+ ///
+ /// Verify that the user project key falls back to the local machine.
+ ///
+ [Test]
+ public void GettingProjectDirWithEmptyUserKeyReturnsLocalMachineKey()
+ {
+ using (var fwHKCU = FwRegistryHelper.FieldWorksRegistryKey)
+ using (var fwHKLM = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine)
+ {
+ if (fwHKCU.GetValue("ProjectsDir") != null)
+ {
+ fwHKCU.DeleteValue("ProjectsDir");
+ }
+ fwHKLM.SetValue("ProjectsDir", "HKLM_TEST");
+ Assert.That(FwDirectoryFinder.ProjectsDirectory, Is.EqualTo(FwDirectoryFinder.ProjectsDirectoryLocalMachine));
+ Assert.That(FwDirectoryFinder.ProjectsDirectory, Is.EqualTo("HKLM_TEST"));
+ }
+ }
+
+ ///
+ /// Verify that the user project key overrides the local machine.
+ ///
+ [Test]
+ public void GettingProjectDirWithUserDifferentFromLMReturnsUser()
+ {
+ FwDirectoryFinder.ProjectsDirectory = "NewHKCU_TEST_Value";
+ Assert.That(FwDirectoryFinder.ProjectsDirectory, Is.Not.EqualTo(FwDirectoryFinder.ProjectsDirectoryLocalMachine));
+ Assert.That(FwDirectoryFinder.ProjectsDirectory, Is.EqualTo("NewHKCU_TEST_Value"));
+ }
+
+ ///
+ /// Verify that setting the user key to null deletes the user setting and falls back to local machine.
+ ///
+ [Test]
+ public void SettingProjectDirToNullDeletesUserKey()
+ {
+ FwDirectoryFinder.ProjectsDirectory = null;
+ Assert.That(FwDirectoryFinder.ProjectsDirectory, Is.EqualTo(FwDirectoryFinder.ProjectsDirectoryLocalMachine));
+
+ using (var fwHKCU = FwRegistryHelper.FieldWorksRegistryKey)
+ using (var fwHKLM = FwRegistryHelper.FieldWorksRegistryKeyLocalMachine)
+ {
+ Assert.Null(fwHKCU.GetValue("ProjectsDir"));
+ Assert.NotNull(fwHKLM.GetValue("ProjectsDir"));
+ }
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the DataDirectory property. This should return the DistFiles directory.
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void DataDirectory()
+ {
+ var currentDir = Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../DistFiles"));
+ Assert.That(FwDirectoryFinder.DataDirectory, Is.SamePath(currentDir));
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the SourceDirectory property. This should return the DistFiles directory.
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void SourceDirectory()
+ {
+ string expectedDir = Path.GetFullPath(Path.Combine(UtilsAssemblyDir, "../../Src"));
+ Assert.That(FwDirectoryFinder.SourceDirectory, Is.SamePath(expectedDir));
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetCodeSubDirectory method when we pass a subdirectory without a
+ /// leading directory separator
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void GetCodeSubDirectory_NoLeadingSlash()
+ {
+ Assert.That(FwDirectoryFinder.GetCodeSubDirectory("Translation Editor/Configuration"),
+ Is.SamePath(Path.Combine(FwDirectoryFinder.CodeDirectory, "Translation Editor/Configuration")));
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetCodeSubDirectory method when we pass a subdirectory with a
+ /// leading directory separator
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void GetCodeSubDirectory_LeadingSlash()
+ {
+ Assert.That(FwDirectoryFinder.GetCodeSubDirectory("/Translation Editor/Configuration"),
+ Is.SamePath(Path.Combine(FwDirectoryFinder.CodeDirectory, "Translation Editor/Configuration")));
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetCodeSubDirectory method when we pass an invalid subdirectory
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void GetCodeSubDirectory_InvalidDir()
+ {
+ Assert.That(FwDirectoryFinder.GetCodeSubDirectory("NotExisting"),
+ Is.SamePath("NotExisting"));
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetDataSubDirectory method when we pass a subdirectory without a
+ /// leading directory separator
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void GetDataSubDirectory_NoLeadingSlash()
+ {
+ Assert.That(FwDirectoryFinder.GetDataSubDirectory("Translation Editor/Configuration"),
+ Is.SamePath(Path.Combine(FwDirectoryFinder.DataDirectory, "Translation Editor/Configuration")));
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetDataSubDirectory method when we pass a subdirectory with a
+ /// leading directory separator
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void GetDataSubDirectory_LeadingSlash()
+ {
+ Assert.That(FwDirectoryFinder.GetDataSubDirectory("/Translation Editor/Configuration"),
+ Is.SamePath(Path.Combine(FwDirectoryFinder.DataDirectory, "Translation Editor/Configuration")));
+ }
+
+ ///-------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetDataSubDirectory method when we pass an invalid subdirectory
+ ///
+ ///-------------------------------------------------------------------------------------
+ [Test]
+ public void GetDataSubDirectory_InvalidDir()
+ {
+ Assert.That(FwDirectoryFinder.GetDataSubDirectory("NotExisting"),
+ Is.SamePath("NotExisting"));
+ }
+
+ ///
+ /// Tests the DefaultBackupDirectory property for use on Windows.
+ ///
+ [Test]
+ [Platform(Exclude="Linux", Reason="Test is Windows specific")]
+ public void DefaultBackupDirectory_Windows()
+ {
+ Assert.AreEqual(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
+ Path.Combine("My FieldWorks", "Backups")), FwDirectoryFinder.DefaultBackupDirectory);
+ }
+
+ ///
+ /// Tests the DefaultBackupDirectory property for use on Linux
+ ///
+ [Test]
+ [Platform(Include="Linux", Reason="Test is Linux specific")]
+ public void DefaultBackupDirectory_Linux()
+ {
+ // SpecialFolder.MyDocuments returns $HOME on Linux!
+ Assert.AreEqual(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
+ "Documents/fieldworks/backups"), FwDirectoryFinder.DefaultBackupDirectory);
+ }
+ }
+}
diff --git a/Src/Common/FwUtils/FwUtilsTests/FwRegistryHelperTests.cs b/Src/Common/FwUtils/FwUtilsTests/FwRegistryHelperTests.cs
index be228ca112..742b830a58 100644
--- a/Src/Common/FwUtils/FwUtilsTests/FwRegistryHelperTests.cs
+++ b/Src/Common/FwUtils/FwUtilsTests/FwRegistryHelperTests.cs
@@ -7,6 +7,7 @@
// ---------------------------------------------------------------------------------------------
using NUnit.Framework;
using SIL.FieldWorks.Test.TestUtils;
+using SIL.Utils;
namespace SIL.FieldWorks.Common.FwUtils
{
@@ -16,6 +17,28 @@ namespace SIL.FieldWorks.Common.FwUtils
[TestFixture]
public class FwRegistryHelperTests : BaseTest
{
+ private DummyFwRegistryHelper m_helper;
+
+ ///
+ /// Setups the test bed
+ ///
+ [SetUp]
+ public void Setup()
+ {
+ m_helper = new DummyFwRegistryHelper();
+ FwRegistryHelper.Manager.SetRegistryHelper(m_helper);
+ m_helper.DeleteAllSubTreesIfPresent();
+ }
+
+ ///
+ /// Tears down the test bed
+ ///
+ [TearDown]
+ public void TearDown()
+ {
+ FwRegistryHelper.Manager.Reset();
+ }
+
///
/// Tests that hklm registry keys can be written correctly.
/// Marked as ByHand as it should show a UAC dialog on Vista and Windows7.
@@ -34,5 +57,65 @@ public void SetValueAsAdmin()
Assert.AreEqual("value", registryKey.GetValue("keyname") as string);
}
}
+
+ ///
+ /// Tests how ProjectShared key was migrated from version 7.
+ ///
+ [Test]
+ public void MigrateVersion7ValueIfNeeded_7Unset_NotMigrated()
+ {
+ // Setup
+ using (var version7Key = m_helper.SetupVersion7Settings())
+ {
+ FwRegistryHelper.MigrateVersion7ValueIfNeeded();
+
+ // Verification
+ // Verify that the version 8 ProjectShared key is missing.
+ object dummy;
+ Assert.IsFalse(RegistryHelper.RegEntryExists(FwRegistryHelper.FieldWorksRegistryKey, null, "ProjectShared", out dummy));
+ }
+ }
+
+ ///
+ /// Tests how ProjectShared key was migrated from version 7.
+ ///
+ [Test]
+ public void MigrateVersion7ValueIfNeeded_7UnsetDespiteExistingPath_NotMigrated()
+ {
+ // Setup
+ using (m_helper.SetupVersion7ProjectSharedSettingLocation())
+ using (var version7Key = m_helper.SetupVersion7Settings())
+ {
+ FwRegistryHelper.MigrateVersion7ValueIfNeeded();
+
+ // Verification
+ // Verify that the version 8 ProjectShared key is missing.
+ object dummy;
+ Assert.IsFalse(RegistryHelper.RegEntryExists(FwRegistryHelper.FieldWorksRegistryKey, null, "ProjectShared", out dummy));
+ }
+ }
+
+ ///
+ /// Tests how ProjectShared key was migrated from version 7.
+ ///
+ [Test]
+ public void MigrateVersion7ValueIfNeeded_7Set_Migrated()
+ {
+ // Setup
+ using (m_helper.SetupVersion7ProjectSharedSetting())
+ using (var version7Key = m_helper.SetupVersion7Settings())
+ {
+ object projectsSharedValue;
+ // Verify that the version 8 ProjectShared key is missing before migration
+ Assert.IsFalse(RegistryHelper.RegEntryExists(FwRegistryHelper.FieldWorksRegistryKey, null, "ProjectShared", out projectsSharedValue));
+
+ FwRegistryHelper.MigrateVersion7ValueIfNeeded();
+
+ // Verification
+ // Verify that the version 8 ProjectShared key is set after migration.
+ Assert.IsTrue(RegistryHelper.RegEntryExists(FwRegistryHelper.FieldWorksRegistryKey, null, "ProjectShared", out projectsSharedValue));
+ Assert.IsTrue(bool.Parse((string)projectsSharedValue));
+ }
+ }
}
}
\ No newline at end of file
diff --git a/Src/Common/FwUtils/FwUtilsTests/FwUtilsTests.csproj b/Src/Common/FwUtils/FwUtilsTests/FwUtilsTests.csproj
index 0b8a84df8c..49e47412ef 100644
--- a/Src/Common/FwUtils/FwUtilsTests/FwUtilsTests.csproj
+++ b/Src/Common/FwUtils/FwUtilsTests/FwUtilsTests.csproj
@@ -114,6 +114,10 @@
False
..\..\..\..\Output\Debug\CoreImpl.dll
+
+ False
+ ..\..\..\..\Output\Debug\FDO.dll
+
False
..\..\..\..\Output\Debug\FwUtils.dll
@@ -126,10 +130,6 @@
nunit.framework
..\..\..\..\Bin\NUnit\bin\nunit.framework.dll
-
- False
- ..\..\..\..\DistFiles\ParatextShared.dll
-
False
..\..\..\..\Output\Debug\SilUtils.dll
@@ -154,7 +154,7 @@
AssemblyInfoForTests.cs
-
+
@@ -165,10 +165,7 @@
-
-
-
diff --git a/Src/Common/FwUtils/IFwRegistryHelper.cs b/Src/Common/FwUtils/IFwRegistryHelper.cs
index 7135ddc12c..c7e9f01f41 100644
--- a/Src/Common/FwUtils/IFwRegistryHelper.cs
+++ b/Src/Common/FwUtils/IFwRegistryHelper.cs
@@ -2,7 +2,7 @@
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
-using System;
+
using Microsoft.Win32;
namespace SIL.FieldWorks.Common.FwUtils
@@ -75,18 +75,5 @@ public interface IFwRegistryHelper
///
/// ------------------------------------------------------------------------------------
bool Paratext7orLaterInstalled();
-
- ///
- /// If there is a registry value for this but the folder is not there we need to return false because
- /// paratext is not installed correctly. Also if there is no registry entry for this then return false.
- ///
- bool ParatextSettingsDirectoryExists();
-
- ///
- /// Returns the path to the Paratext settings (projects) directory as specified in the registry
- /// ENHANCE (Hasso) 2013.09: added this to expose the directory for Unix users, because trying to get it from ScrTextCollections
- /// always returns null on Unix. This is really a Paratext problem, and this method may have no benefit.
- ///
- string ParatextSettingsDirectory();
}
}
diff --git a/Src/Common/FwUtils/ShowHelp.cs b/Src/Common/FwUtils/ShowHelp.cs
index a633a5370b..7f3679bdd0 100644
--- a/Src/Common/FwUtils/ShowHelp.cs
+++ b/Src/Common/FwUtils/ShowHelp.cs
@@ -75,7 +75,7 @@ public static void ShowHelpTopic(IHelpTopicProvider helpTopicProvider, string he
// try to get a path to the help file.
try
{
- helpFile = DirectoryFinder.FWCodeDirectory +
+ helpFile = FwDirectoryFinder.CodeDirectory +
helpTopicProvider.GetHelpString(helpFileKey);
}
catch
diff --git a/Src/Common/FwUtils/ValidationProgress.cs b/Src/Common/FwUtils/ValidationProgress.cs
index de190e8705..6d0dc8031a 100644
--- a/Src/Common/FwUtils/ValidationProgress.cs
+++ b/Src/Common/FwUtils/ValidationProgress.cs
@@ -10,6 +10,7 @@
using System;
using Palaso.Lift.Validation;
+using SIL.Utils;
namespace SIL.FieldWorks.Common.FwUtils
{
diff --git a/Src/Common/FwUtils/gendarme-FwUtils.ignore b/Src/Common/FwUtils/gendarme-FwUtils.ignore
index a226ed4aa8..0e28754d8c 100644
--- a/Src/Common/FwUtils/gendarme-FwUtils.ignore
+++ b/Src/Common/FwUtils/gendarme-FwUtils.ignore
@@ -1,8 +1,3 @@
# Gendarme filter file to suppress reporting of defects
#-----------------------------------------------------------------------------------------------
-R: Gendarme.Rules.Correctness.EnsureLocalDisposalRule
-
-# Reference
-M: System.Collections.IEnumerator SIL.FieldWorks.Common.FwUtils.StringSearcher`1/SortKeyIndex/*::System.Collections.IEnumerable.GetEnumerator()
-M: System.Collections.IEnumerator SIL.FieldWorks.Common.FwUtils.StringSearcher`1/*::System.Collections.IEnumerable.GetEnumerator()
diff --git a/Src/Common/PrintLayout/PrintLayoutTests/PrintLayoutTests.csproj b/Src/Common/PrintLayout/PrintLayoutTests/PrintLayoutTests.csproj
index ff32720784..616b40eaea 100644
--- a/Src/Common/PrintLayout/PrintLayoutTests/PrintLayoutTests.csproj
+++ b/Src/Common/PrintLayout/PrintLayoutTests/PrintLayoutTests.csproj
@@ -133,6 +133,10 @@
FwPrintLayoutComponents
..\..\..\..\Output\Debug\FwPrintLayoutComponents.dll
+
+ False
+ ..\..\..\..\Output\Debug\FwResources.dll
+
False
..\..\..\..\DistFiles\Microsoft.Practices.ServiceLocation.dll
diff --git a/Src/Common/PrintLayout/PrintLayoutTests/PubTestsNoDb.cs b/Src/Common/PrintLayout/PrintLayoutTests/PubTestsNoDb.cs
index d33fb6ace1..1c4dbb75af 100644
--- a/Src/Common/PrintLayout/PrintLayoutTests/PubTestsNoDb.cs
+++ b/Src/Common/PrintLayout/PrintLayoutTests/PubTestsNoDb.cs
@@ -6,15 +6,10 @@
// Responsibility: TE Team
using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Text;
-using System.Windows.Forms;
-
using NUnit.Framework;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.PrintLayout;
+using SIL.FieldWorks.Resources;
using SIL.Utils;
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.FDOTests;
@@ -189,7 +184,7 @@ public void DefaultFontAndLineHeightUsed()
m_pub.BaseLineSpacing = 0;
FwStyleSheet stylesheet = new FwStyleSheet();
stylesheet.Init(Cache, Cache.LangProject.TranslatedScriptureOA.Hvo,
- ScriptureTags.kflidStyles);
+ ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
using (DummyDivision divLayoutMgr = new DummyDivision(new DummyPrintConfigurer(Cache, null), 1))
{
@@ -222,7 +217,7 @@ public void PublicationFontAndLineHeightUsed()
m_pub.BaseLineSpacing = -11000;
FwStyleSheet stylesheet = new FwStyleSheet();
stylesheet.Init(Cache, Cache.LangProject.TranslatedScriptureOA.Hvo,
- ScriptureTags.kflidStyles);
+ ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
using (DummyDivision divLayoutMgr = new DummyDivision(new DummyPrintConfigurer(Cache, null), 1))
{
diff --git a/Src/Common/PrintLayout/PublicationControl.cs b/Src/Common/PrintLayout/PublicationControl.cs
index 098f32e864..1c41201d53 100644
--- a/Src/Common/PrintLayout/PublicationControl.cs
+++ b/Src/Common/PrintLayout/PublicationControl.cs
@@ -1,4 +1,4 @@
-// Copyright (c) 2004-2013 SIL International
+// Copyright (c) 2004-2013 SIL International
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
//
@@ -3212,7 +3212,7 @@ public virtual bool OnViewUpdatePageBreak(object args)
CheckDisposed();
IVwRootBox focusedRootBox = FocusedRootBox;
- using (var dialog = new ProgressDialogWithTask(FindForm(), Cache.ThreadHelper))
+ using (var dialog = new ProgressDialogWithTask(FindForm()))
{
dialog.CancelButtonText = ResourceHelper.GetResourceString("kstidUpdatePageBreakButtonText");
dialog.Title = ResourceHelper.GetResourceString("kstidUpdatePageBreakWindowCaption");
@@ -4745,7 +4745,7 @@ public void ApplyPubOverrides(decimal pubCharSize, decimal pubLineSpacing)
}
printLayoutStylesheet.Init(m_cache, m_origStylesheet.RootObjectHvo,
- m_origStylesheet.StyleListTag);
+ m_origStylesheet.StyleListTag, ResourceHelper.DefaultParaCharsStyleName);
}
}
diff --git a/Src/Common/RootSite/FwBaseVc.cs b/Src/Common/RootSite/FwBaseVc.cs
index a72756e1f3..2db0c09c3e 100644
--- a/Src/Common/RootSite/FwBaseVc.cs
+++ b/Src/Common/RootSite/FwBaseVc.cs
@@ -191,7 +191,7 @@ public override void DisplayEmbeddedObject(IVwEnv vwenv, int hvo)
}
string linkedFilesRoot = sda.get_UnicodeProp(m_hvoLangProject, LangProjectTags.kflidLinkedFilesRootDir);
if (String.IsNullOrEmpty(linkedFilesRoot))
- path = Path.Combine(DirectoryFinder.FWDataDirectory, fileName);
+ path = Path.Combine(FwDirectoryFinder.DataDirectory, fileName);
else
path = Path.Combine(linkedFilesRoot, fileName);
}
diff --git a/Src/Common/RootSite/RootSite.csproj b/Src/Common/RootSite/RootSite.csproj
index dde1120a7e..f6e6cc7d23 100644
--- a/Src/Common/RootSite/RootSite.csproj
+++ b/Src/Common/RootSite/RootSite.csproj
@@ -142,7 +142,7 @@
False
- ..\..\..\Downloads\Palaso.dll
+ ..\..\..\Downloads\Palaso.dll
False
@@ -273,8 +273,7 @@
-
../../../DistFiles
-
+
\ No newline at end of file
diff --git a/Src/Common/RootSite/RootSiteEditingHelper.cs b/Src/Common/RootSite/RootSiteEditingHelper.cs
index ab0f936f8b..92d513abfa 100644
--- a/Src/Common/RootSite/RootSiteEditingHelper.cs
+++ b/Src/Common/RootSite/RootSiteEditingHelper.cs
@@ -548,7 +548,7 @@ private void HandleSelectionChange()
// in response to that. There's also a chance we'll never get a selection, but that
// might be okay, too, in some views.
// Also, need to use Invoke, since this may be running on a progress thread.
- Cache.ThreadHelper.Invoke(() =>
+ Control.Invoke(() =>
{
IVwRootBox rootb = EditedRootBox;
RootSite site = null;
diff --git a/Src/Common/RootSite/RootSiteTests/BasicViewTestsBase.cs b/Src/Common/RootSite/RootSiteTests/BasicViewTestsBase.cs
index cda8cf5de2..6ab00f2a0e 100644
--- a/Src/Common/RootSite/RootSiteTests/BasicViewTestsBase.cs
+++ b/Src/Common/RootSite/RootSiteTests/BasicViewTestsBase.cs
@@ -11,10 +11,10 @@
// --------------------------------------------------------------------------------------------
using System.Diagnostics;
using NUnit.Framework;
-using SIL.CoreImpl;
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.FDOTests;
using SIL.FieldWorks.FDO.DomainServices;
+using SIL.FieldWorks.Resources;
namespace SIL.FieldWorks.Common.RootSites
{
@@ -56,7 +56,7 @@ public override void TestSetup()
base.TestSetup();
var styleSheet = new FwStyleSheet();
- styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
+ styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
Debug.Assert(m_basicView == null, "m_basicView is not null.");
//if (m_basicView != null)
diff --git a/Src/Common/RootSite/RootSiteTests/RootSiteTests.csproj b/Src/Common/RootSite/RootSiteTests/RootSiteTests.csproj
index 7d42ca262d..588b27945c 100644
--- a/Src/Common/RootSite/RootSiteTests/RootSiteTests.csproj
+++ b/Src/Common/RootSite/RootSiteTests/RootSiteTests.csproj
@@ -83,7 +83,7 @@
true
4096
false
- 168,169,219,414,649,1635,1702,1701
+ 168,169,219,414,649,1635,1702,1701,1591,1685
true
false
false
@@ -127,6 +127,10 @@
FDOTests
..\..\..\..\Output\Debug\FDOTests.dll
+
+ False
+ ..\..\..\..\Output\Debug\FwResources.dll
+
False
..\..\..\..\DistFiles\Microsoft.Practices.ServiceLocation.dll
diff --git a/Src/Common/RootSite/RootSiteTests/RootsiteBasicViewTestsBase.cs b/Src/Common/RootSite/RootSiteTests/RootsiteBasicViewTestsBase.cs
index 3aa6a0df69..f609ac3fea 100644
--- a/Src/Common/RootSite/RootSiteTests/RootsiteBasicViewTestsBase.cs
+++ b/Src/Common/RootSite/RootSiteTests/RootsiteBasicViewTestsBase.cs
@@ -17,6 +17,7 @@
using SIL.FieldWorks.FDO.FDOTests;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
+using SIL.FieldWorks.Resources;
namespace SIL.FieldWorks.Common.RootSites
{
@@ -252,7 +253,7 @@ public override void TestSetup()
var styleSheet = new FwStyleSheet();
styleSheet.Init(Cache, m_scr.Hvo,
- ScriptureTags.kflidStyles);
+ ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
Debug.Assert(m_basicView == null, "m_basicView is not null.");
diff --git a/Src/Common/RootSite/RootSiteTests/StVcTests.cs b/Src/Common/RootSite/RootSiteTests/StVcTests.cs
index d1500d23dc..e5da14cdc9 100644
--- a/Src/Common/RootSite/RootSiteTests/StVcTests.cs
+++ b/Src/Common/RootSite/RootSiteTests/StVcTests.cs
@@ -14,6 +14,7 @@
using SIL.FieldWorks.FDO;
using SIL.FieldWorks.Common.COMInterfaces;
+using SIL.FieldWorks.Resources;
using SIL.FieldWorks.Test.TestUtils;
using SIL.FieldWorks.FDO.FDOTests;
using SIL.FieldWorks.FDO.Infrastructure;
@@ -298,7 +299,7 @@ public void SpaceAfterFootnoteMarker()
footnote.FootnoteMarker = Cache.TsStrFactory.MakeString("a", Cache.WritingSystemFactory.GetWsFromStr("en"));
// Prepare the test by creating a footnote view
FwStyleSheet styleSheet = new FwStyleSheet();
- styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
+ styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
using (DummyFootnoteView footnoteView = new DummyFootnoteView(Cache))
{
@@ -362,7 +363,7 @@ public void FootnoteTranslationTest()
translation.Translation.set_String(analWs, TsStringHelper.MakeTSS("abcde", analWs));
FwStyleSheet styleSheet = new FwStyleSheet();
- styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
+ styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
// Prepare the test by creating a footnote view
using (DummyFootnoteView footnoteView = new DummyFootnoteView(Cache, true))
@@ -399,7 +400,7 @@ public void ReadOnlySpaceAfterFootnoteMarker()
{
// Prepare the test by creating a footnote view
FwStyleSheet styleSheet = new FwStyleSheet();
- styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
+ styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
using (Form form = new Form())
using (DummyFootnoteView footnoteView = new DummyFootnoteView(Cache))
diff --git a/Src/Common/ScrUtilsInterfaces/ScrUtilsInterfaces.csproj b/Src/Common/ScrUtilsInterfaces/ScrUtilsInterfaces.csproj
index 998ce9007c..428996b88e 100644
--- a/Src/Common/ScrUtilsInterfaces/ScrUtilsInterfaces.csproj
+++ b/Src/Common/ScrUtilsInterfaces/ScrUtilsInterfaces.csproj
@@ -1,185 +1,183 @@
-
+
- Local
- 9.0.30729
- 2.0
- {9CA14238-3229-4FB3-A42A-A173D25F4A6B}
-
-
-
- Debug
- AnyCPU
-
-
-
-
- ScrUtilsInterfaces
-
-
- JScript
- Grid
- IE50
- false
- Library
- SIL.FieldWorks.Common.ScriptureUtils
- OnBuildSuccess
-
-
-
-
-
-
-
-
- 3.5
- false
- v4.0
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- true
-
+ Local
+ 9.0.30729
+ 2.0
+ {9CA14238-3229-4FB3-A42A-A173D25F4A6B}
+
+
+
+
+
+
+ Debug
+ AnyCPU
+
+
+
+
+ ScrUtilsInterfaces
+
+
+ JScript
+ Grid
+ IE50
+ false
+ Library
+ SIL.FieldWorks.Common.ScriptureUtils
+ OnBuildSuccess
+
+
+
+
+
+
+
+
+ 3.5
+ false
+ v4.0
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ true
+
- ..\..\..\Output\Debug\
- false
- 285212672
- false
-
-
- DEBUG;TRACE
- ..\..\..\Output\Debug\ScrUtilsInterfaces.xml
- true
- 4096
- false
- 168,169,219,414,649,1635,1702,1701
- false
- false
- false
- true
- 4
- full
- prompt
- AllRules.ruleset
- x86
+ ..\..\..\Output\Debug\
+ false
+ 285212672
+ false
+
+
+ DEBUG;TRACE
+ ..\..\..\Output\Debug\ScrUtilsInterfaces.xml
+ true
+ 4096
+ false
+ 168,169,219,414,649,1635,1702,1701
+ false
+ false
+ false
+ true
+ 4
+ full
+ prompt
+ AllRules.ruleset
+ x86
- ..\..\..\Output\Release\
- false
- 285212672
- false
-
-
- TRACE
-
-
- false
- 4096
- false
- 168,169,219,414,649,1635,1702,1701
- true
- false
- false
- false
- 4
- none
- prompt
- AllRules.ruleset
- x86
+ ..\..\..\Output\Release\
+ false
+ 285212672
+ false
+
+
+ TRACE
+
+
+ false
+ 4096
+ false
+ 168,169,219,414,649,1635,1702,1701
+ true
+ false
+ false
+ false
+ 4
+ none
+ prompt
+ AllRules.ruleset
+ x86
-
- False
- ..\..\..\Output\Debug\COMInterfaces.dll
-
-
- False
- ..\..\..\Output\Debug\FwResources.dll
-
-
- False
- ..\..\..\Output\Debug\SharedScrUtils.dll
-
-
- System
-
-
-
- System.Data
-
-
-
- System.XML
-
+
+ False
+ ..\..\..\Output\Debug\COMInterfaces.dll
+
+
+ False
+ ..\..\..\Output\Debug\SharedScrUtils.dll
+
+
+ System
+
+
+
+ System.Data
+
+
+ System.XML
+
-
- CommonAssemblyInfo.cs
-
-
- Code
-
-
- Code
-
-
- Code
-
-
- Code
-
-
-
-
+
+ CommonAssemblyInfo.cs
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+
+
-
- Designer
-
+
+ Designer
+
-
- False
- .NET Framework 3.5 SP1 Client Profile
- false
-
-
- False
- .NET Framework 2.0 %28x86%29
- true
-
-
- False
- .NET Framework 3.0 %28x86%29
- false
-
-
- False
- .NET Framework 3.5
- false
-
-
- False
- .NET Framework 3.5 SP1
- false
-
+
+ False
+ .NET Framework 3.5 SP1 Client Profile
+ false
+
+
+ False
+ .NET Framework 2.0 %28x86%29
+ true
+
+
+ False
+ .NET Framework 3.0 %28x86%29
+ false
+
+
+ False
+ .NET Framework 3.5
+ false
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/Src/Common/ScrUtilsInterfaces/ScriptureUtilsException.cs b/Src/Common/ScrUtilsInterfaces/ScriptureUtilsException.cs
index b9fdd14ad7..0889fdf375 100644
--- a/Src/Common/ScrUtilsInterfaces/ScriptureUtilsException.cs
+++ b/Src/Common/ScrUtilsInterfaces/ScriptureUtilsException.cs
@@ -9,11 +9,9 @@
//
using System;
-using System.Runtime;
using System.Reflection;
using System.Resources;
using SILUBS.SharedScrUtils;
-using SIL.FieldWorks.Resources;
namespace SIL.FieldWorks.Common.ScriptureUtils
{
diff --git a/Src/FDO/DomainServices/ParatextHelper.cs b/Src/Common/ScriptureUtils/ParatextHelper.cs
similarity index 86%
rename from Src/FDO/DomainServices/ParatextHelper.cs
rename to Src/Common/ScriptureUtils/ParatextHelper.cs
index cb5077908b..73815c4beb 100644
--- a/Src/FDO/DomainServices/ParatextHelper.cs
+++ b/Src/Common/ScriptureUtils/ParatextHelper.cs
@@ -8,14 +8,16 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
+using System.IO;
using System.Linq;
+using Microsoft.Win32;
using Paratext;
-using Paratext.DerivedTranslation;
-using SIL.FieldWorks.Common.FwUtils;
+using SIL.FieldWorks.FDO;
+using SIL.FieldWorks.FDO.DomainServices;
using SIL.Utils;
using SILUBS.SharedScrUtils;
-namespace SIL.FieldWorks.FDO.DomainServices
+namespace SIL.FieldWorks.Common.ScriptureUtils
{
#region IParatextHelper interface
/// ----------------------------------------------------------------------------------------
@@ -64,13 +66,8 @@ public interface IParatextHelper
///
/// Load the mappings for a Paratext 6/7 project into the specified list.
///
- /// Paratext project ID
- /// ScrMappingList to which new mappings will be added
- /// The import domain for which this project is the source
- /// true if the Paratext mappings were loaded successfully; false
- /// otherwise
/// ------------------------------------------------------------------------------------
- bool LoadProjectMappings(string project, ScrMappingList mappingList, ImportDomain domain);
+ void LoadProjectMappings(IScrImportSet importSettings);
}
#endregion
@@ -144,6 +141,35 @@ public ParatextHelperAdapter()
RefreshProjects();
}
+ ///
+ /// LT-14787 Database displays error about inaccessible Paratext projects
+ /// If there is a registry value for this but the folder is not there we need to return false because
+ /// paratext is not installed correctly. Also if there is no registry entry for this then return false.
+ ///
+ private bool ParatextSettingsDirectoryExists()
+ {
+ var regValue = ParatextSettingsDirectory();
+ return !String.IsNullOrEmpty(regValue) && Directory.Exists(regValue);
+ }
+
+ ///
+ /// Returns the path to the Paratext settings (projects) directory as specified in the registry
+ /// ENHANCE (Hasso) 2013.09: added this to expose the directory for Unix users, because trying to get it from ScrTextCollections
+ /// always returns null on Unix. This is really a Paratext problem, and this method may have no benefit.
+ ///
+ private string ParatextSettingsDirectory()
+ {
+ using (var paratextKey = Registry.LocalMachine.OpenSubKey("Software\\ScrChecks\\1.0\\Settings_Directory"))
+ {
+ if (paratextKey != null)
+ {
+ var keyName = paratextKey.ToString();
+ return Registry.GetValue(keyName, "", "") as string;
+ }
+ }
+ return null;
+ }
+
/// ------------------------------------------------------------------------------------
///
/// Gets the Paratext projects directory (null if none)
@@ -159,7 +185,7 @@ public string ProjectsDirectory
{
// TODO FWNX-1235: Why does SrcTextCollection.SettingsDirectory not work in Unix?
// Does ScrTextCollection work at all in Unix?
- return FwRegistryHelper.ParatextSettingsDirectory();
+ return ParatextSettingsDirectory();
}
return ScrTextCollection.SettingsDirectory;
}
@@ -176,7 +202,7 @@ public void RefreshProjects()
{
try
{
- if (FwRegistryHelper.ParatextSettingsDirectoryExists())
+ if (ParatextSettingsDirectoryExists())
{
if (!m_IsParatextInitialized)
{
@@ -186,7 +212,7 @@ public void RefreshProjects()
// We pass the directory (rather than passing no arguments, and letting the paratext dll figure
// it out) because the figuring out goes wrong on Linux, where both programs are simulating
// the registry.
- ScrTextCollection.Initialize(FwRegistryHelper.ParatextSettingsDirectory(), false);
+ ScrTextCollection.Initialize(ParatextSettingsDirectory(), false);
m_IsParatextInitialized = true;
}
else
@@ -263,20 +289,36 @@ public IEnumerable GetProjects()
///
/// Load the mappings for a Paratext 6/7 project into the specified list.
///
- /// Paratext project ID
- /// ScrMappingList to which new mappings will be added
- /// The import domain for which this project is the source
/// true if the Paratext mappings were loaded successfully; false
/// otherwise
/// ------------------------------------------------------------------------------------
- [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
- Justification = "See REVIEW comment")]
- public bool LoadProjectMappings(string project, ScrMappingList mappingList, ImportDomain domain)
+ public void LoadProjectMappings(IScrImportSet importSettings)
{
RefreshProjects();
+ if (!m_IsParatextInitialized)
+ {
+ importSettings.ParatextScrProj = null;
+ importSettings.ParatextBTProj = null;
+ importSettings.ParatextNotesProj = null;
+ return;
+ }
+
+ if (!LoadProjectMappings(importSettings.ParatextScrProj, importSettings.GetMappingListForDomain(ImportDomain.Main), ImportDomain.Main))
+ importSettings.ParatextScrProj = null;
+
+ if (!LoadProjectMappings(importSettings.ParatextBTProj, importSettings.GetMappingListForDomain(ImportDomain.BackTrans), ImportDomain.BackTrans))
+ importSettings.ParatextBTProj = null;
- // If Paratext is not initialized or the new project ID is null, then do not load mappings.
- if (!m_IsParatextInitialized || project == null)
+ if (!LoadProjectMappings(importSettings.ParatextNotesProj, importSettings.GetMappingListForDomain(ImportDomain.Annotations), ImportDomain.Annotations))
+ importSettings.ParatextNotesProj = null;
+ }
+
+ [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
+ Justification = "See REVIEW comment")]
+ private bool LoadProjectMappings(string project, ScrMappingList mappingList, ImportDomain domain)
+ {
+ // If the new project ID is null, then do not load mappings.
+ if (string.IsNullOrEmpty(project))
return false;
// Load the tags from the paratext project and create mappings for them.
@@ -295,7 +337,8 @@ public bool LoadProjectMappings(string project, ScrMappingList mappingList, Impo
return false;
}
- mappingList.ResetInUseFlags(domain);
+ foreach (ImportMappingInfo mapping in mappingList)
+ mapping.SetIsInUse(domain, false);
try
{
foreach (ScrTag tag in scParatextText.DefaultStylesheet.Tags)
@@ -468,17 +511,12 @@ public static IEnumerable GetProjectBooks(string projShortName)
/// ------------------------------------------------------------------------------------
///
- /// Load the mappings for a Paratext 6/7 project into the specified list.
+ /// Load the mappings for a Paratext 6/7 project into the specified import settings.
///
- /// Paratext project ID
- /// ScrMappingList to which new mappings will be added
- /// The import domain for which this project is the source
- /// true if the Paratext mappings were loaded successfully; false
- /// otherwise
/// ------------------------------------------------------------------------------------
- public static bool LoadProjectMappings(string project, ScrMappingList mappingList, ImportDomain domain)
+ public static void LoadProjectMappings(IScrImportSet importSettings)
{
- return s_ptHelper.LoadProjectMappings(project, mappingList, domain);
+ s_ptHelper.LoadProjectMappings(importSettings);
}
#endregion
diff --git a/Src/Common/ScriptureUtils/ScriptureUtils.csproj b/Src/Common/ScriptureUtils/ScriptureUtils.csproj
index eeeefc15a0..b8911d61fe 100644
--- a/Src/Common/ScriptureUtils/ScriptureUtils.csproj
+++ b/Src/Common/ScriptureUtils/ScriptureUtils.csproj
@@ -1,186 +1,205 @@
-
+
- Local
- 9.0.30729
- 2.0
- {C98A0201-B55C-4B8C-9408-5F5FC2FD22B6}
-
-
-
- Debug
- AnyCPU
-
-
-
-
- ScriptureUtils
-
-
- JScript
- Grid
- IE50
- false
- Library
- SIL.FieldWorks.Common.ScriptureUtils
- OnBuildSuccess
-
-
-
-
-
-
-
-
- 3.5
- false
- v4.0
- publish\
- true
- Disk
- false
- Foreground
- 7
- Days
- false
- false
- true
- 0
- 1.0.0.%2a
- false
- true
-
+ Local
+ 9.0.30729
+ 2.0
+ {C98A0201-B55C-4B8C-9408-5F5FC2FD22B6}
+
+
+
+
+
+
+ Debug
+ AnyCPU
+
+
+
+
+ ScriptureUtils
+
+
+ JScript
+ Grid
+ IE50
+ false
+ Library
+ SIL.FieldWorks.Common.ScriptureUtils
+ OnBuildSuccess
+
+
+
+
+
+
+
+
+ 3.5
+ false
+ v4.0
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ true
+
- ..\..\..\Output\Debug\
- false
- 285212672
- false
-
-
- DEBUG;TRACE
- ..\..\..\Output\Debug\ScriptureUtils.xml
- true
- 4096
- false
- 168,169,219,414,649,1635,1702,1701
- false
- false
- false
- true
- 4
- full
- prompt
- AllRules.ruleset
- x86
+ ..\..\..\Output\Debug\
+ false
+ 285212672
+ false
+
+
+ DEBUG;TRACE
+ ..\..\..\Output\Debug\ScriptureUtils.xml
+ true
+ 4096
+ false
+ 168,169,219,414,649,1635,1702,1701
+ false
+ false
+ false
+ true
+ 4
+ full
+ prompt
+ AllRules.ruleset
+ x86
- ..\..\..\Output\Release\
- false
- 285212672
- false
-
-
- TRACE
-
-
- true
- 4096
- true
- false
- false
- true
- 4
- full
- prompt
- AllRules.ruleset
- x86
+ ..\..\..\Output\Release\
+ false
+ 285212672
+ false
+
+
+ TRACE
+
+
+ true
+ 4096
+ true
+ false
+ false
+ true
+ 4
+ full
+ prompt
+ AllRules.ruleset
+ x86
-
- False
- ..\..\..\Output\Debug\BasicUtils.dll
-
-
- False
- ..\..\..\Output\Debug\COMInterfaces.dll
-
-
- False
- ..\..\..\Output\Debug\FwResources.dll
-
-
- False
- ..\..\..\Output\Debug\FwUtils.dll
-
-
- False
- ..\..\..\Output\Debug\ScrUtilsInterfaces.dll
-
-
- False
- ..\..\..\Output\Debug\SharedScrUtils.dll
-
-
- False
- ..\..\..\Output\Debug\SilEncConverters40.dll
-
-
- System
-
-
-
- System.Data
-
-
- System.XML
-
+
+ False
+ ..\..\..\Output\Debug\BasicUtils.dll
+
+
+ False
+ ..\..\..\Output\Debug\COMInterfaces.dll
+
+
+ False
+ ..\..\..\Output\Debug\FDO.dll
+
+
+ False
+ ..\..\..\Output\Debug\FwResources.dll
+
+
+ False
+ ..\..\..\Output\Debug\FwUtils.dll
+
+
+ False
+ ..\..\..\Output\Debug\ParatextShared.dll
+
+
+ False
+ ..\..\..\Output\Debug\ScrUtilsInterfaces.dll
+
+
+ False
+ ..\..\..\Output\Debug\SharedScrUtils.dll
+
+
+ False
+ ..\..\..\Output\Debug\SilEncConverters40.dll
+
+
+ System
+
+
+
+ System.Data
+
+
+ System.XML
+
+
+ False
+ ..\..\..\Output\Debug\Utilities.dll
+
-
- CommonAssemblyInfo.cs
-
-
- Code
-
-
-
-
- Code
-
+
+ CommonAssemblyInfo.cs
+
+
+ Code
+
+
+
+
+
+ Code
+
-
- False
- .NET Framework 3.5 SP1 Client Profile
- false
-
-
- False
- .NET Framework 2.0 %28x86%29
- true
-
-
- False
- .NET Framework 3.0 %28x86%29
- false
-
-
- False
- .NET Framework 3.5
- false
-
-
- False
- .NET Framework 3.5 SP1
- false
-
+
+ False
+ .NET Framework 3.5 SP1 Client Profile
+ false
+
+
+ False
+ .NET Framework 2.0 %28x86%29
+ true
+
+
+ False
+ .NET Framework 3.0 %28x86%29
+ false
+
+
+ False
+ .NET Framework 3.5
+ false
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
+
+
+
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/Src/FDO/FDOTests/ParatextHelperTests.cs b/Src/Common/ScriptureUtils/ScriptureUtilsTests/ParatextHelperTests.cs
similarity index 88%
rename from Src/FDO/FDOTests/ParatextHelperTests.cs
rename to Src/Common/ScriptureUtils/ScriptureUtilsTests/ParatextHelperTests.cs
index f0b7a671b7..380fc5deb2 100644
--- a/Src/FDO/FDOTests/ParatextHelperTests.cs
+++ b/Src/Common/ScriptureUtils/ScriptureUtilsTests/ParatextHelperTests.cs
@@ -7,20 +7,20 @@
using System;
using System.Collections.Generic;
-using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using NUnit.Framework;
using Paratext;
-using Paratext.DerivedTranslation;
-using Paratext.LexicalClient;
using SIL.FieldWorks.Common.FwUtils;
+using SIL.FieldWorks.FDO;
using SIL.FieldWorks.FDO.DomainServices;
+using SIL.FieldWorks.FDO.FDOTests;
+using SIL.FieldWorks.Resources;
using SIL.FieldWorks.Test.ProjectUnpacker;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
-namespace SIL.FieldWorks.FDO.FDOTests
+namespace SIL.FieldWorks.Common.ScriptureUtils
{
#region MockParatextHelper class
/// ----------------------------------------------------------------------------------------
@@ -128,11 +128,11 @@ public IEnumerable GetProjects()
/// We never use this method; for tests, we use Rhino.Mocks.MockRepository
///
/// ------------------------------------------------------------------------------------
- public bool LoadProjectMappings(string project, ScrMappingList mappingList, ImportDomain domain)
+ public void LoadProjectMappings(IScrImportSet importSettings)
{
if (m_loadProjectMappingsImpl == null)
throw new NotImplementedException();
- return m_loadProjectMappingsImpl.LoadProjectMappings(project, mappingList, domain);
+ m_loadProjectMappingsImpl.LoadProjectMappings(importSettings);
}
#endregion
@@ -205,7 +205,7 @@ public void AddProject(string shortName, string associatedProject, string basePr
scrText.Name = shortName;
if (!string.IsNullOrEmpty(associatedProject))
- scrText.AssociatedLexicalProject = new AssociatedLexicalProject(LexicalAppType.FieldWorks, associatedProject);
+ scrText.AssociatedLexicalProject = new AssociatedLexicalProject("FieldWorks", associatedProject);
// Don't know how to implement a test involving baseProject now that BaseTranslation is gone from the PT API.
// However all clients I can find so far pass null.
if (!string.IsNullOrEmpty(baseProject))
@@ -411,7 +411,9 @@ public class ParatextHelperTests : ScrInMemoryFdoTestBase
[Test]
public void LoadParatextMappings_NullProjectName()
{
- Assert.IsFalse(ParatextHelper.LoadProjectMappings(null, null, ImportDomain.Main));
+ IScrImportSet importSettings = Cache.ServiceLocator.GetInstance().Create(ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
+ ParatextHelper.LoadProjectMappings(importSettings);
+ Assert.That(importSettings.ParatextScrProj, Is.Null);
}
/// ------------------------------------------------------------------------------------
@@ -425,12 +427,13 @@ public void LoadParatextMappings_Normal()
{
Unpacker.UnPackParatextTestProjects();
- FwStyleSheet stylesheet = new FwStyleSheet();
- stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
- ScrMappingList mappingList = new ScrMappingList(MappingSet.Main, stylesheet);
-
- Assert.IsTrue(ParatextHelper.LoadProjectMappings("KAM", mappingList, ImportDomain.Main));
+ var stylesheet = new FwStyleSheet();
+ stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
+ IScrImportSet importSettings = Cache.ServiceLocator.GetInstance().Create(ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
+ importSettings.ParatextScrProj = "KAM";
+ ParatextHelper.LoadProjectMappings(importSettings);
+ ScrMappingList mappingList = importSettings.GetMappingListForDomain(ImportDomain.Main);
// Test to see that the projects are set correctly
Assert.AreEqual(44, mappingList.Count);
@@ -454,9 +457,11 @@ public void LoadParatextMappings_Normal()
[Ignore("Has not been run for a while and no longer works; possibly obsolete")]
public void LoadParatextMappings_MarkMappingsInUse()
{
- FwStyleSheet stylesheet = new FwStyleSheet();
- stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
- ScrMappingList mappingList = new ScrMappingList(MappingSet.Main, stylesheet);
+ var stylesheet = new FwStyleSheet();
+ stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
+ IScrImportSet importSettings = Cache.ServiceLocator.GetInstance().Create(ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
+ importSettings.ParatextScrProj = "TEV";
+ ScrMappingList mappingList = importSettings.GetMappingListForDomain(ImportDomain.Main);
mappingList.Add(new ImportMappingInfo(@"\hahaha", @"\*hahaha", false,
MappingTargetType.TEStyle, MarkerDomain.Default, "laughing",
null, null, true, ImportDomain.Main));
@@ -465,7 +470,8 @@ public void LoadParatextMappings_MarkMappingsInUse()
"en", null, true, ImportDomain.Main));
Unpacker.UnPackParatextTestProjects();
- Assert.IsTrue(ParatextHelper.LoadProjectMappings("TEV", mappingList, ImportDomain.Main));
+
+ ParatextHelper.LoadProjectMappings(importSettings);
Assert.IsTrue(mappingList[@"\c"].IsInUse);
Assert.IsTrue(mappingList[@"\p"].IsInUse);
@@ -486,12 +492,15 @@ public void LoadParatextMappings_MarkMappingsInUse()
[Category("LongRunning")]
public void LoadParatextMappings_MissingEncodingFile()
{
- FwStyleSheet stylesheet = new FwStyleSheet();
- stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
- ScrMappingList mappingList = new ScrMappingList(MappingSet.Main, stylesheet);
+ var stylesheet = new FwStyleSheet();
+ stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
+ IScrImportSet importSettings = Cache.ServiceLocator.GetInstance().Create(ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
+ importSettings.ParatextScrProj = "NEC";
Unpacker.UnPackMissingFileParatextTestProjects();
- Assert.IsFalse(ParatextHelper.LoadProjectMappings("NEC", mappingList, ImportDomain.Main));
+
+ ParatextHelper.LoadProjectMappings(importSettings);
+ Assert.That(importSettings.ParatextScrProj, Is.Null);
}
/// ------------------------------------------------------------------------------------
@@ -505,11 +514,13 @@ public void LoadParatextMappings_MissingEncodingFile()
public void LoadParatextMappings_MissingStyleFile()
{
FwStyleSheet stylesheet = new FwStyleSheet();
- stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
- ScrMappingList mappingList = new ScrMappingList(MappingSet.Main, stylesheet);
+ stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
+ IScrImportSet importSettings = Cache.ServiceLocator.GetInstance().Create(ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
+ importSettings.ParatextScrProj = "NSF";
Unpacker.UnPackMissingFileParatextTestProjects();
- Assert.IsFalse(ParatextHelper.LoadProjectMappings("NSF", mappingList, ImportDomain.Main));
+ ParatextHelper.LoadProjectMappings(importSettings);
+ Assert.That(importSettings.ParatextScrProj, Is.Null);
}
#endregion
}
diff --git a/Src/Common/ScriptureUtils/ScriptureUtilsTests/ScriptureUtilsTests.csproj b/Src/Common/ScriptureUtils/ScriptureUtilsTests/ScriptureUtilsTests.csproj
index 14decc95f7..3c40488b41 100644
--- a/Src/Common/ScriptureUtils/ScriptureUtilsTests/ScriptureUtilsTests.csproj
+++ b/Src/Common/ScriptureUtils/ScriptureUtilsTests/ScriptureUtilsTests.csproj
@@ -5,9 +5,12 @@
9.0.30729
2.0
{C79E699C-2766-4D5B-9661-3BCE7C9679A6}
- SAK
- SAK
- SAK
+
+
+
+
+
+
Debug
AnyCPU
@@ -30,7 +33,8 @@
- SAK
+
+
3.5
false
v4.0
@@ -98,18 +102,54 @@
x86
+
+ False
+ ..\..\..\..\Output\Debug\BasicUtils.dll
+
False
..\..\..\..\Output\Debug\BasicUtilsTests.dll
+
+ False
+ ..\..\..\..\Output\Debug\COMInterfaces.dll
+
False
..\..\..\..\Output\Debug\COMInterfacesTests.dll
+
+ False
+ ..\..\..\..\Output\Debug\FDO.dll
+
+
+ False
+ ..\..\..\..\Output\Debug\FDOTests.dll
+
+
+ False
+ ..\..\..\..\Output\Debug\FwResources.dll
+
+
+ False
+ ..\..\..\..\Output\Debug\FwUtils.dll
+
+
+ False
+ ..\..\..\..\DistFiles\Microsoft.Practices.ServiceLocation.dll
+
nunit.framework
..\..\..\..\Bin\NUnit\bin\nunit.framework.dll
+
+ False
+ ..\..\..\..\Output\Debug\ParatextShared.dll
+
+
+ False
+ ..\..\..\..\Output\Debug\ProjectUnpacker.dll
+
ScriptureUtils
..\..\..\..\Output\Debug\ScriptureUtils.dll
@@ -126,16 +166,22 @@
System
+
TestUtils
..\..\..\..\Output\Debug\TestUtils.dll
+
+ False
+ ..\..\..\..\Output\Debug\Utilities.dll
+
AssemblyInfoForTests.cs
+
diff --git a/Src/Common/SimpleRootSite/SimpleRootSite.csproj b/Src/Common/SimpleRootSite/SimpleRootSite.csproj
index 6daa81ea4b..37625354be 100644
--- a/Src/Common/SimpleRootSite/SimpleRootSite.csproj
+++ b/Src/Common/SimpleRootSite/SimpleRootSite.csproj
@@ -90,7 +90,7 @@
true
4096
false
- 168,169,219,414,649,1635,1702,1701
+ 168,169,219,414,649,1635,1702,1701,1685
true
false
false
diff --git a/Src/Common/SimpleRootSite/SimpleRootSiteTests/SimpleRootSiteTests.csproj b/Src/Common/SimpleRootSite/SimpleRootSiteTests/SimpleRootSiteTests.csproj
index 241abb38e1..dcd573b1ab 100644
--- a/Src/Common/SimpleRootSite/SimpleRootSiteTests/SimpleRootSiteTests.csproj
+++ b/Src/Common/SimpleRootSite/SimpleRootSiteTests/SimpleRootSiteTests.csproj
@@ -84,7 +84,7 @@
false
4096
false
- 168,169,219,414,649,1635,1702,1701
+ 168,169,219,414,649,1635,1702,1701,1685
true
false
false
@@ -206,9 +206,7 @@
-
- UserControl
-
+
@@ -251,4 +249,4 @@
-
+
\ No newline at end of file
diff --git a/Src/FDO/Application/ApplicationServices/AppStrings.Designer.cs b/Src/FDO/Application/ApplicationServices/AppStrings.Designer.cs
index 5d263ed8ba..777b206e57 100644
--- a/Src/FDO/Application/ApplicationServices/AppStrings.Designer.cs
+++ b/Src/FDO/Application/ApplicationServices/AppStrings.Designer.cs
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
-// Runtime Version:4.0.30319.296
+// Runtime Version:4.0.30319.18052
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -548,15 +548,6 @@ internal static string ksProblemImporting {
}
}
- ///
- /// Looks up a localized string similar to Restore Failed.
- ///
- internal static string ksRestoreDidNotSucceed {
- get {
- return ResourceManager.GetString("ksRestoreDidNotSucceed", resourceCulture);
- }
- }
-
///
/// Looks up a localized string similar to Semantic Domain.
///
diff --git a/Src/FDO/Application/ApplicationServices/AppStrings.resx b/Src/FDO/Application/ApplicationServices/AppStrings.resx
index 814540a3a5..0c5b98a38e 100644
--- a/Src/FDO/Application/ApplicationServices/AppStrings.resx
+++ b/Src/FDO/Application/ApplicationServices/AppStrings.resx
@@ -1,302 +1,299 @@
-
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- text/microsoft-resx
+ text/microsoft-resx
- 2.0
+ 2.0
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- Created {0} {1} objects during import from {2}
+ Created {0} {1} objects during import from {2}
- Loading the XML file into the database took {0:F1} seconds.
+ Loading the XML file into the database took {0:F1} seconds.
- This was automatically created to satisfy a Lexical Relation, and it should be checked.
+ This was automatically created to satisfy a Lexical Relation, and it should be checked.
- {0}:{1}: Created an entry for "{2}" to satisfy a Lexical Relation.
+ {0}:{1}: Created an entry for "{2}" to satisfy a Lexical Relation.
- This was automatically created to satisfy a Cross Reference, and it should be checked.
+ This was automatically created to satisfy a Cross Reference, and it should be checked.
- {0}:{1}: Created an entry for "{2}" to satisfy a Cross Reference.
+ {0}:{1}: Created an entry for "{2}" to satisfy a Cross Reference.
- Info: Creating Entry Or Sense Pair Lexical Reference Type with name="{0}" and abbr="{1}".
+ Info: Creating Entry Or Sense Pair Lexical Reference Type with name="{0}" and abbr="{1}".
- Warning: Invalid <Binary> data.
+ Warning: Invalid <Binary> data.
- Warning: Ignoring extra character at the end of <Binary> data.
+ Warning: Ignoring extra character at the end of <Binary> data.
- Warning: Cannot create desired Lexical Reference Type: <Link {0}/>.
+ Warning: Cannot create desired Lexical Reference Type: <Link {0}/>.
- Warning: Cannot resolve a link for a cross reference: <Link {0}/>.
+ Warning: Cannot resolve a link for a cross reference: <Link {0}/>.
- Warning: Cannot resolve a link for a lexical relation: <Link {0}/>.
+ Warning: Cannot resolve a link for a lexical relation: <Link {0}/>.
- Info: Creating new writing system for "{0}".
+ Info: Creating new writing system for "{0}".
- Warning: Media file "{0}" does not exist.
+ Warning: Media file "{0}" does not exist.
- Warning: Picture file "{0}" does not exist.
+ Warning: Picture file "{0}" does not exist.
- Info: Creating new item with ws="{0}", abbr="{1}", and name="{2}" in the {3} list.
+ Info: Creating new item with ws="{0}", abbr="{1}", and name="{2}" in the {3} list.
- Anthropology Categories
+ Anthropology Categories
- Semantic Domain
+ Semantic Domain
- Parts of Speech
+ Parts of Speech
- Location
+ Location
- People
+ People
- Confidence Level
+ Confidence Level
- Warning: Cannot resolve <Link {0}/>
+ Warning: Cannot resolve <Link {0}/>
- Info: Creating Reversal Index for the {0} ("{1}") language.
+ Info: Creating Reversal Index for the {0} ("{1}") language.
- Info: Implicit CmPossibility target in a Link element has name attribute "{0}" which matches an Abbreviation value.
+ Info: Implicit CmPossibility target in a Link element has name attribute "{0}" which matches an Abbreviation value.
- Info: Implicit CmPossibility target in a Link element has abbr attribute "{0}" which matches a Name value.
+ Info: Implicit CmPossibility target in a Link element has abbr attribute "{0}" which matches a Name value.
- Warning: Unexpected {0} element in XML file.
+ Warning: Unexpected {0} element in XML file.
- Warning: Expected <Boolean val="..."/> here.
+ Warning: Expected <Boolean val="..."/> here.
- Warning: Need explicit val attribute for Boolean elements!
+ Warning: Need explicit val attribute for Boolean elements!
- Warning: Expected <Integer val="..."/> here.
+ Warning: Expected <Integer val="..."/> here.
- Warning: Need explicit val attribute for Integer elements!
+ Warning: Need explicit val attribute for Integer elements!
- Warning: Expected <Guid val="..."/> here.
+ Warning: Expected <Guid val="..."/> here.
- Warning: Need explicit val attribute for Guid elements!
+ Warning: Need explicit val attribute for Guid elements!
- Warning: Expected <Time val="..."/> here.
+ Warning: Expected <Time val="..."/> here.
- Warning: Need explicit val attribute for Time elements!
+ Warning: Need explicit val attribute for Time elements!
- Warning: Expected <GenDate val="..."/> here.
+ Warning: Expected <GenDate val="..."/> here.
- Warning: Need explicit val attribute for GenDate elements!
+ Warning: Need explicit val attribute for GenDate elements!
- Warning: Expected <Binary>...</Binary> here.
+ Warning: Expected <Binary>...</Binary> here.
- Warning: Expected <Uni>...</Uni> here.
+ Warning: Expected <Uni>...</Uni> here.
- Warning: Expected <AUni>...</AUni> here.
+ Warning: Expected <AUni>...</AUni> here.
- Warning: Expected <Str>...</Str> here.
+ Warning: Expected <Str>...</Str> here.
- Warning: Expected <AStr>...</AStr> here.
+ Warning: Expected <AStr>...</AStr> here.
- Warning: Expected <Link .../> here.
+ Warning: Expected <Link .../> here.
- Warning: Invalid <Link/> element - must have at least one attribute!
+ Warning: Invalid <Link/> element - must have at least one attribute!
- Warning: Problem importing from {0}.
+ Warning: Problem importing from {0}.
{1}
- Import could not merge the custom field named "{0}" from one entry to another.
+ Import could not merge the custom field named "{0}" from one entry to another.
- Warning: Nested XML object elements must reflect owning relationships.
+ Warning: Nested XML object elements must reflect owning relationships.
- Warning: Unrecognized ownerless object class.
+ Warning: Unrecognized ownerless object class.
- This was automatically created to satisfy a Components link, and it should be checked.
+ This was automatically created to satisfy a Components link, and it should be checked.
- This was automatically created to satisfy a Show Subentry Under link, and it should be checked.
+ This was automatically created to satisfy a Show Subentry Under link, and it should be checked.
- This was automatically created to satisfy a link target, and it should be checked.
+ This was automatically created to satisfy a link target, and it should be checked.
- {0}:{1}: Created an entry for "{2}" to satisfy a Components link.
+ {0}:{1}: Created an entry for "{2}" to satisfy a Components link.
- {0}:{1}: Created an entry for "{2}" to satisfy a Show Subentry Under link.
+ {0}:{1}: Created an entry for "{2}" to satisfy a Show Subentry Under link.
- {0}:{1}: Created an entry for "{2}" to satisfy a link target.
+ {0}:{1}: Created an entry for "{2}" to satisfy a link target.
- Info: Lexical reference type in a Link element has name attribute "{0}" which matches an Abbreviation value.
+ Info: Lexical reference type in a Link element has name attribute "{0}" which matches an Abbreviation value.
- Info: Lexical reference type in a Link element has abbr attribute "{0}" which matches a Name value.
+ Info: Lexical reference type in a Link element has abbr attribute "{0}" which matches a Name value.
- and {0} subrecords.
+ and {0} subrecords.
- There was an error trying to create a subfolder of the new project.
+ There was an error trying to create a subfolder of the new project.
The error was: {0}
-
- Restore Failed
-
-
+
Saving migrated data before loading.
Message on a progress dialog. Appears after a data migration has completed and before the project is opened by FLEx.
diff --git a/Src/FDO/Application/ApplicationServices/XmlImportData.cs b/Src/FDO/Application/ApplicationServices/XmlImportData.cs
index e3c3687c14..f0c50467ab 100644
--- a/Src/FDO/Application/ApplicationServices/XmlImportData.cs
+++ b/Src/FDO/Application/ApplicationServices/XmlImportData.cs
@@ -8,6 +8,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
@@ -15,7 +16,6 @@
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.Utils;
@@ -178,9 +178,8 @@ public XmlImportData(FdoCache cache)
/// Import the file contents into the database represented by the FdoCache established
/// by the constructor.
///
- /// true if successful, false if an error occurs
/// ------------------------------------------------------------------------------------
- public bool ImportData(string sFilename, IProgress progress)
+ public void ImportData(string sFilename, IProgress progress)
{
DateTime dtBegin = DateTime.Now;
m_sFilename = sFilename;
@@ -189,19 +188,18 @@ public bool ImportData(string sFilename, IProgress progress)
if (idx >= 0)
sLogFile = sLogFile.Substring(0, idx);
sLogFile = sLogFile + "-Import.log";
- bool fRetVal = false;
var streamReader = new StreamReader(sFilename, Encoding.UTF8);
try
{
- fRetVal = ImportData(streamReader,
+ ImportData(streamReader,
new StreamWriter(sLogFile, false, Encoding.UTF8),
progress);
- DateTime dtEnd = DateTime.Now;
- TimeSpan span = new TimeSpan(dtEnd.Ticks - dtBegin.Ticks);
- LogFinalCounts(Path.GetFileName(sFilename), span);
}
finally
{
+ DateTime dtEnd = DateTime.Now;
+ var span = new TimeSpan(dtEnd.Ticks - dtBegin.Ticks);
+ LogFinalCounts(Path.GetFileName(sFilename), span);
if (m_wrtrLog != null)
{
m_wrtrLog.Close();
@@ -209,7 +207,6 @@ public bool ImportData(string sFilename, IProgress progress)
}
streamReader.Dispose();
}
- return fRetVal;
}
private void LogFinalCounts(string sFilename, TimeSpan span)
@@ -260,9 +257,10 @@ private void LogMessage(string sMsg)
/// Import the text reader contents into the database represented by the FdoCache set
/// in the constructor.
///
- /// true if successful, false if an error occurs
/// ------------------------------------------------------------------------------------
- public bool ImportData(TextReader rdr, TextWriter wrtrLog, IProgress progress)
+ [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
+ Justification = "xrdr is disposed when closed.")]
+ public void ImportData(TextReader rdr, TextWriter wrtrLog, IProgress progress)
{
bool fRetVal = true;
m_progress = progress;
@@ -301,9 +299,7 @@ public bool ImportData(TextReader rdr, TextWriter wrtrLog, IProgress progress)
m_sFilename, e.Message);
int line = LineNumber(xrdr);
LogMessage(sMsg, line);
- string sTitle = String.Format("Error on line {0}", line);
- MessageBoxUtils.Show(sMsg, sTitle);
- fRetVal = false;
+ throw;
}
finally
{
@@ -311,7 +307,6 @@ public bool ImportData(TextReader rdr, TextWriter wrtrLog, IProgress progress)
xrdr.Close();
m_cache.MainCacheAccessor.EndNonUndoableTask();
}
- return fRetVal;
}
ILexSenseFactory m_factLexSense;
diff --git a/Src/FDO/Application/ApplicationServices/XmlList.cs b/Src/FDO/Application/ApplicationServices/XmlList.cs
index 7609c3dd26..40bf3c3981 100644
--- a/Src/FDO/Application/ApplicationServices/XmlList.cs
+++ b/Src/FDO/Application/ApplicationServices/XmlList.cs
@@ -17,7 +17,6 @@
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.Utils;
@@ -57,15 +56,8 @@ public void ImportList(ICmObject owner, string sFieldName, string sFile, IProgre
#if DEBUG
DateTime dtBegin = DateTime.Now;
#endif
- try
- {
- using (var reader = new StreamReader(sFile, Encoding.UTF8))
- ImportList(owner, sFieldName, reader, progress);
- }
- catch (Exception e)
- {
- MessageBoxUtils.Show(e.Message);
- }
+ using (var reader = new StreamReader(sFile, Encoding.UTF8))
+ ImportList(owner, sFieldName, reader, progress);
#if DEBUG
DateTime dtEnd = DateTime.Now;
TimeSpan span = new TimeSpan(dtEnd.Ticks - dtBegin.Ticks);
@@ -83,110 +75,103 @@ public void ImportList(ICmObject owner, string sFieldName, TextReader reader, IP
m_wsf = m_cache.WritingSystemFactory;
m_progress = progress;
- try
- {
- NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(m_cache.ActionHandlerAccessor, () =>
+ NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(m_cache.ActionHandlerAccessor, () =>
+ {
+ int flidList = m_mdc.GetFieldId(owner.ClassName, sFieldName, true);
+ if (flidList == 0)
+ throw new Exception(String.Format("Invalid list fieldname (programming error): {0}", sFieldName));
+ using (var xrdr = XmlReader.Create(reader))
{
- int flidList = m_mdc.GetFieldId(owner.ClassName, sFieldName, true);
- if (flidList == 0)
- throw new Exception(String.Format("Invalid list fieldname (programming error): {0}", sFieldName));
- using (var xrdr = XmlReader.Create(reader))
- {
- xrdr.MoveToContent();
- if (xrdr.Name != owner.ClassName)
- throw new Exception(String.Format("Unexpected outer element: {0}", xrdr.Name));
+ xrdr.MoveToContent();
+ if (xrdr.Name != owner.ClassName)
+ throw new Exception(String.Format("Unexpected outer element: {0}", xrdr.Name));
- if (!xrdr.ReadToDescendant(sFieldName))
- throw new Exception(String.Format("Unexpected second element: {0}", xrdr.Name));
+ if (!xrdr.ReadToDescendant(sFieldName))
+ throw new Exception(String.Format("Unexpected second element: {0}", xrdr.Name));
- if (!xrdr.ReadToDescendant("CmPossibilityList"))
- throw new Exception(String.Format("Unexpected third element: {0}", xrdr.Name));
+ if (!xrdr.ReadToDescendant("CmPossibilityList"))
+ throw new Exception(String.Format("Unexpected third element: {0}", xrdr.Name));
- ICmPossibilityList list;
- int hvo = m_cache.MainCacheAccessor.get_ObjectProp(owner.Hvo, flidList);
- if (hvo == 0)
- hvo = m_cache.MainCacheAccessor.MakeNewObject(CmPossibilityListTags.kClassId, owner.Hvo, flidList, -2);
- ICmPossibilityListRepository repo = m_cache.ServiceLocator.GetInstance();
- list = repo.GetObject(hvo);
- string sItemClassName = "CmPossibility";
- xrdr.Read();
- while (xrdr.Depth == 3)
+ ICmPossibilityList list;
+ int hvo = m_cache.MainCacheAccessor.get_ObjectProp(owner.Hvo, flidList);
+ if (hvo == 0)
+ hvo = m_cache.MainCacheAccessor.MakeNewObject(CmPossibilityListTags.kClassId, owner.Hvo, flidList, -2);
+ ICmPossibilityListRepository repo = m_cache.ServiceLocator.GetInstance();
+ list = repo.GetObject(hvo);
+ string sItemClassName = "CmPossibility";
+ xrdr.Read();
+ while (xrdr.Depth == 3)
+ {
+ xrdr.MoveToContent();
+ if (xrdr.Depth < 3)
+ break;
+ switch (xrdr.Name)
{
- xrdr.MoveToContent();
- if (xrdr.Depth < 3)
+ case "Description":
+ SetMultiStringFromXml(xrdr, list.Description);
break;
- switch (xrdr.Name)
- {
- case "Description":
- SetMultiStringFromXml(xrdr, list.Description);
- break;
- case "Name":
- SetMultiUnicodeFromXml(xrdr, list.Name);
- break;
- case "Abbreviation":
- SetMultiUnicodeFromXml(xrdr, list.Abbreviation);
- break;
- case "Depth":
- list.Depth = ReadIntFromXml(xrdr);
- break;
- case "DisplayOption":
- list.DisplayOption = ReadIntFromXml(xrdr);
- break;
- case "HelpFile":
- list.HelpFile = ReadUnicodeFromXml(xrdr);
- break;
- case "IsClosed":
- list.IsClosed = ReadBoolFromXml(xrdr);
- break;
- case "IsSorted":
- list.IsSorted = ReadBoolFromXml(xrdr);
- break;
- case "IsVernacular":
- list.IsVernacular = ReadBoolFromXml(xrdr);
- break;
- case "ItemClsid":
- list.ItemClsid = ReadIntFromXml(xrdr);
- sItemClassName = m_mdc.GetClassName(list.ItemClsid);
- break;
- case "ListVersion":
- list.ListVersion = ReadGuidFromXml(xrdr);
- break;
- case "PreventChoiceAboveLevel":
- list.PreventChoiceAboveLevel = ReadIntFromXml(xrdr);
- break;
- case "PreventDuplicates":
- list.PreventDuplicates = ReadBoolFromXml(xrdr);
- break;
- case "PreventNodeChoices":
- list.PreventNodeChoices = ReadBoolFromXml(xrdr);
- break;
- case "UseExtendedFields":
- list.UseExtendedFields = ReadBoolFromXml(xrdr);
- break;
- case "WsSelector":
- list.WsSelector = ReadIntFromXml(xrdr);
- break;
- case "Possibilities":
- LoadPossibilitiesFromXml(xrdr, list, sItemClassName);
- break;
- case "HeaderFooterSets":
- throw new Exception("We don't (yet?) handle HeaderFooterSets for CmPossibilityList (programming issue)");
- case "Publications":
- throw new Exception("We don't (yet?) handle Publications for CmPossibilityList (programming issue)");
- default:
- throw new Exception(String.Format("Unknown field element in CmPossibilityList: {0}", xrdr.Name));
- }
+ case "Name":
+ SetMultiUnicodeFromXml(xrdr, list.Name);
+ break;
+ case "Abbreviation":
+ SetMultiUnicodeFromXml(xrdr, list.Abbreviation);
+ break;
+ case "Depth":
+ list.Depth = ReadIntFromXml(xrdr);
+ break;
+ case "DisplayOption":
+ list.DisplayOption = ReadIntFromXml(xrdr);
+ break;
+ case "HelpFile":
+ list.HelpFile = ReadUnicodeFromXml(xrdr);
+ break;
+ case "IsClosed":
+ list.IsClosed = ReadBoolFromXml(xrdr);
+ break;
+ case "IsSorted":
+ list.IsSorted = ReadBoolFromXml(xrdr);
+ break;
+ case "IsVernacular":
+ list.IsVernacular = ReadBoolFromXml(xrdr);
+ break;
+ case "ItemClsid":
+ list.ItemClsid = ReadIntFromXml(xrdr);
+ sItemClassName = m_mdc.GetClassName(list.ItemClsid);
+ break;
+ case "ListVersion":
+ list.ListVersion = ReadGuidFromXml(xrdr);
+ break;
+ case "PreventChoiceAboveLevel":
+ list.PreventChoiceAboveLevel = ReadIntFromXml(xrdr);
+ break;
+ case "PreventDuplicates":
+ list.PreventDuplicates = ReadBoolFromXml(xrdr);
+ break;
+ case "PreventNodeChoices":
+ list.PreventNodeChoices = ReadBoolFromXml(xrdr);
+ break;
+ case "UseExtendedFields":
+ list.UseExtendedFields = ReadBoolFromXml(xrdr);
+ break;
+ case "WsSelector":
+ list.WsSelector = ReadIntFromXml(xrdr);
+ break;
+ case "Possibilities":
+ LoadPossibilitiesFromXml(xrdr, list, sItemClassName);
+ break;
+ case "HeaderFooterSets":
+ throw new Exception("We don't (yet?) handle HeaderFooterSets for CmPossibilityList (programming issue)");
+ case "Publications":
+ throw new Exception("We don't (yet?) handle Publications for CmPossibilityList (programming issue)");
+ default:
+ throw new Exception(String.Format("Unknown field element in CmPossibilityList: {0}", xrdr.Name));
}
- xrdr.Close();
- if (m_mapRelatedDomains.Count > 0)
- SetRelatedDomainsLinks();
}
- });
- }
- catch (Exception e)
- {
- MessageBoxUtils.Show(e.Message);
- }
+ xrdr.Close();
+ if (m_mapRelatedDomains.Count > 0)
+ SetRelatedDomainsLinks();
+ }
+ });
}
Guid EnsureGuid(Guid guid)
diff --git a/Src/FDO/Application/ApplicationServices/XmlTranslatedLists.cs b/Src/FDO/Application/ApplicationServices/XmlTranslatedLists.cs
index 407902b62d..17d425f292 100644
--- a/Src/FDO/Application/ApplicationServices/XmlTranslatedLists.cs
+++ b/Src/FDO/Application/ApplicationServices/XmlTranslatedLists.cs
@@ -14,7 +14,6 @@
using ICSharpCode.SharpZipLib.Zip;
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Infrastructure;
using System.Globalization;
using SIL.Utils;
@@ -46,30 +45,23 @@ public bool ImportTranslatedLists(string filename, FdoCache cache, IProgress pro
#if DEBUG
DateTime dtBegin = DateTime.Now;
#endif
- try
+ using (var inputStream = FileUtils.OpenStreamForRead(filename))
{
- using (var inputStream = FileUtils.OpenStreamForRead(filename))
+ var type = Path.GetExtension(filename).ToLowerInvariant();
+ if (type == ".zip")
{
- var type = Path.GetExtension(filename).ToLowerInvariant();
- if (type == ".zip")
- {
- using (var zipStream = new ZipInputStream(inputStream))
- {
- var entry = zipStream.GetNextEntry(); // advances it to where we can read the one zipped file.
- using (var reader = new StreamReader(zipStream, Encoding.UTF8))
- ImportTranslatedLists(reader, cache, progress);
- }
- }
- else
+ using (var zipStream = new ZipInputStream(inputStream))
{
- using (var reader = new StreamReader(inputStream, Encoding.UTF8))
+ var entry = zipStream.GetNextEntry(); // advances it to where we can read the one zipped file.
+ using (var reader = new StreamReader(zipStream, Encoding.UTF8))
ImportTranslatedLists(reader, cache, progress);
}
}
- }
- catch (Exception e)
- {
- MessageBoxUtils.Show(e.Message);
+ else
+ {
+ using (var reader = new StreamReader(inputStream, Encoding.UTF8))
+ ImportTranslatedLists(reader, cache, progress);
+ }
}
#if DEBUG
DateTime dtEnd = DateTime.Now;
@@ -95,16 +87,9 @@ public bool ImportTranslatedLists(TextReader reader, FdoCache cache, IProgress p
Debug.Assert(m_wsEn != 0);
m_progress = progress;
- try
- {
- using (var xreader = XmlReader.Create(reader))
+ using (var xreader = XmlReader.Create(reader))
Import(xreader);
- }
- catch (Exception e)
- {
- MessageBoxUtils.Show(e.Message, "Import Error");
- return false;
- }
+
return true;
}
@@ -125,10 +110,11 @@ public bool ImportTranslatedLists(TextReader reader, FdoCache cache, IProgress p
///
///
///
+ ///
///
- public static void ImportTranslatedListsForWs(string ws, FdoCache cache, IProgress progress)
+ public static void ImportTranslatedListsForWs(string ws, FdoCache cache, string templateDir, IProgress progress)
{
- string path = TranslatedListsPathForWs(ws);
+ string path = TranslatedListsPathForWs(ws, templateDir);
if (File.Exists(path))
{
var instance = new XmlTranslatedLists();
@@ -149,10 +135,11 @@ public static string ProgressDialogCaption
/// Call before ImportTranslatedListsForWs. Call that only if the file exists.
///
///
+ ///
///
- public static string TranslatedListsPathForWs(string ws)
+ public static string TranslatedListsPathForWs(string ws, string templateDir)
{
- return Path.Combine(DirectoryFinder.TemplateDirectory, Path.ChangeExtension(LocalizedListPrefix + ws, "zip"));
+ return Path.Combine(templateDir, Path.ChangeExtension(LocalizedListPrefix + ws, "zip"));
}
private int GetWsFromStr(string sWs)
diff --git a/Src/FDO/Application/DomainDataByFlidDecoratorBase.cs b/Src/FDO/Application/DomainDataByFlidDecoratorBase.cs
index 2e6c5d0e45..0228e3590b 100644
--- a/Src/FDO/Application/DomainDataByFlidDecoratorBase.cs
+++ b/Src/FDO/Application/DomainDataByFlidDecoratorBase.cs
@@ -10,9 +10,9 @@
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
+using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.Infrastructure;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.Application
diff --git a/Src/FDO/Application/ISilDataAccessManaged.cs b/Src/FDO/Application/ISilDataAccessManaged.cs
index 4af751be9a..c3c47a4c7f 100644
--- a/Src/FDO/Application/ISilDataAccessManaged.cs
+++ b/Src/FDO/Application/ISilDataAccessManaged.cs
@@ -1,5 +1,5 @@
+using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using System;
namespace SIL.FieldWorks.FDO.Application
diff --git a/Src/FDO/Application/Impl/DomainDataByFlid.cs b/Src/FDO/Application/Impl/DomainDataByFlid.cs
index 0417aa42fa..b9c87a9cc4 100644
--- a/Src/FDO/Application/Impl/DomainDataByFlid.cs
+++ b/Src/FDO/Application/Impl/DomainDataByFlid.cs
@@ -13,7 +13,6 @@
using System.Diagnostics;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.ScriptureUtils;
using SIL.FieldWorks.FDO.DomainImpl;
using SIL.FieldWorks.FDO.DomainServices;
diff --git a/Src/FDO/BuildInclude.targets b/Src/FDO/BuildInclude.targets
index 2e5cf477f4..d13f12120c 100644
--- a/Src/FDO/BuildInclude.targets
+++ b/Src/FDO/BuildInclude.targets
@@ -77,7 +77,12 @@
TemplateFile="FDOGenerate/main.vm.cs"/>
-
+
+
+
+
+
diff --git a/Src/FDO/DomainImpl/CmObject.cs b/Src/FDO/DomainImpl/CmObject.cs
index 5ef25f8ac5..d96a03f52d 100644
--- a/Src/FDO/DomainImpl/CmObject.cs
+++ b/Src/FDO/DomainImpl/CmObject.cs
@@ -25,7 +25,6 @@
using System.IO; // MemoryStream.
using System.Xml.Linq;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Application;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.Utils;
diff --git a/Src/FDO/DomainImpl/FdoFactoryAdditions.cs b/Src/FDO/DomainImpl/FdoFactoryAdditions.cs
index 0762b502ef..a2534609c9 100644
--- a/Src/FDO/DomainImpl/FdoFactoryAdditions.cs
+++ b/Src/FDO/DomainImpl/FdoFactoryAdditions.cs
@@ -81,13 +81,6 @@ public ILexSense Create(ILexEntry entry, SandboxGenericMSA sandboxMSA, ITsString
if (gloss != null)
{
- if (gloss.Length > 256)
- {
- MessageBoxUtils.Show(Strings.ksTruncatingGloss, Strings.ksWarning,
- System.Windows.Forms.MessageBoxButtons.OK,
- System.Windows.Forms.MessageBoxIcon.Warning);
- gloss = gloss.Substring(0, 256);
- }
sense.Gloss.set_String(gloss.get_WritingSystemAt(0), gloss);
}
return sense;
@@ -2661,4 +2654,18 @@ public IText Create(FdoCache cache, Guid guid)
}
}
#endregion
+
+ #region ScrImportSetFactory class
+
+ internal partial class ScrImportSetFactory
+ {
+ public IScrImportSet Create(string defaultParaCharsStyleName, string stylesPath)
+ {
+ var settings = new ScrImportSet(defaultParaCharsStyleName, stylesPath);
+ ((ICmObjectInternal) settings).InitializeNewOwnerlessCmObject(m_cache);
+ return settings;
+ }
+ }
+
+ #endregion
}
diff --git a/Src/FDO/DomainImpl/FdoScripture.cs b/Src/FDO/DomainImpl/FdoScripture.cs
index f93f09b90c..55f776652d 100644
--- a/Src/FDO/DomainImpl/FdoScripture.cs
+++ b/Src/FDO/DomainImpl/FdoScripture.cs
@@ -12,11 +12,11 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Globalization;
using System.Linq;
using System.Text;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.Common.ScriptureUtils;
-using SIL.FieldWorks.Resources;
using SILUBS.SharedScrUtils;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.CoreImpl;
@@ -401,8 +401,10 @@ private IScrImportSet DefaultImportSettings_internal
/// one (which is probably the only one), or creates new settings if none exist.
///
/// type of import type to find
+ /// The default paragraph characters style name.
+ ///
/// ------------------------------------------------------------------------------------
- public IScrImportSet FindOrCreateDefaultImportSettings(TypeOfImport importType)
+ public IScrImportSet FindOrCreateDefaultImportSettings(TypeOfImport importType, string defaultParaCharsStyleName, string stylesPath)
{
IScrImportSet settings = DefaultImportSettings_internal;
@@ -428,7 +430,7 @@ public IScrImportSet FindOrCreateDefaultImportSettings(TypeOfImport importType)
// Didn't find the specified type of settings, so create a new set.
IScrImportSet newSettings =
- m_cache.ServiceLocator.GetInstance().Create();
+ m_cache.ServiceLocator.GetInstance().Create(defaultParaCharsStyleName, stylesPath);
ImportSettingsOC.Add(newSettings);
newSettings.ImportType = (int)importType;
return newSettings;
@@ -866,7 +868,7 @@ public IPublication FindByName(string publicationName)
/// first ensure there is no book with that ID.
///
/// The book to copy.
- /// Attempt to copy book to current version
+ /// Attempt to copy book to current version
/// when that book already exists in the current version
/// The copied bok
/// ------------------------------------------------------------------------------------
@@ -969,7 +971,7 @@ public string ChapterVerseBridgeAsString(IScrSection section)
{
if (section.IsIntro)
{
- return String.Format(ResourceHelper.GetResourceString("kstidScriptureSectionIntroduction"), section.OwnOrd);
+ return String.Format(Strings.ksScriptureSectionIntroduction, section.OwnOrd);
}
ScrReference startRef = new ScrReference(section.VerseRefStart, Versification);
ScrReference endRef = new ScrReference(section.VerseRefEnd, Versification);
@@ -1001,11 +1003,10 @@ public string ContainingRefAsString(IScrFootnote footnote)
}
else if (footnote.TryGetContainingTitle(out containingTitle))
{
- parentContext = ResourceHelper.GetResourceString("kstidScriptureTitle");
- footnoteRef = footnote.OwnOrd.ToString();
+ parentContext = Strings.ksScriptureTitle;
+ footnoteRef = footnote.OwnOrd.ToString(CultureInfo.InvariantCulture);
}
- return String.Format("{0} {1}({2})", parentContext,
- ResourceHelper.GetResourceString("kstidScriptureFootnote"), footnoteRef);
+ return String.Format("{0} {1}({2})", parentContext, Strings.ksScriptureFootnote, footnoteRef);
}
/// ------------------------------------------------------------------------------------
@@ -1073,8 +1074,7 @@ public ITsString BookChapterVerseBridgeAsTss(IStText stText, int ws)
{
ITsStrBldr bldr = tssBookName.GetBldr();
int cch = bldr.Length;
- bldr.Replace(cch, cch, String.Format(" ({0})",
- ResourceHelper.GetResourceString("kstidScriptureTitle")), null);
+ bldr.Replace(cch, cch, String.Format(" ({0})", Strings.ksScriptureTitle), null);
tssTitle = bldr.GetString();
}
}
diff --git a/Src/FDO/DomainImpl/OverridesCellar.cs b/Src/FDO/DomainImpl/OverridesCellar.cs
index b3b2bf805b..bd68a0526b 100644
--- a/Src/FDO/DomainImpl/OverridesCellar.cs
+++ b/Src/FDO/DomainImpl/OverridesCellar.cs
@@ -8,15 +8,12 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
-using System.Windows.Forms;
using System.Collections.Generic;
using System.Text; // StringBuilder
using System.Xml; // XMLWriter
using System.Diagnostics;
using System.IO;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.FDO.Application;
using SIL.Utils;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
@@ -1761,51 +1758,53 @@ internal static ITsString TSSAbbrforWS(FdoCache cache, ICmPossibility pss, int w
return tss;
}
- ///
- /// Return true if this or one of its children is in use as a Constituent chart column.
- /// Most efficient to call this after checking that the root is a chart template.
- ///
- ///
- bool ThisOrChildIsInUseAsChartColumn()
+ public bool IsDefaultDiscourseTemplate
+ {
+ get
+ {
+ ICmPossibilityList ccTempl = Cache.LangProject.DiscourseDataOA.ConstChartTemplOA;
+ if (OwningList != ccTempl)
+ return false;
+
+ IFdoOwningSequence discourseTemplates = ccTempl.PossibilitiesOS;
+ return discourseTemplates.Count == 1 && Hvo == discourseTemplates[0].Hvo;
+ }
+ }
+
+ public bool IsThisOrDescendantInUseAsChartColumn
+ {
+ get
+ {
+ if (OwningList != Cache.LangProject.DiscourseDataOA.ConstChartTemplOA)
+ return false;
+
+ CmPossibility rootPossibility = this;
+ while (rootPossibility.Owner is CmPossibility)
+ rootPossibility = (CmPossibility) rootPossibility.Owner;
+ IDsChart chart = Services.GetInstance().InstancesWithTemplate(rootPossibility).FirstOrDefault();
+ return chart != null && GetIsThisOrDescendantInUseAsChartColumn();
+ }
+ }
+
+ private bool GetIsThisOrDescendantInUseAsChartColumn()
{
var repo = Services.GetInstance();
if (repo.InstancesWithChartCellColumn(this).FirstOrDefault() != null)
return true;
- foreach (var poss in SubPossibilitiesOS)
- if (((CmPossibility)poss).ThisOrChildIsInUseAsChartColumn())
- return true;
- return false;
+ return SubPossibilitiesOS.Cast().Any(poss => poss.GetIsThisOrDescendantInUseAsChartColumn());
}
- ///
- /// If the recipient is a column in a chart that shouldn't be moved or promoted or deleted, report
- /// accordingly and return true. Return false if OK to delete or move.
- ///
- ///
- public bool CheckAndReportProtectedChartColumn()
+ public bool IsOnlyTextMarkupTag
{
- var discourseTemplates = m_cache.LangProject.DiscourseDataOA.ConstChartTemplOA.PossibilitiesOS;
- if (discourseTemplates.Count == 1 && Hvo == discourseTemplates[0].Hvo)
+ get
{
- MessageBoxUtils.Show(Strings.ksCantDeleteDefaultDiscourseTemplate, Strings.ksWarning,
- MessageBoxButtons.OK, MessageBoxIcon.Warning);
- return true;
- }
- ICmPossibility rootPossibility = this;
- while (rootPossibility.Owner is CmPossibility)
- rootPossibility = (CmPossibility)rootPossibility.Owner;
- var chart =
- rootPossibility.Services.GetInstance().InstancesWithTemplate(rootPossibility).
- FirstOrDefault();
- if (chart != null && ThisOrChildIsInUseAsChartColumn())
- {
- string textName = (chart as DsConstChart).BasedOnRA.Title.BestAnalysisVernacularAlternative.Text;
- // This is an actual column; it's a problem if it has instances
- string msg = string.Format(Strings.ksCantModifyTemplateInUse, textName);
- MessageBoxUtils.Show(msg, Strings.ksErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
- return true;
+ ICmPossibilityList tags = Cache.LangProject.TextMarkupTagsOA;
+ if (OwningList != tags)
+ return false;
+
+ IFdoOwningSequence tagTypes = tags.PossibilitiesOS;
+ return tagTypes.Count == 1 && this == tagTypes[0];
}
- return false;
}
/// ------------------------------------------------------------------------------------
@@ -1818,24 +1817,11 @@ public override bool CanDelete
{
get
{
- if (!base.CanDelete)
- return false;
- var lp = Cache.LangProject;
- if (OwningList == lp.DiscourseDataOA.ConstChartTemplOA &&
- CheckAndReportProtectedChartColumn())
- return false;
- if (OwningList == lp.TextMarkupTagsOA &&
- CheckAndReportUsedMarkupTag())
- return false;
- if (IsProtected == false)
- return true;
- var information = Strings.ksRequiredItem;
- MessageBoxUtils.Show(
- information,
- "",
- System.Windows.Forms.MessageBoxButtons.OK,
- System.Windows.Forms.MessageBoxIcon.Information);
- return false;
+ return base.CanDelete
+ && !IsDefaultDiscourseTemplate && !IsThisOrDescendantInUseAsChartColumn
+ && !IsOnlyTextMarkupTag
+ && (OwningList != Cache.LangProject.TextMarkupTagsOA || !Services.GetInstance().GetByTextMarkupTag(this).Any())
+ && !IsProtected;
}
}
@@ -1870,67 +1856,6 @@ public override void MergeObject(ICmObject objSrc, bool fLoseNoStringData)
base.MergeObject(objSrc, fLoseNoStringData);
}
-
- ///
- /// If the recipient is a Tagging possibility that is used in a TextTag object (which shouldn't
- /// exist unless used in a text, it shouldn't be deleted.
- /// Report accordingly and return true. Return false if OK to delete.
- ///
- /// TRUE if there is a problem!
- public bool CheckAndReportUsedMarkupTag()
- {
- var tagTypes = m_cache.LangProject.TextMarkupTagsOA.PossibilitiesOS.ToHvoArray();
- if (tagTypes.Length == 1 && Hvo == tagTypes[0])
- {
- MessageBoxUtils.Show(Strings.ksCantDeleteLastTagList, Strings.ksWarning,
- MessageBoxButtons.OK, MessageBoxIcon.Warning);
- return true;
- }
-
- // Check for subpossibilities that might be in use too!
- List hvoArray = new List();
- hvoArray.Add(Hvo);
- var subArray = SubPossibilitiesOS.ToHvoArray();
- if (subArray.Length > 0)
- {
- // The presence of SubPossibilities means that this is a tag type
- // (if we're in that list), so we need to check all of the SubPossibilities
- // to see if they are used.
- hvoArray.AddRange(subArray);
- }
- // Look in TextTag repo for one (or more) with this possibility label.
- // If used report and return true, otherwise return false.
- var repo = Cache.ServiceLocator.GetInstance();
- var used = (from tag in repo.AllInstances()
- where hvoArray.Contains(tag.TagRA.Hvo)
- select tag).ToArray();
- var cUsed = used.Length;
- if (cUsed == 0)
- return false;
- // Try to get a nice title.
- var msg = GetCorrectErrorMessage(used[0]);
- MessageBox.Show(msg, Strings.ksWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
- return true;
- }
-
- private string GetCorrectErrorMessage(ITextTag usedTag)
- {
- // Try to get a nice title.
- string textName = null;
- if (usedTag != null && usedTag.BeginSegmentRA != null)
- {
- var ws = Cache.LangProject.DefaultWsForMagicWs(WritingSystemServices.kwsFirstAnalOrVern);
- var text = usedTag.BeginSegmentRA.Owner.Owner as IStText;
- textName = text.Title.get_String(ws).Text;
- if (String.IsNullOrEmpty(textName))
- textName = text.ShortName;
- }
- var msg = string.Format(
- (SubPossibilitiesOS.Count == 0) ?
- Strings.ksCantDeleteMarkupTagInUse : Strings.ksCantDeleteMarkupTypeInUse,
- textName);
- return msg;
- }
}
#endregion
@@ -2082,7 +2007,7 @@ public string InternalPath
if (value == null)
throw new ArgumentNullException("value");
- string srcFilename = DirectoryFinderRelativePaths.GetRelativeLinkedFilesPath(value, m_cache.LangProject.LinkedFilesRootDir);
+ string srcFilename = LinkedFilesRelativePathHelper.GetRelativeLinkedFilesPath(value, m_cache.LangProject.LinkedFilesRootDir);
InternalPath_Generated = srcFilename;
}
@@ -2113,7 +2038,7 @@ public string AbsoluteInternalPath
string internalPath = InternalPath;
if (String.IsNullOrEmpty(internalPath))
internalPath = DomainObjectServices.EmptyFileName;
- return DirectoryFinderRelativePaths.GetFullPathFromRelativeLFPath(internalPath, m_cache.LangProject.LinkedFilesRootDir);
+ return LinkedFilesRelativePathHelper.GetFullPathFromRelativeLFPath(internalPath, m_cache.LangProject.LinkedFilesRootDir);
}
}
diff --git a/Src/FDO/DomainImpl/OverridesLangProj.cs b/Src/FDO/DomainImpl/OverridesLangProj.cs
index 73a6652370..7f601ef1d6 100644
--- a/Src/FDO/DomainImpl/OverridesLangProj.cs
+++ b/Src/FDO/DomainImpl/OverridesLangProj.cs
@@ -21,7 +21,6 @@
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.Utils; // Needed for Set class.
-using SIL.FieldWorks.Common.FwUtils; // for LanguageDefinitionFactory
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.CoreImpl;
@@ -82,7 +81,7 @@ public IEnumerable AllWordforms
/// ------------------------------------------------------------------------------------
///
- /// Return LinkedFilesRootDir if explicitly set, otherwise FWDataDirectory.
+ /// Return LinkedFilesRootDir if explicitly set, otherwise DataDirectory.
///
/// ------------------------------------------------------------------------------------
[ModelProperty(CellarPropertyType.Unicode, 6001042, "string")]
@@ -91,14 +90,14 @@ public string LinkedFilesRootDir
get
{
return String.IsNullOrEmpty(LinkedFilesRootDir_Generated)
- ? Path.Combine(m_cache.ProjectId.SharedProjectFolder, DirectoryFinder.ksLinkedFilesDir)
- : DirectoryFinderRelativePaths.GetLinkedFilesFullPathFromRelativePath(LinkedFilesRootDir_Generated,
- m_cache.ProjectId.SharedProjectFolder);
+ ? Path.Combine(m_cache.ProjectId.SharedProjectFolder, FdoFileHelper.ksLinkedFilesDir)
+ : LinkedFilesRelativePathHelper.GetLinkedFilesFullPathFromRelativePath(Services.GetInstance().ProjectsDirectory,
+ LinkedFilesRootDir_Generated, m_cache.ProjectId.SharedProjectFolder);
}
set
{
- string relativePath = DirectoryFinderRelativePaths.GetLinkedFilesRelativePathFromFullPath(value,
- m_cache.ProjectId.SharedProjectFolder, ShortName);
+ string relativePath = LinkedFilesRelativePathHelper.GetLinkedFilesRelativePathFromFullPath(Services.GetInstance().ProjectsDirectory,
+ value, m_cache.ProjectId.SharedProjectFolder, ShortName);
LinkedFilesRootDir_Generated = relativePath;
}
@@ -144,7 +143,7 @@ public IList InterlinearTexts
// Get regular texts.
- if (FwUtils.IsOkToDisplayScriptureIfPresent && TranslatedScriptureOA != null)
+ if (TranslatedScriptureOA != null)
{
// TE installed, so also get them from Sripture.
foreach (var book in TranslatedScriptureOA.ScriptureBooksOS)
diff --git a/Src/FDO/DomainImpl/OverridesLing_Lex.cs b/Src/FDO/DomainImpl/OverridesLing_Lex.cs
index d5a1fb056b..b32279efe6 100644
--- a/Src/FDO/DomainImpl/OverridesLing_Lex.cs
+++ b/Src/FDO/DomainImpl/OverridesLing_Lex.cs
@@ -13,15 +13,13 @@
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
+using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
-using System.Windows.Forms;
using System.Collections.Generic;
using System.Collections.Specialized;
-using System.Windows.Forms.VisualStyles;
using System.Xml; // XMLWriter
-using System.Drawing;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.Application;
@@ -31,9 +29,6 @@
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.FDO.Validation;
using SIL.CoreImpl;
-using Sharpen.Util;
-
-// XmlUtils
namespace SIL.FieldWorks.FDO.DomainImpl
{
@@ -240,29 +235,29 @@ public ICmPossibilityList PublicationTypesOA
///
/// Allows user to convert LexEntryType to LexEntryInflType.
///
- public void ConvertLexEntryInflTypes(ProgressBar progressBar, IEnumerable list)
+ public void ConvertLexEntryInflTypes(IProgress progressBar, IEnumerable list)
{
progressBar.Minimum = 0;
progressBar.Maximum = list.Count();
- progressBar.Step = 1;
+ progressBar.StepSize = 1;
foreach (var lexEntryType in list)
{
var leitFactory = m_cache.ServiceLocator.GetInstance();
var leit = leitFactory.Create();
leit.ConvertLexEntryType(lexEntryType);
lexEntryType.Delete();
- progressBar.PerformStep();
+ progressBar.Step(1);
}
}
///
/// Allows user to convert LexEntryInflType to LexEntryType.
///
- public void ConvertLexEntryTypes(ProgressBar progressBar, IEnumerable list)
+ public void ConvertLexEntryTypes(IProgress progressBar, IEnumerable list)
{
progressBar.Minimum = 0;
progressBar.Maximum = list.Count();
- progressBar.Step = 1;
+ progressBar.StepSize = 1;
foreach (var lexEntryInflType in list)
{
var leit = lexEntryInflType as ILexEntryInflType;
@@ -273,20 +268,20 @@ public void ConvertLexEntryTypes(ProgressBar progressBar, IEnumerable
/// Resets the homograph numbers for all entries but can take a null progress bar.
///
- public void ResetHomographNumbers(ProgressBar progressBar)
+ public void ResetHomographNumbers(IProgress progressBar)
{
if (progressBar != null)
{
progressBar.Minimum = 0;
progressBar.Maximum = Entries.Count();
- progressBar.Step = 1;
+ progressBar.StepSize = 1;
}
var processedEntryIds = new List();
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(Strings.ksUndoResetHomographs, Strings.ksRedoResetHomographs, Cache.ActionHandlerAccessor,
@@ -297,7 +292,7 @@ public void ResetHomographNumbers(ProgressBar progressBar)
if (processedEntryIds.Contains(le.Hvo))
{
if (progressBar != null)
- progressBar.PerformStep();
+ progressBar.Step(1);
continue;
}
@@ -315,7 +310,7 @@ public void ResetHomographNumbers(ProgressBar progressBar)
{
processedEntryIds.Add(homograph.Hvo);
if (progressBar != null)
- progressBar.PerformStep();
+ progressBar.Step(1);
}
}
});
diff --git a/Src/FDO/DomainImpl/OverridesLing_MoClasses.cs b/Src/FDO/DomainImpl/OverridesLing_MoClasses.cs
index 1bebc4ac49..85fbad15be 100644
--- a/Src/FDO/DomainImpl/OverridesLing_MoClasses.cs
+++ b/Src/FDO/DomainImpl/OverridesLing_MoClasses.cs
@@ -14,11 +14,9 @@
using System.Linq;
using System.Diagnostics;
using System.Text;
-using System.Collections;
using System.Collections.Generic;
using System.Xml; // XMLWriter
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.Utils;
diff --git a/Src/FDO/DomainImpl/ReadWriteServices.cs b/Src/FDO/DomainImpl/ReadWriteServices.cs
index 459289b820..e8fe6b6d6b 100644
--- a/Src/FDO/DomainImpl/ReadWriteServices.cs
+++ b/Src/FDO/DomainImpl/ReadWriteServices.cs
@@ -3,7 +3,6 @@
using System.Xml;
using System.Xml.Linq;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.CoreImpl;
using System.Collections.Generic;
diff --git a/Src/FDO/DomainImpl/ScrBook.cs b/Src/FDO/DomainImpl/ScrBook.cs
index 09fa2cff33..5a83cd13db 100644
--- a/Src/FDO/DomainImpl/ScrBook.cs
+++ b/Src/FDO/DomainImpl/ScrBook.cs
@@ -9,15 +9,11 @@
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Runtime.InteropServices;
-using SIL.FieldWorks.FDO;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.ScriptureUtils;
using SILUBS.SharedScrUtils;
using SIL.Utils;
using System.Text;
-using System.Data.SqlClient;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.CoreImpl;
diff --git a/Src/FDO/DomainImpl/ScrImportSet.cs b/Src/FDO/DomainImpl/ScrImportSet.cs
index 3f9eb250d2..254943f86a 100644
--- a/Src/FDO/DomainImpl/ScrImportSet.cs
+++ b/Src/FDO/DomainImpl/ScrImportSet.cs
@@ -6,18 +6,13 @@
// Responsibility: TE Team
using System;
-using System.IO;
using System.Collections;
-using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
-using System.Linq;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.Utils;
using SILUBS.SharedScrUtils;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.FDO.DomainServices;
-using SIL.FieldWorks.Resources;
namespace SIL.FieldWorks.FDO.DomainImpl
{
@@ -46,6 +41,9 @@ internal partial class ScrImportSet
///
private Hashtable m_notesFileInfoLists = new Hashtable();
+ private readonly string m_defaultParaCharsStyleName;
+ private readonly string m_stylesPath;
+
private IOverlappingFileResolver m_resolver;
private ScrMappingList m_scrMappingsList;
@@ -65,11 +63,16 @@ internal partial class ScrImportSet
private bool m_fImportAnnotations;
private BCVRef m_startRef;
private BCVRef m_endRef;
-
- private string m_helpFile;
#endregion
#region Construction & initialization
+
+ internal ScrImportSet(string defaultParaStylesName, string stylesPath)
+ {
+ m_defaultParaCharsStyleName = defaultParaStylesName;
+ m_stylesPath = stylesPath;
+ }
+
/// ------------------------------------------------------------------------------------
///
/// Initialize the ScrImportSet. Sets the default values after the initialization of a
@@ -85,8 +88,8 @@ protected override void SetDefaultValuesAfterInit()
private void DoCommonNonModelSetup()
{
- m_scrMappingsList = new ScrMappingList(MappingSet.Main, m_stylesheet);
- m_notesMappingsList = new ScrMappingList(MappingSet.Notes, m_stylesheet);
+ m_scrMappingsList = new ScrMappingList(MappingSet.Main, m_stylesheet, m_defaultParaCharsStyleName, m_stylesPath);
+ m_notesMappingsList = new ScrMappingList(MappingSet.Notes, m_stylesheet, m_defaultParaCharsStyleName, m_stylesPath);
LoadInMemoryMappingLists();
LoadSources(false);
@@ -129,9 +132,9 @@ private void LoadSources(bool createSourcesIfNeeded)
private void LoadInMemoryMappingLists()
{
foreach (ScrMarkerMapping mapping in ScriptureMappingsOC)
- m_scrMappingsList.Add(mapping.ToImportMappingInfo());
+ m_scrMappingsList.Add(mapping.ToImportMappingInfo(m_defaultParaCharsStyleName));
foreach (ScrMarkerMapping mapping in NoteMappingsOC)
- m_notesMappingsList.Add(mapping.ToImportMappingInfo());
+ m_notesMappingsList.Add(mapping.ToImportMappingInfo(m_defaultParaCharsStyleName));
m_scrMappingsList.ResetChangedFlags();
m_notesMappingsList.ResetChangedFlags();
}
@@ -149,7 +152,7 @@ private void LoadInMemoryFileLists()
{
m_scrFileInfoList = new ScrSfFileList((ScrImportSFFiles)source,
m_scrMappingsList, ImportDomain.Main,
- (ImportTypeEnum == TypeOfImport.Paratext5), m_helpFile);
+ (ImportTypeEnum == TypeOfImport.Paratext5));
m_scrFileInfoList.OverlappingFileResolver = m_resolver;
break;
}
@@ -164,7 +167,7 @@ private void LoadInMemoryFileLists()
string wsId = source.WritingSystem ?? string.Empty;
m_btFileInfoLists[wsId] = new ScrSfFileList((ScrImportSFFiles)source,
m_scrMappingsList, ImportDomain.BackTrans,
- (ImportTypeEnum == TypeOfImport.Paratext5), m_helpFile);
+ (ImportTypeEnum == TypeOfImport.Paratext5));
}
}
@@ -177,7 +180,7 @@ private void LoadInMemoryFileLists()
((ScrImportSFFiles)source).NoteTypeRA);
m_notesFileInfoLists[key] = new ScrSfFileList((ScrImportSFFiles)source,
m_notesMappingsList, ImportDomain.Annotations,
- (ImportTypeEnum == TypeOfImport.Paratext5), m_helpFile);
+ (ImportTypeEnum == TypeOfImport.Paratext5));
}
}
}
@@ -253,107 +256,6 @@ public TypeOfImport ImportTypeEnum
}
#endregion
- #region Import Project Accessibility Methods
- /// -----------------------------------------------------------------------------------
- ///
- /// Indicates whether the in-memory import projects/files are currently accessible from
- /// this machine.
- ///
- /// A list of Paratext project IDs or file paths that
- /// could not be found.
- ///
- /// For Paratext projects, this will only return true if all projects are accessible.
- /// For Standard Format, this will return true if any of the files are accessible.
- /// We think this might make sense, but we aren't sure why.
- ///
- /// -----------------------------------------------------------------------------------
- public bool ImportProjectIsAccessible(out StringCollection thingsNotFound)
- {
- lock (SyncRoot)
- {
- if (ImportTypeEnum == TypeOfImport.Paratext6)
- return ParatextProjectsAccessible(out thingsNotFound);
- else if (ImportTypeEnum == TypeOfImport.Other || ImportTypeEnum == TypeOfImport.Paratext5)
- return SFProjectFilesAccessible(out thingsNotFound);
- thingsNotFound = null;
- return false;
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Determines whether or not a set of paratext projects can be found and are
- /// accessible.
- ///
- /// A list of the Paratext projects that couldn't
- /// be found or are inaccessible.
- /// A value indicating whether or not the projects are accessible. True if
- /// all are. Otherwise, false.
- /// ------------------------------------------------------------------------------------
- private bool ParatextProjectsAccessible(out StringCollection projectsNotFound)
- {
- projectsNotFound = new StringCollection();
-
- if (m_ParatextScrProject == null)
- return false;
-
- // Paratext seems to want to have write access to do an import...
- string filename = Path.Combine(ParatextHelper.ProjectsDirectory, m_ParatextScrProject + ".ssf");
- if (!FileUtils.IsFileReadableAndWritable(filename) ||
- !ParatextHelper.GetProjectBooks(m_ParatextScrProject).Any())
- {
- projectsNotFound.Add(m_ParatextScrProject);
- }
-
- if (m_ParatextBTProject != null)
- {
- filename = Path.Combine(ParatextHelper.ProjectsDirectory, m_ParatextBTProject + ".ssf");
- if (!FileUtils.IsFileReadableAndWritable(filename) ||
- !ParatextHelper.GetProjectBooks(m_ParatextBTProject).Any())
- {
- projectsNotFound.Add(m_ParatextBTProject);
- }
- }
-
- if (m_ParatextNotesProject != null)
- {
- filename = Path.Combine(ParatextHelper.ProjectsDirectory, m_ParatextNotesProject + ".ssf");
- if (!FileUtils.IsFileReadableAndWritable(filename) ||
- !ParatextHelper.GetProjectBooks(m_ParatextNotesProject).Any())
- {
- projectsNotFound.Add(m_ParatextNotesProject);
- }
- }
-
- return (projectsNotFound.Count == 0);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Determines whether or not a set of SFM project files can be found and are
- /// accessible.
- ///
- /// A list of files that couldn't be found.
- /// true if any SFM files are accessible. Otherwise, false.
- /// ------------------------------------------------------------------------------------
- private bool SFProjectFilesAccessible(out StringCollection filesNotFound)
- {
- filesNotFound = new StringCollection();
-
- bool fProjectFileFound = false;
-
- fProjectFileFound |= m_scrFileInfoList.FilesAreAccessible(ref filesNotFound);
-
- foreach (ScrSfFileList list in m_btFileInfoLists.Values)
- fProjectFileFound |= list.FilesAreAccessible(ref filesNotFound);
-
- foreach (ScrSfFileList list in m_notesFileInfoLists.Values)
- fProjectFileFound |= list.FilesAreAccessible(ref filesNotFound);
-
- return (fProjectFileFound);
- }
- #endregion
-
#region Public Properties
/// ------------------------------------------------------------------------------------
///
@@ -639,18 +541,6 @@ public bool Valid
}
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Sets the StartRef and EndRef based on the requested canonical book numbers.
- ///
- /// ------------------------------------------------------------------------------------
- public void IncludeBooks(int startBook, int endBook, Paratext.ScrVers versification)
- {
- StartRef = new BCVRef(startBook, 0, 0);
- int chapter = versification.LastChapter(endBook);
- EndRef = new BCVRef(endBook, chapter, versification.LastVerse(endBook, chapter));
- }
-
/// ------------------------------------------------------------------------------------
///
/// Gets/sets stylesheet for settings.
@@ -674,20 +564,6 @@ public IVwStylesheet StyleSheet
}
}
}
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Sets the help file used in a message box if an error occurs.
- ///
- /// ------------------------------------------------------------------------------------
- public string HelpFile
- {
- set
- {
- lock (SyncRoot)
- m_helpFile = value;
- }
- }
#endregion
#region Public Methods
@@ -904,7 +780,7 @@ public virtual string ParatextScrProj
if (value != null && (value == ParatextNotesProj || value == ParatextBTProj))
throw new ArgumentException(ScrFdoResources.kstidPtScrAlreadyUsed);
- m_ParatextScrProject = SetParatextProject(value, ImportDomain.Main);
+ m_ParatextScrProject = value;
}
}
}
@@ -930,7 +806,7 @@ public virtual string ParatextBTProj
if (value != null && (value == ParatextScrProj || value == ParatextNotesProj))
throw new ArgumentException(ScrFdoResources.kstidPtBtAlreadyUsed);
- m_ParatextBTProject = SetParatextProject(value, ImportDomain.BackTrans);
+ m_ParatextBTProject = value;
}
}
}
@@ -956,34 +832,11 @@ public virtual string ParatextNotesProj
if (value != null && (value == ParatextScrProj || value == ParatextBTProj))
throw new ArgumentException(ScrFdoResources.kstidPtNotesAlreadyUsed);
- m_ParatextNotesProject = SetParatextProject(value, ImportDomain.Annotations);
+ m_ParatextNotesProject = value;
}
}
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Sets the Paratext project name for the specified domain.
- ///
- /// The name of the Paratext project.
- /// The domain (Scripture, back translation or annotations).
- /// name of the project, if not empty and the project loads without error;
- /// otherwise null
- /// ------------------------------------------------------------------------------------
- private string SetParatextProject(string value, ImportDomain domain)
- {
- string projName = (value == string.Empty) ? null : value;
- if (projName != null)
- {
- // use notes list for the annotations domain, otherwise use the scripture list.
- ScrMappingList loadedList = domain == ImportDomain.Annotations ? m_notesMappingsList : m_scrMappingsList;
- bool fValidProj = ParatextHelper.LoadProjectMappings(value, loadedList, domain);
- return fValidProj ? value : null;
- }
-
- return null;
- }
-
/// ------------------------------------------------------------------------------------
///
/// Commit the "temporary" in-memory settings to the permanent properties
@@ -1070,60 +923,6 @@ private string StartsWithMarker(string line, StringCollection markersList)
return null;
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets a list of books that exist for all of the files in this project.
- ///
- /// A List of integers representing 1-based canonical book numbers that exist
- /// in any source represented by these import settings
- /// If project is not a supported type
- /// ------------------------------------------------------------------------------------
- public List BooksForProject
- {
- get
- {
- Debug.Assert(BasicSettingsExist, "Vernacular Scripture project not defined.");
- switch (ImportTypeEnum)
- {
- case TypeOfImport.Paratext6:
- // TODO (TE-5903): Check BT and Notes projects as well.
- return ParatextHelper.GetProjectBooks(ParatextScrProj).ToList();
- case TypeOfImport.Paratext5:
- case TypeOfImport.Other:
- lock (SyncRoot)
- {
- List booksPresent = new List();
- foreach (IScrImportFileInfo file in m_scrFileInfoList)
- foreach (int iBook in file.BooksInFile)
- {
- if (!booksPresent.Contains(iBook))
- booksPresent.Add(iBook);
- }
-
- foreach (ScrSfFileList fileList in m_btFileInfoLists.Values)
- foreach (IScrImportFileInfo file in fileList)
- foreach (int iBook in file.BooksInFile)
- {
- if (!booksPresent.Contains(iBook))
- booksPresent.Add(iBook);
- }
-
- foreach (ScrSfFileList fileList in m_notesFileInfoLists.Values)
- foreach (IScrImportFileInfo file in fileList)
- foreach (int iBook in file.BooksInFile)
- {
- if (!booksPresent.Contains(iBook))
- booksPresent.Add(iBook);
- }
- booksPresent.Sort();
- return booksPresent;
- }
- default:
- throw new NotSupportedException("Unexpected type of Import Project");
- }
- }
- }
-
/// ------------------------------------------------------------------------------------
///
/// Get a MappingSet that is appropriate for the ImportDomain
@@ -1451,7 +1250,7 @@ private void SaveMappings(IFdoOwningCollection mappingsOC, Sc
mappingsOC.Add(mapping);
// The "Default Paragraph Characters" style is not a real style. So, we save it as
// as separate target type. We want to set the style now for the in-memory info.
- if (info.StyleName == ResourceHelper.DefaultParaCharsStyleName)
+ if (info.StyleName == m_defaultParaCharsStyleName)
info.MappingTarget = MappingTargetType.DefaultParaChars;
else if (info.Style == null || info.Style.Name != info.StyleName)
info.SetStyle((StStyle)m_cache.LangProject.TranslatedScriptureOA.FindStyle(info.StyleName));
diff --git a/Src/FDO/DomainImpl/ScrMarkerMapping.cs b/Src/FDO/DomainImpl/ScrMarkerMapping.cs
index bbb33e7604..6a644ba95b 100644
--- a/Src/FDO/DomainImpl/ScrMarkerMapping.cs
+++ b/Src/FDO/DomainImpl/ScrMarkerMapping.cs
@@ -5,16 +5,8 @@
// File: ScrMarkerMapping.cs
// Responsibility: TE Team
-using System;
-using System.Collections.Generic;
-using System.Collections;
-using System.Diagnostics;
-using SIL.FieldWorks.FDO;
-using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.DomainServices;
-using SIL.FieldWorks.Common.ScriptureUtils;
-using SIL.FieldWorks.Resources;
namespace SIL.FieldWorks.FDO.DomainImpl
{
@@ -48,7 +40,7 @@ internal void InitFromImportMappingInfo(ImportMappingInfo info)
/// Get the members of a ScrMarkerMapping into an ImportMappingInfo object
///
/// ------------------------------------------------------------------------------------
- public ImportMappingInfo ToImportMappingInfo()
+ public ImportMappingInfo ToImportMappingInfo(string defaultParaCharsStyleName)
{
MarkerDomain domain = (MarkerDomain)Domain;
if ((domain & MarkerDomain.DeprecatedScripture) != 0)
@@ -61,7 +53,7 @@ public ImportMappingInfo ToImportMappingInfo()
if (Target == (int)MappingTargetType.DefaultParaChars)
{
return new ImportMappingInfo(BeginMarker, EndMarker, Excluded,
- MappingTargetType.TEStyle, domain, ResourceHelper.DefaultParaCharsStyleName,
+ MappingTargetType.TEStyle, domain, defaultParaCharsStyleName,
WritingSystem, NoteTypeRA);
}
diff --git a/Src/FDO/DomainImpl/ScrScriptureNote.cs b/Src/FDO/DomainImpl/ScrScriptureNote.cs
index 6d356f2c10..0add1b6e77 100644
--- a/Src/FDO/DomainImpl/ScrScriptureNote.cs
+++ b/Src/FDO/DomainImpl/ScrScriptureNote.cs
@@ -10,17 +10,9 @@
//
using System;
-using System.Collections.Generic;
using System.Diagnostics;
-using System.Runtime.InteropServices;
-using System.Text;
-
-using SIL.FieldWorks.FDO;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.Utils;
using SIL.FieldWorks.Common.ScriptureUtils;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.Resources;
using SILUBS.SharedScrUtils;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.CoreImpl;
diff --git a/Src/FDO/DomainImpl/ScrSection.cs b/Src/FDO/DomainImpl/ScrSection.cs
index 6581e31253..f05557a31b 100644
--- a/Src/FDO/DomainImpl/ScrSection.cs
+++ b/Src/FDO/DomainImpl/ScrSection.cs
@@ -10,16 +10,12 @@
using System;
using System.Diagnostics;
-
-using SIL.FieldWorks.FDO;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.ScriptureUtils;
using SILUBS.SharedScrUtils;
using System.Collections.Generic;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.CoreImpl;
-using SIL.FieldWorks.FDO.Infrastructure;
namespace SIL.FieldWorks.FDO.DomainImpl
{
diff --git a/Src/FDO/DomainImpl/StFootnote.cs b/Src/FDO/DomainImpl/StFootnote.cs
index 549b68f0a1..37390bc24e 100644
--- a/Src/FDO/DomainImpl/StFootnote.cs
+++ b/Src/FDO/DomainImpl/StFootnote.cs
@@ -10,15 +10,9 @@
using System;
using System.Diagnostics;
-using System.Xml;
using System.Text;
-using System.Collections.Generic;
-
-using SIL.FieldWorks.FDO;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.Infrastructure;
-using SIL.Utils;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.CoreImpl;
namespace SIL.FieldWorks.FDO.DomainImpl
diff --git a/Src/FDO/DomainServices/BackupRestore/BackupFileRepository.cs b/Src/FDO/DomainServices/BackupRestore/BackupFileRepository.cs
index 911821f95b..f5f5a7fe9d 100644
--- a/Src/FDO/DomainServices/BackupRestore/BackupFileRepository.cs
+++ b/Src/FDO/DomainServices/BackupRestore/BackupFileRepository.cs
@@ -11,9 +11,7 @@
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
-using SIL.FieldWorks.Common.FwUtils;
using System.Collections.Generic;
-using SIL.FieldWorks.Resources;
using SIL.Utils;
using System.Globalization;
@@ -39,12 +37,12 @@ public class BackupFileRepository
/// we'll need to pass in the directory name or have a way to change it.
///
/// ------------------------------------------------------------------------------------
- public BackupFileRepository()
+ public BackupFileRepository(string defaultBackupDir)
{
string[] backups;
try
{
- backups = FileUtils.GetFilesInDirectory(DirectoryFinder.DefaultBackupDirectory);
+ backups = FileUtils.GetFilesInDirectory(defaultBackupDir);
}
catch (Exception)
{
@@ -55,7 +53,7 @@ public BackupFileRepository()
foreach (string backup in backups)
{
string ext = Path.GetExtension(backup);
- if (ext != FwFileExtensions.ksFwBackupFileExtension && ext != FwFileExtensions.ksFw60BackupFileExtension)
+ if (ext != FdoFileHelper.ksFwBackupFileExtension && ext != FdoFileHelper.ksFw60BackupFileExtension)
continue;
string filename = Path.GetFileNameWithoutExtension(backup);
MatchCollection matches = regex.Matches(filename);
@@ -77,7 +75,7 @@ public BackupFileRepository()
{
SortedDictionary versions = GetOrCreateProjectVersions(projectName);
string comment;
- if (ext == FwFileExtensions.ksFw60BackupFileExtension)
+ if (ext == FdoFileHelper.ksFw60BackupFileExtension)
comment = Properties.Resources.kstidFw60OrEarlierBackupComment;
else
{
diff --git a/Src/FDO/DomainServices/BackupRestore/BackupFileSettings.cs b/Src/FDO/DomainServices/BackupRestore/BackupFileSettings.cs
index 57cc4d217a..540f4990bd 100644
--- a/Src/FDO/DomainServices/BackupRestore/BackupFileSettings.cs
+++ b/Src/FDO/DomainServices/BackupRestore/BackupFileSettings.cs
@@ -10,9 +10,7 @@
using System.Runtime.Serialization;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.Utils;
-using SIL.FieldWorks.Resources;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
namespace SIL.FieldWorks.FDO.DomainServices.BackupRestore
@@ -119,11 +117,11 @@ private BackupFileSettings(BackupProjectSettings settings)
m_supportingFiles = settings.IncludeSupportingFiles;
m_linkedFiles = settings.IncludeLinkedFiles;
m_projectName = settings.ProjectName;
- m_projectPathPersisted = DirectoryFinder.GetPathWithoutRoot(settings.ProjectPath);
+ m_projectPathPersisted = FdoFileHelper.GetPathWithoutRoot(settings.ProjectPath);
m_spellCheckAdditions = settings.IncludeSpellCheckAdditions;
m_dbVersion = settings.DbVersion;
m_fwVersion = settings.FwVersion;
- m_linkedFilesPathRelative = DirectoryFinderRelativePaths.GetLinkedFilesRelativePathFromFullPath(settings.LinkedFilesPath, settings.ProjectPath, settings.ProjectName);
+ m_linkedFilesPathRelative = LinkedFilesRelativePathHelper.GetLinkedFilesRelativePathFromFullPath(settings.ProjectsRootFolder, settings.LinkedFilesPath, settings.ProjectPath, settings.ProjectName);
m_linkedFilesPathActual = settings.LinkedFilesPath;
m_appAbbrev = settings.AppAbbrev;
}
@@ -224,8 +222,8 @@ public void Validate()
PopulateSettingsFromZipFileIfNeeded();
if (DbVersion > FDOBackendProvider.ModelVersion)
{
- throw new InvalidBackupFileException(ResourceHelper.FormatResourceString(
- "ksBackupFileCreatedByNewerFwVersion", m_sZipFileName, FwVersion));
+ throw new InvalidBackupFileException(string.Format(Strings.ksBackupFileCreatedByNewerFwVersion,
+ m_sZipFileName, FwVersion));
}
}
#endregion
@@ -321,7 +319,7 @@ public string LinkedFilesPathRelativePersisted
[DataMember]
public string AppAbbrev
{
- get { PopulateSettingsFromZipFileIfNeeded(); return m_appAbbrev ?? FwUtils.ksFlexAbbrev; }
+ get { PopulateSettingsFromZipFileIfNeeded(); return m_appAbbrev; }
private set { m_appAbbrev = value; }
}
@@ -391,7 +389,7 @@ private void PopulateSettingsFromZipFileIfNeeded()
return;
string extension = Path.GetExtension(m_sZipFileName).ToLowerInvariant();
- if (extension == FwFileExtensions.ksFw60BackupFileExtension)
+ if (extension == FdoFileHelper.ksFw60BackupFileExtension)
{
ProcessOldZipFile();
return;
@@ -417,32 +415,32 @@ private void PopulateSettingsFromZipFileIfNeeded()
if (String.IsNullOrEmpty(fileName))
continue;
- if (fileName.Equals(DirectoryFinder.kBackupSettingsFilename))
+ if (fileName.Equals(FdoFileHelper.kBackupSettingsFilename))
{
if (foundBackupSettingsFile)
throw new InvalidOperationException("Zip file " + m_sZipFileName + " contained multiple " +
- DirectoryFinder.kBackupSettingsFilename + " files.");
+ FdoFileHelper.kBackupSettingsFilename + " files.");
foundBackupSettingsFile = true;
InitializeFromStream(zipIn);
}
- else if (Path.GetExtension(fileName) == FwFileExtensions.ksFwDataXmlFileExtension)
+ else if (Path.GetExtension(fileName) == FdoFileHelper.ksFwDataXmlFileExtension)
{
if (dataFileName != null)
throw new InvalidOperationException("Zip file " + m_sZipFileName +
" contained multiple project data files.");
dataFileName = fileName;
}
- else if (!entry.Name.EndsWith("/") && entry.Name.Contains(DirectoryFinder.ksWritingSystemsDir + "/"))
+ else if (!entry.Name.EndsWith("/") && entry.Name.Contains(FdoFileHelper.ksWritingSystemsDir + "/"))
foundWritingSystemFiles = true;
}
if (!foundBackupSettingsFile)
throw new InvalidOperationException("Zip file " + m_sZipFileName + " did not contain the " +
- DirectoryFinder.kBackupSettingsFilename + " file.");
+ FdoFileHelper.kBackupSettingsFilename + " file.");
if (m_projectName == null)
- throw new InvalidOperationException(DirectoryFinder.kBackupSettingsFilename + " in " +
+ throw new InvalidOperationException(FdoFileHelper.kBackupSettingsFilename + " in " +
m_sZipFileName + " did not contain a project name.");
- string expectedProjectFile = DirectoryFinder.GetXmlDataFileName(m_projectName);
+ string expectedProjectFile = FdoFileHelper.GetXmlDataFileName(m_projectName);
if (dataFileName == null || dataFileName != expectedProjectFile)
throw new InvalidOperationException("Zip file " + m_sZipFileName + " did not contain the " +
expectedProjectFile + " file.");
@@ -539,9 +537,9 @@ private void InitializeFromStream(Stream persistenceStream)
m_backupTime = settings.BackupTime;
m_comment = settings.Comment;
m_projectName = settings.ProjectName;
- m_linkedFilesPathRelative = DirectoryFinderRelativePaths.FixPathSlashesIfNeeded(settings.LinkedFilesPathRelativePersisted);
- m_linkedFilesPathActual = DirectoryFinderRelativePaths.FixPathSlashesIfNeeded(settings.LinkedFilesPathActualPersisted);
- m_projectPathPersisted = DirectoryFinderRelativePaths.FixPathSlashesIfNeeded(settings.ProjectPathPersisted);
+ m_linkedFilesPathRelative = LinkedFilesRelativePathHelper.FixPathSlashesIfNeeded(settings.LinkedFilesPathRelativePersisted);
+ m_linkedFilesPathActual = LinkedFilesRelativePathHelper.FixPathSlashesIfNeeded(settings.LinkedFilesPathActualPersisted);
+ m_projectPathPersisted = LinkedFilesRelativePathHelper.FixPathSlashesIfNeeded(settings.ProjectPathPersisted);
m_configurationSettings = settings.IncludeConfigurationSettings;
m_linkedFiles = settings.IncludeLinkedFiles;
m_supportingFiles = settings.IncludeSupportingFiles;
@@ -570,7 +568,7 @@ public class InvalidBackupFileException : Exception
/// The inner exception
/// ------------------------------------------------------------------------------------
public InvalidBackupFileException(string zipFile, Exception inner) :
- base(ResourceHelper.GetResourceString("ksInvalidFwBackupFile") + Environment.NewLine + zipFile, inner)
+ base(Strings.ksInvalidFwBackupFile + Environment.NewLine + zipFile, inner)
{
}
diff --git a/Src/FDO/DomainServices/BackupRestore/BackupProjectSettings.cs b/Src/FDO/DomainServices/BackupRestore/BackupProjectSettings.cs
index 461764c8d5..4eb79e4532 100644
--- a/Src/FDO/DomainServices/BackupRestore/BackupProjectSettings.cs
+++ b/Src/FDO/DomainServices/BackupRestore/BackupProjectSettings.cs
@@ -7,11 +7,9 @@
using System;
using System.IO;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.FDO.Infrastructure;
+using SIL.CoreImpl;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
using System.Reflection;
-using SIL.FieldWorks.Resources;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices.BackupRestore
@@ -23,17 +21,19 @@ namespace SIL.FieldWorks.FDO.DomainServices.BackupRestore
public class BackupProjectSettings : BackupSettings
{
#region Constructors
+
/// ------------------------------------------------------------------------------------
///
/// Constructor
///
/// The cache.
/// The backup info.
+ /// The destination folder.
/// ------------------------------------------------------------------------------------
- public BackupProjectSettings(FdoCache cache, IBackupInfo backupInfo) :
+ public BackupProjectSettings(FdoCache cache, IBackupInfo backupInfo, string destFolder) :
this(Path.GetDirectoryName(cache.ProjectId.ProjectFolder), cache.ProjectId.Name,
cache.LanguageProject.LinkedFilesRootDir, cache.ProjectId.SharedProjectFolder,
- cache.ProjectId.Type)
+ cache.ProjectId.Type, destFolder)
{
if (backupInfo != null)
{
@@ -57,19 +57,20 @@ public BackupProjectSettings(FdoCache cache, IBackupInfo backupInfo) :
/// A possibly alternate project path that
/// should be used for things that should be shared.
/// Type of the project before converting for backup.
+ /// The destination folder.
/// ------------------------------------------------------------------------------------
protected BackupProjectSettings(string projectsRootFolder, string projectName,
- string linkedFilesPath, string sharedProjectFolder, FDOBackendProviderType originalProjType) :
+ string linkedFilesPath, string sharedProjectFolder, FDOBackendProviderType originalProjType, string destFolder) :
base(projectsRootFolder, linkedFilesPath, sharedProjectFolder)
{
ProjectName = projectName;
DbVersion = FDOBackendProvider.ModelVersion;
- FwVersion = new FwVersionInfoProvider(Assembly.GetExecutingAssembly(), false).FieldWorksVersion;
+ FwVersion = new VersionInfoProvider(Assembly.GetExecutingAssembly(), false).MajorVersion;
// For DB4o projects, we need to convert them over to XML. We can't put the
// converted project in the same directory so we convert them to a temporary
// directory (see FWR-2813).
- DatabaseFolder = (originalProjType == FDOBackendProviderType.kXML) ? ProjectPath : Path.GetTempPath();
- DestinationFolder = DirectoryFinder.DefaultBackupDirectory;
+ DatabaseFolder = (originalProjType == FDOBackendProviderType.kXML || originalProjType == FDOBackendProviderType.kSharedXML) ? ProjectPath : Path.GetTempPath();
+ DestinationFolder = destFolder;
BackupTime = DateTime.Now;
}
#endregion
@@ -149,7 +150,7 @@ public string AdjustedComment
private string MakeBackupFileName(string comment)
{
return ProjectName + " " + BackupTime.ToString(ksBackupDateFormat) +
- comment + FwFileExtensions.ksFwBackupFileExtension;
+ comment + FdoFileHelper.ksFwBackupFileExtension;
}
/// ------------------------------------------------------------------------------------
@@ -161,8 +162,8 @@ public string BackupSettingsFile
{
get
{
- return Path.Combine(DirectoryFinder.GetBackupSettingsDir(ProjectPath),
- DirectoryFinder.kBackupSettingsFilename);
+ return Path.Combine(FdoFileHelper.GetBackupSettingsDir(ProjectPath),
+ FdoFileHelper.kBackupSettingsFilename);
}
}
#endregion
diff --git a/Src/FDO/DomainServices/BackupRestore/BackupSettings.cs b/Src/FDO/DomainServices/BackupRestore/BackupSettings.cs
index 77f0073ba9..e7324e4c6f 100644
--- a/Src/FDO/DomainServices/BackupRestore/BackupSettings.cs
+++ b/Src/FDO/DomainServices/BackupRestore/BackupSettings.cs
@@ -8,7 +8,6 @@
using System;
using System.IO;
using SIL.Utils;
-using SIL.FieldWorks.Common.FwUtils;
namespace SIL.FieldWorks.FDO.DomainServices.BackupRestore
{
@@ -82,7 +81,7 @@ protected BackupSettings(string projectsRootFolder, string linkedFilesPath,
/// ------------------------------------------------------------------------------------
public string DbFilename
{
- get { return DirectoryFinder.GetXmlDataFileName(ProjectName); }
+ get { return FdoFileHelper.GetXmlDataFileName(ProjectName); }
}
#region IBackupSettings implementation
@@ -152,6 +151,15 @@ public bool IncludeSpellCheckAdditions
#endregion
#region Paths
+
+ ///
+ /// Gets the projects root folder.
+ ///
+ public string ProjectsRootFolder
+ {
+ get { return m_projectsRootFolder; }
+ }
+
///
/// This is the path of the project being (or about to be) backed up or restored.
///
@@ -175,7 +183,7 @@ public string QuestionNotesFilename
///
public string FlexConfigurationSettingsPath
{
- get { return DirectoryFinder.GetConfigSettingsDir(ProjectPath); }
+ get { return FdoFileHelper.GetConfigSettingsDir(ProjectPath); }
}
///
@@ -188,7 +196,7 @@ public string LinkedFilesPath
if (String.IsNullOrEmpty(m_linkedFilesPath))
{
return Path.Combine(!string.IsNullOrEmpty(m_sharedProjectFolder) ?
- m_sharedProjectFolder : ProjectPath, DirectoryFinder.ksLinkedFilesDir);
+ m_sharedProjectFolder : ProjectPath, FdoFileHelper.ksLinkedFilesDir);
}
return m_linkedFilesPath;
}
@@ -203,7 +211,7 @@ public string LinkedFilesPath
///
public string PicturesPath
{
- get { return DirectoryFinder.GetPicturesDir(LinkedFilesPath); }
+ get { return FdoFileHelper.GetPicturesDir(LinkedFilesPath); }
}
///
@@ -211,7 +219,7 @@ public string PicturesPath
///
public string MediaPath
{
- get { return DirectoryFinder.GetMediaDir(LinkedFilesPath); }
+ get { return FdoFileHelper.GetMediaDir(LinkedFilesPath); }
}
///
@@ -219,7 +227,7 @@ public string MediaPath
///
public string OtherExternalFilesPath
{
- get { return DirectoryFinder.GetOtherExternalFilesDir(LinkedFilesPath); }
+ get { return FdoFileHelper.GetOtherExternalFilesDir(LinkedFilesPath); }
}
///
@@ -229,7 +237,7 @@ public string WritingSystemStorePath
{
get
{
- return DirectoryFinder.GetWritingSystemDir(
+ return FdoFileHelper.GetWritingSystemDir(
string.IsNullOrEmpty(m_sharedProjectFolder) ? ProjectPath : m_sharedProjectFolder);
}
}
@@ -248,7 +256,7 @@ public string SpellingDictionariesPath
///
public string ProjectSupportingFilesPath
{
- get { return DirectoryFinder.GetSupportingFilesDir(ProjectPath); }
+ get { return FdoFileHelper.GetSupportingFilesDir(ProjectPath); }
}
#endregion
}
diff --git a/Src/FDO/DomainServices/BackupRestore/FilesToRestoreAreOlder.resx b/Src/FDO/DomainServices/BackupRestore/FilesToRestoreAreOlder.resx
deleted file mode 100644
index f5ddc71d23..0000000000
--- a/Src/FDO/DomainServices/BackupRestore/FilesToRestoreAreOlder.resx
+++ /dev/null
@@ -1,351 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- text/microsoft-resx
-
-
- 2.0
-
-
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
-
- 60, 12
-
-
- 488, 52
-
-
-
- 3
-
-
- Some files in the Linked Files folder are newer than the ones which will be restored, and these may not be files that this FieldWorks project links to yet.
-
-
- label_message
-
-
- System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- $this
-
-
- 7
-
-
- 60, 64
-
-
- 488, 41
-
-
- 4
-
-
- Would you like to keep the newer files in the folder or replace them with the older ones from the backup?
-
-
- label_Question
-
-
- System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- $this
-
-
- 6
-
-
- 12, 12
-
-
- 42, 38
-
-
- 5
-
-
- pictureBox1
-
-
- System.Windows.Forms.PictureBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- $this
-
-
- 5
-
-
- True
-
-
-
- NoControl
-
-
- 64, 132
-
-
- 192, 17
-
-
- 13
-
-
- Use the older files from the backup.
-
-
- radio_Overwrite
-
-
- System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- $this
-
-
- 0
-
-
- True
-
-
- NoControl
-
-
- 64, 109
-
-
- 164, 17
-
-
- 12
-
-
- Keep newer files in the folder.
-
-
- radio_Keep
-
-
- System.Windows.Forms.RadioButton, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- $this
-
-
- 1
-
-
- NoControl
-
-
- 474, 157
-
-
- 75, 23
-
-
- 11
-
-
- Help
-
-
- button_Help
-
-
- System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- $this
-
-
- 2
-
-
- NoControl
-
-
- 393, 157
-
-
- 75, 23
-
-
- 10
-
-
- Cancel
-
-
- button_Cancel
-
-
- System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- $this
-
-
- 3
-
-
- NoControl
-
-
- 312, 157
-
-
- 75, 23
-
-
- 9
-
-
- OK
-
-
- button_OK
-
-
- System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- $this
-
-
- 4
-
-
- True
-
-
- 6, 13
-
-
- 561, 192
-
-
- Linked files in backup are older
-
-
- FilesToRestoreAreOlder
-
-
- System.Windows.Forms.Form, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
\ No newline at end of file
diff --git a/Src/FDO/DomainServices/BackupRestore/ProjectBackupService.cs b/Src/FDO/DomainServices/BackupRestore/ProjectBackupService.cs
index 11282c89f2..2f83126a04 100644
--- a/Src/FDO/DomainServices/BackupRestore/ProjectBackupService.cs
+++ b/Src/FDO/DomainServices/BackupRestore/ProjectBackupService.cs
@@ -9,10 +9,8 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
-using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
using SIL.CoreImpl;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.Utils;
@@ -25,7 +23,7 @@ public class ProjectBackupService
{
private readonly FdoCache m_cache;
private readonly BackupProjectSettings m_settings;
- List m_failedFiles = new List();
+ private readonly List m_failedFiles = new List();
///
/// Constructor
@@ -36,15 +34,26 @@ public ProjectBackupService(FdoCache cache, BackupProjectSettings settings)
m_settings = settings;
}
+ ///
+ /// Gets the failed files.
+ ///
+ ///
+ /// The failed files.
+ ///
+ public IEnumerable FailedFiles
+ {
+ get { return m_failedFiles; }
+ }
+
///
/// Perform a backup of the current project, using specified settings.
///
/// The backup file or null if something went wrong.
- public string BackupProject(IThreadedProgress progressDlg)
+ public bool BackupProject(IThreadedProgress progressDlg, out string backupFile)
{
PersistBackupFileSettings();
- string backupFile = null;
+ backupFile = null;
try
{
// Make sure any changes we want backup are saved.
@@ -55,23 +64,14 @@ public string BackupProject(IThreadedProgress progressDlg)
var filesToZip = CreateListOfFilesToZip();
progressDlg.Title = Strings.ksBackupProgressCaption;
- progressDlg.ProgressBarStyle = ProgressBarStyle.Marquee;
+ progressDlg.IsIndeterminate = true;
progressDlg.AllowCancel = false;
m_failedFiles.Clear(); // I think it's always a new instance, but play safe.
backupFile = (string)progressDlg.RunTask(true, BackupTask, filesToZip);
- if (m_failedFiles.Count > 0)
- {
- var msg = string.Format(Strings.ksCouldNotBackupSomeFiles, m_failedFiles.ToString(", ", Path.GetFileName));
- if (MessageBox.Show(progressDlg.Form, msg, Strings.ksWarning, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) !=
- DialogResult.Yes)
- {
- File.Delete(backupFile);
- }
- }
if (tempFilePath != null)
File.Delete(tempFilePath); // don't leave the extra fwdata file around to confuse things.
}
- catch(Exception e)
+ catch (Exception e)
{
// Something went catastrophically wrong. Don't leave a junk backup around.
if (backupFile != null)
@@ -80,7 +80,8 @@ public string BackupProject(IThreadedProgress progressDlg)
throw e.InnerException;
throw new ContinuableErrorException("Backup did not succeed. Code is needed to handle this case.", e);
}
- return backupFile;
+
+ return m_failedFiles.Count == 0;
}
/// ------------------------------------------------------------------------------------
@@ -90,8 +91,8 @@ public string BackupProject(IThreadedProgress progressDlg)
/// ------------------------------------------------------------------------------------
private void PersistBackupFileSettings()
{
- string backupSettingsFile = Path.Combine(DirectoryFinder.GetBackupSettingsDir(
- m_settings.ProjectPath), DirectoryFinder.kBackupSettingsFilename);
+ string backupSettingsFile = Path.Combine(FdoFileHelper.GetBackupSettingsDir(
+ m_settings.ProjectPath), FdoFileHelper.kBackupSettingsFilename);
string settingsDir = Path.GetDirectoryName(backupSettingsFile);
if (!Directory.Exists(settingsDir))
diff --git a/Src/FDO/DomainServices/BackupRestore/ProjectRestoreService.cs b/Src/FDO/DomainServices/BackupRestore/ProjectRestoreService.cs
index eaea295ee0..3c5bf4bd6b 100644
--- a/Src/FDO/DomainServices/BackupRestore/ProjectRestoreService.cs
+++ b/Src/FDO/DomainServices/BackupRestore/ProjectRestoreService.cs
@@ -11,14 +11,10 @@
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
-using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.FDO.Application.ApplicationServices;
+using SIL.CoreImpl;
using SIL.Utils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
-using XCore;
-using SIL.FieldWorks.Resources;
namespace SIL.FieldWorks.FDO.DomainServices.BackupRestore
{
@@ -31,8 +27,10 @@ public class ProjectRestoreService
private readonly RestoreProjectSettings m_restoreSettings;
private String m_tempBackupFolder;
private bool m_fRestoreOverProject;
- private readonly IHelpTopicProvider m_helpTopicProvider;
private string m_sLinkDirChangedTo;
+ private readonly IFdoUI m_ui;
+ private readonly string m_converterConsolePath;
+ private readonly string m_dbPath;
#endregion
#region Constructor
@@ -41,27 +39,22 @@ public class ProjectRestoreService
/// Constructor
///
/// The restore settings.
- ///
+ /// The UI service.
+ ///
+ ///
/// ------------------------------------------------------------------------------------
- public ProjectRestoreService(RestoreProjectSettings settings, IHelpTopicProvider helpTopicProvider)
+ public ProjectRestoreService(RestoreProjectSettings settings, IFdoUI ui, string converterConsolePath, string dbPath)
{
m_restoreSettings = settings;
- m_helpTopicProvider = helpTopicProvider;
+ m_ui = ui;
+ m_converterConsolePath = converterConsolePath;
+ m_dbPath = dbPath;
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Constructor used in Tests where we do not need to have a helpTopicProvider.
- ///
- /// The restore settings.
- /// ------------------------------------------------------------------------------------
- public ProjectRestoreService(RestoreProjectSettings settings)
- {
- m_restoreSettings = settings;
- }
#endregion
#region Public methods
+
/// ------------------------------------------------------------------------------------
///
/// Perform a restore of the project specified in the settings.
@@ -96,30 +89,25 @@ public void RestoreProject(IThreadedProgress progressDlg)
try
{
- //Import from FW version 6.0 based on the file extension.
- var extension = Path.GetExtension(fileSettings.File).ToLowerInvariant();
- if (extension == FwFileExtensions.ksFw60BackupFileExtension || extension == ".xml")
- ImportFrom6_0Backup(fileSettings, progressDlg);
- else //Restore from FW version 7.0 and newer backup.
- RestoreFrom7_0AndNewerBackup(fileSettings);
+ //Import from FW version 6.0 based on the file extension.
+ var extension = Path.GetExtension(fileSettings.File).ToLowerInvariant();
+ if (extension == FdoFileHelper.ksFw60BackupFileExtension || extension == ".xml")
+ ImportFrom6_0Backup(fileSettings, progressDlg);
+ else //Restore from FW version 7.0 and newer backup.
+ RestoreFrom7_0AndNewerBackup(fileSettings);
}
- catch(Exception error)
+ catch (Exception error)
{
if (error is IOException || error is InvalidBackupFileException ||
error is UnauthorizedAccessException)
{
CleanupAfterRestore(false);
- // ENHANCE: If/when we have the restore process using a progress dialog so that this code
- // runs in the progress dialog thread instead of the main thread, all message boxes should
- // be replaced with the ThreadHelper.ShowMessageBox() method so that they will be thread-safe.
- MessageBoxUtils.Show(null, error.Message, AppStrings.ksRestoreDidNotSucceed,
- MessageBoxButtons.OK, MessageBoxIcon.Information);
}
throw;
}
// switch to the desired backend (if it's in the projects directory...anything else stays XML for now).
- if (DirectoryFinder.IsSubFolderOfProjectsDirectory(m_restoreSettings.ProjectPath) && !suppressConversion)
+ if (Path.GetDirectoryName(m_restoreSettings.ProjectPath) == m_restoreSettings.ProjectsRootFolder && !suppressConversion)
ClientServerServices.Current.Local.ConvertToDb4oBackendIfNeeded(progressDlg, m_restoreSettings.FullProjectPath);
CleanupAfterRestore(true);
@@ -127,27 +115,42 @@ public void RestoreProject(IThreadedProgress progressDlg)
private void ImportFrom6_0Backup(BackupFileSettings fileSettings, IThreadedProgress progressDlg)
{
- ImportFrom6_0 importer = new ImportFrom6_0(progressDlg);
- string projFile;
- if (!importer.Import(fileSettings.File, m_restoreSettings.ProjectName, out projFile))
+ var importer = new ImportFrom6_0(progressDlg, m_converterConsolePath, m_dbPath);
+ bool importSuccessful;
+ try
{
- ExceptionHelper.LogAndIgnoreErrors(() => CleanupFrom6_0FailedRestore(importer));
- ExceptionHelper.LogAndIgnoreErrors(() => CleanupAfterRestore(false));
+ string projFile;
+ importSuccessful = importer.Import(fileSettings.File, m_restoreSettings.ProjectName, m_restoreSettings.ProjectsRootFolder, out projFile);
+ }
+ catch (CannotConvertException e)
+ {
+ FailedImportCleanUp(importer);
+ throw;
+ }
+ if (!importSuccessful)
+ {
+ FailedImportCleanUp(importer);
+
if (!importer.HaveOldFieldWorks || !importer.HaveFwSqlServer)
{
throw new MissingOldFwException("Error restoring from FieldWorks 6.0 (or earlier) backup",
importer.HaveFwSqlServer, importer.HaveOldFieldWorks);
}
- MessageBoxUtils.Show(Strings.ksRestoringOldFwBackupFailed, Strings.ksFailed);
throw new FailedFwRestoreException("Error restoring from FieldWorks 6.0 (or earlier) backup");
}
}
+ private void FailedImportCleanUp(ImportFrom6_0 importer)
+ {
+ ExceptionHelper.LogAndIgnoreErrors(() => CleanupFrom6_0FailedRestore(importer));
+ ExceptionHelper.LogAndIgnoreErrors(() => CleanupAfterRestore(false));
+ }
+
private void RestoreFrom7_0AndNewerBackup(BackupFileSettings fileSettings)
{
// Get rid of any saved settings, since they may not be consistent with something about the data
// or settings we are restoring. (This extension is also known to RecordView.GetClerkPersistPathname()).
- var tempDirectory = Path.Combine(m_restoreSettings.ProjectPath, DirectoryFinder.ksSortSequenceTempDir);
+ var tempDirectory = Path.Combine(m_restoreSettings.ProjectPath, FdoFileHelper.ksSortSequenceTempDir);
if (Directory.Exists(tempDirectory))
{
foreach (var sortSeqFile in Directory.GetFiles(tempDirectory, "*.fwss"))
@@ -157,19 +160,19 @@ private void RestoreFrom7_0AndNewerBackup(BackupFileSettings fileSettings)
UncompressDataFiles();
// We can't use Path.Combine here, because the zip files stores all file paths with '/'s
- UncompressFilesMatchingPath(DirectoryFinder.ksWritingSystemsDir + "/", m_restoreSettings.WritingSystemStorePath);
+ UncompressFilesMatchingPath(FdoFileHelper.ksWritingSystemsDir + "/", m_restoreSettings.WritingSystemStorePath);
if (m_restoreSettings.IncludeSupportingFiles)
{
Debug.Assert(fileSettings.IncludeSupportingFiles,
"The option to include supporting files should not be allowed if they aren't available in the backup settings");
- var zipEntryStartsWith = DirectoryFinder.ksSupportingFilesDir;
- UncompressFilesContainedInFolderandSubFolders(DirectoryFinder.GetZipfileFormattedPath(zipEntryStartsWith),
+ var zipEntryStartsWith = FdoFileHelper.ksSupportingFilesDir;
+ UncompressFilesContainedInFolderandSubFolders(FdoFileHelper.GetZipfileFormattedPath(zipEntryStartsWith),
m_restoreSettings.ProjectSupportingFilesPath);
}
if (m_restoreSettings.IncludeConfigurationSettings)
- UncompressFilesMatchingPath(DirectoryFinder.ksConfigurationSettingsDir + "/", m_restoreSettings.FlexConfigurationSettingsPath);
+ UncompressFilesMatchingPath(FdoFileHelper.ksConfigurationSettingsDir + "/", m_restoreSettings.FlexConfigurationSettingsPath);
if (m_restoreSettings.IncludeLinkedFiles)
RestoreLinkedFiles(fileSettings);
@@ -202,7 +205,7 @@ private void CleanupFrom6_0FailedRestore(ImportFrom6_0 importer)
var fileName = Path.GetFileName(entry.Name);
if (!String.IsNullOrEmpty(fileName))
{
- string filePath = Path.Combine(DirectoryFinder.ProjectsDirectory, fileName);
+ string filePath = Path.Combine(m_restoreSettings.ProjectsRootFolder, fileName);
if (FileUtils.TrySimilarFileExists(filePath, out filePath))
FileUtils.Delete(filePath);
}
@@ -245,44 +248,6 @@ private void CleanupAfterRestore(bool succeeded)
#endregion
- /// ------------------------------------------------------------------------------------
- ///
- /// Performs the requested actions and handles any IO or zip error by reporting them to
- /// the user. (Intended for operations that deal directly with a backup zip file.
- ///
- /// The parent window to use when reporting an error (can be
- /// null).
- /// Used in title bar of message box when reporting an error
- /// (typically the name of the application).
- ///
- /// The backup zip filename.
- /// The action to perform.
- ///
- /// true if successful (no exception caught); false otherwise
- ///
- /// ------------------------------------------------------------------------------------
- public static bool HandleRestoreFileErrors(IWin32Window parentWindow, string caption,
- string zipFilename, Action action)
- {
- try
- {
- action();
- }
- catch (Exception error)
- {
- if (error is IOException || error is InvalidBackupFileException ||
- error is UnauthorizedAccessException)
- {
- Logger.WriteError(error);
- MessageBoxUtils.Show(parentWindow, error.Message, caption,
- MessageBoxButtons.OK, MessageBoxIcon.Information);
- return false;
- }
- throw;
- }
- return true;
- }
-
#region Private methods
/// ------------------------------------------------------------------------------------
///
@@ -310,7 +275,7 @@ private void UncompressDataFiles()
while ((entry = zipIn.GetNextEntry()) != null)
{
var fileName = Path.GetFileName(entry.Name);
- if (fileName == DirectoryFinder.GetXmlDataFileName(m_restoreSettings.Backup.ProjectName))
+ if (fileName == FdoFileHelper.GetXmlDataFileName(m_restoreSettings.Backup.ProjectName))
UnzipFileToRestoreFolder(zipIn, m_restoreSettings.DbFilename, entry.Size,
m_restoreSettings.ProjectPath, entry.DateTime);
if (fileName == m_restoreSettings.QuestionNotesFilename)
@@ -318,7 +283,7 @@ private void UncompressDataFiles()
m_restoreSettings.ProjectPath, entry.DateTime);
}
string bakFile = Path.Combine(m_restoreSettings.ProjectPath, m_restoreSettings.ProjectName)
- + FwFileExtensions.ksFwDataFallbackFileExtension;
+ + FdoFileHelper.ksFwDataFallbackFileExtension;
if (FileUtils.TrySimilarFileExists(bakFile, out bakFile))
{
FileUtils.Delete(bakFile); // TODO: do something about the .Lock file.......
@@ -332,22 +297,22 @@ private void RestoreLinkedFiles(BackupFileSettings fileSettings)
"The option to include linked files should not be allowed if they aren't available in the backup settings");
var proposedDestinationLinkedFilesPath =
- DirectoryFinderRelativePaths.GetLinkedFilesFullPathFromRelativePath(
+ LinkedFilesRelativePathHelper.GetLinkedFilesFullPathFromRelativePath(m_restoreSettings.ProjectsRootFolder,
fileSettings.LinkedFilesPathRelativePersisted, m_restoreSettings.ProjectPath);
var linkedFilesPathInZip = fileSettings.LinkedFilesPathActualPersisted;
- if (fileSettings.LinkedFilesPathRelativePersisted.StartsWith(DirectoryFinderRelativePaths.ksProjectRelPath))
+ if (fileSettings.LinkedFilesPathRelativePersisted.StartsWith(LinkedFilesRelativePathHelper.ksProjectRelPath))
{
// We store any files inside the project folder as a relative path from the project's directory.
// Make sure we don't attempt to search for the whole directory structure in the zip file. (FWR-2909)
linkedFilesPathInZip = fileSettings.LinkedFilesPathRelativePersisted.Substring(
- DirectoryFinderRelativePaths.ksProjectRelPath.Length + 1);
+ LinkedFilesRelativePathHelper.ksProjectRelPath.Length + 1);
}
var filesContainedInLinkdFilesFolder = GetAllFilesUnderFolderInZipFileAndDateTimes(linkedFilesPathInZip);
//If the proposed location is not in the default location under the project, then ask the user if they want
//to restore the files to the default location instead. Otherwise just go ahead and restore the files.
- var defaultLinkedFilesPath = DirectoryFinder.GetDefaultLinkedFilesDir(m_restoreSettings.ProjectPath);
+ var defaultLinkedFilesPath = FdoFileHelper.GetDefaultLinkedFilesDir(m_restoreSettings.ProjectPath);
if (proposedDestinationLinkedFilesPath.Equals(defaultLinkedFilesPath))
{
if (!Directory.Exists(defaultLinkedFilesPath))
@@ -370,11 +335,7 @@ private void RestoreLinkedFiles(BackupFileSettings fileSettings)
/// Protected so we can subclass in tests.
protected virtual bool CanRestoreLinkedFilesToProjectsFolder()
{
- using (var dlg = new RestoreLinkedFilesToProjectsFolder(m_helpTopicProvider))
- {
- // Let a Cancel result mean "Keep my old non-standard location"
- return dlg.ShowDialog() == DialogResult.OK && dlg.fRestoreLinkedFilesToProjectFolder;
- }
+ return m_ui.RestoreLinkedFilesInProjectFolder();
}
///
@@ -390,7 +351,7 @@ protected void RestoreLinkedFiles(bool fPutFilesInProject, Dictionary
protected virtual void CouldNotRestoreLinkedFilesToOriginalLocation(string linkedFilesPathPersisted, Dictionary filesContainedInLinkdFilesFolder)
{
- using (var dlgCantWriteFiles = new CantRestoreLinkedFilesToOriginalLocation(m_helpTopicProvider))
+ YesNoCancel userSelection = m_ui.CannotRestoreLinkedFilesToOriginalLocation();
+ if (userSelection == YesNoCancel.OkYes)
{
- if (dlgCantWriteFiles.ShowDialog() == DialogResult.OK)
- {
- if (dlgCantWriteFiles.fRestoreLinkedFilesToProjectFolder)
- {
- m_sLinkDirChangedTo = DirectoryFinder.GetDefaultLinkedFilesDir(m_restoreSettings.ProjectPath);
- //Restore the files to the project folder.
- UncompressLinkedFiles(filesContainedInLinkdFilesFolder, m_sLinkDirChangedTo, linkedFilesPathPersisted);
- }
- if (dlgCantWriteFiles.fDoNotRestoreLinkedFiles)
- {
- //Do nothing. Do not restore any LinkedFiles.
- }
- }
+ m_sLinkDirChangedTo = FdoFileHelper.GetDefaultLinkedFilesDir(m_restoreSettings.ProjectPath);
+ //Restore the files to the project folder.
+ UncompressLinkedFiles(filesContainedInLinkdFilesFolder, m_sLinkDirChangedTo, linkedFilesPathPersisted);
+ }
+ else if (userSelection == YesNoCancel.OkNo)
+ {
+ //Do nothing. Do not restore any LinkedFiles.
}
}
private Dictionary GetAllFilesUnderFolderInZipFileAndDateTimes(string dir)
{
var filesAndDateTime = new Dictionary();
- var dirZipFileFormat = DirectoryFinder.GetZipfileFormattedPath(dir);
+ var dirZipFileFormat = FdoFileHelper.GetZipfileFormattedPath(dir);
using (var zipIn = OpenFWBackupZipfile())
{
ZipEntry entry;
@@ -586,14 +537,14 @@ private void UncompressLinkedFiles(Dictionary fileList, String
Debug.Assert(!String.IsNullOrEmpty(fileName));
//Contruct the path where the file will be unzipped too.
- var zipFileLinkFilesPath = DirectoryFinder.GetZipfileFormattedPath(linkedFilesPathPersisted);
+ var zipFileLinkFilesPath = FdoFileHelper.GetZipfileFormattedPath(linkedFilesPathPersisted);
var filenameWithSubFolders = entry.Name.Substring(zipFileLinkFilesPath.Length);
String pathForFileSubFolders = "";
if (!fileName.Equals(filenameWithSubFolders)) //if they are equal the file is in the root of LinkedFiles
{
pathForFileSubFolders = GetPathForSubFolders(filenameWithSubFolders, fileName.Length);
}
- var destFolderZipFileFormat = DirectoryFinder.GetZipfileFormattedPath(destinationLinkedFilesPath);
+ var destFolderZipFileFormat = FdoFileHelper.GetZipfileFormattedPath(destinationLinkedFilesPath);
var pathRoot = Path.GetPathRoot(destinationLinkedFilesPath);
Debug.Assert(!String.IsNullOrEmpty(pathRoot));
var pathforfileunzip = Path.Combine(pathRoot, destFolderZipFileFormat, pathForFileSubFolders);
@@ -697,7 +648,7 @@ private void UnzipFileToRestoreFolder(ZipInputStream zipIn, string fileName,
{
Debug.WriteLine("Failed to create directory {0}; {1}", dir, e.Message);
var msg = string.Format(Strings.ksCannotRestoreLinkedFilesToDir, dir);
- MessageBoxUtils.Show(msg, Strings.ksCannotRestore);
+ m_ui.DisplayMessage(MessageType.Warning, msg, Strings.ksCannotRestore, null);
return;
}
if (FileUtils.TrySimilarFileExists(newFileName, out newFileName))
@@ -737,7 +688,7 @@ private void UnzipFileToRestoreFolder(ZipInputStream zipIn, string fileName,
{
Debug.WriteLine("Failed to restore file {0}; {1}", newFileName, e.Message);
var msg = string.Format(Strings.ksCannotRestoreBackup, newFileName);
- MessageBoxUtils.Show(msg, Strings.ksCannotRestore);
+ m_ui.DisplayMessage(MessageType.Warning, msg, Strings.ksCannotRestore, null);
return;
}
}
diff --git a/Src/FDO/DomainServices/BackupRestore/RestoreProjectSettings.cs b/Src/FDO/DomainServices/BackupRestore/RestoreProjectSettings.cs
index f7078bc2b7..66455f8be6 100644
--- a/Src/FDO/DomainServices/BackupRestore/RestoreProjectSettings.cs
+++ b/Src/FDO/DomainServices/BackupRestore/RestoreProjectSettings.cs
@@ -8,7 +8,6 @@
using System;
using System.IO;
using System.Linq;
-using SIL.FieldWorks.Common.FwUtils;
using System.Text;
using SIL.Utils;
@@ -32,7 +31,7 @@ public class RestoreProjectSettings : BackupSettings
/// Initializes a new instance of the class.
///
/// ------------------------------------------------------------------------------------
- public RestoreProjectSettings() : base (DirectoryFinder.ProjectsDirectory, null, null)
+ public RestoreProjectSettings(string projectsRootFolder) : base (projectsRootFolder, null, null)
{
}
@@ -42,12 +41,13 @@ public RestoreProjectSettings() : base (DirectoryFinder.ProjectsDirectory, null,
/// a list of command-line options as created from the
/// property.
///
- /// The command line options.
- /// Name of the backup zip file.
+ ///
/// Name of the project.
+ /// Name of the backup zip file.
+ /// The command line options.
/// ------------------------------------------------------------------------------------
- public RestoreProjectSettings(string projectName, string backupZipFileName,
- string commandLineOptions) : this()
+ public RestoreProjectSettings(string projectsRootFolder, string projectName, string backupZipFileName,
+ string commandLineOptions) : this(projectsRootFolder)
{
if (string.IsNullOrEmpty(projectName))
throw new ArgumentNullException("projectName");
@@ -149,7 +149,7 @@ public bool UsingSendReceive
{
get
{
- var otherRepoPath = Path.Combine(ProjectPath, FLExBridgeHelper.OtherRepositories);
+ var otherRepoPath = Path.Combine(ProjectPath, FdoFileHelper.OtherRepositories);
return Directory.Exists(Path.Combine(ProjectPath, ".hg")) ||
(Directory.Exists(otherRepoPath) &&
Directory.EnumerateDirectories(otherRepoPath).Any(dir => Directory.Exists(Path.Combine(dir, ".hg"))));
diff --git a/Src/FDO/DomainServices/BaseStyleInfo.cs b/Src/FDO/DomainServices/BaseStyleInfo.cs
index 5d303c8eaf..2fe5239ba2 100644
--- a/Src/FDO/DomainServices/BaseStyleInfo.cs
+++ b/Src/FDO/DomainServices/BaseStyleInfo.cs
@@ -39,7 +39,7 @@ public class InheritableStyleProp : IStyleProp
#region Constructors
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the
+ /// Initializes a new instance of the
/// class for an inherited property (value not set).
///
/// ------------------------------------------------------------------------------------
@@ -66,7 +66,7 @@ public InheritableStyleProp(InheritableStyleProp copyFrom)
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the
+ /// Initializes a new instance of the
/// class for a non-inherited (explicit) property.
///
/// The (explict) value of the property.
@@ -392,7 +392,7 @@ public struct BorderThicknesses
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The thickness of leading border in millipoints
/// The thickness of trailing border in millipoints
@@ -458,7 +458,7 @@ public struct LineHeightInfo
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The line spacing.
/// if set to true line spacing will be
@@ -496,7 +496,7 @@ public class IntPropInfo
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// ------------------------------------------------------------------------------------
public IntPropInfo()
@@ -505,7 +505,7 @@ public IntPropInfo()
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// ------------------------------------------------------------------------------------
public IntPropInfo(int textPropType, int value)
@@ -515,7 +515,7 @@ public IntPropInfo(int textPropType, int value)
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// ------------------------------------------------------------------------------------
public IntPropInfo(int textPropType, int value, int variant)
@@ -670,7 +670,7 @@ public class BaseStyleInfo : IStyle
#region Constructors
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// ------------------------------------------------------------------------------------
public BaseStyleInfo()
@@ -681,7 +681,7 @@ public BaseStyleInfo()
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class from a copy.
+ /// Initializes a new instance of the class from a copy.
/// This constructor is used to make a new copy of a style with a different name.
///
/// The copy from.
@@ -747,7 +747,7 @@ public BaseStyleInfo(BaseStyleInfo copyFrom, string newName)
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class based on a FW
+ /// Initializes a new instance of the class based on a FW
/// style. It will load style overrides for forceStyleInfo even if it is not in any
/// current list.
///
@@ -763,7 +763,7 @@ public BaseStyleInfo(IStStyle style, IWritingSystem forceStyleInfo)
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class based on a FW
+ /// Initializes a new instance of the class based on a FW
/// style.
///
/// ------------------------------------------------------------------------------------
@@ -785,7 +785,7 @@ public BaseStyleInfo(IStStyle style, ITsTextProps props)
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The cache.
/// This constructor is used to create a new style.
diff --git a/Src/FDO/DomainServices/BootstrapNewLanguageProject.cs b/Src/FDO/DomainServices/BootstrapNewLanguageProject.cs
index 4ebff7aead..4fd2a4454a 100644
--- a/Src/FDO/DomainServices/BootstrapNewLanguageProject.cs
+++ b/Src/FDO/DomainServices/BootstrapNewLanguageProject.cs
@@ -1,16 +1,10 @@
using System;
-using System.Collections.Generic;
using System.Diagnostics;
-using System.IO;
-using System.Net;
-using System.Text;
-using System.Windows.Forms;
using Microsoft.Practices.ServiceLocation;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.DomainImpl;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.CoreImpl;
-using SIL.FieldWorks.FDO.Infrastructure.Impl;
namespace SIL.FieldWorks.FDO.DomainServices
{
diff --git a/Src/FDO/DomainServices/ClientServerServices.cs b/Src/FDO/DomainServices/ClientServerServices.cs
index 74208c5b9d..e8ff5a5297 100644
--- a/Src/FDO/DomainServices/ClientServerServices.cs
+++ b/Src/FDO/DomainServices/ClientServerServices.cs
@@ -15,12 +15,9 @@
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
-using System.Windows.Forms;
using FwRemoteDatabaseConnector;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
-using SIL.FieldWorks.Resources;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices
@@ -42,27 +39,18 @@ public static class ClientServerServices
/// ------------------------------------------------------------------------------------
public static IClientServerServices Current { get; internal set; }
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes the class.
- ///
- /// ------------------------------------------------------------------------------------
- static ClientServerServices()
- {
- SetCurrentToDefaultBackend();
- }
-
/// ------------------------------------------------------------------------------------
///
/// This is the implementation for the static constructor. It is in a separate method
/// to allow tests to reset it (using reflection).
///
/// ------------------------------------------------------------------------------------
- private static void SetCurrentToDefaultBackend()
+ public static void SetCurrentToDb4OBackend(IFdoUI ui, IFdoDirectories dirs,
+ Func usingDefaultProjectsDirAccessor)
{
// This is the "one line" that should need to be changed to configure a different backend :-).
// Typically a new implementation of IClientServerServices will be needed, as well as the backend itself.
- Current = new Db4OClientServerServices();
+ Current = new Db4OClientServerServices(ui, dirs, usingDefaultProjectsDirAccessor);
}
/// ------------------------------------------------------------------------------------
@@ -74,8 +62,8 @@ public static string GetExtension(this FDOBackendProviderType type)
{
switch (type)
{
- case FDOBackendProviderType.kDb4oClientServer: return FwFileExtensions.ksFwDataDb4oFileExtension;
- case FDOBackendProviderType.kXML: return FwFileExtensions.ksFwDataXmlFileExtension;
+ case FDOBackendProviderType.kDb4oClientServer: return FdoFileHelper.ksFwDataDb4oFileExtension;
+ case FDOBackendProviderType.kXML: return FdoFileHelper.ksFwDataXmlFileExtension;
default: throw new InvalidEnumArgumentException("type", (int)type, typeof(FDOBackendProviderType));
}
}
@@ -162,22 +150,10 @@ void BeginFindProjects(string host, Action foundProject,
IDisposable GetExclusiveModeToken(FdoCache cache, string id);
///
- /// Display a warning indicating that it may be dangerous to change things that the user has just
- /// asked to change when other users are connected. The warning should only be shown if, in fact,
- /// other users are currently connected. The dialog may contain some information about the other
- /// users that are connected. Return true to continue, false to discard the changes. This is typically
- /// called in response to clicking an OK button in a dialog which changes dangerous user settings.
- ///
- ///
- bool WarnOnConfirmingSingleUserChanges(FdoCache cache);
- ///
- /// Display a warning indicating that it may be dangerous to change things in the dialog that
- /// is about to open when other users are connected. The warning should only be shown if, in fact,
- /// other users are currently connected. The dialog may contain some information about the other
- /// users that are connected. Return true to continue, false to cancel opening the dialog.
+ /// Returns the number of other users currently connected
///
- ///
- bool WarnOnOpeningSingleUserDialog(FdoCache cache);
+ /// The FDO cache.
+ int CountOfOtherUsersConnected(FdoCache cache);
}
#endregion
@@ -294,15 +270,17 @@ internal class Db4OClientServerServices : IClientServerServices
private const char ksServerHostSeperatorChar = ':';
private Db4OServerFinder m_serverFinder;
private FwProjectFinder m_projectFinder;
+ private readonly IFdoDirectories m_dirs;
/// ------------------------------------------------------------------------------------
///
/// Initializes a new instance of the class.
///
/// ------------------------------------------------------------------------------------
- internal Db4OClientServerServices()
+ internal Db4OClientServerServices(IFdoUI ui, IFdoDirectories dirs, Func usingDefaultProjectsDirAccessor)
{
- Local = new Db4OLocalClientServerServices();
+ m_dirs = dirs;
+ Local = new Db4OLocalClientServerServices(ui, dirs, usingDefaultProjectsDirAccessor);
}
/// ------------------------------------------------------------------------------------
@@ -316,9 +294,9 @@ internal Db4OClientServerServices()
/// ------------------------------------------------------------------------------------
public void BeginFindServers(Action foundServer)
{
- if (m_serverFinder != null)
+ if (m_serverFinder != null && !m_serverFinder.IsCompleted)
throw new InvalidOperationException("Can not start a new find servers before the previous one finishes.");
- m_serverFinder = new Db4OServerFinder(foundServer, () => m_serverFinder = null);
+ m_serverFinder = new Db4OServerFinder(foundServer);
}
/// ------------------------------------------------------------------------------------
@@ -354,7 +332,7 @@ public void BeginFindProjects(string host, Action foundProject,
if (m_projectFinder != null)
throw new InvalidOperationException("Can not start a new find projects before the previous one finishes.");
m_projectFinder = new FwProjectFinder(host, foundProject, () => m_projectFinder = null,
- exceptionCallback, showLocalProjects);
+ exceptionCallback, showLocalProjects, m_dirs.ProjectsDirectory);
}
/// ------------------------------------------------------------------------------------
@@ -468,7 +446,12 @@ public IDisposable GetExclusiveModeToken(FdoCache cache, string id)
return null;
}
- int CountOfOtherUsersConnected(FdoCache cache)
+ ///
+ /// Returns the number of other users currently connected
+ ///
+ /// The FDO cache.
+ /// The number of other users currently connected
+ public int CountOfOtherUsersConnected(FdoCache cache)
{
if (cache == null) // Can happen when creating a new project when editing the WS properties. (FWR-2981)
return 0;
@@ -482,41 +465,6 @@ int CountOfOtherUsersConnected(FdoCache cache)
return otherUsers.Length - 1; // Assume this is connected!
}
- ///
- /// Display a warning indicating that it may be dangerous to change things that the user has just
- /// asked to change when other users are connected. The warning should only be shown if, in fact,
- /// other users are currently connected. The dialog may contain some information about the other
- /// users that are connected. Return true to continue, false to discard the changes. This is typically
- /// called in response to clicking an OK button in a dialog which changes dangerous user settings.
- ///
- ///
- public bool WarnOnConfirmingSingleUserChanges(FdoCache cache)
- {
- var others = CountOfOtherUsersConnected(cache);
- if (others == 0)
- return true;
- var msg = string.Format(Strings.ksWarnOnConfirmingSingleUserChanges.Replace("\\n", Environment.NewLine), others);
- return ThreadHelper.ShowMessageBox(null, msg, Strings.ksNotAdvisableOthersConnectedCaption,
- MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes;
- }
-
- ///
- /// Display a warning indicating that it may be dangerous to change things in the dialog that
- /// is about to open when other users are connected. The warning should only be shown if, in fact,
- /// other users are currently connected. The dialog may contain some information about the other
- /// users that are connected. Return true to continue, false to cancel opening the dialog.
- ///
- ///
- public bool WarnOnOpeningSingleUserDialog(FdoCache cache)
- {
- var others = CountOfOtherUsersConnected(cache);
- if (others == 0)
- return true;
- var msg = string.Format(Strings.ksWarnOnOpeningSingleUserDialog.Replace("\\n", Environment.NewLine), others);
- return ThreadHelper.ShowMessageBox(null, msg, Strings.ksOthersConnectedCaption,
- MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK;
- }
-
#region TrivialDisposable class
private sealed class TrivialDisposable: IDisposable
{
@@ -571,6 +519,16 @@ internal class Db4OLocalClientServerServices : ILocalClientServerServices
{
internal const string kLocalService = "localhost";
internal const string ksDoNotShareProjectTxt = "do_not_share_project.txt";
+ private readonly Func m_usingDefaultProjectsDirAccessor;
+ private readonly IFdoUI m_ui;
+ private readonly IFdoDirectories m_dirs;
+
+ public Db4OLocalClientServerServices(IFdoUI ui, IFdoDirectories dirs, Func usingDefaultProjectsDirAccessor)
+ {
+ m_ui = ui;
+ m_dirs = dirs;
+ m_usingDefaultProjectsDirAccessor = usingDefaultProjectsDirAccessor;
+ }
/// ------------------------------------------------------------------------------------
///
@@ -592,7 +550,7 @@ public bool ShareMyProjects
// their personal projects directory. I'm not sure whether such a user will even see that the
// first user has turned on sharing. But in any case, the second user (who did not turn sharing on,
// and has their own projects folder) will just go on seeing their own unshared projects.
- && DirectoryFinder.ProjectsDirectory == DirectoryFinder.ProjectsDirectoryLocalMachine;
+ && m_usingDefaultProjectsDirAccessor();
}
catch (SocketException)
{
@@ -622,10 +580,9 @@ public bool SetProjectSharing(bool fShare, IThreadedProgress progress)
{
}
}
- while ((serverInfo == null && ThreadHelper.ShowMessageBox(progress.Form,
- string.Format(Strings.ksLocalConnectorServiceNotStarted, "FwRemoteDatabaseConnectorService"),
- fShare ? Strings.ksConvertingToShared : Strings.ksConvertingToNonShared,
- MessageBoxButtons.RetryCancel, MessageBoxIcon.None) == DialogResult.Retry));
+ while (serverInfo == null &&
+ m_ui.Retry(string.Format(Strings.ksLocalConnectorServiceNotStarted, "FwRemoteDatabaseConnectorService"),
+ fShare ? Strings.ksConvertingToShared : Strings.ksConvertingToNonShared));
if (serverInfo == null || serverInfo.AreProjectShared() == fShare)
return false;
@@ -679,7 +636,7 @@ public bool WillProjectBeConverted(string projectPath, string parentDirectory, s
///
/// false if clients are still connected.
/// ------------------------------------------------------------------------------------
- private static bool EnsureNoClientsAreConnected()
+ private bool EnsureNoClientsAreConnected()
{
var localService = LocalDb4OServerInfoConnection;
if (localService == null)
@@ -694,8 +651,8 @@ private static bool EnsureNoClientsAreConnected()
connectedClientsMsg.AppendFormat("{2}{0} : {1}", client, Dns.GetHostEntry(client).HostName, Environment.NewLine);
}
- if (MessageBoxUtils.Show(String.Format(Strings.ksAllProjectsMustDisconnectClients, connectedClientsMsg),
- Strings.ksAllProjectsMustDisconnectCaption, MessageBoxButtons.RetryCancel) == DialogResult.Cancel)
+ if (!m_ui.Retry(String.Format(Strings.ksAllProjectsMustDisconnectClients, connectedClientsMsg),
+ Strings.ksAllProjectsMustDisconnectCaption))
return false;
connectedClients = localService.ListConnectedClients();
@@ -712,11 +669,10 @@ private static bool EnsureNoClientsAreConnected()
/// TODO: prevent new connections while in this shutdown phase.
/// TODO: as an enhancement connected clients could be messaged and asked to disconnect.
///
- /// The message box owner.
/// project name.
/// false if clients are still connected.
/// ------------------------------------------------------------------------------------
- private static bool EnsureNoClientsAreConnected(Form messageBoxOwner, string projectName)
+ private bool EnsureNoClientsAreConnected(string projectName)
{
Db4oServerInfo localService = LocalDb4OServerInfoConnection;
if (localService == null)
@@ -728,7 +684,7 @@ private static bool EnsureNoClientsAreConnected(Form messageBoxOwner, string pro
foreach (string client in connectedClients)
connectedClientsMsg.AppendFormat("{2}{0} : {1}", client, Dns.GetHostEntry(client).HostName, Environment.NewLine);
- if (WarnOfOtherConnectedClients(messageBoxOwner, projectName, connectedClientsMsg.ToString()) == DialogResult.Cancel)
+ if (!WarnOfOtherConnectedClients(projectName, connectedClientsMsg.ToString()))
return false;
connectedClients = localService.ListConnectedClients(projectName);
@@ -741,18 +697,16 @@ private static bool EnsureNoClientsAreConnected(Form messageBoxOwner, string pro
///
/// Warns the of other connected clients.
///
- /// The message box owner.
/// Name of the project.
/// The message to show about the connected clients.
///
/// ------------------------------------------------------------------------------------
- private static DialogResult WarnOfOtherConnectedClients(Form messageBoxOwner,
- string projectName, string connectedClientsMsg)
+ private bool WarnOfOtherConnectedClients(string projectName, string connectedClientsMsg)
{
var msg = String.Format(Strings.ksMustDisconnectClients, projectName, connectedClientsMsg);
var caption = String.Format(Strings.ksMustDisconnectCaption, projectName);
- return ThreadHelper.ShowMessageBox(messageBoxOwner, msg, caption,
- MessageBoxButtons.RetryCancel, MessageBoxIcon.None);
+
+ return m_ui.Retry(msg, caption);
}
/// ------------------------------------------------------------------------------------
@@ -769,19 +723,17 @@ private bool ConvertAllProjectsToXml(IThreadedProgress progressDlg)
progressDlg.Title = Strings.ksConvertingToNonShared;
progressDlg.AllowCancel = false;
- progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous;
- progressDlg.Maximum = Directory.GetDirectories(DirectoryFinder.ProjectsDirectory).Count();
+ progressDlg.Maximum = Directory.GetDirectories(m_dirs.ProjectsDirectory).Count();
progressDlg.RunTask(true, ConvertAllProjectsToXmlTask);
-
return true;
}
private object ConvertAllProjectsToXmlTask(IThreadedProgress progress, object[] args)
{
- foreach (var projectFolder in Directory.GetDirectories(DirectoryFinder.ProjectsDirectory))
+ foreach (string projectFolder in Directory.GetDirectories(m_dirs.ProjectsDirectory))
{
var projectName = Path.GetFileName(projectFolder);
- var projectPath = Path.Combine(projectFolder, DirectoryFinder.GetDb4oDataFileName(projectName));
+ var projectPath = Path.Combine(projectFolder, FdoFileHelper.GetDb4oDataFileName(projectName));
progress.Message = Path.GetFileNameWithoutExtension(projectPath);
if (File.Exists(projectPath))
{
@@ -790,8 +742,9 @@ private object ConvertAllProjectsToXmlTask(IThreadedProgress progress, object[]
// The zero in the object array is for db4o and causes it not to open a port.
// This is fine since we aren't yet trying to start up on this restored database.
// The null says we are creating the file on the local host.
- using (var tempCache = FdoCache.CreateCacheFromExistingData(
- new SimpleProjectId(FDOBackendProviderType.kDb4oClientServer, projectPath), "en", progress))
+ using (FdoCache tempCache = FdoCache.CreateCacheFromExistingData(
+ new SimpleProjectId(FDOBackendProviderType.kDb4oClientServer, projectPath), "en", new SilentFdoUI(progress.SynchronizeInvoke),
+ m_dirs, progress))
{
CopyToXmlFile(tempCache, tempCache.ProjectId.ProjectFolder);
// Enhance JohnT: how can we tell this succeeded?
@@ -800,7 +753,7 @@ private object ConvertAllProjectsToXmlTask(IThreadedProgress progress, object[]
}
catch (Exception e)
{
- ReportConversionError(progress.Form, projectPath, e);
+ ReportConversionError(projectPath, e);
}
}
progress.Step(1);
@@ -818,8 +771,7 @@ private bool ConvertAllProjectsToDb4o(IThreadedProgress progressDlg)
{
progressDlg.Title = Strings.ksConvertingToShared;
progressDlg.AllowCancel = false;
- progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous;
- progressDlg.Maximum = Directory.GetDirectories(DirectoryFinder.ProjectsDirectory).Count();
+ progressDlg.Maximum = Directory.GetDirectories(m_dirs.ProjectsDirectory).Count();
return (bool)progressDlg.RunTask(true, ConvertAllProjectsToDb4o);
}
@@ -828,10 +780,10 @@ private object ConvertAllProjectsToDb4o(IThreadedProgress progress, object[] arg
for (; ; )
{
string projects = "";
- foreach (var projectFolder in Directory.GetDirectories(DirectoryFinder.ProjectsDirectory))
+ foreach (string projectFolder in Directory.GetDirectories(m_dirs.ProjectsDirectory))
{
var projectName = Path.GetFileName(projectFolder);
- var projectPath = Path.Combine(projectFolder, DirectoryFinder.GetXmlDataFileName(projectName));
+ var projectPath = Path.Combine(projectFolder, FdoFileHelper.GetXmlDataFileName(projectName));
var suppressPath = Path.Combine(projectFolder, ksDoNotShareProjectTxt);
if (!File.Exists(projectPath) || File.Exists(suppressPath))
continue; // not going to convert, it isn't a problem.
@@ -841,37 +793,36 @@ private object ConvertAllProjectsToDb4o(IThreadedProgress progress, object[] arg
if (projects.Length == 0)
break;
projects = projects.Substring(0, projects.Length - ", ".Length);
- // ENHANCE (TimS): Showing a message box at this level is not a good idea.
- if (ThreadHelper.ShowMessageBox(progress.Form, string.Format(Strings.ksMustCloseProjectsToShare, projects),
- Strings.ksConvertingToShared, MessageBoxButtons.RetryCancel, MessageBoxIcon.None) != DialogResult.Retry)
+
+ if (!m_ui.Retry(string.Format(Strings.ksMustCloseProjectsToShare, projects), Strings.ksConvertingToShared))
return false;
}
- foreach (string projectFolder in Directory.GetDirectories(DirectoryFinder.ProjectsDirectory))
+ foreach (string projectFolder in Directory.GetDirectories(m_dirs.ProjectsDirectory))
{
string projectName = Path.GetFileName(projectFolder);
- string projectPath = Path.Combine(projectFolder, DirectoryFinder.GetXmlDataFileName(projectName));
+ string projectPath = Path.Combine(projectFolder, FdoFileHelper.GetXmlDataFileName(projectName));
var suppressPath = Path.Combine(projectFolder, ksDoNotShareProjectTxt);
progress.Message = Path.GetFileNameWithoutExtension(projectPath);
if (File.Exists(projectPath) && !File.Exists(suppressPath))
{
- try
- {
+ try
+ {
ConvertToDb4oBackendIfNeeded(progress, projectPath);
- }
- catch (Exception e)
- {
- ReportConversionError(progress.Form, projectPath, e);
- }
+ }
+ catch (Exception e)
+ {
+ ReportConversionError(projectPath, e);
+ }
}
progress.Step(1);
}
return true;
}
- private static void ReportConversionError(Form messageBoxOwner, string projectPath, Exception e)
+ private void ReportConversionError(string projectPath, Exception e)
{
string message;
- if (e is FwNewerVersionException)
+ if (e is FdoNewerVersionException)
{
message = string.Format(Strings.ksConvertFailedNewerVersion, Path.GetFileName(projectPath),
Path.GetDirectoryName(projectPath));
@@ -881,8 +832,7 @@ private static void ReportConversionError(Form messageBoxOwner, string projectPa
message = string.Format(Strings.ksConvertFailedDetails, Path.GetFileName(projectPath),
Path.GetDirectoryName(projectPath), e.Message);
}
- ThreadHelper.ShowMessageBox(messageBoxOwner, message, Strings.ksCannotConvert,
- MessageBoxButtons.OK, MessageBoxIcon.Error);
+ m_ui.DisplayMessage(MessageType.Error, message, Strings.ksCannotConvert, null);
}
/// ------------------------------------------------------------------------------------
@@ -901,28 +851,27 @@ public string ConvertToDb4oBackendIfNeeded(IThreadedProgress progressDlg, string
{
if (!ShareMyProjects)
return xmlFilename; // no conversion needed.
- string desiredPath = Path.ChangeExtension(xmlFilename, FwFileExtensions.ksFwDataDb4oFileExtension);
- if (!EnsureNoClientsAreConnected(progressDlg.Form, Path.GetFileNameWithoutExtension(desiredPath)))
+ string desiredPath = Path.ChangeExtension(xmlFilename, FdoFileHelper.ksFwDataDb4oFileExtension);
+ if (!EnsureNoClientsAreConnected(Path.GetFileNameWithoutExtension(desiredPath)))
return null; // fail
try
{
- using (var tempCache = FdoCache.CreateCacheFromExistingData(
- new SimpleProjectId(FDOBackendProviderType.kXML, xmlFilename), "en", progressDlg))
- {
-
- // The zero in the object array is for db4o and causes it not to open a port.
- // This is fine since we aren't yet trying to start up on this restored database.
- // The null says we are creating the file on the local host.
- using (var copyCache = FdoCache.CreateCacheCopy(
- new SimpleProjectId(FDOBackendProviderType.kDb4oClientServer, desiredPath), "en", tempCache, progressDlg.ThreadHelper))
+ using (FdoCache tempCache = FdoCache.CreateCacheFromExistingData(new SimpleProjectId(FDOBackendProviderType.kXML, xmlFilename),
+ "en", new SilentFdoUI(progressDlg.SynchronizeInvoke), m_dirs, progressDlg))
{
- copyCache.ServiceLocator.GetInstance().Commit(new HashSet(),
- new HashSet(), new HashSet());
- // Enhance JohnT: how can we tell this succeeded?
+
+ // The zero in the object array is for db4o and causes it not to open a port.
+ // This is fine since we aren't yet trying to start up on this restored database.
+ // The null says we are creating the file on the local host.
+ using (FdoCache copyCache = FdoCache.CreateCacheCopy(new SimpleProjectId(FDOBackendProviderType.kDb4oClientServer, desiredPath),
+ "en", new SilentFdoUI(progressDlg.SynchronizeInvoke), m_dirs, tempCache))
+ {
+ copyCache.ServiceLocator.GetInstance().Commit(new HashSet(), new HashSet(), new HashSet());
+ // Enhance JohnT: how can we tell this succeeded?
+ }
}
}
- }
catch (Exception)
{
// If we couldn't convert it, try not to leave a corrupted file around.
@@ -951,19 +900,19 @@ public string CopyToXmlFile(FdoCache source, string destDir)
if (dataStorer is XMLBackendProvider)
return null; // already XML, no new file created.
- var newFilePath = Path.Combine(destDir, DirectoryFinder.GetXmlDataFileName(source.ProjectId.Name));
+ var newFilePath = Path.Combine(destDir, FdoFileHelper.GetXmlDataFileName(source.ProjectId.Name));
if (File.Exists(newFilePath))
File.Delete(newFilePath); // Can't create a new file with FDO if the file already exists.
try
{
- using (var copyCache = FdoCache.CreateCacheCopy(
- new SimpleProjectId(FDOBackendProviderType.kXML, newFilePath), "en", source, source.ThreadHelper))
+ using (FdoCache copyCache = FdoCache.CreateCacheCopy(new SimpleProjectId(FDOBackendProviderType.kXML, newFilePath),
+ "en", new SilentFdoUI(source.ServiceLocator.GetInstance().SynchronizeInvoke), m_dirs, source))
{
- copyCache.ServiceLocator.GetInstance().Commit(
- new HashSet(),
- new HashSet(),
- new HashSet());
- // Enhance JohnT: how can we tell this succeeded?
+ copyCache.ServiceLocator.GetInstance().Commit(
+ new HashSet(),
+ new HashSet(),
+ new HashSet());
+ // Enhance JohnT: how can we tell this succeeded?
return newFilePath;
}
}
@@ -985,7 +934,7 @@ public string IdForLocalProject(string projectName)
// Project Name must not have an extension. Can't use ChangeExtension because
// the project name might contain some other period.
Debug.Assert(!projectName.EndsWith(".fwdata") && !projectName.EndsWith(".fwdb"));
- string projectDirectory = Path.Combine(DirectoryFinder.ProjectsDirectory, projectName);
+ string projectDirectory = Path.Combine(m_dirs.ProjectsDirectory, projectName);
var result = Path.Combine(projectDirectory, projectName + DefaultBackendType.GetExtension());
if (!File.Exists(result))
{
diff --git a/Src/FDO/DomainServices/ConstraintFailure.cs b/Src/FDO/DomainServices/ConstraintFailure.cs
index 1ab4177343..2803f7a23b 100644
--- a/Src/FDO/DomainServices/ConstraintFailure.cs
+++ b/Src/FDO/DomainServices/ConstraintFailure.cs
@@ -11,10 +11,7 @@
//
// --------------------------------------------------------------------------------------------
-using System.Collections.Generic;
using System.Linq;
-using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.CoreImpl;
namespace SIL.FieldWorks.FDO.DomainServices
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000019.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000019.cs
index f135bdcbd1..567191cf9d 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000019.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000019.cs
@@ -12,7 +12,6 @@
using Palaso.Xml;
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
@@ -124,7 +123,7 @@ public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepositor
foreach (DomainObjectDTO dto in domainObjectDtoRepository.AllInstances())
UpdateStringsAndProps(domainObjectDtoRepository, dto, referencedWsIds);
- var localStoreFolder = Path.Combine(domainObjectDtoRepository.ProjectFolder, DirectoryFinder.ksWritingSystemsDir);
+ var localStoreFolder = Path.Combine(domainObjectDtoRepository.ProjectFolder, FdoFileHelper.ksWritingSystemsDir);
// If any writing systems that project needs don't already exist as LDML files,
// create them, either by copying relevant data from a shipping LDML file, or by
@@ -152,7 +151,7 @@ public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepositor
// FieldWorks 6 data directory, and this is looking in the FW 7 one. No one has complained
// so we decided not to try to fix it for the new implementation of the migration.
- //string langDefPath = Path.Combine(DirectoryFinder.GetFWDataSubDirectory("Languages"),
+ //string langDefPath = Path.Combine(FwDirectoryFinder.GetDataSubDirectory("Languages"),
// Path.ChangeExtension(langTag, "xml"));
//if (File.Exists(langDefPath))
// FillWritingSystemFromLangDef(XElement.Load(langDefPath), ws);
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000024.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000024.cs
index 1ca7ccb420..984f5b9284 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000024.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000024.cs
@@ -9,13 +9,10 @@
//
using System;
-using System.Collections;
using System.Collections.Generic;
-using System.Windows.Forms;
using System.Xml.Linq;
using System.Linq;
using System.Xml.XPath;
-using SIL.FieldWorks.FDO.DomainImpl;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000026.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000026.cs
index b70d3ddb6e..0cb797b47e 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000026.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000026.cs
@@ -8,14 +8,8 @@
//
//
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Windows.Forms;
using System.Xml.Linq;
using System.Linq;
-using System.Xml.XPath;
-using SIL.FieldWorks.FDO.DomainImpl;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000029.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000029.cs
index 62cb888366..132750ebc8 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000029.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000029.cs
@@ -9,15 +9,10 @@
//
using System;
-using System.Collections;
-using System.Collections.Generic;
using System.IO;
-using System.Windows.Forms;
using System.Xml.Linq;
using System.Linq;
using System.Xml.XPath;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.FDO.DomainImpl;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
@@ -70,14 +65,14 @@ public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepositor
string persistedLinkedFilesRootDir;
if (linkedFilesRootDirElement == null)
{
- persistedLinkedFilesRootDir = Path.Combine(domainObjectDtoRepository.ProjectFolder, DirectoryFinder.ksLinkedFilesDir);
+ persistedLinkedFilesRootDir = Path.Combine(domainObjectDtoRepository.ProjectFolder, FdoFileHelper.ksLinkedFilesDir);
}
else
{
persistedLinkedFilesRootDir = linkedFilesRootDirElement.Value;
}
- var linkedFilesRootDir = DirectoryFinderRelativePaths.GetLinkedFilesFullPathFromRelativePath(persistedLinkedFilesRootDir,
- domainObjectDtoRepository.ProjectFolder);
+ var linkedFilesRootDir = LinkedFilesRelativePathHelper.GetLinkedFilesFullPathFromRelativePath(domainObjectDtoRepository.Directories.ProjectsDirectory,
+ persistedLinkedFilesRootDir, domainObjectDtoRepository.ProjectFolder);
//Get the Elements for class="CmFile"
var CmFileDtosBeforeMigration = domainObjectDtoRepository.AllInstancesSansSubclasses("CmFile");
@@ -85,7 +80,7 @@ public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepositor
{
XElement cmFileXML = XElement.Parse(fileDto.Xml);
var filePath = cmFileXML.XPathSelectElement("InternalPath").XPathSelectElement("Uni").Value;
- var fileAsRelativePath = DirectoryFinderRelativePaths.GetRelativeLinkedFilesPath(filePath,
+ var fileAsRelativePath = LinkedFilesRelativePathHelper.GetRelativeLinkedFilesPath(filePath,
linkedFilesRootDir);
//If these two strings do not match then a full path was converted to a LinkedFiles relative path
//so replace the path in the CmFile object.
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000030.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000030.cs
index 63d1d79dab..d53663e839 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000030.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000030.cs
@@ -9,18 +9,12 @@
//
using System;
-using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
-using System.Windows.Forms;
-using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
-using SIL.CoreImpl;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.FDO.DomainImpl;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
@@ -76,14 +70,14 @@ public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepositor
string persistedLinkedFilesRootDir;
if (linkedFilesRootDirElement == null)
{
- persistedLinkedFilesRootDir = Path.Combine(domainObjectDtoRepository.ProjectFolder, DirectoryFinder.ksLinkedFilesDir);
+ persistedLinkedFilesRootDir = Path.Combine(domainObjectDtoRepository.ProjectFolder, FdoFileHelper.ksLinkedFilesDir);
}
else
{
persistedLinkedFilesRootDir = linkedFilesRootDirElement.Value;
}
- var linkedFilesRootDir = DirectoryFinderRelativePaths.GetLinkedFilesFullPathFromRelativePath(persistedLinkedFilesRootDir,
- domainObjectDtoRepository.ProjectFolder);
+ var linkedFilesRootDir = LinkedFilesRelativePathHelper.GetLinkedFilesFullPathFromRelativePath(domainObjectDtoRepository.Directories.ProjectsDirectory,
+ persistedLinkedFilesRootDir, domainObjectDtoRepository.ProjectFolder);
//-------------------------------------------------
var langProjectGuid = langProjElement.Attribute("guid").Value;
@@ -221,7 +215,7 @@ private List ProcessExternalLinksRelativePaths(IDomainObjectDTORepositor
var filePath = FileUtils.ChangeWindowsPathIfLinux(externalLinkAttributeForThisRun.Value);
//Check the path and if it is a rooted path which is relative to the LinkedFilesRootDir
//then we will have to confirm that is was changed to a relative path after the migration.
- var fileAsRelativePath = DirectoryFinderRelativePaths.GetRelativeLinkedFilesPath(filePath,
+ var fileAsRelativePath = LinkedFilesRelativePathHelper.GetRelativeLinkedFilesPath(filePath,
linkedFilesRootDir);
//Save the file paths so they can be turned into CmFiles
filePathsInTsStrings.Add(fileAsRelativePath);
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000033.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000033.cs
index a601fa9d36..aebe41226d 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000033.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000033.cs
@@ -55,7 +55,7 @@ public void PerformMigration(IDomainObjectDTORepository repoDto)
{
DataMigrationServices.CheckVersionNumber(repoDto, 7000032);
var projectFolder = repoDto.ProjectFolder;
- // This is equivalent to DirectoryFinder.GetConfigSettingsDir(projectFolder) at the time of creating
+ // This is equivalent to FwDirectoryFinder.GetConfigSettingsDir(projectFolder) at the time of creating
// the migration, but could conceivably change later.
var targetDir = Path.Combine(projectFolder, "ConfigurationSettings");
if (Directory.Exists(targetDir))
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000037.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000037.cs
index c20ca7ed73..dd2b3456e4 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000037.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000037.cs
@@ -7,14 +7,10 @@
using System;
using System.IO;
-using System.Linq;
using System.Text;
using System.Web;
-using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
-
-using SIL.FieldWorks.Common.FwUtils;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
@@ -30,6 +26,10 @@ internal class DataMigration7000037 : IDataMigration
{
private static readonly byte[] s_externalLinkTag = Encoding.UTF8.GetBytes("externalLink");
+ // Moved here from FWLinkArgs. We don't want it to change here if it is changed there since
+ // the data migration will expect it to be what it was at that time, not the new value.
+ private const string kFwUrlPrefix = "silfw://localhost/link?";
+
#region IDataMigration Members
public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
@@ -62,11 +62,11 @@ private bool FixExternalLinks(XElement xel, string projectName)
if (attrLink == null)
continue;
string value = attrLink.Value;
- if (value.StartsWith(FwLinkArgs.kFwUrlPrefix.Substring(1)))
- value = FwLinkArgs.kFwUrlPrefix.Substring(0, 1) + value;
- if (!value.StartsWith(FwLinkArgs.kFwUrlPrefix))
+ if (value.StartsWith(kFwUrlPrefix.Substring(1)))
+ value = kFwUrlPrefix.Substring(0, 1) + value;
+ if (!value.StartsWith(kFwUrlPrefix))
continue;
- string query = HttpUtility.UrlDecode(value.Substring(FwLinkArgs.kFwUrlPrefix.Length));
+ string query = HttpUtility.UrlDecode(value.Substring(kFwUrlPrefix.Length));
string[] rgsProps = query.Split(new char[] {'&'}, StringSplitOptions.RemoveEmptyEntries);
string database = null;
int idxDatabase = -1;
@@ -130,7 +130,7 @@ private bool FixExternalLinks(XElement xel, string projectName)
if (!fChange)
continue;
- value = FwLinkArgs.kFwUrlPrefix + HttpUtility.UrlEncode(rgsProps.ToString("&"));
+ value = kFwUrlPrefix + HttpUtility.UrlEncode(rgsProps.ToString("&"));
if (attrLink.Value != value)
{
attrLink.Value = value;
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000040.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000040.cs
index a16a4d5e5d..ed0cc25399 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000040.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000040.cs
@@ -5,17 +5,8 @@
// File: DataMigration7000037.cs
// Responsibility: mcconnel
-using System;
-using System.IO;
using System.Linq;
-using System.Text;
-using System.Web;
-using System.Xml;
using System.Xml.Linq;
-using System.Xml.XPath;
-
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000041.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000041.cs
index 558c7e6366..e0559794ce 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000041.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000041.cs
@@ -6,19 +6,12 @@
// Responsibility: lastufka
using System;
-using System.IO;
using System.Linq;
-using System.Text;
-using System.Web;
-using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Collections.Generic;
using System.Diagnostics;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.Utils;
-
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
/// ----------------------------------------------------------------------------------------
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000042.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000042.cs
index 41f1dcc100..f2ed1bf03d 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000042.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000042.cs
@@ -10,8 +10,8 @@
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;
-using SIL.FieldWorks.Common.FwUtils;
using System;
+using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000044.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000044.cs
index 28fd82a070..72ae2f8d50 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000044.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000044.cs
@@ -15,7 +15,7 @@
using System.Xml.XPath;
using Palaso.WritingSystems.Migration;
using Palaso.WritingSystems.Migration.WritingSystemsLdmlV0To1Migration;
-using SIL.FieldWorks.Common.FwUtils;
+using SIL.CoreImpl;
using System;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
@@ -55,7 +55,7 @@ public void PerformMigration(IDomainObjectDTORepository repoDto)
globalMigrator.Migrate();
}
- var ldmlFolder = Path.Combine(repoDto.ProjectFolder, DirectoryFinder.ksWritingSystemsDir);
+ var ldmlFolder = Path.Combine(repoDto.ProjectFolder, FdoFileHelper.ksWritingSystemsDir);
var migrator = new LdmlInFolderWritingSystemRepositoryMigrator(ldmlFolder, NoteMigration);
migrator.Migrate();
UpdateTags(repoDto);
@@ -156,7 +156,7 @@ private void UpdateTags(IDomainObjectDTORepository repoDto)
lpChanged |= UpdateAttr(langProj, "VernWss");
if (lpChanged)
DataMigrationServices.UpdateDTO(repoDto, langProjDto, langProj.ToString());
- var settingsFolder = Path.Combine(repoDto.ProjectFolder, DirectoryFinder.ksConfigurationSettingsDir);
+ var settingsFolder = Path.Combine(repoDto.ProjectFolder, FdoFileHelper.ksConfigurationSettingsDir);
if (Directory.Exists(settingsFolder))
{
m_tagMap["$wsname"] = "$wsname"; // should never be changed.
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000060.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000060.cs
index 279dffd9b2..d13954f753 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000060.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000060.cs
@@ -7,16 +7,6 @@
using System.Collections.Generic;
using System.IO;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Xml;
-using System.Xml.Linq;
-using System.Xml.XPath;
-using Palaso.WritingSystems.Migration;
-using Palaso.WritingSystems.Migration.WritingSystemsLdmlV0To1Migration;
-using SIL.FieldWorks.Common.FwUtils;
-using System;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
@@ -45,7 +35,7 @@ public void PerformMigration(IDomainObjectDTORepository repoDto)
{
DataMigrationServices.CheckVersionNumber(repoDto, 7000059);
- var configFolder = Path.Combine(repoDto.ProjectFolder, DirectoryFinder.ksConfigurationSettingsDir);
+ var configFolder = Path.Combine(repoDto.ProjectFolder, FdoFileHelper.ksConfigurationSettingsDir);
if (Directory.Exists(configFolder)) // Some of Randy's test data doesn't have the config folder, so it crashes here.
{
const string layoutSuffix = "_Layouts.xml";
diff --git a/Src/FDO/DomainServices/DataMigration/DataMigration7000066.cs b/Src/FDO/DomainServices/DataMigration/DataMigration7000066.cs
index 0d0aa68ec1..f75dec2e8e 100644
--- a/Src/FDO/DomainServices/DataMigration/DataMigration7000066.cs
+++ b/Src/FDO/DomainServices/DataMigration/DataMigration7000066.cs
@@ -3,7 +3,6 @@
using System.Linq;
using System.Xml.Linq;
using SIL.CoreImpl;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Infrastructure;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
diff --git a/Src/FDO/DomainServices/DataMigration/FdoDataMigrationManager.cs b/Src/FDO/DomainServices/DataMigration/FdoDataMigrationManager.cs
index 7b1a00aa87..cfaf727d6f 100644
--- a/Src/FDO/DomainServices/DataMigration/FdoDataMigrationManager.cs
+++ b/Src/FDO/DomainServices/DataMigration/FdoDataMigrationManager.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
-using System.Windows.Forms;
-using SIL.FieldWorks.Common.FwUtils;
+using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
@@ -175,7 +174,6 @@ public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepositor
currentDataStoreModelVersion, updateToVersion));
progressDlg.Title = Strings.ksDataMigrationCaption;
- progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous;
progressDlg.AllowCancel = false;
progressDlg.Minimum = 0;
progressDlg.Maximum = (updateToVersion - currentDataStoreModelVersion) + 1;
diff --git a/Src/FDO/DomainServices/DataMigration/IDataMigrationManager.cs b/Src/FDO/DomainServices/DataMigration/IDataMigrationManager.cs
index 2c7c5ba7fb..08cfe40115 100644
--- a/Src/FDO/DomainServices/DataMigration/IDataMigrationManager.cs
+++ b/Src/FDO/DomainServices/DataMigration/IDataMigrationManager.cs
@@ -6,7 +6,7 @@
// Responsibility: FW team
using System;
-using SIL.FieldWorks.Common.FwUtils;
+using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
{
diff --git a/Src/FDO/DomainServices/DataMigration/IDomainObjectDTORepository.cs b/Src/FDO/DomainServices/DataMigration/IDomainObjectDTORepository.cs
index fb31b858de..fba990dc56 100644
--- a/Src/FDO/DomainServices/DataMigration/IDomainObjectDTORepository.cs
+++ b/Src/FDO/DomainServices/DataMigration/IDomainObjectDTORepository.cs
@@ -213,6 +213,11 @@ void CreateCustomField(string className, string fieldName, SIL.CoreImpl.CellarPr
///
/// ------------------------------------------------------------------------------------
string ProjectFolder { get; }
+
+ ///
+ /// Gets the directories service.
+ ///
+ IFdoDirectories Directories { get; }
}
internal sealed class DomainObjectDtoRepository : IDomainObjectDTORepository
@@ -233,6 +238,7 @@ internal sealed class DomainObjectDtoRepository : IDomainObjectDTORepository
private int m_currentModelVersionNumber;
private readonly HashSet m_oldTimers = new HashSet();
private readonly string m_projectFolder;
+ private readonly IFdoDirectories m_dirs;
private readonly IFwMetaDataCacheManaged m_mdc; // needed for some data migrations changing over to custom fields.
@@ -247,9 +253,10 @@ internal sealed class DomainObjectDtoRepository : IDomainObjectDTORepository
/// The project folder (don't even think about trying to
/// pass a path on a server other than the local machine, and -- yes -- I CAN control
/// your thoughts!).
+ ///
/// ------------------------------------------------------------------------------------
internal DomainObjectDtoRepository(int startingModelVersionNumber, HashSet dtos,
- IFwMetaDataCacheManaged mdc, string projectFolder)
+ IFwMetaDataCacheManaged mdc, string projectFolder, IFdoDirectories dirs)
{
if (dtos == null) throw new ArgumentNullException("dtos");
if (mdc == null) throw new ArgumentNullException("mdc");
@@ -258,6 +265,7 @@ internal DomainObjectDtoRepository(int startingModelVersionNumber, HashSet
+ /// Gets the directories service.
+ ///
+ public IFdoDirectories Directories
+ {
+ get { return m_dirs; }
+ }
#endregion
}
}
diff --git a/Src/FDO/DomainServices/DataMigration/ImportFrom6_0.cs b/Src/FDO/DomainServices/DataMigration/ImportFrom6_0.cs
index 11c93c92ca..ecc6e5dcde 100644
--- a/Src/FDO/DomainServices/DataMigration/ImportFrom6_0.cs
+++ b/Src/FDO/DomainServices/DataMigration/ImportFrom6_0.cs
@@ -10,12 +10,8 @@
using System.IO;
using System.ServiceProcess;
using System.Text;
-using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Win32;
-
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.Resources;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices.DataMigration
@@ -45,29 +41,28 @@ public class ImportFrom6_0
bool m_fHaveSqlServer;
bool m_fHaveOldFieldWorks;
+ private readonly string m_converterConsolePath;
readonly bool m_fVerboseDebug;
private readonly IThreadedProgress m_progressDlg;
#endregion
- ///
- /// provides parent form for progress dialog
- ///
- public Form ParentForm { get; set; }
-
#region Constructors
///
/// Constructor for run-time debugging.
///
- public ImportFrom6_0(IThreadedProgress progressDlg, bool fDebug)
+ public ImportFrom6_0(IThreadedProgress progressDlg, string converterConsolePath, string dbPath, bool fDebug)
{
m_progressDlg = progressDlg;
+ m_converterConsolePath = converterConsolePath;
+ m_dbPath = dbPath;
m_fVerboseDebug = fDebug;
}
///
/// Constructor.
///
- public ImportFrom6_0(IThreadedProgress progressDlg) : this(progressDlg, false)
+ public ImportFrom6_0(IThreadedProgress progressDlg, string converterConsolePath, string dbPath)
+ : this(progressDlg, converterConsolePath, dbPath, false)
{
}
#endregion
@@ -75,22 +70,17 @@ public ImportFrom6_0(IThreadedProgress progressDlg) : this(progressDlg, false)
///
/// Do the import of the specified zip or XML file. Return true if successful and the caller should open the database.
///
- public bool Import(string pathname, string projectName, out string projectFile)
+ public bool Import(string pathname, string projectName, string destFolder, out string projectFile)
{
- var destFolder = DirectoryFinder.ProjectsDirectory;
var folderName = Path.Combine(destFolder, projectName);
- projectFile = Path.Combine(folderName, projectName + FwFileExtensions.ksFwDataXmlFileExtension);
+ projectFile = Path.Combine(folderName, projectName + FdoFileHelper.ksFwDataXmlFileExtension);
string extension = Path.GetExtension(pathname);
if (extension != null)
extension = extension.ToLowerInvariant();
if (extension == ".xml")
{
if (!IsValid6_0Xml(pathname))
- {
- MessageBoxUtils.Show(m_progressDlg.Form, Strings.ksBackupXMLFileTooOld,
- Strings.ksCannotConvert);
- return false;
- }
+ throw new CannotConvertException(Strings.ksBackupXMLFileTooOld);
var result1 = ImportFrom6_0Xml(pathname, folderName, projectFile);
return result1;
}
@@ -109,7 +99,7 @@ public bool Import(string pathname, string projectName, out string projectFile)
if (fCreateFolder)
Directory.CreateDirectory(folderName);
string message = String.Format(Strings.ksExtractingFromZip, Path.GetFileName(entry.Name));
- if (!UnzipFile(zipFile, entry, message, out tempPath))
+ if (!UnzipFile(destFolder, zipFile, entry, message, out tempPath))
{
return false;
}
@@ -126,9 +116,16 @@ public bool Import(string pathname, string projectName, out string projectFile)
else
continue;
}
- // Next step is to run the converter. It should be in the same directory as FDO.dll
- var result = ImportFrom6_0Xml(tempPath, folderName, projectFile);
- File.Delete(tempPath);
+ bool result;
+ try
+ {
+ // Next step is to run the converter. It should be in the same directory as FDO.dll
+ result = ImportFrom6_0Xml(tempPath, folderName, projectFile);
+ }
+ finally
+ {
+ File.Delete(tempPath);
+ }
return result;
}
if (entry.Name.ToLowerInvariant().EndsWith(".bak") && entry.IsFile)
@@ -139,10 +136,7 @@ public bool Import(string pathname, string projectName, out string projectFile)
}
}
if (!fHasBak)
- {
- MessageBoxUtils.Show(m_progressDlg.Form, Strings.ksZipNotFieldWorksBackup, Strings.ksCannotConvert);
- return false;
- }
+ throw new CannotConvertException(Strings.ksZipNotFieldWorksBackup);
if (HaveFwSqlServer && HaveOldFieldWorks)
{
foreach (ZipEntry entry in zipFile)
@@ -151,7 +145,7 @@ public bool Import(string pathname, string projectName, out string projectFile)
{
string tempPath;
string message = String.Format(Strings.ksExtractingFromZip, Path.GetFileName(entry.Name));
- if (!UnzipFile(zipFile, entry, message, out tempPath))
+ if (!UnzipFile(destFolder, zipFile, entry, message, out tempPath))
{
return false;
}
@@ -176,32 +170,37 @@ public bool Import(string pathname, string projectName, out string projectFile)
proj, "{0}", "{1}");
if (!DumpDatabaseAsXml(TempDatabaseName, tempXmlPath, msg3, errMsgFmt3))
return false;
- // Next step is to run the converter. It should be in the same directory as FDO.dll
- var result = ImportFrom6_0Xml(tempXmlPath, folderName, projectFile);
- File.Delete(tempXmlPath);
- DeleteTempDatabase();
+
+ bool result;
+ try
+ {
+ // Next step is to run the converter. It should be in the same directory as FDO.dll
+ result = ImportFrom6_0Xml(tempXmlPath, folderName, projectFile);
+ }
+ finally
+ {
+ File.Delete(tempXmlPath);
+ DeleteTempDatabase();
+ }
return result;
}
}
// Should never get here, but ...
- MessageBoxUtils.Show(m_progressDlg.Form, Strings.ksZipNotFieldWorksBackup, Strings.ksCannotConvert);
+ throw new CannotConvertException(Strings.ksZipNotFieldWorksBackup);
}
return false;
}
}
- private bool UnzipFile(ZipFile zipFile, ZipEntry entry, string message, out string tempPath)
+ private bool UnzipFile(string folderName, ZipFile zipFile, ZipEntry entry, string message, out string tempPath)
{
- string folderName = DirectoryFinder.ProjectsDirectory;
if (!Directory.Exists(folderName))
Directory.CreateDirectory(folderName);
// We will extract the file to here.
tempPath = Path.Combine(folderName, entry.Name);
using (var stream = zipFile.GetInputStream(entry))
{
- var form = ParentForm ?? Form.ActiveForm;
m_progressDlg.Title = Strings.ksConverting;
- m_progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous;
m_progressDlg.Maximum = (int)entry.Size;
if (File.Exists(tempPath))
File.Delete(tempPath); // if we tried and failed earlier, try again.
@@ -254,7 +253,7 @@ public bool IsFwSqlServerInstalled()
catch (Exception)
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("The FieldWorks installation of SQL Server (MSSQL$SILFW) does not exist.",
+ Debug.WriteLine("The FieldWorks installation of SQL Server (MSSQL$SILFW) does not exist.",
"DEBUG!");
return false; // The FieldWorks installation of SQL Server isn't available
}
@@ -279,7 +278,7 @@ public bool IsValidOldFwInstalled(out string version)
if (clsidKey == null)
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("Unable to open the CLSID registry subkey????", "DEBUG!");
+ Debug.WriteLine("Unable to open the CLSID registry subkey????");
return false;
}
// check for registered class id for FwXmlData.
@@ -287,7 +286,7 @@ public bool IsValidOldFwInstalled(out string version)
if (cellarPath == null)
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("FwCellar.dll is not registered.", "DEBUG!");
+ Debug.WriteLine("FwCellar.dll is not registered.", "DEBUG!");
return false;
}
// check for registered class id for MigrateData.
@@ -295,7 +294,7 @@ public bool IsValidOldFwInstalled(out string version)
if (migratePath == null)
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("MigrateData.dll is not registered.", "DEBUG!");
+ Debug.WriteLine("MigrateData.dll is not registered.", "DEBUG!");
return false;
}
// check for registered class id for LgWritingSystemFactory.
@@ -303,7 +302,7 @@ public bool IsValidOldFwInstalled(out string version)
if (languagePath == null)
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("Language.dll is not registered.", "DEBUG!");
+ Debug.WriteLine("Language.dll is not registered.", "DEBUG!");
return false;
}
// check for registered class id for TsStrFactory.
@@ -311,7 +310,7 @@ public bool IsValidOldFwInstalled(out string version)
if (kernelPath == null)
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("FwKernel.dll is not registered.", "DEBUG!");
+ Debug.WriteLine("FwKernel.dll is not registered.", "DEBUG!");
return false;
}
// check for registered class id for OleDbEncap.
@@ -319,7 +318,7 @@ public bool IsValidOldFwInstalled(out string version)
if (dbaccessPath == null)
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("DbAccess.dll is not registered.", "DEBUG!");
+ Debug.WriteLine("DbAccess.dll is not registered.", "DEBUG!");
return false;
}
// Get (and save) the path to dumpxml.exe.
@@ -337,7 +336,7 @@ public bool IsValidOldFwInstalled(out string version)
if (!File.Exists(m_dumpxmlPath))
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("Cannot find dumpxml.exe in the old FieldWorks installation.", "DEBUG!");
+ Debug.WriteLine("Cannot find dumpxml.exe in the old FieldWorks installation.", "DEBUG!");
return false;
}
}
@@ -352,15 +351,14 @@ public bool IsValidOldFwInstalled(out string version)
if (!File.Exists(scriptPath))
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("Cannot find DataMigration\\200259To200260.sql in the old FieldWorks installation.", "DEBUG!");
+ Debug.WriteLine("Cannot find DataMigration\\200259To200260.sql in the old FieldWorks installation.", "DEBUG!");
return false;
}
}
- m_dbPath = Path.Combine(DirectoryFinder.GetFWCodeSubDirectory("MSSQLMigration"), "db.exe");
if (!File.Exists(m_dbPath))
{
if (m_fVerboseDebug)
- MessageBoxUtils.Show("Cannot find MSSQLMigration\\db.exe in the FieldWorks 7.0 or later installation.", "DEBUG!");
+ Debug.WriteLine("Cannot find MSSQLMigration\\db.exe in the FieldWorks 7.0 or later installation.", "DEBUG!");
return false;
}
return true;
@@ -373,7 +371,7 @@ public bool IsValidOldFwInstalled(out string version)
string msg = String.Format(
"An exception was thrown while checking for an old version of FieldWorks:{1}{0}",
e.Message, Environment.NewLine);
- MessageBoxUtils.Show(msg, "DEBUG!");
+ Debug.WriteLine(msg, "DEBUG!");
}
}
return false;
@@ -395,7 +393,7 @@ private string FindComDllIfRegistered(RegistryKey clsidKey, string sClsid, ref s
if (m_fVerboseDebug)
{
string msg = String.Format("Nonexistent file for a registered COM DLL: {0}", dllPath);
- MessageBox.Show(msg, "DEBUG!");
+ Debug.WriteLine(msg, "DEBUG!");
}
return null;
}
@@ -411,40 +409,17 @@ private string FindComDllIfRegistered(RegistryKey clsidKey, string sClsid, ref s
{
string msg = String.Format("Multiple versions found in the registered COM DLLs: {0} and {1} [{2}]",
version, fileVersion, dllPath);
- MessageBoxUtils.Show(msg, "DEBUG!");
+ Debug.WriteLine(msg, "DEBUG!");
}
return null; // don't want a mix of versions!!
}
if (String.IsNullOrEmpty(version) || version.CompareTo("5.4") < 0 || version.CompareTo("6.1") >= 0)
{
- if (!String.IsNullOrEmpty(version) && version.CompareTo("5.4") < 0)
- {
- using (FWVersionTooOld dlg = new FWVersionTooOld(version))
- {
- dlg.ShowDialog();
- }
- string launchesFlex = "0";
- string launchesTE = "0";
- if (RegistryHelper.KeyExists(FwRegistryHelper.FieldWorksRegistryKey, "Language Explorer"))
- {
- using (RegistryKey keyFlex = FwRegistryHelper.FieldWorksRegistryKey.CreateSubKey("Language Explorer"))
- launchesFlex = keyFlex.GetValue("launches", "0") as string;
- }
- if (RegistryHelper.KeyExists(FwRegistryHelper.FieldWorksRegistryKey, FwSubKey.TE))
- {
- using (RegistryKey keyTE = FwRegistryHelper.FieldWorksRegistryKey.CreateSubKey(FwSubKey.TE))
- launchesTE = keyTE.GetValue("launches", "0") as string;
- }
- if (launchesFlex == "0" && launchesTE == "0")
- {
- FwRegistryHelper.FieldWorksRegistryKey.SetValue("MigrationTo7Needed", "true");
- }
- }
- else if (m_fVerboseDebug)
+ if (m_fVerboseDebug)
{
string msg = String.Format("Invalid version found in a registered COM DLL: {0} [{1}]",
version, dllPath);
- MessageBox.Show(msg, "DEBUG!");
+ Debug.WriteLine(msg, "DEBUG!");
}
return null;
}
@@ -525,7 +500,7 @@ private bool CallDbProgram(string args, string progressMsg, string errorMsgFmt)
{
using (var process = CreateAndInitProcess(m_dbPath, args))
{
- m_progressDlg.ProgressBarStyle = ProgressBarStyle.Marquee; // Can't get actual progress from external program
+ m_progressDlg.IsIndeterminate = true; // Can't get actual progress from external program
m_progressDlg.Title = Strings.ksConverting;
if (!(bool)m_progressDlg.RunTask(true, ProcessFile, process, progressMsg))
{
@@ -535,8 +510,7 @@ private bool CallDbProgram(string args, string progressMsg, string errorMsgFmt)
if (process.ExitCode != 0 || !string.IsNullOrEmpty(m_errorMessages))
{
var msg = string.Format(errorMsgFmt, process.ExitCode, m_errorMessages);
- MessageBoxUtils.Show(m_progressDlg.Form, msg, Strings.ksCannotConvert);
- return false;
+ throw new CannotConvertException(msg);
}
return true;
}
@@ -551,7 +525,7 @@ public bool DumpDatabaseAsXml(string dbName, string tempXmlPath, string progress
{
using (var process = CreateAndInitProcess(m_dumpxmlPath, "-d \"" + dbName + "\" -o \"" + tempXmlPath + '"'))
{
- m_progressDlg.ProgressBarStyle = ProgressBarStyle.Marquee; // Can't get actual progress from external program
+ m_progressDlg.IsIndeterminate = true; // Can't get actual progress from external program
m_progressDlg.Title = Strings.ksConverting;
if (!(bool)m_progressDlg.RunTask(true, ProcessFile, process, progressMsg))
{
@@ -561,8 +535,7 @@ public bool DumpDatabaseAsXml(string dbName, string tempXmlPath, string progress
if (process.ExitCode != 0 || !string.IsNullOrEmpty(m_errorMessages))
{
var msg = string.Format(errorMsgFmt, process.ExitCode, m_errorMessages);
- MessageBoxUtils.Show(m_progressDlg.Form, msg, Strings.ksCannotConvert);
- return false;
+ throw new CannotConvertException(msg);
}
return true;
}
@@ -663,11 +636,9 @@ public bool ImportFrom6_0Xml(string pathname, string folderName, string projectF
File.Delete(replacedProj);
File.Move(projectFile, replacedProj);
}
- using (var process = CreateAndInitProcess(
- Path.Combine(DirectoryFinder.FWCodeDirectory, "ConverterConsole.exe"),
- '"' + pathname + "\" \"" + projectFile + '"'))
+ using (var process = CreateAndInitProcess(m_converterConsolePath, '"' + pathname + "\" \"" + projectFile + '"'))
{
- m_progressDlg.ProgressBarStyle = ProgressBarStyle.Marquee; // Can't get actual progress from external program
+ m_progressDlg.IsIndeterminate = true; // Can't get actual progress from external program
m_progressDlg.Title = Strings.ksConverting;
string message = String.Format(Strings.ksConvertingFile, Path.GetFileNameWithoutExtension(projectFile));
if (!(bool)m_progressDlg.RunTask(true, ProcessFile, process, message))
@@ -678,19 +649,12 @@ public bool ImportFrom6_0Xml(string pathname, string folderName, string projectF
else if (process.ExitCode != 0 || !String.IsNullOrEmpty(m_errorMessages))
{
message = String.Format(Strings.ksConversionProcessFailed, process.ExitCode, m_errorMessages);
- // ENHANCE (TimS): We should not be showing a message box at this level. If we
- // really need to show it here, we should pass in the owning form instead of relying on
- // Form.ActiveForm since it can return null if no .Net forms have focus.
- MessageBoxUtils.Show(Form.ActiveForm, message, Strings.ksCannotConvert);
- retval = false;
+ BackOutCleanUp(projectFile, fCreateFolder, folderName, replacedProj);
+ throw new CannotConvertException(message);
}
if (retval == false)
{
- File.Delete(projectFile);
- if (fCreateFolder)
- Directory.Delete(folderName);
- else if (replacedProj != null)
- File.Move(replacedProj, projectFile);
+ BackOutCleanUp(projectFile, fCreateFolder, folderName, replacedProj);
}
else
{
@@ -715,6 +679,15 @@ public bool ImportFrom6_0Xml(string pathname, string folderName, string projectF
}
}
+ private void BackOutCleanUp(string projectFile, bool fCreateFolder, string folderName, string replacedProj)
+ {
+ File.Delete(projectFile);
+ if (fCreateFolder)
+ Directory.Delete(folderName);
+ else if (replacedProj != null)
+ File.Move(replacedProj, projectFile);
+ }
+
///
/// Create a process and initialize it according to our standard way of doing things.
///
@@ -806,4 +779,25 @@ void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
m_stdoutBldr.AppendLine(e.Data);
}
}
+
+ #region class CannotConvertException
+ /// ----------------------------------------------------------------------------------------
+ ///
+ /// Exception type to encapsulate a problem while running the conversion
+ ///
+ /// ----------------------------------------------------------------------------------------
+ public class CannotConvertException : Exception
+ {
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The message.
+ /// ------------------------------------------------------------------------------------
+ public CannotConvertException(string message)
+ : base(message)
+ {
+ }
+ }
+ #endregion
}
diff --git a/Src/FDO/DomainServices/DataStoreInitializationServices.cs b/Src/FDO/DomainServices/DataStoreInitializationServices.cs
index 6b47ab586a..e8f79b3fe4 100644
--- a/Src/FDO/DomainServices/DataStoreInitializationServices.cs
+++ b/Src/FDO/DomainServices/DataStoreInitializationServices.cs
@@ -379,7 +379,7 @@ private static void FixSegmentsForScriptureParas(FdoCache cache)
if (hadError)
{
// Tell the user that something bad happened
- ErrorReporter.ReportException(new Exception("Error during resegmentation"), null, null, null, false);
+ cache.ServiceLocator.GetInstance().ReportException(new Exception("Error during resegmentation"), false);
}
}
diff --git a/Src/FDO/DomainServices/Db4OServerFinder.cs b/Src/FDO/DomainServices/Db4OServerFinder.cs
index ad72db773c..7763f133f9 100644
--- a/Src/FDO/DomainServices/Db4OServerFinder.cs
+++ b/Src/FDO/DomainServices/Db4OServerFinder.cs
@@ -6,6 +6,7 @@
// Responsibility: FW Team
using System;
+using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Sockets;
using System.Threading;
@@ -18,6 +19,8 @@ namespace SIL.FieldWorks.FDO.DomainServices
/// In a separate thread, finds any DB4o servers on the network.
///
/// ----------------------------------------------------------------------------------------
+ [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
+ Justification = "m_hostListenerSocket is disposed when closed.")]
internal class Db4OServerFinder
{
#region Data members
@@ -26,10 +29,9 @@ internal class Db4OServerFinder
private readonly int HostDiscoveryBroadcastReplyPort = Db4OPorts.ReplyPort;
private readonly Thread m_hostListenerThread;
- private volatile Socket m_hostListenerSocket;
+ private Socket m_hostListenerSocket;
private readonly object m_syncRoot = new object();
private readonly Action m_foundServerCallback;
- private readonly Action m_onCompletedCallback;
#endregion
#region Constructor
@@ -39,12 +41,14 @@ internal class Db4OServerFinder
///
/// The method to call when a server is found
/// (string parameter is the IP address of the found server)
- /// Callback to run when the search is completed.
/// ------------------------------------------------------------------------------------
- public Db4OServerFinder(Action foundServerCallback, Action onCompletedCallback)
+ public Db4OServerFinder(Action foundServerCallback)
{
m_foundServerCallback = foundServerCallback;
- m_onCompletedCallback = onCompletedCallback;
+
+ m_hostListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) {Blocking = false};
+ EndPoint ep = new IPEndPoint(IPAddress.Any, HostDiscoveryBroadcastReplyPort);
+ m_hostListenerSocket.Bind(ep);
// Start the thread that collects responses from our broadcast.
m_hostListenerThread = new Thread(ThreadStartListenForServers);
@@ -63,11 +67,6 @@ public Db4OServerFinder(Action foundServerCallback, Action onCompletedCa
/// ------------------------------------------------------------------------------------
private void BroadcastToFindHosts()
{
- // Ensure the thread is listening before doing the broadcast
- // as it could return before we are listening for it.
- while (m_hostListenerThread.IsAlive && (m_hostListenerSocket == null || !m_hostListenerSocket.IsBound))
- Thread.Sleep(80);
-
// On Windows 7, this silently fails if the computer isn't connected to the network.
// On Windows XP, it eventually (after timeout?) throws a SocketException "A socket
// operation was attempted to an unreachable host".
@@ -76,11 +75,11 @@ private void BroadcastToFindHosts()
// Send the broadcast.
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
- sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
- EndPoint iep = new IPEndPoint(IPAddress.Broadcast, HostDiscoveryBroadcastPort);
+ sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
+ EndPoint iep = new IPEndPoint(IPAddress.Broadcast, HostDiscoveryBroadcastPort);
- sock.SendTo(new byte[] { 0 }, iep);
- }
+ sock.SendTo(new byte[] { 0 }, iep);
+ }
}
catch (SocketException)
{
@@ -96,54 +95,44 @@ private void BroadcastToFindHosts()
/// ------------------------------------------------------------------------------------
private void ThreadStartListenForServers()
{
- m_hostListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- try
- {
- m_hostListenerSocket.Blocking = false;
- EndPoint ep = new IPEndPoint(IPAddress.Any, HostDiscoveryBroadcastReplyPort);
try
{
- m_hostListenerSocket.Bind(ep);
- }
- catch (SocketException e)
- {
- MessageBoxUtils.Show(String.Format("Unable to bind to port {0} because {1}", HostDiscoveryBroadcastReplyPort, e));
- return;
- }
-
- byte[] data = new byte[1024];
- int cVainAttempts = 0;
- while (true) // keep listening until thread is killed.
- {
- int recv = 0;
- lock (m_syncRoot)
- {
- if (m_hostListenerSocket == null) // another thread can set this to null.
- break;
- if (m_hostListenerSocket.Available > 0)
- ExceptionHelper.LogAndIgnoreErrors(() => recv = m_hostListenerSocket.ReceiveFrom(data, ref ep));
- }
- if (recv > 0)
+ byte[] data = new byte[1024];
+ int cVainAttempts = 0;
+ while (true) // keep listening until thread is killed.
{
+ EndPoint ep = new IPEndPoint(IPAddress.Any, 0);
+ int recv = 0;
lock (m_syncRoot)
- m_foundServerCallback(((IPEndPoint)ep).Address.ToString());
- cVainAttempts = 0;
- }
- else
- {
- if (cVainAttempts++ > 50)
- break; // if no server has pinged us for 5 seconds, let's hang it up.
- Thread.Sleep(100);
+ {
+ if (m_hostListenerSocket == null) // another thread can set this to null.
+ break;
+ if (m_hostListenerSocket.Available > 0)
+ ExceptionHelper.LogAndIgnoreErrors(() => recv = m_hostListenerSocket.ReceiveFrom(data, ref ep));
+ }
+ if (recv > 0)
+ {
+ lock (m_syncRoot)
+ m_foundServerCallback(((IPEndPoint)ep).Address.ToString());
+ cVainAttempts = 0;
+ }
+ else
+ {
+ if (cVainAttempts++ > 50)
+ break; // if no server has pinged us for 5 seconds, let's hang it up.
+ Thread.Sleep(100);
+ }
}
}
-
- if (m_hostListenerSocket != null && m_onCompletedCallback != null)
- m_onCompletedCallback();
- }
finally
{
- CloseSocket();
+ CloseSocket();
+ }
}
+
+ public bool IsCompleted
+ {
+ get { return !m_hostListenerThread.IsAlive; }
}
/// ------------------------------------------------------------------------------------
diff --git a/Src/FDO/DomainServices/DomainObjectServices.cs b/Src/FDO/DomainServices/DomainObjectServices.cs
index af29dad57d..7f919a3734 100644
--- a/Src/FDO/DomainServices/DomainObjectServices.cs
+++ b/Src/FDO/DomainServices/DomainObjectServices.cs
@@ -17,7 +17,6 @@
using SIL.FieldWorks.FDO.Infrastructure;
using SILUBS.SharedScrUtils;
using SIL.CoreImpl;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainImpl;
namespace SIL.FieldWorks.FDO.DomainServices
@@ -30,36 +29,9 @@ public static class ScriptureServices
{
/// Book marker
public static readonly string kMarkerBook = @"\id";
- /// Delegate to report a non-fatal "warning" message
- private static Action ReportWarning;
internal const char kKeyTokenSeparator = '\uffff';
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes the class.
- ///
- /// ------------------------------------------------------------------------------------
- static ScriptureServices()
- {
- InitializeWarningHandler();
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Initializes the delegate for reporting warnings.
- ///
- /// This needs to be a separate method because it is called by reflection in
- /// test(s).
- /// ------------------------------------------------------------------------------------
- private static void InitializeWarningHandler()
- {
- ReportWarning = sMsg =>
- {
- ErrorReporter.ReportException(new Exception(sMsg), null, null, null, false);
- };
- }
-
/// ------------------------------------------------------------------------------------
///
/// Creates the import source key for a hashtable.
@@ -453,7 +425,8 @@ internal static void AdjustObjectsInArchivedBook(IScrBook book, IScrBook archive
ITsTextProps ttp;
ITsPropsBldr propsBldr;
int iFootnote = 0;
- var pictureRepo = book.Cache.ServiceLocator.GetInstance();
+ IFdoServiceLocator serviceLocator = book.Cache.ServiceLocator;
+ var pictureRepo = serviceLocator.GetInstance();
foreach (IScrTxtPara revPara in archivedBook.Paragraphs)
{
//TODO: TE-5082 Duplicate code! The following should call or use common code with
@@ -498,7 +471,7 @@ internal static void AdjustObjectsInArchivedBook(IScrBook book, IScrBook archive
BCVRef.MakeReferenceString(startRef, endRef, ":", "-") + " with guid " + guid +
" does not have a corresponding footnote object owned by " + book.BookId +
" or refers to a footnote that is owned by another ORC that occurs earlier.";
- ReportWarning(sMsg);
+ serviceLocator.GetInstance().ReportException(new Exception(sMsg), false);
break;
}
Logger.WriteEvent("Footnotes out of order in " + book.BookId + ". Expected footnote with guid " + guid +
@@ -552,7 +525,7 @@ internal static void AdjustObjectsInArchivedBook(IScrBook book, IScrBook archive
{
string sMsg = (archivedBook.FootnotesOS.Count - iFootnote) + " footnote(s) in " +
book.BookId + " did not correspond to any owned footnotes in the vernacular text of that book. They have been moved to the end of the footnote sequence.";
- ReportWarning(sMsg);
+ serviceLocator.GetInstance().ReportException(new Exception(sMsg), false);
}
}
@@ -2348,49 +2321,6 @@ public static ICmFile FindOrCreateFile(ICmFolder folder, string srcFile)
return cmFile;
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Copy source file to a unique file in FW\pictures directory.
- ///
- /// The path to the original filename (an internal copy will
- /// be made in this method)
- /// The subfolder of the FW Data directory in which the
- /// internal copy of the file should be created, if necessary (no backslashes needed)
- ///
- /// Destination file path, relative to the FW data directory, or ".__NONE__"
- /// if source file doesn't exist.
- ///
- /// ------------------------------------------------------------------------------------
- public static string CopyFileToInternal(string srcFilename, string dstSubdir)
- {
- string srcFilenameCorrected;
- if (!FileUtils.TrySimilarFileExists(srcFilename, out srcFilenameCorrected))
- return EmptyFileName;
-
- var strDestFolder = Path.Combine(DirectoryFinder.FWDataDirectory, dstSubdir);
- if (!Directory.Exists(strDestFolder))
- Directory.CreateDirectory(strDestFolder);
-
- var strDestFileRelPath = Path.Combine(dstSubdir, Path.GetFileName(srcFilenameCorrected));
- var strDestFileAbsPath = Path.Combine(DirectoryFinder.FWDataDirectory, strDestFileRelPath);
-
- // (The case-independent comparison is valid only for Microsoft Windows.)
- if (srcFilenameCorrected.Equals(strDestFileAbsPath, StringComparison.OrdinalIgnoreCase))
- return strDestFileRelPath; // don't copy files already in internal directory.
-
- var strFile = Path.GetFileNameWithoutExtension(srcFilenameCorrected);
- var strExt = Path.GetExtension(srcFilenameCorrected);
- var iQual = 0;
- while (FileUtils.FileExists(strDestFileAbsPath))
- {
- iQual++;
- strDestFileRelPath = Path.Combine(dstSubdir, strFile + iQual + strExt);
- strDestFileAbsPath = Path.Combine(DirectoryFinder.FWDataDirectory, strDestFileRelPath);
- }
- File.Copy(srcFilenameCorrected, strDestFileAbsPath);
- return strDestFileRelPath;
- }
-
/// ------------------------------------------------------------------------------------
///
/// Gets the empty name of the file.
diff --git a/Src/FDO/DomainServices/FontInfo.cs b/Src/FDO/DomainServices/FontInfo.cs
index e042781dbf..c7c27ac3fe 100644
--- a/Src/FDO/DomainServices/FontInfo.cs
+++ b/Src/FDO/DomainServices/FontInfo.cs
@@ -8,12 +8,8 @@
//
//
-using System;
using System.Drawing;
-using System.Text;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Resources;
-using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices
{
@@ -106,66 +102,6 @@ public bool IsAnyExplicit
}
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Returns a that represents the current
- /// . This method returns a human-readable
- /// string that is culture-sensitive
- ///
- ///
- /// A that represents the current
- /// .
- ///
- /// ------------------------------------------------------------------------------------
- public override string ToString()
- {
- return ToString(false);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Returns a that represents the current
- /// . This method returns a human-readable
- /// string that is culture-sensitive
- ///
- /// if set to true forces at least minimum
- /// description (i.e., font and size) to be returned.
- ///
- /// A that represents the current
- /// .
- ///
- /// ------------------------------------------------------------------------------------
- public string ToString(bool fForceMinimumDescription)
- {
- StringBuilder text = new StringBuilder();
-
- if (m_fontName.IsExplicit || fForceMinimumDescription)
- AppendToString(text, UIFontName);
-
- if (m_fontSize.IsExplicit || fForceMinimumDescription)
- AppendToString(text, string.Format(Strings.ksXPt, m_fontSize.Value / 1000));
-
- if (m_fontColor.IsExplicit || m_backColor.IsExplicit)
- AppendFontColor(text);
-
- if (m_underline.IsExplicit || m_underlineColor.IsExplicit)
- AppendUnderline(text);
-
- if (m_bold.IsExplicit)
- AppendToString(text, m_bold.Value ? Strings.ksBold : Strings.ksNotBold);
-
- if (m_italic.IsExplicit)
- AppendToString(text, m_italic.Value ? Strings.ksItalic : Strings.ksNotItalic);
-
- if (m_superSub.IsExplicit)
- AppendSuperSub(text, m_superSub.Value);
-
- if (m_offset.IsExplicit)
- AppendFontOffset(text, m_offset.Value);
-
- return text.ToString();
- }
-
/// ------------------------------------------------------------------------------------
///
/// Determines whether the specified is equal to the
@@ -228,190 +164,6 @@ public void SetAllDefaults()
m_underlineColor.SetDefaultValue(Color.Black);
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the name of the font or a UI-compatible (i.e., localizable) token to represent
- /// a magic font value.
- ///
- /// ------------------------------------------------------------------------------------
- public string UIFontName
- {
- get { return GetUIFontName(m_fontName.Value); }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the name of the UI font.
- ///
- /// Name of the font.
- ///
- /// ------------------------------------------------------------------------------------
- public static string GetUIFontName(string fontName)
- {
- if (fontName == StyleServices.DefaultFont)
- return ResourceHelper.GetResourceString("kstidDefaultFont");
- return fontName;
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets the internal font name for the given UI font.
- ///
- /// UI name of the font.
- /// Internal font name
- /// ------------------------------------------------------------------------------------
- public static string GetInternalFontName(string fontNameUI)
- {
- if (fontNameUI == ResourceHelper.GetResourceString("kstidDefaultFont"))
- return StyleServices.DefaultFont;
- return fontNameUI;
- }
-
- #region Helper methods and properties to build font description
- /// ------------------------------------------------------------------------------------
- ///
- /// Appends the font and background color information to the description
- ///
- /// The text.
- /// ------------------------------------------------------------------------------------
- private void AppendFontColor(StringBuilder text)
- {
- if (m_fontColor.IsInherited)
- AppendToString(text, String.Format(Strings.ksBackgroundIsX,
- ColorUtil.ColorToName(m_backColor.Value)));
- else if (m_backColor.IsInherited)
- AppendToString(text, String.Format(Strings.ksTextIsX,
- ColorUtil.ColorToName(m_fontColor.Value)));
- else
- AppendToString(text, string.Format(Strings.ksTextIsXonY,
- ColorUtil.ColorToName(m_fontColor.Value),
- ColorUtil.ColorToName(m_backColor.Value)));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Appends the underline information to the description.
- ///
- /// The text.
- /// ------------------------------------------------------------------------------------
- private void AppendUnderline(StringBuilder text)
- {
- string sUnder = "";
- if (m_underlineColor.IsExplicit)
- {
- string sColor = ColorUtil.ColorToName(m_underlineColor.Value);
- if (m_underline.IsExplicit)
- {
- switch (m_underline.Value)
- {
- case FwUnderlineType.kuntNone:
- sUnder = String.Format(Strings.ksNoColorUnderline, sColor);
- break;
- case FwUnderlineType.kuntSingle:
- sUnder = String.Format(Strings.ksSingleColorUnderline, sColor);
- break;
- case FwUnderlineType.kuntDouble:
- sUnder = String.Format(Strings.ksDoubleColorUnderline, sColor);
- break;
- case FwUnderlineType.kuntDotted:
- sUnder = String.Format(Strings.ksDottedColorUnderline, sColor);
- break;
- case FwUnderlineType.kuntDashed:
- sUnder = String.Format(Strings.ksDashedColorUnderline, sColor);
- break;
- case FwUnderlineType.kuntStrikethrough:
- sUnder = String.Format(Strings.ksColorStrikethrough, sColor);
- break;
- }
- }
- else
- {
- sUnder = String.Format(Strings.ksColorUnderline, sColor);
- }
- }
- else if (m_underline.IsExplicit)
- {
- switch (m_underline.Value)
- {
- case FwUnderlineType.kuntNone:
- sUnder = Strings.ksNoUnderline;
- break;
- case FwUnderlineType.kuntSingle:
- sUnder = Strings.ksSingleUnderline;
- break;
- case FwUnderlineType.kuntDouble:
- sUnder = Strings.ksDoubleUnderline;
- break;
- case FwUnderlineType.kuntDotted:
- sUnder = Strings.ksDottedUnderline;
- break;
- case FwUnderlineType.kuntDashed:
- sUnder = Strings.ksDashedUnderline;
- break;
- case FwUnderlineType.kuntStrikethrough:
- sUnder = Strings.ksStrikethrough;
- break;
- }
- }
- AppendToString(text, sUnder);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Appends the superscript/subscript information to the description
- ///
- /// The text.
- /// The superscript/subscript val.
- /// ------------------------------------------------------------------------------------
- private void AppendSuperSub(StringBuilder text, FwSuperscriptVal value)
- {
- switch (value)
- {
- case FwSuperscriptVal.kssvOff:
- AppendToString(text, Strings.ksNoSuperSubscript);
- break;
- case FwSuperscriptVal.kssvSub:
- AppendToString(text, Strings.ksSubscript);
- break;
- case FwSuperscriptVal.kssvSuper:
- AppendToString(text, Strings.ksSuperscript);
- break;
- }
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Appends the font offset information to the description
- ///
- /// The text.
- /// The value.
- /// ------------------------------------------------------------------------------------
- private void AppendFontOffset(StringBuilder text, int value)
- {
- if (value > 0)
- AppendToString(text, string.Format(Strings.ksRaisedXpt, value / 1000));
- else if (value < 0)
- AppendToString(text, string.Format(Strings.ksLoweredXpt, -value / 1000));
- else
- AppendToString(text, Strings.ksNotRaisedLowered);
-
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Appends to string.
- ///
- /// The text.
- /// The value.
- /// ------------------------------------------------------------------------------------
- private void AppendToString(StringBuilder text, string value)
- {
- if (text.Length > 0)
- text.Append(Strings.ksListSep);
- text.Append(value);
- }
- #endregion
-
/// Name of font to use
public IStyleProp FontName
{
diff --git a/Src/FDO/DomainServices/FwProjectFinder.cs b/Src/FDO/DomainServices/FwProjectFinder.cs
index 10db97dcc3..63f7e3a9e5 100644
--- a/Src/FDO/DomainServices/FwProjectFinder.cs
+++ b/Src/FDO/DomainServices/FwProjectFinder.cs
@@ -7,10 +7,7 @@
using System;
using System.IO;
-using System.Net;
using System.Threading;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.FieldWorks.Resources;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices
@@ -28,6 +25,7 @@ internal class FwProjectFinder
private readonly Action m_projectFoundCallback;
private readonly Action m_onCompletedCallback;
private volatile bool m_forceStop = false;
+ private readonly string m_projectsDir;
/// ------------------------------------------------------------------------------------
///
@@ -38,9 +36,10 @@ internal class FwProjectFinder
/// Callback to run when the search is completed.
/// The exception callback.
/// true if we want to show local fwdata projects
+ /// The projects directory.
/// ------------------------------------------------------------------------------------
public FwProjectFinder(string host, Action projectFoundCallback,
- Action onCompletedCallback, Action exceptionCallback, bool showLocalProjects)
+ Action onCompletedCallback, Action exceptionCallback, bool showLocalProjects, string projectsDir)
{
if (string.IsNullOrEmpty(host))
throw new ArgumentNullException("host");
@@ -52,6 +51,7 @@ public FwProjectFinder(string host, Action projectFoundCallback,
m_onCompletedCallback = onCompletedCallback;
m_exceptionCallback = exceptionCallback;
m_fShowLocalProjects = showLocalProjects;
+ m_projectsDir = projectsDir;
m_projectFinderThread = new Thread(FindProjects);
m_projectFinderThread.Name = "Project Finder";
@@ -75,21 +75,21 @@ private void FindProjects()
if (m_fShowLocalProjects)
{
// search sub dirs
- string[] dirs = Directory.GetDirectories(DirectoryFinder.ProjectsDirectory);
+ string[] dirs = Directory.GetDirectories(m_projectsDir);
foreach (string dir in dirs)
{
- string file = Path.Combine(dir, DirectoryFinder.GetXmlDataFileName(Path.GetFileName(dir)));
+ string file = Path.Combine(dir, FdoFileHelper.GetXmlDataFileName(Path.GetFileName(dir)));
if (FileUtils.SimilarFileExists(file))
m_projectFoundCallback(file);
else
{
- string db4oFile = Path.Combine(dir, DirectoryFinder.GetDb4oDataFileName(Path.GetFileName(dir)));
+ string db4oFile = Path.Combine(dir, FdoFileHelper.GetDb4oDataFileName(Path.GetFileName(dir)));
//If the db4o file exists it will be added to the list later and therefore we do not want to
//show the .bak file to the user in the open project dialog
if (!FileUtils.SimilarFileExists(db4oFile))
{
// See if there is a .bak file
- string backupFile = Path.ChangeExtension(file, FwFileExtensions.ksFwDataFallbackFileExtension);
+ string backupFile = Path.ChangeExtension(file, FdoFileHelper.ksFwDataFallbackFileExtension);
//NOTE: RickM I think this probably should be changed to TrySimilarFileExists but don't want to try this
//on a release build.
if (FileUtils.SimilarFileExists(backupFile))
diff --git a/Src/FDO/DomainServices/FwStyleSheet.cs b/Src/FDO/DomainServices/FwStyleSheet.cs
index 38441c9323..8517eb3d95 100644
--- a/Src/FDO/DomainServices/FwStyleSheet.cs
+++ b/Src/FDO/DomainServices/FwStyleSheet.cs
@@ -26,7 +26,6 @@
using System.Diagnostics;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.Application;
-using SIL.FieldWorks.Resources;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices
@@ -115,7 +114,7 @@ public class StyleInfoCollection : KeyedCollection
{
/// --------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// --------------------------------------------------------------------------------
public StyleInfoCollection()
@@ -152,6 +151,7 @@ protected override string GetKeyForItem(BaseStyleInfo item)
/// The field ID of the owner(m_hvoStylesOwner)'s collection of StStyles.
private int m_tagStylesList;
private FwStyleSheet m_styleSheetWithUiStyle;
+ private string m_defaultParaCharsStyleName;
/// Collection of styles
protected StyleInfoCollection m_StyleInfos;
@@ -184,7 +184,7 @@ private FwStyleSheet StyleSheetWithUiStyle
else
{
m_styleSheetWithUiStyle = new FwStyleSheet();
- m_styleSheetWithUiStyle.Init(Cache, Cache.LangProject.Hvo, LangProjectTags.kflidStyles);
+ m_styleSheetWithUiStyle.Init(Cache, Cache.LangProject.Hvo, LangProjectTags.kflidStyles, m_defaultParaCharsStyleName);
}
}
return m_styleSheetWithUiStyle;
@@ -259,19 +259,21 @@ public StyleInfoCollection Styles
#endregion
#region Constructor, Init, Load
- /// --------------------------------------------------------------------------------------------
- ///
- /// FwStyleSheet.Init() sets the FdoCache, the hvo of the owning object, and the tag
- /// specifying the owner's property which holds the collection of StStyle objects.
- /// Then the internal collections are loaded.
- ///
+
+ /// --------------------------------------------------------------------------------------------
+ ///
+ /// FwStyleSheet.Init() sets the FdoCache, the hvo of the owning object, and the tag
+ /// specifying the owner's property which holds the collection of StStyle objects.
+ /// Then the internal collections are loaded.
+ ///
///
- /// the FDO cache
- /// the owning object
- /// the owner(hvoStylesOwner)'s field ID which holds the collection
- /// of StStyle objects
+ /// the FDO cache
+ /// the owning object
+ /// the owner(hvoStylesOwner)'s field ID which holds the collection
+ /// of StStyle objects
+ /// The default paragraph characters style name.
/// --------------------------------------------------------------------------------------------
- public void Init(FdoCache cache, int hvoStylesOwner, int tagStylesList)
+ public void Init(FdoCache cache, int hvoStylesOwner, int tagStylesList, string defaultParaCharsStyleName)
{
m_fdoCache = cache;
m_hvoStylesOwner = hvoStylesOwner;
@@ -462,7 +464,7 @@ public int GetType(string sName)
if (style != null)
return (int)style.Type;
- if (sName == kstrDefaultCharStyle || sName == ResourceHelper.DefaultParaCharsStyleName)
+ if (sName == kstrDefaultCharStyle || sName == m_defaultParaCharsStyleName)
return (int)StyleType.kstCharacter;
return 0; //ThrowInternalError(E_INVALIDARG);
@@ -926,7 +928,7 @@ private LgCharRenderProps GetStyleChrps(string stylename, int ws, ILgWritingSyst
// that the property store does not implement IVwPropertyStore. See FWR-1918.
// Some more sophisticated trick may be needed if it is ever the case that the stylesheet
// is NOT created on the main UI thread.
- return m_fdoCache.ThreadHelper.Invoke(() => GetChrps(ws, ttp, wsf));
+ return m_fdoCache.ServiceLocator.GetInstance().SynchronizeInvoke.Invoke(() => GetChrps(ws, ttp, wsf));
}
/// ------------------------------------------------------------------------------------
@@ -992,10 +994,8 @@ public virtual IStStyle FindStyle(string name)
/// called for a style already known to exist in the stylesheet.
///
/// The style info table, containing 0 or more new styles
- /// Name of the application calling this (or whatever
- /// string you want to appear in a message box if we happen to show one).
/// ------------------------------------------------------------------------------------
- public void CheckForDuplicates(StyleInfoTable styleInfoTable, string applicationName)
+ public void CheckForDuplicates(StyleInfoTable styleInfoTable)
{
bool fStylesheetReloaded = false;
@@ -1022,11 +1022,10 @@ public void CheckForDuplicates(StyleInfoTable styleInfoTable, string application
basedOn.Structure != style.Structure ||
basedOn.Function != style.Function)
{
- string sMsg = string.Format(
- ResourceHelper.GetResourceString("kstidIncompatibleStyleExists"),
- style.Name);
- MessageBoxUtils.Show(sMsg, applicationName);
styleInfo.IsValid = false;
+ throw new IncompatibleStyleExistsException(string.Format(
+ Strings.ksIncompatibleStyleExists,
+ style.Name));
}
else
{
@@ -1583,4 +1582,18 @@ public override void Delete(int hvoStyle)
}
#endregion
}
+
+ ///
+ /// Exception for handling case when an incompatible style already exists
+ ///
+ public class IncompatibleStyleExistsException : Exception
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The message that describes the error.
+ public IncompatibleStyleExistsException(string message) : base(message)
+ {
+ }
+ }
}
diff --git a/Src/FDO/DomainServices/IScrImportFileInfo.cs b/Src/FDO/DomainServices/IScrImportFileInfo.cs
index 1691fa296a..5dcd066994 100644
--- a/Src/FDO/DomainServices/IScrImportFileInfo.cs
+++ b/Src/FDO/DomainServices/IScrImportFileInfo.cs
@@ -75,7 +75,7 @@ public interface IScrImportFileInfo
/// (only used for Note sources)
///
/// ------------------------------------------------------------------------------------
- SIL.FieldWorks.FDO.ICmAnnotationDefn NoteType { get; }
+ ICmAnnotationDefn NoteType { get; }
/// ------------------------------------------------------------------------------------
///
@@ -111,5 +111,18 @@ public interface IScrImportFileInfo
///
/// ------------------------------------------------------------------------------------
SILUBS.SharedScrUtils.ScrReference StartRef { get; }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Rechecks the accessibility of a file that might have been initially determined to
+ /// be inaccessible. If the file was inaccessible but is now accessible, it will be
+ /// properly initialized so all the cached info will be valid.
+ ///
+ /// Use to recheck accessibility of a file
+ /// that was initially determined to be accessible. Use to
+ /// access the cached value.
+ /// true if the file is currently accessible
+ /// ------------------------------------------------------------------------------------
+ bool RecheckAccessibility();
}
}
diff --git a/Src/FDO/DomainServices/ITextUtils.cs b/Src/FDO/DomainServices/ITextUtils.cs
index 077fac15a6..b32af534b9 100644
--- a/Src/FDO/DomainServices/ITextUtils.cs
+++ b/Src/FDO/DomainServices/ITextUtils.cs
@@ -10,7 +10,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.Common.ScriptureUtils;
using SIL.FieldWorks.FDO.DomainImpl;
diff --git a/Src/FDO/DomainServices/M3ModelExportServices.cs b/Src/FDO/DomainServices/M3ModelExportServices.cs
index dba93406f6..0d774a88f4 100644
--- a/Src/FDO/DomainServices/M3ModelExportServices.cs
+++ b/Src/FDO/DomainServices/M3ModelExportServices.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Practices.ServiceLocation;
@@ -51,9 +50,8 @@ public static void ExportGrammarSketch(string outputPath, ILangProject languageP
///
/// Export the grammar and lexicon.
///
- public static void ExportGrammarAndLexicon(string outputPath, ILangProject languageProject)
+ public static XDocument ExportGrammarAndLexicon(ILangProject languageProject)
{
- if (string.IsNullOrEmpty(outputPath)) throw new ArgumentNullException("outputPath");
if (languageProject == null) throw new ArgumentNullException("languageProject");
var servLoc = languageProject.Cache.ServiceLocator;
@@ -76,7 +74,7 @@ public static void ExportGrammarAndLexicon(string outputPath, ILangProject langu
ExportFeatureSystem(languageProject.PhFeatureSystemOA, "PhFeatureSystem", mode)
)
);
- doc.Save(outputPath);
+ return doc;
}
private static XElement ExportLanguageProject(ILangProject languageProject, Icu.UNormalizationMode mode)
@@ -127,12 +125,12 @@ static bool IsValidTemplate(IMoInflAffixTemplate template)
return
(from affixSlot in template.PrefixSlotsRS.Concat(template.SuffixSlotsRS)
where IsValidSlot(affixSlot)
- select affixSlot).Take(1).Count() > 0;
+ select affixSlot).Take(1).Any();
}
private static bool IsValidSlot(IMoInflAffixSlot affixSlot)
{
- return affixSlot.Affixes.Take(1).Count() > 0;
+ return affixSlot.Affixes.Take(1).Any();
}
@@ -316,7 +314,7 @@ private static XElement ExportLexiconFull(IServiceLocator servLoc, Icu.UNormaliz
{
return new XElement("Lexicon",
ExportEntries(servLoc.GetInstance()),
- ExportMSAs(servLoc),
+ ExportMsas(servLoc),
ExportSenses(servLoc.GetInstance(), mode),
ExportAllomorphs(servLoc, mode));
}
@@ -346,7 +344,7 @@ from lexEntryInflType in lexEntryRef.VariantEntryTypesRS
select ExportItemAsReference(lexEntryInflType, "LexEntryInflType"))));
}
- private static XElement ExportMSAs(IServiceLocator servLoc)
+ private static XElement ExportMsas(IServiceLocator servLoc)
{
return new XElement("MorphoSyntaxAnalyses",
from stemMsa in servLoc.GetInstance().AllInstances()
@@ -503,9 +501,9 @@ private static XElement ExportPhonRuleFeat(IPhPhonRuleFeat phonRuleFeat, Icu.UNo
private static XElement ExportPhonRule(IPhSegmentRule phonRule, Icu.UNormalizationMode mode)
{
- XElement retVal = null;
if (phonRule.Disabled)
- return retVal;
+ return null;
+ XElement retVal = null;
switch (phonRule.ClassName)
{
case "PhMetathesisRule":
@@ -930,10 +928,8 @@ from insertContent in insertPhones.ContentRS
///
/// Export everything needed by parsers for GAFAWS data.
///
- public static void ExportGafaws(string outputFolder, string databaseName, ICollection partsOfSpeech)
+ public static XDocument ExportGafaws(IEnumerable partsOfSpeech)
{
- if (string.IsNullOrEmpty(outputFolder)) throw new ArgumentNullException("outputFolder");
- if (string.IsNullOrEmpty(databaseName)) throw new ArgumentNullException("databaseName");
if (partsOfSpeech == null) throw new ArgumentNullException("partsOfSpeech");
var doc = new XDocument(
@@ -942,7 +938,7 @@ public static void ExportGafaws(string outputFolder, string databaseName, IColle
new XElement("PartsOfSpeech",
from IPartOfSpeech pos in partsOfSpeech
select ExportPartOfSpeechGafaws("PartOfSpeech", pos))));
- doc.Save(Path.Combine(outputFolder, databaseName + "GAFAWSFxtResult.xml"));
+ return doc;
}
///
diff --git a/Src/FDO/DomainServices/ProjectLockingService.cs b/Src/FDO/DomainServices/ProjectLockingService.cs
index 2d71ae15ec..037ab3b06d 100644
--- a/Src/FDO/DomainServices/ProjectLockingService.cs
+++ b/Src/FDO/DomainServices/ProjectLockingService.cs
@@ -17,12 +17,7 @@ public static void LockCurrentProject(FdoCache cache)
// Make sure any changes we want backup are saved.
var ds = cache.ServiceLocator.GetInstance() as XMLBackendProvider;
if (ds != null)
- {
- // REVIEW (EberhardB): I'm not sure this works as intended: XMLBackendProvider.LockProject
- // returns a FileStream, but XMLBackendProvider.UnlockProject works on a private
- // variable.
- using (XMLBackendProvider.LockProject(cache.ProjectId.Path)) { }
- }
+ ds.LockProject();
}
///
diff --git a/Src/FDO/DomainServices/ScrChecksDataSource.cs b/Src/FDO/DomainServices/ScrChecksDataSource.cs
index 654825328f..d6e2898fe7 100644
--- a/Src/FDO/DomainServices/ScrChecksDataSource.cs
+++ b/Src/FDO/DomainServices/ScrChecksDataSource.cs
@@ -13,7 +13,6 @@
using SIL.FieldWorks.Common.ScriptureUtils;
using SIL.Utils;
using SILUBS.SharedScrUtils;
-using SIL.FieldWorks.Resources;
using SIL.CoreImpl;
namespace SIL.FieldWorks.FDO.DomainServices
@@ -46,6 +45,8 @@ public class ScrChecksDataSource : IChecksDataSource
private readonly FdoCache m_cache;
private readonly IScripture m_scr;
private readonly string m_styleSheetFileName;
+ private readonly string m_punctWhitespaceChar;
+ private readonly string m_legacyOverridesFile;
private static StyleMarkupInfo s_styleMarkupInfo = null;
@@ -56,26 +57,32 @@ public class ScrChecksDataSource : IChecksDataSource
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The cache.
+ ///
+ ///
/// ------------------------------------------------------------------------------------
- public ScrChecksDataSource(FdoCache cache) : this(cache, null)
+ public ScrChecksDataSource(FdoCache cache, string punctWhitespaceChar, string legacyOverridesFile) : this(cache, punctWhitespaceChar, legacyOverridesFile, null)
{
}
/// ------------------------------------------------------------------------------------
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The cache.
+ ///
+ ///
/// Path to the stylesheet definition XML file
/// ------------------------------------------------------------------------------------
- public ScrChecksDataSource(FdoCache cache, string styleSheetFileName)
+ public ScrChecksDataSource(FdoCache cache, string punctWhitespaceChar, string legacyOverridesFile, string styleSheetFileName)
{
m_cache = cache;
m_scr = cache.LangProject.TranslatedScriptureOA;
+ m_punctWhitespaceChar = punctWhitespaceChar;
m_styleSheetFileName = styleSheetFileName;
+ m_legacyOverridesFile = legacyOverridesFile;
}
/// ------------------------------------------------------------------------------------
@@ -169,7 +176,7 @@ public string GetParameterValue(string key)
return "Intermediate";
case "PunctWhitespaceChar":
- return ResourceHelper.GetResourceString("kstidPunctCheckWhitespaceChar").Substring(0, 1);
+ return m_punctWhitespaceChar.Substring(0, 1);
case "MatchedPairs":
return ws.MatchedPairs;
@@ -698,7 +705,7 @@ private string GetValidCharactersList(string key, IWritingSystem ws)
return bldr.ToString();
}
- var validChars = ValidCharacters.Load(ws, LoadException ?? NoErrorReport);
+ var validChars = ValidCharacters.Load(ws, LoadException ?? NoErrorReport, m_legacyOverridesFile);
return (validChars != null ? validChars.SpaceDelimitedList : string.Empty);
}
@@ -713,7 +720,7 @@ private ValidCharacters ValidCharacters
{
// Get the writing system and valid characters list
return ValidCharacters.Load(m_cache.ServiceLocator.WritingSystemManager.Get(m_cache.DefaultVernWs),
- LoadException ?? NoErrorReport);
+ LoadException ?? NoErrorReport, m_legacyOverridesFile);
}
}
diff --git a/Src/FDO/DomainServices/ScrImportFileInfo.cs b/Src/FDO/DomainServices/ScrImportFileInfo.cs
index c483f7fb8f..498db95f43 100644
--- a/Src/FDO/DomainServices/ScrImportFileInfo.cs
+++ b/Src/FDO/DomainServices/ScrImportFileInfo.cs
@@ -495,7 +495,7 @@ protected virtual void GuessFileEncoding()
/// access the cached value.
/// true if the file is currently accessible
/// ------------------------------------------------------------------------------------
- internal bool RecheckAccessibility()
+ public bool RecheckAccessibility()
{
if (IsReadable)
return IsStillReadable;
diff --git a/Src/FDO/DomainServices/ScrMappingList.cs b/Src/FDO/DomainServices/ScrMappingList.cs
index 848a0daf95..d837fe44e2 100644
--- a/Src/FDO/DomainServices/ScrMappingList.cs
+++ b/Src/FDO/DomainServices/ScrMappingList.cs
@@ -11,9 +11,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Xml;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Resources;
using SIL.FieldWorks.Common.ScriptureUtils;
-using SIL.FieldWorks.Common.FwUtils;
namespace SIL.FieldWorks.FDO.DomainServices
{
@@ -32,6 +30,9 @@ public class ScrMappingList : IEnumerable
private IVwStylesheet m_stylesheet;
+ private readonly string m_defaultParaCharsStyleName;
+ private readonly string m_stylesPath;
+
private static Dictionary s_defaultMappings = new Dictionary();
private static Dictionary s_defaultProperties = new Dictionary();
private static Dictionary s_defaultExclusions = new Dictionary();
@@ -47,6 +48,7 @@ public class ScrMappingList : IEnumerable
#endregion
#region Constructor
+
/// ------------------------------------------------------------------------------------
///
/// Initializes a new instance of the class.
@@ -54,11 +56,16 @@ public class ScrMappingList : IEnumerable
/// Indicates which type of mapping group this list represents
///
/// The stylesheet
+ ///
+ ///
/// ------------------------------------------------------------------------------------
- public ScrMappingList(MappingSet mappingSet, IVwStylesheet stylesheet)
+ public ScrMappingList(MappingSet mappingSet, IVwStylesheet stylesheet, string defaultParaCharsStyleName,
+ string stylesPath)
{
m_mappingSet = mappingSet;
m_stylesheet = stylesheet;
+ m_defaultParaCharsStyleName = defaultParaCharsStyleName;
+ m_stylesPath = stylesPath;
}
#endregion
@@ -412,6 +419,7 @@ public IVwStylesheet StyleSheet
get { return m_stylesheet; }
set { m_stylesheet = value; }
}
+
#endregion
#region Private methods
@@ -422,10 +430,10 @@ public IVwStylesheet StyleSheet
/// ------------------------------------------------------------------------------------
[SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
Justification = "In .NET 4.5 XmlNodeList implements IDisposable, but not in 4.0.")]
- private static void ReadDefaultMappings()
+ private void ReadDefaultMappings()
{
XmlDocument doc = new XmlDocument();
- doc.Load(DirectoryFinder.TeStylesPath);
+ doc.Load(m_stylesPath);
XmlNode mappingNode = doc.SelectSingleNode("Styles/ImportMappingSets/ImportMapping[@name='TE Default']");
foreach (XmlNode mapNode in mappingNode.SelectNodes("mapping"))
{
@@ -520,12 +528,12 @@ private bool GetDefaultMapping(string marker, out string styleName, out bool exc
case "DefaultParagraphCharacters":
target = MappingTargetType.TEStyle;
- styleName = ResourceHelper.DefaultParaCharsStyleName;
+ styleName = m_defaultParaCharsStyleName;
return true;
case "DefaultFootnoteCharacters":
target = MappingTargetType.TEStyle;
- styleName = ResourceHelper.DefaultParaCharsStyleName;
+ styleName = m_defaultParaCharsStyleName;
markerDomain = MarkerDomain.Footnote;
return true;
}
diff --git a/Src/FDO/DomainServices/ScrSfFileList.cs b/Src/FDO/DomainServices/ScrSfFileList.cs
index 4d8ed4df0b..dfdab6233f 100644
--- a/Src/FDO/DomainServices/ScrSfFileList.cs
+++ b/Src/FDO/DomainServices/ScrSfFileList.cs
@@ -10,10 +10,8 @@
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
-using System.Windows.Forms;
using SIL.FieldWorks.Common.ScriptureUtils;
using SILUBS.SharedScrUtils;
-using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices
{
@@ -81,7 +79,6 @@ public class ScrSfFileList : ArrayList
/// An Overlapping File Resolver
/// ------------------------------------------------------------------------------------
public ScrSfFileList(IOverlappingFileResolver resolver)
- : base()
{
m_resolver = resolver;
}
@@ -99,13 +96,12 @@ public ScrSfFileList(IOverlappingFileResolver resolver)
/// in the middle of lines. (Toolbox dictates that fields tagged with backslash markers
/// must start on a new line, but Paratext considers all backslashes in the data to be
/// SF markers.)
- /// The path of the application help file.
/// ------------------------------------------------------------------------------------
public ScrSfFileList(IScrImportSFFiles source, ScrMappingList mappingList,
- ImportDomain importDomain, bool scanInlineBackslashMarkers, string helpFile)
+ ImportDomain importDomain, bool scanInlineBackslashMarkers)
: this(null)
{
- List deleteList = new List();
+ var deleteList = new List();
// Load the files into an in-memory list
foreach (ICmFile file in source.FilesOC)
{
@@ -117,8 +113,8 @@ public ScrSfFileList(IScrImportSFFiles source, ScrMappingList mappingList,
}
catch (ScriptureUtilsException e)
{
- MessageBoxUtils.Show(string.Format(ScrFdoResources.kstidImportBadFile, e.Message), "", MessageBoxButtons.OK,
- MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0, helpFile, HelpNavigator.Topic, e.HelpTopic);
+ var userAction = source.Services.GetInstance();
+ userAction.DisplayMessage(MessageType.Error, string.Format(ScrFdoResources.kstidImportBadFile, e.Message), Strings.ksErrorCaption, e.HelpTopic);
deleteList.Add(file);
}
}
diff --git a/Src/FDO/DomainServices/SharedBackendServices.cs b/Src/FDO/DomainServices/SharedBackendServices.cs
new file mode 100644
index 0000000000..34a56fbd36
--- /dev/null
+++ b/Src/FDO/DomainServices/SharedBackendServices.cs
@@ -0,0 +1,26 @@
+// Copyright (c) 2013-2014 SIL International
+// This software is licensed under the LGPL, version 2.1 or later
+// (http://www.gnu.org/licenses/lgpl-2.1.html)
+
+using SIL.FieldWorks.FDO.Infrastructure;
+using SIL.FieldWorks.FDO.Infrastructure.Impl;
+
+namespace SIL.FieldWorks.FDO.DomainServices
+{
+ ///
+ /// Services for shared backends
+ ///
+ public static class SharedBackendServices
+ {
+ ///
+ /// Indicates if there are multiple applications that are currently using this project.
+ ///
+ public static bool AreMultipleApplicationsConnected(FdoCache cache)
+ {
+ var sharedBep = cache.ServiceLocator.GetInstance() as SharedXMLBackendProvider;
+ if (sharedBep != null)
+ return sharedBep.OtherApplicationsConnectedCount > 0;
+ return false;
+ }
+ }
+}
diff --git a/Src/FDO/DomainServices/StTxtParaBldr.cs b/Src/FDO/DomainServices/StTxtParaBldr.cs
index 395bff7780..2505060f77 100644
--- a/Src/FDO/DomainServices/StTxtParaBldr.cs
+++ b/Src/FDO/DomainServices/StTxtParaBldr.cs
@@ -10,10 +10,7 @@
//
using System;
-using System.Runtime.InteropServices; // needed for Marshal
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
-using SIL.Utils;
using SIL.CoreImpl;
namespace SIL.FieldWorks.FDO.DomainServices
diff --git a/Src/FDO/DomainServices/StringServices.cs b/Src/FDO/DomainServices/StringServices.cs
index d32db086fc..af750c07f1 100644
--- a/Src/FDO/DomainServices/StringServices.cs
+++ b/Src/FDO/DomainServices/StringServices.cs
@@ -11,7 +11,6 @@
using System.Xml;
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Application;
using SIL.FieldWorks.FDO.DomainImpl;
using SIL.FieldWorks.FDO.Infrastructure;
@@ -74,7 +73,7 @@ public static void MarkTextInBldrAsHyperlink(ITsStrBldr strBldr, int ichStart,
public static string MarkTextInBldrAsHyperlink(ITsStrBldr strBldr, int ichStart,
int ichLim, string url, IStStyle linkStyle, string linkedFilesRootDir)
{
- var relativeUrl = DirectoryFinderRelativePaths.GetRelativeLinkedFilesPath(url, linkedFilesRootDir);
+ var relativeUrl = LinkedFilesRelativePathHelper.GetRelativeLinkedFilesPath(url, linkedFilesRootDir);
if (string.IsNullOrEmpty(relativeUrl))
{
MarkTextInBldrAsHyperlink(strBldr, ichStart, ichLim, url, linkStyle);
diff --git a/Src/FDO/DomainServices/ValidCharacters.cs b/Src/FDO/DomainServices/ValidCharacters.cs
index 25dc4f25e0..1c112e600f 100644
--- a/Src/FDO/DomainServices/ValidCharacters.cs
+++ b/Src/FDO/DomainServices/ValidCharacters.cs
@@ -7,13 +7,11 @@
using System;
using System.Collections.Generic;
-using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.IO;
using System.Xml;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.Utils;
using System.Xml.Serialization;
using SIL.CoreImpl;
@@ -93,6 +91,7 @@ public class ValidCharacters
private List m_OtherCharacters;
private ILgCharacterPropertyEngine m_cpe;
private TsStringComparer m_comparer;
+ private string m_legacyOverridesFile;
#endregion
@@ -119,6 +118,7 @@ protected ValidCharacters()
}
#region Methods and Properties to load and initialize the class
+
/// ------------------------------------------------------------------------------------
///
/// Loads the valid characters from the specified language definition into a new
@@ -127,13 +127,14 @@ protected ValidCharacters()
/// The writing system.
/// The exception handler to use if valid character data
/// cannot be loaded.
+ ///
/// A initialized with the valid characters data
/// from the language definition.
/// ------------------------------------------------------------------------------------
- public static ValidCharacters Load(IWritingSystem ws, LoadExceptionDelegate exceptionHandler)
+ public static ValidCharacters Load(IWritingSystem ws, LoadExceptionDelegate exceptionHandler, string legacyOverridesFile)
{
ValidCharacters validChars = Load(ws.ValidChars, ws.DisplayLabel, ws,
- exceptionHandler);
+ exceptionHandler, legacyOverridesFile);
if (validChars != null)
validChars.InitSortComparer(ws);
@@ -150,10 +151,11 @@ public static ValidCharacters Load(IWritingSystem ws, LoadExceptionDelegate exce
/// The writing system
/// The exception handler to use if valid character data
/// cannot be loaded.
+ ///
///
/// ------------------------------------------------------------------------------------
public static ValidCharacters Load(string xmlSrc, string wsName,
- IWritingSystem ws, LoadExceptionDelegate exceptionHandler)
+ IWritingSystem ws, LoadExceptionDelegate exceptionHandler, string legacyOverridesFile)
{
Exception e;
var validChars = XmlSerializationHelper.DeserializeFromString(xmlSrc, out e);
@@ -161,7 +163,9 @@ public static ValidCharacters Load(string xmlSrc, string wsName,
bool fTryOldStyleList = false;
if (validChars != null)
+ {
validChars.LoadException += exceptionHandler;
+ }
else
{
validChars = new ValidCharacters();
@@ -171,14 +175,14 @@ public static ValidCharacters Load(string xmlSrc, string wsName,
if (!fTryOldStyleList && !String.IsNullOrEmpty(xmlSrc))
{
var bldr = new StringBuilder();
- bldr.AppendFormat("Invalid ValidChars field while loading the {0} writing system:",
- wsName);
+ bldr.AppendFormat("Invalid ValidChars field while loading the {0} writing system:", wsName);
bldr.Append(Environment.NewLine);
bldr.Append("\t");
bldr.Append(xmlSrc);
validChars.ReportError(new ArgumentException(bldr.ToString(), "xmlSrc", e));
}
}
+ validChars.m_legacyOverridesFile = legacyOverridesFile;
List invalidChars = validChars.Init();
@@ -284,15 +288,13 @@ private List Init()
/// Gets the default word forming overrides.
///
/// ------------------------------------------------------------------------------------
- private static IEnumerable DefaultWordFormingOverrides
+ private IEnumerable DefaultWordFormingOverrides
{
get
{
if (s_fTestingMode)
return s_defaultWordformingChars;
- string legacyOverrides = Path.Combine(DirectoryFinder.FWCodeDirectory,
- "WordFormingCharOverrides.xml");
- return ParseLegacyWordFormingCharOverrides(legacyOverrides) ??
+ return ParseLegacyWordFormingCharOverrides(m_legacyOverridesFile) ??
(IEnumerable)s_defaultWordformingChars;
}
}
diff --git a/Src/FDO/DomainServices/WfiWordformServices.cs b/Src/FDO/DomainServices/WfiWordformServices.cs
index 8a7edfe56d..105441a609 100644
--- a/Src/FDO/DomainServices/WfiWordformServices.cs
+++ b/Src/FDO/DomainServices/WfiWordformServices.cs
@@ -12,12 +12,10 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
-using System.Windows.Forms;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.CoreImpl;
using SIL.FieldWorks.FDO.DomainImpl;
-using Sharpen.Util;
+using SIL.Utils;
namespace SIL.FieldWorks.FDO.DomainServices
{
@@ -202,7 +200,7 @@ public static IPunctuationForm FindOrCreatePunctuationform(FdoCache cache, ITsSt
///
///
/// A string containing a list of wordforms that could not be merged because they have differing values for other WSs
- public static string FixDuplicates(FdoCache cache, ProgressBar progressBar)
+ public static string FixDuplicates(FdoCache cache, IProgress progressBar)
{
var failures = new HashSet();
var wfRepo = cache.ServiceLocator.GetInstance();
@@ -210,10 +208,10 @@ public static string FixDuplicates(FdoCache cache, ProgressBar progressBar)
var wfiWordforms = wfRepo.AllInstances().ToArray();
progressBar.Minimum = 0;
progressBar.Maximum = wfiWordforms.Length;
- progressBar.Step = 1;
+ progressBar.StepSize = 1;
foreach (var wf in wfiWordforms)
{
- progressBar.PerformStep();
+ progressBar.Step(1);
var text = wf.Form.VernacularDefaultWritingSystem.Text;
if (string.IsNullOrEmpty(text))
continue;
@@ -284,15 +282,15 @@ public static string FixDuplicates(FdoCache cache, ProgressBar progressBar)
/// Merge duplicate analyses on all wordforms. (Also merges duplicate WfiGlosses.)
///
///
- public static void MergeDuplicateAnalyses(FdoCache cache, ProgressBar progressBar)
+ public static void MergeDuplicateAnalyses(FdoCache cache, IProgress progressBar)
{
var wfiWordforms = cache.ServiceLocator.GetInstance().AllInstances().ToList();
progressBar.Minimum = 0;
progressBar.Maximum = wfiWordforms.Count;
- progressBar.Step = 1;
+ progressBar.StepSize = 1;
foreach (var wf in wfiWordforms)
{
- progressBar.PerformStep();
+ progressBar.Step(1);
var analyses = wf.AnalysesOC.ToList();
for (int i = 0; i < analyses.Count; i++)
{
diff --git a/Src/FDO/DomainServices/WritingSystemServices.cs b/Src/FDO/DomainServices/WritingSystemServices.cs
index 6f8a989890..af76ddff45 100644
--- a/Src/FDO/DomainServices/WritingSystemServices.cs
+++ b/Src/FDO/DomainServices/WritingSystemServices.cs
@@ -1329,12 +1329,13 @@ private static List AnalysisVernacularWss(FdoCache cache, bool f
/// to the requested collection(s).
///
/// The cache.
+ /// The template directory.
/// The identifier.
/// if set to true ***new*** writing systems will be added to the list of analysis writing systems.
/// if set to true ***new*** writing systems will be added to the list of vernacular writing systems.
/// The writing system.
/// true if the writing system already exists, false if it had to be created
- public static bool FindOrCreateWritingSystem(FdoCache cache, string identifier, bool addAnalWss, bool addVernWss, out IWritingSystem ws)
+ public static bool FindOrCreateWritingSystem(FdoCache cache, string templateDir, string identifier, bool addAnalWss, bool addVernWss, out IWritingSystem ws)
{
if (cache.ServiceLocator.WritingSystemManager.GetOrSet(identifier, out ws))
return true;
@@ -1346,7 +1347,8 @@ public static bool FindOrCreateWritingSystem(FdoCache cache, string identifier,
// If the new writing system is one for which we have localized versions of lists, import them.
// We can't easily put up a progress dialog here, because the code is in a project we can't reference.
// However this routine is used in relatively long operations anyway so there should already be some kind of progress bar.
- XmlTranslatedLists.ImportTranslatedListsForWs(identifier, cache, null);
+ if (templateDir != null)
+ XmlTranslatedLists.ImportTranslatedListsForWs(identifier, cache, templateDir, null);
return false;
}
@@ -1357,7 +1359,7 @@ public static bool FindOrCreateWritingSystem(FdoCache cache, string identifier,
/// systems if the appropriate flag is set.
///
/// true if the writing system already exists, false if it had to be created
- public static bool FindOrCreateSomeWritingSystem(FdoCache cache, string identifier, bool addAnalWss, bool addVernWss, out IWritingSystem ws)
+ public static bool FindOrCreateSomeWritingSystem(FdoCache cache, string templateDir, string identifier, bool addAnalWss, bool addVernWss, out IWritingSystem ws)
{
if (cache.ServiceLocator.WritingSystemManager.TryGet(identifier, out ws))
return true;
@@ -1368,12 +1370,12 @@ public static bool FindOrCreateSomeWritingSystem(FdoCache cache, string identifi
if (LangTagUtils.GetSubtags(identifier, out languageSubtag, out scriptSubtag, out regionSubtag, out variantSubtag))
{
// It's a good identifier; we can do this straightforwardly.
- return FindOrCreateWritingSystem(cache, identifier, addAnalWss, addVernWss, out ws);
+ return FindOrCreateWritingSystem(cache, templateDir, identifier, addAnalWss, addVernWss, out ws);
}
// See if we can convert an old-style identifier to a new one.
string newIdentifier = LangTagUtils.ToLangTag(identifier);
if (LangTagUtils.GetSubtags(identifier, out languageSubtag, out scriptSubtag, out regionSubtag, out variantSubtag))
- return FindOrCreateWritingSystem(cache, newIdentifier, addAnalWss, addVernWss, out ws);
+ return FindOrCreateWritingSystem(cache, templateDir, newIdentifier, addAnalWss, addVernWss, out ws);
// No, it's nothing we know how to deal with. Get drastic.
@@ -1392,7 +1394,7 @@ public static bool FindOrCreateSomeWritingSystem(FdoCache cache, string identifi
parts = new [] {"qaa"}.Concat(parts); // Can't start with x, we always use qaa for unknown WS.
newIdentifier = parts.Aggregate((first, second) => first + "-" + second);
// This should now qualify as a private-use writing system identifier.
- return FindOrCreateWritingSystem(cache, newIdentifier, addAnalWss, addVernWss, out ws);
+ return FindOrCreateWritingSystem(cache, templateDir, newIdentifier, addAnalWss, addVernWss, out ws);
}
///
diff --git a/Src/FDO/FDO.csproj b/Src/FDO/FDO.csproj
index c2167a033f..904b7ff3b8 100644
--- a/Src/FDO/FDO.csproj
+++ b/Src/FDO/FDO.csproj
@@ -90,8 +90,9 @@
..\..\Output\Debug\BasicUtils.dll
-
- ..\..\Output\Debug\FwResources.dll
+
+ False
+ ..\..\Output\Debug\protobuf-net.dll
@@ -106,30 +107,17 @@
COMInterfaces
..\..\Output\Debug\COMInterfaces.dll
-
- Microsoft.VisualBasic
-
PhonEnvValidator
..\..\Output\Debug\PhonEnvValidator.dll
-
- System.Data
-
System.Drawing
-
- System.Windows.Forms
-
System.XML
-
- False
- ..\..\DistFiles\Utilities.dll
-
XMLUtils
..\..\Output\Debug\XMLUtils.dll
@@ -146,12 +134,6 @@
..\..\Output\Debug\Db4objects.Db4o.Linq.dll
-
- ..\..\Output\Debug\ECInterfaces.dll
-
-
- ..\..\Output\Debug\FwUtils.dll
-
..\..\Lib\debug\ICSharpCode.SharpZipLib.dll
@@ -161,24 +143,15 @@
..\..\DistFiles\Microsoft.Practices.ServiceLocation.dll
-
- ..\..\DistFiles\ParatextShared.dll
-
..\..\Output\Debug\PhraseTranslationHelper.dll
-
- ..\..\Output\Debug\Reporting.dll
-
..\..\Output\Debug\ScrUtilsInterfaces.dll
..\..\Output\Debug\SharedScrUtils.dll
-
- ..\..\Output\Debug\SilEncConverters40.dll
-
..\..\DistFiles\StructureMap.dll
@@ -188,15 +161,6 @@
..\..\Output\Debug\SilUtils.dll
-
- ..\..\DistFiles\Tamir.SharpSSH.dll
-
-
- ..\..\Output\Debug\xCoreInterfaces.dll
-
-
- ..\..\Output\Debug\ZipUtils.dll
-
@@ -216,6 +180,13 @@
+
+
+
+
+
+
+
@@ -234,30 +205,12 @@
-
- Form
-
-
- CantRestoreLinkedFilesToOriginalLocation.cs
-
-
- Form
-
-
- FilesToRestoreAreOlder.cs
-
Code
-
- Form
-
-
- RestoreLinkedFilesToProjectsFolder.cs
-
@@ -313,17 +266,10 @@
-
- Form
-
-
- FWVersionTooOld.cs
-
-
@@ -364,7 +310,6 @@
-
@@ -417,6 +362,13 @@
+
+
+
+
+
+
+
@@ -425,18 +377,6 @@
-
- Form
-
-
- ConflictingSaveDlg.cs
-
-
- Form
-
-
- ConnectionLostDlg.cs
-
@@ -450,7 +390,6 @@
-
@@ -557,35 +496,11 @@
AppStrings.Designer.cs
Designer
-
- CantRestoreLinkedFilesToOriginalLocation.cs
- Designer
-
-
- FilesToRestoreAreOlder.cs
- Designer
-
-
- RestoreLinkedFilesToProjectsFolder.cs
- Designer
-
-
- FWVersionTooOld.cs
- Designer
-
PublicResXFileCodeGenerator
ScrFdoResources.Designer.cs
Designer
-
- ConflictingSaveDlg.cs
- Designer
-
-
- ConnectionLostDlg.cs
- Designer
-
ResXFileCodeGenerator
Resources.Designer.cs
@@ -627,7 +542,6 @@
-
diff --git a/Src/FDO/FDOGenerate/Interfaces.vm.cs b/Src/FDO/FDOGenerate/Interfaces.vm.cs
index 47ff469d24..f558fe897c 100644
--- a/Src/FDO/FDOGenerate/Interfaces.vm.cs
+++ b/Src/FDO/FDOGenerate/Interfaces.vm.cs
@@ -10,7 +10,7 @@
//This is automatically generated by FDOGenerate task. ****Do not edit****
using System;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
+using SIL.CoreImpl;
namespace SIL.FieldWorks.FDO // All generated class interfaces are in here.
{
diff --git a/Src/FDO/FDOGenerate/main.vm.cs b/Src/FDO/FDOGenerate/main.vm.cs
index b45c5dbde3..29bfbce333 100644
--- a/Src/FDO/FDOGenerate/main.vm.cs
+++ b/Src/FDO/FDOGenerate/main.vm.cs
@@ -16,7 +16,6 @@
using System.Xml.Linq;
using System.Linq;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.CoreImpl;
using SIL.Utils;
using SIL.FieldWorks.FDO.Infrastructure;
diff --git a/Src/FDO/FDOTests/BackupRestore/BackupFileRepositoryTests.cs b/Src/FDO/FDOTests/BackupRestore/BackupFileRepositoryTests.cs
index 79593442a8..2bfcad79cc 100644
--- a/Src/FDO/FDOTests/BackupRestore/BackupFileRepositoryTests.cs
+++ b/Src/FDO/FDOTests/BackupRestore/BackupFileRepositoryTests.cs
@@ -12,8 +12,6 @@
using NUnit.Framework;
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.BackupRestore;
-using SIL.FieldWorks.FDO.Infrastructure;
-using SIL.FieldWorks.Resources;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
@@ -66,9 +64,9 @@ public void Teardown()
[Test]
public void NoBackupFilesAvailable()
{
- m_fileOs.ExistingDirectories.Add(DirectoryFinder.DefaultBackupDirectory);
+ m_fileOs.ExistingDirectories.Add(FwDirectoryFinder.DefaultBackupDirectory);
- BackupFileRepository repo = new BackupFileRepository();
+ BackupFileRepository repo = new BackupFileRepository(FwDirectoryFinder.DefaultBackupDirectory);
Assert.AreEqual(0, repo.AvailableProjectNames.Count());
Assert.Throws(typeof(KeyNotFoundException), () => repo.GetAvailableVersions("monkey"));
Assert.Throws(typeof(KeyNotFoundException), () => repo.GetBackupFile("monkey", DateTime.Now, false));
@@ -93,7 +91,7 @@ public void BackupsForSingleProjectExists()
string backupFileName2 = backupSettings.ZipFileName;
m_fileOs.AddExistingFile(backupFileName2);
- BackupFileRepository repo = new BackupFileRepository();
+ BackupFileRepository repo = new BackupFileRepository(FwDirectoryFinder.DefaultBackupDirectory);
Assert.AreEqual(1, repo.AvailableProjectNames.Count());
Assert.AreEqual(2, repo.GetAvailableVersions("Floozy").Count());
Assert.AreEqual(backupFileName2, repo.GetBackupFile("Floozy", backupSettings.BackupTime, false).File);
@@ -122,7 +120,7 @@ public void InavlidBackupFile()
string backupFileName2 = backupSettings.ZipFileName;
m_fileOs.AddExistingFile(backupFileName2);
- BackupFileRepository repo = new BackupFileRepository();
+ BackupFileRepository repo = new BackupFileRepository(FwDirectoryFinder.DefaultBackupDirectory);
BackupFileSettings invalidFileSettings = repo.GetMostRecentBackup("Floozy");
BackupFileSettings validFileSettings = repo.GetBackupFile("Floozy", backupSettings.BackupTime, false);
ReflectionHelper.SetProperty(validFileSettings, "ProjectName", "Floozy"); // Force it to think it's already loaded and happy.
@@ -158,7 +156,7 @@ public void BackupsForMultipleProjects()
string backupFileName3 = backupSettings.ZipFileName;
m_fileOs.AddExistingFile(backupFileName3);
- BackupFileRepository repo = new BackupFileRepository();
+ BackupFileRepository repo = new BackupFileRepository(FwDirectoryFinder.DefaultBackupDirectory);
Assert.AreEqual(2, repo.AvailableProjectNames.Count());
Assert.AreEqual(2, repo.GetAvailableVersions("AAA").Count());
Assert.AreEqual(1, repo.GetAvailableVersions("ZZZ").Count());
@@ -184,11 +182,11 @@ public void BackupHasOldStyleDatetimeFormat()
{
DummyBackupProjectSettings backupSettings = new DummyBackupProjectSettings("monkey",
"Floozy", null, FDOBackendProviderType.kXML);
- string backupFileName1 = Path.Combine(DirectoryFinder.DefaultBackupDirectory,
- Path.ChangeExtension("Floozy 2010-8-21-0506", FwFileExtensions.ksFwBackupFileExtension));
+ string backupFileName1 = Path.Combine(FwDirectoryFinder.DefaultBackupDirectory,
+ Path.ChangeExtension("Floozy 2010-8-21-0506", FdoFileHelper.ksFwBackupFileExtension));
m_fileOs.AddExistingFile(backupFileName1);
- BackupFileRepository repo = new BackupFileRepository();
+ BackupFileRepository repo = new BackupFileRepository(FwDirectoryFinder.DefaultBackupDirectory);
Assert.AreEqual(1, repo.AvailableProjectNames.Count());
Assert.AreEqual(1, repo.GetAvailableVersions("Floozy").Count());
Assert.AreEqual(backupFileName1, repo.GetMostRecentBackup("Floozy").File);
diff --git a/Src/FDO/FDOTests/BackupRestore/BackupRestoreSettingsTests.cs b/Src/FDO/FDOTests/BackupRestore/BackupRestoreSettingsTests.cs
index 1ae1199cc5..5997f0afbc 100644
--- a/Src/FDO/FDOTests/BackupRestore/BackupRestoreSettingsTests.cs
+++ b/Src/FDO/FDOTests/BackupRestore/BackupRestoreSettingsTests.cs
@@ -11,9 +11,6 @@
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.BackupRestore;
-using SIL.FieldWorks.FDO.Infrastructure;
-using SIL.FieldWorks.Resources;
-using SIL.Utils;
namespace SIL.FieldWorks.FDO.FDOTests.BackupRestore
{
@@ -33,7 +30,7 @@ internal class DummyBackupProjectSettings : BackupProjectSettings
/// ------------------------------------------------------------------------------------
internal DummyBackupProjectSettings(string projectsRootFolder, string projectName, string linkedFilesRootDir,
FDOBackendProviderType originalProjType) :
- base(projectsRootFolder, projectName, linkedFilesRootDir, null, originalProjType)
+ base(projectsRootFolder, projectName, linkedFilesRootDir, null, originalProjType, FwDirectoryFinder.DefaultBackupDirectory)
{
}
}
@@ -53,7 +50,7 @@ public class BackupRestoreSettingsTests : MemoryOnlyBackendProviderBasicTestBase
[Test]
public void DefaultRestoreSettings()
{
- var settings = new RestoreProjectSettings();
+ var settings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory);
Assert.IsNull(settings.Backup);
Assert.True(string.IsNullOrEmpty(settings.ProjectName));
@@ -73,13 +70,13 @@ public void DefaultRestoreSettings()
[Test]
public void RestoreProjectSettings_VerifyExistenceOfProject()
{
- string restoreTestsZipFileDir = Path.Combine(DirectoryFinder.FwSourceDirectory,
+ string restoreTestsZipFileDir = Path.Combine(FwDirectoryFinder.SourceDirectory,
"FDO/FDOTests/BackupRestore/RestoreServiceTestsZipFileDir");
- RestoreProjectSettings restoreSettings = new RestoreProjectSettings()
+ RestoreProjectSettings restoreSettings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory)
{
Backup = new BackupFileSettings(Path.Combine(restoreTestsZipFileDir,
- Path.ChangeExtension("TestRestoreFWProject", FwFileExtensions.ksFwBackupFileExtension))),
+ Path.ChangeExtension("TestRestoreFWProject", FdoFileHelper.ksFwBackupFileExtension))),
IncludeConfigurationSettings = false,
IncludeLinkedFiles = false,
IncludeSupportingFiles = true,
@@ -89,7 +86,8 @@ public void RestoreProjectSettings_VerifyExistenceOfProject()
};
ProjectRestoreServiceTests.RemoveAnyFilesAndFoldersCreatedByTests(restoreSettings);
- ProjectRestoreService restoreProjectService = new ProjectRestoreService(restoreSettings);
+ ProjectRestoreService restoreProjectService = new ProjectRestoreService(restoreSettings, new DummyFdoUI(),
+ FwDirectoryFinder.ConverterConsoleExe, FwDirectoryFinder.DbExe);
Assert.False(restoreSettings.ProjectExists, "Project exists but it should not.");
@@ -113,13 +111,13 @@ public void RestoreProjectSettings_VerifyExistenceOfProject()
[Test]
public void RestoreProjectSettings_VerifyExistenceOfHgRepo()
{
- string restoreTestsZipFileDir = Path.Combine(DirectoryFinder.FwSourceDirectory,
+ string restoreTestsZipFileDir = Path.Combine(FwDirectoryFinder.SourceDirectory,
"FDO/FDOTests/BackupRestore/RestoreServiceTestsZipFileDir");
- RestoreProjectSettings restoreSettings = new RestoreProjectSettings()
+ RestoreProjectSettings restoreSettings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory)
{
Backup = new BackupFileSettings(Path.Combine(restoreTestsZipFileDir,
- Path.ChangeExtension("TestRestoreFWProject", FwFileExtensions.ksFwBackupFileExtension))),
+ Path.ChangeExtension("TestRestoreFWProject", FdoFileHelper.ksFwBackupFileExtension))),
IncludeConfigurationSettings = false,
IncludeLinkedFiles = false,
IncludeSupportingFiles = true,
@@ -128,7 +126,8 @@ public void RestoreProjectSettings_VerifyExistenceOfHgRepo()
BackupOfExistingProjectRequested = false,
};
- ProjectRestoreService restoreProjectService = new ProjectRestoreService(restoreSettings);
+ ProjectRestoreService restoreProjectService = new ProjectRestoreService(restoreSettings, new DummyFdoUI(),
+ FwDirectoryFinder.ConverterConsoleExe, FwDirectoryFinder.DbExe);
try
{
@@ -137,7 +136,7 @@ public void RestoreProjectSettings_VerifyExistenceOfHgRepo()
Assert.True(restoreSettings.ProjectExists, "Project does not exist but it should.");
Assert.False(restoreSettings.UsingSendReceive, "Project is using S/R but it should not be.");
- string otherReposDir = Path.Combine(restoreSettings.ProjectPath, FLExBridgeHelper.OtherRepositories);
+ string otherReposDir = Path.Combine(restoreSettings.ProjectPath, FdoFileHelper.OtherRepositories);
// Create a non-repository folder in OtherRepositories and verify the project is not using Send/Receive
Directory.CreateDirectory(Path.Combine(otherReposDir, "NotARepo_LIFT", "RandomSubdir"));
@@ -167,7 +166,7 @@ public void RestoreProjectSettings_VerifyExistenceOfHgRepo()
[Test]
public void RestoreProjectSettings_CommandLineOptions()
{
- RestoreProjectSettings settings = new RestoreProjectSettings();
+ RestoreProjectSettings settings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory);
Assert.AreEqual(string.Empty, settings.CommandLineOptions);
settings.IncludeConfigurationSettings = true;
Assert.AreEqual("c", settings.CommandLineOptions.ToLower());
@@ -194,15 +193,15 @@ public void RestoreProjectSettings_CommandLineOptions()
[Test]
public void RestoreProjectSettings_CreateFromCommandLineOptions()
{
- RestoreProjectSettings settings = new RestoreProjectSettings("project", "notThere.fwbackup", string.Empty);
+ RestoreProjectSettings settings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory, "project", "notThere.fwbackup", string.Empty);
CheckSettings(settings, false, false, false, false);
- settings = new RestoreProjectSettings("project", "notThere.fwbackup", "fl");
+ settings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory, "project", "notThere.fwbackup", "fl");
CheckSettings(settings, false, true, true, false);
- settings = new RestoreProjectSettings("project", "notThere.fwbackup", "cls");
+ settings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory, "project", "notThere.fwbackup", "cls");
CheckSettings(settings, true, false, true, true);
- settings = new RestoreProjectSettings("project", "notThere.fwbackup", "cfls");
+ settings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory, "project", "notThere.fwbackup", "cfls");
CheckSettings(settings, true, true, true, true);
- settings = new RestoreProjectSettings("project", "notThere.fwbackup", "CFLS");
+ settings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory, "project", "notThere.fwbackup", "CFLS");
CheckSettings(settings, true, true, true, true);
}
@@ -216,8 +215,8 @@ public void RestoreProjectSettings_CreateFromCommandLineOptions()
[Test]
public void BackupFileSettings_InitializeFromZipfileMetadata()
{
- string zipFilePath = Path.Combine(Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/BackupRestore/RestoreProjectPresenterTests"),
- Path.ChangeExtension("RestoreProjectPresenterTests", FwFileExtensions.ksFwBackupFileExtension));
+ string zipFilePath = Path.Combine(Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO/FDOTests/BackupRestore/RestoreProjectPresenterTests"),
+ Path.ChangeExtension("RestoreProjectPresenterTests", FdoFileHelper.ksFwBackupFileExtension));
BackupFileSettings backupSettings = new BackupFileSettings(zipFilePath);
Assert.AreEqual("BackupOnlyCoreFiles", backupSettings.Comment);
@@ -240,7 +239,7 @@ public void BackupFileSettings_InitializeFromZipfileMetadata()
public void BackupProjectSettings_DefaultValues()
{
var settings = new DummyBackupProjectSettings("whatever", "Blah", null, FDOBackendProviderType.kXML);
- Assert.AreEqual(DirectoryFinder.DefaultBackupDirectory, settings.DestinationFolder);
+ Assert.AreEqual(FwDirectoryFinder.DefaultBackupDirectory, settings.DestinationFolder);
}
/// ------------------------------------------------------------------------------------
@@ -252,7 +251,7 @@ public void BackupProjectSettings_DefaultValues()
public void BackupProjectSettings_Values()
{
var backupSettings = new DummyBackupProjectSettings(
- Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/BackupRestore"),
+ Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO/FDOTests/BackupRestore"),
"FieldWorksLanguageProject", null, FDOBackendProviderType.kXML)
{
Comment = "Test comment",
@@ -277,7 +276,7 @@ public void BackupProjectSettings_Values()
public void BackupFileSettings_SerializationAndDeserialization()
{
var backupSettings = new DummyBackupProjectSettings(
- Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/BackupRestore"),
+ Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO/FDOTests/BackupRestore"),
"FieldWorksLanguageProject", null, FDOBackendProviderType.kXML)
{
Comment = "Test comment",
diff --git a/Src/FDO/FDOTests/BackupRestore/ProjectBackupServiceTestForLinkedFiles.cs b/Src/FDO/FDOTests/BackupRestore/ProjectBackupServiceTestForLinkedFiles.cs
index 69e1ca751e..2df6870797 100644
--- a/Src/FDO/FDOTests/BackupRestore/ProjectBackupServiceTestForLinkedFiles.cs
+++ b/Src/FDO/FDOTests/BackupRestore/ProjectBackupServiceTestForLinkedFiles.cs
@@ -47,7 +47,7 @@ public override void FixtureSetup()
{
base.FixtureSetup();
var backupRestoreFolder = Path.Combine("FDO",Path.Combine("FDOTests", "BackupRestore"));
- m_testProjectsRoot = Path.Combine(DirectoryFinder.FwSourceDirectory, backupRestoreFolder);
+ m_testProjectsRoot = Path.Combine(FwDirectoryFinder.SourceDirectory, backupRestoreFolder);
m_linkedFilesRootDir = Path.Combine(m_testProjectsRoot, "LinkedFilesTestProjectFiles");
}
diff --git a/Src/FDO/FDOTests/BackupRestore/ProjectBackupServiceTests.cs b/Src/FDO/FDOTests/BackupRestore/ProjectBackupServiceTests.cs
index 0522976638..5704f33ae1 100644
--- a/Src/FDO/FDOTests/BackupRestore/ProjectBackupServiceTests.cs
+++ b/Src/FDO/FDOTests/BackupRestore/ProjectBackupServiceTests.cs
@@ -42,7 +42,7 @@ public override void FixtureSetup()
{
base.FixtureSetup();
var backupRestoreFolder = Path.Combine("FDO", Path.Combine("FDOTests", "BackupRestore"));
- m_testProjectsRoot = Path.Combine(DirectoryFinder.FwSourceDirectory, backupRestoreFolder);
+ m_testProjectsRoot = Path.Combine(FwDirectoryFinder.SourceDirectory, backupRestoreFolder);
}
/// ------------------------------------------------------------------------------------
@@ -320,7 +320,7 @@ private static bool DateTimesAreWithinACoupleSecondsOfEachOther(DateTime dateTim
/// ------------------------------------------------------------------------------------
private static void VerifyFileExistsInZipFile(ZipFile zip, String fileNameAndPath)
{
- string str = DirectoryFinder.GetZipfileFormattedPath(fileNameAndPath);
+ string str = FdoFileHelper.GetZipfileFormattedPath(fileNameAndPath);
//ensure the entry is the correct one.
ZipEntry entry = zip.GetEntry(str);
Assert.True(entry.Name.Equals(str), String.Format("File {0} should exist in zipFile", str));
diff --git a/Src/FDO/FDOTests/BackupRestore/ProjectRestoreServiceTests.cs b/Src/FDO/FDOTests/BackupRestore/ProjectRestoreServiceTests.cs
index 9818b05cd8..41bfba76de 100644
--- a/Src/FDO/FDOTests/BackupRestore/ProjectRestoreServiceTests.cs
+++ b/Src/FDO/FDOTests/BackupRestore/ProjectRestoreServiceTests.cs
@@ -7,13 +7,11 @@
using System;
using System.IO;
-using System.Text;
using System.Threading;
using NUnit.Framework;
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.BackupRestore;
-using SIL.FieldWorks.Resources;
using SIL.Utils;
using FwRemoteDatabaseConnector;
@@ -28,26 +26,18 @@ public class ProjectRestoreServiceTests : MemoryOnlyBackendProviderBasicTestBase
{
private ProjectRestoreService m_restoreProjectService;
private RestoreProjectSettings m_restoreSettings;
- private bool m_fResetSharedProjectValue;
/// Setup for db4o client server tests.
[TestFixtureSetUp]
public void Init()
{
// Allow db4o client server unit test to work without running the window service.
- RemotingServer.Start();
- if (Db4oServerInfo.AreProjectsShared_Internal)
- {
- m_fResetSharedProjectValue = true;
- Db4oServerInfo.AreProjectsShared_Internal = false;
- }
+ RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => false, v => {});
}
/// Stop db4o client server.
[TestFixtureTearDown]
public void UnInit()
{
- if (m_fResetSharedProjectValue)
- Db4oServerInfo.AreProjectsShared_Internal = m_fResetSharedProjectValue;
RemotingServer.Stop();
}
@@ -57,13 +47,13 @@ public void UnInit()
[SetUp]
public void Initialize()
{
- var restoreTestsZipFileDir = Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO", "FDOTests",
+ var restoreTestsZipFileDir = Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO", "FDOTests",
"BackupRestore","RestoreServiceTestsZipFileDir");
- m_restoreSettings = new RestoreProjectSettings()
+ m_restoreSettings = new RestoreProjectSettings(FwDirectoryFinder.ProjectsDirectory)
{
Backup = new BackupFileSettings(Path.Combine(restoreTestsZipFileDir,
- Path.ChangeExtension("TestRestoreFWProject", FwFileExtensions.ksFwBackupFileExtension))),
+ Path.ChangeExtension("TestRestoreFWProject", FdoFileHelper.ksFwBackupFileExtension))),
IncludeConfigurationSettings = false,
IncludeLinkedFiles = false,
IncludeSupportingFiles = false,
@@ -91,7 +81,8 @@ public void RestoreProject_CreateNew_OnlyDataFileAndWsFiles()
{
m_restoreSettings.ProjectName = "TestRestoreFWProject 01";
- m_restoreProjectService = new ProjectRestoreService(m_restoreSettings);
+ m_restoreProjectService = new ProjectRestoreService(m_restoreSettings, new DummyFdoUI(),
+ FwDirectoryFinder.ConverterConsoleExe, FwDirectoryFinder.DbExe);
m_restoreProjectService.RestoreProject(new DummyProgressDlg());
@@ -107,7 +98,8 @@ public void RestoreProject_CreateNew_DataFileAndConfigurationSettings()
{
m_restoreSettings.ProjectName = "TestRestoreFWProject 01";
m_restoreSettings.IncludeConfigurationSettings = true;
- m_restoreProjectService = new ProjectRestoreService(m_restoreSettings);
+ m_restoreProjectService = new ProjectRestoreService(m_restoreSettings, new DummyFdoUI(),
+ FwDirectoryFinder.ConverterConsoleExe, FwDirectoryFinder.DbExe);
m_restoreProjectService.RestoreProject(new DummyProgressDlg());
@@ -214,7 +206,7 @@ public void RestoreProject_PutLinkedFilesInOldLocation_CancelSelected()
private string GetFullVersionOfRelativeNonStdDir(string nonStdLinkedFilesDir)
{
- return Path.Combine(Directory.GetParent(DirectoryFinder.FwSourceDirectory).ToString(), nonStdLinkedFilesDir);
+ return Path.Combine(Directory.GetParent(FwDirectoryFinder.SourceDirectory).ToString(), nonStdLinkedFilesDir);
}
///
@@ -228,14 +220,15 @@ public void RestoreProject_OverwriteOnlyDataRestored()
IThreadedProgress progressDlg = new DummyProgressDlg();
m_restoreSettings.IncludeConfigurationSettings = false;
- m_restoreProjectService = new ProjectRestoreService(m_restoreSettings);
+ m_restoreProjectService = new ProjectRestoreService(m_restoreSettings, new DummyFdoUI(),
+ FwDirectoryFinder.ConverterConsoleExe, FwDirectoryFinder.DbExe);
//Restore the project once and do not delete it so that we can restore the project over the previous one.
m_restoreProjectService.RestoreProject(progressDlg);
string restoreProjectDirectory = m_restoreSettings.ProjectPath;
- VerifyFileExists(restoreProjectDirectory, DirectoryFinder.GetXmlDataFileName("TestRestoreFWProject"));
- var dateTimeTicksOfFirstFile = GetLastWriteTimeOfRestoredFile(restoreProjectDirectory, DirectoryFinder.GetXmlDataFileName("TestRestoreFWProject"));
+ VerifyFileExists(restoreProjectDirectory, FdoFileHelper.GetXmlDataFileName("TestRestoreFWProject"));
+ var dateTimeTicksOfFirstFile = GetLastWriteTimeOfRestoredFile(restoreProjectDirectory, FdoFileHelper.GetXmlDataFileName("TestRestoreFWProject"));
// Linux filesystem modification time precision can be to the second, so wait a moment.
if (MiscUtils.IsUnix)
@@ -249,7 +242,7 @@ public void RestoreProject_OverwriteOnlyDataRestored()
//Now do another restore then verify that the two files are not the same by comparing the LastWriteTime values.
m_restoreProjectService.RestoreProject(progressDlg);
- var dateTimeTicksOfSecondFile = GetLastWriteTimeOfRestoredFile(restoreProjectDirectory, DirectoryFinder.GetXmlDataFileName("TestRestoreFWProject"));
+ var dateTimeTicksOfSecondFile = GetLastWriteTimeOfRestoredFile(restoreProjectDirectory, FdoFileHelper.GetXmlDataFileName("TestRestoreFWProject"));
Assert.True(dateTimeTicksOfSecondFile.Equals(dateTimeTicksOfFirstFile), "The dates and times of the files should be the same since they are set to the timestamp of the file in the zip file.");
VerifyManditoryFilesUnzippedAndDeleteThem();
@@ -284,7 +277,7 @@ private static void RemoveAllFilesFromFolderAndSubfolders(string restoreDirector
internal static void RemoveAnyFilesAndFoldersCreatedByTests(RestoreProjectSettings settings)
{
- RemoveAllFilesFromFolderAndSubfolders(DirectoryFinder.GetBackupSettingsDir(settings.ProjectPath));
+ RemoveAllFilesFromFolderAndSubfolders(FdoFileHelper.GetBackupSettingsDir(settings.ProjectPath));
RemoveAllFilesFromFolderAndSubfolders(settings.ProjectSupportingFilesPath);
RemoveAllFilesFromFolderAndSubfolders(settings.FlexConfigurationSettingsPath);
RemoveAllFilesFromFolderAndSubfolders(settings.PicturesPath);
@@ -292,7 +285,7 @@ internal static void RemoveAnyFilesAndFoldersCreatedByTests(RestoreProjectSettin
RemoveAllFilesFromFolderAndSubfolders(settings.OtherExternalFilesPath);
RemoveAllFilesFromFolderAndSubfolders(settings.LinkedFilesPath);
RemoveAllFilesFromFolderAndSubfolders(settings.WritingSystemStorePath);
- RemoveAllFilesFromFolderAndSubfolders(Path.Combine(settings.ProjectPath, DirectoryFinder.ksSortSequenceTempDir));
+ RemoveAllFilesFromFolderAndSubfolders(Path.Combine(settings.ProjectPath, FdoFileHelper.ksSortSequenceTempDir));
//Remove this one last of all because the other folders need to be removed first.
RemoveAllFilesFromFolderAndSubfolders(settings.ProjectPath);
diff --git a/Src/FDO/FDOTests/BackupRestore/ProjectRestoreTestService.cs b/Src/FDO/FDOTests/BackupRestore/ProjectRestoreTestService.cs
index 7f14c972db..e7e07ea832 100644
--- a/Src/FDO/FDOTests/BackupRestore/ProjectRestoreTestService.cs
+++ b/Src/FDO/FDOTests/BackupRestore/ProjectRestoreTestService.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.BackupRestore;
namespace SIL.FieldWorks.FDO.FDOTests.BackupRestore
@@ -14,7 +15,8 @@ public class ProjectRestoreTestService : ProjectRestoreService
/// we don't want to show up in tests (a dialog).
///
///
- public ProjectRestoreTestService(RestoreProjectSettings settings) : base(settings)
+ public ProjectRestoreTestService(RestoreProjectSettings settings)
+ : base(settings, new DummyFdoUI(), FwDirectoryFinder.ConverterConsoleExe, FwDirectoryFinder.DbExe)
{
PutFilesInProject = false;
SimulateOKResult = true;
diff --git a/Src/FDO/FDOTests/CellarTests.cs b/Src/FDO/FDOTests/CellarTests.cs
index 3363485d95..ce6a7cc114 100644
--- a/Src/FDO/FDOTests/CellarTests.cs
+++ b/Src/FDO/FDOTests/CellarTests.cs
@@ -491,7 +491,7 @@ public void AddComplexFeaturesToFeatureSystemAndThenToAFeatureStructure()
// Set up the xml fs description
XmlDocument doc = new XmlDocument();
- string sFileDir = Path.Combine(DirectoryFinder.FwSourceDirectory, @"FDO/FDOTests/TestData");
+ string sFileDir = Path.Combine(FwDirectoryFinder.SourceDirectory, @"FDO/FDOTests/TestData");
string sFile = Path.Combine(sFileDir, "FeatureSystem2.xml");
doc.Load(sFile);
diff --git a/Src/FDO/FDOTests/ClientServerServicesTests.cs b/Src/FDO/FDOTests/ClientServerServicesTests.cs
index 2c90c2da07..b3338463a5 100644
--- a/Src/FDO/FDOTests/ClientServerServicesTests.cs
+++ b/Src/FDO/FDOTests/ClientServerServicesTests.cs
@@ -1,11 +1,9 @@
using System;
using System.IO;
-using System.Windows.Forms;
using FwRemoteDatabaseConnector;
using NUnit.Framework;
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices;
-using SIL.FieldWorks.Resources;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
@@ -22,6 +20,7 @@ public class ClientServerServicesTests : BaseTest
private Db4oServerInfo m_db4OServerInfo;
private string m_oldProjectDirectory;
+ private bool m_projectShared;
private IThreadedProgress m_progress;
@@ -31,11 +30,14 @@ public void StartFwRemoteDatabaseConnector()
{
// Change the Project Directory to some temporary directory to ensure, other units tests don't add projects
// which would slow these tests down.
- m_oldProjectDirectory = DirectoryFinder.ProjectsDirectory;
- DirectoryFinder.ProjectsDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
- Directory.CreateDirectory(DirectoryFinder.ProjectsDirectory);
+ m_oldProjectDirectory = FwDirectoryFinder.ProjectsDirectory;
+ FwDirectoryFinder.ProjectsDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
+ Directory.CreateDirectory(FwDirectoryFinder.ProjectsDirectory);
- RemotingServer.Start();
+ FdoTestHelper.SetupClientServerServices();
+
+ m_projectShared = false;
+ RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => m_projectShared, v => m_projectShared = v);
var connectString = String.Format("tcp://{0}:{1}/FwRemoteDatabaseConnector.Db4oServerInfo",
"127.0.0.1", Db4OPorts.ServerPort);
@@ -53,8 +55,8 @@ public void StopFwRemoteDatabaseConnector()
{
RemotingServer.Stop();
- Directory.Delete(DirectoryFinder.ProjectsDirectory, true);
- DirectoryFinder.ProjectsDirectory = m_oldProjectDirectory;
+ Directory.Delete(FwDirectoryFinder.ProjectsDirectory, true);
+ FwDirectoryFinder.ProjectsDirectory = m_oldProjectDirectory;
m_db4OServerInfo = null;
}
@@ -110,10 +112,10 @@ public void ShareMyProjects_TurningShareMyProjectOn_ShareMyProjectsReturnedTrue(
Assert.IsTrue(ClientServerServices.Current.Local.SetProjectSharing(true, m_progress));
Assert.IsTrue(Db4OLocalClientServerServices.LocalDb4OServerInfoConnection.AreProjectShared());
Assert.IsFalse(ClientServerServices.Current.Local.ShareMyProjects, "ShareMyProjects should not be true unless HKCU projects dir same as HKLM");
- var temp = DirectoryFinder.ProjectsDirectory;
- DirectoryFinder.ProjectsDirectory = DirectoryFinder.ProjectsDirectoryLocalMachine;
+ var temp = FwDirectoryFinder.ProjectsDirectory;
+ FwDirectoryFinder.ProjectsDirectory = FwDirectoryFinder.ProjectsDirectoryLocalMachine;
Assert.IsTrue(ClientServerServices.Current.Local.ShareMyProjects);
- DirectoryFinder.ProjectsDirectory = temp;
+ FwDirectoryFinder.ProjectsDirectory = temp;
}
///
@@ -131,10 +133,10 @@ public void IdForLocalProject_SimpleNameProjectsAreNotShared_ReturnedFilenameHas
string filename = ClientServerServices.Current.Local.IdForLocalProject("tom");
// Assert ends with .fwdata
- Assert.AreEqual(FwFileExtensions.ksFwDataXmlFileExtension, Path.GetExtension(filename));
+ Assert.AreEqual(FdoFileHelper.ksFwDataXmlFileExtension, Path.GetExtension(filename));
// Check file is in ProjectDirectory.
- Assert.That(filename, Is.SubPath(DirectoryFinder.ProjectsDirectory));
+ Assert.That(filename, Is.SubPath(FwDirectoryFinder.ProjectsDirectory));
}
///
diff --git a/Src/FDO/FDOTests/ClientServerTests.cs b/Src/FDO/FDOTests/ClientServerTests.cs
index 6d99a7bb35..fd9c0adb6f 100644
--- a/Src/FDO/FDOTests/ClientServerTests.cs
+++ b/Src/FDO/FDOTests/ClientServerTests.cs
@@ -1,15 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Text;
using System.Xml.Linq;
using NUnit.Framework;
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.CoreTests;
using SIL.FieldWorks.FDO.DomainImpl;
-using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
@@ -45,7 +42,7 @@ public void VerifyOkToReconcileChanges()
modified.Add(GetSurrogate(sense1, cmoFactory));
m_actionHandler.Undo();
var uowService = (UnitOfWorkService) undoManager;
- var reconciler = uowService.Reconciler(new List(), modified, new List());
+ var reconciler = uowService.CreateReconciler(new List(), modified, new List());
// Only other client made changes
Assert.That(reconciler.OkToReconcileChanges(), Is.True,
@@ -55,21 +52,21 @@ public void VerifyOkToReconcileChanges()
UndoableUnitOfWorkHelper.Do("undo change gloss", "redo", m_actionHandler,
() => sense1.Gloss.AnalysisDefaultWritingSystem =
Cache.TsStrFactory.MakeString("strike with shoe", Cache.DefaultAnalWs));
- reconciler = uowService.Reconciler(new List(), modified, new List());
+ reconciler = uowService.CreateReconciler(new List(), modified, new List());
Assert.That(reconciler.OkToReconcileChanges(), Is.False,
"we should not be able to make a change if we have a conflicting change to the same object.");
m_actionHandler.Undo();
- reconciler = uowService.Reconciler(new List(), modified, new List());
+ reconciler = uowService.CreateReconciler(new List(), modified, new List());
Assert.That(reconciler.OkToReconcileChanges(), Is.True);
// Foreign modified, local deleted.
UndoableUnitOfWorkHelper.Do("undo delete sense", "redo", m_actionHandler,
() => entry1.SensesOS.RemoveAt(0));
- reconciler = uowService.Reconciler(new List(), modified, new List());
+ reconciler = uowService.CreateReconciler(new List(), modified, new List());
Assert.That(reconciler.OkToReconcileChanges(), Is.False,
"we should not be able to make a change if we have deleted an object that the change modifies.");
m_actionHandler.Undo();
- reconciler = uowService.Reconciler(new List(), modified, new List());
+ reconciler = uowService.CreateReconciler(new List(), modified, new List());
Assert.That(reconciler.OkToReconcileChanges(), Is.True);
// Local modified, foreign deleted.
@@ -78,11 +75,11 @@ public void VerifyOkToReconcileChanges()
Cache.TsStrFactory.MakeString("strike with boot", Cache.DefaultAnalWs));
var listOfSense1Id = new List();
listOfSense1Id.Add(sense1.Id);
- reconciler = uowService.Reconciler(new List(), new List(), listOfSense1Id);
+ reconciler = uowService.CreateReconciler(new List(), new List(), listOfSense1Id);
Assert.That(reconciler.OkToReconcileChanges(), Is.False,
"we should not be able to make a change if it involves deleting an object that we have modified.");
m_actionHandler.Undo();
- reconciler = uowService.Reconciler(new List(), modified, new List());
+ reconciler = uowService.CreateReconciler(new List(), modified, new List());
Assert.That(reconciler.OkToReconcileChanges(), Is.True);
// We added a reference to something they deleted (on a new object).
@@ -94,7 +91,7 @@ public void VerifyOkToReconcileChanges()
newObjectSurrogates.Add(GetSurrogate(bundle.Owner.Owner, cmoFactory));
newObjectSurrogates.Add(GetSurrogate(bundle.Owner,cmoFactory));
newObjectSurrogates.Add(GetSurrogate(bundle, cmoFactory));
- reconciler = uowService.Reconciler(new List(), new List(), listOfSense1Id);
+ reconciler = uowService.CreateReconciler(new List(), new List(), listOfSense1Id);
Assert.That(reconciler.OkToReconcileChanges(), Is.False,
"we should not be able to make a change if it involves deleting an object that one we have added refers to.");
@@ -102,11 +99,11 @@ public void VerifyOkToReconcileChanges()
UndoableUnitOfWorkHelper.Do("undo clear ref", "redo", m_actionHandler,
() => bundle.SenseRA = null);
undoManager.Save();
- reconciler = uowService.Reconciler(new List(), new List(), listOfSense1Id);
+ reconciler = uowService.CreateReconciler(new List(), new List(), listOfSense1Id);
Assert.That(reconciler.OkToReconcileChanges(),Is.True);
UndoableUnitOfWorkHelper.Do("undo set ref", "redo", m_actionHandler,
() => bundle.SenseRA = sense1);
- reconciler = uowService.Reconciler(new List(), new List(), listOfSense1Id);
+ reconciler = uowService.CreateReconciler(new List(), new List(), listOfSense1Id);
Assert.That(reconciler.OkToReconcileChanges(), Is.False,
"we should not be able to make a change if it involves deleting an object that we have made a reference to.");
m_actionHandler.Undo(); // setting the sense of the bundle
@@ -118,13 +115,13 @@ public void VerifyOkToReconcileChanges()
UndoableUnitOfWorkHelper.Do("undo delete sense", "redo", m_actionHandler,
() => entry1.SensesOS.RemoveAt(0));
// Now pretend THEY made the change adding the objects referring to sense1, which we just deleted.
- reconciler = uowService.Reconciler(newObjectSurrogates, new List(), new List());
+ reconciler = uowService.CreateReconciler(newObjectSurrogates, new List(), new List());
Assert.That(reconciler.OkToReconcileChanges(), Is.False,
"we should not be able to make a change if it involves adding an object that refers to an object we have deleted.");
// This is cheating a little bit, because we're passing as modified objects things not in our db at all.
// But it exercises the relevant code, making sure we check the modified objects for refs to our deleted ones.
- reconciler = uowService.Reconciler(new List(), newObjectSurrogates, new List());
+ reconciler = uowService.CreateReconciler(new List(), newObjectSurrogates, new List());
Assert.That(reconciler.OkToReconcileChanges(), Is.False,
"we should not be able to make a change if it involves adding a ref to an object we have deleted.");
}
@@ -160,7 +157,7 @@ public void ReconcileCollectionChanges()
remove.Delete();
});
var uowService = Cache.ServiceLocator.GetInstance();
- var reconciler = ((UnitOfWorkService)uowService).Reconciler(newbiesClockwise, dirtballsClockwise, gonersClockwise);
+ var reconciler = ((UnitOfWorkService)uowService).CreateReconciler(newbiesClockwise, dirtballsClockwise, gonersClockwise);
var notifiee = new Notifiee();
Cache.DomainDataByFlid.AddNotification(notifiee);
Assert.That(reconciler.OkToReconcileChanges(), Is.True);
@@ -239,7 +236,7 @@ public void ModifiedDifferentSenses_EarlierTime()
var newTime = entry1.DateModified; // should be definitely after oldTime.
Assert.That(newTime, Is.GreaterThan(oldTime));
var uowService = Cache.ServiceLocator.GetInstance();
- var reconciler = ((UnitOfWorkService)uowService).Reconciler(newbiesClockwise, dirtballsClockwise, gonersClockwise);
+ var reconciler = ((UnitOfWorkService)uowService).CreateReconciler(newbiesClockwise, dirtballsClockwise, gonersClockwise);
Assert.That(reconciler.OkToReconcileChanges(), Is.True);
reconciler.ReconcileForeignChanges();
@@ -314,7 +311,7 @@ public void ModifiedDifferentSenses_LaterTime()
Assert.That(newTime, Is.LessThan(foreignTime)); // might not be if stepping in debugger
var uowService = Cache.ServiceLocator.GetInstance();
- var reconciler = ((UnitOfWorkService)uowService).Reconciler(newbiesClockwise, dirtballsClockwise, gonersClockwise);
+ var reconciler = ((UnitOfWorkService)uowService).CreateReconciler(newbiesClockwise, dirtballsClockwise, gonersClockwise);
Assert.That(reconciler.OkToReconcileChanges(), Is.True);
reconciler.ReconcileForeignChanges();
@@ -644,26 +641,6 @@ void SetString(IMultiUnicode target, int ws, string text)
target.set_String(ws, Cache.TsStrFactory.MakeString(text, ws));
}
- ///
- /// Helper method for tests on this pattern:
- /// Create some initial state;
- /// Save;
- /// Make a change locally;
- /// Record the changes and their final state;
- /// Undo;
- /// Wait until a new DateTime occurs;
- /// Make the other change locally;
- /// Reconcile the changes in the first group;
- ///
- ///
- ///
- ///
- void VerifyCheckingAndReconcilingAChange(Action firstChange, Action secondChange, string label)
- {
-
- }
-
-
///
/// Helper method for several tests on this pattern:
/// create an object that has the required kind of data;
@@ -686,7 +663,7 @@ void VerifyReconcilingAChange(Action makeTheChange, string label)
GetEffectsOfChange(makeTheChange, out newbySurrogates, out dirtballSurrogates, out gonerList);
var undoManager = Cache.ServiceLocator.GetInstance();
// Re-apply the changes using the reconciliation mechanism
- var reconciler = ((UnitOfWorkService)undoManager).Reconciler(newbySurrogates, dirtballSurrogates, gonerList);
+ var reconciler = ((UnitOfWorkService)undoManager).CreateReconciler(newbySurrogates, dirtballSurrogates, gonerList);
reconciler.ReconcileForeignChanges();
// verify deletions
foreach (var id in gonerList)
diff --git a/Src/FDO/FDOTests/CmSemanticDomainRepositoryTests.cs b/Src/FDO/FDOTests/CmSemanticDomainRepositoryTests.cs
index f9d3d91b4c..4766c870d6 100644
--- a/Src/FDO/FDOTests/CmSemanticDomainRepositoryTests.cs
+++ b/Src/FDO/FDOTests/CmSemanticDomainRepositoryTests.cs
@@ -397,7 +397,7 @@ public void FindDomains_TimingOnLargerDataSet()
const string expectedNum2 = "8.3.3"; // group3 match 'sunshine', under 'Light'
const string expectedName2 = "Light";
const string filePath = @"Templates\semdom.xml";
- var homeDir = DirectoryFinder.FWCodeDirectory;
+ var homeDir = FwDirectoryFinder.CodeDirectory;
LoadSemDomTestDataFromFile(Path.Combine(homeDir, filePath));
// SUT
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000001Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000001Tests.cs
index bd2931b390..70d8d4a4d8 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000001Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000001Tests.cs
@@ -3,6 +3,7 @@
using System.Linq;
using System.Xml.Linq;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -128,7 +129,7 @@ public void DataMigration7000001_and_Delint_Tests()
mockMDC.AddClass(3, "Text", "CmObject", new List());
mockMDC.AddClass(4, "WfiWordform", "CmObject", new List());
mockMDC.AddClass(5, "LexSense", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000000, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000000, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000001, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000002Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000002Tests.cs
index 550dc2f317..cef68f1e77 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000002Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000002Tests.cs
@@ -10,6 +10,7 @@
using System.Text;
using System.Xml.Linq;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -176,7 +177,7 @@ public void DataMigration7000002Test()
mockMDC.AddClass(9, "ScrFootnote", "CmObject", new List());
mockMDC.AddClass(10, "ScrTxtPara", "CmObject", new List());
mockMDC.AddClass(11, "StPara", "CmObject", new List { "StTxtPara" });
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000001, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000001, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000002, new DummyProgressDlg());
Assert.AreEqual(7000002, dtoRepos.CurrentModelVersion, "Wrong updated version.");
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000003Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000003Tests.cs
index 6bc1f1186b..2af15fddc6 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000003Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000003Tests.cs
@@ -2,6 +2,7 @@
using System.Text;
using System.Xml.Linq;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -91,7 +92,7 @@ public void DataMigration7000003Test()
mockMDC.AddClass(9, "ScrFootnote", "CmObject", new List());
mockMDC.AddClass(10, "ScrTxtPara", "CmObject", new List());
mockMDC.AddClass(11, "StPara", "CmObject", new List { "StTxtPara" });
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000002, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000002, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000003, new DummyProgressDlg());
Assert.AreEqual(7000003, dtoRepos.CurrentModelVersion, "Wrong updated version.");
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000005Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000005Tests.cs
index 2aa7698a9a..737fbf08c9 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000005Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000005Tests.cs
@@ -3,6 +3,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -44,7 +45,7 @@ public void DataMigration7000005Test()
mockMDC.AddClass(13, "RnAnalysis", "RnGenericRec", new List());
mockMDC.AddClass(14, "CmPerson", "CmPossibility", new List());
mockMDC.AddClass(15, "CmAnthroItem", "CmPossibility", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000004, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000004, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000005, new DummyProgressDlg());
var nbkDto = dtoRepos.AllInstancesSansSubclasses("RnResearchNbk").First();
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000006Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000006Tests.cs
index 5f7d31fd3b..92e632d258 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000006Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000006Tests.cs
@@ -3,6 +3,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -29,7 +30,7 @@ public void DataMigration7000006Test()
mockMDC.AddClass(1, "CmObject", null, new List { "CmProject" });
mockMDC.AddClass(2, "CmProject", "CmObject", new List { "LangProject" });
mockMDC.AddClass(3, "LangProject", "CmProject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000005, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000005, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000006, new DummyProgressDlg());
var cmProjDto = dtoRepos.AllInstancesSansSubclasses("LangProject").First();
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000007Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000007Tests.cs
index 650e975df0..0fe6fa831d 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000007Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000007Tests.cs
@@ -3,6 +3,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -35,7 +36,7 @@ public void DataMigration7000007Test()
mockMDC.AddClass(7, "StTxtPara", "StPara", new List());
mockMDC.AddClass(9, "StFootnote", "StText", new List {"ScrFootnote"});
mockMDC.AddClass(10, "ScrFootnote", "StFootnote", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000006, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000006, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000007, new DummyProgressDlg());
var ScrInpDto = dtoRepos.AllInstancesSansSubclasses("ScrImportSet").First();
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000008Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000008Tests.cs
index 07582429c3..0da1b59962 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000008Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000008Tests.cs
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -33,7 +34,7 @@ public void DataMigration7000008Test()
mockMDC.AddClass(2, "LangProject", "CmObject", new List());
mockMDC.AddClass(3, "CmBaseAnnotation", "CmObject", new List { "ScrScriptureNote" });
mockMDC.AddClass(4, "ScrScriptureNote", "CmBaseAnnotation", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000007, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000007, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000008, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000009Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000009Tests.cs
index bd1d01983d..f8e447cafb 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000009Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000009Tests.cs
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -64,7 +65,7 @@ public void DataMigration7000009Test()
mockMDC.AddClass(1, "CmObject", null, new List { "LangProject", "Scripture" });
mockMDC.AddClass(2, "LangProject", "CmObject", new List());
mockMDC.AddClass(4, "Scripture", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000008, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000008, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000009, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000010Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000010Tests.cs
index 9bcefab21e..2e44900f98 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000010Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000010Tests.cs
@@ -3,6 +3,7 @@
using System.Linq;
using System.Xml.Linq;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -76,7 +77,7 @@ public void DataMigration7000010_AnnotationDefns_Removed_Test()
mockMDC.AddClass(3, "CmAnnotationDefn", "CmObject", new List());
mockMDC.AddClass(4, "StText", "CmObject", new List());
mockMDC.AddClass(5, "StTxtPara", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000009, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000009, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
// Collect the various annotation defns.
var annDefnDtos = new Dictionary();
@@ -1160,7 +1161,7 @@ private static IDomainObjectDTORepository SetupMDC(HashSet dtos
mockMDC.AddClass(16, "ConstChartMovedTextMarker", "ConstituentChartCellPart", new List());
mockMDC.AddClass(17, "ConstChartClauseMarker", "ConstituentChartCellPart", new List());
mockMDC.AddClass(18, "ConstChartTag", "ConstituentChartCellPart", new List());
- return new DomainObjectDtoRepository(7000009, dtos, mockMDC, null);
+ return new DomainObjectDtoRepository(7000009, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
}
private static void CheckXfics(IDomainObjectDTORepository dtoRepos,
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000011Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000011Tests.cs
index 33193000a4..3680fb1552 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000011Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000011Tests.cs
@@ -4,7 +4,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
-
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -98,7 +98,7 @@ public void DataMigration7000011Test()
mockMDC.AddClass(3, "CmPossibilityList", "CmObject", new List());
mockMDC.AddClass(4, "CmPossibility", "CmObject", new List());
mockMDC.AddClass(5, "RnGenericRec", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000010, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000010, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000011, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000012Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000012Tests.cs
index 747ea57112..be6ab580f2 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000012Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000012Tests.cs
@@ -1,10 +1,9 @@
-using System;
using System.Collections.Generic;
-using System.Text;
using NUnit.Framework;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -56,7 +55,7 @@ public void DataMigration7000012_Unneeded_UserViewField_Removed_Test()
var mockMDC = new MockMDCForDataMigration();
mockMDC.AddClass(1, "CmObject", null, new List { "UserViewField" });
mockMDC.AddClass(2, "UserViewField", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000011, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000011, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
Assert.AreEqual(40, dtoRepos.AllInstancesWithSubclasses("UserViewField").Count());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000013Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000013Tests.cs
index 76fb108a07..56982bd5ac 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000013Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000013Tests.cs
@@ -3,6 +3,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -95,7 +96,7 @@ private static IDomainObjectDTORepository DoCommonBasics(IEnumerable ext
var mockMDC = SetupMDC();
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000012, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000012, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
return dtoRepos;
}
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000014Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000014Tests.cs
index 434939b523..4b58ea39e1 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000014Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000014Tests.cs
@@ -3,6 +3,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -26,7 +27,7 @@ public void DataMigration7000014Test()
var mockMDC = SetupMDC();
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000013, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000013, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
// SUT; Do the migration.
m_dataMigrationManager.PerformMigration(dtoRepos, 7000014, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000015Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000015Tests.cs
index 221ad7122d..b6eef2503d 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000015Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000015Tests.cs
@@ -2,6 +2,7 @@
using System.Linq;
using System.Xml.Linq;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -25,7 +26,7 @@ public void DataMigration7000015Test()
var mockMdc = SetupMdc();
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000014, dtos, mockMdc, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000014, dtos, mockMdc, null, FwDirectoryFinder.FdoDirectories);
// SUT: Do the migration.
m_dataMigrationManager.PerformMigration(dtoRepos, 7000015, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000016Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000016Tests.cs
index 49defea49c..2249fd7b02 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000016Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000016Tests.cs
@@ -15,7 +15,7 @@
using System.Xml.XPath;
using NUnit.Framework;
-
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -57,7 +57,7 @@ public void DataMigration7000016Test()
var mockMdc = SetupMdc();
- IDomainObjectDTORepository repoDTO = new DomainObjectDtoRepository(7000015, dtos, mockMdc, null);
+ IDomainObjectDTORepository repoDTO = new DomainObjectDtoRepository(7000015, dtos, mockMdc, null, FwDirectoryFinder.FdoDirectories);
// SUT: Do the migration.
m_dataMigrationManager.PerformMigration(repoDTO, 7000016, new DummyProgressDlg());
@@ -117,7 +117,7 @@ public void CheckOnNoPossibilitiesInListAtStart()
@"")
};
var mockMdc = SetupMdc();
- IDomainObjectDTORepository repoDto = new DomainObjectDtoRepository(7000015, dtos, mockMdc, null);
+ IDomainObjectDTORepository repoDto = new DomainObjectDtoRepository(7000015, dtos, mockMdc, null, FwDirectoryFinder.FdoDirectories);
// SUT: Do the migration.
m_dataMigrationManager.PerformMigration(repoDto, 7000016, new DummyProgressDlg());
// Verification Phase
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000017Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000017Tests.cs
index 2e5cdaf16b..b8e6eb642f 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000017Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000017Tests.cs
@@ -8,11 +8,9 @@
//
//
-using System;
using System.Collections.Generic;
-using System.Text;
using NUnit.Framework;
-using SIL.FieldWorks.Test.TestUtils;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -37,7 +35,7 @@ public void DeleteWeatherListAndField()
var mockMdc = SetupMdc();
- IDomainObjectDTORepository repoDTO = new DomainObjectDtoRepository(7000016, dtos, mockMdc, null);
+ IDomainObjectDTORepository repoDTO = new DomainObjectDtoRepository(7000016, dtos, mockMdc, null, FwDirectoryFinder.FdoDirectories);
// SUT: Do the migration.
m_dataMigrationManager.PerformMigration(repoDTO, 7000017, new DummyProgressDlg());
@@ -138,7 +136,7 @@ private void ConvertWeatherToCustomListAndField(string datafile)
var mockMdc = SetupMdc();
- IDomainObjectDTORepository repoDTO = new DomainObjectDtoRepository(7000016, dtos, mockMdc, null);
+ IDomainObjectDTORepository repoDTO = new DomainObjectDtoRepository(7000016, dtos, mockMdc, null, FwDirectoryFinder.FdoDirectories);
// SUT: Do the migration.
m_dataMigrationManager.PerformMigration(repoDTO, 7000017, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000018Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000018Tests.cs
index ca8a950304..bd3b2b5d74 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000018Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000018Tests.cs
@@ -12,7 +12,7 @@
using System.Text;
using System.Xml.Linq;
using NUnit.Framework;
-
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
using SIL.Utils;
@@ -38,7 +38,7 @@ public void PerformMigration7000018()
var mockMdc = SetupMdc();
- IDomainObjectDTORepository repoDTO = new DomainObjectDtoRepository(7000017, dtos, mockMdc, null);
+ IDomainObjectDTORepository repoDTO = new DomainObjectDtoRepository(7000017, dtos, mockMdc, null, FwDirectoryFinder.FdoDirectories);
// SUT: Do the migration.
m_dataMigrationManager.PerformMigration(repoDTO, 7000018, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000019Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000019Tests.cs
index dcf25f9f3c..cec6515696 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000019Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000019Tests.cs
@@ -1,5 +1,4 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
@@ -38,7 +37,7 @@ private static void PrepareStore(string path)
[Test]
public void DataMigration7000019Test()
{
- string storePath = Path.Combine(Path.GetTempPath(), DirectoryFinder.ksWritingSystemsDir);
+ string storePath = Path.Combine(Path.GetTempPath(), FdoFileHelper.ksWritingSystemsDir);
PrepareStore(storePath);
string globalStorePath = DirectoryFinder.GlobalWritingSystemStoreDirectory;
PrepareStore(globalStorePath);
@@ -47,7 +46,7 @@ public void DataMigration7000019Test()
IFwMetaDataCacheManaged mockMdc = SetupMdc();
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000018, dtos, mockMdc, Path.GetTempPath());
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000018, dtos, mockMdc, Path.GetTempPath(), FwDirectoryFinder.FdoDirectories);
// Do the migration.
m_dataMigrationManager.PerformMigration(dtoRepos, 7000019, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000020Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000020Tests.cs
index 3da9ab5298..baa00d8acb 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000020Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000020Tests.cs
@@ -13,7 +13,7 @@
using System.Linq;
using NUnit.Framework;
-
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
using SIL.FieldWorks.FDO.Infrastructure;
@@ -38,7 +38,7 @@ public void DataMigration7000020Test()
IFwMetaDataCacheManaged mockMdc = SetupMdc();
IDomainObjectDTORepository repoDto = new DomainObjectDtoRepository(7000019, dtos, mockMdc,
- Path.GetTempPath());
+ Path.GetTempPath(), FwDirectoryFinder.FdoDirectories);
// Initial check that data was read properly.
var cObjects = repoDto.AllInstances().Count();
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000022Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000022Tests.cs
index f43696fae6..3dd6ed2488 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000022Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000022Tests.cs
@@ -4,6 +4,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -39,7 +40,7 @@ public void DataMigration7000022Test()
mockMDC.AddClass(5, "RnResearchNbk", "CmMajorObject", new List());
mockMDC.AddClass(6, "LexDb", "CmMajorObject", new List());
mockMDC.AddClass(7, "CmPossibilityList", "CmMajorObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000021, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000021, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
// SUT
m_dataMigrationManager.PerformMigration(dtoRepos, 7000022, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000023Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000023Tests.cs
index 06bf304299..1936a7a0a2 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000023Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000023Tests.cs
@@ -1,9 +1,7 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
+using System.Collections.Generic;
using System.Xml.Linq;
-using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -38,10 +36,10 @@ public void DataMigration7000023Test()
mockMDC.AddClass(6, "CmFilter", "CmObject", new List());
mockMDC.AddClass(7, "UserView", "CmObject", new List());
mockMDC.AddClass(8, "UserAppFeatAct", "CmObject", new List());
- mockMDC.AddClass(9, "CmResource", "CmObject", new List()); ;
- mockMDC.AddClass(10, "ScrCheckRun", "CmObject", new List()); ;
- mockMDC.AddClass(11, "RnResearchNbk", "CmObject", new List()); ;
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000022, dtos, mockMDC, null);
+ mockMDC.AddClass(9, "CmResource", "CmObject", new List());
+ mockMDC.AddClass(10, "ScrCheckRun", "CmObject", new List());
+ mockMDC.AddClass(11, "RnResearchNbk", "CmObject", new List());
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000022, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
//SUT
m_dataMigrationManager.PerformMigration(dtoRepos, 7000023, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000024Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000024Tests.cs
index 099f9b2e15..5c0e4a2799 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000024Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000024Tests.cs
@@ -3,6 +3,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -47,7 +48,7 @@ public void DataMigration7000024Test()
mockMDC.AddClass(9, "LexEntry", "CmObject", new List());
mockMDC.AddClass(10, "LexSense", "CmObject", new List());
mockMDC.AddClass(11, "CmPossibility", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000023, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000023, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000024, new DummyProgressDlg());
//This object should contain a 'Status' property
@@ -233,7 +234,7 @@ public void DataMigration7000024Test1()
mockMDC.AddClass(5, "RnResearchNbk", "CmMajorObject", new List());
mockMDC.AddClass(6, "RnGenericRec", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000023, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000023, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000024, new DummyProgressDlg());
//This object should contain a 'Status' property
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000025Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000025Tests.cs
index 6e67fbff6b..347d9849eb 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000025Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000025Tests.cs
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
-using System.Linq;
using System.Xml.Linq;
-using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -98,7 +97,7 @@ public void DataMigration7000025Test()
mockMdc.AddClass(13, "RnGenericRec", "CmObject", new List());
mockMdc.AddClass(14, "ScrDraft", "CmObject", new List());
mockMdc.AddClass(15, "ScrCheckRun", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000024, dtos, mockMdc, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000024, dtos, mockMdc, null, FwDirectoryFinder.FdoDirectories);
// SUT
m_dataMigrationManager.PerformMigration(dtoRepos, 7000025, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000026Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000026Tests.cs
index d3393ae0d0..3f19bb81f8 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000026Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000026Tests.cs
@@ -3,6 +3,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -31,7 +32,7 @@ public void DataMigration7000026Test()
mockMDC.AddClass(2, "CmProject", "CmObject", new List { "LangProject" });
mockMDC.AddClass(3, "LangProject", "CmProject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000025, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000025, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
//Before the migration there should be a ExtLinkRootDir element in the project.
var langProjDto = dtoRepos.AllInstancesSansSubclasses("LangProject").First();
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000027Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000027Tests.cs
index e5d3b08e04..03d3348b01 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000027Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000027Tests.cs
@@ -9,6 +9,7 @@
using System.Text;
using System.Xml.Linq;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -152,7 +153,7 @@ public void DataMigration7000027Test()
mockMDC.AddClass(9, "ScrFootnote", "StFootnote", new List());
mockMDC.AddClass(10, "ScrTxtPara", "StTxtPara", new List());
mockMDC.AddClass(11, "StPara", "CmObject", new List { "StTxtPara" });
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000026, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000026, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000027, new DummyProgressDlg());
Assert.AreEqual(7000027, dtoRepos.CurrentModelVersion, "Wrong updated version.");
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000028Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000028Tests.cs
index fb8efc203a..7f63610d55 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000028Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000028Tests.cs
@@ -3,6 +3,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.FDOTests.DataMigrationTests
@@ -33,7 +34,7 @@ public void DataMigration7000028Test()
mockMDC.AddClass(4, "LexDb", "CmObject", new List ());
mockMDC.AddClass(5, "LexEntry", "CmObject", new List());
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000027, dtos, mockMDC, null);
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000027, dtos, mockMDC, null, FwDirectoryFinder.FdoDirectories);
m_dataMigrationManager.PerformMigration(dtoRepos, 7000028, new DummyProgressDlg());
diff --git a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000029Tests.cs b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000029Tests.cs
index 3340e58b10..2e93c0b428 100644
--- a/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000029Tests.cs
+++ b/Src/FDO/FDOTests/DataMigrationTests/DataMigration7000029Tests.cs
@@ -4,6 +4,7 @@
using System.Xml.Linq;
using System.Xml.XPath;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
using SIL.Utils;
@@ -54,7 +55,7 @@ public void DataMigration7000029Test()
mockMDC.AddClass(10, "CmFile", "CmObject", new List());
//-------------------+++++++++++++++++++++++++=
- IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000028, dtos, mockMDC, @"C:\FwWW\DistFiles\Projects\Sena 3");
+ IDomainObjectDTORepository dtoRepos = new DomainObjectDtoRepository(7000028, dtos, mockMDC, @"C:\FwWW\DistFiles\Projects\Sena 3", FwDirectoryFinder.FdoDirectories);
//Get the Element
-
- False
- ..\..\..\DistFiles\ParatextShared.dll
-
False
..\..\..\Output\Debug\PhonEnvValidator.dll
@@ -299,6 +295,7 @@
+
@@ -330,6 +327,7 @@
+
@@ -352,7 +350,6 @@
-
@@ -381,6 +378,7 @@
+
@@ -564,6 +562,12 @@
true
+
+
+ {7B119B65-DD6F-4AFB-BBA3-682DC084FB33}
+ FdoUi
+
+
../../../DistFiles
diff --git a/Src/FDO/FDOTests/FdoCacheTests.cs b/Src/FDO/FDOTests/FdoCacheTests.cs
index 7a4eb8dd97..a043f542fd 100644
--- a/Src/FDO/FDOTests/FdoCacheTests.cs
+++ b/Src/FDO/FDOTests/FdoCacheTests.cs
@@ -29,20 +29,23 @@ namespace SIL.FieldWorks.FDO.CoreTests.FdoCacheTests
public class FdoCacheTests : MemoryOnlyBackendProviderTestBase
{
private string m_oldProjectDirectory;
+ private IFdoUI m_ui;
/// Setup for db4o client server tests.
public override void FixtureSetup()
{
base.FixtureSetup();
- m_oldProjectDirectory = DirectoryFinder.ProjectsDirectory;
- DirectoryFinder.ProjectsDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
- Directory.CreateDirectory(DirectoryFinder.ProjectsDirectory);
+ m_oldProjectDirectory = FwDirectoryFinder.ProjectsDirectory;
+ FwDirectoryFinder.ProjectsDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
+ Directory.CreateDirectory(FwDirectoryFinder.ProjectsDirectory);
+
+ m_ui = new DummyFdoUI();
try
{
// Allow db4o client server unit test to work without running the window service.
- FwRemoteDatabaseConnector.RemotingServer.Start();
+ FwRemoteDatabaseConnector.RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => false, v => {});
}
catch (RemotingException e)
{
@@ -57,8 +60,8 @@ public override void FixtureSetup()
public override void FixtureTeardown()
{
FwRemoteDatabaseConnector.RemotingServer.Stop();
- Directory.Delete(DirectoryFinder.ProjectsDirectory, true);
- DirectoryFinder.ProjectsDirectory = m_oldProjectDirectory;
+ Directory.Delete(FwDirectoryFinder.ProjectsDirectory, true);
+ FwDirectoryFinder.ProjectsDirectory = m_oldProjectDirectory;
base.FixtureTeardown();
}
@@ -71,19 +74,19 @@ public override void FixtureTeardown()
[ExpectedException(typeof(ArgumentException))]
public void CreateNewLangProject_DbFilesExist()
{
- var preExistingDirs = new List(Directory.GetDirectories(DirectoryFinder.ProjectsDirectory));
+ var preExistingDirs = new List(Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
try
{
// Setup: Create "pre-existing" DB filenames
- using (new DummyFileMaker(Path.Combine(DirectoryFinder.ProjectsDirectory, "Gumby", DirectoryFinder.GetXmlDataFileName("Gumby"))))
+ using (new DummyFileMaker(Path.Combine(FwDirectoryFinder.ProjectsDirectory, "Gumby", FdoFileHelper.GetXmlDataFileName("Gumby"))))
{
using (var threadHelper = new ThreadHelper())
- FdoCache.CreateNewLangProj(new DummyProgressDlg(), "Gumby", threadHelper);
+ FdoCache.CreateNewLangProj(new DummyProgressDlg(), "Gumby", FwDirectoryFinder.FdoDirectories, threadHelper);
}
}
finally
{
- RemoveTestDirs(preExistingDirs, Directory.GetDirectories(DirectoryFinder.ProjectsDirectory));
+ RemoveTestDirs(preExistingDirs, Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
}
}
@@ -97,20 +100,20 @@ public void CreateNewLangProject_DbFilesExist()
public void CreateNewLangProject_NameWithSingleQuote()
{
const string dbName = "!!t'st";
- string dbDir = Path.Combine(DirectoryFinder.ProjectsDirectory, dbName);
+ string dbDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, dbName);
SureRemoveDb(dbName);
- var expectedDirs = new List(Directory.GetDirectories(DirectoryFinder.ProjectsDirectory)) { dbDir };
- var writingSystemsCommonDir = Path.Combine(DirectoryFinder.ProjectsDirectory, DirectoryFinder.ksWritingSystemsDir);
+ var expectedDirs = new List(Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory)) { dbDir };
+ var writingSystemsCommonDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, FdoFileHelper.ksWritingSystemsDir);
List currentDirs = null;
try
{
string dbFileName;
using (var threadHelper = new ThreadHelper())
- dbFileName = FdoCache.CreateNewLangProj(new DummyProgressDlg(), dbName, threadHelper);
+ dbFileName = FdoCache.CreateNewLangProj(new DummyProgressDlg(), dbName, FwDirectoryFinder.FdoDirectories, threadHelper);
- currentDirs = new List(Directory.GetDirectories(DirectoryFinder.ProjectsDirectory));
+ currentDirs = new List(Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
if (currentDirs.Contains(writingSystemsCommonDir) && !expectedDirs.Contains(writingSystemsCommonDir))
expectedDirs.Add(writingSystemsCommonDir);
CollectionAssert.AreEquivalent(expectedDirs, currentDirs);
@@ -132,16 +135,16 @@ public void CreateNewLangProject_AnthropologyCategoriesExist()
{
const string dbName = "AnthropologicalTest";
SureRemoveDb(dbName);
- var preExistingDirs = new List(Directory.GetDirectories(DirectoryFinder.ProjectsDirectory));
+ var preExistingDirs = new List(Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
try
{
// create project
string dbFileName;
using (var threadHelper = new ThreadHelper())
- dbFileName = FdoCache.CreateNewLangProj(new DummyProgressDlg(), dbName, threadHelper);
+ dbFileName = FdoCache.CreateNewLangProj(new DummyProgressDlg(), dbName, FwDirectoryFinder.FdoDirectories, threadHelper);
- using (var cache = FdoCache.CreateCacheFromLocalProjectFile(dbFileName, "en", new DummyProgressDlg()))
+ using (var cache = FdoCache.CreateCacheFromLocalProjectFile(dbFileName, "en", m_ui, FwDirectoryFinder.FdoDirectories, new DummyProgressDlg()))
{
Assert.AreEqual(Strings.ksAnthropologyCategories, cache.LangProject.AnthroListOA.Name.UiString,
"Anthropology Categories list was not properly initialized.");
@@ -155,7 +158,7 @@ public void CreateNewLangProject_AnthropologyCategoriesExist()
}
finally
{
- RemoveTestDirs(preExistingDirs, Directory.GetDirectories(DirectoryFinder.ProjectsDirectory));
+ RemoveTestDirs(preExistingDirs, Directory.GetDirectories(FwDirectoryFinder.ProjectsDirectory));
}
}
@@ -166,8 +169,8 @@ public void CreateNewLangProject_AnthropologyCategoriesExist()
/// name of the FW DB to remove
private static void SureRemoveDb(string dbName)
{
- string dbDir = Path.Combine(DirectoryFinder.ProjectsDirectory, dbName);
- var tmpDbDir = Path.Combine(DirectoryFinder.ProjectsDirectory, "..", dbName);
+ string dbDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, dbName);
+ var tmpDbDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "..", dbName);
if (Directory.Exists(dbDir))
{
// it might seem strange to move the directory first before deleting it.
@@ -209,10 +212,9 @@ private static void RemoveTestDirs(List preExistingDirs, IEnumerable
{
- WritingSystemServices.FindOrCreateWritingSystem(cache, "de", false, true, out wsObjGerman);
+ WritingSystemServices.FindOrCreateWritingSystem(cache, FwDirectoryFinder.TemplateDirectory, "de", false, true, out wsObjGerman);
Assert.That(cache.DefaultVernWs, Is.EqualTo(wsFr));
cache.LangProject.DefaultVernacularWritingSystem = wsObjGerman;
Assert.That(cache.DefaultVernWs, Is.EqualTo(wsObjGerman.Handle));
@@ -243,10 +245,9 @@ public void ChangingLangProjDefaultVernWs_ChangesCacheDefaultVernWs()
[Test]
public void ChangingLangProjDefaultAnalysisWs_ChangesCacheDefaultAnalWs()
{
- using (var threadHelper = new ThreadHelper())
using (
var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
- "en", "fr", "en", threadHelper))
+ "en", "fr", "en", m_ui, FwDirectoryFinder.FdoDirectories))
{
var wsEn = cache.DefaultAnalWs;
Assert.That(cache.LangProject.DefaultAnalysisWritingSystem.Handle, Is.EqualTo(wsEn));
@@ -254,7 +255,7 @@ public void ChangingLangProjDefaultAnalysisWs_ChangesCacheDefaultAnalWs()
UndoableUnitOfWorkHelper.Do("undoit", "redoit", cache.ActionHandlerAccessor,
() =>
{
- WritingSystemServices.FindOrCreateWritingSystem(cache, "de", true, false, out wsObjGerman);
+ WritingSystemServices.FindOrCreateWritingSystem(cache, FwDirectoryFinder.TemplateDirectory, "de", true, false, out wsObjGerman);
Assert.That(cache.DefaultAnalWs, Is.EqualTo(wsEn));
cache.LangProject.DefaultAnalysisWritingSystem = wsObjGerman;
Assert.That(cache.DefaultAnalWs, Is.EqualTo(wsObjGerman.Handle));
@@ -278,10 +279,9 @@ public void ChangingLangProjDefaultAnalysisWs_ChangesCacheDefaultAnalWs()
[Test]
public void ChangingLangProjDefaultPronunciationWs_ChangesCacheDefaultPronunciationWs()
{
- using (var threadHelper = new ThreadHelper())
using (
var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
- "en", "fr", "en", threadHelper))
+ "en", "fr", "en", m_ui, FwDirectoryFinder.FdoDirectories))
{
var wsFr = cache.DefaultPronunciationWs;
Assert.That(cache.LangProject.DefaultPronunciationWritingSystem.Handle, Is.EqualTo(wsFr));
@@ -290,7 +290,7 @@ public void ChangingLangProjDefaultPronunciationWs_ChangesCacheDefaultPronunciat
UndoableUnitOfWorkHelper.Do("undoit", "redoit", cache.ActionHandlerAccessor,
() =>
{
- WritingSystemServices.FindOrCreateWritingSystem(cache, "de", false, true, out wsObjGerman);
+ WritingSystemServices.FindOrCreateWritingSystem(cache, FwDirectoryFinder.TemplateDirectory, "de", false, true, out wsObjGerman);
Assert.That(cache.DefaultPronunciationWs, Is.EqualTo(wsFr));
cache.LangProject.DefaultVernacularWritingSystem = wsObjGerman;
cache.LangProject.CurrentPronunciationWritingSystems.Clear();
@@ -305,7 +305,7 @@ public void ChangingLangProjDefaultPronunciationWs_ChangesCacheDefaultPronunciat
//Assert.That(cache.DefaultPronunciationWs, Is.EqualTo(wsObjGermanIpa.Handle));
// Unless we clear the list it does not regenerate.
- WritingSystemServices.FindOrCreateWritingSystem(cache, "es", false, true, out wsObjSpanish);
+ WritingSystemServices.FindOrCreateWritingSystem(cache, FwDirectoryFinder.TemplateDirectory, "es", false, true, out wsObjSpanish);
// Once we've found a real pronunciation WS, changing the default vernacular should not change it.
Assert.That(cache.DefaultPronunciationWs, Is.EqualTo(wsObjGerman.Handle));
});
@@ -321,91 +321,6 @@ public void ChangingLangProjDefaultPronunciationWs_ChangesCacheDefaultPronunciat
Assert.That(cache.DefaultPronunciationWs, Is.EqualTo(wsObjSpanish.Handle));
}
}
-
- ///
- /// Unit test helper to set up environment in which to test EnsureValidLinkedFilesFolderCore.
- /// testToExecute takes (string defaultFolder, FdoCache cache).
- ///
- public void EnsureValidLinkedFilesFolderCore_TestHelper(Action testToExecute)
- {
- using (var cache = new FdoCache())
- {
- var defaultFolder = FileUtils.ChangePathToPlatform("/ProjectDir/LinkedFiles");
-
- var m_fileOs = new MockFileOS();
- try
- {
- FileUtils.Manager.SetFileAdapter(m_fileOs);
-
- testToExecute(defaultFolder, cache);
- }
- finally
- {
- FileUtils.Manager.Reset();
- }
- }
- }
-
- ///
- [Test]
- public void EnsureValidLinkedFilesFolderCore_IfUsingDefaultDir_CreatesDirIfNotExist()
- {
- EnsureValidLinkedFilesFolderCore_TestHelper((defaultFolder, cache) => {
- var configuredFolder = defaultFolder;
- Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.False, "Unit test not testing what it's supposed to");
- cache.EnsureValidLinkedFilesFolderCore(configuredFolder, defaultFolder);
- Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.True, "Should have created directory");
- });
- }
-
- ///
- [Test]
- public void EnsureValidLinkedFilesFolderCore_IfUsingDefaultDirAndItExists_DoesntCrashOrAnything()
- {
- EnsureValidLinkedFilesFolderCore_TestHelper((defaultFolder, cache) => {
- var configuredFolder = defaultFolder;
-
- // Make default linked files directory already exist
- FileUtils.EnsureDirectoryExists(defaultFolder);
-
- Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.True, "Unit test not testing what it's supposed to");
- // Not crash or anything
- cache.EnsureValidLinkedFilesFolderCore(configuredFolder, defaultFolder);
- });
- }
-
- ///
- [Test]
- public void EnsureValidLinkedFilesFolderCore_NonDefaultLocation_NotCreateNonExistentDir()
- {
- EnsureValidLinkedFilesFolderCore_TestHelper((defaultFolder, cache) => {
- var configuredFolder = FileUtils.ChangePathToPlatform("/nondefaultAndNonexistentPath");
-
- Assert.That(defaultFolder, Is.Not.EqualTo(configuredFolder), "Unit test not set up right");
- Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.False, "Unit test not testing what it's supposed to");
-
- cache.EnsureValidLinkedFilesFolderCore(configuredFolder, defaultFolder);
- Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.False, "Shouldn't have just made the nondefault directory");
- });
- }
-
- ///
- [Test]
- public void EnsureValidLinkedFilesFolderCore_NonDefaultLocationAndExists_DoesntCrashOrAnything()
- {
- EnsureValidLinkedFilesFolderCore_TestHelper((defaultFolder, cache) => {
- var configuredFolder = FileUtils.ChangePathToPlatform("/nondefaultPath");
-
- // Make linked files directory already exist
- FileUtils.EnsureDirectoryExists(configuredFolder);
-
- Assert.That(defaultFolder, Is.Not.EqualTo(configuredFolder), "Unit test not set up right");
- Assert.That(FileUtils.DirectoryExists(configuredFolder), Is.True, "Unit test not testing what it's supposed to");
-
- // Not crash or anything
- cache.EnsureValidLinkedFilesFolderCore(configuredFolder, defaultFolder);
- });
- }
}
/// ----------------------------------------------------------------------------------------
@@ -416,6 +331,8 @@ public void EnsureValidLinkedFilesFolderCore_NonDefaultLocationAndExists_DoesntC
[TestFixture]
public class FdoCacheDisposedTests: BaseTest
{
+ private readonly IFdoUI m_ui = new DummyFdoUI();
+
///
/// Make sure the CheckDisposed method works.
///
@@ -424,16 +341,13 @@ public class FdoCacheDisposedTests: BaseTest
public void CacheCheckDisposedTest()
{
// This can't be in the minimalist class, because it disposes the cache.
- using (var threadHelper = new ThreadHelper())
- {
- var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
- "en", "fr", "en", threadHelper);
- // Init backend data provider
- var dataSetup = cache.ServiceLocator.GetInstance();
- dataSetup.LoadDomain(BackendBulkLoadDomain.All);
- cache.Dispose();
- cache.CheckDisposed();
- }
+ var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
+ "en", "fr", "en", m_ui, FwDirectoryFinder.FdoDirectories);
+ // Init backend data provider
+ var dataSetup = cache.ServiceLocator.GetInstance();
+ dataSetup.LoadDomain(BackendBulkLoadDomain.All);
+ cache.Dispose();
+ cache.CheckDisposed();
}
///
@@ -442,18 +356,15 @@ public void CacheCheckDisposedTest()
[Test]
public void CacheIsDisposedTest()
{
- using (var threadHelper = new ThreadHelper())
- {
- // This can't be in the minimalist class, because it disposes the cache.
- var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
- "en", "fr", "en", threadHelper);
- // Init backend data provider
- var dataSetup = cache.ServiceLocator.GetInstance();
- dataSetup.LoadDomain(BackendBulkLoadDomain.All);
- Assert.IsFalse(cache.IsDisposed, "Should not have been disposed.");
- cache.Dispose();
- Assert.IsTrue(cache.IsDisposed, "Should have been disposed.");
- }
+ // This can't be in the minimalist class, because it disposes the cache.
+ var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
+ "en", "fr", "en", m_ui, FwDirectoryFinder.FdoDirectories);
+ // Init backend data provider
+ var dataSetup = cache.ServiceLocator.GetInstance();
+ dataSetup.LoadDomain(BackendBulkLoadDomain.All);
+ Assert.IsFalse(cache.IsDisposed, "Should not have been disposed.");
+ cache.Dispose();
+ Assert.IsTrue(cache.IsDisposed, "Should have been disposed.");
}
///
@@ -462,17 +373,14 @@ public void CacheIsDisposedTest()
[Test]
public void CacheDisposedForFDOObject()
{
- using (var threadHelper = new ThreadHelper())
- {
- var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
- "en", "fr", "en", threadHelper);
- // Init backend data provider
- var dataSetup = cache.ServiceLocator.GetInstance();
- dataSetup.LoadDomain(BackendBulkLoadDomain.All);
- var lp = cache.LanguageProject;
- cache.Dispose();
- Assert.IsFalse(lp.IsValidObject);
- }
+ var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
+ "en", "fr", "en", m_ui, FwDirectoryFinder.FdoDirectories);
+ // Init backend data provider
+ var dataSetup = cache.ServiceLocator.GetInstance();
+ dataSetup.LoadDomain(BackendBulkLoadDomain.All);
+ var lp = cache.LanguageProject;
+ cache.Dispose();
+ Assert.IsFalse(lp.IsValidObject);
}
///
@@ -481,9 +389,8 @@ public void CacheDisposedForFDOObject()
[Test]
public void FDOObjectDeleted()
{
- using (var threadHelper = new ThreadHelper())
using (var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
- "en", "fr", "en", threadHelper))
+ "en", "fr", "en", m_ui, FwDirectoryFinder.FdoDirectories))
{
// Init backend data provider
var dataSetup = cache.ServiceLocator.GetInstance();
@@ -504,10 +411,9 @@ public void FDOObjectDeleted()
[Test]
public void NumberOfRemoteClients_NotClientServer_ReturnsZero()
{
- using (var threadHelper = new ThreadHelper())
using (
var cache = FdoCache.CreateCacheWithNewBlankLangProj(new TestProjectId(FDOBackendProviderType.kMemoryOnly, null),
- "en", "fr", "en", threadHelper))
+ "en", "fr", "en", m_ui, FwDirectoryFinder.FdoDirectories))
{
Assert.AreEqual(0, cache.NumberOfRemoteClients);
}
diff --git a/Src/FDO/FDOTests/FdoScriptureTests.cs b/Src/FDO/FDOTests/FdoScriptureTests.cs
index bd962dfa33..d3b7c91cfa 100644
--- a/Src/FDO/FDOTests/FdoScriptureTests.cs
+++ b/Src/FDO/FDOTests/FdoScriptureTests.cs
@@ -12,7 +12,9 @@
using NUnit.Framework;
using SIL.FieldWorks.Common.COMInterfaces;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.ScriptureUtils;
+using SIL.FieldWorks.Resources;
using SIL.Utils;
using SIL.FieldWorks.Test.TestUtils;
using SILUBS.SharedScrUtils;
@@ -246,7 +248,8 @@ internal class DummyScrChecksDataSource : ScrChecksDataSource
/// The maximum number of identical errors that will
/// be allowed for a Scripture check.
/// ------------------------------------------------------------------------------------
- public DummyScrChecksDataSource(FdoCache cache, int maxIdenticalErrors) : base(cache)
+ public DummyScrChecksDataSource(FdoCache cache, int maxIdenticalErrors) : base(cache, ResourceHelper.GetResourceString("kstidPunctCheckWhitespaceChar"),
+ FwDirectoryFinder.LegacyWordformingCharOverridesFile)
{
m_maxIdenticalErrors = maxIdenticalErrors;
}
@@ -309,19 +312,6 @@ public override void TestSetup()
m_servloc = Cache.ServiceLocator;
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Override to end the undoable UOW, Undo everything, and 'commit',
- /// which will essentially clear out the Redo stack.
- ///
- /// ------------------------------------------------------------------------------------
- public override void TestTearDown()
- {
- base.TestTearDown();
-
- ReflectionHelper.CallMethod(typeof(ScriptureServices), "InitializeWarningHandler");
- }
-
/// ------------------------------------------------------------------------------------
///
/// Does setup for all the tests
@@ -764,7 +754,7 @@ public void AdjustAnnotationReferences_WithQuote()
[Test]
public void RecordError_ParaContentsToken()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
Dictionary> bkChkFailedLst =
@@ -810,7 +800,7 @@ public void RecordError_ParaContentsToken()
[Test]
public void RecordError_ParaContentsToken_SecondRun()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 10);
Dictionary> bkChkFailedLst =
@@ -854,7 +844,7 @@ public void RecordError_ParaContentsToken_SecondRun()
[Test]
public void RecordError_PictureCaptionToken()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
ScrCheckingToken tok = new DummyPictureCheckingToken(m_scr, Cache.DefaultUserWs, "en");
Dictionary> bkChkFailedLst =
@@ -897,7 +887,7 @@ public void RecordError_PictureCaptionToken()
[Test]
public void RecordError_Duplicate()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
check.m_ErrorsToReport.Add(new DummyEditorialCheck.DummyError(tok, 5, 8, "Lousy message"));
@@ -926,7 +916,7 @@ public void RecordError_Duplicate()
[Test]
public void RecordError_DuplicateAfterAdjustingReference()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
tok.MissingStartRef = new BCVRef(tok.StartRef);
@@ -1248,7 +1238,7 @@ public void RecordError_ErrorMaxIncreased()
[Test]
public void RecordError_Duplicate_SameErrorTwiceInVerse()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
check.m_ErrorsToReport.Add(new DummyEditorialCheck.DummyError(tok, 5, 2, "Lousy message"));
@@ -1289,7 +1279,7 @@ public void RecordError_Duplicate_SameErrorTwiceInVerse()
[Test]
public void RunCheck_ScrCheckRunRecordsWithFixedInconsistency()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
check.m_ErrorsToReport.Add(new DummyEditorialCheck.DummyError(tok, 5, 2, "Verbification"));
@@ -1304,7 +1294,7 @@ public void RunCheck_ScrCheckRunRecordsWithFixedInconsistency()
Assert.AreEqual(1, annotations.NotesOS.Count);
IScrCheckRun scr =
- annotations.ChkHistRecsOC.First();
+ annotations.ChkHistRecsOC.First();
Assert.AreEqual(ScrCheckRunResult.Inconsistencies, scr.Result);
Assert.AreEqual(NoteStatus.Open, annotations.NotesOS[0].ResolutionStatus);
@@ -1315,7 +1305,7 @@ public void RunCheck_ScrCheckRunRecordsWithFixedInconsistency()
Assert.AreEqual(1, annotations.ChkHistRecsOC.Count);
Assert.AreEqual(0, annotations.NotesOS.Count);
- scr = annotations.ChkHistRecsOC.First();
+ scr = annotations.ChkHistRecsOC.First();
Assert.AreEqual(ScrCheckRunResult.NoInconsistencies, scr.Result);
}
@@ -1327,7 +1317,7 @@ public void RunCheck_ScrCheckRunRecordsWithFixedInconsistency()
[Test]
public void RunCheck_ScrCheckRunRecordsWithOneBookOneCheck()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
check.m_ErrorsToReport.Add(new DummyEditorialCheck.DummyError(tok, 5, 2, "Verbification"));
@@ -1370,7 +1360,7 @@ public void RunCheck_ScrCheckRunRecordsWithOneBookOneCheck()
[Test]
public void RunCheck_ScrCheckRunRecordsWithOneBookTwoChecks()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check1 = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
check1.m_ErrorsToReport.Add(new DummyEditorialCheck.DummyError(tok, 5, 2, "Verbification"));
@@ -1421,7 +1411,7 @@ public void RunCheck_ScrCheckRunRecordsWithOneBookTwoChecks()
[Test]
public void RunCheck_CorrectedErrorGetsDeleted()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
check.m_ErrorsToReport.Add(new DummyEditorialCheck.DummyError(tok, 5, 8, "Lousy message"));
@@ -1457,7 +1447,7 @@ public void RunCheck_CorrectedErrorGetsDeleted()
[Test]
public void RecordError_NearDuplicate_DifferByMessage()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
check.m_ErrorsToReport.Add(new DummyEditorialCheck.DummyError(tok, 5, 8, "Lousy message"));
@@ -1492,7 +1482,7 @@ public void RecordError_NearDuplicate_DifferOnlyByParaHvo()
BCVRef reference = new BCVRef(1, 2, 3);
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(book,
Cache.DefaultVernWs, 0, reference, reference);
@@ -1538,7 +1528,7 @@ public void RecordError_NearDuplicate_DifferOnlyByParaHvo()
public void RecordError_NearDuplicate_DifferByCheck()
{
IFdoServiceLocator servloc = Cache.ServiceLocator;
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
ICmAnnotationDefn annDefnChkError = servloc.GetInstance().CheckingError;
ICmAnnotationDefn errorCheck1 = servloc.GetInstance().Create(
Guid.NewGuid(), annDefnChkError);
@@ -1581,7 +1571,7 @@ public void RecordError_NearDuplicate_DifferByStartRef()
{
BCVRef endRef = new BCVRef(1, 2, 3);
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr,
Cache.DefaultVernWs, 0, new BCVRef(1, 2, 3), endRef);
@@ -1616,7 +1606,7 @@ public void RecordError_NearDuplicate_DifferByEndRef()
{
BCVRef startRef = new BCVRef(1, 2, 3);
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr,
Cache.DefaultVernWs, 0, startRef, new BCVRef(1, 2, 3));
@@ -1649,7 +1639,7 @@ public void RecordError_NearDuplicate_DifferByEndRef()
[Test]
public void RecordError_NearDuplicate_DifferByCitedText()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
DummyEditorialCheck check = new DummyEditorialCheck(kCheckId1);
ScrCheckingToken tok = new DummyParaCheckingToken(m_scr, Cache.DefaultVernWs, 0);
check.m_ErrorsToReport.Add(new DummyEditorialCheck.DummyError(tok, 0, 4, "Message"));
@@ -1678,7 +1668,7 @@ public void RecordError_NearDuplicate_DifferByCitedText()
[Test]
public void GetTextTokens_Chapter0()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
int iExodus = 2;
IScrBook exodus = AddBookToMockedScripture(iExodus, "Exodus");
AddTitleToMockedBook(exodus, "Exodus");
@@ -1712,7 +1702,7 @@ public void GetTextTokens_Chapter0()
[Test]
public void GetTextTokens_WholeBook()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
AddBookToMockedScripture(1, "Genesis");
int iExodus = 2;
IScrBook exodus = AddBookToMockedScripture(iExodus, "Exodus");
@@ -1801,7 +1791,7 @@ public void GetTextTokens_FirstChapter()
IScrBook exodus = AddBookToMockedScripture(iExodus, "Exodus");
AddTitleToMockedBook(exodus, "Exodus");
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
IScrSection section = AddSectionToMockedBook(exodus, true);
IStTxtPara para = AddParaToMockedText(section.HeadingOA, ScrStyleNames.IntroSectionHead);
AddRunToMockedPara(para, "Everything you wanted to know about Exodus but were afraid to ask", null);
@@ -1869,7 +1859,7 @@ public void GetTextTokens_DifferentWritingSystem()
AddTitleToMockedBook(exodus, "Exodus");
// Get the text (and set the valid characters for each writing system).
- var dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
dataSource.GetText(iExodus, 1);
iWs = 0;
@@ -1891,7 +1881,7 @@ public void GetTextTokens_DifferentWritingSystem()
[Test]
public void GetTextTokens_LastChapter()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
AddBookToMockedScripture(1, "Genesis");
int iExodus = 2;
IScrBook exodus = AddBookToMockedScripture(iExodus, "Exodus");
@@ -1939,7 +1929,7 @@ public void GetTextTokens_LastChapter()
public void GetTextTokens_ChapterStartsAndEndsMidSection()
{
- ScrChecksDataSource dataSource = new ScrChecksDataSource(Cache);
+ ScrChecksDataSource dataSource = CreateScrChecksDataSource();
AddBookToMockedScripture(1, "Genesis");
int iExodus = 2;
IScrBook exodus = AddBookToMockedScripture(iExodus, "Exodus");
@@ -1993,6 +1983,12 @@ public void GetTextTokens_ChapterStartsAndEndsMidSection()
}
#region Helper methods
+ private ScrChecksDataSource CreateScrChecksDataSource()
+ {
+ return new ScrChecksDataSource(Cache, ResourceHelper.GetResourceString("kstidPunctCheckWhitespaceChar"),
+ FwDirectoryFinder.LegacyWordformingCharOverridesFile);
+ }
+
/// ------------------------------------------------------------------------------------
///
/// Verifies that an "empty" journal text has a single empty paragraph with the correct
@@ -2528,6 +2524,9 @@ public void SavedVersion_TestFootnoteOrder()
[Test]
public void SavedVersion_BogusUnownedFootnoteORC()
{
+ var ui = (DummyFdoUI) Cache.ServiceLocator.GetInstance();
+ ui.Reset();
+
IStText titleText;
IScrBook hebrews = m_servloc.GetInstance().Create(58, out titleText);
IStTxtPara title = AddParaToMockedText(titleText, ScrStyleNames.MainBookTitle);
@@ -2547,8 +2546,6 @@ public void SavedVersion_BogusUnownedFootnoteORC()
IScrFootnote footnoteOrig2 = AddFootnote(hebrews, para2, 0);
// archive draft
- string sWarningMessage = null;
- ReflectionHelper.SetAction(typeof(ScriptureServices), "ReportWarning", sMsg => { sWarningMessage = sMsg; });
IScrDraft draft = m_servloc.GetInstance().Create("", new [] { hebrews });
Assert.AreEqual(1, m_scr.ArchivedDraftsOC.Count);
@@ -2594,7 +2591,8 @@ public void SavedVersion_BogusUnownedFootnoteORC()
string sOrc = tss.get_RunText(0);
Assert.AreEqual(StringUtils.kChObject, sOrc[0]);
- Assert.AreEqual("1 footnote(s) in HEB did not correspond to any owned footnotes in the vernacular text of that book. They have been moved to the end of the footnote sequence.", sWarningMessage);
+ // Expecting error to have been thrown in ScriptureServices.AdjustObjectsInArchivedBook, so now we make sure the error is the one expected.
+ Assert.AreEqual("1 footnote(s) in HEB did not correspond to any owned footnotes in the vernacular text of that book. They have been moved to the end of the footnote sequence.", ui.ErrorMessage);
}
/// ------------------------------------------------------------------------------------
@@ -2934,7 +2932,7 @@ public override void TestSetup()
AddScrStyle("Parallel Passage", ContextValues.Text, StructureValues.Heading, FunctionValues.Prose, false);
AddScrStyle("Line 1", ContextValues.Text, StructureValues.Body, FunctionValues.Prose, false);
- m_stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
+ m_stylesheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
AddBookWithTwoSections(40, "Matthew");
m_philemon = AddBookWithTwoSections(57, "Philemon");
diff --git a/Src/FDO/FDOTests/FdoTestBase.cs b/Src/FDO/FDOTests/FdoTestBase.cs
index e9c5e50c72..f2efcf26eb 100644
--- a/Src/FDO/FDOTests/FdoTestBase.cs
+++ b/Src/FDO/FDOTests/FdoTestBase.cs
@@ -10,18 +10,15 @@
// Implements FdoTestBase, the base class for the FDO tests
//
-using System;
-using System.Collections.Generic;
using System.IO;
-using System.Linq;
using NUnit.Framework;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.Common.FwUtils;
+using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
using SIL.CoreImpl;
-using SIL.FieldWorks.FDO.Infrastructure.Impl;
namespace SIL.FieldWorks.FDO.FDOTests
{
@@ -101,7 +98,8 @@ protected void SetupEverythingButBase()
DisposeEverythingButBase();
// We need FieldWorks here to get the correct registry key HKLM\Software\SIL\FieldWorks.
// The default without this would be HKLM\Software\SIL\SIL FieldWorks, which breaks some tests.
- SIL.Utils.RegistryHelper.ProductName = "FieldWorks";
+ RegistryHelper.ProductName = "FieldWorks";
+ FdoTestHelper.SetupClientServerServices();
m_cache = CreateCache();
m_actionHandler = m_cache.ServiceLocator.GetInstance();
}
@@ -125,11 +123,7 @@ public override void FixtureTeardown()
protected void DisposeEverythingButBase()
{
if (m_cache != null)
- {
- if (m_cache.ThreadHelper != null)
- m_cache.ThreadHelper.Dispose();
m_cache.Dispose();
- }
m_cache = null;
m_actionHandler = null;
}
@@ -176,9 +170,8 @@ public virtual void TestTearDown()
/// a working FdoCache
protected FdoCache BootstrapSystem(IProjectIdentifier projectId, BackendBulkLoadDomain loadType)
{
- // This thread helper will be disposed in FixtureTeardown along with the cache.
- var retval = m_internalRestart ? FdoCache.CreateCacheFromExistingData(projectId, "en", new DummyProgressDlg()) :
- FdoCache.CreateCacheWithNewBlankLangProj(projectId, "en", "fr", "en", new ThreadHelper());
+ var retval = m_internalRestart ? FdoCache.CreateCacheFromExistingData(projectId, "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories, new DummyProgressDlg()) :
+ FdoCache.CreateCacheWithNewBlankLangProj(projectId, "en", "fr", "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories);
var dataSetup = retval.ServiceLocator.GetInstance();
dataSetup.LoadDomain(loadType);
return retval;
diff --git a/Src/FDO/FDOTests/FdoTestHelper.cs b/Src/FDO/FDOTests/FdoTestHelper.cs
index 5d8021889a..17a17642f5 100644
--- a/Src/FDO/FDOTests/FdoTestHelper.cs
+++ b/Src/FDO/FDOTests/FdoTestHelper.cs
@@ -10,6 +10,7 @@
using System.Linq;
using SIL.FieldWorks.Common.COMInterfaces;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.CoreImpl;
using SIL.Utils;
@@ -410,5 +411,14 @@ public static void VerifyHyperlinkPropsAreCorrect(ITsTextProps props, int expect
Assert.AreEqual(Convert.ToChar((int)FwObjDataTypes.kodtExternalPathName), sObjData[0]);
Assert.AreEqual(sUrl, sObjData.Substring(1));
}
+
+ ///
+ /// Sets up the client server services.
+ ///
+ public static void SetupClientServerServices()
+ {
+ ClientServerServices.SetCurrentToDb4OBackend(new DummyFdoUI(), FwDirectoryFinder.FdoDirectories,
+ () => FwDirectoryFinder.ProjectsDirectory == FwDirectoryFinder.ProjectsDirectoryLocalMachine);
+ }
}
}
diff --git a/Src/FDO/FDOTests/FwCharacterCategorizerTests.cs b/Src/FDO/FDOTests/FwCharacterCategorizerTests.cs
index 864078621a..409426f136 100644
--- a/Src/FDO/FDOTests/FwCharacterCategorizerTests.cs
+++ b/Src/FDO/FDOTests/FwCharacterCategorizerTests.cs
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using NUnit.Framework;
using SIL.FieldWorks.Common.COMInterfaces;
+using SIL.FieldWorks.Common.FwUtils;
using SILUBS.SharedScrUtils;
using SIL.FieldWorks.FDO.DomainServices;
@@ -51,7 +52,7 @@ public void SymbolPunctuationOnly()
"a\uFFFCb\uFFFCc\uFFFCd\uFFFCe" +
"1\uFFFC2\uFFFC3\uFFFC4\uFFFC5" +
"'\uFFFC-\uFFFC#" +
- "", "Test WS", null, null);
+ "", "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ILgCharacterPropertyEngine lgCharPropEngineEn = Cache.WritingSystemFactory.get_CharPropEngine(
m_wsEn);
@@ -73,7 +74,7 @@ public void WordAndPuncs_OverridePunc()
"a\uFFFCb\uFFFCc\uFFFCd\uFFFCe\uFFFC." +
"1\uFFFC2\uFFFC3\uFFFC4\uFFFC5" +
"'\uFFFC-\uFFFC#" +
- "", "Test WS", null, null);
+ "", "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ILgCharacterPropertyEngine lgCharPropEngineEn = Cache.WritingSystemFactory.get_CharPropEngine(
m_wsEn);
@@ -100,7 +101,7 @@ public void WordAndPuncs_Spaces()
"a\uFFFCb\uFFFCc" +
"1\uFFFC2\uFFFC3\uFFFC4\uFFFC5" +
"-\uFFFCU+0020" +
- "", "Test WS", null, null);
+ "", "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
var english = Cache.ServiceLocator.WritingSystemManager.Get("en");
var lgCharPropEngineEn = Cache.WritingSystemFactory.get_CharPropEngine(english.Handle);
@@ -126,7 +127,7 @@ public void WordAndPuncs_EmptyString()
"a\uFFFCb\uFFFCc" +
"1\uFFFC2\uFFFC3\uFFFC4\uFFFC5" +
"-\uFFFCU+0020" +
- "", "Test WS", null, null);
+ "", "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
var english = Cache.ServiceLocator.WritingSystemManager.Get("en");
var lgCharPropEngineEn = Cache.WritingSystemFactory.get_CharPropEngine(
english.Handle);
@@ -152,7 +153,7 @@ public void WordAndPuncs_NoOverridePunc()
"a\uFFFCb\uFFFCc\uFFFCd\uFFFCe" +
"1\uFFFC2\uFFFC3\uFFFC4\uFFFC5" +
"'\uFFFC-\uFFFC#" +
- "", "Test WS", null, null);
+ "", "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ILgCharacterPropertyEngine lgCharPropEngineEn = Cache.WritingSystemFactory.get_CharPropEngine(
m_wsEn);
diff --git a/Src/FDO/FDOTests/FwSetupFixtureClass.cs b/Src/FDO/FDOTests/FwSetupFixtureClass.cs
index 0825a659a3..ac47a4a6df 100644
--- a/Src/FDO/FDOTests/FwSetupFixtureClass.cs
+++ b/Src/FDO/FDOTests/FwSetupFixtureClass.cs
@@ -3,6 +3,7 @@
// (http://www.gnu.org/licenses/lgpl-2.1.html)
using NUnit.Framework;
+using SIL.FieldWorks.FDO.FDOTests;
using SIL.Utils;
namespace SIL.FieldWorks
@@ -24,6 +25,7 @@ public class FwSetupFixtureClass
[SetUp]
public void SetUp()
{
+ FdoTestHelper.SetupClientServerServices();
}
///--------------------------------------------------------------------------------------
diff --git a/Src/FDO/FDOTests/FwStyleSheetTests.cs b/Src/FDO/FDOTests/FwStyleSheetTests.cs
index 7b3c56690d..76b24ade5a 100644
--- a/Src/FDO/FDOTests/FwStyleSheetTests.cs
+++ b/Src/FDO/FDOTests/FwStyleSheetTests.cs
@@ -15,6 +15,7 @@
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.Common.ScriptureUtils;
using SIL.FieldWorks.FDO.DomainServices;
+using SIL.FieldWorks.Resources;
namespace SIL.FieldWorks.FDO.FDOTests.CellarTests
{
@@ -92,7 +93,7 @@ public override void TestSetup()
base.TestSetup();
m_styleSheet = new DummyFwStyleSheet();
- m_styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles);
+ m_styleSheet.Init(Cache, m_scr.Hvo, ScriptureTags.kflidStyles, ResourceHelper.DefaultParaCharsStyleName);
}
/// ------------------------------------------------------------------------------------
diff --git a/Src/FDO/FDOTests/GeneratedPropertyAccessorTests.cs b/Src/FDO/FDOTests/GeneratedPropertyAccessorTests.cs
index 3346c8577f..dd47cb9ca2 100644
--- a/Src/FDO/FDOTests/GeneratedPropertyAccessorTests.cs
+++ b/Src/FDO/FDOTests/GeneratedPropertyAccessorTests.cs
@@ -15,6 +15,7 @@
using System;
using System.Linq;
using NUnit.Framework;
+using SIL.CoreImpl;
using SIL.FieldWorks.FDO.FDOTests;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.Common.FwUtils;
diff --git a/Src/FDO/FDOTests/LangProjectTests.cs b/Src/FDO/FDOTests/LangProjectTests.cs
index 2c6f1df011..77343cb94b 100644
--- a/Src/FDO/FDOTests/LangProjectTests.cs
+++ b/Src/FDO/FDOTests/LangProjectTests.cs
@@ -7,16 +7,9 @@
using System;
using System.IO;
-using System.Collections;
using System.Collections.Generic;
-using System.Reflection;
-using System.Diagnostics;
-
using NUnit.Framework;
-
-using SIL.FieldWorks.FDO;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
using SIL.FieldWorks.Common.FwUtils;
using SIL.CoreImpl;
@@ -179,14 +172,14 @@ public void AddingWritingSystems()
public void LinkedFilesRootDirTests()
{
//test when LinkedFiles is in the project's root folder
- var projectFolder = Path.Combine(DirectoryFinder.ProjectsDirectory, "TestProjectName");
+ var projectFolder = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "TestProjectName");
var linkedFilesFullPath = Path.Combine(projectFolder, "LinkedFiles");
Cache.LanguageProject.LinkedFilesRootDir = linkedFilesFullPath;
var outputLinkedFilesFullPath = Cache.LanguageProject.LinkedFilesRootDir;
Assert.True(linkedFilesFullPath.Equals(outputLinkedFilesFullPath));
//test when linked files is in FW Projects folder
- linkedFilesFullPath = Path.Combine(DirectoryFinder.ProjectsDirectory, "LinkedFiles");
+ linkedFilesFullPath = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "LinkedFiles");
Cache.LanguageProject.LinkedFilesRootDir = linkedFilesFullPath;
outputLinkedFilesFullPath = Cache.LanguageProject.LinkedFilesRootDir;
Assert.True(linkedFilesFullPath.Equals(outputLinkedFilesFullPath));
diff --git a/Src/FDO/FDOTests/LingTests.cs b/Src/FDO/FDOTests/LingTests.cs
index 286070aca4..6125c6e709 100644
--- a/Src/FDO/FDOTests/LingTests.cs
+++ b/Src/FDO/FDOTests/LingTests.cs
@@ -16,11 +16,13 @@
using System.Xml;
using NUnit.Framework;
using SIL.FieldWorks.Common.COMInterfaces;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainImpl;
using SIL.FieldWorks.FDO.FDOTests.CellarTests;
using SIL.FieldWorks.FDO.Validation;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.CoreImpl;
+using SIL.FieldWorks.FdoUi;
using SIL.Utils;
namespace SIL.FieldWorks.FDO.FDOTests.LingTests
@@ -2470,11 +2472,13 @@ public void ConvertLexEntryInflTypes()
using (var progressBar = new ProgressBar())
{
+ IProgress progressBarWrapper = new ProgressBarWrapper(progressBar);
+
var itemsToChange = new List();
itemsToChange.Add(lexEntryType1);
itemsToChange.Add(lexEntryType1Sub1);
- Cache.LangProject.LexDbOA.ConvertLexEntryInflTypes(progressBar, itemsToChange);
+ Cache.LangProject.LexDbOA.ConvertLexEntryInflTypes(progressBarWrapper, itemsToChange);
var leit1 = ler1.VariantEntryTypesRS[0];
Assert.AreEqual(LexEntryInflTypeTags.kClassId, leit1.ClassID, "first lex entry type of first entry should be irregularly inflected form");
leit1 = ler1.VariantEntryTypesRS[1];
@@ -2525,11 +2529,13 @@ public void ConvertLexEntryTypes()
using (var progressBar = new ProgressBar())
{
+ IProgress progressBarWrapper = new ProgressBarWrapper(progressBar);
+
var itemsToChange = new List();
itemsToChange.Add(lexEntryInflType1);
itemsToChange.Add(lexEntryInflType1Sub1);
- Cache.LangProject.LexDbOA.ConvertLexEntryTypes(progressBar, itemsToChange);
+ Cache.LangProject.LexDbOA.ConvertLexEntryTypes(progressBarWrapper, itemsToChange);
var let1 = ler1.VariantEntryTypesRS[0];
Assert.AreEqual(LexEntryTypeTags.kClassId, let1.ClassID, "first lex entry type of first entry should be variant");
let1 = ler1.VariantEntryTypesRS[1];
diff --git a/Src/FDO/FDOTests/LinkedFilesRelativePathHelperTests.cs b/Src/FDO/FDOTests/LinkedFilesRelativePathHelperTests.cs
new file mode 100644
index 0000000000..57dead5112
--- /dev/null
+++ b/Src/FDO/FDOTests/LinkedFilesRelativePathHelperTests.cs
@@ -0,0 +1,137 @@
+using System;
+using System.IO;
+using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
+
+namespace SIL.FieldWorks.FDO.FDOTests
+{
+ ///
+ /// Test fixture for LinkedFilesRelativePathHelper
+ ///
+ [TestFixture]
+ public class LinkedFilesRelativePathHelperTests
+ {
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetLinkedFilesRelativePathFromFullPath method
+ ///
+ /// ------------------------------------------------------------------------------------
+ [Test]
+ public void GetLinkedFilesRelativePathFromFullPath()
+ {
+ Assert.AreEqual(String.Format("%proj%{0}LinkedFiles", Path.DirectorySeparatorChar),
+ LinkedFilesRelativePathHelper.GetLinkedFilesRelativePathFromFullPath(FwDirectoryFinder.ProjectsDirectory, String.Format("%proj%{0}LinkedFiles", Path.DirectorySeparatorChar),
+ Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO", "FDOTests", "BackupRestore", "Project"),
+ "Project"));
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetLinkedFilesFullPathFromRelativePath method
+ ///
+ /// ------------------------------------------------------------------------------------
+ [Test]
+ public void GetLinkedFilesFullPathFromRelativePath()
+ {
+ var projectPath = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "TestProject");
+ var linkedFilesRootDir = Path.Combine(projectPath, "LinkedFiles");
+ var linkedFilesPath = LinkedFilesRelativePathHelper.GetLinkedFilesFullPathFromRelativePath(FwDirectoryFinder.ProjectsDirectory,
+ String.Format("%proj%{0}LinkedFiles", Path.DirectorySeparatorChar), projectPath);
+
+ Assert.AreEqual(linkedFilesRootDir, linkedFilesPath);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetFullFilePathFromRelativeLFPath method
+ ///
+ /// ------------------------------------------------------------------------------------
+ [Test]
+ public void GetFullFilePathFromRelativeLFPath()
+ {
+ var linkedFilesRootDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "TestProject", "LinkedFiles");
+ var fullLFPath = LinkedFilesRelativePathHelper.GetFullFilePathFromRelativeLFPath(String.Format("%lf%{0}AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar), linkedFilesRootDir);
+ var audioVisualFile = Path.Combine(linkedFilesRootDir, "AudioVisual", "StarWars.mvi");
+ Assert.AreEqual(audioVisualFile, fullLFPath);
+
+ //if a fully rooted path is passed in the return value should be null.
+ var projectRootDir = FwDirectoryFinder.DataDirectory;
+ fullLFPath = LinkedFilesRelativePathHelper.GetFullFilePathFromRelativeLFPath(projectRootDir, linkedFilesRootDir);
+ Assert.True(string.IsNullOrEmpty(fullLFPath));
+
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetRelativeLFPathFromFullFilePath method
+ ///
+ /// ------------------------------------------------------------------------------------
+ [Test]
+ public void GetRelativeLFPathFromFullFilePath()
+ {
+ var linkedFilesRootDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "TestProject", "LinkedFiles");
+ var audioVisualFile = Path.Combine(linkedFilesRootDir, "AudioVisual", "StarWars.mvi");
+ var relativeLFPath = LinkedFilesRelativePathHelper.GetRelativeLFPathFromFullFilePath(audioVisualFile, linkedFilesRootDir);
+ Assert.AreEqual(String.Format("%lf%{0}AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar), relativeLFPath);
+
+ //Ensure empty string is returned when the path is not relative to the LinkedFiles directory.
+ var pathNotUnderLinkedFiles = Path.Combine(FwDirectoryFinder.DataDirectory, "LordOfTheRings.mvi");
+ relativeLFPath = LinkedFilesRelativePathHelper.GetRelativeLFPathFromFullFilePath(pathNotUnderLinkedFiles, linkedFilesRootDir);
+ Assert.True(string.IsNullOrEmpty(relativeLFPath));
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetRelativeLinkedFilesPath method
+ ///
+ /// ------------------------------------------------------------------------------------
+ [Test]
+ public void GetRelativeLinkedFilesPath()
+ {
+ var linkedFilesRootDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "TestProject", "LinkedFiles");
+ var audioVisualFile = Path.Combine(linkedFilesRootDir, "AudioVisual", "StarWars.mvi");
+ var relativeLFPath = LinkedFilesRelativePathHelper.GetRelativeLinkedFilesPath(audioVisualFile, linkedFilesRootDir);
+ Assert.True(String.Equals(String.Format("AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar), relativeLFPath));
+
+ //Ensure ORIGINAL path is returned when the path is not relative to the LinkedFiles directory.
+ var pathNotUnderLinkedFiles = Path.Combine(FwDirectoryFinder.DataDirectory, "LordOfTheRings.mvi");
+ relativeLFPath = LinkedFilesRelativePathHelper.GetRelativeLinkedFilesPath(pathNotUnderLinkedFiles, linkedFilesRootDir);
+ Assert.True(String.Equals(pathNotUnderLinkedFiles,relativeLFPath));
+ Assert.That(LinkedFilesRelativePathHelper.GetRelativeLinkedFilesPath(
+ "silfw://localhost/link?app%3dflex%26database%3dc%3a%5cTestLangProj%5cTestLangProj.fwdata%26server%3d%26tool%3dnaturalClassedit%26guid%3d43c9ba97-2883-4f95-aa5d-ef9309e85025%26tag%3d",
+ relativeLFPath), Is.Null, "hyperlinks should be left well alone!!");
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetFullPathFromRelativeLFPath method
+ ///
+ /// ------------------------------------------------------------------------------------
+ [Test]
+ public void GetFullPathFromRelativeLFPath()
+ {
+ var linkedFilesRootDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "TestProject", "LinkedFiles");
+ var fullLFPath = LinkedFilesRelativePathHelper.GetFullPathFromRelativeLFPath(String.Format("AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar), linkedFilesRootDir);
+ var audioVisualFile = Path.Combine(linkedFilesRootDir, "AudioVisual", "StarWars.mvi");
+ Assert.AreEqual(audioVisualFile, fullLFPath);
+
+ //if a fully rooted path is passed in the return value should be the path that was passed in.
+ var fileUnderProjectRootDir = String.Format("{1}{0}AudioVisual{0}StarWars.mvi", Path.DirectorySeparatorChar, FwDirectoryFinder.DataDirectory);
+ fullLFPath = LinkedFilesRelativePathHelper.GetFullPathFromRelativeLFPath(fileUnderProjectRootDir, linkedFilesRootDir);
+ Assert.AreEqual(fullLFPath, fileUnderProjectRootDir);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Tests the GetFullPathFromRelativeLFPath method with illegal characters
+ ///
+ /// ------------------------------------------------------------------------------------
+ [Test]
+ public void GetFullPathFromRelativeLFPath_WithIllegalCharacters_ReturnsSpecialPath()
+ {
+ var linkedFilesRootDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, "TestProject", "LinkedFiles");
+ var fullLFPath = LinkedFilesRelativePathHelper.GetFullPathFromRelativeLFPath("1\";1\"", linkedFilesRootDir);
+ Assert.That(fullLFPath, Is.EqualTo(Path.Combine(linkedFilesRootDir,"__ILLEGALCHARS__")));
+ }
+ }
+}
diff --git a/Src/FDO/FDOTests/ParagraphParserTests.cs b/Src/FDO/FDOTests/ParagraphParserTests.cs
index fdb9b2738b..836163923b 100644
--- a/Src/FDO/FDOTests/ParagraphParserTests.cs
+++ b/Src/FDO/FDOTests/ParagraphParserTests.cs
@@ -64,7 +64,7 @@ public object Clone()
///
protected string ConfigurationFilePath(string fileRelativePath)
{
- return Path.Combine(DirectoryFinder.FwSourceDirectory, fileRelativePath);
+ return Path.Combine(FwDirectoryFinder.SourceDirectory, fileRelativePath);
}
///
@@ -543,7 +543,7 @@ virtual public IWfiWordform SetAlternateCase(int iSegment, int iSegForm, StringC
ITsString tssWordformBaseline = GetBaselineText(iSegment, iSegForm);
// Add any relevant 'other case' forms.
int nvar;
- int ws = tssWordformBaseline.get_Properties(0).GetIntPropValues((int)FwTextPropType.ktptWs, out nvar); ;
+ int ws = tssWordformBaseline.get_Properties(0).GetIntPropValues((int)FwTextPropType.ktptWs, out nvar);
string locale = m_cache.ServiceLocator.WritingSystemManager.Get(ws).IcuLocale;
var cf = new CaseFunctions(locale);
switch (targetState)
@@ -2435,7 +2435,7 @@ void SetupOldWordformingOverrides()
{
IWritingSystem wsObj = Cache.ServiceLocator.WritingSystems.DefaultVernacularWritingSystem;
var validChars = ValidCharacters.Load(wsObj.ValidChars,
- wsObj.DisplayLabel, null, null);
+ wsObj.DisplayLabel, null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
var fChangedSomething = false;
if (!validChars.IsWordForming('-'))
{
diff --git a/Src/FDO/FDOTests/PersistingBackendProviderTests.cs b/Src/FDO/FDOTests/PersistingBackendProviderTests.cs
index d7a6a8bece..4080fabf41 100644
--- a/Src/FDO/FDOTests/PersistingBackendProviderTests.cs
+++ b/Src/FDO/FDOTests/PersistingBackendProviderTests.cs
@@ -2,8 +2,8 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
using System.IO;
+using System.Linq;
using FwRemoteDatabaseConnector;
using NUnit.Framework;
using SIL.FieldWorks.Common.COMInterfaces;
@@ -15,6 +15,7 @@
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.CoreImpl;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
+using SIL.Utils;
namespace SIL.FieldWorks.FDO.CoreTests.PersistingLayerTests
{
@@ -187,6 +188,7 @@ public void BasicDataTypes()
lp.EthnologueCode = newEthCode;
// CellarPropertyType.String:
var le = Cache.ServiceLocator.GetInstance().Create();
+ Guid leGuid = le.Guid;
var irOriginalValue = Cache.TsStrFactory.MakeString("",
Cache.WritingSystemFactory.UserWs);
le.ImportResidue = irOriginalValue;
@@ -276,10 +278,11 @@ public void BasicDataTypes()
// Check Unicode
Assert.AreEqual(newEthCode, lp.EthnologueCode, "Wrong Unicode value restored.");
// Check string (ITsString)
- var irRestoredValue = lp.LexDbOA.Entries.ToArray()[0].ImportResidue;
+ le = Cache.ServiceLocator.GetInstance().GetObject(leGuid);
+ var irRestoredValue = le.ImportResidue;
var xmlRestoredValue = TsStringUtils.GetXmlRep(irRestoredValue, Cache.WritingSystemFactory, Cache.WritingSystemFactory.UserWs, true);
Assert.AreEqual(xmlOriginalValue, xmlRestoredValue, "Wrong ITsString value restored.");
- var irRestoredBlankValue = lp.LexDbOA.Entries.ToArray()[0].Comment.get_String(Cache.WritingSystemFactory.UserWs);
+ var irRestoredBlankValue = le.Comment.get_String(Cache.WritingSystemFactory.UserWs);
var xmlRestoredBlankValue = TsStringUtils.GetXmlRep(irRestoredBlankValue, Cache.WritingSystemFactory, Cache.WritingSystemFactory.UserWs, true);
Assert.AreEqual(xmlOriginalBlankValue, xmlRestoredBlankValue, "Wrong ITsString value restored for blank string.");
// ITsTextProps
@@ -414,7 +417,7 @@ public void CustomFieldDataTest()
public void RenameDatabaseTest()
{
string sOrigName = Cache.ProjectId.Name;
- string newProjectDir = Path.Combine(DirectoryFinder.ProjectsDirectory, NewProjectName);
+ string newProjectDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, NewProjectName);
if (Cache.ProjectId.Type != FDOBackendProviderType.kMemoryOnly && Directory.Exists(newProjectDir))
{
// make sure database doesn't exist before running the test
@@ -519,7 +522,7 @@ protected override FdoCache CreateCache()
while (true)
{
_randomProjectName = "TestLangProjCS" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
- var projectDir = Path.Combine(DirectoryFinder.ProjectsDirectory, _randomProjectName);
+ var projectDir = Path.Combine(FwDirectoryFinder.ProjectsDirectory, _randomProjectName);
if (!Directory.Exists(projectDir))
{
_projectDir = projectDir;
@@ -537,7 +540,7 @@ protected override FdoCache CreateCache()
/// ------------------------------------------------------------------------------------
public override void FixtureSetup()
{
- RemotingServer.Start();
+ RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => false, v => {});
base.FixtureSetup();
}
@@ -562,8 +565,8 @@ public override void FixtureTeardown()
/// ------------------------------------------------------------------------------------
protected override void CheckAdditionalStuffAfterFirstRename()
{
- Assert.AreEqual(Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, NewProjectName),
- DirectoryFinder.GetDb4oDataFileName(NewProjectName)), Cache.ProjectId.Path);
+ Assert.AreEqual(Path.Combine(Path.Combine(FwDirectoryFinder.ProjectsDirectory, NewProjectName),
+ FdoFileHelper.GetDb4oDataFileName(NewProjectName)), Cache.ProjectId.Path);
}
}
@@ -586,8 +589,8 @@ public sealed class XMLTests : PersistingBackendProviderTestBase
protected override FdoCache CreateCache()
{
const string projName = "TestLangProj-test";
- string filename = Path.Combine(DirectoryFinder.ProjectsDirectory,
- Path.Combine(projName, DirectoryFinder.GetXmlDataFileName(projName)));
+ string filename = Path.Combine(FwDirectoryFinder.ProjectsDirectory,
+ Path.Combine(projName, FdoFileHelper.GetXmlDataFileName(projName)));
if (!m_internalRestart)
{
if (File.Exists(filename))
@@ -607,7 +610,7 @@ protected override FdoCache CreateCache()
[Ignore("There is a timing problem with this test - project file may not exist becuase background thread is doing commit.")]
public void OnlyOneCacheAllowed()
{
- string filename = DirectoryFinder.GetXmlDataFileName("TestLangProj");
+ string filename = FdoFileHelper.GetXmlDataFileName("TestLangProj");
Assert.True(File.Exists(filename), "Test XML file not found");
using (FdoCache cache = OpenExistingFile(filename))
Assert.Fail("Able to open XML file that is already open");
@@ -616,7 +619,7 @@ public void OnlyOneCacheAllowed()
private FdoCache OpenExistingFile(string filename)
{
return FdoCache.CreateCacheFromExistingData(
- new TestProjectId(FDOBackendProviderType.kXMLWithMemoryOnlyWsMgr, filename), "en", new DummyProgressDlg());
+ new TestProjectId(FDOBackendProviderType.kXMLWithMemoryOnlyWsMgr, filename), "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories, new DummyProgressDlg());
}
/// ------------------------------------------------------------------------------------
@@ -626,8 +629,8 @@ private FdoCache OpenExistingFile(string filename)
/// ------------------------------------------------------------------------------------
protected override void CheckAdditionalStuffAfterFirstRename()
{
- Assert.AreEqual(Path.Combine(Path.Combine(DirectoryFinder.ProjectsDirectory, NewProjectName),
- DirectoryFinder.GetXmlDataFileName(NewProjectName)), Cache.ProjectId.Path);
+ Assert.AreEqual(Path.Combine(Path.Combine(FwDirectoryFinder.ProjectsDirectory, NewProjectName),
+ FdoFileHelper.GetXmlDataFileName(NewProjectName)), Cache.ProjectId.Path);
}
///
@@ -635,10 +638,10 @@ protected override void CheckAdditionalStuffAfterFirstRename()
/// throw an Exception.
///
[Test]
- [ExpectedException(typeof(FwStartupException))]
+ [ExpectedException(typeof(StartupException))]
public void CorruptedXMLFileTest()
{
- var testDataPath = Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/TestData");
+ var testDataPath = Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO/FDOTests/TestData");
var projName = Path.Combine(testDataPath, "CorruptedXMLFileTest.fwdata");
// MockXMLBackendProvider implements IDisposable therefore we need the "using".
@@ -646,7 +649,7 @@ public void CorruptedXMLFileTest()
using (var xmlBep = new MockXMLBackendProvider(Cache, projName))
{
// Should throw an XMLException, but this will be caught and because there's
- // no .bak file, an FwStartupException will be thrown instead.
+ // no .bak file, an StartupException will be thrown instead.
xmlBep.Startup();
}
}
@@ -665,7 +668,7 @@ public void StartupExtantTest()
string testFileName = String.Empty;
try
{
- var testDataPath = Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/BackupRestore/BackupTestProject");
+ var testDataPath = Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO/FDOTests/BackupRestore/BackupTestProject");
var projName = Path.Combine(testDataPath, "BackupTestProject.fwdata");
testFileName = Path.GetTempFileName();
// If we leave the extension as .tmp, we get a sharing violation when the
@@ -694,7 +697,7 @@ public void StartupExtantTest()
[Test]
public void SlightlyCorruptedXMLFileTest()
{
- var testDataPath = Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/TestData");
+ var testDataPath = Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO/FDOTests/TestData");
var projName = Path.Combine(testDataPath, "SlightlyCorruptedXMLFile.fwdata");
// MockXMLBackendProvider implements IDisposable therefore we need the "using".
@@ -713,7 +716,7 @@ public void SlightlyCorruptedXMLFileTest()
[Test]
public void XMLFileWithDuplicateGuidsTest()
{
- var testDataPath = Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/TestData");
+ var testDataPath = Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO/FDOTests/TestData");
var projName = Path.Combine(testDataPath, "DuplicateGuids.fwdata");
// MockXMLBackendProvider implements IDisposable therefore we need the "using".
@@ -741,7 +744,7 @@ public void XMLFileWithDuplicateGuidsTest()
public void ClosingTagSpansBufferTest()
{
int numCharsInClosingTag = kClosingTag.Length;
- string testDataPath = Path.Combine(DirectoryFinder.FwSourceDirectory, "FDO/FDOTests/TestData", "ClosingTagSpansBuffer.fwdata");
+ string testDataPath = Path.Combine(FwDirectoryFinder.SourceDirectory, "FDO/FDOTests/TestData", "ClosingTagSpansBuffer.fwdata");
var numCharsInFile = (int) new FileInfo(testDataPath).Length;
// Try each edge case
@@ -788,7 +791,7 @@ internal class MockXMLBackendProvider : XMLBackendProvider
public MockXMLBackendProvider(FdoCache cache, string projName):
base(cache, new IdentityMap((IFwMetaDataCacheManaged)cache.MetaDataCache),
new CmObjectSurrogateFactory(cache), (IFwMetaDataCacheManagedInternal)cache.MetaDataCache,
- new FdoDataMigrationManager())
+ new FdoDataMigrationManager(), new DummyFdoUI(), FwDirectoryFinder.FdoDirectories)
{
Project = projName;
Cache = cache;
@@ -807,7 +810,7 @@ public void StartupExtant()
ProjectId = new TestProjectId(FDOBackendProviderType.kXML, Project);
// This will throw an UnauthorizedAccessException because of the
// StartupInternalWithDataMigrationIfNeeded() override below
- StartupExtantLanguageProject(ProjectId, false, new DummyProgressDlg());
+ StartupExtantLanguageProject(ProjectId, false, new DummyProgressDlg(), false);
}
///
@@ -828,9 +831,288 @@ internal override void ReportDuplicateGuidsIfTheyExist()
{
}
- protected override void StartupInternalWithDataMigrationIfNeeded(IThreadedProgress progressDlg)
+ protected override void StartupInternalWithDataMigrationIfNeeded(IThreadedProgress progressDlg, bool forbidDataMigration)
{
throw new UnauthorizedAccessException();
}
}
+
+ /// ----------------------------------------------------------------------------------------
+ ///
+ /// Base class for testing the FdoCache with the FDOBackendProviderType.kSharedXML
+ /// backend provider.
+ ///
+ /// ----------------------------------------------------------------------------------------
+ [TestFixture]
+ public sealed class SharedXMLTests : PersistingBackendProviderTestBase
+ {
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Override to create and load a very basic cache.
+ ///
+ /// ------------------------------------------------------------------------------------
+ protected override FdoCache CreateCache()
+ {
+ SharedXMLBackendProvider.CommitLogFileSize = 102400;
+ IProjectIdentifier projectID = ProjectID;
+ if (!m_internalRestart)
+ {
+ if (File.Exists(projectID.Path))
+ File.Delete(projectID.Path);
+ }
+ return BootstrapSystem(projectID, m_loadType);
+ }
+
+ private IProjectIdentifier ProjectID
+ {
+ get
+ {
+ const string projName = "TestLangProj-test";
+ string filename = Path.Combine(FwDirectoryFinder.ProjectsDirectory,
+ Path.Combine(projName, FdoFileHelper.GetXmlDataFileName(projName)));
+ return new TestProjectId(FDOBackendProviderType.kSharedXMLWithMemoryOnlyWsMgr, filename);
+ }
+ }
+
+ private FdoCache CreateOtherCache()
+ {
+ FdoCache retval = FdoCache.CreateCacheFromExistingData(ProjectID, "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories, new DummyProgressDlg());
+ var dataSetup = retval.ServiceLocator.GetInstance();
+ dataSetup.LoadDomain(m_loadType);
+ return retval;
+ }
+
+ ///
+ /// Tests sequential changes by two caches on the same project.
+ ///
+ [Test]
+ public void SequentialChanges()
+ {
+ Cache.ServiceLocator.GetInstance().Save();
+ Cache.ServiceLocator.GetInstance().CompleteAllCommits();
+ using (FdoCache otherCache = CreateOtherCache())
+ {
+ ILexEntry entry1 = null;
+ NonUndoableUnitOfWorkHelper.Do(Cache.ServiceLocator.ActionHandler, () =>
+ {
+ IMoMorphType stemType = Cache.ServiceLocator.GetInstance().GetObject(MoMorphTypeTags.kguidMorphStem);
+ entry1 = Cache.ServiceLocator.GetInstance().Create(stemType, Cache.TsStrFactory.MakeString("form1", Cache.DefaultVernWs),
+ Cache.TsStrFactory.MakeString("gloss1", Cache.DefaultAnalWs), new SandboxGenericMSA());
+ });
+ Cache.ServiceLocator.GetInstance().Save();
+
+ ILexEntry otherEntry1;
+ Assert.That(otherCache.ServiceLocator.GetInstance().TryGetObject(entry1.Guid, out otherEntry1), Is.False);
+ otherCache.ServiceLocator.GetInstance().Save();
+
+ Assert.That(otherCache.ServiceLocator.GetInstance().TryGetObject(entry1.Guid, out otherEntry1), Is.True);
+ Assert.That(otherEntry1.LexemeFormOA.ShortName, Is.EqualTo(entry1.LexemeFormOA.ShortName));
+ Assert.That(otherEntry1.SensesOS[0].ShortName, Is.EqualTo(entry1.SensesOS[0].ShortName));
+
+ ILexEntry otherEntry2 = null;
+ NonUndoableUnitOfWorkHelper.Do(otherCache.ServiceLocator.ActionHandler, () =>
+ {
+ IMoMorphType stemType = otherCache.ServiceLocator.GetInstance().GetObject(MoMorphTypeTags.kguidMorphStem);
+ otherEntry2 = otherCache.ServiceLocator.GetInstance().Create(stemType, otherCache.TsStrFactory.MakeString("form2", otherCache.DefaultVernWs),
+ otherCache.TsStrFactory.MakeString("gloss2", otherCache.DefaultAnalWs), new SandboxGenericMSA());
+ });
+ otherCache.ServiceLocator.GetInstance().Save();
+
+ ILexEntry entry2;
+ Assert.That(Cache.ServiceLocator.GetInstance().TryGetObject(otherEntry2.Guid, out entry2), Is.False);
+ Cache.ServiceLocator.GetInstance().Save();
+
+ Assert.That(Cache.ServiceLocator.GetInstance().TryGetObject(otherEntry2.Guid, out entry2), Is.True);
+ Assert.That(entry2.LexemeFormOA.ShortName, Is.EqualTo(otherEntry2.LexemeFormOA.ShortName));
+ Assert.That(entry2.SensesOS[0].ShortName, Is.EqualTo(otherEntry2.SensesOS[0].ShortName));
+ }
+ }
+
+ ///
+ /// Tests simultaneous changes by two caches on the same project.
+ ///
+ [Test]
+ public void SimultaneousChanges()
+ {
+ Cache.ServiceLocator.GetInstance().Save();
+ Cache.ServiceLocator.GetInstance().CompleteAllCommits();
+ using (FdoCache otherCache = CreateOtherCache())
+ {
+ ILexEntry entry1 = null;
+ NonUndoableUnitOfWorkHelper.Do(Cache.ServiceLocator.ActionHandler, () =>
+ {
+ IMoMorphType stemType = Cache.ServiceLocator.GetInstance().GetObject(MoMorphTypeTags.kguidMorphStem);
+ entry1 = Cache.ServiceLocator.GetInstance().Create(stemType, Cache.TsStrFactory.MakeString("form1", Cache.DefaultVernWs),
+ Cache.TsStrFactory.MakeString("gloss1", Cache.DefaultAnalWs), new SandboxGenericMSA());
+ });
+
+ ILexEntry otherEntry2 = null;
+ NonUndoableUnitOfWorkHelper.Do(otherCache.ServiceLocator.ActionHandler, () =>
+ {
+ IMoMorphType stemType = otherCache.ServiceLocator.GetInstance().GetObject(MoMorphTypeTags.kguidMorphStem);
+ otherEntry2 = otherCache.ServiceLocator.GetInstance().Create(stemType, otherCache.TsStrFactory.MakeString("form2", otherCache.DefaultVernWs),
+ otherCache.TsStrFactory.MakeString("gloss2", otherCache.DefaultAnalWs), new SandboxGenericMSA());
+ });
+
+ Cache.ServiceLocator.GetInstance().Save();
+
+ ILexEntry otherEntry1;
+ Assert.That(otherCache.ServiceLocator.GetInstance().TryGetObject(entry1.Guid, out otherEntry1), Is.False);
+ otherCache.ServiceLocator.GetInstance().Save();
+
+ ILexEntry entry2;
+ Assert.That(Cache.ServiceLocator.GetInstance().TryGetObject(otherEntry2.Guid, out entry2), Is.False);
+ Cache.ServiceLocator.GetInstance().Save();
+
+ Assert.That(otherCache.ServiceLocator.GetInstance().TryGetObject(entry1.Guid, out otherEntry1), Is.True);
+ Assert.That(otherEntry1.LexemeFormOA.ShortName, Is.EqualTo(entry1.LexemeFormOA.ShortName));
+ Assert.That(otherEntry1.SensesOS[0].ShortName, Is.EqualTo(entry1.SensesOS[0].ShortName));
+
+ Assert.That(Cache.ServiceLocator.GetInstance().TryGetObject(otherEntry2.Guid, out entry2), Is.True);
+ Assert.That(entry2.LexemeFormOA.ShortName, Is.EqualTo(otherEntry2.LexemeFormOA.ShortName));
+ Assert.That(entry2.SensesOS[0].ShortName, Is.EqualTo(otherEntry2.SensesOS[0].ShortName));
+ }
+ }
+
+ ///
+ /// Tests that renaming the project is not allowed when there are multiple caches using the same project.
+ ///
+ [Test]
+ public void RenameDatabaseNotAllowedWhenMultipleCaches()
+ {
+ Cache.ServiceLocator.GetInstance().Save();
+ Cache.ServiceLocator.GetInstance().CompleteAllCommits();
+ using (FdoCache otherCache = CreateOtherCache())
+ {
+ Assert.That(Cache.RenameDatabase("NewName"), Is.False);
+ Assert.That(otherCache.RenameDatabase("NewName"), Is.False);
+ }
+ Assert.That(Cache.RenameDatabase("NewName"), Is.True);
+ Assert.That(Cache.RenameDatabase("TestLangProj-test"), Is.True);
+ }
+
+ ///
+ /// Tests conflicting changes by two caches on the same project.
+ ///
+ [Test]
+ public void ConflictingChanges()
+ {
+ Cache.ServiceLocator.GetInstance().Save();
+ Cache.ServiceLocator.GetInstance().CompleteAllCommits();
+ using (FdoCache otherCache = CreateOtherCache())
+ {
+ ILexEntry entry1 = null;
+ NonUndoableUnitOfWorkHelper.Do(Cache.ServiceLocator.ActionHandler, () =>
+ {
+ IMoMorphType stemType = Cache.ServiceLocator.GetInstance().GetObject(MoMorphTypeTags.kguidMorphStem);
+ entry1 = Cache.ServiceLocator.GetInstance().Create(stemType, Cache.TsStrFactory.MakeString("form1", Cache.DefaultVernWs),
+ Cache.TsStrFactory.MakeString("gloss1", Cache.DefaultAnalWs), new SandboxGenericMSA());
+ });
+ Cache.ServiceLocator.GetInstance().Save();
+ otherCache.ServiceLocator.GetInstance().Save();
+
+ ILexEntry otherEntry1;
+ Assert.That(otherCache.ServiceLocator.GetInstance().TryGetObject(entry1.Guid, out otherEntry1), Is.True);
+ NonUndoableUnitOfWorkHelper.Do(otherCache.ServiceLocator.ActionHandler, () =>
+ {
+ otherEntry1.CitationForm.set_String(otherCache.DefaultVernWs, "othercitation");
+ });
+ otherCache.ServiceLocator.GetInstance().Save();
+
+ NonUndoableUnitOfWorkHelper.Do(Cache.ServiceLocator.ActionHandler, () =>
+ {
+ entry1.CitationForm.set_String(Cache.DefaultVernWs, "citation");
+ });
+ var ui = (DummyFdoUI) Cache.ServiceLocator.GetInstance();
+ ui.Reset();
+ Cache.ServiceLocator.GetInstance().Save();
+ // the first in should win
+ Assert.That(entry1.CitationForm.VernacularDefaultWritingSystem.Text, Is.EqualTo("othercitation"));
+ // check that the user was prompted about conflicting changes
+ Assert.That(ui.ConflictingSaveOccurred, Is.True);
+ }
+ }
+
+ ///
+ /// Tests shutting down the master cache and letting the slave take over.
+ ///
+ [Test]
+ public void SwitchMasters()
+ {
+ Cache.ServiceLocator.GetInstance().Save();
+ Cache.ServiceLocator.GetInstance().CompleteAllCommits();
+ Guid otherEntryGuid1;
+ using (FdoCache otherCache = CreateOtherCache())
+ {
+ DisposeEverythingButBase();
+ ILexEntry otherEntry1 = null;
+ NonUndoableUnitOfWorkHelper.Do(otherCache.ServiceLocator.ActionHandler, () =>
+ {
+ IMoMorphType stemType = otherCache.ServiceLocator.GetInstance().GetObject(MoMorphTypeTags.kguidMorphStem);
+ otherEntry1 = otherCache.ServiceLocator.GetInstance().Create(stemType, otherCache.TsStrFactory.MakeString("form1", otherCache.DefaultVernWs),
+ otherCache.TsStrFactory.MakeString("gloss1", otherCache.DefaultAnalWs), new SandboxGenericMSA());
+ });
+ otherEntryGuid1 = otherEntry1.Guid;
+ otherCache.ServiceLocator.GetInstance().Save();
+ }
+
+ RestartCache(false);
+ ILexEntry entry1;
+ Assert.That(Cache.ServiceLocator.GetInstance().TryGetObject(otherEntryGuid1, out entry1), Is.True);
+ Assert.That(entry1.LexemeFormOA.Form.VernacularDefaultWritingSystem.Text, Is.EqualTo("form1"));
+ Assert.That(entry1.SensesOS[0].Gloss.AnalysisDefaultWritingSystem.Text, Is.EqualTo("gloss1"));
+ }
+
+ ///
+ /// Tests wrapping around the internal commit log circular buffer.
+ ///
+ [Test]
+ public void WrapAroundCommitLogBuffer()
+ {
+ // totally reset project
+ SetupEverythingButBase();
+
+ // add some commit records to log, so that the log will wrap around
+ int i;
+ for (i = 0; i < 5; i++)
+ {
+ NonUndoableUnitOfWorkHelper.Do(Cache.ServiceLocator.ActionHandler, () =>
+ {
+ IMoMorphType stemType = Cache.ServiceLocator.GetInstance().GetObject(MoMorphTypeTags.kguidMorphStem);
+ ILexEntry entry1 = Cache.ServiceLocator.GetInstance().Create(stemType, Cache.TsStrFactory.MakeString("form1", Cache.DefaultVernWs),
+ Cache.TsStrFactory.MakeString("gloss1", Cache.DefaultAnalWs), new SandboxGenericMSA());
+ });
+ Cache.ServiceLocator.GetInstance().Save();
+ }
+ Cache.ServiceLocator.GetInstance().CompleteAllCommits();
+ Cache.ServiceLocator.GetInstance().Save();
+ using (FdoCache otherCache = CreateOtherCache())
+ {
+ // add commit records until the log fills up
+ // once the log is full, we know that the internal buffer has wrapped around
+ while (true)
+ {
+ NonUndoableUnitOfWorkHelper.Do(Cache.ServiceLocator.ActionHandler, () =>
+ {
+ IMoMorphType stemType = Cache.ServiceLocator.GetInstance().GetObject(MoMorphTypeTags.kguidMorphStem);
+ ILexEntry entry1 = Cache.ServiceLocator.GetInstance().Create(stemType, Cache.TsStrFactory.MakeString("form1", Cache.DefaultVernWs),
+ Cache.TsStrFactory.MakeString("gloss1", Cache.DefaultAnalWs), new SandboxGenericMSA());
+ });
+ try
+ {
+ Cache.ServiceLocator.GetInstance().Save();
+ }
+ catch (InvalidOperationException)
+ {
+ break;
+ }
+ i++;
+ }
+ // the other cache will now read the wrapped around commit log buffer
+ otherCache.ServiceLocator.GetInstance().Save();
+
+ Assert.That(otherCache.ServiceLocator.GetInstance().GetHomographs("form1").Count, Is.EqualTo(i));
+ }
+ }
+ }
}
diff --git a/Src/FDO/FDOTests/PersistingLayerTests.BEPPortTests.cs b/Src/FDO/FDOTests/PersistingLayerTests.BEPPortTests.cs
index 3cba5ae764..f63fd560c4 100644
--- a/Src/FDO/FDOTests/PersistingLayerTests.BEPPortTests.cs
+++ b/Src/FDO/FDOTests/PersistingLayerTests.BEPPortTests.cs
@@ -82,7 +82,7 @@ public void Setup()
m_sourceInfo = new List
{
new BackendStartupParameter(true, BackendBulkLoadDomain.All,
- new TestProjectId(FDOBackendProviderType.kXML, DirectoryFinder.GetXmlDataFileName("TLP" + randomFileExtension))),
+ new TestProjectId(FDOBackendProviderType.kXML, FdoFileHelper.GetXmlDataFileName("TLP" + randomFileExtension))),
new BackendStartupParameter(true, BackendBulkLoadDomain.All,
new TestProjectId(FDOBackendProviderType.kMemoryOnly, null)),
new BackendStartupParameter(true, BackendBulkLoadDomain.All,
@@ -91,7 +91,7 @@ public void Setup()
m_targetInfo = new List
{
new BackendStartupParameter(true, BackendBulkLoadDomain.All,
- new TestProjectId(FDOBackendProviderType.kXML, DirectoryFinder.GetXmlDataFileName("TLP_New" + randomFileExtension))),
+ new TestProjectId(FDOBackendProviderType.kXML, FdoFileHelper.GetXmlDataFileName("TLP_New" + randomFileExtension))),
new BackendStartupParameter(true, BackendBulkLoadDomain.All,
new TestProjectId(FDOBackendProviderType.kMemoryOnly, null)),
new BackendStartupParameter(true, BackendBulkLoadDomain.All,
@@ -106,7 +106,7 @@ public void Setup()
/// ------------------------------------------------------------------------------------
public override void FixtureSetup()
{
- RemotingServer.Start();
+ RemotingServer.Start(FwDirectoryFinder.RemotingTcpServerConfigFile, FwDirectoryFinder.FdoDirectories, () => false, v => {});
base.FixtureSetup();
}
@@ -216,10 +216,9 @@ public void PortAllBEPsTestsUsingAnAlreadyOpenedSource(
// Set up data source, but only do it once.
var sourceGuids = new List();
- using (var threadHelper = new ThreadHelper())
using (var sourceCache = FdoCache.CreateCacheWithNewBlankLangProj(
new TestProjectId(sourceBackendStartupParameters.ProjectId.Type,
- sourceBackendStartupParameters.ProjectId.Path), "en", "fr", "en", threadHelper))
+ sourceBackendStartupParameters.ProjectId.Path), "en", "fr", "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories))
{
// BEP is a singleton, so we shouldn't call Dispose on it. This will be done
// by service locator.
@@ -232,10 +231,9 @@ public void PortAllBEPsTestsUsingAnAlreadyOpenedSource(
DeleteDatabase(targetBackendStartupParameters);
// Migrate source data to new BEP.
- using (var otherThreadHelper = new ThreadHelper())
using (var targetCache = FdoCache.CreateCacheCopy(
new TestProjectId(targetBackendStartupParameters.ProjectId.Type,
- targetBackendStartupParameters.ProjectId.Path), "en", sourceCache, otherThreadHelper))
+ targetBackendStartupParameters.ProjectId.Path), "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories, sourceCache))
{
// BEP is a singleton, so we shouldn't call Dispose on it. This will be done
// by service locator.
@@ -284,7 +282,7 @@ public void PortAllBEPsTestsUsingAnUnopenedSource(
sourceBackendStartupParameters.ProjectId.Path);
IThreadedProgress progressDlg = new DummyProgressDlg();
using (FdoCache sourceCache = FdoCache.CreateCacheWithNewBlankLangProj(
- projId, "en", "fr", "en", progressDlg.ThreadHelper))
+ projId, "en", "fr", "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories))
{
// BEP is a singleton, so we shouldn't call Dispose on it. This will be done
// by service locator.
@@ -298,7 +296,7 @@ public void PortAllBEPsTestsUsingAnUnopenedSource(
// Migrate source data to new BEP.
progressDlg = new DummyProgressDlg();
using (var targetCache = FdoCache.CreateCacheWithNoLangProj(
- new TestProjectId(targetBackendStartupParameters.ProjectId.Type, null), "en", progressDlg.ThreadHelper))
+ new TestProjectId(targetBackendStartupParameters.ProjectId.Type, null), "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories))
{
// BEP is a singleton, so we shouldn't call Dispose on it. This will be done
// by service locator.
diff --git a/Src/FDO/FDOTests/ScrChecksDataSourceTests.cs b/Src/FDO/FDOTests/ScrChecksDataSourceTests.cs
index dc2c76ce8c..1eddd524d4 100644
--- a/Src/FDO/FDOTests/ScrChecksDataSourceTests.cs
+++ b/Src/FDO/FDOTests/ScrChecksDataSourceTests.cs
@@ -8,6 +8,7 @@
using System.Collections.Generic;
using NUnit.Framework;
using SIL.CoreImpl;
+using SIL.FieldWorks.Resources;
using SIL.Utils;
using SILUBS.SharedScrUtils;
using SIL.FieldWorks.FDO.DomainServices;
@@ -23,7 +24,7 @@ namespace SIL.FieldWorks.FDO.FDOTests
[TestFixture]
public class ScrChecksDataSourceTests : ScrInMemoryFdoTestBase
{
- private ScrChecksDataSource m_dataSource = null;
+ private ScrChecksDataSource m_dataSource;
/// ------------------------------------------------------------------------------------
///
@@ -35,7 +36,8 @@ public class ScrChecksDataSourceTests : ScrInMemoryFdoTestBase
public override void TestSetup()
{
base.TestSetup();
- m_dataSource = new ScrChecksDataSource(Cache, DirectoryFinder.TeStylesPath);
+ m_dataSource = new ScrChecksDataSource(Cache, ResourceHelper.GetResourceString("kstidPunctCheckWhitespaceChar"),
+ FwDirectoryFinder.LegacyWordformingCharOverridesFile, FwDirectoryFinder.TeStylesPath);
}
///--------------------------------------------------------------------------------------
diff --git a/Src/FDO/FDOTests/ScrImportFileInfoTests.cs b/Src/FDO/FDOTests/ScrImportFileInfoTests.cs
index 992e6e5e9e..336eb2a07b 100644
--- a/Src/FDO/FDOTests/ScrImportFileInfoTests.cs
+++ b/Src/FDO/FDOTests/ScrImportFileInfoTests.cs
@@ -9,9 +9,10 @@
using System.IO;
using System.Text;
using NUnit.Framework;
-using SIL.FieldWorks.Test.TestUtils;
-using SIL.FieldWorks.FDO;
+using SIL.FieldWorks.Common.FwUtils;
+using SIL.FieldWorks.Resources;
using SIL.FieldWorks.Common.ScriptureUtils;
+using SIL.FieldWorks.Test.TestUtils;
using SILUBS.SharedScrUtils;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.Utils;
@@ -24,7 +25,7 @@ namespace SIL.FieldWorks.FDO.FDOTests
///
/// ----------------------------------------------------------------------------------------
[TestFixture]
- public class ScrImportFileInfoTests: SIL.FieldWorks.Test.TestUtils.BaseTest
+ public class ScrImportFileInfoTests : BaseTest
{
#region class DummyScrImportFileInfo
/// ------------------------------------------------------------------------------------
@@ -122,7 +123,7 @@ protected override TextReader GetReader()
[SetUp]
public void Init()
{
- m_mappingList = new ScrMappingList(MappingSet.Main, null);
+ m_mappingList = new ScrMappingList(MappingSet.Main, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
m_factory = new ScrImportFileInfoFactory();
m_fileOs = new MockFileOS();
FileUtils.Manager.SetFileAdapter(m_fileOs);
diff --git a/Src/FDO/FDOTests/ScrImportSetTests.cs b/Src/FDO/FDOTests/ScrImportSetTests.cs
index 103fd721dd..6269fcf6d8 100644
--- a/Src/FDO/FDOTests/ScrImportSetTests.cs
+++ b/Src/FDO/FDOTests/ScrImportSetTests.cs
@@ -8,16 +8,13 @@
using System;
using System.Collections;
using System.Collections.Generic;
-using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
-using System.IO;
-using System.Text;
-
using NUnit.Framework;
using Rhino.Mocks;
-
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.ScriptureUtils;
using SIL.FieldWorks.FDO.DomainServices;
+using SIL.FieldWorks.Resources;
using SIL.Utils;
using SILUBS.SharedScrUtils;
@@ -123,39 +120,13 @@ public override IScrImportFileInfo Create(string fileName, ScrMappingList mappin
public class ScrImportSetTests : ScrInMemoryFdoTestBase
{
#region data members
- private MockParatextHelper m_ptHelper;
private IScrImportSet m_importSettings;
private ICmAnnotationDefn m_translatorNoteDefn;
private ICmAnnotationDefn m_consultantNoteDefn;
- private IParatextHelper m_mockParatextHelper;
private MockFileOS m_fileOs;
#endregion
#region Setup & Teardown
- /// ------------------------------------------------------------------------------------
- ///
- ///
- ///
- /// ------------------------------------------------------------------------------------
- public override void FixtureSetup()
- {
- base.FixtureSetup();
- m_ptHelper = new MockParatextHelper();
- ParatextHelper.Manager.SetParatextHelperAdapter(m_ptHelper);
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- ///
- ///
- /// ------------------------------------------------------------------------------------
- public override void FixtureTeardown()
- {
- base.FixtureTeardown();
- m_ptHelper.Dispose();
- ParatextHelper.Manager.Reset();
- }
-
/// ------------------------------------------------------------------------------------
///
/// Test setup stuff
@@ -164,12 +135,9 @@ public override void FixtureTeardown()
public override void TestSetup()
{
base.TestSetup();
- m_ptHelper.Projects.Clear();
- m_importSettings = Cache.ServiceLocator.GetInstance().Create();
- m_mockParatextHelper = MockRepository.GenerateMock();
+ m_importSettings = Cache.ServiceLocator.GetInstance().Create(ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
m_scr.ImportSettingsOC.Add(m_importSettings);
- m_ptHelper.m_loadProjectMappingsImpl = m_mockParatextHelper;
m_translatorNoteDefn = Cache.ServiceLocator.GetInstance().TranslatorAnnotationDefn;
m_consultantNoteDefn = Cache.ServiceLocator.GetInstance().ConsultantAnnotationDefn;
@@ -688,8 +656,6 @@ public void SaveAndReloadSources_SaveSeparateSourcesWhenImportTypeChanges()
// Now that we've saved the settings, we'll "revert" in order to re-load from the DB
m_importSettings.RevertToSaved();
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Equal("KAM"),
- Arg.Is.Anything, Arg.Is.Equal(ImportDomain.Main))).Return(true);
m_importSettings.ImportTypeEnum = TypeOfImport.Paratext6;
m_importSettings.ParatextScrProj = "KAM";
m_importSettings.SaveSettings();
@@ -794,11 +760,6 @@ public void SaveAndReloadParatext6Projects()
ScrMappingList mappingList = (ScrMappingList)m_importSettings.Mappings(MappingSet.Main);
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Equal("KAM"),
- Arg.Is.Equal(mappingList), Arg.Is.Equal(ImportDomain.Main))).Return(true);
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Equal("TEV"),
- Arg.Is.Equal(mappingList), Arg.Is.Equal(ImportDomain.BackTrans))).Return(true);
-
// add Scripture files
m_importSettings.ParatextScrProj = "KAM";
m_importSettings.ParatextBTProj = "TEV";
@@ -851,32 +812,6 @@ public void AddFile_Main()
((ScrSfFileList)ReflectionHelper.GetField(m_importSettings, "m_scrFileInfoList"))[0]);
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Test adding a file that is locked
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void AddFileAndCheckAccessibility_Locked()
- {
- m_importSettings.ImportTypeEnum = TypeOfImport.Other;
-
- string filename = m_fileOs.MakeSfFile("EPH", @"\c 1", @"\v 1");
- m_fileOs.LockFile(filename);
-
- // Lock the file
- //using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite))
- //{
- IScrImportFileInfo info = m_importSettings.AddFile(filename, ImportDomain.Main, null, null);
- Assert.AreEqual(Encoding.ASCII, info.FileEncoding);
- Assert.AreEqual(1, m_importSettings.GetImportFiles(ImportDomain.Main).Count);
- StringCollection notFound;
- Assert.IsFalse(m_importSettings.ImportProjectIsAccessible(out notFound));
- Assert.AreEqual(1, notFound.Count);
- Assert.AreEqual(filename, (string)notFound[0]);
- //}
- }
-
/// ------------------------------------------------------------------------------------
///
/// Try to add non-existent file to the SF Project. This should be allowed because
@@ -973,11 +908,6 @@ public void MarkMappingsInUse_SwitchFromParatext6ToOther()
ScrMappingList mappingListMain = (ScrMappingList)m_importSettings.Mappings(MappingSet.Main);
ScrMappingList mappingListNotes = (ScrMappingList)m_importSettings.Mappings(MappingSet.Notes);
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Equal("KAM"),
- Arg.Is.Equal(mappingListMain), Arg.Is.Equal(ImportDomain.Main))).Return(true);
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Equal("TEV"),
- Arg.Is.Equal(mappingListNotes), Arg.Is.Equal(ImportDomain.Annotations))).Return(true);
-
// set Scripture project
m_importSettings.ParatextScrProj = "TEV";
m_importSettings.ParatextNotesProj = "KAM";
@@ -1055,9 +985,6 @@ public void AttemptToUseSameParatextProjectTwice()
{
m_importSettings.ImportTypeEnum = TypeOfImport.Paratext6;
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Equal("KAM"),
- Arg.Is.Anything, Arg.Is.Equal(ImportDomain.BackTrans))).Return(true);
-
m_importSettings.ParatextBTProj = "KAM";
m_importSettings.ParatextNotesProj = "KAM";
}
@@ -1073,9 +1000,6 @@ public void SwitchFromParatext6ToParatext5Project()
{
m_importSettings.ImportTypeEnum = TypeOfImport.Paratext6;
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Equal("KAM"),
- Arg.Is.Anything, Arg.Is.Equal(ImportDomain.BackTrans))).Return(true);
-
ScrMappingList mappings = m_importSettings.GetMappingListForDomain(ImportDomain.Main);
m_importSettings.SetMapping(MappingSet.Main, new ImportMappingInfo(@"\q", null, "Qute"));
@@ -1142,9 +1066,6 @@ public void BasicSettingsExist_Paratext6()
{
m_importSettings.ImportTypeEnum = TypeOfImport.Paratext6;
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Anything,
- Arg.Is.Anything, Arg.Is.Anything)).Return(true);
-
Assert.IsFalse(m_importSettings.BasicSettingsExist, "No project settings set yet");
m_importSettings.ParatextBTProj = "KAM";
@@ -1209,83 +1130,6 @@ public void BasicSettingsExist_Paretxt5()
}
#endregion
- #region Attempting to load Paratext project with missing files
- /// ------------------------------------------------------------------------------------
- ///
- /// Attempting to set the Paratext project to a project that can't be loaded should not
- /// set the value.
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void ParatextScrProj_Set_FailureToLoadProject()
- {
- m_importSettings.ImportTypeEnum = TypeOfImport.Paratext6;
-
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Equal("NEC"),
- Arg.Is.Anything, Arg.Is.Anything)).Return(false);
-
- m_importSettings.ParatextScrProj = "NEC";
-
- Assert.IsNull(m_importSettings.ParatextScrProj);
- }
- #endregion
-
- #region ImportProjectIsAccessible tests
- /// ------------------------------------------------------------------------------------
- ///
- /// Test to see if the ImportProjectIsAccessible method works for Paratext 6 projects.
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void ImportProjectIsAccessible_Paratext6()
- {
- m_importSettings.ImportTypeEnum = TypeOfImport.Paratext6;
-
- string paratextDir = ParatextHelper.ProjectsDirectory;
- m_mockParatextHelper.Stub(x => x.LoadProjectMappings(Arg.Is.Anything,
- Arg.Is.Anything, Arg.Is.Anything)).Return(true);
- m_ptHelper.AddProject("TEV", null, null, true, false, "100001");
-
- m_fileOs.AddExistingFile(Path.Combine(paratextDir, "TEV.ssf"));
-
- m_importSettings.ParatextScrProj = "KAM";
- m_importSettings.ParatextBTProj = "TEV";
-
- StringCollection projectsNotFound;
- Assert.IsFalse(m_importSettings.ImportProjectIsAccessible(out projectsNotFound));
- Assert.AreEqual(1, projectsNotFound.Count);
- Assert.AreEqual("KAM", projectsNotFound[0]);
-
- m_fileOs.AddExistingFile(Path.Combine(paratextDir, "KAM.ssf"));
- m_ptHelper.AddProject("KAM", null, null, true, false, "000101");
- Assert.IsTrue(m_importSettings.ImportProjectIsAccessible(out projectsNotFound));
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Test to see if the ImportProjectIsAccessible method works for Paratext 5 projects.
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void ImportProjectIsAccessible_Paratext5()
- {
- m_importSettings.ImportTypeEnum = TypeOfImport.Paratext5;
- ImportProjectIsAccessible_helper();
- }
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Test to see if the ImportProjectIsAccessible method works for Other projects.
- ///
- /// ------------------------------------------------------------------------------------
- [Test]
- public void ImportProjectIsAccessible_Other()
- {
- m_importSettings.ImportTypeEnum = TypeOfImport.Other;
- ImportProjectIsAccessible_helper();
- }
- #endregion
-
#region Helper methods
/// ------------------------------------------------------------------------------------
///
@@ -1338,77 +1182,6 @@ private void CheckFileListContents(string[] files, ImportDomain domain)
for (int index = 0; index < found.Length; index++)
Assert.IsTrue(found[index], "File not found in " + domain + " source: " + files[index]);
}
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Test to see if the ImportProjectIsAccessible method works for projects other than
- /// Paratext 6.
- ///
- /// ------------------------------------------------------------------------------------
- private void ImportProjectIsAccessible_helper()
- {
- string scrFile1 = m_fileOs.MakeSfFile("GEN", @"\p", @"\c 1", @"\v 1", @"\v 2");
- string scrFile2 = m_fileOs.MakeSfFile("EXO", @"\p", @"\c 1", @"\v 1", @"\v 2");
- string scrFile3 = m_fileOs.MakeSfFile("LEV", @"\p", @"\c 1", @"\v 1", @"\v 2");
- string btFileDef = m_fileOs.MakeSfFile("GEN", @"\p", @"\c 3", @"\v 1");
- string btFileSpan = m_fileOs.MakeSfFile("GEN", @"\p", @"\c 3", @"\v 1");
- string annotFileCons = m_fileOs.MakeSfFile("GEN", @"\p", @"\c 3", @"\v 1");
- string annotFileTrans = m_fileOs.MakeSfFile("GEN", @"\p", @"\c 3", @"\v 1");
-
- m_importSettings.AddFile(scrFile1, ImportDomain.Main, null, null);
- m_importSettings.AddFile(scrFile2, ImportDomain.Main, null, null);
- m_importSettings.AddFile(scrFile3, ImportDomain.Main, null, null);
- m_importSettings.AddFile(btFileDef, ImportDomain.BackTrans, null, null);
- m_importSettings.AddFile(btFileSpan, ImportDomain.BackTrans, "es", null);
- m_importSettings.AddFile(annotFileCons, ImportDomain.Annotations, null, m_consultantNoteDefn);
- m_importSettings.AddFile(annotFileTrans, ImportDomain.Annotations, null, m_translatorNoteDefn);
-
- StringCollection filesNotFound;
- Assert.IsTrue(m_importSettings.ImportProjectIsAccessible(out filesNotFound));
- Assert.AreEqual(0, filesNotFound.Count);
- m_importSettings.SaveSettings();
-
- // Blow away some project files: should still return true, but should
- // report missing files.
- FileUtils.Delete(scrFile2);
- FileUtils.Delete(scrFile3);
- FileUtils.Delete(btFileDef);
- FileUtils.Delete(annotFileCons);
- FileUtils.Delete(annotFileTrans);
-
- // Now that we've saved the settings, we'll "revert" in order to re-load from the DB
- m_importSettings.RevertToSaved();
-
- Assert.IsTrue(m_importSettings.ImportProjectIsAccessible(out filesNotFound));
- Assert.AreEqual(5, filesNotFound.Count);
-
- Assert.IsTrue(filesNotFound.Contains(scrFile2));
- Assert.IsTrue(filesNotFound.Contains(scrFile3));
- Assert.IsTrue(filesNotFound.Contains(btFileDef));
- Assert.IsTrue(filesNotFound.Contains(annotFileCons));
- Assert.IsTrue(filesNotFound.Contains(annotFileTrans));
-
- m_importSettings.SaveSettings();
-
- // Blow away the rest of the project files: should return false and report
- // missing files.
- FileUtils.Delete(scrFile1);
- FileUtils.Delete(btFileSpan);
-
- // Now that we've saved the settings, we'll "revert" in order to re-load from the DB
- m_importSettings.RevertToSaved();
-
- Assert.IsFalse(m_importSettings.ImportProjectIsAccessible(out filesNotFound));
- Assert.AreEqual(7, filesNotFound.Count);
-
- Assert.IsTrue(filesNotFound.Contains(scrFile1));
- Assert.IsTrue(filesNotFound.Contains(scrFile2));
- Assert.IsTrue(filesNotFound.Contains(scrFile3));
- Assert.IsTrue(filesNotFound.Contains(btFileDef));
- Assert.IsTrue(filesNotFound.Contains(btFileSpan));
- Assert.IsTrue(filesNotFound.Contains(annotFileCons));
- Assert.IsTrue(filesNotFound.Contains(annotFileTrans));
- }
#endregion
}
}
diff --git a/Src/FDO/FDOTests/ScrMappingListTests.cs b/Src/FDO/FDOTests/ScrMappingListTests.cs
index 718400bae8..580331eeac 100644
--- a/Src/FDO/FDOTests/ScrMappingListTests.cs
+++ b/Src/FDO/FDOTests/ScrMappingListTests.cs
@@ -11,7 +11,10 @@
using Rhino.Mocks;
using SIL.FieldWorks.Common.COMInterfaces;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.ScriptureUtils;
+using SIL.FieldWorks.Resources;
+using SIL.FieldWorks.Test.TestUtils;
using SIL.Utils;
using SIL.FieldWorks.FDO.DomainServices;
@@ -23,7 +26,7 @@ namespace SIL.FieldWorks.FDO.FDOTests
///
/// ----------------------------------------------------------------------------------------
[TestFixture]
- public class ScrMappingListTests: SIL.FieldWorks.Test.TestUtils.BaseTest
+ public class ScrMappingListTests : BaseTest
{
#region Save/load mappings tests
/// ------------------------------------------------------------------------------------
@@ -34,7 +37,7 @@ public class ScrMappingListTests: SIL.FieldWorks.Test.TestUtils.BaseTest
[Test]
public void SetMappings_Main()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Main, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\a", null, false, MappingTargetType.TEStyle, MarkerDomain.Default, ScrStyleNames.NormalParagraph, null));
list.Add(new ImportMappingInfo(@"\a", null, false, MappingTargetType.TEStyle, MarkerDomain.BackTrans, ScrStyleNames.NormalParagraph, "es"));
list.Add(new ImportMappingInfo(@"\b", null, false, MappingTargetType.TEStyle, MarkerDomain.Default, ScrStyleNames.NormalParagraph, null));
@@ -87,7 +90,7 @@ public void SetMappings_Main()
[Test]
public void SetMappings_Notes()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Notes, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Notes, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\a", null, false, MappingTargetType.TEStyle, MarkerDomain.Note, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\b", null, false, MappingTargetType.TEStyle, MarkerDomain.Default, ScrStyleNames.Remark, null));
try
@@ -116,7 +119,7 @@ public void SetMappings_Notes()
[Test]
public void Delete()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Main, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\aa", null, false, MappingTargetType.TEStyle, MarkerDomain.Default, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\bb", null, false, MappingTargetType.TEStyle, MarkerDomain.Default, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\cc", null, false, MappingTargetType.TEStyle, MarkerDomain.BackTrans, ScrStyleNames.Remark, null));
@@ -139,7 +142,7 @@ public void Delete()
[Test]
public void HasChanged()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Main, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\aa", null, false, MappingTargetType.TEStyle, MarkerDomain.Default, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\bb", null, false, MappingTargetType.TEStyle, MarkerDomain.Default, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\cc", null, false, MappingTargetType.TEStyle, MarkerDomain.BackTrans, ScrStyleNames.Remark, null));
@@ -166,7 +169,7 @@ public void HasChanged()
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Index_OutOfRange()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Notes, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Notes, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\a", null, false, MappingTargetType.TEStyle, MarkerDomain.Note, ScrStyleNames.Remark, null));
// Access the second element which should throw an exception
@@ -181,7 +184,7 @@ public void Index_OutOfRange()
[Test]
public void LookupByKey()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Notes, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Notes, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\aa", null, false, MappingTargetType.TEStyle, MarkerDomain.Note, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\bb", null, false, MappingTargetType.TEStyle, MarkerDomain.Note, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\cc", null, false, MappingTargetType.TEStyle, MarkerDomain.Note, ScrStyleNames.Remark, null));
@@ -199,7 +202,7 @@ public void LookupByKey()
[Test]
public void LookupByKey_NonExistent()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Notes, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Notes, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
Assert.IsNull(list["moogy"]);
}
@@ -211,7 +214,7 @@ public void LookupByKey_NonExistent()
[Test]
public void Enumerator()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Notes, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Notes, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\aa", null, false, MappingTargetType.TEStyle, MarkerDomain.Note, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\bb", null, false, MappingTargetType.TEStyle, MarkerDomain.Note, ScrStyleNames.Remark, null));
list.Add(new ImportMappingInfo(@"\cc", null, false, MappingTargetType.TEStyle, MarkerDomain.Note, ScrStyleNames.Remark, null));
@@ -235,7 +238,7 @@ public void AddDefaultMappingIfNeeded_FigureMarkers()
{
IVwStylesheet stylesheet = MockRepository.GenerateMock();
- ScrMappingList list = new ScrMappingList(MappingSet.Main, stylesheet);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, stylesheet, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.AddDefaultMappingIfNeeded(@"\cap", ImportDomain.Main, true);
list.AddDefaultMappingIfNeeded(@"\cat", ImportDomain.Main, true);
list.AddDefaultMappingIfNeeded(@"\gmb", ImportDomain.Main, true);
@@ -288,7 +291,7 @@ public void AddDefaultMappingIfNeeded_btMappings()
stylesheet.Stub(x => x.GetType("Emphasis")).Return((int)StyleType.kstCharacter);
stylesheet.Stub(x => x.GetType(ScrStyleNames.Remark)).Return((int)StyleType.kstParagraph);
- ScrMappingList list = new ScrMappingList(MappingSet.Main, stylesheet);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, stylesheet, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.AddDefaultMappingIfNeeded(@"\bt", ImportDomain.Main, true);
list.AddDefaultMappingIfNeeded(@"\btc", ImportDomain.Main, true);
list.AddDefaultMappingIfNeeded(@"\btf", ImportDomain.Main, true);
@@ -364,7 +367,7 @@ public void AddDefaultMappingIfNeeded_btMappingsWithNonDefaultMappings()
stylesheet.Stub(x => x.GetContext("Emphasis")).Return((int)ContextValues.General);
stylesheet.Stub(x => x.GetType("Emphasis")).Return((int)StyleType.kstCharacter);
- ScrMappingList list = new ScrMappingList(MappingSet.Main, stylesheet);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, stylesheet, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\p", null, "Emphasis"));
list.AddDefaultMappingIfNeeded(@"\btp", ImportDomain.Main, true);
Assert.AreEqual(2, list.Count);
@@ -390,7 +393,7 @@ public void AddDefaultMappingIfNeeded_btNotFromTeStyle()
{
IVwStylesheet stylesheet = MockRepository.GenerateStrictMock();
- ScrMappingList list = new ScrMappingList(MappingSet.Main, stylesheet);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, stylesheet, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(@"\h", null, false, MappingTargetType.TitleShort,
MarkerDomain.Default, null, null));
list.AddDefaultMappingIfNeeded(@"\bth", ImportDomain.Main, true);
@@ -425,7 +428,7 @@ public void AddDefaultMappingIfNeeded_btNotFromTeStyle()
[ExpectedException(typeof(ArgumentNullException))]
public void AddNullMappingInfo()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Main, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(null);
}
@@ -439,7 +442,7 @@ public void AddNullMappingInfo()
[ExpectedException(typeof(ArgumentException))]
public void AddInfoWithNullMarker()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Main, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(null, null, null));
}
@@ -453,7 +456,7 @@ public void AddInfoWithNullMarker()
[ExpectedException(typeof(ArgumentException))]
public void AddBlankMarker()
{
- ScrMappingList list = new ScrMappingList(MappingSet.Main, null);
+ ScrMappingList list = new ScrMappingList(MappingSet.Main, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
list.Add(new ImportMappingInfo(string.Empty, string.Empty, string.Empty));
}
#endregion
diff --git a/Src/FDO/FDOTests/ScrSfFileListTests.cs b/Src/FDO/FDOTests/ScrSfFileListTests.cs
index 1b7e408246..9b6b47da78 100644
--- a/Src/FDO/FDOTests/ScrSfFileListTests.cs
+++ b/Src/FDO/FDOTests/ScrSfFileListTests.cs
@@ -7,8 +7,10 @@
using System.Collections.Generic;
using NUnit.Framework;
+using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainServices;
using Rhino.Mocks;
+using SIL.FieldWorks.Resources;
using SIL.FieldWorks.Test.TestUtils;
using SIL.FieldWorks.Common.ScriptureUtils;
using SILUBS.SharedScrUtils;
@@ -25,7 +27,7 @@ public class ScrSfFileListTests: BaseTest
{
#region data members
private IOverlappingFileResolver m_resolver;
- private ScrMappingList m_mappingList = new ScrMappingList(MappingSet.Main, null);
+ private ScrMappingList m_mappingList = new ScrMappingList(MappingSet.Main, null, ResourceHelper.DefaultParaCharsStyleName, FwDirectoryFinder.TeStylesPath);
private ScrSfFileList m_fileList;
private List m_expectedRemovedFiles;
private int m_callCountForVerifyFileRemoved;
diff --git a/Src/Common/FwUtils/FwUtilsTests/TestProjectId.cs b/Src/FDO/FDOTests/TestProjectId.cs
similarity index 96%
rename from Src/Common/FwUtils/FwUtilsTests/TestProjectId.cs
rename to Src/FDO/FDOTests/TestProjectId.cs
index 794e619522..a4ae046787 100644
--- a/Src/Common/FwUtils/FwUtilsTests/TestProjectId.cs
+++ b/Src/FDO/FDOTests/TestProjectId.cs
@@ -5,9 +5,9 @@
// File: TestProjectId.cs
// Responsibility: FW Team
// ---------------------------------------------------------------------------------------------
-using SysPath = System.IO.Path;
+using SIL.FieldWorks.Common.FwUtils;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.FieldWorks.FDO.FDOTests
{
/// ----------------------------------------------------------------------------------------
///
@@ -78,7 +78,7 @@ public string PipeHandle
/// ------------------------------------------------------------------------------------
public string Name
{
- get { return SysPath.GetFileNameWithoutExtension(Path); }
+ get { return System.IO.Path.GetFileNameWithoutExtension(Path); }
}
/// ------------------------------------------------------------------------------------
@@ -89,7 +89,7 @@ public string Name
/// ------------------------------------------------------------------------------------
public string ProjectFolder
{
- get { return SysPath.GetDirectoryName(Path); }
+ get { return System.IO.Path.GetDirectoryName(Path); }
}
/// ------------------------------------------------------------------------------------
diff --git a/Src/FDO/FDOTests/ValidCharactersTests.cs b/Src/FDO/FDOTests/ValidCharactersTests.cs
index b6d1c72c47..34622bbaf2 100644
--- a/Src/FDO/FDOTests/ValidCharactersTests.cs
+++ b/Src/FDO/FDOTests/ValidCharactersTests.cs
@@ -123,7 +123,7 @@ public List OtherCharacters
[Test]
public void InitializeFromOldValidCharsList()
{
- var validChars = ValidCharacters.Load(" a b c d . 1 2 3", "Test WS", null, null);
+ var validChars = ValidCharacters.Load(" a b c d . 1 2 3", "Test WS", null, null, FwDirectoryFinder.CodeDirectory);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(4, validCharsW.WordFormingCharacters.Count);
Assert.IsTrue(validCharsW.WordFormingCharacters.Contains("a"));
@@ -161,7 +161,7 @@ public void InitializeFromXml_Valid()
"4\uFFFC5" +
",\uFFFC!\uFFFC*" +
"";
- var validChars = ValidCharacters.Load(sXml, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(sXml, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(4, validCharsW.WordFormingCharacters.Count);
Assert.IsTrue(validCharsW.WordFormingCharacters.Contains("e"));
@@ -191,7 +191,7 @@ public void InitializeFromXml_ValidEmpty()
"" +
"" +
"";
- var validChars = ValidCharacters.Load(sXml, "Test WS", null, RememberError);
+ var validChars = ValidCharacters.Load(sXml, "Test WS", null, RememberError, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(0, validCharsW.WordFormingCharacters.Count);
Assert.AreEqual(0, validCharsW.NumericCharacters.Count);
@@ -209,7 +209,7 @@ public void InitializeFromXml_ValidEmpty()
[Test]
public void InitializeFromXml_ValidNull()
{
- var validChars = ValidCharacters.Load(null, "Test WS", null, RememberError);
+ var validChars = ValidCharacters.Load(null, "Test WS", null, RememberError, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(0, validCharsW.WordFormingCharacters.Count);
Assert.AreEqual(0, validCharsW.NumericCharacters.Count);
@@ -225,7 +225,7 @@ public void InitializeFromXml_ValidNull()
[Test]
public void InitializeFromXml_ValidEmptyString()
{
- var validChars = ValidCharacters.Load(String.Empty, "Test WS", null, RememberError);
+ var validChars = ValidCharacters.Load(String.Empty, "Test WS", null, RememberError, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(0, validCharsW.WordFormingCharacters.Count);
Assert.AreEqual(0, validCharsW.NumericCharacters.Count);
@@ -246,7 +246,7 @@ public void InitializeFromXml_AllowHardLineBreakCharacter()
"" +
"\u2028" +
"";
- var validChars = ValidCharacters.Load(sXml, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(sXml, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(1, validCharsW.OtherCharacters.Count);
Assert.IsTrue(validCharsW.OtherCharacters.Contains("\u2028"));
@@ -269,7 +269,7 @@ public void InitializeFromXml_NumericElementClosedTooEarly()
"4\uFFFC5" +
",\uFFFC!\uFFFC*" +
"";
- var validChars = ValidCharacters.Load(ws, null);
+ var validChars = ValidCharacters.Load(ws, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(4, validCharsW.WordFormingCharacters.Count);
Assert.IsTrue(validCharsW.WordFormingCharacters.Contains("e"));
@@ -299,7 +299,7 @@ public void InitializeFromXml_BogusFormat()
",\uFFFC!\uFFFC*" +
"";
- var validChars = ValidCharacters.Load(ws, RememberError);
+ var validChars = ValidCharacters.Load(ws, RememberError, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
VerifyDefaultWordFormingCharacters(validChars);
Assert.AreEqual("Invalid ValidChars field while loading the English (United States) writing system:" +
@@ -323,7 +323,7 @@ public void InitializeFromXml_SingleBogusCharacter()
"" +
"";
- var validChars = ValidCharacters.Load(ws, RememberError);
+ var validChars = ValidCharacters.Load(ws, RememberError, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
VerifyDefaultWordFormingCharacters(validChars);
Assert.AreEqual("Invalid ValidChars field while loading the English (United States) writing system. " +
"The following characters are invalid:" +
@@ -347,7 +347,7 @@ public void InitializeFromXml_SingleCompoundBogusCharacter()
"" +
"";
- var validChars = ValidCharacters.Load(ws, RememberError);
+ var validChars = ValidCharacters.Load(ws, RememberError, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
VerifyDefaultWordFormingCharacters(validChars);
Assert.AreEqual("Invalid ValidChars field while loading the English (United States) writing system. " +
"The following characters are invalid:" +
@@ -371,7 +371,7 @@ public void InitializeFromXml_ValidAndBogusCharacters()
"" +
"";
- var validChars = ValidCharacters.Load(ws, RememberError);
+ var validChars = ValidCharacters.Load(ws, RememberError, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(2, validCharsW.WordFormingCharacters.Count);
Assert.IsTrue(validCharsW.WordFormingCharacters.Contains("g"));
@@ -401,7 +401,7 @@ public void InitializeFromXml_SameCharacterInWordFormingAndPunctuationXMLLists()
"" +
"'" +
"";
- var validChars = ValidCharacters.Load(sXml, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(sXml, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(1, validCharsW.WordFormingCharacters.Count);
Assert.IsTrue(validCharsW.WordFormingCharacters.Contains("'"));
@@ -422,7 +422,7 @@ public void InitializeFromXml_SameCharacterInWordFormingAndNumbericXMLLists()
"1" +
"" +
"";
- var validChars = ValidCharacters.Load(sXml, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(sXml, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(1, validCharsW.WordFormingCharacters.Count);
Assert.IsTrue(validCharsW.WordFormingCharacters.Contains("1"));
@@ -443,7 +443,7 @@ public void InitializeFromXml_SameCharacterInNumericAndPunctuationXMLLists()
"1" +
"1" +
"";
- var validChars = ValidCharacters.Load(sXml, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(sXml, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(0, validCharsW.WordFormingCharacters.Count);
Assert.AreEqual(1, validCharsW.NumericCharacters.Count);
@@ -464,7 +464,7 @@ public void InitializeFromXml_DuplicateCharacters()
"4\uFFFC4" +
"'\uFFFC'" +
"";
- var validChars = ValidCharacters.Load(sXml, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(sXml, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(1, validCharsW.WordFormingCharacters.Count);
Assert.IsTrue(validCharsW.WordFormingCharacters.Contains("a"));
@@ -482,7 +482,7 @@ public void InitializeFromXml_DuplicateCharacters()
[Test]
public void InitializeFromNullString()
{
- var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(0, validCharsW.WordFormingCharacters.Count);
Assert.AreEqual(0, validCharsW.NumericCharacters.Count);
@@ -500,7 +500,7 @@ public void InitializeFromNullString()
[Test]
public void AddCharacter_Duplicate()
{
- var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
validChars.AddCharacter("a");
validChars.AddCharacter("a");
@@ -528,7 +528,7 @@ public void AddCharacter_DuplicateOfOverriddenWordFormingChar()
"" +
"{" +
"";
- var validChars = ValidCharacters.Load(sXml, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(sXml, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
Assert.AreEqual(2, validCharsW.WordFormingCharacters.Count);
Assert.AreEqual(0, validCharsW.NumericCharacters.Count);
@@ -555,7 +555,7 @@ public void AddCharacter_DuplicateOfOverriddenWordFormingChar()
[Test]
public void AddCharacter_SuperscriptedToneNumber()
{
- var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
ValidCharsWrapper validCharsW = new ValidCharsWrapper(validChars);
validChars.AddCharacter("\u00b9");
validChars.AddCharacter("\u2079");
@@ -574,7 +574,7 @@ public void AddCharacter_SuperscriptedToneNumber()
[Test]
public void GetNaturalCharType()
{
- var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
DummyCharPropEngine cpe = new DummyCharPropEngine();
ReflectionHelper.SetField(validChars, "m_cpe", cpe);
Assert.AreEqual(ValidCharacterType.WordForming,
@@ -601,7 +601,7 @@ public void IsWordFormingChar()
"a\uFFFCb\uFFFCc\uFFFCd\uFFFCe\uFFFC#" +
"" +
"" +
- "", "Test WS", null, null);
+ "", "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
Assert.IsTrue(validChars.IsWordForming('#'));
//Assert.IsTrue(validChars.IsWordForming("#"));
}
@@ -614,7 +614,7 @@ public void IsWordFormingChar()
[Test]
public void SortAfterAddSingles()
{
- var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
IWritingSystem ws = m_wsManager.Create("en");
validChars.InitSortComparer(ws);
validChars.AddCharacter("z");
@@ -636,7 +636,7 @@ public void SortAfterAddSingles()
[Test]
public void SortAfterAddRange()
{
- var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null);
+ var validChars = ValidCharacters.Load(string.Empty, "Test WS", null, null, FwDirectoryFinder.LegacyWordformingCharOverridesFile);
IWritingSystem ws = m_wsManager.Create("en");
validChars.InitSortComparer(ws);
var list = new List(new[] { "z", "c", "t", "b", "8", "7", "6", "5" });
diff --git a/Src/FDO/FDOTests/WritingSystemServicesTests.cs b/Src/FDO/FDOTests/WritingSystemServicesTests.cs
index 923922f17a..ca1be12016 100644
--- a/Src/FDO/FDOTests/WritingSystemServicesTests.cs
+++ b/Src/FDO/FDOTests/WritingSystemServicesTests.cs
@@ -1,14 +1,10 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.Collections.Generic;
using NUnit.Framework;
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
-using SIL.FieldWorks.Test.TestUtils;
namespace SIL.FieldWorks.FDO.FDOTests
{
@@ -49,7 +45,7 @@ public void UpdateWritingSystemListField_ReplacesNonDuplicateCode()
public void FindOrCreateSomeWritingSystem_Converts_x_unk_To_qaa_x_unk()
{
IWritingSystem ws;
- Assert.That(WritingSystemServices.FindOrCreateSomeWritingSystem(Cache, "x-unk", true, false, out ws), Is.False);
+ Assert.That(WritingSystemServices.FindOrCreateSomeWritingSystem(Cache, null, "x-unk", true, false, out ws), Is.False);
Assert.That(ws.Id, Is.EqualTo("qaa-x-unk"));
}
@@ -62,7 +58,7 @@ public void FindOrCreateSomeWritingSystem_Converts_x_unk_To_qaa_x_unk()
public void FindOrCreateSomeWritingSystem_Converts_Fr_Tech_30Oct_To_qaa_x_Fr_Tech_30Oct()
{
IWritingSystem ws;
- Assert.That(WritingSystemServices.FindOrCreateSomeWritingSystem(Cache, "Fr-Tech 30Oct", true, false, out ws), Is.False);
+ Assert.That(WritingSystemServices.FindOrCreateSomeWritingSystem(Cache, null, "Fr-Tech 30Oct", true, false, out ws), Is.False);
Assert.That(ws.Id, Is.EqualTo("qaa-x-Fr-Tech30Oc")); //8 characters is the maximum allowed for a part.
}
@@ -73,7 +69,7 @@ public void FindOrCreateSomeWritingSystem_Converts_Fr_Tech_30Oct_To_qaa_x_Fr_Tec
public void FindOrCreateSomeWritingSystem_Converts_x_To_qaa_x_qaa()
{
IWritingSystem ws;
- Assert.That(WritingSystemServices.FindOrCreateSomeWritingSystem(Cache, "x", true, false, out ws), Is.False);
+ Assert.That(WritingSystemServices.FindOrCreateSomeWritingSystem(Cache, null, "x", true, false, out ws), Is.False);
Assert.That(ws.Id, Is.EqualTo("qaa-x-qaa"));
}
///
@@ -108,7 +104,7 @@ public void UpdateWritingSystemTag_MarksObjectsAsDirty()
{
var entry0 = Cache.ServiceLocator.GetInstance().Create();
IWritingSystem newWs;
- var ws = WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-NO", true, false, out newWs);
+ var ws = WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-NO", true, false, out newWs);
// A string property NOT using the WS we will change.
entry0.ImportResidue = Cache.TsStrFactory.MakeString("hello", Cache.DefaultAnalWs);
// A multilingual one using the WS.
@@ -172,9 +168,9 @@ public void MergeWritingSystem_ConvertsMultiStrings()
{
var entry1 = Cache.ServiceLocator.GetInstance().Create();
IWritingSystem fromWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-NO", true, false, out fromWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-NO", true, false, out fromWs);
IWritingSystem toWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-SO", true, false, out toWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-SO", true, false, out toWs);
EnsureAnalysisWs(new [] {fromWs, toWs});
var sense1 = Cache.ServiceLocator.GetInstance().Create();
entry1.SensesOS.Add(sense1);
@@ -209,9 +205,9 @@ void EnsureAnalysisWs(IWritingSystem[] wss)
public void MergeWritingSystem_ConvertsStyleDefinition()
{
IWritingSystem fromWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-NO", true, false, out fromWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-NO", true, false, out fromWs);
IWritingSystem toWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-SO", true, false, out toWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-SO", true, false, out toWs);
EnsureAnalysisWs(new [] { fromWs, toWs });
var style1 = Cache.ServiceLocator.GetInstance().Create();
@@ -240,9 +236,9 @@ public void MergeWritingSystem_ConvertsStyleDefinition()
public void MergeWritingSystemWithStyleDefnForToWs_DoesNotConvertStyleDefinition()
{
IWritingSystem fromWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-NO", true, false, out fromWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-NO", true, false, out fromWs);
IWritingSystem toWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-SO", true, false, out toWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-SO", true, false, out toWs);
EnsureAnalysisWs(new[] { fromWs, toWs });
var style1 = Cache.ServiceLocator.GetInstance().Create();
@@ -277,9 +273,9 @@ public void MergeWritingSystemWithStyleDefnForToWs_DoesNotConvertStyleDefinition
public void MergeWritingSystem_ConvertsLiftResidue()
{
IWritingSystem fromWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-NO", true, false, out fromWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-NO", true, false, out fromWs);
IWritingSystem toWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "en-SO", true, false, out toWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "en-SO", true, false, out toWs);
EnsureAnalysisWs(new[] { fromWs, toWs });
var entry1 = Cache.ServiceLocator.GetInstance().Create();
@@ -306,7 +302,7 @@ public void CollatorSort_DoesNotThrow()
Assert.DoesNotThrow(() =>
{
IWritingSystem fromWs;
- WritingSystemServices.FindOrCreateWritingSystem(Cache, "sen", false, true, out fromWs);
+ WritingSystemServices.FindOrCreateWritingSystem(Cache, null, "sen", false, true, out fromWs);
Cache.LangProject.DefaultVernacularWritingSystem = fromWs;
fromWs.Collator.GetSortKey("boom");
});
diff --git a/Src/FDO/FDOTests/XmlImportDataTests.cs b/Src/FDO/FDOTests/XmlImportDataTests.cs
index 54055e1868..961247c76d 100644
--- a/Src/FDO/FDOTests/XmlImportDataTests.cs
+++ b/Src/FDO/FDOTests/XmlImportDataTests.cs
@@ -21,7 +21,6 @@
using SIL.FieldWorks.FDO.Application.ApplicationServices;
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.Test.TestUtils;
-using SIL.Utils;
namespace SIL.FieldWorks.FDO.FDOTests
{
@@ -48,7 +47,7 @@ public void CreateTestCache()
{
m_now = DateTime.Now;
m_cache = FdoCache.CreateCacheWithNewBlankLangProj(
- new TestProjectId(FDOBackendProviderType.kMemoryOnly, "MemoryOnly.mem"), "en", "fr", "en", new ThreadHelper());
+ new TestProjectId(FDOBackendProviderType.kMemoryOnly, "MemoryOnly.mem"), "en", "fr", "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories);
IDataSetup dataSetup = m_cache.ServiceLocator.GetInstance();
dataSetup.LoadDomain(BackendBulkLoadDomain.All);
if (m_cache.LangProject != null)
@@ -76,7 +75,6 @@ public void DestroyTestCache()
{
if (m_cache != null)
{
- m_cache.ThreadHelper.Dispose();
m_cache.Dispose();
m_cache = null;
}
@@ -161,8 +159,7 @@ public void ImportData1()
Assert.AreEqual(0, m_cache.LangProject.AnthroListOA.PossibilitiesOS.Count);
Assert.AreEqual(0, m_cache.LangProject.SemanticDomainListOA.PossibilitiesOS.Count);
Assert.AreEqual(0, m_cache.LangProject.PartsOfSpeechOA.PossibilitiesOS.Count);
- bool fOk = xid.ImportData(rdr, new StringWriter(sbLog), null);
- Assert.IsTrue(fOk, "Import of one lexical entry succeeded.");
+ xid.ImportData(rdr, new StringWriter(sbLog), null);
DateTime dtLexNew = m_cache.LangProject.LexDbOA.DateCreated;
DateTime dt2 = new DateTime(1995, 12, 19, 10, 31, 25);
Assert.AreEqual(dt2, dtLexNew, "LexDb DateCreated changed to reflect import value.");
@@ -385,8 +382,7 @@ public void ImportData2()
))
{
StringBuilder sbLog = new StringBuilder();
- bool fOk = xid.ImportData(rdr, new StringWriter(sbLog), null);
- Assert.IsTrue(fOk, "Import of one LexEntry, one RreversalIndexEntry, and two WfiWordforms succeeded.");
+ xid.ImportData(rdr, new StringWriter(sbLog), null);
IWritingSystem wsEn = m_cache.ServiceLocator.WritingSystemManager.Get("en");
Assert.AreEqual(1, m_cache.LangProject.LexDbOA.ReversalIndexesOC.Count);
IReversalIndex revIdx = m_cache.LangProject.LexDbOA.ReversalIndexesOC.ToArray()[0];
@@ -497,7 +493,7 @@ public void ImportData2()
public void ImportData3()
{
XmlImportData xid = new XmlImportData(m_cache);
- string sFwSrcDir = DirectoryFinder.FwSourceDirectory;
+ string sFwSrcDir = FwDirectoryFinder.SourceDirectory;
using (var rdr = new StringReader(
"" + Environment.NewLine +
"" + Environment.NewLine +
@@ -868,8 +864,7 @@ public void ImportData3()
))
{
StringBuilder sbLog = new StringBuilder();
- bool fOk = xid.ImportData(rdr, new StringWriter(sbLog), null);
- Assert.IsTrue(fOk, "Import of a bunch of stuff succeeded.");
+ xid.ImportData(rdr, new StringWriter(sbLog), null);
int wsEn = m_cache.WritingSystemFactory.GetWsFromStr("en");
int wsAme = m_cache.WritingSystemFactory.GetWsFromStr("qaa-x-ame");
Assert.AreEqual(0, m_cache.LangProject.LexDbOA.ReversalIndexesOC.Count);
@@ -1023,7 +1018,7 @@ private void CheckTheText(IText text)
private void CheckFirstEntry(ILexEntry le, int wsEn, int wsAme)
{
- string sFwSrcDir = DirectoryFinder.FwSourceDirectory;
+ string sFwSrcDir = FwDirectoryFinder.SourceDirectory;
Assert.AreEqual(1, le.LexemeFormOA.Form.StringCount);
Assert.AreEqual("an", le.LexemeFormOA.Form.get_String(wsAme).Text);
Assert.AreEqual("root", le.LexemeFormOA.MorphTypeRA.Name.get_String(wsEn).Text);
@@ -1373,8 +1368,7 @@ public void ImportData4()
Assert.AreEqual(0, m_cache.LangProject.SemanticDomainListOA.PossibilitiesOS.Count);
Assert.AreEqual(0, m_cache.LangProject.PartsOfSpeechOA.PossibilitiesOS.Count);
StringBuilder sbLog = new StringBuilder();
- bool fOk = xid.ImportData(rdr, new StringWriter(sbLog), null);
- Assert.IsTrue(fOk, "Import of one lexical entry succeeded.");
+ xid.ImportData(rdr, new StringWriter(sbLog), null);
Assert.AreEqual(1, m_cache.LangProject.LexDbOA.Entries.Count());
ILexEntry le = m_cache.LangProject.LexDbOA.Entries.ToArray()[0];
int wsKal = m_cache.WritingSystemFactory.GetWsFromStr("qaa-x-kal");
diff --git a/Src/FDO/FDOTests/XmlListTests.cs b/Src/FDO/FDOTests/XmlListTests.cs
index 671f957225..5e34721cda 100644
--- a/Src/FDO/FDOTests/XmlListTests.cs
+++ b/Src/FDO/FDOTests/XmlListTests.cs
@@ -10,9 +10,7 @@
using System.IO;
using NUnit.Framework;
using SIL.FieldWorks.FDO.Application.ApplicationServices;
-using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.Test.TestUtils;
-using SIL.Utils;
using SIL.FieldWorks.Common.FwUtils;
namespace SIL.FieldWorks.FDO.FDOTests
@@ -594,7 +592,7 @@ public class XmlListTests : BaseTest
public void CreateMockCache()
{
m_cache = FdoCache.CreateCacheWithNewBlankLangProj(
- new TestProjectId(FDOBackendProviderType.kMemoryOnly, null), "en", "es", "en", new ThreadHelper());
+ new TestProjectId(FDOBackendProviderType.kMemoryOnly, null), "en", "es", "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories);
}
///
@@ -603,7 +601,6 @@ public void CreateMockCache()
[TearDown]
public void DestroyMockCache()
{
- m_cache.ThreadHelper.Dispose();
m_cache.Dispose();
m_cache = null;
}
diff --git a/Src/FDO/FDOTests/XmlTranslatedListsTests.cs b/Src/FDO/FDOTests/XmlTranslatedListsTests.cs
index bd7fd109df..1e84f6da3f 100644
--- a/Src/FDO/FDOTests/XmlTranslatedListsTests.cs
+++ b/Src/FDO/FDOTests/XmlTranslatedListsTests.cs
@@ -638,7 +638,7 @@ public class XmlTranslatedListsTests : BaseTest
public void CreateMockCache()
{
m_cache = FdoCache.CreateCacheWithNewBlankLangProj(
- new TestProjectId(FDOBackendProviderType.kMemoryOnly, null), "en", "es", "en", new ThreadHelper());
+ new TestProjectId(FDOBackendProviderType.kMemoryOnly, null), "en", "es", "en", new DummyFdoUI(), FwDirectoryFinder.FdoDirectories);
var xl = new XmlList();
using (var reader = new StringReader(XmlListTests.s_ksPartsOfSpeechXml))
@@ -667,7 +667,6 @@ public void CreateMockCache()
[TearDown]
public void DestroyMockCache()
{
- m_cache.ThreadHelper.Dispose();
m_cache.Dispose();
m_cache = null;
}
diff --git a/Src/FDO/FdoCacheIFwDisposableInterfaceImpl.cs b/Src/FDO/FdoCacheIFwDisposableInterfaceImpl.cs
index 9f340f32eb..9523e781e7 100644
--- a/Src/FDO/FdoCacheIFwDisposableInterfaceImpl.cs
+++ b/Src/FDO/FdoCacheIFwDisposableInterfaceImpl.cs
@@ -10,7 +10,6 @@
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.IOC;
using SIL.Utils;
-using SIL.FieldWorks.FDO.Infrastructure;
namespace SIL.FieldWorks.FDO
{
@@ -159,7 +158,6 @@ private void Dispose(bool disposing)
// Main data members.
m_lgwsFactory = null;
m_serviceLocator = null;
- m_threadHelper = null;
m_isDisposed = true;
}
diff --git a/Src/FDO/FdoDataMigrationForbiddenException.cs b/Src/FDO/FdoDataMigrationForbiddenException.cs
new file mode 100644
index 0000000000..f0400e25ee
--- /dev/null
+++ b/Src/FDO/FdoDataMigrationForbiddenException.cs
@@ -0,0 +1,15 @@
+// Copyright (c) 2014-2014 SIL International
+// This software is licensed under the LGPL, version 2.1 or later
+// (http://www.gnu.org/licenses/lgpl-2.1.html)
+
+using System;
+
+namespace SIL.FieldWorks.FDO
+{
+ ///
+ /// Exception thrown when we try to open a project which requires data migration but data migration has been forbidden by the application
+ ///
+ public class FdoDataMigrationForbiddenException : Exception
+ {
+ }
+}
\ No newline at end of file
diff --git a/Src/FDO/FdoFactoryInterfaceAdditions.cs b/Src/FDO/FdoFactoryInterfaceAdditions.cs
index d318d55f34..c762285e5c 100644
--- a/Src/FDO/FdoFactoryInterfaceAdditions.cs
+++ b/Src/FDO/FdoFactoryInterfaceAdditions.cs
@@ -1096,4 +1096,12 @@ public partial interface ICmMediaURIFactory
/// A new, unowned CmMediaURI with the given guid
ICmMediaURI Create(FdoCache cache, Guid guid);
}
+
+ public partial interface IScrImportSetFactory
+ {
+ ///
+ /// Creates a new scripture import settings with the default paragraph characters style name.
+ ///
+ IScrImportSet Create(string defaultParaCharsStyleName, string stylesPath);
+ }
}
\ No newline at end of file
diff --git a/Src/FDO/FdoFileHelper.cs b/Src/FDO/FdoFileHelper.cs
new file mode 100644
index 0000000000..be1860eacb
--- /dev/null
+++ b/Src/FDO/FdoFileHelper.cs
@@ -0,0 +1,260 @@
+// Copyright (c) 2013-2014 SIL International
+// This software is licensed under the LGPL, version 2.1 or later
+// (http://www.gnu.org/licenses/lgpl-2.1.html)
+
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Text;
+using SIL.Utils;
+
+namespace SIL.FieldWorks.FDO
+{
+ /// ----------------------------------------------------------------------------------------
+ ///
+ /// Static class to hold a few constant FDO file extensions.
+ ///
+ /// ----------------------------------------------------------------------------------------
+ public static class FdoFileHelper
+ {
+ /// Default extension for FieldWorks XML data files (with the period)
+ public const string ksFwDataXmlFileExtension = ".fwdata";
+ /// Default extension for FieldWorks DB4o data files (with the period)
+ public const string ksFwDataDb4oFileExtension = ".fwdb";
+ /// Default extension for FieldWorks backup files (with the period).
+ public const string ksFwBackupFileExtension = ".fwbackup";
+ /// Default extension for FieldWorks 6.0 and earlier backup files (with the period).
+ public const string ksFw60BackupFileExtension = ".zip";
+ /// Default extension for FieldWorks TEMPORARY fallback data files (with the period).
+ public const string ksFwDataFallbackFileExtension = ".bak";
+
+
+ /// The name of the folder containing FLEx configuration settings
+ public const string ksConfigurationSettingsDir = "ConfigurationSettings";
+ /// The name of the folder containing FLEx backup settings
+ public const string ksBackupSettingsDir = "BackupSettings";
+ /// The name of the folder where the user can copy files for backup such as fonts and keyboards
+ public const string ksSupportingFilesDir = "SupportingFiles";
+ /// The default name of the folder containing LinkedFiles (media, pictures, etc) for a project
+ public const string ksLinkedFilesDir = "LinkedFiles";
+ /// The name of the subfolder containing media for a project
+ public const string ksMediaDir = "AudioVisual";
+ /// The name of the subfolder containing pictures for a project
+ public const string ksPicturesDir = "Pictures";
+ /// The name of the subfolder containing other LinkedFiles for a project
+ public const string ksOtherLinkedFilesDir = "Others";
+ /// The name of the folder containing writing systems for a project
+ public const string ksWritingSystemsDir = "WritingSystemStore";
+ /// The name of the folder containing temporary persisted sort sequence info for a project
+ public const string ksSortSequenceTempDir = "Temp";
+
+ /// Constant for locating the other repositories path of a project
+ public const string OtherRepositories = @"OtherRepositories";
+
+ /// The filename of the backup settings file
+ public const string kBackupSettingsFilename = "BackupSettings.xml";
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the configuration settings for the specified project.
+ ///
+ /// The path to the project folder.
+ /// ------------------------------------------------------------------------------------
+ public static string GetConfigSettingsDir(string projectFolder)
+ {
+ return Path.Combine(projectFolder, ksConfigurationSettingsDir);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the backup settings for the specified project
+ ///
+ /// The path to the project folder.
+ /// ------------------------------------------------------------------------------------
+ public static string GetBackupSettingsDir(string projectFolder)
+ {
+ return Path.Combine(projectFolder, ksBackupSettingsDir);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the fonts for the specified project.
+ ///
+ /// The path to the project folder.
+ /// ------------------------------------------------------------------------------------
+ public static string GetSupportingFilesDir(string projectFolder)
+ {
+ return Path.Combine(projectFolder, ksSupportingFilesDir);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the writing systems for the specified project.
+ ///
+ /// The path to the project folder.
+ /// ------------------------------------------------------------------------------------
+ public static string GetWritingSystemDir(string projectFolder)
+ {
+ return Path.Combine(projectFolder, ksWritingSystemsDir);
+ }
+
+ ///
+ /// Gets the path to the standard eternal linked files directory for the specified project.
+ ///
+ /// The path to the project.
+ ///
+ public static string GetDefaultLinkedFilesDir(string projectPath)
+ {
+ return Path.Combine(projectPath, ksLinkedFilesDir);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the standard media files directory for the specified project. Note
+ /// that if this project keepes its externally linked files in a separate folder from
+ /// the rest of the project files (such as a shared folder common to multiple projects
+ /// on a server), the directory returned by this method will not actually contain any
+ /// files.
+ ///
+ /// The path to the project.
+ /// ------------------------------------------------------------------------------------
+ public static string GetDefaultMediaDir(string projectPath)
+ {
+ return Path.Combine(projectPath, Path.Combine(ksLinkedFilesDir, ksMediaDir));
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the standard pictures directory for the specified project. Note
+ /// that if this project keepes its externally linked files in a separate folder from
+ /// the rest of the project files (such as a shared folder common to multiple projects
+ /// on a server), the directory returned by this method will not actually contain any
+ /// files.
+ ///
+ /// The path to the project.
+ /// ------------------------------------------------------------------------------------
+ public static string GetDefaultPicturesDir(string projectPath)
+ {
+ return Path.Combine(projectPath, Path.Combine(ksLinkedFilesDir, ksPicturesDir));
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the standard directory for other externally linked project files.
+ /// Note that if this project keepes its externally linked files in a separate folder
+ /// from the rest of the project files (such as a shared folder common to multiple
+ /// projects on a server), the directory returned by this method will not actually
+ /// contain any files.
+ ///
+ /// The path to the project.
+ /// ------------------------------------------------------------------------------------
+ public static string GetDefaultOtherExternalFilesDir(string projectPath)
+ {
+ return Path.Combine(projectPath, Path.Combine(ksLinkedFilesDir, ksOtherLinkedFilesDir));
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the other repositories for the specified project.
+ ///
+ /// The path to the project folder.
+ /// ------------------------------------------------------------------------------------
+ public static string GetOtherRepositoriesDir(string projectFolder)
+ {
+ return Path.Combine(projectFolder, OtherRepositories);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the media files directory for the project.
+ ///
+ /// The project's LinkedFiles path. (eg. m_cache.LangProject.LinkedFilesRootDir)
+ /// ------------------------------------------------------------------------------------
+ public static string GetMediaDir(string projectLinkedFilesPath)
+ {
+ return Path.Combine(projectLinkedFilesPath, ksMediaDir);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the pictures directory for the project.
+ ///
+ /// The project's LinkedFiles path. (eg. m_cache.LangProject.LinkedFilesRootDir)
+ /// ------------------------------------------------------------------------------------
+ public static string GetPicturesDir(string projectLinkedFilesPath)
+ {
+ return Path.Combine(projectLinkedFilesPath, ksPicturesDir);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path to the directory for other externally linked project files.
+ ///
+ /// The project's LinkedFiles path. (eg. m_cache.LangProject.LinkedFilesRootDir)
+ /// ------------------------------------------------------------------------------------
+ public static string GetOtherExternalFilesDir(string projectLinkedFilesPath)
+ {
+ return Path.Combine(projectLinkedFilesPath, ksOtherLinkedFilesDir);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the name of the XML data file, given a project name (basically just adds the
+ /// FW data XML file extension).
+ ///
+ /// Name of the project (not a filename).
+ /// ------------------------------------------------------------------------------------
+ public static string GetXmlDataFileName(string projectName)
+ {
+ Debug.Assert(Path.GetExtension(projectName) != ksFwDataXmlFileExtension,
+ String.Format("There is a faint chance the user might have specified a real project name ending in {0} (in which case, sorry, but we're going to trim it off), but probably this is a programming error", ksFwDataXmlFileExtension));
+ // Do not use Path.ChangeExtension because it will strip off anything following a period in the project name!
+ return projectName.EndsWith(ksFwDataXmlFileExtension) ? projectName :
+ projectName + ksFwDataXmlFileExtension;
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the name of the DB4O data file, given a project name (basically just adds the
+ /// FW db4o file extension).
+ ///
+ /// Name of the project (not a filename).
+ /// ------------------------------------------------------------------------------------
+ public static string GetDb4oDataFileName(string projectName)
+ {
+ Debug.Assert(Path.GetExtension(projectName) != ksFwDataDb4oFileExtension,
+ String.Format("There is a faint chance the user might have specified a real project name ending in {0} (in which case, sorry, but we're going to trim it off), but probably this is a programming error", ksFwDataDb4oFileExtension));
+ // Do not use Path.ChangeExtension because it will strip off anything following a period in the project name!
+ return projectName.EndsWith(ksFwDataDb4oFileExtension) ? projectName :
+ projectName + ksFwDataDb4oFileExtension;
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Gets the path without the root directory (i.e. make it un-rooted).
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string GetPathWithoutRoot(string pathWithRoot)
+ {
+ string pathRoot = Path.GetPathRoot(pathWithRoot);
+ return pathWithRoot.Substring(pathRoot.Length);
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Takes a windows path and returns it in the format which our backup zip files
+ /// stores them in.
+ ///
+ /// ------------------------------------------------------------------------------------
+ public static string GetZipfileFormattedPath(string path)
+ {
+ StringBuilder strBldr = new StringBuilder(path);
+ string pathRoot = Path.GetPathRoot(path);
+ strBldr.Remove(0, pathRoot.Length);
+ // replace back slashes with forward slashes (for Windows)
+ if (!MiscUtils.IsUnix && !MiscUtils.IsMac)
+ strBldr.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
+ return strBldr.ToString();
+ }
+ }
+}
diff --git a/Src/FDO/FdoFileLockedException.cs b/Src/FDO/FdoFileLockedException.cs
new file mode 100644
index 0000000000..dfedc0bb3c
--- /dev/null
+++ b/Src/FDO/FdoFileLockedException.cs
@@ -0,0 +1,40 @@
+// Copyright (c) 2013-2014 SIL International
+// This software is licensed under the LGPL, version 2.1 or later
+// (http://www.gnu.org/licenses/lgpl-2.1.html)
+
+using System;
+using SIL.CoreImpl;
+
+namespace SIL.FieldWorks.FDO
+{
+ ///
+ /// Exception thrown when we try to open a project that is locked
+ ///
+ public class FdoFileLockedException : StartupException
+ {
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The message.
+ /// ------------------------------------------------------------------------------------
+ public FdoFileLockedException(string message)
+ : base(message)
+ {
+ }
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The message.
+ /// The inner exception.
+ /// True to report this error to the user, false otherwise
+ ///
+ /// ------------------------------------------------------------------------------------
+ public FdoFileLockedException(string message, Exception innerException, bool fReportToUser) :
+ base(message, innerException, fReportToUser)
+ {
+ }
+ }
+}
\ No newline at end of file
diff --git a/Src/FDO/FdoInterfaceAdditions.cs b/Src/FDO/FdoInterfaceAdditions.cs
index ddd1c1765c..0acce21c96 100644
--- a/Src/FDO/FdoInterfaceAdditions.cs
+++ b/Src/FDO/FdoInterfaceAdditions.cs
@@ -13,12 +13,9 @@
using System;
using System.Collections.Generic;
using System.Xml;
-using System.Windows.Forms;
using System.Collections;
-using System.Collections.Specialized;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainImpl;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.Utils;
@@ -863,17 +860,17 @@ IEnumerable AllAllomorphs
///
/// Resets the homograph numbers for all entries.
///
- void ResetHomographNumbers(ProgressBar progressBar);
+ void ResetHomographNumbers(IProgress progressBar);
///
/// Allows user to convert LexEntryType to LexEntryInflType.
///
- void ConvertLexEntryInflTypes(ProgressBar progressBar, IEnumerable list);
+ void ConvertLexEntryInflTypes(IProgress progressBar, IEnumerable list);
///
/// Allows user to convert LexEntryInflType to LexEntryType.
///
- void ConvertLexEntryTypes(ProgressBar progressBar, IEnumerable list);
+ void ConvertLexEntryTypes(IProgress progressBar, IEnumerable list);
///
/// used when dumping the lexical database for the automated Parser
///
@@ -1525,6 +1522,13 @@ string LongNameAdHoc
///
///
bool CanDeleteIfSenseDeleted(ILexSense lexSense);
+
+ ///
+ ///
+ ///
+ /// The ws.
+ ///
+ ITsString PartOfSpeechForWsTSS(int ws);
}
///
@@ -1652,11 +1656,20 @@ ICmPossibility MainPossibility
}
///
- /// If the recipient is a column in a chart that shouldn't be moved or deleted, report
- /// accordingly and return true. Return false if OK to delete or move.
+ /// Gets a value indicating whether this is the default discourse template.
///
- ///
- bool CheckAndReportProtectedChartColumn();
+ bool IsDefaultDiscourseTemplate { get; }
+
+ ///
+ /// Return true if this or one of its children is in use as a Constituent chart column.
+ /// Most efficient to call this after checking that the root is a chart template.
+ ///
+ bool IsThisOrDescendantInUseAsChartColumn { get; }
+
+ ///
+ /// Gets a value indicating whether this is the only text markup tag.
+ ///
+ bool IsOnlyTextMarkupTag { get; }
/// ------------------------------------------------------------------------------------
///
@@ -4158,21 +4171,6 @@ string ParatextNotesProj
set;
}
- /// -----------------------------------------------------------------------------------
- ///
- /// Indicates whether the in-memory import projects/files are currently accessible from
- /// this machine.
- ///
- /// A list of Paratext project IDs or file paths that
- /// could not be found.
- ///
- /// For Paratext projects, this will only return true if all projects are accessible.
- /// For Standard Format, this will return true if any of the files are accessible.
- /// We think this might make sense, but we aren't sure why.
- ///
- /// -----------------------------------------------------------------------------------
- bool ImportProjectIsAccessible(out StringCollection thingsNotFound);
-
/// ------------------------------------------------------------------------------------
///
/// Gets whether to import back translations
@@ -4342,20 +4340,6 @@ IScrImportFileInfo AddFile(string fileName, ImportDomain domain, string wsId,
/// ------------------------------------------------------------------------------------
void RevertToSaved();
- /// ------------------------------------------------------------------------------------
- ///
- /// Gets a list of books that exist for all of the files in this project.
- ///
- /// A List of integers representing 1-based canonical book numbers that exist
- /// in any source represented by these import settings
- /// If project is not a supported type
- /// ------------------------------------------------------------------------------------
- List BooksForProject
- {
- get;
- }
-
-
/// ------------------------------------------------------------------------------------
///
/// Starting reference for the import; for now, we ignore the
@@ -4391,16 +4375,6 @@ IVwStylesheet StyleSheet
set;
}
- /// ------------------------------------------------------------------------------------
- ///
- /// Sets the help file used in a message box if an error occurs.
- ///
- /// ------------------------------------------------------------------------------------
- string HelpFile
- {
- set;
- }
-
/// ------------------------------------------------------------------------------------
///
/// Sets the Overlapping File Resolver
@@ -4425,13 +4399,6 @@ bool Valid
{
get;
}
-
- /// ------------------------------------------------------------------------------------
- ///
- /// Sets the StartRef and EndRef based on the requested canonical book numbers.
- ///
- /// ------------------------------------------------------------------------------------
- void IncludeBooks(int startBook, int endBook, Paratext.ScrVers versification);
}
/// ----------------------------------------------------------------------------------------
@@ -5110,8 +5077,10 @@ bool HasDefaultFootnoteSettings
/// one (which is probably the only one), or creates new settings if none exist.
///
/// type of import type to find.
+ /// The default paragraph characters style name.
+ ///
/// ------------------------------------------------------------------------------------
- IScrImportSet FindOrCreateDefaultImportSettings(TypeOfImport importType);
+ IScrImportSet FindOrCreateDefaultImportSettings(TypeOfImport importType, string defaultParaCharsStyleName, string stylesPath);
/// ------------------------------------------------------------------------------------
///
diff --git a/Src/FDO/FdoInterfaceDeclarations.cs b/Src/FDO/FdoInterfaceDeclarations.cs
index ddee48c781..30626a7e0e 100644
--- a/Src/FDO/FdoInterfaceDeclarations.cs
+++ b/Src/FDO/FdoInterfaceDeclarations.cs
@@ -7,7 +7,6 @@
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.Infrastructure;
-using SIL.FieldWorks.Common.FwUtils;
// Add additional methods/properties to domain object in FdoInterfaceAdditions.cs.
// Add new interfaces to the FdoInterfaceDeclarations file.
diff --git a/Src/FDO/FdoNewerVersionException.cs b/Src/FDO/FdoNewerVersionException.cs
new file mode 100644
index 0000000000..6992ba990f
--- /dev/null
+++ b/Src/FDO/FdoNewerVersionException.cs
@@ -0,0 +1,21 @@
+// Copyright (c) 2013-2014 SIL International
+// This software is licensed under the LGPL, version 2.1 or later
+// (http://www.gnu.org/licenses/lgpl-2.1.html)
+
+using SIL.CoreImpl;
+
+namespace SIL.FieldWorks.FDO
+{
+ ///
+ /// Exception thrown when we try to open a project that belongs to a newer version of FieldWorks than this.
+ ///
+ public class FdoNewerVersionException : StartupException
+ {
+ ///
+ /// Make one.
+ ///
+ public FdoNewerVersionException(string message) : base(message)
+ {
+ }
+ }
+}
\ No newline at end of file
diff --git a/Src/FDO/FdoRepositoryInterfaceAdditions.cs b/Src/FDO/FdoRepositoryInterfaceAdditions.cs
index fcc396b14a..9808695c06 100644
--- a/Src/FDO/FdoRepositoryInterfaceAdditions.cs
+++ b/Src/FDO/FdoRepositoryInterfaceAdditions.cs
@@ -12,10 +12,10 @@
using System;
using System.Collections.Generic;
-using System.Windows.Forms;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.DomainServices.SemanticDomainSearch;
+using SIL.Utils;
namespace SIL.FieldWorks.FDO
{
@@ -417,7 +417,7 @@ public partial interface ILexEntryRepository
///
/// Clear the list of homograph information
///
- void ResetHomographs(ProgressBar progressBar);
+ void ResetHomographs(IProgress progressBar);
///
/// Return a list of all the homographs of the specified form.
@@ -435,6 +435,26 @@ public partial interface ILexEntryRepository
/// entries to see whether they are homographs.
///
int HomographMorphOrder(FdoCache cache, IMoMorphType morphType);
+
+ ///
+ /// Find the list of LexEntry objects which conceivably match the given wordform.
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ List FindEntriesForWordform(FdoCache cache, ITsString tssWf, IWfiAnalysis wfa, ref bool duplicates);
+
+ /// ------------------------------------------------------------------------------------
+ ///
+ /// Find wordform given a cache and the string.
+ ///
+ ///
+ ///
+ ///
+ /// ------------------------------------------------------------------------------------
+ ILexEntry FindEntryForWordform(FdoCache cache, ITsString tssWf);
}
internal interface ILexEntryRepositoryInternal
@@ -643,4 +663,12 @@ public partial interface IScrBookAnnotationsRepository
/// The annotations for the requested book
IScrBookAnnotations InstanceForBook(int bookId);
}
+
+ public partial interface ITextTagRepository
+ {
+ ///
+ /// Gets all text tags that reference the specified text markup tag.
+ ///
+ IEnumerable GetByTextMarkupTag(ICmPossibility tag);
+ }
}
diff --git a/Src/FDO/FieldDescription.cs b/Src/FDO/FieldDescription.cs
index d28ed06d76..b23e327049 100644
--- a/Src/FDO/FieldDescription.cs
+++ b/Src/FDO/FieldDescription.cs
@@ -16,7 +16,6 @@
using System.Reflection;
using System.Collections;
using SIL.FieldWorks.FDO.DomainImpl;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
namespace SIL.FieldWorks.FDO
diff --git a/Src/FDO/IFdoDirectories.cs b/Src/FDO/IFdoDirectories.cs
new file mode 100644
index 0000000000..d341680f3f
--- /dev/null
+++ b/Src/FDO/IFdoDirectories.cs
@@ -0,0 +1,18 @@
+namespace SIL.FieldWorks.FDO
+{
+ ///
+ /// This interface is used by FDO to retrieve directories that it needs.
+ ///
+ public interface IFdoDirectories
+ {
+ ///
+ /// Gets the projects directory.
+ ///
+ string ProjectsDirectory { get; }
+
+ ///
+ /// Gets the template directory.
+ ///
+ string TemplateDirectory { get; }
+ }
+}
diff --git a/Src/FDO/IFdoUI.cs b/Src/FDO/IFdoUI.cs
new file mode 100644
index 0000000000..d4f499ec42
--- /dev/null
+++ b/Src/FDO/IFdoUI.cs
@@ -0,0 +1,157 @@
+// Copyright (c) 2013-2014 SIL International
+// This software is licensed under the LGPL, version 2.1 or later
+// (http://www.gnu.org/licenses/lgpl-2.1.html)
+
+using System;
+using System.ComponentModel;
+
+namespace SIL.FieldWorks.FDO
+{
+ ///
+ /// This interface abstracts the UI from FDO.
+ ///
+ public interface IFdoUI
+ {
+ ///
+ /// Gets the object that is used to invoke methods on the main UI thread.
+ ///
+ ISynchronizeInvoke SynchronizeInvoke { get; }
+
+ ///
+ /// Check with user regarding conflicting changes
+ ///
+ /// True if user wishes to revert to saved state. False otherwise.
+ bool ConflictingSave();
+
+ ///
+ /// Inform the user of a lost connection
+ ///
+ /// True if user wishes to attempt reconnect. False otherwise.
+ bool ConnectionLost();
+
+ ///
+ /// Gets the last time that there was user activity.
+ ///
+ DateTime LastActivityTime { get; }
+
+ ///
+ /// Check with user regarding which files to use
+ ///
+ ///
+ FileSelection ChooseFilesToUse();
+
+ ///
+ /// Check with user regarding restoring linked files in the project folder or original path
+ ///
+ /// True if user wishes to restore linked files in project folder. False to leave them in the original location.
+ bool RestoreLinkedFilesInProjectFolder();
+
+ ///
+ /// Cannot restore linked files to original path.
+ /// Check with user regarding restoring linked files in the project folder or not at all
+ ///
+ /// OkYes to restore to project folder, OkNo to skip restoring linked files, Cancel otherwise
+ YesNoCancel CannotRestoreLinkedFilesToOriginalLocation();
+
+ ///
+ /// Displays information to the user
+ ///
+ void DisplayMessage(MessageType type, string message, string caption, string helpTopic);
+
+ ///
+ /// Show a dialog or output to the error log, as appropriate.
+ ///
+ /// the exception you want to report
+ /// set to true if the error is lethal, otherwise
+ /// false.
+ void ReportException(Exception error, bool isLethal);
+
+ ///
+ /// Reports duplicate guids to the user
+ ///
+ /// The error text.
+ void ReportDuplicateGuids(string errorText);
+
+ ///
+ /// Present a message to the user and allow the options to Retry or Cancel
+ ///
+ /// The message.
+ /// The caption.
+ /// True to retry. False otherwise
+ bool Retry(string msg, string caption);
+
+ ///
+ /// Ask user if they wish to restore an XML project from a backup project file.
+ ///
+ /// The project path.
+ /// The backup path.
+ ///
+ bool OfferToRestore(string projectPath, string backupPath);
+
+ ///
+ /// Exits the application.
+ ///
+ void Exit();
+ }
+
+ ///
+ /// Message type
+ ///
+ public enum MessageType
+ {
+ ///
+ /// Information message
+ ///
+ Info,
+ ///
+ /// Warning message
+ ///
+ Warning,
+ ///
+ /// Error message
+ ///
+ Error
+ }
+
+ ///
+ /// File selection enum
+ ///
+ public enum FileSelection
+ {
+ ///
+ /// OK - Keep new files
+ ///
+ OkKeepNewer,
+
+ ///
+ /// OK - Use older files
+ ///
+ OkUseOlder,
+
+ ///
+ /// Cancel
+ ///
+ Cancel
+ }
+
+ ///
+ /// Yes No Cancel enum
+ ///
+ public enum YesNoCancel
+ {
+ ///
+ /// Ok - Yes
+ ///
+ OkYes,
+
+ ///
+ /// Ok - No
+ ///
+ OkNo,
+
+ ///
+ /// Cancel
+ ///
+ Cancel
+ }
+}
diff --git a/Src/FDO/IOC/FdoServiceLocatorFactory.cs b/Src/FDO/IOC/FdoServiceLocatorFactory.cs
index 6f659be17d..a713d613cd 100644
--- a/Src/FDO/IOC/FdoServiceLocatorFactory.cs
+++ b/Src/FDO/IOC/FdoServiceLocatorFactory.cs
@@ -14,7 +14,6 @@
using Microsoft.Practices.ServiceLocation;
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Application;
using SIL.FieldWorks.FDO.Application.Impl;
using SIL.FieldWorks.FDO.DomainImpl;
@@ -22,6 +21,7 @@
using SIL.FieldWorks.FDO.Infrastructure;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
+using SIL.Utils;
using StructureMap;
using StructureMap.Configuration.DSL;
using StructureMap.Pipeline;
@@ -36,16 +36,20 @@ namespace SIL.FieldWorks.FDO.IOC
internal sealed partial class FdoServiceLocatorFactory : IServiceLocatorBootstrapper
{
private readonly FDOBackendProviderType m_backendProviderType;
+ private readonly IFdoUI m_ui;
+ private readonly IFdoDirectories m_dirs;
- /// ------------------------------------------------------------------------------------
///
/// Constructor
///
/// Type of backend provider to create.
- /// ------------------------------------------------------------------------------------
- internal FdoServiceLocatorFactory(FDOBackendProviderType backendProviderType)
+ /// The UI service.
+ /// The directories service.
+ internal FdoServiceLocatorFactory(FDOBackendProviderType backendProviderType, IFdoUI ui, IFdoDirectories dirs)
{
m_backendProviderType = backendProviderType;
+ m_ui = ui;
+ m_dirs = dirs;
}
#region Implementation of IServiceLocatorBootstrapper
@@ -171,6 +175,12 @@ public IServiceLocator CreateServiceLocator()
.LifecycleIs(new SingletonLifecycle())
.Use();
break;
+ case FDOBackendProviderType.kSharedXML:
+ registry
+ .For()
+ .LifecycleIs(new SingletonLifecycle())
+ .Use();
+ break;
}
// Register two additional interfaces of the BEP, which are injected into other services.
registry
@@ -233,7 +243,7 @@ public IServiceLocator CreateServiceLocator()
registry
.For()
.LifecycleIs(new SingletonLifecycle())
- .Use(() => FwUtils.CreateWritingSystemManager());
+ .Use(() => new PalasoWritingSystemManager {TemplateFolder = m_dirs.TemplateDirectory});
registry
.For()
.Use(c => (ILgWritingSystemFactory)c.GetInstance());
@@ -242,6 +252,14 @@ public IServiceLocator CreateServiceLocator()
.For()
.Use(c => c.GetInstance().Singleton);
+ registry
+ .For()
+ .Use(m_ui);
+
+ registry
+ .For()
+ .Use(m_dirs);
+
// =================================================================================
// Don't add COM object to the registry. StructureMap does not properly release COM
// objects when the container is disposed, it will crash when the container is
diff --git a/Src/Common/FwUtils/IProjectIdentifier.cs b/Src/FDO/IProjectIdentifier.cs
similarity index 92%
rename from Src/Common/FwUtils/IProjectIdentifier.cs
rename to Src/FDO/IProjectIdentifier.cs
index ee56f649b7..a7be4d70bb 100644
--- a/Src/Common/FwUtils/IProjectIdentifier.cs
+++ b/Src/FDO/IProjectIdentifier.cs
@@ -7,7 +7,7 @@
using System;
-namespace SIL.FieldWorks.Common.FwUtils
+namespace SIL.FieldWorks.FDO
{
#region FDOBackendProviderType enum
///
@@ -84,6 +84,19 @@ public enum FDOBackendProviderType
///
/// db4oClientServer
kDb4oClientServer = 103,
+
+ ///
+ /// A FieldWorks XML file that can be accessed by multiple local clients.
+ ///
+ kSharedXML = 104,
+
+ ///
+ /// A FieldWorks XML file that can be accessed by multiple local clients.
+ /// This has an actual backend data store on the hard drive, but does not use a real
+ /// repository of writing systems. There is probably no legitimate reason to use this
+ /// except for testing the shared XML BEP.
+ ///
+ kSharedXMLWithMemoryOnlyWsMgr = 105
};
#endregion
diff --git a/Src/FDO/IStylesheet.cs b/Src/FDO/IStylesheet.cs
index 3f49bae814..0cadde32b0 100644
--- a/Src/FDO/IStylesheet.cs
+++ b/Src/FDO/IStylesheet.cs
@@ -1,8 +1,5 @@
using System;
-using System.Collections.Generic;
using System.Drawing;
-using System.Linq;
-using System.Text;
using SIL.FieldWorks.Common.COMInterfaces;
using SIL.FieldWorks.FDO.DomainServices;
diff --git a/Src/FDO/Infrastructure/BackendStartupParameter.cs b/Src/FDO/Infrastructure/BackendStartupParameter.cs
index 481a175a9b..fe515de7c8 100644
--- a/Src/FDO/Infrastructure/BackendStartupParameter.cs
+++ b/Src/FDO/Infrastructure/BackendStartupParameter.cs
@@ -1,5 +1,3 @@
-using SIL.FieldWorks.Common.FwUtils;
-
namespace SIL.FieldWorks.FDO.Infrastructure
{
///
diff --git a/Src/FDO/Infrastructure/IPersistenceStrategyInterfaces.cs b/Src/FDO/Infrastructure/IPersistenceStrategyInterfaces.cs
index 0d604ccfb2..80184bd6f9 100644
--- a/Src/FDO/Infrastructure/IPersistenceStrategyInterfaces.cs
+++ b/Src/FDO/Infrastructure/IPersistenceStrategyInterfaces.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using SIL.Utils;
-using SIL.FieldWorks.Common.FwUtils;
namespace SIL.FieldWorks.FDO.Infrastructure
{
@@ -43,7 +42,8 @@ public interface IDataSetup : IFWDisposable
/// True to bootstrap the existing system, false to skip that
/// step
/// The progress dialog box
- void StartupExtantLanguageProject(IProjectIdentifier projectId, bool fBootstrapSystem, IThreadedProgress progressDlg);
+ /// True if the application forbids data migration
+ void StartupExtantLanguageProject(IProjectIdentifier projectId, bool fBootstrapSystem, IThreadedProgress progressDlg, bool forbidDataMigration);
///
/// Create a new LanguageProject for the BEP with the given parameters.
@@ -261,19 +261,6 @@ internal interface IDataStorer : IFWDisposable
///
internal interface IClientServerDataManager
{
- ///
- /// Get any changes we haven't previously seen which other clients have made to our database.
- ///
- /// New objects created on the other client
- /// Object we know about modified on the other client.
- /// objects we know about deleted by the other client.
- /// if true, we intend to Commit; if there are no conflicts, lock
- /// until commit. (If there are conflicts, we don't lock till we reconciled.)
- /// true if there are any foreign changes
- bool GetUnseenForeignChanges(out List foreignNewbies,
- out List foreignDirtballs,
- out List foreignGoners, bool fGetCommitLock);
-
///
/// Return a string (typically at or near shutdown) which may be passed back to NewObjectsSinceVersion.
///
diff --git a/Src/FDO/Infrastructure/IUnitOfWorkService.cs b/Src/FDO/Infrastructure/IUnitOfWorkService.cs
index 90ef6a7a10..a13b98ec18 100644
--- a/Src/FDO/Infrastructure/IUnitOfWorkService.cs
+++ b/Src/FDO/Infrastructure/IUnitOfWorkService.cs
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
+using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.Infrastructure.Impl;
namespace SIL.FieldWorks.FDO.Infrastructure
@@ -261,5 +261,21 @@ void RegisterVirtualAsModified(ICmObject dirtball, int modifiedFlid, int ws, ITs
///
void GatherChanges(HashSet newbies, HashSet dirtballs,
HashSet goners);
+
+ ///
+ /// Creates a change reconciler.
+ ///
+ /// The foreign newbies.
+ /// The foreign dirtballs.
+ /// The foreign goners.
+ ///
+ IReconcileChanges CreateReconciler(List foreignNewbies,
+ List foreignDirtballs, List foreignGoners);
+
+ ///
+ /// Notifies the service of conflicting changes.
+ ///
+ /// The pending reconciliation.
+ void ConflictingChanges(IReconcileChanges pendingReconciliation);
}
}
diff --git a/Src/FDO/Infrastructure/Impl/ChangeReconciler.cs b/Src/FDO/Infrastructure/Impl/ChangeReconciler.cs
index 181cfa8fd6..15303d20ad 100644
--- a/Src/FDO/Infrastructure/Impl/ChangeReconciler.cs
+++ b/Src/FDO/Infrastructure/Impl/ChangeReconciler.cs
@@ -5,7 +5,6 @@
using System.Xml.Linq;
using SIL.CoreImpl;
using SIL.FieldWorks.Common.COMInterfaces;
-using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.FDO.DomainImpl;
using SIL.Utils;
@@ -655,6 +654,16 @@ public void GatherChanges(HashSet newbies, HashSet foreignNewbies, List foreignDirtballs, List foreignGoners)
+ {
+ throw new NotImplementedException();
+ }
+
+ public void ConflictingChanges(IReconcileChanges pendingReconciliation)
+ {
+ throw new NotImplementedException();
+ }
}
///
diff --git a/Src/FDO/Infrastructure/Impl/ClientServerBackendProvider.cs b/Src/FDO/Infrastructure/Impl/ClientServerBackendProvider.cs
index ea6cfdfa66..bc1bfde669 100644
--- a/Src/FDO/Infrastructure/Impl/ClientServerBackendProvider.cs
+++ b/Src/FDO/Infrastructure/Impl/ClientServerBackendProvider.cs
@@ -9,7 +9,6 @@
/* This class may well replace ClientServerBackend, which currently is used only by the MySQL classes */
-using System.Collections.Generic;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
namespace SIL.FieldWorks.FDO.Infrastructure.Impl
@@ -20,17 +19,11 @@ protected ClientServerBackendProvider(FdoCache cache,
IdentityMap identityMap,
ICmObjectSurrogateFactory surrogateFactory,
IFwMetaDataCacheManagedInternal mdc,
- IDataMigrationManager dataMigrationManager) : base(cache, identityMap, surrogateFactory, mdc, dataMigrationManager)
+ IDataMigrationManager dataMigrationManager,
+ IFdoUI ui, IFdoDirectories dirs) : base(cache, identityMap, surrogateFactory, mdc, dataMigrationManager, ui, dirs)
{
}
- ///
- /// Get changes we haven't seen.
- ///
- public abstract bool GetUnseenForeignChanges(out List foreignNewbies,
- out List foreignDirtballs,
- out List foreignGoners, bool fGetCommitLock);
-
public abstract string VersionStamp { get; }
public abstract bool NewObjectsSinceVersion(string versionStamp, string classname);
}
diff --git a/Src/FDO/Infrastructure/Impl/CmObjectSurrogate.cs b/Src/FDO/Infrastructure/Impl/CmObjectSurrogate.cs
index c056303c89..a34b553f91 100644
--- a/Src/FDO/Infrastructure/Impl/CmObjectSurrogate.cs
+++ b/Src/FDO/Infrastructure/Impl/CmObjectSurrogate.cs
@@ -7,7 +7,6 @@
using System.Linq;
using System.Reflection;
using System.Text;
-using System.Windows.Forms;
using System.Xml.Linq;
using SIL.Utils;
using System.Threading;
@@ -548,11 +547,9 @@ ICmObject ICmObjectOrSurrogate.Object
const int nLines = 40;
if (lines.Length > nLines)
msg = String.Join("\n", lines.Take(nLines).ToArray()) + "\n...";
- m_cache.ThreadHelper.Invoke(() =>
- {
- MessageBox.Show(null, msg, Strings.ksErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
- ErrorReporter.ReportException(new Exception(fullMsg, e), null, null, null, true);
- });
+ var userAction = m_cache.ServiceLocator.GetInstance();
+ userAction.DisplayMessage(MessageType.Error, msg, Strings.ksErrorCaption, null);
+ userAction.ReportException(new Exception(fullMsg, e), true);
}
return m_object;
}
diff --git a/Src/FDO/Infrastructure/Impl/CommitLogMetadata.cs b/Src/FDO/Infrastructure/Impl/CommitLogMetadata.cs
new file mode 100644
index 0000000000..211e714aac
--- /dev/null
+++ b/Src/FDO/Infrastructure/Impl/CommitLogMetadata.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Collections.Generic;
+using ProtoBuf;
+
+namespace SIL.FieldWorks.FDO.Infrastructure.Impl
+{
+ ///
+ /// Contains all of the commit log metadata for the shared XML backend. This
+ /// class is serialized to a memory mapped file using protobuf-net.
+ ///
+ [ProtoContract]
+ internal class CommitLogMetadata
+ {
+ public CommitLogMetadata()
+ {
+ Peers = new Dictionary();
+ }
+
+ ///
+ /// The current commit generation of the commit log.
+ ///
+ [ProtoMember(1)]
+ public int CurrentGeneration;
+
+ ///
+ /// The current commit generation of the XML file.
+ ///
+ [ProtoMember(2)]
+ public int FileGeneration;
+
+ ///
+ /// The offset into the memory mapped file where the commit log starts.
+ ///
+ [ProtoMember(3)]
+ public int LogOffset;
+
+ ///
+ /// The length of the commit log. The length includes padding.
+ ///
+ [ProtoMember(4)]
+ public int LogLength;
+
+ ///
+ /// The amount of padding at the end of the memory mapped file if the commit log wraps
+ /// around the file.
+ ///
+ [ProtoMember(5)]
+ public int Padding;
+
+ ///
+ /// All of the peers that are currently accessing the XML file.
+ ///
+ [ProtoMember(6)]
+ public Dictionary Peers;
+
+ ///
+ /// The GUID of the master peer that is reponsible for reading and writing to the XML file.
+ ///
+ [ProtoMember(7)]
+ public Guid Master;
+ }
+
+ ///
+ /// A shared XML backend peer.
+ ///
+ [ProtoContract]
+ internal class CommitLogPeer
+ {
+ ///
+ /// The commit generation that the peer has seen.
+ ///
+ [ProtoMember(1)]
+ public int Generation;
+
+ ///
+ /// The peer's process ID.
+ ///
+ [ProtoMember(2)]
+ public int ProcessID;
+ }
+}
diff --git a/Src/FDO/Infrastructure/Impl/CommitLogRecord.cs b/Src/FDO/Infrastructure/Impl/CommitLogRecord.cs
new file mode 100644
index 0000000000..9095883e7c
--- /dev/null
+++ b/Src/FDO/Infrastructure/Impl/CommitLogRecord.cs
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using ProtoBuf;
+
+namespace SIL.FieldWorks.FDO.Infrastructure.Impl
+{
+ ///
+ /// A record that is used by the shared XML backend to record all information for a commit so that peers
+ /// can update their FDO instance appropriately. These records are serialized to the commit log memory
+ /// mapped file using protobuf-net.
+ ///
+ [ProtoContract]
+ internal struct CommitLogRecord
+ {
+ ///
+ /// Corresponds to WriteGeneration in CmObjectSurrogate. Orders all CommitData absolutely, since each
+ /// Commit gets a fresh WriteGeneration.
+ ///
+ [ProtoMember(1)]
+ public int WriteGeneration;
+
+ ///
+ /// A guid unique to one particular peer; used by each peer to eliminate its own commits from queries.
+ ///
+ [ProtoMember(2)]
+ public Guid Source;
+
+ ///
+ /// Our IDs of the objects that were added.
+ ///
+ [ProtoMember(3)]
+ public List ObjectsAdded;
+
+ ///
+ /// Our IDs of the objects that were modified.
+ ///
+ [ProtoMember(4)]
+ public List ObjectsUpdated;
+
+ ///
+ /// Our IDs of the objects that were deleted.
+ ///
+ [ProtoMember(5)]
+ public List ObjectsDeleted;
+ }
+}
diff --git a/Src/FDO/Infrastructure/Impl/Db4oClientServerBackendProvider.cs b/Src/FDO/Infrastructure/Impl/Db4oClientServerBackendProvider.cs
index c4b7cd5cae..f3d81fcdb3 100644
--- a/Src/FDO/Infrastructure/Impl/Db4oClientServerBackendProvider.cs
+++ b/Src/FDO/Infrastructure/Impl/Db4oClientServerBackendProvider.cs
@@ -16,7 +16,6 @@
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Threading;
-using System.Windows.Forms;
using Db4objects.Db4o;
using Db4objects.Db4o.Config;
using Db4objects.Db4o.Config.Encoding;
@@ -24,7 +23,7 @@
using Db4objects.Db4o.CS.Config;
using Db4objects.Db4o.Linq;
using FwRemoteDatabaseConnector;
-using SIL.FieldWorks.Common.FwUtils;
+using SIL.CoreImpl;
using SIL.FieldWorks.FDO.DomainServices;
using SIL.FieldWorks.FDO.DomainServices.DataMigration;
using SIL.Utils;
@@ -85,13 +84,17 @@ internal class Db4oClientServerBackendProvider : ClientServerBackendProvider
///