/// <summary> /// Loads the detailed information for an index entry. /// </summary> /// <param name="entry">The learning module entry.</param> /// <remarks>Documented by Dev03, 2008-12-03</remarks> private static void LoadIndexEntry(LearningModulesIndexEntry entry) { try { if (entry.Dictionary is PreviewDictionary) { entry.Dictionary = DAL.User.UpdatePreviewDictionary(entry.Dictionary as PreviewDictionary); } entry.DisplayName = entry.Dictionary.Title; entry.Description = entry.Dictionary.Description; entry.Author = entry.Dictionary.Author; entry.Category = entry.Dictionary.Category; entry.Count = entry.Dictionary.Cards.Count; entry.Size = entry.Dictionary.DictionarySize; Settings settings = new Settings(entry.Dictionary); IMedia logo = settings.Logo as IImage; if (logo != null) { entry.Logo = (Image)Bitmap.FromStream(logo.Stream).Clone(); } if (entry.Dictionary.Statistics.Count > 0) { entry.LastTimeLearned = entry.Dictionary.Statistics[entry.Dictionary.Statistics.Count - 1].StartTimestamp; } } catch (Exception ex) { Debug.WriteLine("LoadIndexEntry - " + ex.Message); } }
/// <summary> /// Gets the statistics for an index entry. /// </summary> /// <param name="entry">The learning module index entry.</param> /// <remarks>Documented by Dev03, 2008-12-04</remarks> private static void GetStatistics(LearningModulesIndexEntry entry) { LearningModuleStatistics lms = new LearningModuleStatistics(); entry.Statistics = lms; try { if (entry.Dictionary.Statistics.Count > 0) { for (int i = (entry.Dictionary.Statistics.Count - 1); i >= 0; i--) { IStatistic stat = entry.Dictionary.Statistics[i]; if ((stat.Right + stat.Wrong) > 0) { lms.CardsAsked = stat.Right + stat.Wrong; lms.LastSessionTime = stat.EndTimestamp - stat.StartTimestamp; lms.LastEndTime = stat.EndTimestamp; lms.LastStartTime = stat.StartTimestamp; lms.Right = stat.Right; lms.Wrong = stat.Wrong; break; } } } } catch (Exception ex) { Debug.WriteLine("LearningModulesIndex.GetStatistics() - " + ex.Message); } }
/// <summary> /// Initializes a new instance of the <see cref="RecentLearningModulesTest"/> class. /// </summary> /// <remarks>Documented by Dev07, 2009-03-03</remarks> public OfflineModulesTest() { tempFolder = Path.Combine(Path.GetTempPath(), "ML_Temp"); Directory.CreateDirectory(tempFolder); File.Create(Path.Combine(tempFolder, "lm1.mlm")); File.Create(Path.Combine(tempFolder, "lm2.mlm")); lm1 = new LearningModulesIndexEntry(); lm2 = new LearningModulesIndexEntry(); ConnectionStringStruct css1 = new ConnectionStringStruct(); css1.ConnectionString = Path.Combine(tempFolder, "lm1.mlm"); css1.Typ = MLifter.DAL.DatabaseType.MsSqlCe; css1.LmId = 1; ConnectionStringStruct css2 = new ConnectionStringStruct(); css2.ConnectionString = Path.Combine(tempFolder, "lm2.mlm"); css2.Typ = MLifter.DAL.DatabaseType.MsSqlCe; css2.LmId = 2; IConnectionString con = new UncConnectionStringBuilder(tempFolder); lm1.DisplayName = "learnmodule1"; lm1.ConnectionName = "connectionname1"; lm1.Connection = con; lm1.ConnectionString = css1; lm1.SyncedPath = css1.ConnectionString; lm2.DisplayName = "learnmodule2"; lm2.ConnectionName = "connectionname2"; lm2.Connection = con; lm2.ConnectionString = css2; lm2.SyncedPath = css2.ConnectionString; }
/// <summary> /// Serializes the index cache. /// </summary> /// <param name="stream">The stream.</param> /// <remarks>Documented by Dev02, 2008-12-04</remarks> private void SerializeIndexCache(Stream stream) { //cache for passwords - they must not be saved in the disk cache Dictionary <string, string> passwords = new Dictionary <string, string>(); foreach (KeyValuePair <string, LearningModulesIndexEntry> pair in indexCache) { if (pair.Value.ConnectionString.Password != string.Empty) { passwords.Add(pair.Key, pair.Value.ConnectionString.Password); ConnectionStringStruct css = pair.Value.ConnectionString; css.Password = string.Empty; pair.Value.ConnectionString = css; } } IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, indexCacheTimestamps); formatter.Serialize(stream, indexCache); foreach (KeyValuePair <string, string> pair in passwords) { LearningModulesIndexEntry entry = indexCache[pair.Key]; ConnectionStringStruct css = entry.ConnectionString; css.Password = pair.Value; entry.ConnectionString = css; } }
/// <summary> /// Refreshes the cache item. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev02, 2008-12-11</remarks> public void RefreshCacheItem(LearningModulesIndexEntry entry) { if (entry.IsVerified) { string key = GetEntryKey(entry); lock (indexCache) { lock (indexCacheTimestamps) { if (!indexCache.ContainsKey(key) && entry.IsAccessible) { indexCache.Add(key, entry); } else { indexCache[key] = entry; } if (!indexCacheTimestamps.ContainsKey(key)) { indexCacheTimestamps.Add(key, DateTime.Now); } else { indexCacheTimestamps[key] = DateTime.Now; } } } } }
/// <summary> /// Gets the cache item. /// </summary> /// <param name="entry">The entry.</param> /// <returns>True, if success, false, when the entry was not found in cache.</returns> /// <remarks>Documented by Dev02, 2008-12-11</remarks> public bool GetCacheItem(LearningModulesIndexEntry entry) { string key = GetEntryKey(entry); if (!indexCache.ContainsKey(key)) return false; LearningModulesIndexEntry cacheEntry = indexCache[key]; if (cacheEntry.Preview != null && cacheEntry.Preview.PreviewImage != null) entry.Preview = cacheEntry.Preview; if (cacheEntry.Statistics != null) entry.Statistics = cacheEntry.Statistics; entry.Author = cacheEntry.Author; entry.Count = cacheEntry.Count; entry.Category = cacheEntry.Category; entry.Description = cacheEntry.Description; entry.DisplayName = cacheEntry.DisplayName; entry.LastTimeLearned = cacheEntry.LastTimeLearned; ConnectionStringStruct css = entry.ConnectionString; css.ProtectedLm = cacheEntry.ConnectionString.ProtectedLm; entry.ConnectionString = css; if (cacheEntry.Logo != null) entry.Logo = cacheEntry.Logo; entry.IsFromCache = entry.IsVerified = true; return true; }
/// <summary> /// Serializes to the specified stream. /// </summary> /// <param name="stream">The stream.</param> /// <remarks>Documented by Dev02, 2008-12-04</remarks> private static void Serialize(Stream stream) { //cache for passwords - they must not be saved on disk Dictionary <DateTime, string> passwords = new Dictionary <DateTime, string>(); foreach (KeyValuePair <DateTime, LearningModulesIndexEntry> pair in recentModules) { if (pair.Value.ConnectionString.Password != string.Empty) { passwords.Add(pair.Key, pair.Value.ConnectionString.Password); ConnectionStringStruct css = pair.Value.ConnectionString; css.Password = string.Empty; pair.Value.ConnectionString = css; } } IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, recentModules); foreach (KeyValuePair <DateTime, string> pair in passwords) { LearningModulesIndexEntry entry = recentModules[pair.Key]; ConnectionStringStruct css = entry.ConnectionString; css.Password = pair.Value; entry.ConnectionString = css; } }
/// <summary> /// Adds the specified entry. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev02, 2008-04-29</remarks> public static void Add(LearningModulesIndexEntry entry) { if (entry == null) { throw new ArgumentNullException("entry"); } List <DateTime> deleteKeys = new List <DateTime>(); //delete old duplicates foreach (KeyValuePair <DateTime, LearningModulesIndexEntry> pair in recentModules) { if (pair.Value.ConnectionString.ConnectionString == entry.ConnectionString.ConnectionString && pair.Value.ConnectionString.LmId == entry.ConnectionString.LmId) { deleteKeys.Add(pair.Key); } } foreach (DateTime key in deleteKeys) { recentModules.Remove(key); } while (recentModules.ContainsKey(DateTime.Now)) { System.Threading.Thread.Sleep(5); } recentModules.Add(DateTime.Now, entry); OnListChanged(EventArgs.Empty); }
/// <summary> /// Adds the specified synced module index entry, together with the online connection string. /// </summary> /// <param name="connectionString">The connection string.</param> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev02, 2009-03-26</remarks> public static void Add(IConnectionString connectionString, LearningModulesIndexEntry entry) { if (!syncedModules.ContainsKey(connectionString.ConnectionString)) syncedModules[connectionString.ConnectionString] = new List<LearningModulesIndexEntry>(); syncedModules[connectionString.ConnectionString].RemoveAll(e => e.SyncedPath == entry.SyncedPath && e.ConnectionName == entry.ConnectionName && e.UserName == entry.UserName); syncedModules[connectionString.ConnectionString].Add(entry); }
/// <summary> /// Deletes the entry. /// </summary> /// <param name="entry">The entry.</param> /// <returns></returns> /// <remarks>Documented by Dev09, 2009-05-15</remarks> public bool DeleteEntry(LearningModulesIndexEntry entry) { if (learningModules.Contains(entry)) { learningModules.Remove(entry); } return(false); }
/// <summary> /// Removes a specific offline module index entry. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev02, 2009-03-26</remarks> public static void Remove(IConnectionString connectionString, LearningModulesIndexEntry entry) { if (syncedModules.ContainsKey(connectionString.ConnectionString)) { if (syncedModules[connectionString.ConnectionString].Contains(entry)) { syncedModules[connectionString.ConnectionString].Remove(entry); } } }
/// <summary> /// Adds the specified synced module index entry, together with the online connection string. /// </summary> /// <param name="connectionString">The connection string.</param> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev02, 2009-03-26</remarks> public static void Add(IConnectionString connectionString, LearningModulesIndexEntry entry) { if (!syncedModules.ContainsKey(connectionString.ConnectionString)) { syncedModules[connectionString.ConnectionString] = new List <LearningModulesIndexEntry>(); } syncedModules[connectionString.ConnectionString].RemoveAll(e => e.SyncedPath == entry.SyncedPath && e.ConnectionName == entry.ConnectionName && e.UserName == entry.UserName); syncedModules[connectionString.ConnectionString].Add(entry); }
/// <summary> /// Gets the cache item timestamp. /// </summary> /// <param name="entry">The entry.</param> /// <returns>The timestamp, null, in case not found.</returns> /// <remarks>Documented by Dev02, 2008-12-11</remarks> public DateTime?GetCacheItemTimestamp(LearningModulesIndexEntry entry) { string key = GetEntryKey(entry); if (!indexCacheTimestamps.ContainsKey(key)) { return(null); } return(indexCacheTimestamps[key]); }
private static string GetEntryKey(LearningModulesIndexEntry entry) { if (!entry.IsAccessible && entry.NotAccessibleReason == LearningModuleNotAccessibleReason.Protected) { return(entry.ConnectionString.ConnectionString + "_PROTECTED"); } else { return(entry.ConnectionString.ConnectionString + entry.ConnectionString.LmId.ToString() + entry.User.Id.ToString()); } }
/// <summary> /// Gets the recent modules list, sorted with newest on top. /// </summary> /// <value>The recent modules list.</value> /// <remarks>Documented by Dev02, 2009-02-26</remarks> public static List <LearningModulesIndexEntry> GetRecentModules() { List <LearningModulesIndexEntry> list = new List <LearningModulesIndexEntry>(); CleanupList(); //go through all items in reverse order (newest items at top). for (int i = 1; i <= recentModules.Count; i++) { LearningModulesIndexEntry entry = recentModules.Values[recentModules.Count - i]; list.Add(entry); } return(list); }
/// <summary> /// Generates the preview. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev08, 2008-12-09</remarks> private static void GeneratePreview(LearningModulesIndexEntry entry) { Bitmap preview = new Bitmap(MAX_WIDTH, MAX_HEIGHT); //Todo: get the available preview size Graphics g = Graphics.FromImage(preview); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; try { LearningModulePreviewStruct lmps = GetLearningModulePreviewData(entry.Dictionary, entry.ConnectionString); Font font = new Font("Arial", 9.0f); StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Center; //Preview Background: g.FillRectangle(Brushes.White, 0, 0, MAX_WIDTH, MAX_HEIGHT); //Border g.DrawLine(Pens.Black, new Point(0, 0), new Point(0, MAX_HEIGHT)); g.DrawLine(Pens.Black, new Point(0, 0), new Point(MAX_WIDTH, 0)); g.DrawLine(Pens.Black, new Point(0, MAX_HEIGHT - 1), new Point(MAX_WIDTH - 1, MAX_HEIGHT - 1)); g.DrawLine(Pens.Black, new Point(MAX_WIDTH - 1, 0), new Point(MAX_WIDTH - 1, MAX_HEIGHT - 1)); //Text String: lmps.Text = FitStringToArea(g, lmps.Text, font, MAX_WIDTH); g.DrawString(lmps.Text, font, Brushes.Black, new RectangleF(0, 0, MAX_WIDTH, 15), stringFormat); //the rectangleF is needed to cut the string if FitStringToArea does not cut enough of the string. //Preview Image: g.DrawImage(lmps.Media, MAX_WIDTH / 2 - lmps.Media.Width / 2, 15); LearningModulePreview lmPreview = new LearningModulePreview(); lmPreview.Description = lmps.Description; lmPreview.PreviewImage = (Image)preview.Clone(); entry.Preview = lmPreview; } catch (Exception ex) { Debug.WriteLine("LearningModulesIndex.GeneratePreview(" + entry.DisplayName + ")" + ex.Message); } finally { preview.Dispose(); g.Dispose(); } }
/// <summary> /// Raises the <see cref="E:LearningModuleDetailsLoaded"/> event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-03-10</remarks> protected virtual void OnLearningModuleDetailsLoaded(LearningModulesIndexEntry sender, EventArgs e) { lock (loadingModules) { try { if (loadingModules.Contains(sender)) { loadingModules.Remove(sender); } } catch (Exception exp) { Trace.WriteLine(exp.ToString()); } } if (LearningModuleDetailsLoaded != null) { LearningModuleDetailsLoaded(sender, e); } }
/// <summary> /// Initializes a new instance of the <see cref="LearningModuleListViewItem"/> class. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev05, 2009-03-07</remarks> public LearningModuleListViewItem(LearningModulesIndexEntry entry) : base(entry.DisplayName) { LearningModule = entry; LearningModule.IsVerifiedChanged += new EventHandler(LearningModule_IsVerifiedChanged); while (SubItems.Count < 6) SubItems.Add(new ListViewItem.ListViewSubItem()); //grey pictures ImageIndex = entry.Type == LearningModuleType.Local ? 1 : 5; Group = entry.Group; if (entry.IsVerified) UpdateDetails(); else SubItems[1].Text = Resources.STARTPAGE_LOADING; }
/// <summary> /// Raises the <see cref="E:LearningModuleDetailsLoading"/> event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-03-10</remarks> protected virtual void OnLearningModuleDetailsLoading(LearningModulesIndexEntry sender, EventArgs e) { lock (loadingModules) { try { if (!loadingModules.Contains(sender) && sender != null) { loadingModules.Add(sender); } } catch (Exception exp) { Trace.WriteLine(exp.ToString()); } updateTimer.Enabled = true; } if (LearningModuleDetailsLoading != null) { LearningModuleDetailsLoading(sender, e); } }
/// <summary> /// Initializes a new instance of the <see cref="RecentLearningModulesTest"/> class. /// </summary> /// <remarks>Documented by Dev07, 2009-03-03</remarks> public RecentLearningModulesTest() { lm1 = new LearningModulesIndexEntry(); lm2 = new LearningModulesIndexEntry(); ConnectionStringStruct css1 = new ConnectionStringStruct(); css1.ConnectionString = "con1"; css1.LmId = 1; ConnectionStringStruct css2 = new ConnectionStringStruct(); css2.ConnectionString = "con2"; css2.LmId = 2; lm1.DisplayName = "learnmodule1"; lm1.ConnectionName = "connectionname1"; lm1.ConnectionString = css1; lm2.DisplayName = "learnmodule2"; lm2.ConnectionName = "connectionname2"; lm2.ConnectionString = css2; }
private LearningModulesIndexEntry CreateLerningModuleEntry(IDictionary dic, IUser user, bool protectedLm) { LearningModulesIndexEntry entry = new LearningModulesIndexEntry(); entry.Connection = Connection; entry.User = user; entry.Dictionary = dic; entry.DisplayName = dic.Title; entry.Author = dic.Author; entry.Category = dic.Category; entry.Type = currentUser.ConnectionString.Typ == DatabaseType.Unc || currentUser.ConnectionString.Typ == DatabaseType.MsSqlCe || currentUser.ConnectionString.Typ == DatabaseType.Xml ? LearningModuleType.Local : LearningModuleType.Remote; entry.Group = LearningModulesIndex.Groups.Find(g => g.Tag == Connection); ConnectionStringStruct css = new ConnectionStringStruct(user.ConnectionString.Typ, dic.Connection, dic.Id); css.ProtectedLm = protectedLm; entry.ConnectionString = css; entry.Connection = Connection; return(entry); }
private LearningModulesIndexEntry CreateNewEmbeddedDbLearningModuleEntry(string path) { try { ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.MsSqlCe, path, DAL.User.GetIdOfLearningModule(path, currentUser)); IUser user = UserFactory.Create(getLogin, css, dataAccessError, path); IDictionary dic = user.Open(); return(CreateLerningModuleEntry(dic, user)); } catch (ProtectedLearningModuleException) { LearningModulesIndexEntry entry = new LearningModulesIndexEntry(); entry.IsAccessible = false; entry.NotAccessibleReason = LearningModuleNotAccessibleReason.Protected; entry.ConnectionString = new ConnectionStringStruct(DatabaseType.MsSqlCe, path); entry.DisplayName = System.IO.Path.GetFileNameWithoutExtension(path); entry.Connection = Connection; return(entry); } }
/// <summary> /// Gets the cache item. /// </summary> /// <param name="entry">The entry.</param> /// <returns>True, if success, false, when the entry was not found in cache.</returns> /// <remarks>Documented by Dev02, 2008-12-11</remarks> public bool GetCacheItem(LearningModulesIndexEntry entry) { string key = GetEntryKey(entry); if (!indexCache.ContainsKey(key)) { return(false); } LearningModulesIndexEntry cacheEntry = indexCache[key]; if (cacheEntry.Preview != null && cacheEntry.Preview.PreviewImage != null) { entry.Preview = cacheEntry.Preview; } if (cacheEntry.Statistics != null) { entry.Statistics = cacheEntry.Statistics; } entry.Author = cacheEntry.Author; entry.Count = cacheEntry.Count; entry.Category = cacheEntry.Category; entry.Description = cacheEntry.Description; entry.DisplayName = cacheEntry.DisplayName; entry.LastTimeLearned = cacheEntry.LastTimeLearned; ConnectionStringStruct css = entry.ConnectionString; css.ProtectedLm = cacheEntry.ConnectionString.ProtectedLm; entry.ConnectionString = css; if (cacheEntry.Logo != null) { entry.Logo = cacheEntry.Logo; } entry.IsFromCache = entry.IsVerified = true; return(true); }
/// <summary> /// Creates the new odx learning module entry. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2009-06-15</remarks> public static LearningModulesIndexEntry CreateNewOdxLearningModuleEntryStatic(string path) { ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.Xml, path, true); IUser user = UserFactory.Create((GetLoginInformation) delegate(UserStruct u, ConnectionStringStruct c) { return(u); }, css, (DataAccessErrorDelegate) delegate(object sender, Exception e) { }, path); IDictionary dic = DAL.User.GetPreviewDictionary(path, user, false); string directory = new FileInfo(path).DirectoryName; UncConnectionStringBuilder connection = new UncConnectionStringBuilder(directory); connection.Name = directory; LearningModulesIndexEntry entry = new LearningModulesIndexEntry(); entry.Connection = connection; entry.User = user; entry.Dictionary = dic; entry.DisplayName = dic.Title; entry.Type = LearningModuleType.Local; css.ProtectedLm = false; entry.ConnectionString = css; return(entry); }
/// <summary> /// Loads the detailed information for an index entry. /// </summary> /// <param name="entry">The learning module entry.</param> /// <remarks>Documented by Dev03, 2008-12-03</remarks> private static void LoadIndexEntry(LearningModulesIndexEntry entry) { try { if (entry.Dictionary is PreviewDictionary) entry.Dictionary = DAL.User.UpdatePreviewDictionary(entry.Dictionary as PreviewDictionary); entry.DisplayName = entry.Dictionary.Title; entry.Description = entry.Dictionary.Description; entry.Author = entry.Dictionary.Author; entry.Category = entry.Dictionary.Category; entry.Count = entry.Dictionary.Cards.Count; entry.Size = entry.Dictionary.DictionarySize; Settings settings = new Settings(entry.Dictionary); IMedia logo = settings.Logo as IImage; if (logo != null) entry.Logo = (Image)Bitmap.FromStream(logo.Stream).Clone(); if (entry.Dictionary.Statistics.Count > 0) entry.LastTimeLearned = entry.Dictionary.Statistics[entry.Dictionary.Statistics.Count - 1].StartTimestamp; } catch (Exception ex) { Debug.WriteLine("LoadIndexEntry - " + ex.Message); } }
private void CompareLMIndexEntry(LearningModulesIndexEntry expected, LearningModulesIndexEntry actual) { Assert.IsTrue(actual.DisplayName == expected.DisplayName, "Display name is not equal"); Assert.IsTrue(actual.ConnectionName == expected.ConnectionName, "Connection name is not equal"); Assert.IsTrue(actual.ConnectionString.ConnectionString == expected.ConnectionString.ConnectionString, "Connection string is not equal"); Assert.IsTrue(actual.ConnectionString.LmId == expected.ConnectionString.LmId, "LmId is not equal"); }
/// <summary> /// Handles the Tick event of the FileDropTimer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev08, 2009-02-27</remarks> private void FileDropTimer_Tick(object sender, EventArgs e) { System.Windows.Forms.Timer timer = sender as System.Windows.Forms.Timer; timer.Stop(); if (timer.Tag != null && timer.Tag is string) { string file = (string)timer.Tag; if (Helper.CheckFileName(file)) { if (Helper.IsLearningModuleFileName(file)) { LearningModuleSelectedEventArgs args = new LearningModuleSelectedEventArgs( new LearningModulesIndexEntry( new ConnectionStringStruct( (Path.GetExtension(file) == DAL.Helper.OdxExtension || Path.GetExtension(file) == DAL.Helper.DzpExtension || Path.GetExtension(file) == DAL.Helper.OdfExtension) ? DatabaseType.Xml : DatabaseType.MsSqlCe, file, false) ) { ConnectionName = Path.GetDirectoryName(file) } ); selectedLearningModule = args.LearnModule; args.IsUsedDragAndDrop = true; //[ML-2023] Inconsistent Drag and Drop behaviour if (LearningModuleSelected != null) LearningModuleSelected(this, args); } else { if (ImportConfigFile(file)) LoadLearningModules(); } } } timer.Dispose(); }
/// <summary> /// Handles the OnOpenLearningModule event of the learningModulesTreeViewControl control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="MLifter.Controls.LearningModuleSelectedEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev03, 2009-03-11</remarks> private void learningModulesTreeViewControl_OnOpenLearningModule(object sender, LearningModuleSelectedEventArgs e) { selectedLearningModule = e.LearnModule; if (LearningModuleSelected != null) LearningModuleSelected(this, e); }
public byte[] GetLearningModuleIndexEntry(int learningModuleId, string clientId) { try { if ((int)Session["uid"] < 0) throw new NoValidUserException(); string key = string.Format("user-{0}", (int)Session["uid"]); string lmKey = string.Format("lm-{0}", learningModuleId); IUser user = null; lock (formatter) { try { user = HttpContext.Current.Cache[key] as IUser; } catch { } if (user == null) { user = UserFactory.Create((GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { if (u.LastLoginError != LoginError.NoError) throw new InvalidCredentialsException("Some of the submited credentials are wrong!"); string username = Session["username"].ToString(); string password = Session["password"].ToString(); UserAuthenticationTyp authType = password == string.Empty ? UserAuthenticationTyp.ListAuthentication : UserAuthenticationTyp.FormsAuthentication; return new UserStruct(username, password, authType, true, true); }, new ConnectionStringStruct(DatabaseType.PostgreSQL, ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString, -1), (DataAccessErrorDelegate)delegate { return; }, ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString, true); HttpContext.Current.Cache[key] = user; } } IDictionary dic = new MLifter.DAL.DB.DbDictionary(learningModuleId, user); LearningModulesIndexEntry entry = new LearningModulesIndexEntry(); entry.User = user; entry.Dictionary = dic; entry.DisplayName = dic.Title; entry.Type = LearningModuleType.Remote; entry.Type = LearningModuleType.Remote; entry.ConnectionString = new ConnectionStringStruct(DatabaseType.PostgreSQL, dic.Connection, dic.Id, user.ConnectionString.SessionId); LearningModulesIndex.LoadEntry(entry); if (entry.Dictionary.ContentProtected) { // MemoryLifter > 2.3 does not support DRM protected content entry.IsAccessible = false; entry.NotAccessibleReason = LearningModuleNotAccessibleReason.Protected; } ConnectionStringStruct conString = entry.ConnectionString; conString.ConnectionString = string.Empty; entry.ConnectionString = conString; MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, entry); return stream.ToArray(); } catch (Exception exp) { try { WriteLogEntry(exp.ToString()); } catch { throw exp; } return null; } }
/// <summary> /// Adds the recent file to the stick config. /// </summary> /// <param name="learningModule">The learning module.</param> /// <remarks>Documented by Dev03, 2009-05-12</remarks> private static void AddRecentFileToStick(LearningModulesIndexEntry learningModule) { if (learningModule.ConnectionString.Typ == MLifter.DAL.DatabaseType.MsSqlCe) { List<string> recentFiles = Setup.GetRecentFilesFromStick(); if (recentFiles.Count > 0) { recentFiles.Reverse(); if (recentFiles.Exists(r => r == learningModule.ConnectionString.ConnectionString)) recentFiles.Remove(learningModule.ConnectionString.ConnectionString); recentFiles.Add(learningModule.ConnectionString.ConnectionString); if (recentFiles.Count > Settings.Default.RecentFilesCount && Settings.Default.RecentFilesCount > 0) recentFiles.Remove(recentFiles[0]); recentFiles.Reverse(); Settings.Default.Reload(); Settings.Default.RecentFiles = "\"" + String.Join("\",\"", recentFiles.ToArray()) + "\""; } else { Settings.Default.Reload(); Settings.Default.RecentFiles = "\"" + learningModule.ConnectionString.ConnectionString + "\""; } Settings.Default.Save(); } }
/// <summary> /// Adds the recent learning module. /// </summary> /// <param name="learningModule">The learning module.</param> /// <remarks>Documented by Dev03, 2009-05-11</remarks> public static void AddRecentLearningModule(LearningModulesIndexEntry learningModule) { RecentLearningModules.Add(learningModule); RecentLearningModules.Dump(Setup.RecentLearningModulesPath); if (RunningFromStick()) Setup.AddRecentFileToStick(learningModule); }
/// <summary> /// Initializes a new instance of the <see cref="LearningModuleAddedEventArgs"/> class. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev05, 2009-03-06</remarks> public LearningModuleAddedEventArgs(LearningModulesIndexEntry entry) { LearningModule = entry; }
protected virtual void OnLearningModuleSelected(LearningModuleSelectedEventArgs e) { selectedLearningModule = e.LearnModule; if (LearningModuleSelected != null) LearningModuleSelected(this, e); }
protected virtual void OnCancelPressed(EventArgs e) { selectedLearningModule = null; if (CancelPressed != null) CancelPressed(this, e); }
/// <summary> /// Syncs the specified module. /// </summary> /// <param name="module">The module.</param> /// <param name="reportingDelegate">The reporting delegate.</param> /// <param name="syncedLearningModulePath">The synced learning module path (necessary when Startpage isn't initialized).</param> /// <remarks>Documented by Dev03, 2009-02-12</remarks> public static void Sync(LearningModulesIndexEntry module, SyncStatusReportingDelegate reportingDelegate, string syncedLearningModulePath) { if (module.Connection == null) //no user is required for syncing throw new SynchronizationFailedException(new ServerOfflineException()); try { string serverUri = module.Connection is WebConnectionStringBuilder ? (module.Connection as WebConnectionStringBuilder).SyncURI : (module.Connection as PostgreSqlConnectionStringBuilder).SyncURI; bool createNew = (module.SyncedPath == string.Empty); string path = Tools.GetFullSyncPath(module.SyncedPath, syncedLearningModulePath, module.ConnectionName, module.UserName); Sync(serverUri, module.ConnectionString.LmId, module.UserId, ref path, module.ConnectionString.ProtectedLm, module.ConnectionString.Password, createNew, false, reportingDelegate); module.SyncedPath = Tools.GetSyncedPath(path, syncedLearningModulePath, module.ConnectionName, module.UserName); } catch (SynchronizationFailedException) { throw; } catch { throw new SynchronizationFailedException(new ServerOfflineException()); } }
/// <summary> /// Syncs the specified module. /// </summary> /// <param name="module">The module.</param> /// <param name="reportingDelegate">The reporting delegate.</param> /// <remarks>Documented by Dev08, 2009-04-30</remarks> public static void Sync(LearningModulesIndexEntry module, SyncStatusReportingDelegate reportingDelegate) { Sync(module, reportingDelegate, SyncedLearningModulePath); }
/// <summary> /// Updates the LearningModule item. /// </summary> /// <param name="entry">The entry.</param> /// <param name="onlyRefresh">if set to <c>true</c> [only refresh].</param> /// <remarks>Documented by Dev08, 2009-03-04</remarks> private void UpdateItem(LearningModulesIndexEntry entry) { try { listViewLearningModules.Invoke((MethodInvoker)delegate { ListViewItem item = null; foreach (ListViewItem listItem in listViewLearningModules.Items) { if (!(listItem is LearningModuleListViewItem)) continue; LearningModuleListViewItem itm = listItem as LearningModuleListViewItem; if (itm.LearningModule == entry) { item = itm; break; } } if (item == null) return; //Updated the PreviewControl if (listViewLearningModules.SelectedItems.Contains(item)) UpdateDetails(); if (categoryToolStripMenuItem.Checked && entry.Category != null) { foreach (ListViewGroup group in listViewLearningModules.Groups) if (group.Header == entry.Category.ToString()) { item.Group = group; break; } } else if (authorToolStripMenuItem.Checked && !String.IsNullOrEmpty(entry.Author)) { foreach (ListViewGroup group in listViewLearningModules.Groups) if (group.Header == entry.Author) { item.Group = group; break; } if (item.Group == null) { ListViewGroup grp = new ListViewGroup(entry.Author); listViewLearningModules.Groups.Add(grp); item.Group = grp; } } }); } catch (InvalidOperationException exp) { Trace.WriteLine(exp.ToString()); } }
/// <summary> /// Handles the Click event of the RecentItem control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev08, 2009-03-09</remarks> private void RecentItem_Click(object sender, EventArgs e) { selectedLearningModule = (sender as TaskItem).Tag as LearningModulesIndexEntry; if (selectedLearningModule.ConnectionString.SyncType != SyncType.NotSynchronized) { try { if (selectedLearningModule.ConnectionString.SyncType != SyncType.FullSynchronized) { foreach (KeyValuePair<IConnectionString, IUser> pair in LearningModulesIndex.ConnectionUsers) { if (pair.Key.ConnectionString == selectedLearningModule.ConnectionString.ConnectionString) { selectedLearningModule.User = pair.Value; selectedLearningModule.User.Login(); break; } } if (selectedLearningModule.User == null) { IUser user = UserFactory.Create(LoginForm.OpenLoginForm, selectedLearningModule.ConnectionString, DataAccessError, this); if (user == null) return; selectedLearningModule.User = user; } } } catch (NoValidUserException) { return; } try { Sync(selectedLearningModule, SyncStatusUpdate); } catch (SynchronizationFailedException exp) { TaskDialog.MessageBox(Resources.LEARNING_MODULES_PAGE_SYNC_FAILED_TITLE, Resources.LEARNING_MODULES_PAGE_SYNC_FAILED_MAIN, Resources.LEARNING_MODULES_PAGE_SYNC_FAILED_CONTENT, exp.ToString(), string.Empty, string.Empty, TaskDialogButtons.OK, TaskDialogIcons.Error, TaskDialogIcons.Information); return; } } OnLearningModuleSelected(new LearningModuleSelectedEventArgs(selectedLearningModule)); }
/// <summary> /// Downloads the content of the media table. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev05, 2009-03-31</remarks> private void DownloadMediaContent(LearningModulesIndexEntry entry, string syncedPath) { int counter = 1; SyncStatusUpdate(0, Resources.SYNC_DOWNLOAD_MEDIA); ConnectionStringStruct cssSync = entry.ConnectionString; cssSync.Typ = DatabaseType.MsSqlCe; cssSync.ConnectionString = syncedPath; cssSync.LmId = entry.Dictionary.Id; cssSync.SyncType = SyncType.FullSynchronized; cssSync.LearningModuleFolder = (entry.Connection as ISyncableConnectionString).MediaURI; cssSync.ServerUser = entry.User; IUser user = UserFactory.Create((GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { return AuthenticationUsers[entry.Connection.ConnectionString]; }, cssSync, DataAccessError, syncedPath); IDictionary dic = user.Open(); List<int> mediaIds = dic.GetEmptyResources(); WebClient webClient = new WebClient(); foreach (int mediaId in mediaIds) { SyncStatusUpdate(counter * 100.0 / mediaIds.Count, string.Format(Resources.SYNC_DOWNLOAD_MEDIA_STEP, counter, mediaIds.Count)); counter++; try { string uri = DbMediaServer.Instance(dic.Parent).GetMediaURI(mediaId).ToString(); webClient.DownloadData(uri); } catch { Trace.WriteLine("Failed to get media!", "DownloadMediaContent"); } } SyncStatusUpdate(100, string.Empty); }
/// <summary> /// Downloads the extension files. /// </summary> /// <param name="entry">The entry.</param> /// <param name="syncedPath">The synced path.</param> /// <remarks>Documented by Dev02, 2009-07-06</remarks> private void DownloadExtensionFiles(LearningModulesIndexEntry entry, string syncedPath) { SyncStatusUpdate(0, Resources.SYNC_DOWNLOAD_EXTENSIONS); ConnectionStringStruct cssSync = entry.ConnectionString; cssSync.Typ = DatabaseType.MsSqlCe; cssSync.ConnectionString = syncedPath; cssSync.LmId = entry.Dictionary.Id; cssSync.SyncType = SyncType.FullSynchronized; cssSync.ExtensionURI = (entry.Connection as ISyncableConnectionString).ExtensionURI; cssSync.ServerUser = entry.User; IUser user = UserFactory.Create((GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { return AuthenticationUsers[entry.Connection.ConnectionString]; }, cssSync, DataAccessError, syncedPath); IDictionary dic = user.Open(); WebClient webClient = new WebClient(); foreach (IExtension ext in dic.Extensions) { try { string uri = DbMediaServer.Instance(dic.Parent).GetExtensionURI(ext.Id).ToString(); webClient.DownloadData(uri); } catch { Trace.WriteLine("Failed to get extension files!", "DownloadExtensionFiles"); } } SyncStatusUpdate(100, string.Empty); }
private void ImportLearningModule(LearningModulesIndexEntry source) { try { FolderIndexEntry folder = GetFolderOfConnection(conTarget); if (folder == null) return; try { if (!LearningModulesIndex.ConnectionUsers[conTarget].List().HasPermission(PermissionTypes.CanModify)) { TaskDialog.MessageBox(Resources.STARTUP_IMPORT_LEARNING_MODULE_PERMISSION_MBX_CAPTION, Resources.STARTUP_IMPORT_LEARNING_MODULE_PERMISSION_MBX_TEXT, string.Empty, TaskDialogButtons.OK, TaskDialogIcons.Error); return; } } catch (KeyNotFoundException) { return; } ShowStatusMessage(false); IUser targetUser = folder.CurrentUser; if (conTarget.ConnectionType == DatabaseType.Unc) { string newFileName = Path.Combine(folder.Connection.ConnectionString, source.DisplayName.Replace(@"\", "_") + DAL.Helper.EmbeddedDbExtension); targetUser.ConnectionString = new ConnectionStringStruct(DatabaseType.MsSqlCe, newFileName); } IDictionary target = targetUser.List().AddNew(source.Category.Id > 5 ? MLifter.DAL.Category.DefaultCategory : source.Category.Id, source.DisplayName); int newId = target.Id; ConnectionStringStruct css = new ConnectionStringStruct(conTarget.ConnectionType == DatabaseType.Unc ? DatabaseType.MsSqlCe : conTarget.ConnectionType, target.Connection, newId); try { LearnLogic.CopyToFinished += new EventHandler(LearnLogic_CopyToFinished); LearnLogic.CopyLearningModule(source.ConnectionString, css, GetUser, UpdateStatusMessage, DataAccessError, null); } #region error handling catch (DictionaryNotDecryptedException) { HideStatusMessage(); LearningModulesIndex.ConnectionUsers[conTarget].List().Delete(css); MessageBox.Show(Properties.Resources.DIC_ERROR_NOT_DECRYPTED_TEXT, Properties.Resources.DIC_ERROR_NOT_DECRYPTED_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (DictionaryContentProtectedException) { HideStatusMessage(); LearningModulesIndex.ConnectionUsers[conTarget].List().Delete(css); MessageBox.Show(string.Format(Properties.Resources.DIC_ERROR_CONTENTPROTECTED_TEXT, source.ConnectionString.ConnectionString), Properties.Resources.DIC_ERROR_CONTENTPROTECTED_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (MLifter.DAL.InvalidDictionaryException) { HideStatusMessage(); LearningModulesIndex.ConnectionUsers[conTarget].List().Delete(css); MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_TEXT, source.ConnectionString.ConnectionString), Properties.Resources.DIC_ERROR_LOADING_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (System.Xml.XmlException) { HideStatusMessage(); LearningModulesIndex.ConnectionUsers[conTarget].List().Delete(css); MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_TEXT, source.ConnectionString.ConnectionString), Properties.Resources.DIC_ERROR_LOADING_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (System.IO.IOException) { HideStatusMessage(); LearningModulesIndex.ConnectionUsers[conTarget].List().Delete(css); MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_LOCKED_TEXT, source.ConnectionString.ConnectionString), Properties.Resources.DIC_ERROR_LOADING_LOCKED_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch { HideStatusMessage(); LearningModulesIndex.ConnectionUsers[conTarget].List().Delete(css); MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_TEXT, source.DisplayName), Properties.Resources.DIC_ERROR_LOADING_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } #endregion } catch (PermissionException) { TaskDialog.MessageBox(Resources.STARTUP_IMPORT_LEARNING_MODULE_PERMISSION_MBX_CAPTION, Resources.STARTUP_IMPORT_LEARNING_MODULE_PERMISSION_MBX_TEXT, string.Empty, TaskDialogButtons.OK, TaskDialogIcons.Error); return; } catch { HideStatusMessage(); MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_TEXT, source.ConnectionString.ConnectionString), Properties.Resources.DIC_ERROR_LOADING_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } }
public IsOdxFormatException(LearningModulesIndexEntry module) { this.module = module; }
/// <summary> /// Initializes a new instance of the <see cref="LearningModuleSelectedEventArgs"/> class. /// </summary> /// <param name="entry">The entry which was updated.</param> /// <remarks>Documented by Dev05, 2008-12-03</remarks> public LearningModuleSelectedEventArgs(LearningModulesIndexEntry learnModuleConnection) { this.learnModule = learnModuleConnection; IsUsedDragAndDrop = false; }
/// <summary> /// Initializes the profile environment. /// </summary> /// <remarks>Documented by Dev05, 2007-11-15</remarks> public static void InitializeProfile(bool copyDemoDictionary, string dictionaryParentPath) { MLifter.Controls.LoadStatusMessage progress = new MLifter.Controls.LoadStatusMessage(Resources.UNPACK_TLOADMSG, 100, true); try { if (!Directory.Exists(dictionaryParentPath)) Directory.CreateDirectory(dictionaryParentPath); if (!copyDemoDictionary) return; string zipFilePath = Path.Combine(Application.StartupPath, Resources.SETUP_STARTUP_FOLDERS); if (!File.Exists(zipFilePath)) return; progress.SetProgress(0); Cursor.Current = Cursors.WaitCursor; progress.Show(); long zCount = 0; ZipFile zFile = null; try { zFile = new ZipFile(zipFilePath); zCount = zFile.Count; } catch (Exception ex) { throw ex; } finally { if (zFile != null) zFile.Close(); } if (zCount == 0) return; using (ZipInputStream zipFile = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry entry; int zCounter = 1; while ((entry = zipFile.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(entry.Name); string fileName = Path.GetFileName(entry.Name); if (directoryName.Length > 0) Directory.CreateDirectory(Path.Combine(dictionaryParentPath, directoryName)); if (fileName.Length > 0) { using (FileStream stream = File.Open(Path.Combine(Path.Combine(dictionaryParentPath, directoryName), fileName), FileMode.Create, FileAccess.Write, FileShare.None)) { int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (bufferSize > 0) { bufferSize = zipFile.Read(buffer, 0, buffer.Length); if (bufferSize > 0) stream.Write(buffer, 0, bufferSize); } } } if ((Path.GetExtension(fileName) == MLifter.DAL.Helper.OdxExtension) || (Path.GetExtension(fileName) == MLifter.DAL.Helper.EmbeddedDbExtension)) { string dicPath = Path.Combine(Path.Combine(dictionaryParentPath, directoryName), fileName); LearningModulesIndexEntry indexEntry = new LearningModulesIndexEntry(); indexEntry.DisplayName = "StartUp"; indexEntry.ConnectionString = new MLifter.DAL.Interfaces.ConnectionStringStruct(MLifter.DAL.DatabaseType.MsSqlCe, dicPath, false); Setup.AddRecentLearningModule(indexEntry); } progress.SetProgress((int)Math.Floor(100.0 * (zCounter++) / zCount)); } } Settings.Default.Save(); } catch { MessageBox.Show(Properties.Resources.INITIALIZE_ENVIRONMENT_ERROR_TEXT, Properties.Resources.INITIALIZE_ENVIRONMENT_ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { progress.Dispose(); Cursor.Current = Cursors.Default; } }
/// <summary> /// Removes a specific offline module index entry. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev02, 2009-03-26</remarks> public static void Remove(IConnectionString connectionString, LearningModulesIndexEntry entry) { if (syncedModules.ContainsKey(connectionString.ConnectionString)) { if (syncedModules[connectionString.ConnectionString].Contains(entry)) syncedModules[connectionString.ConnectionString].Remove(entry); } }
public NeedToUnPackException(LearningModulesIndexEntry module) { this.module = module; }
/// <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(); } }
/// <summary> /// Handles the Click event of the buttonOK control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev03, 2008-12-22</remarks> private void buttonOK_Click(object sender, EventArgs e) { #region NON FEED if (!FeedIsVisible) { foreach (ListViewItem item in listViewLearningModules.SelectedItems) { if (item is LearningModuleListViewItem) { lmItem = item as LearningModuleListViewItem; break; } } if (lmItem != null) { try { LearningModulesIndexEntry entry = lmItem.LearningModule; if (!entry.IsVerified || !entry.IsAccessible) return; #region PgSQL if (entry.Connection is PostgreSqlConnectionStringBuilder) { string serverUri = (entry.Connection as PostgreSqlConnectionStringBuilder).SyncURI; string path = Tools.GetFullSyncPath(entry.DisplayName + MLifter.DAL.Helper.SyncedEmbeddedDbExtension, SyncedLearningModulePath, entry.ConnectionName, entry.UserName); bool createNew = (entry.SyncedPath == string.Empty); ConnectionStringStruct css = entry.ConnectionString; switch ((entry.Connection as PostgreSqlConnectionStringBuilder).SyncType) { case SyncType.NotSynchronized: entry.SyncedPath = string.Empty; entry.ConnectionString = css; break; case SyncType.HalfSynchronizedWithDbAccess: Sync(serverUri, entry.ConnectionString.LmId, entry.UserId, ref path, entry.ConnectionString.ProtectedLm, entry.ConnectionString.Password, createNew, false, (SyncStatusReportingDelegate)SyncStatusUpdate); DownloadExtensionFiles(entry, path); entry.SyncedPath = Tools.GetSyncedPath(path, SyncedLearningModulePath, entry.ConnectionName, entry.UserName); css.SyncType = SyncType.HalfSynchronizedWithDbAccess; css.ServerUser = entry.User; entry.ConnectionString = css; break; case SyncType.HalfSynchronizedWithoutDbAccess: Sync(serverUri, entry.ConnectionString.LmId, entry.UserId, ref path, entry.ConnectionString.ProtectedLm, entry.ConnectionString.Password, createNew, false, (SyncStatusReportingDelegate)SyncStatusUpdate); DownloadExtensionFiles(entry, path); entry.SyncedPath = Tools.GetSyncedPath(path, SyncedLearningModulePath, entry.ConnectionName, entry.UserName); css.SyncType = SyncType.HalfSynchronizedWithoutDbAccess; css.LearningModuleFolder = (entry.Connection as PostgreSqlConnectionStringBuilder).MediaURI; entry.ConnectionString = css; entry.User.Logout(); break; case SyncType.FullSynchronized: if (entry.User == null) break; Sync(serverUri, entry.ConnectionString.LmId, entry.UserId, ref path, entry.ConnectionString.ProtectedLm, entry.ConnectionString.Password, createNew, false, (SyncStatusReportingDelegate)SyncStatusUpdate); DownloadMediaContent(entry, path); DownloadExtensionFiles(entry, path); entry.SyncedPath = Tools.GetSyncedPath(path, SyncedLearningModulePath, entry.ConnectionName, entry.UserName); css.SyncType = SyncType.FullSynchronized; css.LearningModuleFolder = (entry.Connection as PostgreSqlConnectionStringBuilder).MediaURI; entry.ConnectionString = css; SyncedModulesIndex.Add(entry.Connection, entry); SyncedModulesIndex.Dump(Path.Combine(SyncedLearningModulePath, Settings.Default.SyncedModulesFile)); entry.User.Logout(); break; default: throw new NotImplementedException(); } lmIndex.DumpIndexCache(lmIndex.CacheFile); } #endregion #region WEB else if (entry.Connection is WebConnectionStringBuilder) { string serverUri = (entry.Connection as WebConnectionStringBuilder).SyncURI; string path = Tools.GetFullSyncPath(entry.DisplayName + MLifter.DAL.Helper.SyncedEmbeddedDbExtension, SyncedLearningModulePath, entry.ConnectionName, entry.UserName); bool createNew = (entry.SyncedPath == string.Empty); ConnectionStringStruct css = entry.ConnectionString; switch ((entry.Connection as WebConnectionStringBuilder).SyncType) { case SyncType.HalfSynchronizedWithoutDbAccess: Sync(serverUri, entry.ConnectionString.LmId, entry.UserId, ref path, entry.ConnectionString.ProtectedLm, entry.ConnectionString.Password, createNew, false, (SyncStatusReportingDelegate)SyncStatusUpdate); DownloadExtensionFiles(entry, path); entry.SyncedPath = Tools.GetSyncedPath(path, SyncedLearningModulePath, entry.ConnectionName, entry.UserName); css.SyncType = SyncType.HalfSynchronizedWithoutDbAccess; css.ServerUser = entry.User; css.LearningModuleFolder = (entry.Connection as WebConnectionStringBuilder).MediaURI; entry.ConnectionString = css; break; case SyncType.FullSynchronized: if (entry.User == null) break; Sync(serverUri, entry.ConnectionString.LmId, entry.UserId, ref path, entry.ConnectionString.ProtectedLm, entry.ConnectionString.Password, createNew, false, (SyncStatusReportingDelegate)SyncStatusUpdate); DownloadMediaContent(entry, path); DownloadExtensionFiles(entry, path); entry.SyncedPath = Tools.GetSyncedPath(path, SyncedLearningModulePath, entry.ConnectionName, entry.UserName); css.SyncType = SyncType.FullSynchronized; css.ServerUser = entry.User; css.LearningModuleFolder = (entry.Connection as WebConnectionStringBuilder).MediaURI; entry.ConnectionString = css; SyncedModulesIndex.Add(entry.Connection, entry); SyncedModulesIndex.Dump(Path.Combine(SyncedLearningModulePath, Settings.Default.SyncedModulesFile)); break; case SyncType.NotSynchronized: case SyncType.HalfSynchronizedWithDbAccess: default: throw new NotImplementedException(); } lmIndex.DumpIndexCache(lmIndex.CacheFile); } #endregion OnLearningModuleSelected(new LearningModuleSelectedEventArgs(entry)); } catch (NotEnoughtDiskSpaceException) { TaskDialog.MessageBox(Resources.TASK_DIALOG_DISK_FULL_TITLE, Resources.TASK_DIALOG_DISK_FULL_CAPTION, Resources.TASK_DIALOG_DISK_FULL_TEXT, TaskDialogButtons.OK, TaskDialogIcons.Error); } catch (SynchronizationFailedException exp) { Trace.WriteLine(exp.ToString()); TaskDialog.MessageBox(Resources.LEARNING_MODULES_PAGE_SYNC_FAILED_TITLE, Resources.LEARNING_MODULES_PAGE_SYNC_FAILED_MAIN, Resources.LEARNING_MODULES_PAGE_SYNC_FAILED_CONTENT, exp.ToString(), string.Empty, string.Empty, TaskDialogButtons.OK, TaskDialogIcons.Error, TaskDialogIcons.Error); } } } #endregion else { if (listViewFeed.SelectedIndices.Count == 0) return; ModuleInfo info = (ModuleInfo)listViewFeed.SelectedItems[0].Tag; string remoteFile = info.DownloadUrl; string folder = LearningModulesIndex.ConnectionsHandler.ConnectionStrings.Find(c => c.IsDefault).ConnectionString; string localFile = Path.Combine(folder, Methods.GetValidFileName(info.Title + DAL.Helper.EmbeddedDbExtension, String.Empty)); if (File.Exists(localFile)) { EmulatedTaskDialog dialog = new EmulatedTaskDialog(); dialog.Owner = ParentForm; dialog.StartPosition = FormStartPosition.CenterParent; dialog.Title = Resources.LEARNING_MODULES_PAGE_DOWNLOAD_EXISTS_CAPTION; dialog.MainInstruction = Resources.LEARNING_MODULES_PAGE_DOWNLOAD_EXISTS_HEADER; dialog.Content = Resources.LEARNING_MODULES_PAGE_DOWNLOAD_EXISTS_TEXT; dialog.CommandButtons = String.Format("{0}|{1}|{2}", Resources.LEARNING_MODULES_PAGE_DOWNLOAD_EXISTS_OPEN, Resources.LEARNING_MODULES_PAGE_DOWNLOAD_EXISTS_OVERWRITE, Resources.LEARNING_MODULES_PAGE_DOWNLOAD_EXISTS_RENAME); dialog.Buttons = TaskDialogButtons.Cancel; dialog.MainIcon = TaskDialogIcons.Question; dialog.MainImages = new Image[] { Resources.document_open_big, Resources.document_save, Resources.document_save_as }; dialog.HoverImages = new Image[] { Resources.document_open_big, Resources.document_save, Resources.document_save_as }; dialog.CenterImages = true; dialog.BuildForm(); if (dialog.ShowDialog() == DialogResult.Cancel) return; switch (dialog.CommandButtonClickedIndex) { case 0: LearningModulesIndexEntry entry = new LearningModulesIndexEntry(new ConnectionStringStruct(DatabaseType.MsSqlCe, localFile)); OnLearningModuleSelected(new LearningModuleSelectedEventArgs(entry)); return; case 1: lmIndex.EndLearningModulesScan(); disposeAndDisconnectLMs(); File.Delete(localFile); break; case 2: default: int cnt = 1; while (File.Exists(localFile)) localFile = Path.Combine(folder, Methods.GetValidFileName(info.Title + "_" + cnt++ + DAL.Helper.EmbeddedDbExtension, String.Empty)); break; } } info.DownloadUrl = localFile; listViewFeed.SelectedItems[0].Tag = info; WebClient webClient = new WebClient(); webClient.DownloadProgressChanged += (s, args) => { UpdateStatusMessage(String.Format(Resources.LEARNING_MODULES_PAGE_DOWNLOAD_PROGRESS, Methods.GetFileSize(args.BytesReceived), Methods.GetFileSize(args.TotalBytesToReceive)), args.ProgressPercentage); }; webClient.DownloadFileCompleted += (s, args) => { HideStatusMessage(); OnLearningModuleSelected(new LearningModuleSelectedEventArgs(new LearningModulesIndexEntry( new ConnectionStringStruct(DatabaseType.MsSqlCe, localFile)))); }; ShowStatusMessage(message: Resources.LEARNING_MODULES_PAGE_DOWNLOAD_START); webClient.DownloadFileAsync(new Uri(remoteFile), localFile); } }
private void LoadContent() { try { lock (content) content.Clear(); if (Connection is UncConnectionStringBuilder && Directory.Exists(Path)) { foreach (string file in Directory.GetFiles(Path, "*" + DAL.Helper.EmbeddedDbExtension, SearchOption.TopDirectoryOnly)) { try { LearningModulesIndexEntry entry; try { entry = CreateNewEmbeddedDbLearningModuleEntry(file); } catch (DatabaseVersionNotSupported e) { Trace.WriteLine("FolderIndexEntry.LoadContent() found an old version db - use File->Open to convert the DB."); if (!e.CanUpdate) { continue; } else { entry = CreateNewEmbeddedDbLearningModuleEntry(file); } } catch (System.Data.SqlServerCe.SqlCeException ex) { //probably an invalid db file Trace.WriteLine("FolderIndexEntry.LoadContent() found an invalid db - " + ex.Message); continue; } lock (content) content.Add(entry); OnLearningModuleAdded(new LearningModuleAddedEventArgs(entry)); } catch (IOException exp) { Trace.WriteLine(exp.ToString()); } } foreach (string file in Directory.GetFiles(Path, "*" + DAL.Helper.OdxExtension, SearchOption.TopDirectoryOnly)) { try { LearningModulesIndexEntry entry = CreateNewOdxLearningModuleEntry(file); lock (content) content.Add(entry); OnLearningModuleAdded(new LearningModuleAddedEventArgs(entry)); } catch (IOException exp) { Trace.WriteLine(exp.ToString()); } } foreach (string folder in Directory.GetDirectories(Path, "*", SearchOption.TopDirectoryOnly)) { try { FolderIndexEntry entry = CreateNewFolderEntry(folder); lock (content) content.Add(entry); OnFolderAdded(new FolderAddedEventArgs(entry)); } catch (IOException exp) { Trace.WriteLine(exp.ToString()); } } } else { foreach (IDictionary dic in currentUser.List().Dictionaries) { try { LearningModulesIndexEntry entry = CreateLerningModuleEntry(dic, currentUser); lock (content) content.Add(entry); OnLearningModuleAdded(new LearningModuleAddedEventArgs(entry)); } catch (IOException exp) { Trace.WriteLine(exp.ToString()); } } } } catch (Exception exp) { OnContentLoadException(this, exp); } finally { IsLoading = false; OnContentLoaded(this, EventArgs.Empty); } }
/// <summary> /// Handles the OnImportLearningModule event of the learningModulesTreeViewControl control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="MLifter.Controls.ImportLearningModuleEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev03, 2009-03-11</remarks> private void learningModulesTreeViewControl_OnImportLearningModule(object sender, ImportLearningModuleEventArgs e) { IConnectionString target = e.TreeNode.Connection; if (target.ConnectionType == DatabaseType.Web) { TaskDialog.MessageBox(Resources.STARTUP_IMPORT_LEARNING_MODULE_PERMISSION_MBX_CAPTION, Resources.STARTUP_IMPORT_LEARNING_MODULE_PERMISSION_MBX_TEXT, string.Empty, TaskDialogButtons.OK, TaskDialogIcons.Error); return; } if (e.LearningModule.ConnectionString.Typ == DatabaseType.Xml || DAL.Helper.IsOdfFormat(e.LearningModule.ConnectionString.ConnectionString)) { // open/convert instead of import if (target.ConnectionType == DatabaseType.Unc) { LearningModuleSelectedEventArgs args = new LearningModuleSelectedEventArgs(e.LearningModule); if (LearningModuleSelected != null) LearningModuleSelected(this, args); } else { DialogResult resultConvert = MLifter.Controls.TaskDialog.ShowTaskDialogBox(Resources.LEARNING_MODULES_PAGE_CONVERT_TITLE, Resources.LEARNING_MODULES_PAGE_CONVERT_MAIN, Resources.LEARNING_MODULES_PAGE_CONVERT_CONTENT, String.Empty, String.Empty, String.Empty, String.Empty, String.Format("{0}|{1}", Resources.LEARNING_MODULES_PAGE_CONVERT_OPTION_YES, Resources.LEARNING_MODULES_PAGE_CONVERT_OPTION_NO), MLifter.Controls.TaskDialogButtons.None, MLifter.Controls.TaskDialogIcons.Question, MLifter.Controls.TaskDialogIcons.Warning); switch (MLifter.Controls.TaskDialog.CommandButtonResult) { case 0: LearningModuleSelectedEventArgs args = new LearningModuleSelectedEventArgs(e.LearningModule); if (LearningModuleSelected != null) LearningModuleSelected(this, args); break; case 1: default: break; } } } else { DialogResult result = MLifter.Controls.TaskDialog.ShowTaskDialogBox(Resources.STARTUP_IMPORT_LEARNING_MODULE_MBX_CAPTION, Resources.STARTUP_IMPORT_LEARNING_MODULE_MBX_TEXT, String.Format(Resources.STARTUP_IMPORT_LEARNING_MODULE_CONTENT, target.Name), String.Empty, String.Empty, String.Empty, String.Empty, String.Format("{0}|{1}", Resources.STARTUP_IMPORT_LEARNING_MODULE_MBX_OPTION_YES, Resources.STARTUP_IMPORT_LEARNING_MODULE_MBX_OPTION_NO), MLifter.Controls.TaskDialogButtons.None, MLifter.Controls.TaskDialogIcons.Question, MLifter.Controls.TaskDialogIcons.Warning); switch (MLifter.Controls.TaskDialog.CommandButtonResult) { case 0: LearningModulesIndexEntry source = null; try { FolderIndexEntry folder = lmIndex.GetFolderOfConnection(target); learningModulesTreeViewControl.SetSelectedFolder(folder); conTarget = target; source = lmIndex.CreateLearningModuleIndexEntry(e.LearningModule.ConnectionString.ConnectionString); } catch (ServerOfflineException) { ShowServerOfflineMessage(new List<IConnectionString>() { target }, false); } catch (NoValidUserException) { // user pressed cancel on login dialog } catch { MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_LOCKED_TEXT, e.LearningModule.ConnectionString.ConnectionString), Properties.Resources.DIC_ERROR_LOADING_LOCKED_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } if (source == null) return; ImportLearningModule(source); break; case 1: default: selectedLearningModule = e.LearningModule; if (LearningModuleSelected != null) LearningModuleSelected(this, new LearningModuleSelectedEventArgs(e.LearningModule)); break; } } }
/// <summary> /// Loads the dictionary. /// </summary> /// <param name="entry">The entry.</param> /// <remarks>Documented by Dev02, 2009-06-26</remarks> public void LoadDictionary(LearningModulesIndexEntry entry) { if (MLifter.Program.MainForm.IsHandleCreated && !MLifter.Program.SuspendIPC) { MLifter.Program.MainForm.Invoke((MethodInvoker)delegate { try { //[ML-1126] Do not allow to open dictionaries when an edit form is still open MLifter.Program.MainForm.CloseLearningModulesPage(); if (!MLifter.Program.MainForm.OtherFormsOpen) MLifter.Program.MainForm.OpenEntry(entry); else throw new FormsOpenException(); } catch (Exception exp) { if (exp is FormsOpenException) throw; RemotingException(exp); } }); } else { MLifter.Program.MainForm.MainformLoaded += new EventHandler(delegate { LoadDictionary(entry); }); } }