Exemplo n.º 1
0
 /// <inheritdoc  cref="Owasp.Esapi.Interfaces.IHttpUtilities.ChangeSessionIdentifier()" />
 public void ChangeSessionIdentifier()
 {
     SessionIDManager manager = new SessionIDManager();
     string newSessionId = manager.CreateSessionID(HttpContext.Current);            
     bool redirected = false;
     bool IsAdded = false; 
     manager.SaveSessionID(HttpContext.Current, newSessionId, out redirected, out IsAdded);            
 }
Exemplo n.º 2
0
        protected void Session_Start(Object sender, EventArgs e)
        {
            SessionIDManager manager = new SessionIDManager();
            string newSessionId = manager.CreateSessionID(HttpContext.Current);

            var ckSession = new HttpCookie("omg-session");
            ckSession.Value = newSessionId;
            HttpContext.Current.Response.Cookies.Add(ckSession);
        }
Exemplo n.º 3
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if(filterContext.HttpContext.Session["SessionID"] == null)
            {

                SessionIDManager mgr = new SessionIDManager();
                string sessionID = mgr.CreateSessionID(HttpContext.Current);
                filterContext.HttpContext.Session.Timeout = 30;
                filterContext.HttpContext.Session["SessionID"] = sessionID;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            IHttpUtilities httpUtilities =  Esapi.HttpUtilities;
            httpUtilities.ChangeSessionIdentifier();
            SessionIDManager manager = new SessionIDManager();
            String orig = manager.GetSessionID(HttpContext.Current);

            if (String.IsNullOrEmpty(orig))
            {
                string newSessionId = manager.CreateSessionID(HttpContext.Current);
                Session["cookie"] = newSessionId;
            }
        }
Exemplo n.º 5
0
        protected string _AbandonSession()
        {
            Session.Abandon();
            Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

            SessionIDManager sessionManager = new SessionIDManager();
            string sID = sessionManager.CreateSessionID(System.Web.HttpContext.Current);
            bool redirected = false;
            bool cookieAdded = false;

            sessionManager.SaveSessionID(System.Web.HttpContext.Current, sID, out redirected, out cookieAdded);

            return sID;
        }
        private void RegenerateSessionId()
        {
            var Context = System.Web.HttpContext.Current;

            System.Web.SessionState.SessionIDManager manager = new System.Web.SessionState.SessionIDManager();
            string oldId = manager.GetSessionID(Context);
            string newId = manager.CreateSessionID(Context);
            bool   isAdd = false, isRedir = false;

            manager.SaveSessionID(Context, newId, out isRedir, out isAdd);
            HttpApplication      ctx  = Context.ApplicationInstance;
            HttpModuleCollection mods = ctx.Modules;

            System.Web.SessionState.SessionStateModule ssm = (SessionStateModule)mods.Get("Session");
            System.Reflection.FieldInfo[] fields           = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            SessionStateStoreProviderBase store            = null;

            System.Reflection.FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;
            foreach (System.Reflection.FieldInfo field in fields)
            {
                if (field.Name.Equals("_store"))
                {
                    store = (SessionStateStoreProviderBase)field.GetValue(ssm);
                }
                if (field.Name.Equals("_rqId"))
                {
                    rqIdField = field;
                }
                if (field.Name.Equals("_rqLockId"))
                {
                    rqLockIdField = field;
                }
                if (field.Name.Equals("_rqSessionStateNotFound"))
                {
                    rqStateNotFoundField = field;
                }
            }
            object lockId = rqLockIdField.GetValue(ssm);

            if ((lockId != null) && (oldId != null))
            {
                store.ReleaseItemExclusive(Context, oldId, lockId);
            }
            rqStateNotFoundField.SetValue(ssm, true);
            rqIdField.SetValue(ssm, newId);
        }
Exemplo n.º 7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            System.Web.SessionState.SessionIDManager Manager = new System.Web.SessionState.SessionIDManager();

            string NewID      = Manager.CreateSessionID(Context);
            bool   redirected = false;
            bool   IsAdded    = false;
            Manager.SaveSessionID(Context, NewID, out redirected, out IsAdded);

            this.UsuarioL.Focus();
            Session.Abandon();

            UsuarioL.Attributes.Add("onkeypress", "return clickButton(event,'" + BtnLogin.ClientID + "')");
            ContrasenaL.Attributes.Add("onkeypress", "return clickButton(event,'" + BtnLogin.ClientID + "')");
        }
    }
        private ISessionIDManager InitSessionIDManager(SessionStateSection config)
        {
            ISessionIDManager manager;
            string            sessionIDManagerType = config.SessionIDManagerType;

            if (string.IsNullOrEmpty(sessionIDManagerType))
            {
                manager = new SessionIDManager();
                this._usingAspnetSessionIdManager = true;
            }
            else
            {
                Type type = ConfigUtil.GetType(sessionIDManagerType, "sessionIDManagerType", config);
                ConfigUtil.CheckAssignableType(typeof(ISessionIDManager), type, config, "sessionIDManagerType");
                manager = (ISessionIDManager)HttpRuntime.CreatePublicInstance(type);
            }
            manager.Initialize();
            return(manager);
        }
        // Remove an item.  Note that the item is originally obtained by GetExclusive
        // Same note as Set on lockId
        public override void RemoveItem(HttpContext context,
                                        String id,
                                        object lockId,
                                        SessionStateStoreData item)
        {
            Debug.Assert(lockId != null, "lockId != null");

            string        key           = CreateSessionStateCacheKey(id);
            CacheInternal cacheInternal = HttpRuntime.CacheInternal;
            int           lockCookie    = (int)lockId;

            SessionIDManager.CheckIdLength(id, true /* throwOnFail */);

            InProcSessionState state = (InProcSessionState)cacheInternal.Get(key);

            /* If the item isn't there, we probably took too long to run. */
            if (state == null)
            {
                return;
            }

            state._spinLock.AcquireWriterLock();

            try {
                /* Only remove the item if we are the owner */
                if (!state._locked || state._lockCookie != lockCookie)
                {
                    return;
                }

                /* prevent overwriting when we drop the lock */
                state._lockCookie = 0;
            }
            finally {
                state._spinLock.ReleaseWriterLock();
            }

            cacheInternal.Remove(key);

            TraceSessionStats();
        }
Exemplo n.º 10
0
        public override void CreateUninitializedItem(HttpContext context, String id, int timeout)
        {
            string key = CreateSessionStateCacheKey(id);

            Debug.Assert(timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");

            SessionIDManager.CheckIdLength(id, true /* throwOnFail */);

            Debug.Trace("SessionStateClientSet", "Inserting an uninitialized item into Cache; key = " + key);

            InProcSessionState state = new InProcSessionState(
                null,
                null,
                timeout,
                false,
                DateTime.MinValue,
                NewLockCookie,
                (int)SessionStateItemFlags.Uninitialized);

            // DevDivBugs 146875
            // We do not want to overwrite an item with an uninitialized item if it is
            // already in the cache
            try {
            }
            finally {
                // protected from ThreadAbortEx
                object existingEntry = HttpRuntime.Cache.InternalCache.Add(key, state, new CacheInsertOptions()
                {
                    SlidingExpiration = new TimeSpan(0, timeout, 0),
                    Priority          = CacheItemPriority.NotRemovable,
                    OnRemovedCallback = _callback
                });
                if (existingEntry == null)
                {
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE);
                }
            }
        }
        public override void ReleaseItemExclusive(HttpContext context, string id, object lockId)
        {
            string key = this.CreateSessionStateCacheKey(id);
            int    num = (int)lockId;

            SessionIDManager.CheckIdLength(id, true);
            InProcSessionState state = (InProcSessionState)HttpRuntime.CacheInternal.Get(key);

            if ((state != null) && state._locked)
            {
                state._spinLock.AcquireWriterLock();
                try
                {
                    if (state._locked && (num == state._lockCookie))
                    {
                        state._locked = false;
                    }
                }
                finally
                {
                    state._spinLock.ReleaseWriterLock();
                }
            }
        }
        SessionStateStoreData DoGet(HttpContext context,
                                    String id,
                                    bool exclusive,
                                    out bool locked,
                                    out TimeSpan lockAge,
                                    out object lockId,
                                    out SessionStateActions actionFlags)
        {
            string key = CreateSessionStateCacheKey(id);

            // Set default return values
            locked      = false;
            lockId      = null;
            lockAge     = TimeSpan.Zero;
            actionFlags = 0;

            // Not technically necessary for InProc, but we do it to be consistent
            // with SQL provider
            SessionIDManager.CheckIdLength(id, true /* throwOnFail */);

            InProcSessionState state = (InProcSessionState)HttpRuntime.CacheInternal.Get(key);

            if (state != null)
            {
                bool lockedByOther;          // True if the state is locked by another session
                int  initialFlags;

                initialFlags = (int)state._flags;
                if ((initialFlags & (int)SessionStateItemFlags.Uninitialized) != 0)
                {
                    // It is an uninitialized item.  We have to remove that flag.
                    // We only allow one request to do that.
                    // For details, see inline doc for SessionStateItemFlags.Uninitialized flag.

                    // If initialFlags != return value of CompareExchange, it means another request has
                    // removed the flag.

                    Debug.Trace("SessionStateClientSet", "Removing the Uninit flag for item; key = " + key);
                    if (initialFlags == Interlocked.CompareExchange(
                            ref state._flags,
                            initialFlags & (~((int)SessionStateItemFlags.Uninitialized)),
                            initialFlags))
                    {
                        actionFlags = SessionStateActions.InitializeItem;
                    }
                }

                if (exclusive)
                {
                    lockedByOther = true;

                    // If unlocked, use a spinlock to test and lock the state.
                    if (!state._locked)
                    {
                        state._spinLock.AcquireWriterLock();
                        try {
                            if (!state._locked)
                            {
                                lockedByOther      = false;
                                state._locked      = true;
                                state._utcLockDate = DateTime.UtcNow;
                                state._lockCookie++;
                            }
                            lockId = state._lockCookie;
                        }
                        finally {
                            state._spinLock.ReleaseWriterLock();
                        }
                    }
                    else
                    {
                        // It's already locked by another request.  Return the lockCookie to caller.
                        lockId = state._lockCookie;
                    }
                }
                else
                {
                    state._spinLock.AcquireReaderLock();
                    try {
                        lockedByOther = state._locked;
                        lockId        = state._lockCookie;
                    }
                    finally {
                        state._spinLock.ReleaseReaderLock();
                    }
                }

                if (lockedByOther)
                {
                    // Item found, but locked
                    locked  = true;
                    lockAge = DateTime.UtcNow - state._utcLockDate;
                    return(null);
                }
                else
                {
                    return(SessionStateUtility.CreateLegitStoreData(context, state._sessionItems,
                                                                    state._staticObjects, state._timeout));
                }
            }

            // Not found
            return(null);
        }
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                        String id,
                                                        SessionStateStoreData item,
                                                        object lockId,
                                                        bool newItem)
        {
            string        key                         = CreateSessionStateCacheKey(id);
            bool          doInsert                    = true;
            CacheInternal cacheInternal               = HttpRuntime.CacheInternal;
            int           lockCookieForInsert         = NewLockCookie;
            ISessionStateItemCollection items         = null;
            HttpStaticObjectsCollection staticObjects = null;

            Debug.Assert(item.Items != null, "item.Items != null");
            Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null");
            Debug.Assert(item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");

            SessionIDManager.CheckIdLength(id, true /* throwOnFail */);

            if (item.Items.Count > 0)
            {
                items = item.Items;
            }

            if (!item.StaticObjects.NeverAccessed)
            {
                staticObjects = item.StaticObjects;
            }

            if (!newItem)
            {
                Debug.Assert(lockId != null, "lockId != null");
                InProcSessionState stateCurrent = (InProcSessionState)cacheInternal.Get(key);
                int lockCookie = (int)lockId;

                /* If the state isn't there, we probably took too long to run. */
                if (stateCurrent == null)
                {
                    return;
                }

                Debug.Trace("SessionStateClientSet", "state is inStorage; key = " + key);
                Debug.Assert((stateCurrent._flags & (int)SessionStateItemFlags.Uninitialized) == 0, "Should never set an unitialized item; key = " + key);

                stateCurrent._spinLock.AcquireWriterLock();

                try {
                    /* Only set the state if we are the owner */
                    if (!stateCurrent._locked || stateCurrent._lockCookie != lockCookie)
                    {
                        Debug.Trace("SessionStateClientSet", "Leave because we're not the owner; key = " + key);
                        return;
                    }

                    /* We can change the state in place if the timeout hasn't changed */
                    if (stateCurrent._timeout == item.Timeout)
                    {
                        stateCurrent.Copy(
                            items,
                            staticObjects,
                            item.Timeout,
                            false,
                            DateTime.MinValue,
                            lockCookie,
                            stateCurrent._flags);

                        // Don't need to insert into the Cache because an in-place copy is good enough.
                        doInsert = false;
                        Debug.Trace("SessionStateClientSet", "Changing state inplace; key = " + key);
                    }
                    else
                    {
                        /* We are going to insert a new item to replace the current one in Cache
                         * because the expiry time has changed.
                         *
                         * Pleas note that an insert will cause the Session_End to be incorrectly raised.
                         *
                         * Please note that the item itself should not expire between now and
                         * where we do UtcInsert below because CacheInternal.Get above have just
                         * updated its expiry time.
                         */
                        stateCurrent._flags |= (int)SessionStateItemFlags.IgnoreCacheItemRemoved;

                        /* By setting _lockCookie to 0, we prevent an overwriting by ReleaseExclusive
                         * when we drop the lock.
                         * The scenario can happen if another request is polling and trying to prempt
                         * the lock we have on the item.
                         */
                        lockCookieForInsert      = lockCookie;
                        stateCurrent._lockCookie = 0;
                    }
                }
                finally {
                    stateCurrent._spinLock.ReleaseWriterLock();
                }
            }

            if (doInsert)
            {
                Debug.Trace("SessionStateClientSet", "Inserting state into Cache; key = " + key);
                InProcSessionState state = new InProcSessionState(
                    items,
                    staticObjects,
                    item.Timeout,
                    false,
                    DateTime.MinValue,
                    lockCookieForInsert,
                    0);

                try {
                }
                finally {
                    // protected from ThreadAbortEx
                    cacheInternal.UtcInsert(
                        key, state, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, state._timeout, 0),
                        CacheItemPriority.NotRemovable, _callback);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE);

                    TraceSessionStats();
                }
            }
        }
 public void CreateNewSession()
 {
     SessionId = new SessionIDManager().CreateSessionID(null);
     _httpContext.ResponseCookies[AspNetSessionCookieName] = SessionId;
 }
 private ISessionIDManager InitSessionIDManager(SessionStateSection config)
 {
     ISessionIDManager manager;
     string sessionIDManagerType = config.SessionIDManagerType;
     if (string.IsNullOrEmpty(sessionIDManagerType))
     {
         manager = new SessionIDManager();
         this._usingAspnetSessionIdManager = true;
     }
     else
     {
         Type type = ConfigUtil.GetType(sessionIDManagerType, "sessionIDManagerType", config);
         ConfigUtil.CheckAssignableType(typeof(ISessionIDManager), type, config, "sessionIDManagerType");
         manager = (ISessionIDManager) HttpRuntime.CreatePublicInstance(type);
     }
     manager.Initialize();
     return manager;
 }
Exemplo n.º 16
0
        ISessionIDManager InitSessionIDManager(SessionStateSection config) {
            string  sessionIDManagerType = config.SessionIDManagerType;
            ISessionIDManager  iManager;

            if (String.IsNullOrEmpty(sessionIDManagerType)) {
                iManager = new SessionIDManager();
                _usingAspnetSessionIdManager = true;
            }
            else {
                Type    managerType;

                managerType = ConfigUtil.GetType(sessionIDManagerType, "sessionIDManagerType", config);
                ConfigUtil.CheckAssignableType(typeof(ISessionIDManager), managerType, config, "sessionIDManagerType");

                iManager = (ISessionIDManager)HttpRuntime.CreatePublicInstance(managerType);
            }

            iManager.Initialize();

            return iManager;
        }
        /// <summary>
        /// Try to retrive the existing session data from Redis
        /// If the data is not found, it will create a new session with a new sessionId
        /// </summary>
        private void InitSession()
        {
            // If sessionProvider is not null that means we already initialized the session and got the dataStore
            if (_sessionProvider == null)
            {
                _sessionProvider = new RedisASPSessionStateProvider();
            }

            _storeData = null;

            // Get write lock and session from cache
            bool locked;
            TimeSpan lockAge;
            object lockId;
            SessionStateActions actions;

            if (!string.IsNullOrWhiteSpace(_sessionId))
            {
                // Try Retrieve the existing session
                _storeData = _sessionProvider.GetItem(null, _sessionId, out locked, out lockAge, out lockId,
                    out actions);
            }

            // If we cannot find an existing session we will create a new one
            if (_storeData == null)
            {
                // Generate a new session id
                SessionIDManager Manager = new SessionIDManager();
                _sessionId = Manager.CreateSessionID(_context);

                // Create a new Session in Redis
                _sessionTimeout = (int)RedisSessionStateProvider.configuration.SessionTimeout.TotalMinutes;
                _sessionProvider.CreateUninitializedItem(null, _sessionId, _sessionTimeout);
                // Get the store Data from the new session created
                _storeData = _sessionProvider.GetItem(null, _sessionId, out locked, out lockAge, out lockId,
                    out actions);

                // If for some reason it failed to get the store data we raise an exception
                if (_storeData == null)
                {
                    throw new InvalidOperationException("Store Data cannot be created");
                }
            }
        }
        public void LoginUser(string user, string token)
        {
            if (!AuthenticateUser(user, token))
            {
                String result = "{result: 'error', errormsg: 'Login Failed!'}";
                SendResponse(result);
            }
            else
            {
                if(user.ToLower().Equals("guest"))
                {
                    user = "******";
                }

                User session_user = UserBLL.GetUserByEmail(user);

                SessionIDManager Manager = new System.Web.SessionState.SessionIDManager();
                string session_id = Manager.CreateSessionID(Context);
                GreyhoundSession session = new GreyhoundSession(session_id, session_user);

                // TODO: Implement session keys:
                //    1) generate a session key and ad it to the session keys table with an expiration date and associated to the user id
                //    2) return the key to the mobile application
                //    3) in each method call check the session key validity for the user id:
                //        i) if the key is invalid ignore the request
                //       ii) if the key is valid respond to the method call
                //      iii) if the key is valid but has expired generate a new key, return the key to the mobile app and respond to the method call

                String result = "{result: 'success', " +
                    "sessionid: '" + session.Session_Id + "'," +
                    "user_id: '" + session_user.User_Id + "'," +
                    "role_id: '" + session_user.Role_Id + "'," +
                    "name: '" + session_user.Name + "'," +
                    "address: '" + session_user.Address + "'," +
                    "mobile: '" + session_user.Mobile + "'," +
                    "paypal_id: '" + session_user.Paypal_Id + "'," +
                    "betfair_id: '" + session_user.Betfair_Id + "'," +
                    "expire: '" + session.Validity + "'}";

                SendResponse(result);
            }
        }
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            string        key           = this.CreateSessionStateCacheKey(id);
            bool          flag          = true;
            CacheInternal cacheInternal = HttpRuntime.CacheInternal;
            int           newLockCookie = NewLockCookie;
            ISessionStateItemCollection sessionItems  = null;
            HttpStaticObjectsCollection staticObjects = null;

            SessionIDManager.CheckIdLength(id, true);
            if (item.Items.Count > 0)
            {
                sessionItems = item.Items;
            }
            if (!item.StaticObjects.NeverAccessed)
            {
                staticObjects = item.StaticObjects;
            }
            if (!newItem)
            {
                InProcSessionState state = (InProcSessionState)cacheInternal.Get(key);
                int lockCookie           = (int)lockId;
                if (state == null)
                {
                    return;
                }
                state._spinLock.AcquireWriterLock();
                try
                {
                    if (!state._locked || (state._lockCookie != lockCookie))
                    {
                        return;
                    }
                    if (state._timeout == item.Timeout)
                    {
                        state.Copy(sessionItems, staticObjects, item.Timeout, false, DateTime.MinValue, lockCookie, state._flags);
                        flag = false;
                    }
                    else
                    {
                        state._flags     |= 2;
                        newLockCookie     = lockCookie;
                        state._lockCookie = 0;
                    }
                }
                finally
                {
                    state._spinLock.ReleaseWriterLock();
                }
            }
            if (flag)
            {
                InProcSessionState state2 = new InProcSessionState(sessionItems, staticObjects, item.Timeout, false, DateTime.MinValue, newLockCookie, 0);
                try
                {
                }
                finally
                {
                    cacheInternal.UtcInsert(key, state2, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, state2._timeout, 0), CacheItemPriority.NotRemovable, this._callback);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL);
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE);
                }
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// 保存当前请求的会话状态
 /// </summary>
 protected void SaveSessionState()
 {
     if (Context.Session != null && Context.Session.IsNewSession && !Context.Session.IsCookieless)
     {
         Context.Response.Cookies.Remove("ASP.NET_SessionId");
         bool redirected, cookieAdded; SessionIDManager sidMgr = new SessionIDManager();
         sidMgr.SaveSessionID(HttpContext.Current, Context.Session.SessionID, out redirected, out cookieAdded);
     }
 }
Exemplo n.º 21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Web.SessionState.SessionIDManager manager = new System.Web.SessionState.SessionIDManager();
        string oldId = manager.GetSessionID(Context);
        string name  = (string)Session["staffname"]; //TO GET THE WELCOME MESSAGE

        if (Session["id"] == null)
        {
            Response.Redirect("Login.aspx");
        }

        String logintime = (string)Session["lasttime"];

        current_test_status  = "Archived";
        current_test_status2 = "Completed";

        st_role = (string)Session["staffrole"];
        string login_staff_id = (string)Session["staffid"];

        // Code disables caching by browser.
        Response.Cache.SetCacheability(HttpCacheability.NoCache);// this tells the client not to cache responses in the History folder, so that when you use the back/forward buttons the client requests a new version of the response each time.
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();

        login_staff_ID = (string)Session["staffname"];


        if (st_role == "Instructor" || st_role == "Chief Instructor" || st_role == "Guest")
        {
            SqlConnection con9 = obj.getcon();
            con9.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection  = con9;
            cmd.CommandText = "select a.admin_id,a.testsession_id,a.test_type,a.test_date,a.testsession_status,UPPER(a.chiefinstructor_name) as chiefinstructor_name ,count(b.student_id) as student_id from testsession_details a ,student_vs_testsession_details b where a.testsession_status not in(@status1, @status2) and a.testsession_id=b.testsession_id group by   a.admin_id,a.testsession_id,a.test_type,a.test_date,a.testsession_status,a.chiefinstructor_name ORDER BY a.testsession_id DESC ";
            SqlParameter param1 = new SqlParameter("@status1", current_test_status);
            SqlParameter param2 = new SqlParameter("@status2", current_test_status2);
            cmd.Parameters.Add(param1);
            cmd.Parameters.Add(param2);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet        ds      = new DataSet();
            adapter.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();


            con9.Close();
        }
        else if (st_role == "Director/Asst Director")//if role=Admin
        {
            SqlConnection con8 = obj.getcon();
            con8.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection  = con8;
            cmd.CommandText = "select a.admin_id,a.testsession_id,a.test_type,a.test_date,a.testsession_status,UPPER(a.chiefinstructor_name) as chiefinstructor_name,count(b.student_id) as student_id from testsession_details a ,student_vs_testsession_details b where a.testsession_status<>@status1 and a.testsession_id=b.testsession_id group by   a.admin_id,a.testsession_id,a.test_type,a.test_date,a.testsession_status,a.chiefinstructor_name ORDER BY a.testsession_id DESC ";
            SqlParameter param1 = new SqlParameter("@status1", current_test_status);
            cmd.Parameters.Add(param1);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet        ds      = new DataSet();
            adapter.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            con8.Close();
        }
    }
Exemplo n.º 22
0
    private void ValidateUser(string userName, string password)
    {
        SqlConnection con = obj1.getcon();

        con.Open();

        SqlCommand cmd = new SqlCommand("select staff_id,staff_name,staff_role,NPstaff from staff_details where staff_id = @STAFF_id  ", con);

        cmd.Parameters.Add(new SqlParameter("STAFF_id", userName));
        SqlDataReader dr = cmd.ExecuteReader();
        // bool password_valid = NPpasswordCheck_BCLS(userName,password);//NP SERVER
        bool password_valid = ZTpasswordCheck_BCLS(userName, password); //LOCAL SERVER

        if (dr.HasRows && password_valid)                               //if username and password is correct
        {
            //  Session.Abandon();
            regenerateId();
            Guid   guid_string_Id = System.Guid.NewGuid();
            string newID          = guid_string_Id.ToString();
            Session["CPRactSessionCheck"] = newID;
            HttpCookie cookie = new HttpCookie("CPRactCookieCheck", newID);

            cookie.Values.Add("TRXID", (string)Session["CPRactSessionCheck"]);
            cookie.Values.Add("EVSS_ID", Session.SessionID);
            Response.Cookies.Add(cookie);
            //        Response.Cookies["CPRactCookieCheck"].Secure = true;//We can enable secure cookie to set true(HTTPs).


            dr.Read();
            s_id   = dr[0].ToString();
            s_name = dr[1].ToString();
            s_role = dr[2].ToString();

            if (s_role == "Guest")
            {
                Session["id"] = 01;
            }
            else if (s_role == "Instructor")
            {
                Session["id"] = 11;
            }

            else if (s_role == "Chief Instructor")
            {
                Session["id"] = 21;
            }
            else if (s_role == "Director/Asst Director")//Director/Asst Director
            {
                Session["id"] = 31;
            }
            else//there is a chnace for enter the role through sql query and misspelled
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "alert('Role assignment unsuccessful, please contact techincal support');window.location='Login.aspx';", true);
                return;
            }

            System.Web.SessionState.SessionIDManager manager = new System.Web.SessionState.SessionIDManager();
            string oldId = manager.GetSessionID(Context);
            //        regenerateId();
            Session["staffname"]      = s_name;
            Session["staffid"]        = s_id;
            Session["staffrole"]      = s_role;
            Session["staff_password"] = password;
            String last_interaction_time = DateTime.Now.ToString("dd/MM/yyyy HH:mm");//TO GET THE CURRENT LOGIN TIME
            Session["lasttime"] = last_interaction_time;
            if (s_role == "Chief Instructor")
            {
                Response.Redirect("follow_up.aspx");
            }
            else
            {
                Response.Redirect("Active_testsessiondetails.aspx");
            }
        }
        else
        {
            lb_invalid.Visible   = true;
            tb_password.Text     = "";
            hdnfldpassword.Value = "";
            // lb_invalid.Text =" Invalid userID or Password ! "+ " HasRows in DB: "+ dr.HasRows.ToString()+"  Valid LDAP: " + password_valid.ToString() ;
            lb_invalid.Text = " Invalid userID or Password ! ";
        }

        con.Close();
    }
Exemplo n.º 23
0
        private void MakeRequest(System.Web.UnsafeNativeMethods.StateProtocolVerb verb, string id, System.Web.UnsafeNativeMethods.StateProtocolExclusive exclusiveAccess, int extraFlags, int timeout, int lockCookie, byte[] buf, int cb, int networkTimeout, out System.Web.UnsafeNativeMethods.SessionNDMakeRequestResults results)
        {
            int num;
            OutOfProcConnection o = null;
            bool checkVersion     = false;

            SessionIDManager.CheckIdLength(id, true);
            if (this._partitionInfo == null)
            {
                this._partitionInfo = (StateServerPartitionInfo)s_partitionManager.GetPartition(this._partitionResolver, id);
                if (this._partitionInfo == null)
                {
                    throw new HttpException(System.Web.SR.GetString("Bad_partition_resolver_connection_string", new object[] { "PartitionManager" }));
                }
            }
            try
            {
                HandleRef ref2;
                o = (OutOfProcConnection)this._partitionInfo.RetrieveResource();
                if (o != null)
                {
                    ref2 = new HandleRef(this, o._socketHandle.Handle);
                }
                else
                {
                    ref2 = new HandleRef(this, INVALID_SOCKET);
                }
                if (this._partitionInfo.StateServerVersion == -1)
                {
                    checkVersion = true;
                }
                string uri = HttpUtility.UrlEncode(s_uribase + id);
                num = System.Web.UnsafeNativeMethods.SessionNDMakeRequest(ref2, this._partitionInfo.Server, this._partitionInfo.Port, networkTimeout, verb, uri, exclusiveAccess, extraFlags, timeout, lockCookie, buf, cb, checkVersion, out results);
                if (o != null)
                {
                    if (results.socket == INVALID_SOCKET)
                    {
                        o.Detach();
                        o = null;
                    }
                    else if (results.socket != ref2.Handle)
                    {
                        o._socketHandle = new HandleRef(this, results.socket);
                    }
                }
                else if (results.socket != INVALID_SOCKET)
                {
                    o = new OutOfProcConnection(results.socket);
                }
                if (o != null)
                {
                    this._partitionInfo.StoreResource(o);
                }
            }
            catch
            {
                if (o != null)
                {
                    o.Dispose();
                }
                throw;
            }
            if (num == 0)
            {
                if (results.httpStatus == 400)
                {
                    if (s_usePartition)
                    {
                        throw new HttpException(System.Web.SR.GetString("Bad_state_server_request_partition_resolver", new object[] { s_configPartitionResolverType, this._partitionInfo.Server, this._partitionInfo.Port.ToString(CultureInfo.InvariantCulture) }));
                    }
                    throw new HttpException(System.Web.SR.GetString("Bad_state_server_request"));
                }
                if (checkVersion)
                {
                    this._partitionInfo.StateServerVersion = results.stateServerMajVer;
                    if (this._partitionInfo.StateServerVersion < WHIDBEY_MAJOR_VERSION)
                    {
                        if (s_usePartition)
                        {
                            throw new HttpException(System.Web.SR.GetString("Need_v2_State_Server_partition_resolver", new object[] { s_configPartitionResolverType, this._partitionInfo.Server, this._partitionInfo.Port.ToString(CultureInfo.InvariantCulture) }));
                        }
                        throw new HttpException(System.Web.SR.GetString("Need_v2_State_Server"));
                    }
                }
            }
            else
            {
                HttpException exception = CreateConnectionException(this._partitionInfo.Server, this._partitionInfo.Port, num);
                string        str2      = null;
                switch (results.lastPhase)
                {
                case 0:
                    str2 = System.Web.SR.GetString("State_Server_detailed_error_phase0");
                    break;

                case 1:
                    str2 = System.Web.SR.GetString("State_Server_detailed_error_phase1");
                    break;

                case 2:
                    str2 = System.Web.SR.GetString("State_Server_detailed_error_phase2");
                    break;

                case 3:
                    str2 = System.Web.SR.GetString("State_Server_detailed_error_phase3");
                    break;
                }
                WebBaseEvent.RaiseSystemEvent(System.Web.SR.GetString("State_Server_detailed_error", new object[] { str2, "0x" + num.ToString("X08", CultureInfo.InvariantCulture), cb.ToString(CultureInfo.InvariantCulture) }), this, 0xbc1, 0xc360, exception);
                throw exception;
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// sigh - this fixes a f****d up issue, where previewing pages containing code writing to Session, 
        /// will breake all subsequent page previews regardless of content. Should you obtain the wisdom as
        /// to what exactly is the trick here, I'd love to now. I will leave it as "well, this fix the issue 
        /// and pass testing. Hurray for Harry Potter and magic!". Oh how I loathe doing that :(
        /// </summary>
        /// <param name="ctx">the Http context that will be shared between master and child process</param>
        private static void AllowChildRequestSessionAccess(HttpContext ctx)
        {
            SessionIDManager manager = new SessionIDManager();
            string oldId = manager.GetSessionID(ctx);
            string newId = manager.CreateSessionID(ctx);
            bool isAdd = false, isRedir = false;

            manager.SaveSessionID(ctx, newId, out isRedir, out isAdd);
            HttpApplication ctx2 = (HttpApplication)HttpContext.Current.ApplicationInstance;
            HttpModuleCollection mods = ctx2.Modules;
            SessionStateModule ssm = (SessionStateModule)mods.Get("Session");
            System.Reflection.FieldInfo[] fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            SessionStateStoreProviderBase store = null;
            System.Reflection.FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;
            foreach (System.Reflection.FieldInfo field in fields)
            {
                if (field.Name.Equals("_store")) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
                if (field.Name.Equals("_rqId")) rqIdField = field;
                if (field.Name.Equals("_rqLockId")) rqLockIdField = field;
                if (field.Name.Equals("_rqSessionStateNotFound")) rqStateNotFoundField = field;
            }
            object lockId = rqLockIdField.GetValue(ssm);
            if ((lockId != null) && (oldId != null)) store.ReleaseItemExclusive(ctx, oldId, lockId);
            rqStateNotFoundField.SetValue(ssm, true);
            rqIdField.SetValue(ssm, newId);
        }
Exemplo n.º 25
0
        void MakeRequest(
            UnsafeNativeMethods.StateProtocolVerb verb,
            String id,
            UnsafeNativeMethods.StateProtocolExclusive exclusiveAccess,
            int extraFlags,
            int timeout,
            int lockCookie,
            byte[]                                  buf,
            int cb,
            int networkTimeout,
            out UnsafeNativeMethods.SessionNDMakeRequestResults results)
        {
            int    hr;
            string uri;
            OutOfProcConnection conn = null;
            HandleRef           socketHandle;
            bool checkVersion = false;

            Debug.Assert(timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");

            SessionIDManager.CheckIdLength(id, true /* throwOnFail */);

            if (_partitionInfo == null)
            {
                Debug.Assert(s_partitionManager != null);
                Debug.Assert(_partitionResolver != null);

                _partitionInfo = (StateServerPartitionInfo)s_partitionManager.GetPartition(_partitionResolver, id);

                // If its still null, we give up
                if (_partitionInfo == null)
                {
                    throw new HttpException(SR.GetString(SR.Bad_partition_resolver_connection_string, "PartitionManager"));
                }
            }

            // Need to make sure we dispose the connection if anything goes wrong
            try {
                conn = (OutOfProcConnection)_partitionInfo.RetrieveResource();
                if (conn != null)
                {
                    socketHandle = new HandleRef(this, conn._socketHandle.Handle);
                }
                else
                {
                    socketHandle = new HandleRef(this, INVALID_SOCKET);
                }

                if (_partitionInfo.StateServerVersion == -1)
                {
                    // We don't need locking here because it's okay to have two
                    // requests initializing s_stateServerVersion.
                    checkVersion = true;
                }

                Debug.Trace("OutOfProcSessionStateStoreMakeRequest",
                            "Calling MakeRequest, " +
                            "socket=" + (IntPtr)socketHandle.Handle +
                            "verb=" + verb +
                            " id=" + id +
                            " exclusiveAccess=" + exclusiveAccess +
                            " timeout=" + timeout +
                            " buf=" + ((buf != null) ? "non-null" : "null") +
                            " cb=" + cb +
                            " checkVersion=" + checkVersion +
                            " extraFlags=" + extraFlags);

                // Have to UrlEncode id because it may contain non-URL-safe characters
                uri = HttpUtility.UrlEncode(s_uribase + id);

                hr = UnsafeNativeMethods.SessionNDMakeRequest(
                    socketHandle, _partitionInfo.Server, _partitionInfo.Port, _partitionInfo.ServerIsIPv6NumericAddress /* forceIPv6 */, networkTimeout, verb, uri,
                    exclusiveAccess, extraFlags, timeout, lockCookie,
                    buf, cb, checkVersion, out results);

                Debug.Trace("OutOfProcSessionStateStoreMakeRequest", "MakeRequest returned: " +
                            "hr=" + hr +
                            " socket=" + (IntPtr)results.socket +
                            " httpstatus=" + results.httpStatus +
                            " timeout=" + results.timeout +
                            " contentlength=" + results.contentLength +
                            " uri=" + (IntPtr)results.content +
                            " lockCookie=" + results.lockCookie +
                            " lockDate=" + string.Format("{0:x}", results.lockDate) +
                            " lockAge=" + results.lockAge +
                            " stateServerMajVer=" + results.stateServerMajVer +
                            " actionFlags=" + results.actionFlags);

                if (conn != null)
                {
                    if (results.socket == INVALID_SOCKET)
                    {
                        conn.Detach();
                        conn = null;
                    }
                    else if (results.socket != socketHandle.Handle)
                    {
                        // The original socket is no good.  We've got a new one.
                        // Pleae note that EnsureConnected has closed the bad
                        // one already.
                        conn._socketHandle = new HandleRef(this, results.socket);
                    }
                }
                else if (results.socket != INVALID_SOCKET)
                {
                    conn = new OutOfProcConnection(results.socket);
                }

                if (conn != null)
                {
                    _partitionInfo.StoreResource(conn);
                }
            }
            catch {
                // We just need to dispose the connection if anything bad happened
                if (conn != null)
                {
                    conn.Dispose();
                }

                throw;
            }

            if (hr != 0)
            {
                HttpException e = CreateConnectionException(_partitionInfo.Server, _partitionInfo.Port, hr);

                string phase = null;

                switch (results.lastPhase)
                {
                case (int)UnsafeNativeMethods.SessionNDMakeRequestPhase.Initialization:
                    phase = SR.GetString(SR.State_Server_detailed_error_phase0);
                    break;

                case (int)UnsafeNativeMethods.SessionNDMakeRequestPhase.Connecting:
                    phase = SR.GetString(SR.State_Server_detailed_error_phase1);
                    break;

                case (int)UnsafeNativeMethods.SessionNDMakeRequestPhase.SendingRequest:
                    phase = SR.GetString(SR.State_Server_detailed_error_phase2);
                    break;

                case (int)UnsafeNativeMethods.SessionNDMakeRequestPhase.ReadingResponse:
                    phase = SR.GetString(SR.State_Server_detailed_error_phase3);
                    break;

                default:
                    Debug.Assert(false, "Unknown results.lastPhase: " + results.lastPhase);
                    break;
                }

                WebBaseEvent.RaiseSystemEvent(SR.GetString(SR.State_Server_detailed_error,
                                                           phase,
                                                           "0x" + hr.ToString("X08", CultureInfo.InvariantCulture),
                                                           cb.ToString(CultureInfo.InvariantCulture)),
                                              this, WebEventCodes.WebErrorOtherError, WebEventCodes.StateServerConnectionError, e);

                throw e;
            }

            if (results.httpStatus == 400)
            {
                if (s_usePartition)
                {
                    throw new HttpException(
                              SR.GetString(SR.Bad_state_server_request_partition_resolver,
                                           s_configPartitionResolverType, _partitionInfo.Server, _partitionInfo.Port.ToString(CultureInfo.InvariantCulture)));
                }
                else
                {
                    throw new HttpException(
                              SR.GetString(SR.Bad_state_server_request));
                }
            }

            if (checkVersion)
            {
                _partitionInfo.StateServerVersion = results.stateServerMajVer;
                if (_partitionInfo.StateServerVersion < WHIDBEY_MAJOR_VERSION)
                {
                    // We won't work with versions lower than Whidbey
                    if (s_usePartition)
                    {
                        throw new HttpException(
                                  SR.GetString(SR.Need_v2_State_Server_partition_resolver,
                                               s_configPartitionResolverType, _partitionInfo.Server, _partitionInfo.Port.ToString(CultureInfo.InvariantCulture)));
                    }
                    else
                    {
                        throw new HttpException(
                                  SR.GetString(SR.Need_v2_State_Server));
                    }
                }
            }
        }
Exemplo n.º 26
0
 //tymczasowo nieużywana
 private string NewSessionId()
 {
     SessionIDManager manager = new SessionIDManager();
     string newID = manager.CreateSessionID(HttpContext.Current);
     bool redirected = false;
     bool isAdded = false;
     manager.SaveSessionID(HttpContext.Current, newID, out redirected, out isAdded);
     return newID;
 }
Exemplo n.º 27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["Username"] == null && Session.IsNewSession == false)
            {
                Response.Redirect("Logout.aspx", false);
                return;
            }

            if (globle.UserValue != null && Session.IsNewSession == true)
            {
                Session["Username"] = globle.UserValue;
                Session["Role"]     = globle.Role;
                Session["Location"] = "";
                Session["PF_Index"] = globle.PF_Index;
                Session["LoggedIn"] = "Yes";
            }
            else if (globle.UserValue == null)
            {
                Response.Redirect("Logout.aspx", false);
                return;
            }
            else
            {
                HttpContext.Current.Session.Abandon();
                HttpContext.Current.Session.Clear();
                Session["Username"] = null;
                Session.Abandon();
                Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
                Response.Cookies.Add(new HttpCookie("__AntiXsrfToken", ""));
                Request.Cookies.Clear();

                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
                HttpContext.Current.Response.AddHeader("Expires", "0");
                Session.Abandon(); // Session Expire but cookie do exist
                                   //  Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30); //Delete the cookie
                Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
                Request.Cookies["Asp.net_sessionId"].Expires = DateTime.UtcNow.AddDays(-1d);
                Response.Cookies["Asp.net_sessionId"].Value  = "";
                Response.Cookies["Username"].Value           = "";
                Response.Cookies.Add(Request.Cookies["Username"]);

                Session.RemoveAll();
                Session.Abandon();
                Session["Username"] = null;
                Session.Clear();
                ClearCache();
                string USER = globle.UserValue;

                FormsAuthentication.SignOut();

                Context.ApplicationInstance.CompleteRequest();
                bool redirected = false;
                bool isAdded    = false;
                System.Web.SessionState.SessionIDManager Manager = new System.Web.SessionState.SessionIDManager();
                string NewID = Manager.CreateSessionID(Context);
                string OldID = Context.Session.SessionID;
                Manager.SaveSessionID(Context, NewID, out redirected, out isAdded);
            }
        }
        catch (Exception)
        {
            //  string USER = globle.UserValue;
            //  Dictionary<string, string> dic = ((Dictionary<string, string>)Application["Sessions"]);
            //  ((Dictionary<string, string>)Application["Sessions"]).Remove(USER);
        }
    }
        private SessionStateStoreData DoGet(HttpContext context, string id, bool exclusive, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags)
        {
            bool   flag;
            string key = this.CreateSessionStateCacheKey(id);

            locked      = false;
            lockId      = null;
            lockAge     = TimeSpan.Zero;
            actionFlags = SessionStateActions.None;
            SessionIDManager.CheckIdLength(id, true);
            InProcSessionState state = (InProcSessionState)HttpRuntime.CacheInternal.Get(key);

            if (state == null)
            {
                return(null);
            }
            int comparand = state._flags;

            if (((comparand & 1) != 0) && (comparand == Interlocked.CompareExchange(ref state._flags, comparand & -2, comparand)))
            {
                actionFlags = SessionStateActions.InitializeItem;
            }
            if (exclusive)
            {
                flag = true;
                if (!state._locked)
                {
                    state._spinLock.AcquireWriterLock();
                    try
                    {
                        if (!state._locked)
                        {
                            flag               = false;
                            state._locked      = true;
                            state._utcLockDate = DateTime.UtcNow;
                            state._lockCookie++;
                        }
                        lockId = state._lockCookie;
                        goto Label_00FE;
                    }
                    finally
                    {
                        state._spinLock.ReleaseWriterLock();
                    }
                }
                lockId = state._lockCookie;
            }
            else
            {
                state._spinLock.AcquireReaderLock();
                try
                {
                    flag   = state._locked;
                    lockId = state._lockCookie;
                }
                finally
                {
                    state._spinLock.ReleaseReaderLock();
                }
            }
Label_00FE:
            if (flag)
            {
                locked  = true;
                lockAge = (TimeSpan)(DateTime.UtcNow - state._utcLockDate);
                return(null);
            }
            return(SessionStateUtility.CreateLegitStoreData(context, state._sessionItems, state._staticObjects, state._timeout));
        }