Ejemplo n.º 1
0
        }       //	prepare

        /// <summary>
        /// Doit
        /// </summary>
        /// <returns>message</returns>
        protected override String DoIt()
        {
            log.Info("AD_Issue_ID=" + _AD_Issue_ID);
            if (!MSystem.Get(GetCtx()).IsAutoErrorReport())
            {
                return("NOT reported - Enable Error Reporting in Window System");
            }
            //
            MIssue issue = new MIssue(GetCtx(), _AD_Issue_ID, Get_TrxName());

            if (issue.Get_ID() == 0)
            {
                return("No Issue to report - ID=" + _AD_Issue_ID);
            }
            //
            String error = issue.Report();

            if (error != null)
            {
                throw new SystemException(error);
            }
            if (issue.Save())
            {
                return("Issue Reported: " + issue.GetRequestDocumentNo());
            }
            throw new SystemException("Issue Not Saved");
        }       //	doIt
Ejemplo n.º 2
0
 public void Initialize()
 {
     mSystemObjects               = new DeserializedObjects(mSystemDescription, _path);
     m_testMSystem                = new MSystem(mSystemObjects);
     m_tilesWorld                 = new TilesWorld(m_testMSystem);
     m_floatingObjWorld           = new FloatingObjectsWorld(m_testMSystem, m_tilesWorld);
     m_tilesWorld.FltObjectsWorld = m_floatingObjWorld;
 }
Ejemplo n.º 3
0
        public static void InitializeClass(TestContext context)
        {
            string    path = @"../../Classes/Xml/TestXML/testMSystemDescription.xml";
            XDocument mSystemDescription = XDocument.Load(path);
            var       mSystemObjects     = new DeserializedObjects(mSystemDescription, path);

            _testMSystem = new MSystem(mSystemObjects);
        }
Ejemplo n.º 4
0
        public void TestAreCompatible()
        {
            MSystem mSystem = new MSystem(v_TestDeserializedMSystemObjects);

            var c1 = mSystem.SeedTiles.First(tile => tile.Name == "q1").Connectors[0];
            var c2 = v_TestDeserializedMSystemObjects.Tiles["q1"].Connectors[1];
            var c3 = v_TestDeserializedMSystemObjects.Tiles["s1"].Connectors[1];

            Assert.IsTrue(mSystem.AreCompatible(c1, c2));
            Assert.IsFalse(mSystem.AreCompatible(c1, c3));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Server Base Class
        /// </summary>
        /// <param name="model"></param>
        /// <param name="initialNap">delay time running in sec</param>
        protected ViennaServer(ViennaProcessor model, int initialNap)

        {
            log    = VLogger.GetVLogger(this.GetType().FullName);
            _model = model;
            _ctx   = new Ctx(model.GetCtx().GetMap());
            if (_system == null)
            {
                _system = MSystem.Get(_ctx);
            }
            _client = MClient.Get(_ctx);
            _ctx.SetContext("#AD_Client_ID", _client.GetAD_Client_ID());
            _initialNap = initialNap;
        }
Ejemplo n.º 6
0
        public void TestConstructor()
        {
            MSystem mSystem = new MSystem(v_TestDeserializedMSystemObjects);

            // Tiles
            ReadOnlyDictionary <string, Tile> tiles = mSystem.Tiles;

            Assert.AreEqual(3, tiles.Count);
            Tile tileQ1     = tiles["q1"];
            var  connectors = tileQ1.Connectors;

            Assert.AreEqual(6, connectors.Count);
            var connectorC1 = connectors[0];

            Assert.AreEqual("c1", connectorC1.Name);
            Assert.AreEqual(Tile.SideType.undef, connectorC1.Side);
            Assert.AreEqual(v_TestDeserializedMSystemObjects.Glues["pa"], connectorC1.Glue);
            Assert.AreEqual(Angle.FromRadians(2.034443935795703), connectorC1.Angle);
            Assert.AreEqual(2, connectorC1.Positions.Count);
            Assert.AreEqual(new Point3D(0, 10, 0), connectorC1.Positions[0]);
            double posY = 10 * Math.Cos((1) * 2 * Math.PI / 5);
            double posX = 10 * Math.Sin((1) * 2 * Math.PI / 5);

            Assert.AreEqual(new Point3D(posX, posY, 0), connectorC1.Positions[1]);
            Glue surfaceGLuePx = tileQ1.SurfaceGlue;

            Assert.AreEqual("px", surfaceGLuePx.Name);
            Assert.AreEqual(4, tileQ1.Proteins.Count);
            Assert.AreEqual("p1", tileQ1.Proteins[0].Name);
            Assert.AreEqual("p1", tileQ1.Proteins[1].Name);
            Assert.AreEqual("p2", tileQ1.Proteins[2].Name);
            Assert.AreEqual("p2", tileQ1.Proteins[3].Name);
            foreach (var protein in tileQ1.Proteins)
            {
                Assert.AreEqual(Point3D.Origin, protein.Position);
            }

            Assert.AreEqual(Color.DeepSkyBlue, tileQ1.Color);
            Tile tileS1 = tiles["s1"];

            Assert.AreEqual(2, tileS1.Connectors.Count);
            Assert.AreEqual(1, tileS1.Proteins.Count);

            //Initial objects
            IReadOnlyList <TileInSpace> seedTiles = mSystem.SeedTiles;

            Assert.AreEqual(3, seedTiles.Count);
            TileInSpace seedTileQ1 = seedTiles[0];

            Assert.AreEqual("q1", seedTileQ1.Name);
            Assert.AreEqual(new Point3D(0, 0, 0), seedTileQ1.Position.Round(14));
            Assert.AreEqual(new EulerAngles(default(Angle), default(Angle), default(Angle)).ToQuaternion(), seedTileQ1.Quaternion);

            //Environmental objects
            var environmentalObjects = mSystem.FloatingObjects.Values.Where(obj => obj.Concentration > 0).ToList();

            Assert.AreEqual(1, environmentalObjects.Count);
            var environmentalObjectA = environmentalObjects[0];

            Assert.AreEqual("b", environmentalObjectA.Name);
            Assert.AreEqual(2, environmentalObjectA.Concentration);

            //GlueRadius
            Assert.AreEqual(0.1, mSystem.GlueRadius);

            //Mobility
            Assert.AreEqual(3, mSystem.Mobility);

            //Tolerance
            Assert.AreEqual(1E-10, MSystem.Tolerance);

            //SideDist
            Assert.AreEqual(5E-10, MSystem.SideDist);

            //GlueRelation
            GlueRelation glueTuples = mSystem.GlueRelation;

            Assert.AreEqual(3, glueTuples.Count);

            Tuple <Glue, Glue> glueTuplePaPb = glueTuples.Keys.ElementAt(0);

            Assert.AreEqual("pa", glueTuplePaPb.Item1.Name);
            Assert.AreEqual("pb", glueTuplePaPb.Item2.Name);
            Assert.AreEqual(1, glueTuples.Values.ElementAt(0).ToDictionary()["a"]);

            Tuple <Glue, Glue> glueTuplePaPa = glueTuples.Keys.ElementAt(1);

            Assert.AreEqual("pa", glueTuplePaPa.Item1.Name);
            Assert.AreEqual("pa", glueTuplePaPa.Item2.Name);
            Assert.AreEqual(1, glueTuples.Values.ElementAt(1).ToDictionary().Count);

            Tuple <Glue, Glue> glueTuplePbPb = glueTuples.Keys.ElementAt(2);

            Assert.AreEqual("pb", glueTuplePbPb.Item1.Name);
            Assert.AreEqual("pb", glueTuplePbPb.Item2.Name);
            Assert.AreEqual(0, glueTuples.Values.ElementAt(2).ToDictionary().Count);

            //MetabolicRules
            Dictionary <string, IReadOnlyList <EvoMetabolicRule> > metabolicRules = mSystem.MetabolicRules;

            Assert.AreEqual(2, metabolicRules.Count);
            Assert.IsNotNull(metabolicRules["p1"]);
            Assert.AreEqual(1, metabolicRules["p1"].Count);
            Assert.IsNotNull(metabolicRules["p2"]);
            Assert.AreEqual(0, metabolicRules["p2"].Count);

            EvoMetabolicRule metabolicRule = metabolicRules["p1"][0];

            Assert.AreEqual(0, metabolicRule.Priority);
            Assert.AreEqual(EvolutionRule.RuleType.Metabolic, metabolicRule.Type);
            Assert.AreEqual(EvoMetabolicRule.MetabolicRuleType.Symport, metabolicRule.SubType);
            Assert.AreEqual(2, metabolicRule.LeftSideObjects.Count);
            Assert.AreEqual("a", metabolicRule.LeftSideObjects[0].Name);
            Assert.AreEqual("p1", metabolicRule.LeftSideObjects[1].Name);
            Assert.AreEqual(2, metabolicRule.RightSideObjects.Count);
            Assert.AreEqual("p1", metabolicRule.RightSideObjects[0].Name);
            Assert.AreEqual("a", metabolicRule.RightSideObjects[1].Name);
            Assert.AreEqual(0, metabolicRule.MLeftInNames.Count);
            Assert.AreEqual(1, metabolicRule.MLeftOutNames.Count);
            Assert.AreEqual(1, metabolicRule.MLeftOutNames.ToDictionary()["a"]);
            Assert.AreEqual(1, metabolicRule.MRightInNames.Count);
            Assert.AreEqual(1, metabolicRule.MRightInNames.ToDictionary()["a"]);
            Assert.AreEqual(0, metabolicRule.MRightOutNames.Count);
            Assert.AreEqual("p1", metabolicRule.RProtein.Name);


            //CreationRules
            Dictionary <Glue, IReadOnlyList <EvoNonMetabolicRule> > createRules = mSystem.CreationRules;

            Assert.AreEqual(3, createRules.Count);

            Glue pa = v_TestDeserializedMSystemObjects.Glues["pa"];
            Glue pb = v_TestDeserializedMSystemObjects.Glues["pb"];
            Glue px = v_TestDeserializedMSystemObjects.Glues["px"];

            Assert.IsNotNull(createRules[pa]);
            Assert.AreEqual(1, createRules[pa].Count);
            Assert.IsNotNull(createRules[pb]);
            Assert.AreEqual(1, createRules[pb].Count);
            Assert.IsNotNull(createRules[px]);
            Assert.AreEqual(0, createRules[px].Count);

            // For different glues there is the same creation rule - this is OK.
            EvoNonMetabolicRule createRulePA = createRules[pa][0];

            Assert.AreEqual(1, createRulePA.Priority);
            Assert.AreEqual(EvolutionRule.RuleType.Create, createRulePA.Type);
            Assert.AreEqual(3, createRulePA.LeftSideObjects.Count);
            Assert.AreEqual("a", createRulePA.LeftSideObjects[0].Name);
            Assert.AreEqual("a", createRulePA.LeftSideObjects[1].Name);
            Assert.AreEqual("a", createRulePA.LeftSideObjects[2].Name);
            Assert.AreEqual(1, createRulePA.RightSideObjects.Count);
            Assert.AreEqual("q1", createRulePA.RightSideObjects[0].Name);
            Assert.AreEqual(3, createRulePA.MLeftSideFloatingNames.Count);
            Assert.AreEqual(3, createRulePA.MLeftSideFloatingNames.ToDictionary()["a"]);
            Assert.AreEqual(0, createRulePA.MRightSideFloatingNames.Count);

            // For different glues there is the same creation rule - this is OK.
            EvoNonMetabolicRule createRulePB = createRules[pb][0];

            Assert.AreEqual(1, createRulePB.Priority);
            Assert.AreEqual(EvolutionRule.RuleType.Create, createRulePB.Type);
            Assert.AreEqual(3, createRulePB.LeftSideObjects.Count);
            Assert.AreEqual("a", createRulePB.LeftSideObjects[0].Name);
            Assert.AreEqual("a", createRulePB.LeftSideObjects[1].Name);
            Assert.AreEqual("a", createRulePB.LeftSideObjects[2].Name);
            Assert.AreEqual(1, createRulePB.RightSideObjects.Count);
            Assert.AreEqual("q1", createRulePB.RightSideObjects[0].Name);
            Assert.AreEqual(3, createRulePB.MLeftSideFloatingNames.Count);
            Assert.AreEqual(3, createRulePB.MLeftSideFloatingNames.ToDictionary()["a"]);
            Assert.AreEqual(0, createRulePB.MRightSideFloatingNames.Count);

            //DestructionRules
            var destructionRules = mSystem.DestructionRules;

            Assert.AreEqual(3, destructionRules.Count);
            Assert.IsNotNull(destructionRules["q1"]);
            Assert.AreEqual(0, destructionRules["q1"].Count);
            Assert.IsNotNull(destructionRules["s1"]);
            Assert.AreEqual(1, destructionRules["s1"].Count);

            EvoNonMetabolicRule destroyRule = destructionRules["s1"][0];

            Assert.AreEqual(1, destroyRule.Priority);
            Assert.AreEqual(EvolutionRule.RuleType.Destroy, destroyRule.Type);
            Assert.AreEqual(3, destroyRule.LeftSideObjects.Count);
            Assert.AreEqual("a", destroyRule.LeftSideObjects[0].Name);
            Assert.AreEqual("a", destroyRule.LeftSideObjects[1].Name);
            Assert.AreEqual("s1", destroyRule.LeftSideObjects[2].Name);
            Assert.AreEqual(2, destroyRule.RightSideObjects.Count);
            Assert.AreEqual("c", destroyRule.RightSideObjects[0].Name);
            Assert.AreEqual("c", destroyRule.RightSideObjects[1].Name);
            Assert.AreEqual(2, destroyRule.MLeftSideFloatingNames.Count);
            Assert.AreEqual(2, destroyRule.MLeftSideFloatingNames.ToDictionary()["a"]);
            Assert.AreEqual(2, destroyRule.MRightSideFloatingNames.Count);
            Assert.AreEqual(2, destroyRule.MRightSideFloatingNames.ToDictionary()["c"]);

            //DivisionRules
            var divisionRules = mSystem.DivisionRules;

            Assert.AreEqual(1, divisionRules.Count);

            Assert.IsNotNull(divisionRules[pa]);
            Assert.AreEqual(1, divisionRules[pa].Count);

            Assert.IsNotNull(divisionRules[pa][pa]);
            Assert.AreEqual(1, divisionRules[pa][pa].Count);

            EvoNonMetabolicRule divideRule = divisionRules[pa][pa][0];

            Assert.AreEqual(1, divideRule.Priority);
            Assert.AreEqual(EvolutionRule.RuleType.Divide, divideRule.Type);
            Assert.AreEqual(4, divideRule.LeftSideObjects.Count);
            Assert.AreEqual("pa", divideRule.LeftSideObjects[0].Name);
            Assert.AreEqual("pa", divideRule.LeftSideObjects[1].Name);
            Assert.AreEqual("a", divideRule.LeftSideObjects[2].Name);
            Assert.AreEqual("a", divideRule.LeftSideObjects[3].Name);
            Assert.AreEqual(2, divideRule.RightSideObjects.Count);
            Assert.AreEqual("pa", divideRule.RightSideObjects[0].Name);
            Assert.AreEqual("pa", divideRule.RightSideObjects[1].Name);
            Assert.AreEqual(2, divideRule.MLeftSideFloatingNames.Count);
            Assert.AreEqual(2, divideRule.MLeftSideFloatingNames.ToDictionary()["a"]);
            Assert.AreEqual(0, divideRule.MRightSideFloatingNames.Count);
        }
        /// <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)
        {
            roles = null;
            // loginModel = null;
            //bool isMatch = false;

            SecureEngine.Encrypt("t"); //Initialize

            //	Cannot use encrypted password
            if (model.Login1Model.Password != null && SecureEngine.IsEncrypted(model.Login1Model.Password))
            {
                //log.warning("Cannot use Encrypted Password");
                return(false);
            }
            //	Authentification
            bool    authenticated = false;
            bool    isLDAP        = false;
            MSystem system        = MSystem.Get(new Ctx());

            if (system != null && system.IsLDAP())
            {
                authenticated = system.IsLDAP(model.Login1Model.UserName, model.Login1Model.Password);
                if (authenticated)
                {
                    model.Login1Model.Password = null;
                }
                isLDAP = true;
                // if not authenticated, use AD_User as backup
            }



            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
            if (isLDAP && authenticated)
            {
                sql.Append(" WHERE (COALESCE(u.LDAPUser,u.Value)=@username)");
            }
            else if (isLDAP && !authenticated && model.Login1Model.Password == null)// If user not authenicated using LDAP, then if LDAP user is available
            {
                sql.Append(" WHERE (u.LDAPUser=@username OR u.Name=@username OR u.Value=@username)");
            }
            else
            {
                sql.Append(" WHERE (u.Name=@username OR u.Value=@username)");
            }

            sql.Append(" AND u.IsActive='Y' ")
            .Append(" AND u.IsLoginUser='******' ")
            .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')");
            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));

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

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

            if (!dr.Read())             //	no record found
            {
                dr.Close();
                return(false);
            }

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

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

            List <int> usersRoles = new List <int>();


            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);

                roles.Add(p);

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

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


            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;
                        //1 firt check  - Check role exist
                        //if (usersRoles.Contains(Util.GetValueOfInt(drLogin[0])))
                        //{
                        //    //check for Org Access Setting
                        //    bool isUseUserOrgAccess = Util.GetValueOfString(DB.ExecuteScalar("SELECT IsUseUserOrgAccess FROM AD_ROLE WHERE AD_ROLE_ID = " + drLogin[0].ToString())) == "Y";
                        //    if (isUseUserOrgAccess) //User User Org
                        //    {
                        //        if (Convert.ToInt32(DB.ExecuteScalar("SELECT Count(1) FROM AD_User_OrgAccess WHERE AD_User_ID = " + AD_User_ID + " AND AD_ORG_ID= " + drLogin[2].ToString() + " AND IsActive='Y'")) < 1)
                        //        {
                        //            deleteRecord = true;
                        //        }
                        //    }
                        //    else //User Role Org Access
                        //    {
                        //        if (Convert.ToInt32(DB.ExecuteScalar("SELECT Count(1) FROM AD_Role_OrgAccess WHERE AD_Role_ID = " + drLogin[0] + " AND AD_ORG_ID= " + drLogin[2].ToString() + " AND IsActive='Y'")) < 1)
                        //        {
                        //            deleteRecord = true;
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    deleteRecord = true;
                        //}

                        //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);
        }
Ejemplo n.º 8
0
 //Initialize object/s before each test is run. It will be called for each test.
 public void Initialize()
 {
     _testDeserializedMSystemObjects = new DeserializedObjects(_mSystemDescription, _path);
     _testMSystem   = new MSystem(_testDeserializedMSystemObjects);
     _testSimulator = new SimulatorFacade(_testDeserializedMSystemObjects);
 }
Ejemplo n.º 9
0
 /// <summary>
 /// No functionality.
 /// </summary>
 /// <param name="mSystem">M system.</param>
 public void CalculateMSystemStats(MSystem mSystem)
 {
 }
        /// <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);
        }
Ejemplo n.º 11
0
        }       //	prepare

        /// <summary>
        /// DoIt
        /// </summary>
        /// <returns> Message</returns>
        protected override String DoIt()
        {
            int AD_Registration_ID = GetRecord_ID();

            log.Info("doIt - AD_Registration_ID=" + AD_Registration_ID);
            //	Check Ststem
            MSystem sys = MSystem.Get(GetCtx());

            if (sys.GetName().Equals("?") || sys.GetName().Length < 2)
            {
                throw new Exception("Set System Name in System Record");
            }
            if (sys.GetUserName().Equals("?") || sys.GetUserName().Length < 2)
            {
                throw new Exception("Set User Name (as in Web Store) in System Record");
            }
            if (sys.GetPassword().Equals("?") || sys.GetPassword().Length < 2)
            {
                throw new Exception("Set Password (as in Web Store) in System Record");
            }
            //	Registration
            M_Registration reg = new M_Registration(GetCtx(), AD_Registration_ID, Get_TrxName());
            //	Location
            MLocation loc = null;

            if (reg.GetC_Location_ID() > 0)
            {
                loc = new MLocation(GetCtx(), reg.GetC_Location_ID(), Get_TrxName());
                if (loc.GetCity() == null || loc.GetCity().Length < 2)
                {
                    throw new Exception("No City in Address");
                }
            }
            if (loc == null)
            {
                throw new Exception("Please enter Address with City");
            }

            //	Create Query String
            //String enc = WebEnv.ENCODING;
            //	Send GET Request
            StringBuilder urlString = new StringBuilder("http://www.ViennaAdvantage.com")
                                      .Append("/wstore/registrationServlet?");

            //	System Info
            urlString.Append("Name=").Append(HttpUtility.UrlEncode(sys.GetName(), UTF8Encoding.UTF8))
            .Append("&UserName="******"&Password="******"&Description=").Append(HttpUtility.UrlEncode(reg.GetDescription(), UTF8Encoding.UTF8));
            }
            urlString.Append("&IsInProduction=").Append(reg.IsInProduction() ? "Y" : "N");
            if (reg.GetStartProductionDate() != null)
            {
                urlString.Append("&StartProductionDate=").Append(HttpUtility.UrlEncode(Convert.ToString(reg.GetStartProductionDate()), UTF8Encoding.UTF8));
            }
            urlString.Append("&IsAllowPublish=").Append(reg.IsAllowPublish() ? "Y" : "N")
            .Append("&NumberEmployees=").Append(HttpUtility.UrlEncode(Convert.ToString(reg.GetNumberEmployees()), UTF8Encoding.UTF8))
            .Append("&C_Currency_ID=").Append(HttpUtility.UrlEncode(Convert.ToString(reg.GetC_Currency_ID()), UTF8Encoding.UTF8))
            .Append("&SalesVolume=").Append(HttpUtility.UrlEncode(Convert.ToString(reg.GetSalesVolume()), UTF8Encoding.UTF8));
            if (reg.GetIndustryInfo() != null && reg.GetIndustryInfo().Length > 0)
            {
                urlString.Append("&IndustryInfo=").Append(HttpUtility.UrlEncode(reg.GetIndustryInfo(), UTF8Encoding.UTF8));
            }
            if (reg.GetPlatformInfo() != null && reg.GetPlatformInfo().Length > 0)
            {
                urlString.Append("&PlatformInfo=").Append(HttpUtility.UrlEncode(reg.GetPlatformInfo(), UTF8Encoding.UTF8));
            }
            urlString.Append("&IsRegistered=").Append(reg.IsRegistered() ? "Y" : "N")
            .Append("&Record_ID=").Append(HttpUtility.UrlEncode(Convert.ToString(reg.GetRecord_ID()), UTF8Encoding.UTF8));
            //	Address
            urlString.Append("&City=").Append(HttpUtility.UrlEncode(loc.GetCity(), UTF8Encoding.UTF8))
            .Append("&C_Country_ID=").Append(HttpUtility.UrlEncode(Convert.ToString(loc.GetC_Country_ID()), UTF8Encoding.UTF8));
            //	Statistics
            if (reg.IsAllowStatistics())
            {
                urlString.Append("&NumClient=").Append(HttpUtility.UrlEncode(Convert.ToString(
                                                                                 DataBase.DB.GetSQLValue(null, "SELECT Count(*) FROM AD_Client")), UTF8Encoding.UTF8))
                .Append("&NumOrg=").Append(HttpUtility.UrlEncode(Convert.ToString(
                                                                     DataBase.DB.GetSQLValue(null, "SELECT Count(*) FROM AD_Org")), UTF8Encoding.UTF8))
                .Append("&NumBPartner=").Append(HttpUtility.UrlEncode(Convert.ToString(
                                                                          DataBase.DB.GetSQLValue(null, "SELECT Count(*) FROM C_BPartner")), UTF8Encoding.UTF8))
                .Append("&NumUser="******"SELECT Count(*) FROM AD_User")), UTF8Encoding.UTF8))
                .Append("&NumProduct=").Append(HttpUtility.UrlEncode(Convert.ToString(
                                                                         DataBase.DB.GetSQLValue(null, "SELECT Count(*) FROM M_Product")), UTF8Encoding.UTF8))
                .Append("&NumInvoice=").Append(HttpUtility.UrlEncode(Convert.ToString(
                                                                         DataBase.DB.GetSQLValue(null, "SELECT Count(*) FROM C_Invoice")), UTF8Encoding.UTF8));
            }
            log.Fine(urlString.ToString());

            //	Send it
            //URL url = new URL (urlString.toString());
            // Url url=new Url(urlString.ToString());
            Uri           url = new Uri(urlString.ToString());
            StringBuilder sb  = new StringBuilder();

            try
            {
                //URLConnection uc = url.openConnection();
                //System.IO.StreamReader inn = new System.IO.StreamReader(urlString.ToString());
                //InputStreamReader in = new InputStreamReader(uc.getInputStream());
                WebRequest  request  = WebRequest.Create(url.ToString());
                WebResponse response = (WebResponse)request.GetResponse();
                Stream      stream   = response.GetResponseStream();
                byte[]      buffer   = new byte[stream.Length];
                int         c;
                int         len        = Convert.ToInt32(stream.Length);
                String      tempstring = null;
                while ((c = stream.Read(buffer, 0, len)) > 0)
                {
                    //sb.Append((char)c);
                    tempstring = Encoding.ASCII.GetString(buffer, 0, len);
                    sb.Append(tempstring);
                }
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "Connect - " + e.ToString());
                throw new Exception("Cannot connect to Server - Please try later");
            }
            //
            String info = sb.ToString();

            log.Info("Response=" + info);
            //	Record at the end
            int index = sb.ToString().IndexOf("Record_ID=");

            if (index != -1)
            {
                try
                {
                    int Record_ID = Utility.Util.GetValueOfInt(sb.ToString().Substring(index + 10));
                    reg.SetRecord_ID(Record_ID);
                    reg.SetIsRegistered(true);
                    reg.Save();
                    //
                    info = info.Substring(0, index);
                }
                catch (Exception e)
                {
                    log.Log(Level.SEVERE, "Record - ", e);
                }
            }

            return(info);
        } //	doIt