/// <summary>
        /// return is credential provide by user is right or not
        /// </summary>
        /// <param name="model">login model class</param>
        /// <param name="roles">out roles , has role list of user</param>
        /// <param name="ctx" ></param>
        /// <returns>true if athenicated</returns>
        public static bool Login(LoginModel model, out List <KeyNamePair> roles)
        {
            // loginModel = null;
            //bool isMatch = false;
            roles = null;
            SecureEngine.Encrypt("t"); //Initialize

            //	Cannot use encrypted password
            //if ())
            //{
            //    //log.warning("Cannot use Encrypted Password");
            //    return false;
            //}
            //	Authentification
            bool    authenticated = false;
            bool    isLDAP        = false;
            MSystem system        = MSystem.Get(new Ctx());
            string  output        = "";

            if (system != null && system.IsLDAP())
            {
                authenticated = system.IsLDAP(model.Login1Model.UserValue, model.Login1Model.Password, out output);

                isLDAP = true;
            }
            //Save Failed Login Count and Password validty in cache
            GetSysConfigForlogin();


            int fCount            = Util.GetValueOfInt(cache[Common.Failed_Login_Count_Key]);
            int passwordValidUpto = Util.GetValueOfInt(cache[Common.Password_Valid_Upto_Key]);

            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@username", model.Login1Model.UserValue);



            DataSet dsUserInfo = DB.ExecuteDataset("SELECT AD_User_ID, Value, Password,IsLoginUser,FailedLoginCount, IsOnlyLDAP FROM AD_User WHERE Value=@username", param);

            if (dsUserInfo != null && dsUserInfo.Tables[0].Rows.Count > 0)
            {
                // skipped Login user check for SuperUser (100)
                if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue) &&
                    !dsUserInfo.Tables[0].Rows[0]["IsLoginUser"].ToString().Equals("Y"))
                {
                    throw new Exception("NotLoginUser");
                }

                // output length will be greater than 0 if there is any error while ldap auth.
                //output check is applied to becuase after first login, when user redriect to home page, this functioexecutes again and password is null on that time.
                // so ldap reject auth , but user is actually authenticated. so to avoid error, this check is used.
                if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue) && dsUserInfo.Tables[0].Rows[0]["IsOnlyLDAP"].ToString().Equals("Y") &&
                    isLDAP && !authenticated)
                {
                    throw new Exception(output);
                }
            }
            else
            {
                throw new Exception("UserNotFound");
            }

            //if authenticated by LDAP or password is null(Means request from home page)
            if (!authenticated && model.Login1Model.Password != null)
            {
                string sqlEnc      = "SELECT isencrypted FROM ad_column WHERE ad_table_id=(SELECT ad_table_id FROM ad_table WHERE tablename='AD_User') AND columnname='Password'";
                char   isEncrypted = Convert.ToChar(DB.ExecuteScalar(sqlEnc));
                string originalpwd = model.Login1Model.Password;
                if (isEncrypted == 'Y' && model.Login1Model.Password != null)
                {
                    model.Login1Model.Password = SecureEngine.Encrypt(model.Login1Model.Password);
                }

                //  DataSet dsUserInfo = DB.ExecuteDataset("SELECT AD_User_ID, Value, Password,IsLoginUser,FailedLoginCount FROM AD_User WHERE Value=@username", param);
                if (dsUserInfo != null && dsUserInfo.Tables[0].Rows.Count > 0)
                {
                    //if username or password is not matching
                    if ((!dsUserInfo.Tables[0].Rows[0]["Value"].Equals(model.Login1Model.UserValue) ||
                         !dsUserInfo.Tables[0].Rows[0]["Password"].Equals(model.Login1Model.Password)) ||
                        (originalpwd != null && SecureEngine.IsEncrypted(originalpwd)))
                    {
                        //if current user is Not superuser, then increase failed login count
                        if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue))
                        {
                            param[0] = new SqlParameter("@username", model.Login1Model.UserValue);
                            int count = DB.ExecuteQuery("UPDATE AD_User Set FAILEDLOGINCOUNT=FAILEDLOGINCOUNT+1 WHERE Value=@username ", param);

                            if (fCount > 0 && fCount <= Util.GetValueOfInt(dsUserInfo.Tables[0].Rows[0]["FailedLoginCount"]) + 1)
                            {
                                throw new Exception("MaxFailedLoginAttempts");
                            }
                        }

                        throw new Exception("UserPwdError");
                    }
                    else// if username and password matched, then check if account is locked or not
                    {
                        if (fCount > 0 && fCount <= Util.GetValueOfInt(dsUserInfo.Tables[0].Rows[0]["FailedLoginCount"]))
                        {
                            throw new Exception("MaxFailedLoginAttempts");
                        }
                    }
                }
            }

            IDataReader dr = GetRoles(model.Login1Model.UserValue, authenticated, isLDAP);

            if (!dr.Read())             //	no record found, then return msaage that role not found.
            {
                dr.Close();
                throw new Exception("RoleNotDefined");
            }

            // if user logged in successfully, then set failed login count to 0
            DB.ExecuteQuery("UPDATE AD_User SET FailedLoginCount=0 WHERE Value=@username", param);

            int AD_User_ID = Util.GetValueOfInt(dr[0].ToString()); //User Id

            if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue))
            {
                String Token2FAKey = Util.GetValueOfString(dr["TokenKey2FA"]);
                bool   enable2FA   = Util.GetValueOfString(dr["Is2FAEnabled"]) == "Y";
                if (enable2FA)
                {
                    model.Login1Model.QRFirstTime = false;
                    TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                    SetupCode setupInfo        = null;
                    string    userSKey         = Util.GetValueOfString(dr["Value"]);
                    int       ADUserID         = Util.GetValueOfInt(dr["AD_User_ID"]);
                    // if token key don't exist for user, then create new
                    if (Token2FAKey.Trim() == "")
                    {
                        model.Login1Model.QRFirstTime = true;
                        Token2FAKey = userSKey;
                        // get Random Number
                        model.Login1Model.TokenKey2FA = GetRndNum();
                        // create Token key based on Value, UserID and Random Number
                        Token2FAKey = userSKey + ADUserID.ToString() + model.Login1Model.TokenKey2FA;
                    }
                    else
                    {
                        // Decrypt token key saved in database
                        string decKey = SecureEngine.Decrypt(Token2FAKey);
                        Token2FAKey = userSKey + ADUserID.ToString() + decKey;
                    }

                    string url = Util.GetValueOfString(HttpContext.Current.Request.Url.AbsoluteUri).Replace("VIS/Account/JsonLogin", "").Replace("https://", "").Replace("http://", "");

                    setupInfo = tfa.GenerateSetupCode("VA ", url + " " + userSKey, Token2FAKey, 150, 150);
                    model.Login1Model.QRCodeURL = setupInfo.QrCodeSetupImageUrl;
                }

                model.Login1Model.Is2FAEnabled = enable2FA;
            }


            if (!authenticated)
            {
                DateTime?pwdExpireDate = Util.GetValueOfDateTime(dr["PasswordExpireOn"]);
                if (pwdExpireDate == null || (passwordValidUpto > 0 && (DateTime.Compare(DateTime.Now, Convert.ToDateTime(pwdExpireDate)) > 0)))
                {
                    model.Login1Model.ResetPwd = true;
                    //if (SecureEngine.IsEncrypted(model.Login1Model.Password))
                    //    model.Login1Model.Password = SecureEngine.Decrypt(model.Login1Model.Password);
                }
            }

            roles = new List <KeyNamePair>(); //roles

            List <int> usersRoles = new List <int>();
            string     username   = "";

            do  //	read all roles
            {
                AD_User_ID = Util.GetValueOfInt(dr[0].ToString());
                int AD_Role_ID = Util.GetValueOfInt(dr[1].ToString());

                String      Name = dr[2].ToString();
                KeyNamePair p    = new KeyNamePair(AD_Role_ID, Name);
                username = Util.GetValueOfString(dr["username"].ToString());
                roles.Add(p);

                usersRoles.Add(AD_Role_ID);
            }while (dr.Read());

            dr.Close();
            model.Login1Model.AD_User_ID  = AD_User_ID;
            model.Login1Model.DisplayName = username;

            IDataReader drLogin = null;

            if (model.Login2Model == null)
            {
                try
                {
                    //* Change sub query into ineer join */

                    drLogin = DB.ExecuteReader(" SELECT l.AD_Role_ID," +
                                               " (SELECT r.Name FROM AD_ROLE r WHERE r.AD_Role_ID=l.AD_ROLE_ID) as RoleName," +

                                               " l.AD_Org_ID," +
                                               " (SELECT o.Name FROM AD_Org o WHERE o.AD_Org_ID=l.AD_Org_ID) as OrgName," +
                                               " l.AD_Client_ID," +
                                               " (SELECT c.Name FROM AD_Client c WHERE c.AD_Client_ID=l.AD_Client_ID) as ClientName," +
                                               " l.M_Warehouse_ID," +
                                               " (SELECT m.Name FROM M_Warehouse m WHERE m.M_Warehouse_Id = l.M_Warehouse_ID) as WarehouseName" +
                                               " FROM AD_LoginSetting l WHERE l.IsActive = 'Y' AND l.AD_User_ID=" + AD_User_ID);
                    if (drLogin.Read())
                    {
                        bool deleteRecord = false;

                        //Delete Login Setting
                        if (deleteRecord)
                        {
                            DB.ExecuteQuery("DELETE FROM AD_LoginSetting WHERE AD_User_ID = " + AD_User_ID);
                        }
                        else
                        {
                            model.Login2Model               = new Login2Model();
                            model.Login2Model.Role          = drLogin[0].ToString();
                            model.Login2Model.RoleName      = drLogin[1].ToString();
                            model.Login2Model.Org           = drLogin[2].ToString();
                            model.Login2Model.OrgName       = drLogin[3].ToString();
                            model.Login2Model.Client        = drLogin[4].ToString();
                            model.Login2Model.ClientName    = drLogin[5].ToString();
                            model.Login2Model.Warehouse     = drLogin[6].ToString();
                            model.Login2Model.WarehouseName = drLogin[7].ToString();
                            model.Login2Model.Date          = System.DateTime.Now.Date;
                        }
                    }
                    drLogin.Close();
                }
                catch
                {
                    if (drLogin != null)
                    {
                        drLogin.Close();
                    }
                }
            }
            return(true);
        }
Exemplo n.º 2
0
 /** Static Constructor
  * Set Table ID By Table Name
  * added by ->Harwinder */
 static X_M_Inventory()
 {
     Table_ID = Get_Table_ID(Table_Name);
     model    = new KeyNamePair(Table_ID, Table_Name);
 }
Exemplo n.º 3
0
 /** Static Constructor
  * Set Table ID By Table Name
  * added by ->Harwinder */
 static X_M_Movement()
 {
     Table_ID = Get_Table_ID(Table_Name);
     model    = new KeyNamePair(Table_ID, Table_Name);
 }
        }                                                                                              /** Static Constructor
                                                                                                        * Set Table ID By Table Name
                                                                                                        * added by ->Harwinder */

        static X_VA027_ChequeDetails()
        {
            Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID, Table_Name);
        }                                               /** Serial Version No */
 /** Static Constructor
  * Set Table ID By Table Name
  * added by ->Harwinder */
 static X_C_RevenueRecognition_Run()
 {
     Table_ID = Get_Table_ID(Table_Name);
     model    = new KeyNamePair(Table_ID, Table_Name);
 }
        }                                                                                                      /** Static Constructor
                                                                                                                * Set Table ID By Table Name
                                                                                                                * added by ->Harwinder */

        static X_VAMFG_M_WrkOdrTrnsctionLine()
        {
            Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID, Table_Name);
        }                                               /** Serial Version No */
 /** Static Constructor
  * Set Table ID By Table Name
  * added by ->Harwinder */
 static X_M_MatchPO()
 {
     Table_ID = Get_Table_ID(Table_Name);
     model    = new KeyNamePair(Table_ID, Table_Name);
 }
        }       //	getAD_Role_ID

        /// <summary>
        /// Load Preferences into Context for selected client.
        /// <para>
        /// Sets Org info in context and loads relevant field from
        /// - AD_Client/Info,
        /// - C_AcctSchema,
        /// - C_AcctSchema_Elements
        /// - AD_Preference
        /// </para>
        /// Assumes that the context is set for #AD_Client_ID, ##AD_User_ID, #AD_Role_ID
        /// </summary>
        /// <param name="org">org information</param>
        /// <param name="warehouse">optional warehouse information</param>
        /// <param name="timestamp">optional date</param>
        /// <param name="printerName">optional printer info</param>
        /// <returns>AD_Message of error (NoValidAcctInfo) or ""</returns>
        public String LoadPreferences(KeyNamePair org,
                                      KeyNamePair warehouse, DateTime timestamp, String printerName)
        {
            m_org = org;

            if (m_ctx == null || org == null)
            {
                throw new ArgumentException("Required parameter missing");
            }
            if (m_ctx.GetContext("#AD_Client_ID").Length == 0)
            {
                throw new Exception("Missing Context #AD_Client_ID");
            }
            if (m_ctx.GetContext("##AD_User_ID").Length == 0)
            {
                throw new Exception("Missing Context ##AD_User_ID");
            }
            if (m_ctx.GetContext("#AD_Role_ID").Length == 0)
            {
                throw new Exception("Missing Context #AD_Role_ID");
            }


            //  Org Info - assumes that it is valid
            m_ctx.SetAD_Org_ID(org.GetKey());
            m_ctx.SetContext("#AD_Org_Name", org.GetName());
            Ini.SetProperty(Ini.P_ORG, org.GetName());

            //  Warehouse Info
            if (warehouse != null)
            {
                m_ctx.SetContext("#M_Warehouse_ID", warehouse.GetKey());
                Ini.SetProperty(Ini.P_WAREHOUSE, warehouse.GetName());
            }

            //	Date (default today)
            long today = CommonFunctions.CurrentTimeMillis();

            if (timestamp != null)
            {
                today = CommonFunctions.CurrentTimeMillis(timestamp);
            }
            m_ctx.SetContext("#Date", today.ToString());

            //	Load User/Role Info
            MUser           user       = MUser.Get(m_ctx, GetAD_User_ID());
            MUserPreference preference = user.GetPreference();
            MRole           role       = MRole.GetDefault(m_ctx, true);

            //	Optional Printer
            if (printerName == null)
            {
                printerName = "";
            }
            if (printerName.Length == 0 && preference.GetPrinterName() != null)
            {
                printerName = preference.GetPrinterName();
            }
            m_ctx.SetPrinterName(printerName);
            if (preference.GetPrinterName() == null && printerName.Length > 0)
            {
                preference.SetPrinterName(printerName);
            }

            //	Other
            m_ctx.SetAutoCommit(preference.IsAutoCommit());
            m_ctx.SetAutoNew(Ini.IsPropertyBool(Ini.P_A_NEW));
            if (role.IsShowAcct())
            {
                m_ctx.SetContext("#ShowAcct", preference.IsShowAcct());
            }
            else
            {
                m_ctx.SetContext("#ShowAcct", "N");
            }
            m_ctx.SetContext("#ShowTrl", preference.IsShowTrl());
            m_ctx.SetContext("#ShowAdvanced", preference.IsShowAdvanced());

            String retValue     = "";
            int    AD_Client_ID = m_ctx.GetAD_Client_ID();
            //	int AD_Org_ID =  org.getKey();
            //	int AD_User_ID =  Env.getAD_User_ID (m_ctx);
            int AD_Role_ID = m_ctx.GetAD_Role_ID();

            //	Other Settings
            m_ctx.SetContext("#YYYY", "Y");

            //	AccountSchema Info (first)
            String sql = "SELECT a.C_AcctSchema_ID, a.C_Currency_ID, a.HasAlias, c.ISO_Code, c.StdPrecision "
                         + "FROM C_AcctSchema a"
                         + " INNER JOIN AD_ClientInfo ci ON (a.C_AcctSchema_ID=ci.C_AcctSchema1_ID)"
                         + " INNER JOIN C_Currency c ON (a.C_Currency_ID=c.C_Currency_ID) "
                         + "WHERE ci.AD_Client_ID='" + AD_Client_ID + "'";
            IDataReader dr = null;

            try
            {
                int C_AcctSchema_ID = 0;
                dr = DataBase.DB.ExecuteReader(sql);

                if (!dr.Read())
                {
                    //  No Warning for System
                    if (AD_Role_ID != 0)
                    {
                        retValue = "NoValidAcctInfo";
                    }
                }
                else
                {
                    //	Accounting Info
                    C_AcctSchema_ID = Utility.Util.GetValueOfInt(dr[0].ToString());
                    m_ctx.SetContext("$C_AcctSchema_ID", C_AcctSchema_ID);
                    m_ctx.SetContext("$C_Currency_ID", Utility.Util.GetValueOfInt(dr[1].ToString()));
                    m_ctx.SetContext("$HasAlias", dr[2].ToString());
                    m_ctx.SetContext("$CurrencyISO", dr[3].ToString());
                    m_ctx.SetStdPrecision(Utility.Util.GetValueOfInt(dr[4].ToString()));
                }
                dr.Close();

                //	Accounting Elements
                sql = "SELECT ElementType "
                      + "FROM C_AcctSchema_Element "
                      + "WHERE C_AcctSchema_ID='" + C_AcctSchema_ID + "'"
                      + " AND IsActive='Y'";

                dr = DataBase.DB.ExecuteReader(sql);
                while (dr.Read())
                {
                    m_ctx.SetContext("$Element_" + dr["ElementType"].ToString(), "Y");
                }
                dr.Close();


                //	This reads all relevant window neutral defaults
                //	overwriting superseeded ones.  Window specific is read in Maintain
                sql = "SELECT Attribute, Value, AD_Window_ID "
                      + "FROM AD_Preference "
                      + "WHERE AD_Client_ID IN (0, @#AD_Client_ID@)"
                      + " AND AD_Org_ID IN (0, @#AD_Org_ID@)"
                      + " AND (AD_User_ID IS NULL OR AD_User_ID=0 OR AD_User_ID=@##AD_User_ID@)"
                      + " AND IsActive='Y' "
                      + "ORDER BY Attribute, AD_Client_ID, AD_User_ID DESC, AD_Org_ID";
                //	the last one overwrites - System - Client - User - Org - Window
                sql = Utility.Env.ParseContext(m_ctx, 0, sql, false);
                if (sql.Length == 0)
                {
                }
                else
                {
                    dr = DataBase.DB.ExecuteReader(sql);
                    while (dr.Read())
                    {
                        string AD_Window_ID = dr[2].ToString();
                        String at           = "";
                        if (string.IsNullOrEmpty(AD_Window_ID))
                        {
                            at = "P|" + dr[0].ToString();
                        }
                        else
                        {
                            at = "P" + AD_Window_ID + "|" + dr[0].ToString();
                        }
                        String va = dr[1].ToString();
                        m_ctx.SetContext(at, va);
                    }
                    dr.Close();
                }

                //	Default Values
                sql = "SELECT t.TableName, c.ColumnName "
                      + "FROM AD_Column c "
                      + " INNER JOIN AD_Table t ON (c.AD_Table_ID=t.AD_Table_ID) "
                      + "WHERE c.IsKey='Y' AND t.IsActive='Y'"
                      + " AND EXISTS (SELECT * FROM AD_Column cc "
                      + " WHERE ColumnName = 'IsDefault' AND t.AD_Table_ID=cc.AD_Table_ID AND cc.IsActive='Y')";

                dr = DataBase.DB.ExecuteReader(sql);
                while (dr.Read())
                {
                    LoadDefault(dr[0].ToString(), dr[1].ToString());
                }
                dr.Close();
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                }
            }

            Ini.SaveProperties(Ini.IsClient());
            //	Country
            m_ctx.SetContext("#C_Country_ID", MCountry.GetDefault(m_ctx).GetC_Country_ID());

            m_ctx.SetShowClientOrg(Ini.IsShowClientOrg() ? "Y" : "N");
            m_ctx.SetShowMiniGrid(Ini.GetProperty(Ini.P_Show_Mini_Grid));
            return(retValue);
        }       //	loadPreferences
        }   //  login

        /// <summary>
        /// Actual DB login procedure.
        /// </summary>
        /// <param name="app_user">user</param>
        /// <param name="app_pwd">pwd</param>
        /// <param name="force">ignore pwd</param>
        /// <param name="ignore_pwd">If true, indicates that the user had previously authenticated successfully, and therefore
        /// there is no need to check password again.  This differs from the <b>force</b> parameter in that <b>force</b>
        /// will force a login with System Administrator privileges.
        /// </param>
        /// <returns>array or null if in error.</returns>
        private KeyNamePair[] GetRoles(String app_user, String app_pwd, bool force, bool ignore_pwd)
        {
            long start = CommonFunctions.CurrentTimeMillis();

            if (app_user == null)
            {
                return(null);
            }

            //	Authenticate


            KeyNamePair[]      retValue = null;
            List <KeyNamePair> list     = new List <KeyNamePair>();
            //
            StringBuilder sql = new StringBuilder("SELECT u.AD_User_ID, r.AD_Role_ID,r.Name,")
                                .Append(" u.ConnectionProfile, u.Password ") //	4,5
                                .Append("FROM AD_User u")
                                .Append(" INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')")
                                .Append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') ")
                                .Append("WHERE COALESCE(u.LDAPUser,u.Name)=@username") //	#1
                                .Append(" AND u.IsActive='Y'")
                                .Append(" AND EXISTS (SELECT * FROM AD_Client c WHERE u.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')")
                                .Append(" AND EXISTS (SELECT * FROM AD_Client c WHERE r.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')");

            if (app_pwd != null)
            {
                sql.Append(" AND (u.Password='******' OR u.Password='******')");      //  #2/3
            }
            sql.Append(" ORDER BY r.Name");
            IDataReader dr = null;

            try
            {
                SqlParameter[] param = new SqlParameter[1];
                param[0] = new SqlParameter("@username", app_user);
                //	execute a query
                dr = DataBase.DB.ExecuteReader(sql.ToString(), param);

                if (!dr.Read())         //	no record found
                {
                    if (force)
                    {
                        m_ctx.SetAD_User_ID(0);
                        m_ctx.SetContext("##AD_User_Name", "System (force)");
                        m_ctx.SetContext("##AD_User_Description", "System Forced Login");
                        m_ctx.SetContext("#User_Level", "S  ");         //	Format 'SCO'
                        m_ctx.SetContext("#User_Client", "0");          //	Format c1, c2, ...
                        m_ctx.SetContext("#User_Org", "0");             //	Format o1, o2, ...
                        m_user = new KeyNamePair(0, app_user + " (force)");
                        dr.Close();
                        retValue = new KeyNamePair[] { new KeyNamePair(0, "System Administrator (force)") };
                        return(retValue);
                    }
                    else
                    {
                        dr.Close();
                        return(null);
                    }
                }

                int AD_User_ID = Utility.Util.GetValueOfInt(dr[0].ToString());
                m_ctx.SetAD_User_ID(AD_User_ID);
                m_user = new KeyNamePair(AD_User_ID, app_user);
                m_ctx.SetContext("##AD_User_Name", app_user);

                if (MUser.IsSalesRep(AD_User_ID))
                {
                    m_ctx.SetContext("#SalesRep_ID", AD_User_ID);
                }
                //
                Ini.SetProperty(Ini.P_UID, app_user);

                if (Ini.IsPropertyBool(Ini.P_STORE_PWD))
                {
                    Ini.SetProperty(Ini.P_PWD, app_pwd);
                }


                m_roles.Clear();
                m_users.Clear();
                do      //	read all roles
                {
                    AD_User_ID = Utility.Util.GetValueOfInt(dr[0].ToString());
                    m_users.Add(AD_User_ID);    //	for role
                    //
                    int AD_Role_ID = Utility.Util.GetValueOfInt(dr[1].ToString());
                    if (AD_Role_ID == 0)        //	User is a Sys Admin
                    {
                        m_ctx.SetContext("#SysAdmin", "Y");
                    }
                    String      Name = dr[2].ToString();
                    KeyNamePair p    = new KeyNamePair(AD_Role_ID, Name);
                    m_roles.Add(p);
                    list.Add(p);
                }while (dr.Read());

                dr.Close();
                //
                retValue = new KeyNamePair[list.Count];
                retValue = list.ToArray();
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                }
                retValue = null;
            }
            long ms = CommonFunctions.CurrentTimeMillis() - start;

            return(retValue);
        }       //	getRoles
Exemplo n.º 10
0
        /// <summary>
        /// Get the Zoom Across Targets for a table.
        /// </summary>
        /// <param name="targetTableName">Target Table for zoom</param>
        /// <param name="curWindow_ID">Window from where zoom is invoked</param>
        /// <param name="targetWhereClause">Where Clause in the format "Record_ID=value"</param>
        /// <returns>Record list</returns>
        public static List <KeyNamePair> GetZoomTargets(String targetTableName, int curWindow_ID, String targetWhereClause, VAdvantage.Utility.Ctx ctx)
        {
            #region variables
            //The Option List
            List <KeyNamePair>       zoomList   = new List <KeyNamePair>();
            List <WindowWhereClause> windowList = new List <WindowWhereClause>();
            ArrayList columns        = new ArrayList();
            int       zoom_Window_ID = 0;
            string    PO_Window_ID;
            string    zoom_WindowName = "";
            string    whereClause     = "";
            bool      windowFound     = false;
            //Context ctx = Utility.Env.GetContext();
            #endregion

            // Find windows where the first tab is based on the table
            string sql = "SELECT DISTINCT w.AD_Window_ID, w.Name, tt.WhereClause, t.TableName, " +
                         "wp.AD_Window_ID, wp.Name, ws.AD_Window_ID, ws.Name "
                         + "FROM AD_Table t "
                         + "INNER JOIN AD_Tab tt ON (tt.AD_Table_ID = t.AD_Table_ID) ";

            bool baseLanguage = Utility.Env.IsBaseLanguage(ctx, "");// GlobalVariable.IsBaseLanguage();
            if (baseLanguage)
            {
                sql += "INNER JOIN AD_Window w ON (tt.AD_Window_ID=w.AD_Window_ID)";
                sql += " LEFT OUTER JOIN AD_Window ws ON (t.AD_Window_ID=ws.AD_Window_ID)"
                       + " LEFT OUTER JOIN AD_Window wp ON (t.PO_Window_ID=wp.AD_Window_ID)";
            }
            else
            {
                sql += "INNER JOIN AD_Window_Trl w ON (tt.AD_Window_ID=w.AD_Window_ID AND w.AD_Language='" + Utility.Env.GetAD_Language(ctx) + "')";
                sql += " LEFT OUTER JOIN AD_Window_Trl ws ON (t.AD_Window_ID=ws.AD_Window_ID AND ws.AD_Language='" + Utility.Env.GetAD_Language(ctx) + "')"
                       + " LEFT OUTER JOIN AD_Window_Trl wp ON (t.PO_Window_ID=wp.AD_Window_ID AND wp.AD_Language='" + Utility.Env.GetAD_Language(ctx) + "')";
            }
            sql += "WHERE t.TableName ='" + targetTableName
                   + "' AND w.AD_Window_ID <>" + curWindow_ID
                   + " AND tt.SeqNo=10"
                   + " AND (wp.AD_Window_ID IS NOT NULL "
                   + "OR EXISTS (SELECT 1 FROM AD_Tab tt2 WHERE tt2.AD_Window_ID = ws.AD_Window_ID AND tt2.AD_Table_ID=t.AD_Table_ID AND tt2.SeqNo=10))"
                   + " ORDER BY 2";


            DataSet ds = null;
            try
            {
                ds = ExecuteQuery.ExecuteDataset(sql);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    //rs = ds.Tables[0].Rows[i];
                    windowFound     = true;
                    zoom_Window_ID  = int.Parse(ds.Tables[0].Rows[i][6].ToString());
                    zoom_WindowName = ds.Tables[0].Rows[i][7].ToString();
                    PO_Window_ID    = ds.Tables[0].Rows[i][4].ToString();
                    whereClause     = ds.Tables[0].Rows[i][2].ToString();

                    // Multiple window support only for Order, Invoice, Shipment/Receipt which have PO windows
                    if (PO_Window_ID == null || PO_Window_ID.Length == 0)
                    {
                        break;
                    }

                    WindowWhereClause windowClause = new WindowWhereClause(int.Parse(ds.Tables[0].Rows[i][0].ToString()), ds.Tables[0].Rows[i][1].ToString(), whereClause);
                    windowList.Add(windowClause);
                }
                ds = null;
            }
            catch (Exception e)
            {
                // fill error log
                log.Log(Level.SEVERE, sql, e);
                //VAdvantage.//Common.////ErrorLog.FillErrorLog("ZoomTarget.GetZoomTargets", GlobalVariable.LAST_EXECUTED_QUERY, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
            }
            string sql1 = "";

            if (!windowFound || (windowList.Count <= 1 && zoom_Window_ID == 0))
            {
                return(zoomList);
            }
            //If there is a single window for the table, no parsing is neccessary
            if (windowList.Count <= 1)
            {
                //Check if record exists in target table
                sql1 = "SELECT count(*) FROM " + targetTableName + " WHERE " + targetWhereClause;
                if (whereClause != null && whereClause.Length != 0)
                {
                    sql1 += " AND " + Evaluator.ReplaceVariables(whereClause, ctx, null);
                }
            }
            else if (windowList.Count > 1)
            {
                // Get the columns used in the whereClause and stores in an arraylist
                for (int i = 0; i < windowList.Count; i++)
                {
                    ParseColumns(columns, windowList[i].whereClause);
                }

                // Get the distinct values of the columns from the table if record exists
                sql1 = "SELECT DISTINCT ";
                for (int i = 0; i < columns.Count; i++)
                {
                    if (i != 0)
                    {
                        sql1 += ",";
                    }
                    sql1 += columns[i].ToString();
                }

                if (columns.Count == 0)
                {
                    sql1 += "count(*) ";
                }
                sql1 += " FROM " + targetTableName + " WHERE " + targetWhereClause;
            }
            log.Fine(sql1);
            List <ValueNamePair> columnValues = new List <ValueNamePair>();

            try
            {
                ds = ExecuteQuery.ExecuteDataset(sql1);
                for (int cnt = 0; cnt < ds.Tables[0].Rows.Count; cnt++)
                {
                    if (columns.Count > 0)
                    {
                        columnValues.Clear();
                        // store column names with their values in the variable
                        for (int i = 0; i < columns.Count; i++)
                        {
                            String columnName  = (String)columns[i].ToString();
                            String columnValue = (String)ds.Tables[0].Rows[cnt][columnName].ToString();
                            log.Fine(columnName + " = " + columnValue);
                            columnValues.Add(new ValueNamePair(columnValue, columnName));
                        }

                        // Find matching windows
                        for (int i = 0; i < windowList.Count; i++)
                        {
                            log.Fine("Window : " + windowList[i].windowName + " WhereClause : " + windowList[i].whereClause);
                            if (EvaluateWhereClause(columnValues, windowList[i].whereClause))
                            {
                                log.Fine("MatchFound : " + windowList[i].windowName);
                                KeyNamePair pp = new KeyNamePair(windowList[i].AD_Window_ID, windowList[i].windowName);
                                zoomList.Add(pp);
                                // Use first window found. Ideally there should be just one matching
                                break;
                            }
                        }
                    }
                    else
                    {
                        // get total number of records
                        int rowCount = int.Parse(ds.Tables[0].Rows[cnt][0].ToString());
                        if (rowCount != 0)
                        {
                            // make a key name pair
                            KeyNamePair pp = new KeyNamePair(zoom_Window_ID, zoom_WindowName);
                            zoomList.Add(pp);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // fill error log
                log.Log(Level.SEVERE, sql1, e);
                //VAdvantage.//Common.////ErrorLog.FillErrorLog("ZoomTarget.GetZoomTargets", GlobalVariable.LAST_EXECUTED_QUERY, e.Message, VAdvantage.Framework.Message.MessageType.ERROR);
            }

            return(zoomList);
        }
                                                   }                                               /** Static Constructor
                                                                                                    * Set Table ID By Table Name
                                                                                                    * added by ->Harwinder */

                                                   static X_INT15_AcctSchema_Default()
                                                   {
                                                       Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID, Table_Name);
                                                   }                                               /** Serial Version No */
Exemplo n.º 12
0
/** Static Constructor
 * Set Table ID By Table Name
 * added by ->Harwinder */
        static X_A_Asset_Delivery()
        {
            Table_ID = Get_Table_ID(Table_Name);
            model    = new KeyNamePair(Table_ID, Table_Name);
        }
/** Static Constructor
 * Set Table ID By Table Name
 * added by ->Harwinder */
        static X_C_OrderTax()
        {
            Table_ID = Get_Table_ID(Table_Name);
            model    = new KeyNamePair(Table_ID, Table_Name);
        }
        /// <summary>
        /// return org access list aginst client and role of user
        /// </summary>
        /// <param name="AD_Role_ID">role id </param>
        /// <param name="AD_User_ID">user id</param>
        /// <param name="AD_Client_ID"> client id</param>
        /// <returns></returns>
        public static List <KeyNamePair> GetOrgs(int AD_Role_ID, int AD_User_ID, int AD_Client_ID)
        {
            List <KeyNamePair> list = new List <KeyNamePair>();

            String sql = "SELECT o.AD_Org_ID,o.Name,o.IsSummary "       //	1..3
                         + "FROM AD_Role r, AD_Client c"
                         + " INNER JOIN AD_Org o ON (c.AD_Client_ID=o.AD_Client_ID OR o.AD_Org_ID=0) "
                         + "WHERE r.AD_Role_ID='" + AD_Role_ID + "'"    //	#1
                         + " AND c.AD_Client_ID='" + AD_Client_ID + "'" //	#2
                         + " AND o.IsActive='Y' AND o.IsSummary='N' AND o.IsCostCenter='N' AND o.IsProfitCenter='N' "
                         + " AND (r.IsAccessAllOrgs='Y' "
                         + "OR (r.IsUseUserOrgAccess='N' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_Role_OrgAccess ra "
                         + "WHERE ra.AD_Role_ID=r.AD_Role_ID AND ra.IsActive='Y')) "
                         + "OR (r.IsUseUserOrgAccess='Y' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_User_OrgAccess ua "
                         + "WHERE ua.AD_User_ID='" + AD_User_ID + "' AND ua.IsActive='Y'))"             //	#3
                         + ") "
                         + "ORDER BY o.Name";
            //
            MRole       role = null;
            IDataReader dr   = null;

            //list.Add(new KeyNamePair(-1, "Select"));
            try
            {
                dr = DB.ExecuteReader(sql);
                //  load Orgs
                Ctx ctx = new Ctx();
                while (dr.Read())
                {
                    int    AD_Org_ID = Util.GetValueOfInt(dr[0].ToString());
                    String Name      = dr[1].ToString();
                    bool   summary   = "Y".Equals(dr[2].ToString());
                    if (summary)
                    {
                        if (role == null)
                        {
                            ctx.SetAD_Client_ID(AD_Client_ID);
                            role = MRole.Get(ctx, AD_Role_ID, AD_User_ID, false);
                        }
                        GetOrgsAddSummary(list, AD_Org_ID, Name, role, ctx);
                    }
                    else
                    {
                        KeyNamePair p = new KeyNamePair(AD_Org_ID, Name);
                        if (!list.Contains(p))
                        {
                            list.Add(p);
                        }
                    }
                }
                dr.Close();

                //
                //retValue = new KeyNamePair[list.Count];
                // retValue = list.ToArray();
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                }
            }

            //	No Orgs
            return(list);
        }   //  getOrgs
Exemplo n.º 15
0
 /** Static Constructor
  * Set Table ID By Table Name
  * added by ->Harwinder */
 static X_C_CashLine()
 {
     Table_ID = Get_Table_ID(Table_Name);
     model    = new KeyNamePair(Table_ID, Table_Name);
 }
        /// <summary>
        /// Get Roles for the user with email in client with the web store.
        /// If the user does not have roles and the web store has a default role, it will return that.
        /// </summary>
        /// <param name="eMail">email add</param>
        /// <param name="password">password</param>
        /// <param name="W_Store_ID">web store</param>
        /// <returns></returns>
        private KeyNamePair[] GetRolesByEmail(String eMail, String password, int W_Store_ID)
        {
            long start = CommonFunctions.CurrentTimeMillis();

            if (eMail == null || eMail.Length == 0 ||
                password == null || password.Length == 0 ||
                W_Store_ID == 0)
            {
                return(null);
            }
            //	Cannot use encrypted password
            if (SecureEngine.IsEncrypted(password))
            {
                return(null);
            }

            KeyNamePair[]      retValue = null;
            List <KeyNamePair> list     = new List <KeyNamePair>();
            //
            String sql = "SELECT u.AD_User_ID, r.AD_Role_ID, u.Name "
                         + "FROM AD_User u"
                         + " INNER JOIN W_Store ws ON (u.AD_Client_ID=ws.AD_Client_ID) "
                         + " INNER JOIN AD_Role r ON (ws.AD_Role_ID=r.AD_Role_ID) "
                         + "WHERE u.EMail='" + eMail + "'"
                         + " AND (u.Password='******' OR u.Password='******')"
                         + " AND ws.W_Store_ID='" + W_Store_ID + "'"
                         + " AND (r.IsActive='Y' OR r.IsActive IS NULL)"
                         + " AND u.isActive='Y' AND ws.IsActive='Y'"
                         + " AND u.AD_Client_ID=ws.AD_Client_ID "
                         + "ORDER BY r.Name";

            m_roles.Clear();
            m_users.Clear();
            IDataReader dr = null;

            try
            {
                //	execute a query
                dr = DataBase.DB.ExecuteReader(sql);

                if (!dr.Read())
                {
                    dr.Close();
                    return(null);
                }

                int AD_User_ID = Utility.Util.GetValueOfInt(dr[0].ToString());
                m_ctx.SetAD_User_ID(AD_User_ID);
                m_user = new KeyNamePair(AD_User_ID, eMail);
                m_users.Add(AD_User_ID);        //	for role
                //
                int AD_Role_ID = Utility.Util.GetValueOfInt(dr[1].ToString());
                m_ctx.SetAD_Role_ID(AD_Role_ID);
                String Name = dr[2].ToString();
                m_ctx.SetContext("##AD_User_Name", Name);
                if (AD_Role_ID == 0)    //	User is a Sys Admin
                {
                    m_ctx.SetContext("#SysAdmin", "Y");
                }
                KeyNamePair p = new KeyNamePair(AD_Role_ID, Name);
                m_roles.Add(p);
                list.Add(p);

                dr.Close();
                //
                retValue = new KeyNamePair[list.Count];
                retValue = list.ToArray();
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                }
                retValue = null;
                m_ctx.SetContext("##AD_User_Name", eMail);
            }

            return(retValue);
        }
Exemplo n.º 17
0
                                                  }                                               /** Static Constructor
                                                                                                   * Set Table ID By Table Name
                                                                                                   * added by ->Harwinder */

                                                  static X_M_CostAllocationSetting()
                                                  {
                                                      Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID, Table_Name);
                                                  }                                               /** Serial Version No */
        }       //	getRoles

        /// <summary>
        /// Load Clients.
        /// <para>
        /// Sets Role info in context and loads its clients
        /// </para>
        /// </summary>
        /// <param name="role"> role information</param>
        /// <returns>list of valid client KeyNodePairs or null if in error</returns>
        public KeyNamePair[] GetClients(KeyNamePair role)
        {
            if (role == null)
            {
                throw new Exception("Role missing");
            }
            m_role = role;
            //	Web Store Login
            if (m_store != null)
            {
                return new KeyNamePair[] { new KeyNamePair(m_store.GetAD_Client_ID(), m_store.GetName() + " Tenant") }
            }
            ;

            //	Set User for Role
            int AD_Role_ID = role.GetKey();

            for (int i = 0; i < m_roles.Count; i++)
            {
                if (AD_Role_ID == m_roles[i].GetKey())
                {
                    int AD_User_ID = m_users[i];
                    m_ctx.SetAD_User_ID(AD_User_ID);
                    if (MUser.IsSalesRep(AD_User_ID))
                    {
                        m_ctx.SetContext("#SalesRep_ID", AD_User_ID);
                    }
                    m_user = new KeyNamePair(AD_User_ID, m_user.GetName());
                    break;
                }
            }

            List <KeyNamePair> list = new List <KeyNamePair>();

            KeyNamePair[] retValue = null;
            String        sql      = "SELECT DISTINCT r.UserLevel, r.ConnectionProfile, " //	1..2
                                     + " c.AD_Client_ID,c.Name "                          //	3..4
                                     + "FROM AD_Role r"
                                     + " INNER JOIN AD_Client c ON (r.AD_Client_ID=c.AD_Client_ID) "
                                     + "WHERE r.AD_Role_ID=@roleid" //	#1
                                     + " AND r.IsActive='Y' AND c.IsActive='Y'";

            //	get Role details
            IDataReader dr = null;

            try
            {
                SqlParameter[] param = new SqlParameter[1];
                param[0] = new SqlParameter("@roleid", role.GetKey());

                dr = DataBase.DB.ExecuteReader(sql, param);
                if (!dr.Read())
                {
                    dr.Close();
                    return(null);
                }

                //  Role Info
                m_ctx.SetAD_Role_ID(role.GetKey());
                m_ctx.SetContext("#AD_Role_Name", role.GetName());
                Ini.SetProperty(Ini.P_ROLE, role.GetName());
                //	User Level
                m_ctx.SetContext("#User_Level", dr[0].ToString());      //	Format 'SCO'

                //  load Clients
                do
                {
                    int         AD_Client_ID = Utility.Util.GetValueOfInt(dr[2].ToString());
                    String      Name         = dr[3].ToString();
                    KeyNamePair p            = new KeyNamePair(AD_Client_ID, Name);
                    list.Add(p);
                }while (dr.Read());
                dr.Close();
                //
                retValue = new KeyNamePair[list.Count];
                retValue = list.ToArray();
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                }
                retValue = null;
            }
            return(retValue);
        }
Exemplo n.º 19
0
        //public ActionResult Index(string param )
        //{
        //   // FormCollection fc = null;
        //    if (!string.IsNullOrEmpty(param))
        //    {
        //     //   fc = new FormCollection();
        //        TempData["param"] =  param;
        //        RedirectToAction("Index");
        //    }
        //    return Home(null);
        //}

        //[MethodImpl(MethodImplOptions.Synchronized)]
        //[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        /// <summary>
        /// Entry Point of Framework
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public ActionResult Index(FormCollection form)
        {
            if (Request.QueryString.Count > 0)
            {
                // string user = Request.QueryString["U"];
                // string pwd = Request.QueryString["P"];
                // AccountController ac = new AccountController();
                // LoginModel md = new LoginModel();
                // md.Login1Model = new Login1Model();
                // md.Login1Model.UserValue = user;
                // md.Login1Model.Password = pwd;
                //JsonResult jr =  ac.JsonLogin(md, "");
                // ac.SetAuthCookie(md, Response); //AutoLogin if all passed
                // return RedirectToAction("Index");
            }

            //if (!User.Identity.IsAuthenticated)
            //{
            //    // Required to allow javascript redirection through to browser
            //    this.Response.TrySkipIisCustomErrors = true;
            //    this.Response.Status = "401 Unauthorized";
            //    this.Response.StatusCode = 401;
            //    // note that the following line is .NET 4.5 or later only
            //    // otherwise you have to suppress the return URL etc manually!
            //    this.Response.SuppressFormsAuthenticationRedirect = true;
            //    // If we got this far, something failed

            //}


            var url = CloudLogin.IsAllowedToLogin(Request.Url.ToString());

            if (!string.IsNullOrEmpty(url))
            {
                return(RedirectPermanent(url));
            }


            VAdvantage.DataBase.DBConn.SetConnectionString();//Init database conection
            Language.GetLanguages();
            LoginModel model = null;

            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString.Count > 0)     /* if has value */
                {
                    return(RedirectToAction("Index")); /*redirect to same url without querystring*/
                }
                try
                {
                    //var conf = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                    //  SessionStateSection section = (SessionStateSection) conf.GetSection("system.web/sessionState");
                    // int timeout = (int) section.Timeout.TotalMinutes;
                    Session.Timeout = 20; // ideal timout
                }
                catch
                {
                }


                //AccountController a = new AccountController();
                //a.LogOff();
                FormsIdentity ident = User.Identity as FormsIdentity;
                Ctx           ctx   = null;
                if (ident != null)
                {
                    FormsAuthenticationTicket ticket = ident.Ticket;
                    string       loginContextString  = ticket.UserData;// get login context string from Form Ticket
                    LoginContext lCtx = JsonHelper.Deserialize(loginContextString, typeof(LoginContext)) as LoginContext;
                    IDataReader  dr   = null;



                    //create class from string
                    string key = "";
                    if (Session["ctx"] != null)
                    {
                        ctx = Session["ctx"] as Ctx;

                        //Update Old Session
                        MSession session = MSession.Get(ctx, false);
                        if (session != null)
                        {
                            session.Logout();
                        }

                        key = ctx.GetSecureKey();

                        //if (Session.Timeout < 2)
                        //{
                        SessionEventHandler.SessionEnd(ctx);
                        Session.Timeout = 17;
                        //}
                        Session["ctx"] = null;
                    }
                    ctx = new Ctx(lCtx.ctxMap); //cretae new context

                    /* fix for User Value Null value */

                    if (string.IsNullOrEmpty(ctx.GetContext("##AD_User_Value")))
                    {
                        return(new AccountController().LogOff());
                    }

                    if (key != "")
                    {
                        ctx.SetSecureKey(key);
                    }
                    Session["ctx"] = ctx;

                    //get login Language object on server
                    var loginLang = ctx.GetAD_Language();

                    Language l = Language.GetLanguage(ctx.GetAD_Language()); //Language.GetLoginLanguage();
                    l = VAdvantage.Utility.Env.VerifyLanguage(ctx, l);

                    ctx.SetContext(VAdvantage.Utility.Env.LANGUAGE, l.GetAD_Language());
                    ctx.SetContext(VAdvantage.Utility.Env.ISRIGHTTOLEFT, VAdvantage.Utility.Env.IsRightToLeft(loginLang) ? "Y" : "N");
                    new VAdvantage.Login.LoginProcess(ctx).LoadSysConfig();
                    LoginHelper.SetSysConfigInContext(ctx);

                    ViewBag.culture   = ctx.GetAD_Language();
                    ViewBag.direction = ctx.GetIsRightToLeft() ? "rtl" : "ltr";

                    //Change Authentication
                    model                           = new LoginModel();
                    model.Login1Model               = new Login1Model();
                    model.Login2Model               = new Login2Model();
                    model.Login1Model.UserValue     = ctx.GetContext("##AD_User_Value");
                    model.Login1Model.DisplayName   = ctx.GetContext("##AD_User_Name");
                    model.Login1Model.LoginLanguage = ctx.GetAD_Language();

                    model.Login2Model.Role      = ctx.GetAD_Role_ID().ToString();
                    model.Login2Model.Client    = ctx.GetAD_Client_ID().ToString();
                    model.Login2Model.Org       = ctx.GetAD_Org_ID().ToString();
                    model.Login2Model.Warehouse = ctx.GetAD_Warehouse_ID().ToString();


                    var         RoleList      = new List <KeyNamePair>();
                    var         ClientList    = new List <KeyNamePair>();
                    var         OrgList       = new List <KeyNamePair>();
                    var         WareHouseList = new List <KeyNamePair>();
                    string      username      = "";
                    IDataReader drRoles       = LoginHelper.GetRoles(model.Login1Model.UserValue, false, false);
                    int         AD_User_ID    = 0;
                    if (drRoles.Read())
                    {
                        do  //	read all roles
                        {
                            AD_User_ID = Util.GetValueOfInt(drRoles[0].ToString());
                            int         AD_Role_ID = Util.GetValueOfInt(drRoles[1].ToString());
                            String      Name       = drRoles[2].ToString();
                            KeyNamePair p          = new KeyNamePair(AD_Role_ID, Name);
                            RoleList.Add(p);
                            username = Util.GetValueOfString(drRoles["username"].ToString());
                        }while (drRoles.Read());
                    }
                    drRoles.Close();

                    model.Login1Model.AD_User_ID  = AD_User_ID;
                    model.Login1Model.DisplayName = username;

                    //string diableMenu = ctx.GetContext("#DisableMenu");
                    Helpers.MenuHelper mnuHelper = new Helpers.MenuHelper(ctx); // inilitilize menu class

                    bool disableMenu = MRole.GetDefault(ctx).IsDisableMenu();
                    ctx.SetIsBasicDB(mnuHelper.GetIsBasicDB());


                    // If Home page not linked OR home page Linked BUT Menu is not disabled , then show home page.
                    // If Home is linked as well as menu is disabled then don't load Default Home Page Settings
                    if (MRole.GetDefault(ctx).GetHomePage_ID() == 0 || (MRole.GetDefault(ctx).GetHomePage_ID() > 0 && !disableMenu))
                    {
                        HomeModels hm = new HomeModels();
                        objHomeHelp     = new HomeHelper();
                        hm              = objHomeHelp.getLoginUserInfo(ctx, 32, 32);
                        ViewBag.UserPic = hm.UsrImage;
                    }
                    ViewBag.DisplayName = model.Login1Model.DisplayName;

                    if (!disableMenu) // if menu is not disabled, only then load menu.
                    {
                        //get current user info
                        ViewBag.Menu        = mnuHelper.GetMenuTree();    // create tree
                        Session["barNodes"] = ViewBag.Menu.GetBarNodes(); /* add is session to get it in favourite call */

                        ViewBag.TreeHtml = mnuHelper.GetMenuTreeUI(ViewBag.Menu.GetRootNode(), @Url.Content("~/"));
                    }

                    ViewBag.disableMenu = disableMenu;

                    mnuHelper.dispose();

                    //  LoginHelper.GetClients(id)

                    ClientList    = LoginHelper.GetClients(ctx.GetAD_Role_ID());                                          // .Add(new KeyNamePair(ctx.GetAD_Client_ID(), ctx.GetAD_Client_Name()));
                    OrgList       = LoginHelper.GetOrgs(ctx.GetAD_Role_ID(), ctx.GetAD_User_ID(), ctx.GetAD_Client_ID()); // .Add(new KeyNamePair(ctx.GetAD_Org_ID(), ctx.GetAD_Org_Name()));
                    WareHouseList = LoginHelper.GetWarehouse(ctx.GetAD_Org_ID());                                         // .Add(new KeyNamePair(ctx.GetAD_Warehouse_ID(), ctx.GetContext("#M_Warehouse_Name")));


                    ViewBag.RoleList      = RoleList;
                    ViewBag.ClientList    = ClientList;
                    ViewBag.OrgList       = OrgList;
                    ViewBag.WarehouseList = WareHouseList;
                    lock (_lock)    // Locked bundle Object and session Creation to handle concurrent requests.
                    {
                        //Cretae new Sessin
                        MSession sessionNew = MSession.Get(ctx, true, GetVisitorIPAddress(true));


                        var lst = VAdvantage.ModuleBundles.GetStyleBundles(); //Get All Style Bundle
                        foreach (var b in lst)
                        {
                            if (!BundleTable.Bundles.Contains(b))
                            {
                                BundleTable.Bundles.Add(b); //Add in Mvc Bundle Table
                            }
                        }

                        var lstRTLStyle = VAdvantage.ModuleBundles.GetRTLStyleBundles(); //Get All Script Bundle

                        foreach (var b in lstRTLStyle)
                        {
                            if (!BundleTable.Bundles.Contains(b))
                            {
                                BundleTable.Bundles.Add(b); //Add in Mvc Bundlw Table
                            }
                        }

                        var lstScript = VAdvantage.ModuleBundles.GetScriptBundles(); //Get All Script Bundle

                        foreach (var b in lstScript)
                        {
                            if (!BundleTable.Bundles.Contains(b))
                            {
                                BundleTable.Bundles.Add(b); //Add in Mvc Bundlw Table
                            }
                        }

                        ViewBag.LibSuffix   = "";
                        ViewBag.FrameSuffix = "_v1";
                        int libFound = 0;
                        foreach (Bundle b in BundleTable.Bundles)
                        {
                            if (b.Path.Contains("ViennaBase") && b.Path.Contains("_v") && ViewBag.LibSuffix == "")
                            {
                                ViewBag.LibSuffix = Util.GetValueOfInt(ctx.GetContext("#FRONTEND_LIB_VERSION")) > 2
                                                      ? "_v3" : "_v2";
                                libFound++;
                            }

                            if (b.Path.Contains("VIS") && b.Path.Contains("_v"))
                            {
                                ViewBag.FrameSuffix = Util.GetValueOfInt(ctx.GetContext("#FRAMEWORK_VERSION")) > 1
                                                      ? "_v2" : "_v1";
                                libFound++;
                            }
                            if (libFound >= 2)
                            {
                                break;
                            }
                        }
                        //check system setting// set to skipped lib
                    }
                }
            }

            else
            {
                model             = new LoginModel();
                model.Login1Model = new Login1Model();
                if (Request.QueryString.Count > 0) /* if query has values*/
                {
                    try
                    {
                        TempData["user"] = SecureEngine.Decrypt(Request.QueryString["U"]); //get uservalue
                        TempData["pwd"]  = SecureEngine.Decrypt(Request.QueryString["P"]); //get userpwd
                    }
                    catch
                    {
                        TempData.Clear();
                    }
                    return(RedirectToAction("Index")); // redirect to same url to remove cookie
                }

                if (TempData.ContainsKey("user"))
                {
                    model.Login1Model.UserValue = TempData["user"].ToString() + "^Y^" + TempData["pwd"].ToString();
                    // model.Login1Model.Password = TempData.Peek("pwd").ToString();
                }

                model.Login1Model.LoginLanguage = "en_US";
                model.Login2Model = new Login2Model();

                ViewBag.RoleList      = new List <KeyNamePair>();
                ViewBag.OrgList       = new List <KeyNamePair>();
                ViewBag.WarehouseList = new List <KeyNamePair>();
                ViewBag.ClientList    = new List <KeyNamePair>();

                ViewBag.Languages = Language.GetLanguages();

                Session["ctx"]    = null;
                ViewBag.direction = "ltr";

                ViewBag.LibSuffix = "";
                foreach (Bundle b in BundleTable.Bundles)
                {
                    if (b.Path.Contains("ViennaBase") && b.Path.Contains("_v"))
                    {
                        ViewBag.LibSuffix = "_v2";
                        break;
                    }
                }
            }
            return(View(model));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public KeyNamePair[] GetOrgs(KeyNamePair client)
        {
            if (client == null)
            {
                throw new ArgumentException("Client missing");
            }
            //	Web Store Login
            if (m_store != null)
            {
                return new KeyNamePair[] { new KeyNamePair(m_store.GetAD_Org_ID(), m_store.GetName() + " Org") }
            }
            ;

            if (m_ctx.GetContext("#AD_Role_ID").Length == 0)    //	could be number 0
            {
                throw new Exception("Missing Context #AD_Role_ID");
            }

            int AD_Role_ID = m_ctx.GetAD_Role_ID();
            int AD_User_ID = m_ctx.GetAD_User_ID();
            //	s_log.fine("Client: " + client.toStringX() + ", AD_Role_ID=" + AD_Role_ID);

            //	get Client details for role
            List <KeyNamePair> list = new List <KeyNamePair>();

            KeyNamePair[] retValue = null;
            //
            String sql = "SELECT o.AD_Org_ID,o.Name,o.IsSummary "       //	1..3
                         + "FROM AD_Role r, AD_Client c"
                         + " INNER JOIN AD_Org o ON (c.AD_Client_ID=o.AD_Client_ID OR o.AD_Org_ID=0) "
                         + "WHERE r.AD_Role_ID='" + AD_Role_ID + "'"       //	#1
                         + " AND c.AD_Client_ID='" + client.GetKey() + "'" //	#2
                         + " AND o.IsActive='Y' AND o.IsSummary='N'"
                         + " AND (r.IsAccessAllOrgs='Y' "
                         + "OR (r.IsUseUserOrgAccess='N' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_Role_OrgAccess ra "
                         + "WHERE ra.AD_Role_ID=r.AD_Role_ID AND ra.IsActive='Y')) "
                         + "OR (r.IsUseUserOrgAccess='Y' AND o.AD_Org_ID IN (SELECT AD_Org_ID FROM AD_User_OrgAccess ua "
                         + "WHERE ua.AD_User_ID='" + AD_User_ID + "' AND ua.IsActive='Y'))"             //	#3
                         + ") "
                         + "ORDER BY o.Name";
            //
            MRole       role = null;
            IDataReader dr   = null;

            try
            {
                dr = DataBase.DB.ExecuteReader(sql);
                //  load Orgs
                while (dr.Read())
                {
                    int    AD_Org_ID = Utility.Util.GetValueOfInt(dr[0].ToString());
                    String Name      = dr[1].ToString();
                    bool   summary   = "Y".Equals(dr[2].ToString());
                    if (summary)
                    {
                        if (role == null)
                        {
                            role = MRole.Get(m_ctx, AD_Role_ID, AD_User_ID, false);
                        }
                        GetOrgsAddSummary(list, AD_Org_ID, Name, role);
                    }
                    else
                    {
                        KeyNamePair p = new KeyNamePair(AD_Org_ID, Name);
                        if (!list.Contains(p))
                        {
                            list.Add(p);
                        }
                    }
                }
                dr.Close();

                //
                retValue = new KeyNamePair[list.Count];
                retValue = list.ToArray();
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                }
                retValue = null;
            }

            //	No Orgs
            if (retValue == null || retValue.Length == 0)
            {
                return(null);
            }

            //  Client Info
            m_ctx.SetContext("#AD_Client_ID", client.GetKey());
            m_ctx.SetContext("#AD_Client_Name", client.GetName());
            Ini.SetProperty(Ini.P_CLIENT, client.GetName());
            return(retValue);
        }   //  getOrgs
/** Static Constructor
 * Set Table ID By Table Name
 * added by ->Harwinder */
        static X_C_LandedCostAllocation()
        {
            Table_ID = Get_Table_ID(Table_Name);
            model    = new KeyNamePair(Table_ID, Table_Name);
        }
        }       //	getOrgAddSummary

        /// <summary>
        ///  Load Warehouses
        /// </summary>
        /// <param name="org"></param>
        /// <returns></returns>
        public KeyNamePair[] GetWarehouses(KeyNamePair org)
        {
            ;
            if (org == null)
            {
                throw new Exception("Org missing");
            }
            m_org = org;
            if (m_store != null)
            {
                return new KeyNamePair[] { new KeyNamePair(m_store.GetM_Warehouse_ID(), m_store.GetName() + " Warehouse") }
            }
            ;

            //	s_log.info("loadWarehouses - Org: " + org.toStringX());

            List <KeyNamePair> list = new List <KeyNamePair>();

            KeyNamePair[] retValue = null;
            String        sql      = "SELECT M_Warehouse_ID, Name FROM M_Warehouse "
                                     + "WHERE AD_Org_ID=@p1 AND IsActive='Y' "
                                     + "ORDER BY Name";
            IDataReader dr = null;

            try
            {
                SqlParameter[] param = new SqlParameter[1];

                param[0] = new SqlParameter("@p1", org.GetKey());
                dr       = DataBase.DB.ExecuteReader(sql, param);
                if (!dr.Read())
                {
                    dr.Close();
                    return(null);
                }

                //  load Warehouses
                do
                {
                    int         AD_Warehouse_ID = Utility.Util.GetValueOfInt(dr[0].ToString());
                    String      Name            = dr[1].ToString();
                    KeyNamePair p = new KeyNamePair(AD_Warehouse_ID, Name);
                    list.Add(p);
                }while (dr.Read());

                dr.Close();
                //
                retValue = new KeyNamePair[list.Count];
                retValue = list.ToArray();
            }
            catch
            {
                if (dr != null)
                {
                    dr.Close();
                }
                retValue = null;
            }

            return(retValue);
        }   //  getWarehouses
/** Static Constructor
 * Set Table ID By Table Name
 * added by ->Harwinder */
        static X_VA009_PaymentBatchLog()
        {
            Table_ID = Get_Table_ID(Table_Name);
            model    = new KeyNamePair(Table_ID, Table_Name);
        }
                                              }                                               /** Static Constructor
                                                                                               * Set Table ID By Table Name
                                                                                               * added by ->Harwinder */

                                              static X_GL_AssignAcctSchema()
                                              {
                                                  Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID, Table_Name);
                                              }                                               /** Serial Version No */
Exemplo n.º 25
0
        }                                                                                                /** Static Constructor
                                                                                                          * Set Table ID By Table Name
                                                                                                          * added by ->Harwinder */

        static X_AD_CardView_Condition()
        {
            Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID, Table_Name);
        }                                               /** Serial Version No */
Exemplo n.º 26
0
/** Static Constructor
 * Set Table ID By Table Name
 * added by ->Harwinder */
        static X_C_AccountGroup()
        {
            Table_ID = Get_Table_ID(Table_Name);
            model    = new KeyNamePair(Table_ID, Table_Name);
        }
Exemplo n.º 27
0
 /** Static Constructor
  * Set Table ID By Table Name
  * added by ->Harwinder */
 static X_VAMFG_M_WorkOrder()
 {
     Table_ID = Get_Table_ID(Table_Name);
     model    = new KeyNamePair(Table_ID, Table_Name);
 }
                                         }                                               /** Static Constructor
                                                                                          * Set Table ID By Table Name
                                                                                          * added by ->Harwinder */

                                         static X_AD_ModuleTable()
                                         {
                                             Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID, Table_Name);
                                         }                                               /** Serial Version No */
/** Static Constructor
 * Set Table ID By Table Name
 * added by ->Harwinder */
        static X_VA009_BatchLines()
        {
            Table_ID = Get_Table_ID(Table_Name);
            model    = new KeyNamePair(Table_ID, Table_Name);
        }
 ///<summary>
 /// Static Constructor
 /// Set Table ID By Table Name
 ///</summary>
 static X_AD_MailQueue()
 {
     Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID, Table_Name);
 }