using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.OracleClient;
using System.Text;
using System.Data.OleDb;
using System.DirectoryServices;

// IRFAN_MOD 20150222 To remove password from the log.

public partial class Security_LoginPage : System.Web.UI.Page
{
    string LM = "";
    protected void Page_Load(object sender, EventArgs e)
    {
             Session["pageArea"] = "";
       
            HyperLink1.Visible = false;
            if (!IsPostBack)
            {
                string oldPath = Environment.GetEnvironmentVariable("path");
                bool found = oldPath.Contains(ConfigurationManager.AppSettings["EncDllPath"]);
                if (!found)
                    System.Environment.SetEnvironmentVariable("Path", ConfigurationManager.AppSettings["EncDllPath"] + oldPath);
                ExceptionUtility.LogException(0, "", "", "Page_Load", "");
               Helper.Read_APP_VersoinNo();

                txtUserID.Focus();

                lbl_securityBanner.Text = "- This is a Controlled Access Application and only Authorized Users are Permitted. "
                                          + "<br />"
                                          + "- If you are not authorized to access thie service, please EXIT now. Unauthorized users may be subject to legal prosecution."
                                          + "<br />"
                                          + "- By continuing to use or access this application, the user signifies that they are an authorized user and consents to monitoring.";
            }

            LM = getParamByID("200");

            if (LM.Equals("AU"))
            {
                LoginActiveUser();
            }

            Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
            Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
            Response.AppendHeader("Expires", "0"); // Proxies.
    }

    private bool LoginUser(string userName, string password, ref string error)
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            //OleDbConnection oracon1 = new OleDbConnection(DBConnection);
            //oracon1.Open();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "sec_authenticate.authenticate_user_login";

            oracom.Parameters.Add("p_user_id", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_password", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_output", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_output1", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

            oracom.Parameters["p_lang"].Value = "EN";
            oracom.Parameters["p_user_id"].Value = userName;
            oracom.Parameters["p_password"].Value = Helper.DecPassword(password);
          

            oracom.ExecuteNonQuery();
            oracon.Close();
            string output = oracom.Parameters["p_output"].Value.ToString();
            string output1 = oracom.Parameters["p_output1"].Value.ToString();

            string a = oracom.Parameters["p_res_code"].Value.ToString();
            error = oracom.Parameters["p_res_msg"].Value.ToString();
            if (a == "0")
            {
                Session["uid"] = output;
                Session["username"] = output1;
                string guid = Guid.NewGuid().ToString();
                Session["AuthToken"] = guid;
                Session["pageArea"] = "L";
                // now create a new cookie with this guid value
                //Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                var responseCookie = new HttpCookie("AuthToken")
                {
                    //Set the HttpOnly property to prevent the cookie from
                    //being accessed by client side script
                    HttpOnly = true,

                    //Add the Anti-XSRF token to the cookie value
                    Value = guid
                    //,
                    //Path = Request.ApplicationPath
                };
                Response.Cookies.Add(responseCookie);
                ExceptionUtility.LogException(0, "sec_authenticate.authenticate_user_login", "1.1", "Login_user", "userName -" + userName + /*":password -" + password +*/ ":error -" + error + "");
                return true;
            }
            else if (a == "4")
            {
                HyperLink1.Visible = true;
                ExceptionUtility.LogException(9, "sec_authenticate.authenticate_user_login", "1.1", "Login_user", "userName -" + userName + /*":password -" +  password +*/ ":error -" + error + "");
                return false;
            }
            else
            {
                ExceptionUtility.LogException(9, "sec_authenticate.authenticate_user_login", "1.1", "Login_user", "userName -" + userName + /* ":password -" + password +*/":error -" + error + "");
                return false;
            }
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "sec_authenticate.authenticate_user_login", "1.1", "Login_user", "userName -" + userName + /* ":password -" + password +*/":error -" + error + "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return false;
        }
    }

    private bool LoginUser(string userName, ref string error)
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            //OleDbConnection oracon1 = new OleDbConnection(DBConnection);
            //oracon1.Open();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "sec_authenticate.authenticate_user_login_AU";

            oracom.Parameters.Add("p_user_id", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_output", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_output1", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

            oracom.Parameters["p_lang"].Value = "EN";
            oracom.Parameters["p_user_id"].Value = userName;

            oracom.ExecuteNonQuery();
            oracon.Close();
            string output = oracom.Parameters["p_output"].Value.ToString();
            string output1 = oracom.Parameters["p_output1"].Value.ToString();

            string a = oracom.Parameters["p_res_code"].Value.ToString();
            error = oracom.Parameters["p_res_msg"].Value.ToString();
            if (a == "0")
            {
                Session["uid"] = output;
                Session["username"] = output1;
                string guid = Guid.NewGuid().ToString();
                Session["AuthToken"] = guid;
                Session["pageArea"] = "L";
                // now create a new cookie with this guid value
                Response.Cookies.Add(new HttpCookie("AuthToken", guid));
                ExceptionUtility.LogException(0, "sec_authenticate.authenticate_user_login_AU", "1.1", "LoginUser", "userName -" + userName + "");
                return true;
            }
            else if (a == "4")
            {
                HyperLink1.Visible = true;
                ExceptionUtility.LogException(9, "sec_authenticate.authenticate_user_login_AU", "1.1", "LoginUser", "userName -" + userName + "");
                return false;
            }
            else
            {
                ExceptionUtility.LogException(9, "sec_authenticate.authenticate_user_login_AU", "", "LoginUser", "userName -" + userName + "");
                return false;
            }
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "sec_authenticate.authenticate_user_login_AU","1.1", "LoginUser", "userName -"+userName+"");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return false;
        }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string error = "";
        
            string clientIPAdd = Request.ServerVariables["REMOTE_ADDR"].ToString();



            if (this.txtUserID.Text.Equals(""))
            {
                this.lblError.Text = "Please enter a user ID.";
            }

            else
            {

                setMode();
                if (!LM.Equals("AU"))
                {
                    bool saved = false;
                    if (LM.Equals("DB"))
                    {
                        ExceptionUtility.LogException(0, "", "1", "btnLogin_Click", "");
                        saved = LoginUser(txtUserID.Text, txtPass1.Text, ref error);

                        if (saved)
                        {
                            
                            Response.Redirect("../Security/ExecSecurityBanner.aspx");
                        }
                        else
                        {
                            if (Helper.OracleError(error))
                            {
                                ExceptionUtility.LogException(9, "", "", "btnLogin_Click", error);
                                lblError.Text = "Login Failed";
                            }
                            else
                                lblError.Text = error;
                            txtPass1.Focus();

                            lbl_securityBanner.Text =
                                                "- If you have forgotten you sign-on or password please contact service Desk."
                                              + "- This is a monitored system and only Authorized Users are Permitted. "
                                              + "<br />"
                                              + "- If you are not authorized to access thie service, please EXIT now. Unauthorized users may be subject to legal prosecution.";

                            this.logUserLoginViolation(this.txtUserID.Text, clientIPAdd);
                            ExceptionUtility.LogException(9, "", "", "btnLogin_Click", "");
                        }
                    }
                    else
                    {
                        ExceptionUtility.LogException(0, "", "", "btnLogin_Click", "");
                        saved = LoginActiveDirectory(txtUserID.Text, txtPass1.Text, ref error);
                        if (saved)
                        {
                            
                            Response.Redirect("../Security/ExecSecurityBanner.aspx");
                        }
                        else
                        {
                            lbl_securityBanner.Text =
                                                "- If you have forgotten you sign-on or password please contact service Desk."
                                              + "- This is a monitored system and only Authorized Users are Permitted. "
                                              + "<br />"
                                              + "- If you are not authorized to access thie service, please EXIT now. Unauthorized users may be subject to legal prosecution.";


                            lblError.Text = error;
                            txtPass1.Focus();

                            this.logUserLoginViolation(this.txtUserID.Text, clientIPAdd);
                            ExceptionUtility.LogException(9, "", "", "btnLogin_Click", "");
                        }
                    }
                }
                else
                {
                    ExceptionUtility.LogException(0, "", "", "btnLogin_Click", "");
                    Response.Redirect("../Security/ExecSecurityBanner.aspx");
                }
            }
            
       
    }

    private String DecPassword(String pass)
    {
        try
        {
            string FsPassWord = "";
            String FsDecPassword = "";
            int pwd;

            for (int nCount = 0; nCount < pass.Length; nCount++)
            {
                FsPassWord = pass.Substring(nCount, 1);
                pwd = ((Encoding.ASCII.GetBytes(FsPassWord)[0]) + 15) - 12;
                FsDecPassword = FsDecPassword + Convert.ToString((Convert.ToChar(pwd)));
            }
            return FsDecPassword;
        }
        catch (Exception ex)
        {
            ExceptionUtility .LogException (ex,"","DecPassword","","pass :"+pass +"");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return null;
        }
    }

    private void setMode()
    {
        try
        {
            if (rdLive.Checked)
            {
                Session["mode"] = "l";
            }
            else if (rdArchive.Checked)
            {
                Session["mode"] = "a";
            }
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "","", "setMode", "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
    }

    private void LoginActiveUser()
    {
        try
        {
            //begin LDAP
            rowuser.Visible = false;
            rowpass.Visible = false;
            string login = Context.User.Identity.Name.ToString();

            int number = login.IndexOf("\\");
            if (login.Substring(0, number).Equals(ConfigurationSettings.AppSettings["DOMAIN"]))
            {
                string username = login.Substring(number + 1, login.Length - number - 1);
                string error = "";
                setMode();
                ExceptionUtility.LogException(0, "", "1.1", "LoginActiveUser", "");
                bool saved = LoginUser(username, ref error);
                if (saved)
                {
                    //Response.Redirect("../Business/Default.aspx");
                    loginbutton.Visible = true;
                    lblError.Text = "Please select application mode";
                }
                else
                {
                    loginbutton.Visible = false;
                    if (Helper.OracleError(error))
                    {
                        lblError.Text = "An Error Occured!";
                        ExceptionUtility.LogException(9, "", "1.1", "LoginActiveUser", error);
                    }
                    else
                        lblError.Text = error;
                }
            }
            else
            {
                lblError.Text = "Not a domain user ! <br>Please login with your domain user to be able to access this application";
                loginbutton.Visible = false;
                ExceptionUtility.LogException(9, "", "1.1", "LoginActiveUser", "");
            }
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "","1.1", "LoginActiveUser", "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
        //End LDAP
    }

    private bool LoginActiveDirectory(string userName, string password, ref string error)
    {
        try
        {
            ExceptionUtility.LogException(0, "", "LoginActiveDirectory", "1.1", "username-" + userName +/* ":password-" + password +*/ "");
            ActiveDirectoryUser user;

            user = this.getUserDetails_FromAD(userName, password, ref error);

            if (user != null)
            {
                bool isPermittedGroup = false;
                bool isExistedUser = false;

                bool isSuperUser = false;

                ArrayList groups = this.getUserGroups(userName, password);

                if (groups == null)
                {
                    isPermittedGroup = false;

                    error = "Sorry your Department is NOT authorized to use this application.";
                }
                else
                {
                    IEnumerator iterator = groups.GetEnumerator();

                    string tempGroupName = "";

                    while (iterator.MoveNext())
                    {
                        tempGroupName = (string)iterator.Current;

                        isPermittedGroup = this.isExistedGroup(tempGroupName);

                        if (isPermittedGroup) break;
                    }

                    if (isPermittedGroup)
                    {
                        isSuperUser = (tempGroupName == Constants.AMINS_GROUP_NAME ? true : false);

                        isExistedUser = this.isExistedUser(int.Parse(user.getUserId()));

                        if (isExistedUser && isSuperUser)
                        {
                            //Existed and Super user NOW, but not assigned to the current group.
                            if (!this.isUserAssignedToThisGroup(int.Parse(user.getUserId()), tempGroupName))
                            {
                                this.assignUserToGroup(int.Parse(user.getUserId()), tempGroupName, true);
                            }
                        }
                        else if (isExistedUser && !isSuperUser)
                        {
                            //Existed and not Super user NOW, but not assigned to the current group.
                            if (!this.isUserAssignedToThisGroup(int.Parse(user.getUserId()), tempGroupName))
                            {
                                this.assignUserToGroup(int.Parse(user.getUserId()), tempGroupName, false);
                            }
                        }
                        else if (!isExistedUser && isSuperUser)
                        {
                            //Not existed in the system and super
                            this.addUser(user.getUserId(), user.getUserName(), tempGroupName, true, ref error);
                        }
                        else if (!isExistedUser && !isSuperUser)
                        {
                            //Not existed in the system and not super
                            this.addUser(user.getUserId(), user.getUserName(), tempGroupName, false, ref error);
                        }


                        bool loggedIn = this.LoginUser(user.getUserId(), ref error);
                        if (!loggedIn)
                            return false;

                    }
                    else
                    {
                        error = "Sorry your Department is NOT authorized to use this application.";
                    }
                }
                
                return isPermittedGroup;
            }
            else
            {
                ExceptionUtility.LogException(9, "", "LoginActiveDirectory", "1.1", "username-" + userName +/* ":password-" + password +*/ "");
                return false;
            }
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "", "LoginActiveDirectory","1.1", "username-" + userName + /*":password-" + password + */"");
            return false;
        }
    }

    private string getParamByID(string ID)
    {
        string DBConnection = "";
        try
        {
             DBConnection = Helper.dbConnectionLive();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "SYSTEM_PARAM_EDITOR.get_parameter_by_id";

            oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_param_id", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

            oracom.Parameters["p_param_id"].Value = ID;
            oracom.Parameters["p_lang"].Value = "EN";
            oracom.Parameters["p_current_uid"].Value = "1";

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            string temp = ds.Tables[0].Rows[0][2].ToString();
            oracon.Close();

            return temp;
        }
        catch (Exception ex)
        {
           
            ExceptionUtility.LogException(ex, "SYSTEM_PARAM_EDITOR.get_parameter_by_id","", "getParamByID", "ID :" + ID+ DBConnection + "");
            return null;
        }
    }

    private void logUserLoginViolation(string enteredUserId, string clientIPAddess)
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "USER_AUDITOR.LOG_LOGIN_VIOLATION";

            oracom.Parameters.Add("P_USER_ID", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_IP_ADDRESS", OracleType.VarChar).Direction = ParameterDirection.Input;

            oracom.Parameters["P_USER_ID"].Value = enteredUserId;
            oracom.Parameters["P_IP_ADDRESS"].Value = clientIPAddess;

            oracom.ExecuteNonQuery();
            oracon.Close();
           
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "USER_AUDITOR.LOG_LOGIN_VIOLATION","", "logUserLoginViolation", "enteredUserId-" + enteredUserId + ",clientIPAddress-" + clientIPAddess + "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
    }

    private ArrayList getUserGroups(string userName, string password)
    {
       
        ArrayList userGroups = new ArrayList();
        string domain = getParamByID("201");
        string domainAndUserName = getParamByID("202") + "\\" + userName;
        //string domain = @"LDAP://DC=anb,DC=net";
        //string domainAndUserName = @"anb-pdc-central\" + userName;

        DirectoryEntry directoryEntry = new DirectoryEntry(domain, domainAndUserName, password);

        DirectorySearcher searcher = new DirectorySearcher(directoryEntry);

        searcher.Filter = "(SAMAccountName=" + userName + ")";
        searcher.PropertiesToLoad.Add("memberOf");

        try
        {
            SearchResult result = searcher.FindOne();

            int foundGroupsCount = result.Properties["memberOf"].Count;

            string groupName;

            if (foundGroupsCount == 0)
            {
                return null;
            }
            else
            {

                for (int counter = 0; counter < foundGroupsCount; counter++)
                {
                    groupName = (string)result.Properties["memberOf"][counter];

                    groupName = groupName.Remove(groupName.IndexOf(","));

                    groupName = groupName.Replace("CN=", "");

                    userGroups.Add(groupName);
                }

            }
        }
        catch (Exception e)
        {
            ExceptionUtility.LogException(e, "", "getUserGroups","", "userName-" + userName + /*",password-" + password +*/ "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return null;
        }


        return userGroups;
    }

    private bool isExistedGroup (string groupName)
    {
        try
        {
            bool isExisted = false;

            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "SEC_GROUP_MAINTAIN.IS_EXISTED";

            oracom.Parameters.Add("p_group_name", OracleType.VarChar).Direction = ParameterDirection.Input;

            oracom.Parameters.Add("p_is_existed", OracleType.Number).Direction = ParameterDirection.Output;

            oracom.Parameters["p_group_name"].Value = groupName;

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            oracon.Close();

            isExisted = (int.Parse(oracom.Parameters["p_is_existed"].Value.ToString()) == 1 ? true : false);

            return isExisted;
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "", "","", "groupName :" + groupName + "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return false;
        }
    }

    private bool isExistedUser(int userId)
    {
        try
        {
            bool isExisted = false;

            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "sec_user_maintain.IS_USER_EXSITED";

            oracom.Parameters.Add("P_USER_ID", OracleType.Number).Direction = ParameterDirection.Input;

            oracom.Parameters.Add("P_IS_EXISTED", OracleType.Number).Direction = ParameterDirection.Output;

            oracom.Parameters["P_USER_ID"].Value = userId;

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            oracon.Close();

            isExisted = (int.Parse(oracom.Parameters["P_IS_EXISTED"].Value.ToString()) == 1 ? true : false);

            return isExisted;
        }
        catch (Exception ex)
        {
            ExceptionUtility .LogException (ex,"sec_user_maintain.IS_USER_EXSITED","","isExistedUser","userId :"+userId+"");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return false;
        }
    }

    private bool isUserAssignedToThisGroup(int userId, string groupName)
    {
        try
        {
            bool isAssigned = false;

            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "sec_user_maintain.IS_USER_ASSIGNED_THIS_GROUP";

            oracom.Parameters.Add("P_USER_ID", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_GROUP_NAME", OracleType.VarChar).Direction = ParameterDirection.Input;

            oracom.Parameters.Add("P_IS_ASSIGNED", OracleType.Number).Direction = ParameterDirection.Output;

            oracom.Parameters["P_USER_ID"].Value = userId;
            oracom.Parameters["P_GROUP_NAME"].Value = groupName;

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            oracon.Close();

            isAssigned = (int.Parse(oracom.Parameters["P_IS_ASSIGNED"].Value.ToString()) == 1 ? true : false);

            return isAssigned;
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "sec_user_maintain.IS_USER_ASSIGNED_THIS_GROUP","", "isUserAssignedToThisGroup", "userID- " + userId + ",GroupName- " + groupName + "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return false;
        }
    }

    private void assignUserToGroup(int userId, string groupName, bool isSuper)
    {
        try
        {

            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "sec_user_maintain.ASSIGN_USER_TO_GROUP";

            oracom.Parameters.Add("P_USER_ID", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_GROUP_NAME", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_IS_SUPER", OracleType.Number).Direction = ParameterDirection.Input;

            oracom.Parameters["P_USER_ID"].Value = userId;
            oracom.Parameters["P_GROUP_NAME"].Value = groupName;
            oracom.Parameters["P_IS_SUPER"].Value = (isSuper ? 1 : 0);

            oracom.ExecuteNonQuery();
            oracon.Close();
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex,"","","","userId :"+userId +",groupName-"+groupName+",IsSuper-"+isSuper+"");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
    }

    private ActiveDirectoryUser getUserDetails_FromAD(string userName, string password, ref string error)
    {
        string path = @"LDAP://DC=anb,DC=net";

        string domainAndUserName = @"anb-pdc-central\" + userName;
        DirectoryEntry entry = new DirectoryEntry(path, domainAndUserName, password);

        ActiveDirectoryUser user = null;

        try
        {
            Object obj = entry.NativeObject;

            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(SAMAccountName=" + userName + ")";
            search.PropertiesToLoad.Add("cn");
            search.PropertiesToLoad.Add("givenname");
            search.PropertiesToLoad.Add("sn");
            search.PropertiesToLoad.Add("sn");
            SearchResult result = search.FindOne();

            user = new ActiveDirectoryUser();
            user.setUserId(userName);
            user.setUserName(result.GetDirectoryEntry().Properties["givenname"].Value.ToString() + " " +  
                             result.GetDirectoryEntry().Properties["sn"].Value.ToString());
        }
        catch (Exception ex)
        {
            error = ex.Message;
            ExceptionUtility.LogException(ex, "", "getUserDetails_FromAD", "", "userName- " + userName +/* ",password-" +password +*/"");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return null;
        }

        return user;
    }

    private bool addUser(string userId, string userName, string groupName,bool isSuper, ref string error)
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "sec_user_maintain.ADD_APPROVED_USER";

            oracom.Parameters.Add("P_USER_ID", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_USER_NAME", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_GROUP_NAME", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_IS_SUPER", OracleType.Number).Direction = ParameterDirection.Input;

            oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

            oracom.Parameters["P_USER_ID"].Value = userId;
            oracom.Parameters["P_USER_NAME"].Value = userName;
            oracom.Parameters["P_GROUP_NAME"].Value = groupName;
            oracom.Parameters["P_IS_SUPER"].Value = (isSuper ? 1 : 0);

            oracom.ExecuteNonQuery();
            oracon.Close();

            string a = oracom.Parameters["p_res_code"].Value.ToString();
            error = oracom.Parameters["p_res_msg"].Value.ToString();
            if (a == "0")
            {
                ExceptionUtility.LogException(0, "sec_user_maintain.ADD_APPROVED_USER", "", "addUser", "userId -" + userId + ",userName -" + userName + ",groupName -" + groupName + ",isSuper -" + isSuper + "");
                return true;
            }
            else
            {
                ExceptionUtility.LogException(9, "sec_user_maintain.ADD_APPROVED_USER", "", "addUser", "userId -" + userId + ",userName -" + userName + ",groupName -" + groupName + ",isSuper -" + isSuper + "");
                return false;
            }
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "sec_user_maintain.ADD_APPROVED_USER", "", "addUser", "userId -" + userId + ",userName -" + userName + ",groupName -" + groupName + ",isSuper -" + isSuper + "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return false;
        }
    }
}
