コード例 #1
0
 public void Can_get_using_default_key()
 {
     var data = "test";
     _stateData[Utils.BuildFullKey<string>(null)] = data;
     var returned = new HttpSessionState(_context).Get<string>();
     Assert.That(returned, Is.EqualTo(data));
 }
コード例 #2
0
    //处理BeginRequest事件的实际代码
    void Application_AcquireRequestState(object sender, EventArgs e)
    {
        context = ((HttpApplication)sender).Context;
        request = context.Request;
        session = context.Session;

        requestPath = request.Path;
        defaultPath = request.ApplicationPath + "/Default.aspx";

        //仅处理向页面的请求,排除向资源文件的请求,排除非文件夹admin下的所有文件和后台首页
        //admin/index.aspx可以被任何已登陆用户访问,所以排除
        if (requestPath.IndexOf(".aspx") != -1 && !requestPath.StartsWith(defaultPath))
        {
            tbUser user = (tbUser)session[Constant.User];
            if (user == null)
            {
                //还没有登陆
                //context.Response.Redirect("~/Default.aspx");
                context.Response.Write("<script>parent.location.href='" + request.ApplicationPath + "/Default.aspx';</script>");
                context.Response.End();
            }
            else
            {
                bool isGranted = IsGranted(user.usertype, requestPath);
                if (isGranted == false)
                {
                    //没有权限访问
                    context.Response.Redirect("~/403.html");
                }

            }
        }
    }
コード例 #3
0
ファイル: AppState.cs プロジェクト: ClaireBrill/GPV
 public static void RemoveFrom(HttpSessionState session)
 {
   if (IsIn(session))
   {
     session.Remove(Key);
   }
 }
コード例 #4
0
ファイル: GameManager.cs プロジェクト: juncao/GuessingGame
    /// <summary>
    /// registerPlayer
    /// This method adds a player as a HttpSessionState object
    /// to the waitinglist.
    /// When there are two players 
    /// they are passed to a new Game object
    /// and removed from the list 
    /// </summary>
    public void registerPlayer(HttpSessionState player)
    {
        waitingList.Add(player);
        // if 2 or more waiting, make a game
        if( waitingList.Count >= 2 )
        {
            //Creates a new game
            //Sends the two session objects in the array
            //to the newly created game

            // Game constructor called passing name and SessionID for each player
            Game newGame = new Game(
                    (string)((HttpSessionState)waitingList[0])["Name"],
                    (string)((HttpSessionState)waitingList[0]).SessionID,
                    (string)((HttpSessionState)waitingList[1])["Name"],
                    (string)((HttpSessionState)waitingList[1]).SessionID );

            // Give each player HttpSessionState object a reference to the Game
            // This is one way communication instead of two way
            ((HttpSessionState)waitingList[0])["Game"] = newGame;
            ((HttpSessionState)waitingList[1])["Game"] = newGame;
            ((HttpSessionState)waitingList[0])["Status"] = "In Game";
            ((HttpSessionState)waitingList[1])["Status"] = "In Game";

            // remove from waiting list
            waitingList.RemoveAt(0);
            waitingList.RemoveAt(0);
        }
    }
コード例 #5
0
ファイル: DBHelper.cs プロジェクト: jbvios/mtbscout
    //--------------------------------------------------------------------------------
    public static void CountVisitor(HttpRequest request, HttpSessionState session)
    {
        string host = request["REMOTE_HOST"];
        long visitorSessionCount;
        using (ISession iSession = NHSessionManager.GetSession())
        {
            using (ITransaction transaction = iSession.BeginTransaction())
            {
                Visitor visitor = iSession.Get<Visitor>(host);
                if (visitor == null)
                    visitor = new Visitor(host);
                visitor.Visits++;
                iSession.SaveOrUpdate(visitor);
                iSession.Flush();
                visitorSessionCount = visitor.Visits;
                transaction.Commit();
                session[VisitorSessionCount] = visitorSessionCount;

            }

            Expression<Func<Visitor, object>> expr = v => v.Visits;
            var criteria = iSession.CreateCriteria<Visitor>()
                    .SetProjection(Projections.Sum(expr), Projections.Count(expr));
            object[] result = criteria.UniqueResult<object[]>();

            session[SessionCount] = Convert.ToInt64(result[0]);
            session[HostCount] = Convert.ToInt64(result[1]);
        }
    }
コード例 #6
0
 public void Can_get()
 {
     var data = "test";
     _stateData[typeof (string).FullName + "test_key"] = data;
     var returned = new HttpSessionState(_context).Get<string>("test_key");
     Assert.That(returned, Is.EqualTo(data));
 }
コード例 #7
0
ファイル: index.cs プロジェクト: sebseb7/xsphandler_sharp
    // static ?!?!?!?
    public static XmlDocument Query(HttpRequest req, HttpSessionState session,Hashtable xsltParameters)
    {
        XmlDocument inputDoc = new XmlDocument();

        inputDoc.AppendChild(inputDoc.CreateProcessingInstruction("http-redirect", "/"+xsltParameters["base"].ToString()+"/static.cs?page=index"));

        return inputDoc;
    }
コード例 #8
0
ファイル: Tools.cs プロジェクト: samercs/ArchiveSystem
 public Users GetUser(HttpSessionState session)
 {
     if (IsUserLogin(session))
     {
         Users u = session["User"] as Users;
         return u;
     }
     return null;
 }
コード例 #9
0
ファイル: SessionStateUtility.cs プロジェクト: nlhepler/mono
		public static void AddHttpSessionStateToContext (HttpContext context, IHttpSessionState container)
		{
			if (context == null || container == null)
				return;
			if (context.Session != null)
				throw new HttpException ("An HttpSessionState object for the current session has already been added to the specified context.");
			
			HttpSessionState state = new HttpSessionState (container);
			context.SetSession (state);
		}
コード例 #10
0
ファイル: UserSession.cs プロジェクト: BradFuller/pspplayer
    public static UserSession FromContext( HttpSessionState session, bool failOnMissing )
    {
        if( session == null )
            throw new ArgumentNullException( "session" );

        UserSession mySession = session[ "UserSession" ] as UserSession;
        if( ( mySession == null ) &&
            ( failOnMissing == false ) )
        {
            mySession = new UserSession();
            session.Add( "UserSession", mySession );
        }
        return mySession;
    }
コード例 #11
0
ファイル: Authenic.cs プロジェクト: 690312856/DIS
    public override bool Login(string username, string password, HttpSessionState session)
    {
        string sql = "select * from [User] where UserName = '******' and [Password] = '" + Utils.Crypto(password) + "'";
        DbDataReader r = DBHelper.INST.ExecuteSqlDR(sql);

        if (!r.Read())
            return false;

        session[IAuthenicable.NameKey] = username;
        session[IAuthenicable.IDKey] = r.GetInt32(0);

        return true;
    }
コード例 #12
0
        public void Update( String Sessionid, HttpSessionState session )
        {
            SessionReference _session = null;
            lock ( sessionCollection )
            _session = sessionCollection.ContainsKey( Sessionid ) ? sessionCollection[ Sessionid ] : new SessionReference();

            _session.Session = session;

            _session.LasAccess = DateTime.Now;
            lock ( sessionCollection )
            {
                sessionCollection[ Sessionid ] = _session;
            }
        }
コード例 #13
0
ファイル: LoaderScriptSupport.cs プロジェクト: tordf/iLabs
 /// <summary>
 /// Process will take all %field% in the loader script and replace them with values from
 /// the HTTPsession
 /// </summary>
 /// <param name="loaderScript"></param>
 /// <param name="session"></param>
 public static string process(ref string loaderScript, HttpSessionState session)
 {
     string newLoaderScript = loaderScript;
     int i = 0;
     while (-1 != (i = loaderScript.IndexOf('%')))
     {
         //int i = loaderScript.IndexOf('%');
         int y = loaderScript.IndexOf('%', i + 1);
         string variableName = loaderScript.Substring(i + 1, y - i - 1);
         string sessionValue = session[variableName] as string;
         newLoaderScript = newLoaderScript.Replace("%" + variableName + "%", sessionValue);
     }
     loaderScript = newLoaderScript;
     return newLoaderScript;
 }
コード例 #14
0
    /// <summary>コンストラクタ</summary>
    /// <param name="HashtableQueueName">キュー名</param>
    public CustQueue(string HashtableQueueName)
    {
        // セッションからキューを取り出す。
        this.Session = HttpContext.Current.Session;

        // セッションが空の場合は新規作成する。
        if (Session[HashtableQueueName] == null)
        {
            Session[HashtableQueueName] = new Queue();
        }

        // メンバに保持する。
        this._Queue = (Queue)Session[HashtableQueueName];

        // キューのキャパシティ
        this.Capacity = int.Parse(ConfigurationManager.AppSettings["QueueCapacity"]);
    }
コード例 #15
0
ファイル: AppState.cs プロジェクト: ClaireBrill/GPV
  public static AppState RestoreFrom(HttpSessionState session, bool remove)
  {
    if (IsIn(session))
    {
      AppState appState = FromString((string)session[Key]);

      if (remove)
      {
        RemoveFrom(session);
      }

      return appState;
    }
    else
    {
      return new AppState();
    }
  }
コード例 #16
0
    public static void EnforcePermissions_RequireAll(HttpSessionState session, HttpResponse response, bool requireStakeholder, bool requireMasterAdmin, bool requireAdmin, bool requirePrincipal, bool requireProvider, bool requireStaff)
    {
        UserView userView = UserView.GetInstance();

        if (requireStakeholder && !userView.IsStakeholder)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requireMasterAdmin && !userView.IsMasterAdmin)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requireAdmin       && !userView.IsAdmin)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requirePrincipal   && !userView.IsPrincipal)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requireProvider    && !userView.IsProvider)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());

        if (requireStaff       && !userView.IsStaff)
            response.Redirect(PagePermissions.UnauthorisedAccessPageForward());
    }
コード例 #17
0
ファイル: Authenic.cs プロジェクト: 690312856/DIS
 public abstract bool IsAuthenic(HttpSessionState session);
コード例 #18
0
ファイル: PaginasAplicacao.cs プロジェクト: dramosti/Web
 public static void Logoff(HttpResponse Response, HttpSessionState Session)
 {
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     Session.Clear();
     FormsAuthentication.SignOut();
 }
コード例 #19
0
 public SessionManager(HttpSessionState httpSessionState)
 {
     session = httpSessionState;
 }
コード例 #20
0
ファイル: UserSession.cs プロジェクト: BradFuller/pspplayer
 public static UserSession FromContext( HttpSessionState session )
 {
     return FromContext( session, false );
 }
コード例 #21
0
ファイル: Authenic.cs プロジェクト: 690312856/DIS
 public override void Logout(HttpSessionState session)
 {
     session.Clear();
 }
コード例 #22
0
ファイル: Tools.cs プロジェクト: samercs/ArchiveSystem
 public bool IsUserLogin(HttpSessionState session)
 {
     return session["User"] != null;
 }
コード例 #23
0
ファイル: MvcExtension.cs プロジェクト: EagleSmith/hiwjcn
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetObject <T>(this HttpSessionState session, string key)
        {
            var value = session[key]?.ToString();

            return(value == null ? default(T) : value.JsonToEntity <T>());
        }
コード例 #24
0
 private SessionAdapter()
 {
     _session = HttpContext.Current.Session;
 }
コード例 #25
0
 public SessionHelperService(HttpSessionState sessionState)
 {
     this._sessionState = sessionState;
 }
コード例 #26
0
ファイル: MvcExtension.cs プロジェクト: EagleSmith/hiwjcn
 /// <summary>
 /// 设置实体
 /// </summary>
 /// <param name="session"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public static void SetObject(this HttpSessionState session, string key, object value)
 {
     session[key] = value.ToJson();
 }
コード例 #27
0
ファイル: Extensions.cs プロジェクト: jojoli123/GuiZhouCore
 public static void SetString(this  HttpSessionState session, string key, string value)
 {
     session.Add(key, value);
 }
コード例 #28
0
 //Constructor
 public CultureHelper(HttpSessionState httpSessionState)
 {
     session = httpSessionState;
 }
コード例 #29
0
        }         //

        /// <summary>
        /// Helper Session method - future use if required to chg to another session provider such as SQL Server
        /// </summary>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <param name="sysObject"></param>
        public static void SessionSet(HttpSessionState session, string key, System.Object sysObject)
        {
            session[key] = sysObject;
        }         //
コード例 #30
0
ファイル: Authenic.cs プロジェクト: 690312856/DIS
 public abstract void Logout(HttpSessionState session);
コード例 #31
0
    void GetRegister()
    {
        if (string.IsNullOrEmpty(this.phone.Value.ToString()))
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('手机还没填呢!');</script>");

            return;
        }


        if (string.IsNullOrEmpty(this.USER_AGE.Value))
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('生日还没填呢!');</script>");

            return;
        }

        if (string.IsNullOrEmpty(this.name.Value))
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('姓名(会员名)还没填呢!');</script>");

            return;
        }

        if (string.IsNullOrEmpty(txtChkCode.Value))
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('请填写验证码!');</script>");
            return;
        }
        else
        {
            HttpSessionState Session = HttpContext.Current.Session;

            if (Session["MobileYzm"] == null)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('请重新获取验证码!');</script>");
                return;
            }

            if (Session["MobileYzm"].ToString() != txtChkCode.Value)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('验证码不正确,请重试!');</script>");
                return;
            }
        }

        if (!chkYes.Checked)
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('请接受服务协议!');</script>");
            return;
        }

        if (ddlMD.SelectedValue == "0")
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('请选择所属门店!');</script>");
            return;
        }

        MemberVO memberVO = new MemberVO();

        memberVO.phone = Request.Form["phone"];
        //  memberVO.gender = Request.Form["sex1"] == null ? Request.Form["sex2"] : Request.Form["sex1"];
        //   memberVO.gender = Request.Form["sex1"];
        memberVO.memName = Request.Form["name"];
        //   memberVO.OrgCode = ddlMD.SelectedValue;

        //  memberVO.idx = "2016071800001";
        memberVO.idx      = DateTime.Now.ToString("yyyyMMdd hhmmssfff");
        memberVO.birthday = Request.Form["USER_AGE"];

        int data = APIManage.Register.GetRegister(memberVO);



        if (data == 1223)
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('卡面号重复!');</script>");

            return;
        }
        else if (data == 1221)
        {
            APIManage.UpdateMem.updateM(memberVO.phone);

            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('手机号已存在,请登陆!');</script>");

            return;
        }
        else if (data == 1222)
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('证件号重复!');</script>");

            return;
        }



        else if (data == 0)
        {
            APIManage.UpdateMem.updateM(memberVO.phone);

            HttpCookie cookie = new HttpCookie("cookiePhone");
            cookie.Value   = phone.Value;
            cookie.Expires = DateTime.MaxValue;
            //cookie.Expires = DateTime.Now.Add(TimeSpan.MaxValue);
            HttpContext.Current.Response.Cookies.Add(cookie);
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>sky('成功!');</script>");

            //   Response.Redirect("index.aspx");
        }
        else
        {
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>show_err_msg('输入有误!');</script>");
            return;
        }
    }
コード例 #32
0
ファイル: Authenic.cs プロジェクト: 690312856/DIS
 public override bool IsAuthenic(HttpSessionState session)
 {
     return session[IAuthenicable.NameKey] != null;
 }
コード例 #33
0
ファイル: SessionManager.cs プロジェクト: kajpawl/AspNetMvc
 public SessionManager()
 {
     session = HttpContext.Current.Session;
 }
コード例 #34
0
ファイル: SignupProcessor.cs プロジェクト: Oxigen2/Oxigen
 public SignupProcessor(HttpSessionState session) : base(session)
 {
 }
コード例 #35
0
 public SessionTools(HttpSessionState session)
 {
     this.Session = session;
 }
コード例 #36
0
 public static string GetAsString(this HttpSessionState pair, string key, string defaultValue = "")
 {
     return((string)Get(pair, key, defaultValue));
 }
コード例 #37
0
ファイル: WebExtension.cs プロジェクト: yumaster/Tools
 /// <summary>
 /// 获取Session
 /// </summary>
 /// <typeparam name="T">对象</typeparam>
 /// <param name="session"></param>
 /// <param name="key">键</param>
 /// <returns>对象</returns>
 public static T Get <T>(this HttpSessionState session, string key) => (T)session[key];
コード例 #38
0
 public static void InitSession(HttpSessionState session)
 {
     session.Add(SESSION_KEY, new Dictionary <string, TempDir>());
 }
コード例 #39
0
ファイル: WebExtension.cs プロジェクト: yumaster/Tools
 /// <summary>
 /// 写Session
 /// </summary>
 /// <param name="session"></param>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 public static void Set(this HttpSessionState session, string key, dynamic value) => session[key] = value;
コード例 #40
0
ファイル: LoginManager.cs プロジェクト: NiponJaiboon/RiskEval
        private static UserSession CreateFailedSession(BizPortalSessionContext context, HttpSessionState session, iSystem systemApplication,
                                                       String ipAddress, string userName, MemberUser user, string message)
        {
            DateTime    now           = DateTime.Now;
            UserSession failedSession = new UserSession
            {
                ApplicationSessionID = session.SessionID,
                FromIPAddress        = ipAddress,
                LoginFailed          = true,
                LoginMessage         = message,
                SystemID             = systemApplication.SystemID,
                SessionPeriod        = new TimeInterval(now, now),
                User     = user,
                UserName = userName,
            };

            return(failedSession);
        }
コード例 #41
0
        public static bool SetSession(HttpSessionState session, long signInId)
        {
            if (session != null)
            {
                try
                {
                    if (signInId.Equals(0))
                    {
                        RequestLogOnPage();
                        return(false);
                    }

                    Entities.Office.SignInView signInView = Data.Office.User.GetSignInView(signInId);

                    if (signInView == null || signInView.LoginId == null)
                    {
                        session.Remove("UserName");
                        FormsAuthentication.SignOut();
                        return(false);
                    }

                    session["SignInTimestamp"]    = DateTime.Now;
                    session["LogOnId"]            = signInView.LoginId;
                    session["UserId"]             = signInView.UserId;
                    session["Culture"]            = signInView.Culture;
                    session["UserName"]           = signInView.UserName;
                    session["FullUserName"]       = signInView.FullName;
                    session["Role"]               = signInView.Role;
                    session["IsSystem"]           = signInView.IsSystem;
                    session["IsAdmin"]            = signInView.IsAdmin;
                    session["OfficeCode"]         = signInView.OfficeCode;
                    session["OfficeId"]           = signInView.OfficeId;
                    session["NickName"]           = signInView.NickName;
                    session["OfficeName"]         = signInView.OfficeName;
                    session["RegistrationDate"]   = signInView.RegistrationDate;
                    session["CurrencyCode"]       = signInView.CurrencyCode;
                    session["RegistrationNumber"] = signInView.RegistrationNumber;
                    session["PanNumber"]          = signInView.PanNumber;
                    session["AddressLine1"]       = signInView.AddressLine1;
                    session["AddressLine2"]       = signInView.AddressLine2;
                    session["Street"]             = signInView.Street;
                    session["City"]               = signInView.City;
                    session["State"]              = signInView.State;
                    session["Country"]            = signInView.Country;
                    session["ZipCode"]            = signInView.ZipCode;
                    session["Phone"]              = signInView.Phone;
                    session["Fax"]   = signInView.Fax;
                    session["Email"] = signInView.Email;
                    session["Url"]   = signInView.Url;

                    SetCulture();


                    return(true);
                }
                catch (DbException ex)
                {
                    Log.Warning("Cannot set session for user with SingIn #{SigninId}. {Exception}.", signInId, ex);
                }
            }

            return(false);
        }
コード例 #42
0
    public static Cart GetCartFromSession(HttpSessionState Session)
    {
        Cart cart = null;
        int site_id;
        bool logged_in = CartUsers.IsUserLoggedIn(Session);
        string user_id = logged_in ? CartUsers.GetUserName(Session) : "";
        if (Session[Constants.SessionKeys.SITE_ID] != null)
        {
            if (Int32.TryParse((string)Session[Constants.SessionKeys.SITE_ID], out site_id) == false)
            {
                throw new CartException("Could not find SiteID in current session");
            }
        }
        else
        {
            throw new CartException("Could not find SiteID in current session");
        }

        // This is a three step process
        // We do this because the current context of the shopping cart, should always override the saved context of the shopping cart.
        // This makes most sense in this scenario:
        /* So say you were browsing the site without logging in, and you've added a bunch of items to your cart.
           Now, you don't hit checkout or anything, but instead decide to log in to your account you remember you had.
           Should the cart you just created override any existing (saved) cart in the user account? */

        // 0. If a user is logged in, and the current session doesn't have any items in it, and a saved session exists, use it.
        if (logged_in)
        {
            cart = Cart.GetCartByUserID(site_id, Session.SessionID);
            if (cart != null && cart.IsLoaded && cart.HasItems == false)
            {
                cart = Cart.GetCartByUserID(site_id, user_id);
                if (cart != null && cart.IsLoaded)
                {
                    return cart;
                }
            }
        }

        // 1. If one exists in the current session, and it actually has items in it, use it. In this case, if the username has not been updated, update it.
        cart = Cart.GetCartByUserID(site_id, Session.SessionID);
        if (cart != null && cart.IsLoaded)
        {
            if (logged_in && cart.UserId == Session.SessionID)
            {
                CartDB db = new CartDB();
                db.CartUpdateUserId(cart.CartId, user_id);
            }
            cart.Refresh();
            return cart;
        }

        // 2. If this is not the case, try loading from the user id.
        if (logged_in)
        {
            cart = Cart.GetCartByUserID(site_id, user_id);
            if (cart != null && cart.IsLoaded)
            {
                return cart;
            }
        }

        // 3. If we still do not have one, just create a new one. If logged in, use the current username, if not, use the session id
        cart = Cart.CreateNew(site_id, logged_in ? user_id : Session.SessionID);
        if (cart != null && cart.IsLoaded)
        {
            return cart;
        }

        throw new CartException("Could not retrieve a cart from the current session");
    }
コード例 #43
0
ファイル: LoginManager.cs プロジェクト: NiponJaiboon/RiskEval
        /// <summary>
        /// Log in as a new session.  If success, regardless of expired password, set context.User to the user instance.
        /// If failed, it will throw exception with message in the language specified in context.CurrentLanguage.
        /// The user with expired password, the caller must force the user to change password.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="session"></param>
        /// <param name="application"></param>
        /// <param name="ipAddress"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="userMustChangePassword"></param>
        /// <returns>last log in time of the user</returns>
        //public static void Login(BizPortalSessionContext context, HttpSessionState session, HttpApplicationState application,
        //                            iSystem systemApplication, String ipAddress, String userName, String password, int systemID,
        //                            out bool userMustChangePassword, bool fakeLogin = false)
        public static void Login(BizPortalSessionContext context, HttpSessionState session, HttpApplicationState application, String ipAddress,
                                 String userName, String password, out bool userMustChangePassword)
        {
            userMustChangePassword = false;

            try
            {
                BizPortalConfiguration config = GetConfiguration(context, context.MySystem.SystemID);
                if (config.ID != BizPortalConfiguration.CurrentConfiguration.ID)
                {
                    BizPortalConfiguration.CurrentConfiguration = config;
                    //BizPortalConfiguration.CurrentConfiguration.Security.WebSessionTimeoutValueInMinutes = config.Security.WebSessionTimeoutValueInMinutes;
                    //BizPortalConfiguration.CurrentConfiguration.Security.PasswordPolicy.MinPasswordLength = config.Security.PasswordPolicy.MinPasswordLength;
                    //BizPortalConfiguration.CurrentConfiguration.Security.PasswordPolicy.MaxPasswordLength = config.Security.PasswordPolicy.MaxPasswordLength;
                    //BizPortalConfiguration.CurrentConfiguration.Security.MaxConsecutiveFailedLogonAttempts = config.Security.MaxConsecutiveFailedLogonAttempts;
                    //BizPortalConfiguration.CurrentConfiguration.Security.MaxDaysOfInactivity = config.Security.MaxDaysOfInactivity;
                    //BizPortalConfiguration.CurrentConfiguration.Security.MaxUsernameLength = config.Security.MaxUsernameLength;
                }
            }
            catch (Exception)
            {
                throw new Exception("เกิดข้อผิดพลาดในการติดต่อฐานข้อมูลกรุณาติดต่อผู้ดูแลระบบ");
            }

            MemberUser  mu          = null;
            LoginResult loginResult = LoginResult.IncorrectPassword;

            try
            {
                User user;
                loginResult = context.MySystem.Login(context, userName, password, out user, out userMustChangePassword);
                mu          = (MemberUser)context.PersistenceSession.GetSessionImplementation().PersistenceContext.Unproxy(user);
            }
            catch (Exception exc)
            {
                LogFailureSession(context, session.SessionID, userName, mu, exc.ToString());
                throw exc;
            }

            int    invalidPasswordAttemptLimit;
            string message = null;

            switch (loginResult)
            {
            case LoginResult.AuthenticationSuccess:
                if (mu.IsDisable)
                {
                    message = Messages.Security.UserIsDisable.Format(context.CurrentLanguage.Code);
                    LogFailureSession(context, session.SessionID, userName, mu, message);
                    throw new Exception(Messages.Security.UserIsDisableDisplayScreen.Format(context.CurrentLanguage.Code));
                }
                invalidPasswordAttemptLimit = context.Configuration.Security.MaxConsecutiveFailedLogonAttempts;
                if (mu.NumberOfConsecutiveFailedLoginAttemptsReachesLimit(invalidPasswordAttemptLimit))
                {
                    message = Messages.Security.UserIsSuspended.Format(context.CurrentLanguage.Code, invalidPasswordAttemptLimit);
                    LogFailureSession(context, session.SessionID, userName, mu, message);
                    SendSMSToSelfAuthenticatedUser(context, mu, message);
                    throw new Exception(Messages.Security.UserIsConsecutiveFailedLoginDisplayScreen.Format(context.CurrentLanguage.Code));
                }
                else if (mu.HasBeenInactiveTooLong(context.Configuration.Security.MaxDaysOfInactivity))
                {
                    message = Messages.Security.UserIsInactive.Format(context.CurrentLanguage.Code, context.Configuration.Security.MaxDaysOfInactivity);
                    LogFailureSession(context, session.SessionID, userName, mu, message);
                    SendSMSToSelfAuthenticatedUser(context, mu, message);
                    throw new Exception(Messages.Security.UserIsInactiveDisplayScreen.Format(context.CurrentLanguage.Code));
                }

                //Check for login collision
                var userId = mu.ID;

                var activeUsers = (Dictionary <long, string>)application["ActivingUsers"];
                if (activeUsers.ContainsKey(userId))
                {
                    ForceLogout(context, application, mu);
                    LogFailureSession(context, session.SessionID, userName, mu, Messages.Security.MultipleLogon.Format(context.CurrentLanguage.Code));
                    throw new Exception(Messages.Security.MultipleLogon.Format(context.CurrentLanguage.Code));
                }
                if (activeUsers.ContainsValue(session.SessionID))
                {
                    while (activeUsers.ContainsValue(session.SessionID))
                    {
                        foreach (var pair in activeUsers)
                        {
                            if (session.SessionID.Equals(pair.Value))
                            {
                                ForceLogoutForDIfferenceUserSameSession(context, application, mu);
                                break;
                            }
                        }
                    }
                }

                activeUsers.Add(userId, session.SessionID);
                break;

            case LoginResult.IncorrectPassword:
                invalidPasswordAttemptLimit = context.Configuration.Security.MaxConsecutiveFailedLogonAttempts;
                if (mu.NumberOfConsecutiveFailedLoginAttemptsReachesLimit(invalidPasswordAttemptLimit))
                {
                    message = Messages.Security.UserIsSuspended.Format(context.CurrentLanguage.Code, invalidPasswordAttemptLimit);
                }
                else
                {
                    message = Messages.Security.IncorrectPassword.Format(context.CurrentLanguage.Code, mu.ConsecutiveFailedLoginCount, invalidPasswordAttemptLimit);
                }

                LogFailureSession(context, session.SessionID, userName, mu, message);
                SendSMSToSelfAuthenticatedUser(context, mu, message);
                throw new Exception(Messages.Security.PasswordIsInvalidCode.Format(context.CurrentLanguage.Code));

            case LoginResult.UsernameNotFound:
                LogFailureSession(context, session.SessionID, userName, mu, Messages.Security.UsernameIsInvalidCode.Format(context.CurrentLanguage.Code));
                throw new Exception(Messages.Security.UsernameIsInvalidCode.Format(context.CurrentLanguage.Code));

            default:
                LogFailureSession(context, session.SessionID, userName, mu, Messages.Security.LoginFailed.Format(context.CurrentLanguage.Code));
                throw new Exception(Messages.Security.LoginFailed.Format(context.CurrentLanguage.Code));
            }

            context.User = mu;
            InitializeSession(context, mu, session);

            #region Old
            //}
            //catch (Exception exc)
            //{
            //    LogFailure(context, session, systemApplication, ipAddress, userName, mu, exc.ToString());
            //    if (exc.Message != Messages.Security.MultipleLogon.Format(context.CurrentLanguage.Code) && mu != null)
            //    {
            //        string loginFailed = Messages.Security.UsernameIsInvalidCode.Format(context.CurrentLanguage.Code, mu.ConsecutiveFailedLoginCount);
            //        if (mu is SelfAuthenticatedUser)
            //        {
            //            string messageSMS = "";

            //            if (exc.Message == Messages.Security.UserIsSuspendedForTooManyConsecutiveLoginFailures.Format(context.CurrentLanguage.Code,
            //                                               context.Configuration.Security.MaxConsecutiveFailedLogonAttempts))
            //            {
            //                messageSMS = Messages.Security.UserIsSuspendedForTooManyConsecutiveLoginFailures.Format(context.CurrentLanguage.Code,
            //                                               context.Configuration.Security.MaxConsecutiveFailedLogonAttempts);
            //            }
            //            else if (mu.ConsecutiveFailedLoginCount >= context.Configuration.Security.MaxConsecutiveFailedLogonAttempts)//by kittikun
            //            {
            //                messageSMS = Messages.Security.UserIsSuspendedForTooManyConsecutiveLoginFailures.Format(context.CurrentLanguage.Code,
            //                                               context.Configuration.Security.MaxConsecutiveFailedLogonAttempts);
            //            }
            //            else if (exc.Message == Messages.Security.UserHasBeenInactiveLongerThanLimit.Format(context.CurrentLanguage.Code, context.Configuration.Security.MaxDaysOfInactivity))
            //            {
            //                messageSMS = Messages.Security.UserHasBeenInactiveLongerThanLimit.Format(context.CurrentLanguage.Code,
            //                                                context.Configuration.Security.MaxDaysOfInactivity);
            //            }
            //            else
            //            {
            //                messageSMS = Messages.Security.UserIsDisableForExcessiveConsecutiveFailedLoginUnLimit.Format(
            //                    context.CurrentLanguage.Code,
            //                    mu.ConsecutiveFailedLoginCount,
            //                    context.Configuration.Security.MaxConsecutiveFailedLogonAttempts);
            //            }

            //            try
            //            {
            //                Adapter.SendLoginFailed(context, CIMB.Adapter.CIMBSMS.SmsLanguageType.TH, mu.MobilePhoneNumber, messageSMS);
            //            }
            //            catch (Exception ex)
            //            {
            //                context.Log(SystemFunctionID.Login.ID, 0, 0, ActionLog.SystemFunction.SendSMSFailed, string.Format("<b>ส่ง SMS ไม่สำเร็จ</b><br /><b>ข้อผิดพลาด</b> : {0}", ex.Message));
            //            }
            //        }
            //        context.Log(SystemFunctionID.Login.ID, 0, 0, SystemFunctionID.Login.Action.Failed, string.Format("<b>เข้าสู่ระบบไม่สำเร็จ</b><br /><b>ชื่อเข้าใช้งาน</b> : {0}<br /><b>ข้อผิดพลาด</b> : {1}", userName, exc.Message));

            //        throw;
            //    }
            //context.Log(SystemFunctionID.Login.ID, 0, 0, SystemFunctionID.Login.Action.Failed, string.Format("<b>เข้าสู่ระบบไม่สำเร็จ</b><br /><b>ชื่อเข้าใช้งาน</b> : {0}<br /><b>ข้อผิดพลาด</b> : {1}", userName, exc.Message));
            //throw exc;
            //}
            #endregion Old
        }
コード例 #44
0
ファイル: Authenic.cs プロジェクト: 690312856/DIS
 public abstract Users CurrentUser(HttpSessionState session);
コード例 #45
0
        public SessionStateContainer(HttpSessionState persistedDataContainer, string contextId)
        {
            DataContainer = persistedDataContainer;

            ContextId = contextId;
        }
コード例 #46
0
ファイル: Authenic.cs プロジェクト: 690312856/DIS
 public abstract bool Login(string username, string password, HttpSessionState session);
コード例 #47
0
ファイル: WebContext.cs プロジェクト: zszqwe/ClownFish.net
        public void AddSession(string name, object value)
        {
            HttpSessionState state = this.HttpContext.Items["AspSession"] as HttpSessionState;

            state.Add(name, value);
        }
コード例 #48
0
ファイル: Authenic.cs プロジェクト: 690312856/DIS
 public override Users CurrentUser(HttpSessionState session)
 {
     return null;
 }
コード例 #49
0
        public IHttpActionResult AddToCart(CartDto dto)
        {
            HttpSessionState session = HttpContext.Current.Session;

            List <CartViewModel> carts;

            if (dto.Id == null)
            {
                return(BadRequest());
            }

            var product = _unitOfWork.Products.Get((int)dto.Id);

            if (product == null)
            {
                return(NotFound());
            }

            var productDiscount = _unitOfWork.ProductDiscounts.GetProductDiscountNotDeleted()
                                  .SingleOrDefault(p => p.ProductId == product.Id);

            if (productDiscount != null)
            {
                product.Price = product.Price - (product.Price * productDiscount.Discount / 100);
            }
            var cart = new CartViewModel
            {
                ProductId = product.Id,
                Name      = product.Name,
                ImagePath = product.ImagePath,
                Price     = (decimal)product.Price,
                Quantity  = int.Parse(dto.Quantity ?? "1")
            };

            if (session["cart"] == null)
            {
                carts = new List <CartViewModel>();
                carts.Add(cart);
                session["cart"] = carts;
            }
            else
            {
                carts = session["cart"] as List <CartViewModel>;

                //To see if this item exsists before
                if (carts != null)
                {
                    var productInCart = carts.ToList().FirstOrDefault(c => c.ProductId == product.Id);

                    if (productInCart == null)
                    {
                        carts.Add(cart);
                    }
                    else
                    {
                        productInCart.Quantity += cart.Quantity;
                    }
                }

                session["cart"] = carts;
            }

            return(Ok());
        }
コード例 #50
0
ファイル: LoginManager.cs プロジェクト: NiponJaiboon/RiskEval
        private static void InitializeSession(BizPortalSessionContext context, MemberUser user, HttpSessionState session)
        {
            context.StartNewSession(user, session.SessionID);

            UserSession userSession = context.UserSession;

            session["UserPrivilegeLevel"]        = context.User.GetEffectivePrivilegeLevel(context.MySystem);
            session["ASP.modules_selectip_aspx"] = 0;

            MySiteMapProvider siteMap = MenuManager.BuildMenu(context, context.MySystem.GetRootMenus(context));

            session["MenuProvider"] = siteMap;

            MergeUserRoles(context, session);
        }
コード例 #51
0
 public static bool IsLoggedOut(this HttpSessionState instance)
 {
     return(instance[Common.SessionVariables.IsLogout] == true.ToString());
 }
コード例 #52
0
 public static void StoreSelectedItemsInSession(ListBox lb, HttpSessionState Session, String Key)
 {
     List<ListItem> list = new List<ListItem>();
     foreach (ListItem item in lb.Items)
     {
       list.Add(item);
     }
     Session[Key] = list;
 }
コード例 #53
0
 public static bool SetIsLoggedOut(this HttpSessionState instance, bool value)
 {
     instance[Common.SessionVariables.IsLogout] = value.ToString();
 }
コード例 #54
0
 public SecurityService(IUserService users, HttpSessionState session = null)
 {
     _users   = users;
     _session = session ?? HttpContext.Current.Session;
 }
コード例 #55
0
 public SessionManager(HttpSessionState session)
 {
     this._currentSession = session;
 }
コード例 #56
0
ファイル: SessionStateUtility.cs プロジェクト: nlhepler/mono
		public static void RaiseSessionEnd (IHttpSessionState session, Object eventSource, EventArgs eventArgs)
		{
			HttpSessionState state = new HttpSessionState (session);
			HttpApplicationFactory.InvokeSessionEnd (state, eventSource, eventArgs);
		}
コード例 #57
0
        /// <summary>
        /// Stores the querystring parameters found in the request for
        /// later use in the discovery process.
        /// </summary>
        /// <param name="context">HttpContext containing session, request, and response objects.</param>
        /// <returns>
        /// Returns the NameValueCollection containing the parameters stored
        /// into the session from the last invocation of the method
        /// StoreRequestParameters.
        /// </returns>
        public static NameValueCollection RetrieveRequestParameters(HttpContext context)
        {
            HttpSessionState session = context.Session;

            return((NameValueCollection)session[IdentityProviderDiscoveryUtils.OriginalParametersSessionAttribute]);
        }
コード例 #58
0
 public EditChannelWeightingProcessor(HttpSessionState session) : base(session)
 {
 }
コード例 #59
0
 public SessionStateContainer(HttpSessionState persistedDataContainer)
     : this(persistedDataContainer, "DEFAULT_CONTEXT")
 {
 }