Пример #1
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        internal static Exception GetBetterException(Exception e, AccessConnectionHolder holder)
        {
            try
            {
                if (!(e is SqlException) || holder.Connection == null ||
                    holder.Connection.DataSource == null || holder.Connection.DataSource.Length < 1)
                {
                    return(e);
                }
                if (!File.Exists(holder.Connection.DataSource))
                {
                    return(new FileNotFoundException(String.Empty, holder.Connection.DataSource, e));
                }
            }
            finally
            {
                if (holder.Connection != null)
                {
                    holder.Connection.Close();
                }
            }

            FileStream s      = null;
            Exception  eWrite = null;

            try
            {
                s = File.OpenWrite(holder.Connection.DataSource);
            }
            catch (Exception except)
            {
                eWrite = except;
            }
            finally
            {
                if (s != null)
                {
                    s.Close();
                }
            }
            if (eWrite != null && (eWrite is UnauthorizedAccessException))
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    context.Response.Clear();
                    context.Response.StatusCode = 500;
                    context.Response.Write("Cannot write to DB File");
                    context.Response.End();
                }
                return(new Exception("AccessFile is not writtable", eWrite));
            }
            return(e);
        }
Пример #2
0
        public override bool ValidateUser(string username, string password)
        {
            if (!SecUtility.ValidateParameter(ref username,
                                              true,
                                              true,
                                              false,
                                              255))
            {
                return(false);
            }

            if (!SecUtility.ValidateParameter(ref password,
                                              true,
                                              true,
                                              false,
                                              128))
            {
                return(false);
            }

            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_databaseFileName, true);
            SqlConnection          connection = holder.Connection;

            try
            {
                try
                {
                    int appId  = GetAppplicationId(holder);
                    int userId = MyConnectionHelper.GetUserID(connection, appId, username, false);
                    if (CheckPassword(connection, userId, password))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (Exception e)
                {
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }
Пример #3
0
        public override string[] GetAllRoles()
        {
            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_DatabaseFileName, true);
            SqlConnection          connection = holder.Connection;
            SqlDataReader          reader     = null;

            try
            {
                try
                {
                    int              appId = GetApplicationId(holder);
                    SqlCommand       command;
                    StringCollection sc        = new StringCollection();
                    String[]         strReturn = null;

                    command = new SqlCommand(@"SELECT RoleName FROM Roles ORDER BY RoleName", connection);
                    reader  = command.ExecuteReader(CommandBehavior.SequentialAccess);
                    while (reader.Read())
                    {
                        sc.Add(reader.GetString(0));
                    }
                    strReturn = new String[sc.Count];
                    sc.CopyTo(strReturn, 0);
                    return(strReturn);
                }
                catch (Exception e)
                {
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }
Пример #4
0
        private int GetApplicationId(AccessConnectionHolder holder)
        {
            if (_ApplicationId != 0 && holder.CreateDate < _ApplicationIDCacheDate) // Already cached?
            {
                return(_ApplicationId);
            }
            string appName = _AppName;

            if (appName.Length > 255)
            {
                appName = appName.Substring(0, 255);
            }
            _ApplicationId          = 10011;
            _ApplicationIDCacheDate = DateTime.Now;
            if (_ApplicationId != 0)
            {
                return(_ApplicationId);
            }
            throw new ProviderException("sorry exception in GetApplicationId");
        }
Пример #5
0
        public override bool RoleExists(string roleName)
        {
            try
            {
                SecUtility.CheckParameter(ref roleName, true, true, true, 255, "roleName");
            }
            catch
            {
                return(false);
            }
            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_DatabaseFileName, true);
            SqlConnection          connection = holder.Connection;

            try
            {
                try
                {
                    int appId  = GetApplicationId(holder);
                    int roleId = GetRoleId(connection, appId, roleName);

                    return(roleId != 0);
                }
                catch (Exception e)
                {
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }
Пример #6
0
        public override void CreateRole(string roleName)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, 255, "roleName");

            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_DatabaseFileName, true);
            SqlConnection          connection = holder.Connection;

            try
            {
                try
                {
                    int        appId = GetApplicationId(holder);
                    SqlCommand command;
                    command = new SqlCommand(@"INSERT INTO Roles (RoleName) VALUES (@RName)", connection);
                    command.Parameters.Add(new SqlParameter("@RName", roleName));
                    int returnValue = command.ExecuteNonQuery();
                    if (returnValue == 1)
                    {
                        return;
                    }
                    throw new ProviderException("Unknown provider failure");
                }
                catch (Exception e)
                {
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }
Пример #7
0
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            SecUtility.CheckArrayParameter(ref roleNames, true, true, true, 255, "roleNames");
            SecUtility.CheckArrayParameter(ref usernames, true, true, true, 255, "usernames");

            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_DatabaseFileName, true);
            SqlConnection          connection = holder.Connection;
            bool fBeginTransCalled            = false;

            try
            {
                try
                {
                    int   appId   = GetApplicationId(holder);
                    int[] userIds = new int[usernames.Length];
                    int[] roleIds = new int[roleNames.Length];

                    SqlCommand command;

                    for (int iterR = 0; iterR < roleNames.Length; iterR++)
                    {
                        roleIds[iterR] = GetRoleId(connection, appId, roleNames[iterR]);
                        if (roleIds[iterR] == 0)
                        {
                            throw new ProviderException("Provider role not found: " + roleNames[iterR]);
                        }
                    }
                    for (int iterU = 0; iterU < usernames.Length; iterU++)
                    {
                        userIds[iterU] = MyConnectionHelper.GetUserID(connection, appId, usernames[iterU], false);
                    }
                    command = new SqlCommand("BEGIN TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    fBeginTransCalled = true;

                    for (int iterU = 0; iterU < usernames.Length; iterU++)
                    {
                        if (userIds[iterU] == 0)
                        {
                            continue;
                        }
                        for (int iterR = 0; iterR < roleNames.Length; iterR++)
                        {
                            command = new SqlCommand(@"SELECT UserId FROM UsersInRoles WHERE UserId = @UserId AND RoleId = @RoleId",
                                                     connection);
                            command.Parameters.Add(new SqlParameter("@UserId", userIds[iterU]));
                            command.Parameters.Add(new SqlParameter("@RoleId", roleIds[iterR]));

                            object result = command.ExecuteScalar();
                            if (result != null && (result is int) && ((int)result) == userIds[iterU])
                            { // Exists!
                                throw new ProviderException("The user " + usernames[iterU] + " is already in role " + roleNames[iterR]);
                            }
                        }
                    }

                    for (int iterU = 0; iterU < usernames.Length; iterU++)
                    {
                        if (userIds[iterU] == 0)
                        {
                            userIds[iterU] = MyConnectionHelper.GetUserID(connection, appId, usernames[iterU], true);
                        }
                        if (userIds[iterU] == 0)
                        {
                            throw new ProviderException("User not found: " + usernames[iterU]);
                        }
                    }
                    for (int iterU = 0; iterU < usernames.Length; iterU++)
                    {
                        for (int iterR = 0; iterR < roleNames.Length; iterR++)
                        {
                            command = new SqlCommand(@"INSERT INTO UsersInRoles (UserId, RoleId) VALUES(@UserId, @RoleId)",
                                                     connection);
                            command.Parameters.Add(new SqlParameter("@UserId", userIds[iterU]));
                            command.Parameters.Add(new SqlParameter("@RoleId", roleIds[iterR]));

                            if (command.ExecuteNonQuery() != 1)
                            {
                                throw new ProviderException("Unknown provider failure");
                            }
                        }
                    }
                    command = new SqlCommand("COMMIT TRANSACTION", connection);
                    command.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    try
                    {
                        if (fBeginTransCalled)
                        {
                            SqlCommand command = new SqlCommand("ROLLBACK TRANSACTION", connection);
                            command.ExecuteNonQuery();
                        }
                    }
                    catch { }
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }
Пример #8
0
        public override string[] GetRolesForUser(string username)
        {
            SecUtility.CheckParameter(ref username, true, false, true, 255, "username");
            if (username.Length < 1)
            {
                return(new string[0]);
            }

            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_DatabaseFileName, true);
            SqlConnection          connection = holder.Connection;
            SqlDataReader          reader     = null;

            try
            {
                try
                {
                    int appId  = GetApplicationId(holder);
                    int userId = MyConnectionHelper.GetUserID(connection, appId, username, false);

                    if (userId == 0)
                    {
                        return(new string[0]);
                    }

                    SqlCommand       command;
                    StringCollection sc = new StringCollection();
                    String[]         strReturn;


                    command = new SqlCommand(@"SELECT RoleName FROM UsersInRoles ur, Roles r " +
                                             @"WHERE ur.UserId = @UserId AND ur.RoleId = r.RoleId " +
                                             @"ORDER BY RoleName",
                                             connection);
                    command.Parameters.Add(new SqlParameter("@UserId", userId));
                    reader = command.ExecuteReader(CommandBehavior.SequentialAccess);
                    while (reader.Read())
                    {
                        sc.Add(reader.GetString(0));
                    }
                    strReturn = new String[sc.Count];
                    sc.CopyTo(strReturn, 0);
                    return(strReturn);
                }
                catch (Exception e)
                {
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }
Пример #9
0
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, 255, "roleName");
            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_DatabaseFileName, true);
            SqlConnection          connection = holder.Connection;
            bool fBeginTransCalled            = false;

            try
            {
                try
                {
                    int        appId = GetApplicationId(holder);
                    SqlCommand command;
                    int        roleId = GetRoleId(connection, appId, roleName);

                    if (roleId == 0)
                    {
                        return(false);
                    }

                    if (throwOnPopulatedRole)
                    {
                        command = new SqlCommand(@"SELECT COUNT(*) " +
                                                 @"FROM UsersInRoles ur, Users u " +
                                                 @"WHERE ur.RoleId = @RoleId AND ur.UserId = u.UserId",
                                                 connection);

                        command.Parameters.Add(new SqlParameter("@RoleId", roleId));
                        object num = command.ExecuteScalar();
                        if (!(num is int) || ((int)num) != 0)
                        {
                            throw new ProviderException("Role is not empty");
                        }
                    }

                    command = new SqlCommand("BEGIN TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    fBeginTransCalled = true;
                    command           = new SqlCommand(@"DELETE FROM Roles WHERE RoleId = @RoleId", connection);
                    command.Parameters.Add(new SqlParameter("@RoleId", roleId));
                    int returnValue = command.ExecuteNonQuery();
                    command = new SqlCommand("COMMIT TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    fBeginTransCalled = false;

                    return(returnValue == 1);
                }
                catch (Exception e)
                {
                    if (fBeginTransCalled)
                    {
                        try
                        {
                            SqlCommand command = new SqlCommand("ROLLBACK TRANSACTION", connection);
                            command.ExecuteNonQuery();
                        }
                        catch { }
                    }
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }
Пример #10
0
 private int GetAppplicationId(AccessConnectionHolder holder)
 {
     if (_applicationId != 0 && holder.CreateDate < _applicationIdCacheDate) // Already cached?
         return _applicationId;
     string appName = _appName;
     if (appName.Length > 255)
         appName = appName.Substring(0, 255);
     _applicationId = 10011;
     _applicationIdCacheDate = DateTime.Now;
     if (_applicationId != 0)
         return _applicationId;
     throw new ProviderException("sorry exception in GetApplicationId");
 }
Пример #11
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        internal static Exception GetBetterException(Exception e, AccessConnectionHolder holder)
        {
            try
            {
                if (!(e is SqlException) || holder.Connection == null ||
                    holder.Connection.DataSource == null || holder.Connection.DataSource.Length < 1)
                {
                    return e;
                }
                if (!File.Exists(holder.Connection.DataSource))
                {
                    return new FileNotFoundException(String.Empty, holder.Connection.DataSource, e);
                }
            }
            finally
            {
                if (holder.Connection != null)
                    holder.Connection.Close();
            }

            FileStream s = null;
            Exception eWrite = null;
            try
            {
                s = File.OpenWrite(holder.Connection.DataSource);
            }
            catch (Exception except)
            {
                eWrite = except;
            }
            finally
            {
                if (s != null)
                    s.Close();
            }
            if (eWrite != null && (eWrite is UnauthorizedAccessException))
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    context.Response.Clear();
                    context.Response.StatusCode = 500;
                    context.Response.Write("Cannot write to DB File");
                    context.Response.End();
                }
                return new Exception("AccessFile is not writtable", eWrite);
            }
            return e;
        }
Пример #12
0
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            if (pageIndex < 0)
            {
                throw new ArgumentException("PageIndex cannot be negative");
            }
            if (pageSize < 1)
            {
                throw new ArgumentException("PageSize must be positive");
            }

            long lBound = (long)pageIndex * pageSize;
            long uBound = lBound + pageSize - 1;

            if (uBound > System.Int32.MaxValue)
            {
                throw new ArgumentException("PageIndex too big");
            }

            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_databaseFileName, true);
            SqlConnection          connection = holder.Connection;
            SqlDataReader          reader     = null;
            long recordCount = 0;

            try
            {
                try
                {
                    int        appId = GetAppplicationId(holder);
                    SqlCommand command;
                    MembershipUserCollection users = new MembershipUserCollection();

                    command = new SqlCommand(@"SELECT UserName,UserID  from Users ORDER BY UserName", connection);
                    //command.Parameters.Add(new SqlParameter("@AppId", appId));

                    reader = command.ExecuteReader(CommandBehavior.SequentialAccess);

                    while (reader.Read())
                    {
                        recordCount++;
                        if (recordCount - 1 < lBound || recordCount - 1 > uBound)
                        {
                            continue;
                        }
                        string   username, email, passwordQuestion, comment;
                        DateTime dtCreate, dtLastLogin, dtLastActivity, dtLastPassChange;
                        bool     isApproved;
                        int      userId;
                        username         = GetNullableString(reader, 0);
                        email            = "";           //GetNullableString(reader, 1);
                        passwordQuestion = "";           //GetNullableString(reader, 2);
                        comment          = "";           //GetNullableString(reader, 3);
                        dtCreate         = DateTime.Now; //reader.GetDateTime(4);
                        dtLastLogin      = DateTime.Now; //reader.GetDateTime(5);
                        dtLastActivity   = DateTime.Now; //reader.GetDateTime(6);
                        dtLastPassChange = DateTime.Now; //reader.GetDateTime(7);
                        isApproved       = true;         //reader.GetBoolean(8);
                        userId           = reader.GetInt32(1);
                        users.Add(new MembershipUser("LMSMembershipProvider",
                                                     username,
                                                     userId,
                                                     email,
                                                     passwordQuestion,
                                                     comment,
                                                     isApproved,
                                                     false,
                                                     dtCreate,
                                                     dtLastLogin,
                                                     dtLastActivity,
                                                     dtLastPassChange,
                                                     DateTime.MinValue));
                    }
                    totalRecords = (int)recordCount;
                    return(users);
                }
                catch (Exception e)
                {
                    throw new Exception("Exception in creating users Collection", e);
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    holder.Close();
                }
            }
            catch (Exception e)
            {
                throw new Exception("Exception on line 490: ", e);
            }
        }
Пример #13
0
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            SecUtility.CheckParameter(ref username, true, true, true, 255, "username");

            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_databaseFileName, true);
            SqlConnection          connection = holder.Connection;
            bool fBeginTransCalled            = false;

            try
            {
                try
                {
                    int appId  = GetAppplicationId(holder);
                    int userId = MyConnectionHelper.GetUserID(connection, appId, username, false);

                    if (userId == 0)
                    {
                        return(false); // User not found
                    }
                    SqlCommand command;

                    //
                    // Start transaction
                    //

                    command = new SqlCommand("BEGIN TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    fBeginTransCalled = true;

                    bool returnValue = false;
                    if (deleteAllRelatedData)
                    {
                        command = new SqlCommand(@"DELETE FROM UsersInRoles WHERE UserId = @UserId", connection);
                        command.Parameters.Add(new SqlParameter("@UserId", userId));
                        command.ExecuteNonQuery();

                        command = new SqlCommand(@"DELETE FROM Users WHERE UserId = @UserId", connection);
                        command.Parameters.Add(new SqlParameter("@UserId", userId));
                        returnValue = (command.ExecuteNonQuery() == 1);
                    }

                    //
                    // End transaction
                    //

                    command = new SqlCommand("COMMIT TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    fBeginTransCalled = false;

                    return(returnValue);
                }
                catch (Exception e)
                {
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    if (fBeginTransCalled)
                    {
                        try
                        {
                            SqlCommand cmd = new SqlCommand("ROLLBACK TRANSACTION",
                                                            connection);
                            cmd.ExecuteNonQuery();
                        }
                        catch { }
                    }

                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }
Пример #14
0
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (!SecUtility.ValidateParameter(ref password,
                                              true,
                                              true,
                                              false,
                                              0))
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            string salt = GenerateSalt();
            string pass = EncodePassword(password, (int)_passwordFormat, salt);

            if (pass.Length > 128)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            if (!SecUtility.ValidateParameter(ref username,
                                              true,
                                              true,
                                              true,
                                              255))
            {
                status = MembershipCreateStatus.InvalidUserName;
                return(null);
            }


            AccessConnectionHolder holder     = MyConnectionHelper.GetConnection(_databaseFileName, true);
            SqlConnection          connection = holder.Connection;

            try
            {
                try
                {
                    //
                    // Start transaction
                    //

                    SqlCommand command = new SqlCommand();

                    int    appId = GetAppplicationId(holder);
                    object result;
                    int    uid;

                    ////////////////////////////////////////////////////////////
                    // Step 1: Check if the user exists in the Users table: create if not
                    uid = MyConnectionHelper.GetUserID(connection, appId, username, false);
                    if (uid != 0)
                    { // User not created successfully!
                        status = MembershipCreateStatus.DuplicateUserName;
                        return(null);
                    }

                    ////////////////////////////////////////////////////////////
                    // Step 4: Create user in Membership table
                    DateTime dt = MyConnectionHelper.RoundToSeconds(DateTime.Now);
                    command = new SqlCommand(@"INSERT INTO users " +
                                             "(UserName,PasswordHash, Salt) " +
                                             "VALUES (@UserName,@PasswordHash, @salt)",
                                             connection);
                    int pFormat = (int)_passwordFormat;
                    command.Parameters.Add(new SqlParameter("@UserName", username));
                    command.Parameters.Add(new SqlParameter("@PasswordHash", pass));
                    command.Parameters.Add(new SqlParameter("@salt", salt));
                    //
                    // Error inserting row
                    //

                    if (command.ExecuteNonQuery() != 1)
                    {
                        status = MembershipCreateStatus.ProviderError;
                        return(null);
                    }

                    status = MembershipCreateStatus.Success;
                    return(new MembershipUser(this.Name,
                                              username,
                                              uid,
                                              email,
                                              passwordQuestion,
                                              null,
                                              isApproved,
                                              false,
                                              dt,
                                              dt,
                                              dt,
                                              dt,
                                              DateTime.MinValue));
                }
                catch (Exception e)
                {
                    throw MyConnectionHelper.GetBetterException(e, holder);
                }
                finally
                {
                    holder.Close();
                }
            }
            catch
            {
                throw;
            }
        }