/// <summary> /// Opens the learning module (or schedules it for opening). /// </summary> /// <param name="configFilePath">The config file path.</param> /// <param name="LmId">The lm id.</param> /// <param name="LmName">Name of the lm.</param> /// <param name="UserId">The user id.</param> /// <param name="UserName">Name of the user.</param> /// <param name="UserPassword">The user password (needed for FormsAuthentication, else empty).</param> /// <remarks>Documented by Dev02, 2009-06-26</remarks> /// <exception cref="MLHasOpenFormsException">Occurs when settings or the learning module could not be changed because MemoryLifter has other forms/windows open.</exception> /// <exception cref="ConfigFileParseException">Occurs when the supplied config file could not be parsed properly or does not contain a valid connection.</exception> /// <exception cref="MLCouldNotBeStartedException">Occurs when MemoryLifter did not start or did not react to connection attempts.</exception> public void OpenLearningModule(string configFilePath, int LmId, string LmName, int UserId, string UserName, string UserPassword) { ConnectionStringHandler csHandler = new ConnectionStringHandler(configFilePath); if (csHandler.ConnectionStrings.Count < 1) throw new ConfigFileParseException(); Debug.WriteLine(string.Format("Config file parsed ({0}), building connection...", configFilePath)); IConnectionString connectionString = csHandler.ConnectionStrings[0]; ConnectionStringStruct css = new ConnectionStringStruct(); css.LmId = LmId; css.Typ = connectionString.ConnectionType; css.ConnectionString = connectionString.ConnectionString; if (connectionString is UncConnectionStringBuilder) { css.ConnectionString = Path.Combine(css.ConnectionString, LmName + Helper.EmbeddedDbExtension); css.Typ = DatabaseType.MsSqlCe; } if (connectionString is ISyncableConnectionString) { ISyncableConnectionString syncConnectionString = (ISyncableConnectionString)connectionString; css.LearningModuleFolder = syncConnectionString.MediaURI; css.ExtensionURI = syncConnectionString.ExtensionURI; css.SyncType = syncConnectionString.SyncType; } LearningModulesIndexEntry entry = new LearningModulesIndexEntry(css); entry.User = new DummyUser(UserId, UserName); ((DummyUser)entry.User).Password = UserPassword; entry.UserName = UserName; entry.UserId = UserId; entry.Connection = connectionString; entry.DisplayName = LmName; entry.SyncedPath = LmName + Helper.SyncedEmbeddedDbExtension; Debug.WriteLine("Opening learning module..."); try { loader.LoadDictionary(entry); } catch (MLifter.Classes.FormsOpenException) { throw new MLHasOpenFormsException(); } }
public void CSHConstructorTestNull() { string generalPath = null; string userPath = null; ConnectionStringHandler target = new ConnectionStringHandler(generalPath, userPath); Assert.IsTrue(target.ConnectionStrings.FindAll(c => !(c is UncConnectionStringBuilder) || !(c as UncConnectionStringBuilder).IsOnStick).Count == 0, "CSHConstructorTest - There should be 0 connection strings!"); }
public void UncStickCSBReadWriteTest() { List<DriveInfo> drives = Methods.GetMLifterSticks(); if (drives.Count < 1) Assert.Inconclusive("No Stick plugged in! To test the stick functionality please plug in a stick!"); string LMPath = Path.Combine(drives[0].RootDirectory.ToString(), "LearningModules"); UncConnectionStringBuilder stick = new UncConnectionStringBuilder(Path.Combine(drives[0].RootDirectory.ToString(), "LearningModules"), false, true); ConnectionStringHandler.CreateUncConnection("StickTest", LMPath, drives[0].RootDirectory.ToString(), "defaultConnection.mlcfg", false, true); // test that the file was generated with the proper placeholder StreamReader sreader = new StreamReader(drives[0].RootDirectory.ToString() + "defaultConnection.mlcfg"); Assert.AreNotEqual(-1, sreader.ReadToEnd().IndexOf("MEMSTICK:\\"), "MEMSTICK identifier not found"); sreader.Close(); // test that reading the file translates to the proper drive letter ConnectionStringHandler handler = new ConnectionStringHandler(drives[0].RootDirectory.ToString(), string.Empty); IConnectionString connection = handler.ConnectionStrings.Find(c => c.Name == "StickTest"); Assert.IsNotNull(connection, "MEMSTICK config file not generated"); Assert.AreEqual<string>(drives[0].RootDirectory.ToString() + "defaultConnection.mlcfg", connection.ConfigFileName); File.Delete(Path.Combine(drives[0].RootDirectory.ToString(), "defaultConnection.mlcfg")); }
/// <summary> /// GUI logic for Drag and Drop /// </summary> /// <param name="file">The file.</param> /// <remarks>Documented by Dev08, 2009-03-02</remarks> public void DoDragAndDrop(string file) { bool draggedLearningModuleIsOpen = false; string appConfigFile = Setup.GlobalConfigPath; string usrConfigFile = Setup.UserConfigPath; ConnectionStringHandler handler = new ConnectionStringHandler(appConfigFile, usrConfigFile); IConnectionString defaultConString = handler.ConnectionStrings.Find(c => c.IsDefault || c.ConnectionType == DatabaseType.Unc); TaskDialogResult result; //No default connection available if (defaultConString == null) { TaskDialog.MessageBox(Resources.DRAG_NO_DEFAULT_CONNECTION_AVAILABLE_TITLE, Resources.DRAG_NO_DEFAULT_CONNECTION_AVAILABLE_MAININTRODUCTION, Resources.DRAG_NO_DEFAULT_CONNECTION_AVAILABLE_CONTENT, TaskDialogButtons.OK, TaskDialogIcons.Error); return; } //User draged a LM from a available UNC connection to the ML else if (ConnectionStringHandler.IsFileInUncConnection(file, appConfigFile, usrConfigFile)) //(Path.GetDirectoryName(file) == defaultConString.ConnectionString) { OpenLearningModule(file); return; } //File already exists else if (File.Exists(Path.Combine(defaultConString.ConnectionString, Path.GetFileName(file)))) { //User draged the LM which is currently opened into MemoryLifter. (only possible while user is learning) //[Check if the future place of the LM is currently opened (e.g. the older LM is open)] if (LearnLogic != null && LearnLogic.CurrentLearningModule != null && LearnLogic.CurrentLearningModule.ConnectionString.ConnectionString == Path.Combine(defaultConString.ConnectionString, Path.GetFileName(file))) draggedLearningModuleIsOpen = true; TaskDialogResult resultFileExists = ShowFileExistsDragAndDropDialog(); switch (resultFileExists.CommandButtonsIndex) { // Replace case 0: if (draggedLearningModuleIsOpen) { if (!LearnLogic.CloseLearningModule()) return; } try { ConnectionStringHandler.PutLearningModuleToDefaultUNC(file, defaultConString.ConnectionString, false, true); } catch (Exception exc) { TaskDialog.MessageBox(Resources.DRAG_COPY_ERROR_TITLE, Resources.DRAG_COPY_ERROR_MAININTRODUCTION, exc.Message, exc.ToString(), string.Empty, string.Empty, TaskDialogButtons.OK, TaskDialogIcons.Error, TaskDialogIcons.Error); } OpenLearningModule(Path.Combine(defaultConString.ConnectionString, Path.GetFileName(file))); break; //Just learn case 1: OpenLearningModule(file); break; //Cancel case 2: default: break; } return; } else if (Path.GetExtension(file) == Helper.DzpExtension) result = new TaskDialogResult() { CommandButtonsIndex = 2, VerificationChecked = false }; else result = ShowDefaultDragAndDropDialog(); //User draged the LM which is currently opened into MemoryLifter. (only possible while user is learning) //[Check if currently ] if (LearnLogic != null && LearnLogic.CurrentLearningModule != null && LearnLogic.CurrentLearningModule.ConnectionString.ConnectionString == file) draggedLearningModuleIsOpen = true; switch (result.CommandButtonsIndex) { //Copy case 0: try { ConnectionStringHandler.PutLearningModuleToDefaultUNC(file, defaultConString.ConnectionString, false); } catch (Exception exc) { TaskDialog.MessageBox(Resources.DRAG_COPY_ERROR_TITLE, Resources.DRAG_COPY_ERROR_MAININTRODUCTION, exc.Message, exc.ToString(), string.Empty, string.Empty, TaskDialogButtons.OK, TaskDialogIcons.Error, TaskDialogIcons.Error); } OpenLearningModule(Path.Combine(defaultConString.ConnectionString, Path.GetFileName(file))); break; //Move case 1: if (draggedLearningModuleIsOpen) { if (!LearnLogic.CloseLearningModule()) return; } try { ConnectionStringHandler.PutLearningModuleToDefaultUNC(file, defaultConString.ConnectionString, true); } catch (Exception exc) { TaskDialog.MessageBox(Resources.DRAG_COPY_ERROR_TITLE, Resources.DRAG_COPY_ERROR_MAININTRODUCTION, exc.Message, exc.ToString(), string.Empty, string.Empty, TaskDialogButtons.OK, TaskDialogIcons.Error, TaskDialogIcons.Error); } OpenLearningModule(Path.Combine(defaultConString.ConnectionString, Path.GetFileName(file))); break; //Just open case 2: OpenLearningModule(file); break; //Cancel case 3: default: break; } }
public void CSHConstructorTest() { Dictionary<string, string> referenceValues1, referenceValues2, referenceValues3, referenceValues4, referenceValues5, referenceValues6; string generalPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); string userPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(generalPath); Directory.CreateDirectory(userPath); ConnectionStringHandler.CreateUncConnection(PrepareUncConnectionStringBuilder(out referenceValues1), generalPath, "unc1.mlcfg"); ConnectionStringHandler.CreateUncConnection(PrepareUncConnectionStringBuilder(out referenceValues2), generalPath, "unc2.mlcfg"); ConnectionStringHandler.CreatePostgreSqlConnection(PreparePostgreSqlConnectionStringBuilder(out referenceValues3), generalPath, "pg1.mlcfg"); ConnectionStringHandler.CreateUncConnection(PrepareUncConnectionStringBuilder(out referenceValues4), userPath, "unc1.mlcfg"); ConnectionStringHandler.CreatePostgreSqlConnection(PreparePostgreSqlConnectionStringBuilder(out referenceValues5), userPath, "pg1.mlcfg"); ConnectionStringHandler.CreatePostgreSqlConnection(PreparePostgreSqlConnectionStringBuilder(out referenceValues6), userPath, "pg2.mlcfg"); ConnectionStringHandler target = new ConnectionStringHandler(generalPath, userPath); Assert.IsTrue(target.ConnectionStrings.FindAll(c => !(c is UncConnectionStringBuilder) || !(c as UncConnectionStringBuilder).IsOnStick).Count == 2, "CSHConstructorTest - There should be 6 connection strings!"); foreach (IConnectionString csb in target.ConnectionStrings.FindAll(c => !(c is UncConnectionStringBuilder) || !(c as UncConnectionStringBuilder).IsOnStick)) { if (csb.ConnectionType == MLifter.DAL.DatabaseType.PostgreSQL) { Assert.AreEqual<MLifter.DAL.DatabaseType>(MLifter.DAL.DatabaseType.PostgreSQL, csb.ConnectionType, "CSHPostgreSqlConnectionStringBuilderTest - ConnectionType is not correct!"); Assert.AreEqual<string>(referenceValues3["Name"], csb.Name, "CSHPostgreSqlConnectionStringBuilderTest - Name is not correct!"); } else { Assert.AreEqual<MLifter.DAL.DatabaseType>(MLifter.DAL.DatabaseType.Unc, csb.ConnectionType, "CSHUncConnectionStringBuilderTest - ConnectionType is not correct!"); Assert.AreEqual<string>(referenceValues1["Name"], csb.Name, "CSHUncConnectionStringBuilderTest - Name is not correct!"); Assert.AreEqual<string>(referenceValues1["ConnectionString"], csb.ConnectionString, "CSHUncConnectionStringBuilderTest - ConnectionString is not correct!"); } } Directory.Delete(generalPath, true); Directory.Delete(userPath, true); }
/// <summary> /// Saves the given connection string to the configPath. If the conString.Name doesn't exists, a new connection will be created. /// If the conString.Name exists it will be updated. /// </summary> /// <param name="configPath">The config path (e.g. %ProgramFiles%\MemoryLifter\Config).</param> /// <param name="conString">The ConnectionString. ATTENTION: conString.ConfigFileName must be a valid FileName!!!</param> /// <param name="identifier">The identifier.</param> /// <exception cref="T:System.IO.IOException" /> /// <remarks>Documented by Dev08, 2009-04-01</remarks> public static void SaveConnectionString(string configPath, IConnectionString conString, ConnectionStringIdentifier identifier) { //todo: get all connections from the configPath //todo: search for the connectionString based on the identifier //todo: update/create the new connection //1. Get all connections ConnectionStringHandler handler = new ConnectionStringHandler(configPath, string.Empty, false); //2. Check if the given connection is already available (search based on identifier) bool connectionStringLocated = false; foreach (IConnectionString cs in handler.ConnectionStrings) { if (identifier == ConnectionStringIdentifier.IdentifyByConnectionStringAndType) { if (cs.ConnectionString == conString.ConnectionString && cs.ConnectionType == conString.ConnectionType) { conString.ConfigFileName = cs.ConfigFileName; connectionStringLocated = true; break; } } else { if (cs.Name == conString.Name) { conString.ConfigFileName = cs.ConfigFileName; connectionStringLocated = true; break; } } } //3.1 Update connectionstring if (!Directory.Exists(Path.GetDirectoryName(conString.ConfigFileName))) throw new IOException("The given connectionString does not have a valid value in ConfigFileName property."); if (connectionStringLocated) { XmlDocument doc = new XmlDocument(); doc.Load(File.OpenWrite(conString.ConfigFileName)); foreach (XmlNode item in doc.GetElementsByTagName("Connections")) { foreach (XmlNode subItem in item.ChildNodes) { } } } else //3.2 Create new connection; Should not happen, because the startupWiz always creates a connection { List<IConnectionString> list = new List<IConnectionString>(); list.Add(conString); CreateConnections(list, conString.ConfigFileName); } }
/// <summary> /// Checks if the given filename is in one of the available UNC connections /// </summary> /// <param name="filename">The filename.</param> /// <returns> /// <c>true</c> if [is file in unc connection] [the specified filename]; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev08, 2009-03-03</remarks> public static bool IsFileInUncConnection(string filename, string generalPath, string userPath) { ConnectionStringHandler handler = new ConnectionStringHandler(generalPath, userPath); foreach (IConnectionString conString in handler.ConnectionStrings) { if (conString.ConnectionType != DatabaseType.Unc) continue; if (Path.GetDirectoryName(filename).StartsWith(conString.ConnectionString)) return true; } return false; }
/// <summary> /// Imports the mlcfg-file. /// </summary> /// <param name="filepath">The filepath.</param> /// <param name="generalPath">The general path.</param> /// <param name="userPath">The user path.</param> /// <returns>The number of successfully imported/updated connections</returns> /// <remarks>Documented by Dev08, 2009-03-02</remarks> public static int ImportConfigFile(string filepath, string generalPath, string userPath) { ConnectionStringHandler currentHandler = new ConnectionStringHandler(generalPath, userPath); List<IConnectionString> fromNewFileConnectionStrings; List<IConnectionString> importConnectionList = new List<IConnectionString>(); List<ModuleFeedConnection> feedsInFile; List<ModuleFeedConnection> importFeeds = new List<ModuleFeedConnection>(); try { fromNewFileConnectionStrings = GetConnectionStringsFromFile(filepath); feedsInFile = GetFeedsFromFile(filepath); } catch { throw new InvalidConfigFileException(); } if (fromNewFileConnectionStrings.Count + feedsInFile.Count == 0) return 0; //Compare and write new connections to importConnectionList foreach (IConnectionString newConString in fromNewFileConnectionStrings) { bool isEqual = false; foreach (IConnectionString oldConString in currentHandler.ConnectionStrings) isEqual = newConString.ConnectionString == oldConString.ConnectionString && newConString.ConnectionType == oldConString.ConnectionType; if (!isEqual) importConnectionList.Add(newConString); } //compare and write new feeds to importFeeds foreach (ModuleFeedConnection feed in feedsInFile) { bool isEqual = false; foreach (ModuleFeedConnection oldFeed in currentHandler.Feeds) isEqual = oldFeed.ModulesUri == feed.ModulesUri && oldFeed.CategoriesUri == feed.CategoriesUri; if (!isEqual) importFeeds.Add(feed); } if (importConnectionList.Count + importFeeds.Count == 0) return 0; //Search for a config file with the same filename... int loopKillCounter = 1; string newConfigFile = Path.Combine(userPath, Path.GetFileName(filepath)); while (File.Exists(newConfigFile) && loopKillCounter <= 10000) { newConfigFile = Path.Combine(Path.GetDirectoryName(newConfigFile), Path.GetFileNameWithoutExtension(newConfigFile) + "_" + loopKillCounter.ToString() + Path.GetExtension(newConfigFile)); ++loopKillCounter; } return CreateConnections(importConnectionList, newConfigFile, importFeeds); }
/// <summary> /// Gets the default connection string. If there are more than one default conStrings (which isn't allowed), this methods returns the first /// located default connection. If there is no default connection string, it returns null. /// </summary> /// <param name="configPath">The config path (e.g. %ProgramFiles%\MemoryLifter\Config).</param> /// <returns>The default connection string if there is one, otherwise null</returns> /// <remarks>Documented by Dev08, 2009-04-01</remarks> public static IConnectionString GetDefaultConnectionString(string configPath) { ConnectionStringHandler csh = new ConnectionStringHandler(configPath, string.Empty, false); foreach (IConnectionString conString in csh.ConnectionStrings) { if (conString.IsDefault) return conString; } return null; }
/// <summary> /// Initializes a new instance of the <see cref="LearningModulesIndex"/> class. /// </summary> /// <param name="generalPath">The general path.</param> /// <param name="userPath">The path to the user configurations.</param> /// <param name="getLoginDelegate">The get login delegate.</param> /// <param name="dataAccessErrorDelegate">The data access error delegate.</param> /// <remarks>Documented by Dev05, 2008-12-03</remarks> public LearningModulesIndex(string generalPath, string userPath, GetLoginInformation getLoginDelegate, DataAccessErrorDelegate dataAccessErrorDelegate, string syncedModulesPath) : this() { SyncedModulesPath = syncedModulesPath; getLogin = getLoginDelegate; dataAccessError = dataAccessErrorDelegate; updateTimer.Interval = 1000; updateTimer.Tick += new EventHandler(updateTimer_Tick); if (userPath != null && userPath != string.Empty) { cacheFile = System.IO.Path.Combine(userPath, Properties.Settings.Default.LMIndexCacheFilename); try { if (System.IO.File.Exists(cacheFile)) RestoreIndexCache(cacheFile); } catch (Exception e) { Trace.WriteLine("Index entry cache restore failed: " + e.ToString()); } } ConnectionsHandler = new ConnectionStringHandler(generalPath, userPath); ConnectionUsers.Clear(); foreach (IConnectionString con in ConnectionsHandler.ConnectionStrings) { ListViewGroup group = new ListViewGroup(con.Name); group.Tag = con; Groups.Add(group); } }