1

追加されたユーザーの情報をデータベースに保存するイントラネット Web ベースのアプリケーションがあります。

私がやりたいことは次のとおりです。ユーザーが webstie を参照すると、ユーザーが独自のデータベースに存在するかどうかがチェックされます。そうでない場合は、Active Directory を使用して彼の情報を確認します。

メソッドを書きましたが、データベースをチェックした後に問題が発生し、ユーザーが存在しない場合は、従業員の組織コードをチェックする 2 番目のメソッドに進みます。

public static bool isMember(string userid)
{
        Employee employee = new Employee(userid);

        if (!String.IsNullOrEmpty(userid))
        {
            string username = userid;
            string connString = "Data Source=appServer\\sqlexpress;Initial Catalog=dbTest;Integrated Security=True";
            string cmdText2 = "SELECT Count(*) FROM employee WHERE Username = @username";

            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                // Open DB connection.
                using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
                {
                    cmd.Parameters.Add("@Username", SqlDbType.VarChar);
                    cmd.Parameters["@username"].Value = username;
                    var count = (int)cmd.ExecuteScalar();
                    return count == 1; // return true if there's only one employee with given name
                }
            }
        }
        else if (employee.department.Code == "30003143") //The SapCode of department is "30003143"
            return true;
        else
            return false;
    }

それで、それを修正する方法は?ユーザーがデータベースに存在しない場合、アプリケーションが (else if) 句を通過するようにする方法は?

4

1 に答える 1

1

とても簡単:

public static bool isMember(string userid)
{
    // guard clause - if "userid" is invalid, return "false" right away 
    if (String.IsNullOrEmpty(userid))
    {
        return false
    }

    //Object from Employee class
    Employee employee = new Employee(userid);

    string username = userid;
    string connString = "Data Source=appServer\\sqlexpress;Initial Catalog=dbTest;Integrated Security=True";
    string cmdText2 = "SELECT Count(*) FROM employee WHERE Username = @username";

    using (SqlConnection conn = new SqlConnection(connString))
    using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
    {
            cmd.Parameters.Add("@Username", SqlDbType.VarChar);
            cmd.Parameters["@username"].Value = username;

            conn.Open();

            var count = (int)cmd.ExecuteScalar();

            if (count == 1)
            {
               return true; // return true if there's only one employee with given name
            }
    }

    // if the user already existed in the database - then the above RETURN has 
    // returned "true" to the caller. So these lines are **only** executed if the
    // user was NOT found in the database.

    if (employee.department.Code == "30003143") //The SapCode of department is "30003143"
        return true;

    // now check in Active Directory here.....     
    return UserExistsInActiveDirectory();
}
于 2012-12-08T12:27:24.557 に答える