Beispiel #1
0
        internal DbUser(UserStruct? user, ParentClass parent, ConnectionStringStruct connection, DataAccessErrorDelegate errorMessageDelegate, bool standAlone)
        {
            this.parent = parent;
            connectionString = connection;
            ErrorMessageDelegate = errorMessageDelegate;

            cache = new Cache(true);

            if (!user.HasValue)
                throw new NoValidUserException();

            this.authenticationStruct = user.Value;
            this.username = user.Value.UserName;
            this.hashedPassword = user.Value.Password;

            this.standAlone = standAlone;
            this.user = user;

            securityFramework = MLifter.DAL.Security.SecurityFramework.GetDataAdapter(this);
            if (username != null && securityFramework != null)
            {
                try
                {
                    securityToken = securityFramework.CreateSecurityToken(this.username);
                    securityToken.IsCaching = cachePermissions;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Failed to create security token! (" + ex.Message + ")");
                }
            }

            Login();
        }
Beispiel #2
0
        public static UserStruct? OpenLoginForm(UserStruct userStruct, ConnectionStringStruct connection)
        {
            LoginForm loginForm = new LoginForm();

            //select a server icon depending on connection type
            switch (connection.Typ)
            {
                case DatabaseType.Xml:
                case DatabaseType.Unc:
                case DatabaseType.MsSqlCe:
                    loginForm.ServerIcon = Resources.learning_48;
                    break;
                case DatabaseType.PostgreSQL:
                case DatabaseType.Web:
                    loginForm.ServerIcon = Resources.world_48;
                    break;
                default:
                    loginForm.ServerIcon = Resources.login_48;
                    break;
            }

            UserStruct? newUser = loginForm.AuthentificationControl.Initialize(connection, userStruct);

            if (newUser.HasValue)
                return newUser;

            if (loginForm.ShowDialog() == DialogResult.OK)
                return loginForm.SelectedUser;
            else
                return null;
        }
        /// <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;
        }
Beispiel #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebUser"/> class.
 /// </summary>
 /// <param name="userId">The user id.</param>
 /// <param name="authenticationStruct">The authentication struct.</param>
 /// <param name="connection">The connection.</param>
 /// <param name="service">The service.</param>
 /// <param name="parent">The parent.</param>
 /// <remarks>Documented by Dev05, 2009-03-06</remarks>
 internal WebUser(int userId, UserStruct authenticationStruct, ConnectionStringStruct connection, MLifterLearningModulesService service, ParentClass parent)
 {
     id = userId;
     authStruct = authenticationStruct;
     ConnectionString = connection;
     WebService = service;
     this.parent = parent;
 }
 /// <summary>
 /// Gets the security data adapter.
 /// </summary>
 /// <param name="connectionString">The connection string struct.</param>
 /// <returns></returns>
 /// <remarks>Documented by Dev03, 2009-01-14</remarks>
 internal static Framework GetDataAdapter(ConnectionStringStruct connectionString)
 {
     XmlSecurityDataAdapter adapter;
     //TODO implement data adapter code here
     //adapter = new DbSecurityDataAdapter();
     //test code using XmlSecurityDataAdapter
     adapter = new XmlSecurityDataAdapter("Resources\\XmlSecurityFramework.xml");
     return new SecurityFramework(adapter);
 }
Beispiel #6
0
        /// <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;
        }
Beispiel #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="User"/> class.
        /// </summary>
        /// <param name="getLoginInformation">A delegate used to collect login information (username/password).</param>
        /// <param name="connectionString">A struct containing the connection info.</param>
        /// <param name="errorMessageDelegate">A delegate used to handle login errors.</param>
        /// <param name="standAlone">if set to <c>true</c> [stand alone].</param>
        /// <remarks>Documented by Dev03, 2008-11-25</remarks>
        public User(GetLoginInformation getLoginInformation, ConnectionStringStruct connectionString, DataAccessErrorDelegate errorMessageDelegate, bool standAlone)
        {
            if (getLoginInformation == null)
                throw new ArgumentNullException();
            if (errorMessageDelegate == null)
                throw new ArgumentNullException();

            isStandAlone = standAlone;
            if (standAlone) standAloneId = Guid.NewGuid();
            connectionString.SessionId = standAlone ? standAloneId : sessionId;

            getLogin = getLoginInformation;
            ErrorMessageDelegate = errorMessageDelegate;
            user = new DummyUser(connectionString);

            switch (connectionString.Typ)
            {
                case DatabaseType.MsSqlCe:
                    user = GetCeUser(connectionString);
                    break;
                case DatabaseType.Web:
                    user = GetWebUser(connectionString);
                    break;
                case DatabaseType.Unc:
                    user = new UncUser(new XmlUser(connectionString, errorMessageDelegate), new DbUser(new UserStruct(), Parent, connectionString, errorMessageDelegate, standAlone), connectionString);
                    break;
                case DatabaseType.Xml:
                    user = new XmlUser(connectionString, errorMessageDelegate);
                    break;
                case DatabaseType.PostgreSQL:
                    user = GetDbUser(connectionString, errorMessageDelegate, standAlone);
                    break;
                default:
                    throw new UnsupportedDatabaseTypeException(connectionString.Typ);
            }
        }
        /// <summary>
        /// Handles the Click event of the buttonImport 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 Dev02, 2008-09-22</remarks>
        private void buttonImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            if (localLMOpenFilter != string.Empty)
                openDialog.Filter = localLMOpenFilter;
            if (localLMDirectory != string.Empty)
                openDialog.InitialDirectory = localLMDirectory;

            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                string filename = openDialog.FileName;
                ConnectionStringStruct connectionSource = new ConnectionStringStruct(DatabaseType.Xml, filename, true);

                int newLmId = dictionaries.AddNew(MLifter.DAL.Category.DefaultCategory, string.Empty).Id;
                ConnectionStringStruct connectionTarget = dictionaries.Parent.CurrentUser.ConnectionString;
                connectionTarget.LmId = newLmId;

                ShowStatusMessage(true);
                LearnLogic.CopyToFinished += new EventHandler(LearnLogic_CopyToFinished);
                try
                {
                    LearnLogic.CopyLearningModule(connectionSource, connectionTarget,
                        (GetLoginInformation)LoginForm.OpenLoginForm, (CopyToProgress)UpdateStatusMessage,
                        (DataAccessErrorDelegate)DataAccessError, m_learnLogic.User);
                }
                catch (DictionaryNotDecryptedException)
                {
                    HideStatusMessage();

                    //delete partially created dictionary
                    dictionaries.Delete(new ConnectionStringStruct(DatabaseType.PostgreSQL, string.Empty, newLmId));
                    UpdateList();

                    MessageBox.Show(Properties.Resources.DIC_ERROR_NOT_DECRYPTED_TEXT,
                        Properties.Resources.DIC_ERROR_NOT_DECRYPTED_CAPTION,
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (DictionaryContentProtectedException)
                {
                    HideStatusMessage();

                    //delete partially created dictionary
                    dictionaries.Delete(new ConnectionStringStruct(DatabaseType.PostgreSQL, string.Empty, newLmId));
                    UpdateList();

                    MessageBox.Show(string.Format(Properties.Resources.DIC_ERROR_CONTENTPROTECTED_TEXT, filename),
                        Properties.Resources.DIC_ERROR_CONTENTPROTECTED_CAPTION,
                        MessageBoxButtons.OK, MessageBoxIcon.Error);

                }
                catch (MLifter.DAL.InvalidDictionaryException)
                {
                    HideStatusMessage();

                    //delete partially created dictionary
                    dictionaries.Delete(new ConnectionStringStruct(DatabaseType.PostgreSQL, string.Empty, newLmId));
                    UpdateList();

                    MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_TEXT, filename),
                        Properties.Resources.DIC_ERROR_LOADING_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (System.Xml.XmlException)
                {
                    HideStatusMessage();

                    //delete partially created dictionary
                    dictionaries.Delete(new ConnectionStringStruct(DatabaseType.PostgreSQL, string.Empty, newLmId));
                    UpdateList();

                    MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_TEXT, filename),
                        Properties.Resources.DIC_ERROR_LOADING_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (System.IO.IOException)
                {
                    HideStatusMessage();

                    //delete partially created dictionary
                    dictionaries.Delete(new ConnectionStringStruct(DatabaseType.PostgreSQL, string.Empty, newLmId));
                    UpdateList();

                    MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_LOCKED_TEXT, filename),
                        Properties.Resources.DIC_ERROR_LOADING_LOCKED_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch
                {
                    HideStatusMessage();

                    //delete partially created dictionary
                    dictionaries.Delete(new ConnectionStringStruct(DatabaseType.PostgreSQL, string.Empty, newLmId));
                    UpdateList();

                    MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_TEXT, filename),
                        Properties.Resources.DIC_ERROR_LOADING_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
 /// <summary>
 /// Deletes a specific LM.
 /// </summary>
 /// <param name="css">The connection string struct.</param>
 public void Delete(ConnectionStringStruct css)
 {
     switch (css.Typ)
     {
         case DatabaseType.Xml:
             xmlDictionaries.Delete(css);
             break;
         case DatabaseType.PostgreSQL:
             throw new NotImplementedException();
         case DatabaseType.Unc:
             throw new NotImplementedException();
         case DatabaseType.MsSqlCe:
             dbDictionaries.Delete(css);
             break;
         default:
             throw new NotImplementedException();
     }
 }
 /// <summary>
 /// Deletes a specific LM.
 /// </summary>
 /// <param name="css">The connection string struct.</param>
 /// <remarks>Documented by Dev02, 2008-07-28</remarks>
 /// <remarks>Documented by Dev08, 2008-12-09</remarks>
 /// <remarks>Documented by Dev05, 2009-03-06</remarks>
 public void Delete(ConnectionStringStruct css)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Handles the Click event of the buttonExport 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 Dev02, 2008-09-22</remarks>
        private void buttonExport_Click(object sender, EventArgs e)
        {
            if (SelectedLMId >= 0)
            {
                SaveFileDialog saveDialog = new SaveFileDialog();
                if (localLMSaveFilter != string.Empty)
                    saveDialog.Filter = localLMSaveFilter;
                if (localLMDirectory != string.Empty)
                    saveDialog.InitialDirectory = localLMDirectory;

                saveDialog.FileName = listViewLMs.SelectedItems[0].Text;

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    ConnectionStringStruct connectionSource = dictionaries.Parent.CurrentUser.ConnectionString;
                    connectionSource.LmId = SelectedLMId;

                    string filename = saveDialog.FileName;
                    ConnectionStringStruct connectionTarget = new ConnectionStringStruct(DatabaseType.Xml, filename, true);

                    //delete target LM if it already exists (=overwrite it)
                    try
                    {
                        if (File.Exists(filename))
                            File.Delete(filename);
                    }
                    catch (System.IO.IOException)
                    {
                        MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_LOCKED_TEXT, filename),
                            Properties.Resources.DIC_ERROR_LOADING_LOCKED_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    ShowStatusMessage(false);
                    LearnLogic.CopyToFinished += new EventHandler(LearnLogic_CopyToFinished);
                    try
                    {
                        LearnLogic.CopyLearningModule(connectionSource, connectionTarget,
                            (GetLoginInformation)LoginForm.OpenLoginForm, (CopyToProgress)UpdateStatusMessage,
                            (DataAccessErrorDelegate)DataAccessError, m_learnLogic.User);
                    }
                    catch
                    {
                        HideStatusMessage();

                        //delete partially created dictionary
                        if (File.Exists(filename))
                            File.Delete(filename);

                        MessageBox.Show(String.Format(Properties.Resources.DIC_ERROR_LOADING_TEXT, filename),
                            Properties.Resources.DIC_ERROR_LOADING_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);

                    }
                }
            }
        }
Beispiel #12
0
 /// <summary>
 /// Sets the connection string.
 /// </summary>
 /// <param name="css">The CSS.</param>
 /// <remarks>Documented by Dev05, 2010-02-03</remarks>
 public void SetConnectionString(ConnectionStringStruct css)
 {
     connectionString = css;
 }
Beispiel #13
0
 internal XmlUser(ConnectionStringStruct connection, DataAccessErrorDelegate errorMessageDelegate)
 {
     connectionString = connection; ErrorMessageDelegate = errorMessageDelegate;
 }
Beispiel #14
0
        /// <summary>
        /// Gets the web user.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev05, 2009-03-06</remarks>
        private IUser GetWebUser(ConnectionStringStruct connection)
        {
            MLifterLearningModulesService webService = new MLifterLearningModulesService();
            webService.Url = connection.ConnectionString;
            webService.CookieContainer = new System.Net.CookieContainer();

            int uid = -1;
            UserStruct? user = null;

            do
            {
                user = getLogin.Invoke(user.HasValue ? user.Value : new UserStruct(), new ConnectionStringStruct(DatabaseType.Web, connection.ConnectionString, true));

                if (!user.HasValue)
                    break;
                else if (user.Value.AuthenticationType != UserAuthenticationTyp.ListAuthentication)
                    uid = webService.Login(user.Value.UserName, user.Value.Password);
                else
                    uid = webService.Login(user.Value.UserName, string.Empty);

                UserStruct lastUser = user.Value;
                try { Methods.CheckUserId(uid); lastUser.LastLoginError = LoginError.NoError; }
                catch (InvalidUsernameException) { lastUser.LastLoginError = LoginError.InvalidUsername; }
                catch (InvalidPasswordException) { lastUser.LastLoginError = LoginError.InvalidPassword; }
                catch (WrongAuthenticationException) { lastUser.LastLoginError = LoginError.WrongAuthentication; }
                catch (ForbiddenAuthenticationException) { lastUser.LastLoginError = LoginError.ForbiddenAuthentication; }
                catch (UserSessionCreationException) { lastUser.LastLoginError = LoginError.AlreadyLoggedIn; }
                user = lastUser;
            }
            while (user.HasValue && uid < 0);

            if (!user.HasValue)
                throw new NoValidUserException();

            return new WebUser(uid, user.Value, connection, webService, Parent);
        }
Beispiel #15
0
        /// <summary>
        /// Handles the CopyToFinished event of the LearnLogic 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 Dev05, 2008-12-15</remarks>
        void LearnLogic_CopyToFinished(object sender, EventArgs e)
        {
            HideStatusMessage();

            if (cleanUpOdx)
            {
                ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.Xml, Path.GetDirectoryName(odxFile), odxFile, true);
                IUser xmlUser = UserFactory.Create((GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { return u; },
                      css, DataAccessError, this);
                xmlUser.List().Delete(css);
            }
            else
            {
                FileInfo fi = new FileInfo(odxFile);
                if (File.Exists(odxFile + ".bak"))
                {
                    try
                    {
                        File.Delete(odxFile + ".bak");
                    }
                    catch { }
                }
                try
                {
                    fi.MoveTo(odxFile + ".bak");
                }
                catch { }
            }

            OnConvertedFinish(new ConvertingEventArgs(edbFile));
        }
Beispiel #16
0
 /// <summary>
 /// Sets the connection string.
 /// </summary>
 /// <param name="css">The CSS.</param>
 /// <remarks>Documented by Dev05, 2010-02-03</remarks>
 public void SetConnectionString(ConnectionStringStruct css)
 {
     user.SetConnectionString(css);
 }
Beispiel #17
0
 private UserStruct? GetUser(UserStruct user, ConnectionStringStruct connection)
 {
     return authenticationUsers[connection.ConnectionString];
 }
Beispiel #18
0
 /// <summary>
 /// Sets the connection string.
 /// </summary>
 /// <param name="newConnection">The new connection.</param>
 /// <remarks>Documented by Dev05, 2010-02-03</remarks>
 public void SetConnectionString(ConnectionStringStruct newConnection)
 {
     connectionString = newConnection;
 }
Beispiel #19
0
 /// <summary>
 /// Checks the connection and throws an exception depending on the error, if the connection is invalid.
 /// </summary>
 /// <param name="connection">The connection to test.</param>
 /// <remarks>Documented by Dev02, 2008-09-23</remarks>
 /// <remarks>Documented by Dev03, 2009-01-14</remarks>
 public void CheckConnection(ConnectionStringStruct connection)
 {
     Parent.CurrentUser.CheckConnection(connection);
 }
Beispiel #20
0
        /// <summary>
        /// Handles the Click event of the buttonStart 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 Dev02, 2008-03-17</remarks>
        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (BusinessLayer.WorkingThreadActive)
            {
                BusinessLayer.AbortWorkingThread();
                return;
            }

            textBoxLog.Clear();
            tracelistener.LogMessages.Clear();

            //check if input file exists
            if (!File.Exists(textBoxLearningModule.Text))
            {
                BusinessLayer.AddLog("The specified learning module file cannot be found");
                return;
            }

            //check if any audio fields are selected
            if (listViewPlaybackSequence.Items.Count == 0)
            {
                BusinessLayer.AddLog("Please select at least one field for the playback sequence");
                return;
            }

            IDictionary dictionary = null;
            try
            {
                AudioBookOptions options = new AudioBookOptions();

                //add mono/stereo selection to options
                options.Stereo = radioButtonStereo.Checked;

                //add selected fields to the options
                foreach (ListViewItem lvi in listViewPlaybackSequence.Items)
                {
                    MediaField mediafield = lvi.Tag as MediaField;
                    if (mediafield != null)
                        options.MediaFields.Add(mediafield);
                }

                //check for valid file paths
                FileInfo dictionaryfile = null, audiobook = null;
                try
                {
                    dictionaryfile = new FileInfo(textBoxLearningModule.Text);
                    audiobook = new FileInfo(textBoxAudiobook.Text);
                    if (string.IsNullOrEmpty(audiobook.Extension))
                    {
                        BusinessLayer.AddLog("Please enter a valid extension for the target audiobook file");
                        return;
                    }
                }
                catch
                {
                    BusinessLayer.AddLog("The specified file paths are not valid. Please check your input");
                    return;
                }

                //save file paths to settings as recent files
                Settings.Default.RecentLearningModule = dictionaryfile.FullName;
                Settings.Default.RecentAudioBook = audiobook.FullName;
                Settings.Default.Save();

                //open learning module and start audio book generation
                try
                {
                    ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.MsSqlCe, dictionaryfile.FullName);
                    MLifter.DAL.Interfaces.IUser user = UserFactory.Create((GetLoginInformation)MLifter.Controls.LoginForm.OpenLoginForm, css, (DataAccessErrorDelegate)delegate { return; }, this);
                    css.LmId = User.GetIdOfLearningModule(dictionaryfile.FullName, user);
                    user.ConnectionString = css;
                    dictionary = user.Open();
                }
                catch (System.IO.IOException)
                {
                    BusinessLayer.AddLog("The Learning Module file could not be accessed. Please make sure that it is not open within another program (e.g. MemoryLifter)");
                    return;
                }
                catch (System.Xml.XmlException)
                {
                    BusinessLayer.AddLog("The Learning Module file does not seem to be in a valid format");
                    return;
                }
                catch (ProtectedLearningModuleException)
                {
                    BusinessLayer.AddLog("The Learning Module could not be opened: It is content protected");
                    return;
                }
                catch (Exception exp)
                {
                    BusinessLayer.AddLog("The Learning Module file could not be opened:" + Environment.NewLine + exp.Message);
                    return;
                }
                buttonStart.Text = "Cancel";
                BusinessLayer.GenerateAudioBook(dictionary, audiobook, options, codecs);
            }
            catch (Exception exp)
            {
                BusinessLayer.AddLog("Audio book generation exception happened: " + Environment.NewLine + exp.ToString());
                return;
            }
            finally
            {
                if (dictionary != null)
                    dictionary.Dispose();
            }
        }
Beispiel #21
0
        /// <summary>
        /// Gets the id of a learning module.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="user">The user.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        /// <remarks>
        /// Documented by CFI, 2009-03-06
        /// </remarks>
        public static int GetIdOfLearningModule(string path, IUser user, string password)
        {
            if (!path.EndsWith(Helper.EmbeddedDbExtension))
                return -1;

            int lmId = -1;
            try
            {
                ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.MsSqlCe, path, -1);
                css.Password = password;
                IList<int> ids = DbDictionaries.GetConnector(new ParentClass(new DbUser(user.AuthenticationStruct, user.Parent, css, user.ErrorMessageDelegate, true), null)).GetLMIds();
                if (ids.Count == 0)
                    return -1;
                lmId = ids[0];
            }
            catch (ProtectedLearningModuleException) { throw; }
            catch (Exception ex) { Debug.WriteLine("DbDictionaries.Dictionaries - " + ex.Message); }
            return lmId;
        }
Beispiel #22
0
        public void CopyToBasicTest()
        {
            //Perform Test only if we use a db connection otherwise test case makes no sense
            if (TestInfrastructure.IsActive(TestContext) && TestInfrastructure.ConnectionType(TestContext) != "File")
            {
                IUser sourceUser = null;
                IUser targetUser = null;
                try
                {
                    string repositoryNameFinal = "finalTargetForCopyTest" + System.Environment.MachineName.ToLower();

                    //Do we have a target to copy from
                    Assert.IsTrue(File.Exists(TestDic), "Test Learning Module file cannot be found.");
                    ConnectionStringStruct sourceConnection = new ConnectionStringStruct(DatabaseType.Xml, CopyToTest.TestDic, false);
                    sourceUser = UserFactory.Create((GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { return u; },
                        sourceConnection, (DataAccessErrorDelegate)delegate { return; }, this);
                    if (!authenticationUsers.ContainsKey(sourceConnection.ConnectionString))
                        authenticationUsers.Add(sourceConnection.ConnectionString, sourceUser.AuthenticationStruct);

                    //Copy the reference LM to the new persistent LM
                    ConnectionStringStruct dbConnection;
                    using (Dictionary dbTarget = TestInfrastructure.GetConnection(TestContext))
                    {
                        IUser dbUser = dbTarget.DictionaryDAL.Parent.CurrentUser;
                        dbConnection = dbUser.ConnectionString;
                        if (!authenticationUsers.ContainsKey(dbConnection.ConnectionString))
                            authenticationUsers.Add(dbConnection.ConnectionString, dbUser.AuthenticationStruct);
                        dbTarget.Dispose();

                        finished = false;
                        LearnLogic.CopyToFinished += new EventHandler(LearnLogic_CopyToFinished);
                        LearnLogic.CopyLearningModule(sourceConnection, dbConnection,
                            GetUser, (MLifter.DAL.Tools.CopyToProgress)delegate(string m, double p) { return; }, (DataAccessErrorDelegate)delegate { return; }, null);
                        while (!finished) { System.Threading.Thread.Sleep(100); };
                        LearnLogic.CopyToFinished -= new EventHandler(LearnLogic_CopyToFinished);
                    }

                    //copy to another persistent LM where we use Save to store as odx again
                    ConnectionStringStruct targetConnection;
                    using (Dictionary target = TestInfrastructure.GetPersistentLMConnection(TestContext, "sqlce"))
                    {
                        targetUser = target.DictionaryDAL.Parent.CurrentUser;
                        targetConnection = targetUser.ConnectionString;
                        if (!authenticationUsers.ContainsKey(targetConnection.ConnectionString))
                            authenticationUsers.Add(targetConnection.ConnectionString, targetUser.AuthenticationStruct);
                        target.Dispose();

                        finished = false;
                        LearnLogic.CopyToFinished += new EventHandler(LearnLogic_CopyToFinished);
                        LearnLogic.CopyLearningModule(dbConnection, targetConnection,
                            GetUser, (MLifter.DAL.Tools.CopyToProgress)delegate(string m, double p) { return; }, (DataAccessErrorDelegate)delegate { return; }, null);
                        while (!finished) { System.Threading.Thread.Sleep(100); };
                        LearnLogic.CopyToFinished -= new EventHandler(LearnLogic_CopyToFinished);
                    }

                    using (Dictionary source = new Dictionary(sourceUser.Open(), null))
                    using (Dictionary target = new Dictionary(targetUser.Open(), null))
                    {
                        CompareChapters(source.Chapters.Chapters, target.Chapters.Chapters);

                        //Verification Code compare finalTarget with the reference target
                        CompareCards(source.Cards.Cards, target.Cards.Cards, source, target);

                        //Compare Settings
                        CompareSettings(source.Settings, target.Settings);
                        if ((source.Settings != null) && (target.Settings != null))
                        {
                            //Compare Styles
                            CompareStyles(source.Settings.Style, target.Settings.Style);
                        }
                    }
                }
                finally
                {
                    if (sourceUser != null)
                        sourceUser.Logout();
                    if (targetUser != null)
                        targetUser.Logout();
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Checks the connection.
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        /// <remarks>Documented by Dev03, 2008-11-27</remarks>
        public void CheckConnection(ConnectionStringStruct connectionString)
        {
            if (!dbConnectionValid && connectionString.Typ != DatabaseType.Xml)
            {
                DummyUser user = new DummyUser(connectionString);
                DbConnection con = connectionString.Typ == DatabaseType.PostgreSQL ? PostgreSQLConn.CreateConnection(user) as DbConnection : MSSQLCEConn.GetConnection(user) as DbConnection;

                if (con.State == System.Data.ConnectionState.Open)
                    dbConnectionValid = true;
                else
                    throw new ConnectionInvalidException();

                if (connectionString.Typ == DatabaseType.PostgreSQL)
                    con.Close();

                DbDatabase.GetInstance(new ParentClass(new DummyUser(connectionString), this)).CheckIfDatabaseVersionSupported();
            }
        }
Beispiel #24
0
        /// <summary>
        /// Converts an ODX to an eDB file.
        /// </summary>
        /// <param name="filename">The filename.</param>
        /// <param name="cleanup">if set to <c>true</c> [cleanup].</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev05, 2009-03-02</remarks>
        internal string FromOdx(string filename, bool cleanup)
        {
            if (filename == (string)null) throw new ArgumentNullException("filename");
            if (filename.Length == 0) throw new ArgumentException("filename");
            try
            {
                ShowStatusMessage();
                odxFile = filename;
                cleanUpOdx = cleanup;
                IUser xmlUser = UserFactory.Create((GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { return u; },
                    new ConnectionStringStruct(DatabaseType.Xml, Path.GetDirectoryName(filename), filename, true), DataAccessError, this);

                IDictionary oldDic = xmlUser.Open();

                IUser dbUser = UserFactory.Create((GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { return u; },
                    new ConnectionStringStruct(DatabaseType.Unc, Path.GetDirectoryName(filename), Path.ChangeExtension(filename, Helper.EmbeddedDbExtension), true), DataAccessError, this);

                IDictionary newDic = dbUser.List().AddNew(oldDic.Category.Id > 5 ? 3 : oldDic.Category.Id, oldDic.Title);

                ConnectionStringStruct oldCon = new ConnectionStringStruct(DatabaseType.Xml, filename);
                ConnectionStringStruct newCon = new ConnectionStringStruct(DatabaseType.MsSqlCe, newDic.Connection, newDic.Id);
                edbFile = newCon.ConnectionString;

                oldDic.Dispose();
                newDic.Dispose();

                LearnLogic.CopyToFinished += new EventHandler(LearnLogic_CopyToFinished);
                LearnLogic.CopyLearningModule(oldCon, newCon, (GetLoginInformation)delegate(UserStruct u, ConnectionStringStruct c) { return u; }, UpdateStatusMessage, DataAccessError, null);

                return newCon.ConnectionString;
            }
            catch { HideStatusMessage(); throw; }
        }
Beispiel #25
0
        /// <summary>
        /// Gets the Compact Edition user.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev05, 2009-01-13</remarks>
        private IUser GetCeUser(ConnectionStringStruct connection)
        {
            int userId;
            UserStruct? userStruct = null;
            List<UserStruct> users = connector.GetUserList() as List<UserStruct>;
            if (connection.SyncType != SyncType.NotSynchronized)
            {
                if (connection.SyncType == SyncType.FullSynchronized && connection.ServerUser == null)
                {
                    if (users.Count == 2)
                    {
                        userStruct = users[1];
                        userId = connector.LoginListUser(userStruct.Value.UserName, Guid.NewGuid(), true, true);
                    }
                    else
                    {
                        UserStruct? us = getLogin.Invoke(new UserStruct(Resources.CREATE_NEW_USER, UserAuthenticationTyp.ListAuthentication), connection);
                        if (!us.HasValue || us.Value.UserName == Resources.CREATE_NEW_USER)
                            userId = connector.LoginFormsUser(CurrentWindowsUserName, CurrentWindowsUserId, new Guid(), true, true);
                        else
                            userId = connector.LoginLocalDirectoryUser(us.Value.UserName, CurrentWindowsUserId, new Guid(), true, true);
                    }
                }
                else
                {
                    userStruct = users.Find(u => u.UserName == connection.ServerUser.UserName);
                    userId = connector.LoginListUser(userStruct.Value.UserName, connection.ServerUser.ConnectionString.SessionId, true, true);
                }
            }
            else if (Methods.IsOnMLifterStick(connection.ConnectionString))
            {
                if (users.Exists(u => u.UserName == Resources.StickUserName))
                {
                    userStruct = users.Find(u => u.UserName == Resources.StickUserName);
                    userId = connector.LoginListUser(Resources.StickUserName, new Guid(), true, true);
                }
                else
                {
                    userStruct = new UserStruct(Resources.StickUserName, UserAuthenticationTyp.ListAuthentication);
                    userId = connector.LoginFormsUser(Resources.StickUserName, string.Empty, new Guid(), true, true);
                }
            }
            else if (users.Exists(u => u.Identifier == CurrentWindowsUserId))
            {
                userStruct = users.Find(u => u.Identifier == CurrentWindowsUserId);
                userId = connector.LoginListUser(userStruct.Value.UserName, new Guid(), true, true);
            }
            else if (users.Count == 1)
                userId = connector.LoginFormsUser(CurrentWindowsUserName, CurrentWindowsUserId, new Guid(), true, true);
            else
            {
                UserStruct? us = getLogin.Invoke(new UserStruct(Resources.CREATE_NEW_USER, UserAuthenticationTyp.ListAuthentication), connection);
                if (!us.HasValue || us.Value.UserName == Resources.CREATE_NEW_USER)
                    userId = connector.LoginFormsUser(CurrentWindowsUserName, CurrentWindowsUserId, new Guid(), true, true);
                else
                    userId = connector.LoginLocalDirectoryUser(us.Value.UserName, CurrentWindowsUserId, new Guid(), true, true);
            }

            if (!userStruct.HasValue)
                userStruct = new UserStruct(CurrentWindowsUserName, UserAuthenticationTyp.ListAuthentication);

            DbUser newUser = new DbUser(userStruct, Parent, connection, errMsgDel, true);
            newUser.SetId(userId);
            return newUser;
        }
        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;
            }
        }
Beispiel #27
0
        /// <summary>
        /// Gets the db user.
        /// </summary>
        /// <param name="connection">A struct containing the connection info.</param>
        /// <param name="errorMessageDelegate">A delegate used to handle login errors.</param>
        /// <param name="standAlone">if set to <c>true</c> [stand alone].</param>
        /// <returns>A DB user which implements IUser</returns>
        /// <remarks>Documented by Dev03, 2008-11-25</remarks>
        private IUser GetDbUser(ConnectionStringStruct connection, DataAccessErrorDelegate errorMessageDelegate, bool standAlone)
        {
            CheckConnection(connection);

            UserAuthenticationTyp authTyp = connector.GetAllowedAuthenticationModes().Value;

            bool ldUserChecked = false;
            IUser dbUser = null;
            UserStruct? userStruct = null;
            while (dbUser == null)
            {
                if (!IsWebService && !ldUserChecked && (authTyp & UserAuthenticationTyp.LocalDirectoryAuthentication) == UserAuthenticationTyp.LocalDirectoryAuthentication)
                {
                    ldUserChecked = true;
                    try { userStruct = GetLocalDirectoryUser(); }
                    catch (NoValidUserException) { userStruct = null; }
                }
                else
                    userStruct = getLogin.Invoke(userStruct.HasValue ? userStruct.Value : new UserStruct(string.Empty, authTyp), ConnectionString);

                if (userStruct.HasValue)
                {
                    UserStruct lastUser = userStruct.Value;
                    try { dbUser = new DbUser(userStruct, Parent, connection, errorMessageDelegate, standAlone); lastUser.LastLoginError = LoginError.NoError; }
                    catch (InvalidUsernameException) { lastUser.LastLoginError = LoginError.InvalidUsername; }
                    catch (InvalidPasswordException) { lastUser.LastLoginError = LoginError.InvalidPassword; }
                    catch (WrongAuthenticationException) { lastUser.LastLoginError = LoginError.WrongAuthentication; }
                    catch (ForbiddenAuthenticationException) { lastUser.LastLoginError = LoginError.ForbiddenAuthentication; }
                    catch (UserSessionCreationException) { lastUser.LastLoginError = LoginError.AlreadyLoggedIn; }
                    userStruct = lastUser;
                }
                else
                    throw new NoValidUserException();
            }

            return dbUser;
        }
 private static UserStruct? GetUser(UserStruct user, ConnectionStringStruct connection)
 {
     if (!MLifter.BusinessLayer.User.PreventAutoLogin && authenticationUsers.ContainsKey(connection.ConnectionString) && (!defaultUserSubmitted.ContainsKey(connection) || !defaultUserSubmitted[connection]))
     {
         defaultUserSubmitted[connection] = true;
         return authenticationUsers[connection.ConnectionString];
     }
     else
     {
         UserStruct? newUser = LoginForm.OpenLoginForm(user, connection);
         if (newUser.HasValue)
             authenticationUsers[connection.ConnectionString] = newUser.Value;
         return newUser;
     }
 }
Beispiel #29
0
 /// <summary>
 /// Deletes a specific LM.
 /// </summary>
 /// <param name="css">The connection string struct.</param>
 /// <remarks>Documented by Dev02, 2008-07-28</remarks>
 /// <remarks>Documented by Dev08, 2008-12-09</remarks>
 /// <remarks>Documented by Dev08, 2008-12-09</remarks>
 public void Delete(ConnectionStringStruct css)
 {
     if (!this.HasPermission(PermissionTypes.CanModify))
         throw new PermissionException();
     switch (css.Typ)
     {
         case DatabaseType.PostgreSQL:
             parent.CurrentUser.CheckConnection(parent.CurrentUser.ConnectionString);
             connector.DeleteLM(css.LmId);
             break;
         case DatabaseType.MsSqlCe:
             //MSSQLCEConn.CloseAllConnections();
             MSSQLCEConn.CloseMyConnection(css.ConnectionString);        //[ML-1939] "Delete" of EDB needs very long time
             File.Delete(css.ConnectionString);
             break;
         default:
             throw new UnsupportedDatabaseTypeException(css.Typ);
     }
 }
Beispiel #30
0
 /// <summary>
 /// Checks the connection and throws an exception depending on the error, if the connection is invalid.
 /// </summary>
 /// <param name="connection">The connection to test.</param>
 /// <remarks>Documented by Dev02, 2008-09-23</remarks>
 /// <remarks>Documented by Dev03, 2009-01-14</remarks>
 public void CheckConnection(ConnectionStringStruct connection)
 {
     throw new NotImplementedException("This method or operation is not implemented.");
 }