Exemple #1
1
        protected VimClient ConnectServer(string viServer, string viUser, string viPassword)
        {
            //
            // Establish a connetion to the provided sdk server
            //
            VimClient vimClient = new VimClient();
            ServiceContent vimServiceContent = new ServiceContent();
            UserSession vimSession = new UserSession();
            //
            // Connect over https to the /sdk page
            //
            try
            {
                vimClient.Connect(viServer);
                vimSession = vimClient.Login(viUser, viPassword);
                vimServiceContent = vimClient.ServiceContent;

                return vimClient;
            }
            catch (VimException ex)
            {
                //
                // VMware Exception occurred
                //
                txtErrors.Text = "A server fault of type " + ex.MethodFault.GetType().Name + " with message '" + ex.Message + "' occured while performing requested operation.";
                Error_Panel.Visible = true;
                return null;
            }
            catch (Exception e)
            {
                //
                // Regular Exception occurred
                //
                txtErrors.Text = "A server fault of type " + e.GetType().Name + " with message '" + e.Message + "' occured while performing requested operation.";
                Error_Panel.Visible = true;
                vimClient = null;
                return vimClient;
            }
        }
 public void UpdateCurrentCharacter(Guid userCharacterId)
 {
     var userSession = CurrentUserSession;
     userSession.CurrentUserCharacterId = userCharacterId;
     CurrentUserSession = userSession;
     _userSessionRepo.UpdateCurrentCharacter(userSession.UserSessionId, userSession.CurrentUserCharacterId);
 }
 public override void ProcessInput(UserSession session, string input)
 {
     if (input.ToLower() == "new")
     {
         session.WriteToUser("Functionality not implemented..." + Environment.NewLine, false);
         session.WriteToUser("Disconnecting..." + Environment.NewLine, false);
         session.Connection.Disconnect();
     }
 }
 public void EndUserSession()
 {
     var userSession = CurrentUserSession;
     if (CurrentUserSession != null)
     {
         _userSessionRepo.EndUserSession(CurrentUserSession.UserSessionId);
         CurrentUserSession = null;
     }
 }
 public void shootTest()
 {
     UserAccount user = null; // TODO: Initialize to an appropriate value
     List<ShipPosition> shipPositions = null; // TODO: Initialize to an appropriate value
     UserSession target = new UserSession(user, shipPositions); // TODO: Initialize to an appropriate value
     Field field = null; // TODO: Initialize to an appropriate value
     target.shoot(field);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Exemple #6
0
            // deauthenticates the user given by the input session
            public void Deauthenticate(ref UserSession session)
            {
                // gets the sessions authenticated id (possibly null)
                var authenticatedId = session?.Identity().AuthenticatedId;
                if (authenticatedId == null) return;

                // deauthenticates the current user
                var userId = new UserIdentity(authenticatedId.GetValueOrDefault(), "");
                session = new UserSession(userId, false);
            }
            /// <summary>
            /// Registers provided <see cref="UserSession"/> in active sessions collection.
            /// </summary>
            /// <param name="session"><see cref="UserSession"/> to register.</param>
            internal static bool Register( UserSession session )
            {
                if ( session == UserSession.Null || Connected(session.ID) )
                    return false;

                m_ActiveSessions.Add(session.ID, session);
                m_ActiveUsers.Add(session.AccountName, session.ID);

                return true;
            }
Exemple #8
0
		internal UserSessionSummary GetUserSessionSummary(UserSession session)
		{
			return new UserSessionSummary
			       	{
			       		Application = session.Application,
			       		CreationTime = session.CreationTime,
			       		ExpiryTime = session.ExpiryTime,
			       		HostName = session.HostName,
			       		SessionId = session.SessionId
			       	};
		}
Exemple #9
0
    protected void lIniciarSesion_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string userName = string.Empty;
        UserSession userSessionInfo;

        if (SessionManager.IsValidUser(lLogin.UserName, lLogin.Password)) {
            userName = SessionManager.GetUserName(lLogin.UserName);
            userSessionInfo = new UserSession(lLogin.UserName, userName);
            Session["user_session_info"] = userSessionInfo;
            FormsAuthentication.RedirectFromLoginPage(lLogin.UserName, false);
        }
    }
 public SessionUserHelper()
 {
     try
     {
         _session = (UserSession)HttpContext.Current.Session["UserSession"];
     }
     catch (Exception ex)
     {
          Logger.Error(string.Format("Error Acess Session. Error: {0}", ex));
         _session = new UserSession();
     }
 }
        public ActionResult Create(UserSession usersession)
        {
            if (ModelState.IsValid)
            {
                db.Sessions.Add(usersession);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.UserId = new SelectList(db.Users, "Id", "Username", usersession.UserId);
            return View(usersession);
        }
        //the UserSession class here is where I store the users session information, including the UserInfo object.
        //Add to your User Session/Player object : [JsonIgnoreAttribute] public GoogleAnalyticsTracker.AnalyticsSession analyticsSession;
        public static void LogItem(string pageTitle, string pageURL, UserSession userSession)
        {
            //Allow the Analytics to be turned on/off dynamically.
            if (!Config.AnalyticsEnabled)
            {
                return;
            }

            try
            {
                if (userSession.analyticsSession == null)
                {
                    userSession.analyticsSession = new AnalyticsSession();
                }

                using (Tracker tracker = new Tracker(Config.AnalyticsKey, Config.AnalyticsSite, userSession.analyticsSession))
                {
                    //You can define your own custom variables here. You can either use a unique 'site' per app,
                    //or combine them all in one site, and use a custom variable to pass your app name in.
                    //You can then use Advanced Segments to split your statistics by App
                    tracker.SetCustomVariable(1, "app", Config.AppName);
                    if (userSession.userInfo == null)
                    {
                        tracker.SetCustomVariable(2, "country", "unknown");
                        tracker.SetCustomVariable(3, "city", "unknown");
                        tracker.SetCustomVariable(4, "gender", "unknown");
                    }
                    else
                    {
                        tracker.SetCustomVariable(2, "country", userSession.userInfo.CurrentCountry);
                        tracker.SetCustomVariable(3, "city", userSession.userInfo.CurrentCity);
                        switch (userSession.userInfo.Gender)
                        {
                            case GenderType.Male:
                                tracker.SetCustomVariable(4, "gender", "male");
                                break;
                            case GenderType.Female:
                                tracker.SetCustomVariable(4, "gender", "female");
                                break;
                        }
                    }
                    //This uses asynchronous calls, so won't hold up your thread
                    //(was able to leave enabled during a Tradepost Broadcast)
                    tracker.TrackPageView(pageTitle, pageURL);
                }
            }
            catch (Exception e)
            {
                log.Error("Error logging analytics", e);
            }
        }
Exemple #13
0
    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;
    }
 public void CreateUserSession(Guid userId, Guid userCharacterId, Guid worldId)
 {
     var userSession = new UserSession
     {
         UserSessionId = Guid.NewGuid(),
         UserId = userId,
         CurrentUserCharacterId = userCharacterId,
         CurrentWorldId = worldId,
         CreatedTime = DateTime.Now,
         LastUpdated = DateTime.Now,
         IsActive = true
     };
     CurrentUserSession = userSession;
     _userSessionRepo.Insert(userSession);
 }
        /// <summary>
        /// Initializes new instance of <see cref="CacheUserSessionRequest"/> struct.
        /// </summary>
        /// <param name="p"><see cref="Packet"/> to initialize from.</param>
        public CacheUserSessionRequest( Packet p )
        {
            RequestID = p.ReadLong();

            UserSession session = new UserSession();
            session.AccountName = p.ReadString();
            session.IPAddress = p.ReadString();
            session.ID = p.ReadInt();
            session.AccountID = p.ReadInt();
            session.Login1 = p.ReadInt();
            session.Login2 = p.ReadInt();
            session.Play1 = p.ReadInt();
            session.Play2 = p.ReadInt();
            session.StartTime = p.InternalReadDateTime();

            Session = session;
        }
Exemple #16
0
            // confirms write access to data related to the user id contained in the session
            public bool ConfirmWriteAccess(UserSession session)
            {
                if (session == null || session.Authenticated() == false) return false;

                // returns false if user could not be authenticated based on the input   
                using (var db = new SmartPoolContext())
                {
                    // queries the database for users matching input session
                    var userQuery = from users in db.Users
                        where
                            users.UserId == session.Identity().AuthenticatedId &&
                            users.Password == session.Identity().Password
                        select users.UserId;

                    // returns true if the input was matched by the query
                    return userQuery.Any();
                }
            }
        public bool AddSession(UserSession session)
        {
            NameValueCollection requestArgs = new NameValueCollection
            {
                { "RequestMethod", "AddSession" },
                { "UserID", session.User.ID.ToString() },
                { "SessionID", session.SessionID.ToString() },
                { "SecureSessionID", session.SecureSessionID.ToString() }
            };

            OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
            bool success = response["Success"].AsBoolean();

            if (!success)
                m_log.Warn("Failed to add session for " + session.User.ID + ": " + response["Message"].AsString());

            return success;
        }
        /// <summary>
        /// Autentifica las credenciales de un usuario
        /// </summary>
        /// <param name="username">The user.</param>
        /// <param name="password">The password.</param>
        /// <param name="sessionId">The session id.</param>
        /// <returns>El resultado de la operación con una sesión de usuario autentificada</returns>
        public IOperationResult<IUserSession> Autentificar(string username, string password, string sessionId)
        {
            IUserSession uSession = Model.Cache.Retrieve<IUserSession>(u => u.SessionId == sessionId);
            if (uSession != null)
            {
                return new OperationResult<IUserSession>(ResultValue.Success, "", uSession);
            }

            var account = RequestContext.Model<Entities>().Accounts
                            .FirstOrDefault(acc => acc.Username == username && acc.Password == password);
            if (account != null)
            {
                uSession = new UserSession(sessionId, account.Username);
                Model.Cache.Add(null, uSession);
                return new OperationResult<IUserSession>(ResultValue.Success, "", uSession);
            }

            return new OperationResult<IUserSession>(ResultValue.Fail, "Credenciales de usuario incorrectas", uSession);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (this.Page.Session["MenuStructure"] == null)
     {
         if (this.Page.Request.Cookies["User"] != null && this.Page.Request.Cookies["User"].Value != "")
         {
             UserSession loUserSession = new UserSession(this.Session);
             //if (!loUserSession.ReLogin(this.Page.Request.Cookies["User"].Value))
             //    throw new Exception("用户已下线,请重新登陆!");
         }
         else
         {
             //throw new Exception("用户已下线,请重新登陆!");
         }
     }
     lsleftHtml = "<table id=\"LeftMenuTable\"  width=120  border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >";
     GetLeftMenuHtml();
     lsleftHtml += "</table>";
     //this.Page.Response.Write(lsleftHtml);
 }
        public void StartSession(string sessionId)
        {
            string httpSessionId = HttpContext.Current.Session.SessionID;
            using (var ctx = new UsersContext())
            {
                var session = ctx.UserSessions.Find(httpSessionId);
                if (session == null)
                {
                    session = new UserSession
                        {
                            SessionId = httpSessionId
                        };

                    ctx.UserSessions.Add(session);
                }

                session.AuthenticatedDatetime = null;
                session.SqrlId = sessionId;
                session.CreatedDatetime = DateTime.UtcNow;

                ctx.SaveChanges();
            }
        }
        public static string CreateOrReturnSession(UserProfile profile, bool rememberMe = false)
        {
            string token = UserOperations.CreateToken(profile);

            UserSession session = null;
            if (SessionManager.Current.SessionExists(token))
            {
                session = SessionManager.Current.GetSession(token);
                session.LastLoginTimestamp = DateTime.UtcNow;
                if (rememberMe)
                {
                    session.ExpirationTimestamp = session.CreationTimestamp.AddDays(14);
                }
            }
            else
            {
                session = new UserSession() { Token = token, CreationTimestamp = DateTime.UtcNow, ExpirationTimestamp = DateTime.UtcNow.AddDays(1), LastLoginTimestamp = DateTime.UtcNow, UserID = profile.UserID, UserProfile = new UserProfileHandle(profile) };
                session = SessionManager.Current.CreateOrReturnSession(session);
            }

            SessionManager.Current.UpdateSession(token, session);
            return session.Token;
        }
Exemple #22
0
        public void SetAuthorizedState(UserSession Session)
        {
            this.Message = string.Empty;

            if (Session.Token.User.WhoIs != null) {
                this.FullName = Session.Token.User.WhoIs.FullName;

                if (!string.IsNullOrEmpty(Session.Token.User.WhoIs.ImageURL)) {
                    this.ImageUrl = Session.Token.User.WhoIs.ImageURL;
                }
                else {
                    this.ImageUrl = Concepts.Ring8.Tunity.Avatar.GetValueString(Session.Token.User.WhoIs);//Utils.GetGravatarUrl(string.Empty);
                }
            }
            else {
                this.FullName = Session.Token.User.FullName;
                this.ImageUrl = Utils.GetGravatarUrl(string.Empty);
            }

            this.SignInAuthToken = Session.Token.Name;
            this.IsSignedIn = true;

            this.UpdateSignInForm();
        }
Exemple #23
0
 public DbBulkDeleteMgr(UserSession userSession)
     : base(userSession)
 {
     _userSession = userSession;
     initialize();
 }
Exemple #24
0
        public void TestExecuteBonus()
        {
            // Arrange
            var user    = new UserGameKey(-1, 3);
            var spinBet = new SpinBet(user, PlatformType.None)
            {
                Lines   = 10,
                LineBet = 1.0m
            };
            var result1 = new FortuneKoiSpinResult(user)
            {
                Wheel = new FortuneKoiWheel
                {
                    Reels = new List <int[]>
                    {
                        new int[] { },
                        new int[] { 7, 7, 7 },
                        new int[] { },
                        new int[] { },
                        new int[] { }
                    }
                },
                BonusPositions = new List <BonusPosition> {
                    new BonusPosition {
                        Line = 1, Multiplier = 1, RowPositions = new List <int> {
                            0, 2, 0, 0, 0
                        }
                    }
                },
                Bonus = new Stake(Guid.NewGuid(), 2)
                {
                    Count = 1
                }
            };

            result1.SpinBet = spinBet;
            var userSession = new UserSession
            {
                SessionKey = "unittest",
                UserId     = -1
            };
            var requestContext = new RequestContext <SpinArgs>("simulation", "FortuneKoi", PlatformType.None)
            {
                GameSetting = new GameSetting {
                    GameSettingGroupId = 1
                },
                Query = new QueryCollection {
                },
                Game  = new Game {
                    Id = 32
                }
            };
            var requestBonusContext = new RequestContext <BonusArgs>("unittest", "FortuneKoi", PlatformType.None)
            {
                GameSetting = new GameSetting {
                    GameSettingGroupId = 1
                },
                Query = new QueryCollection {
                },
            };

            requestBonusContext.UserSession = userSession;
            requestBonusContext.UserGameKey = user;
            var bonus1 = module.CreateBonus(result1).Value;

            var entity1 = new BonusEntity
            {
                UserId       = userSession.UserId,
                GameId       = requestContext.Game.Id,
                Guid         = bonus1.Guid.ToString("N"),
                Data         = Model.Utility.Extension.ToByteArray(bonus1),
                BonusType    = bonus1.GetType().Name,
                Version      = 3,
                IsOptional   = bonus1.IsOptional,
                IsStarted    = bonus1.IsStarted,
                RoundId      = 1,
                BetReference = ""
            };

            // action
            var reSpinResult = module.ExecuteBonus(1, entity1, requestBonusContext).Value as FortuneKoiReSpinResult;

            // Assert
            Assert.NotNull(reSpinResult);
            Assert.AreEqual(reSpinResult.SpinResult.HasBonus, ((FortuneKoiBonus)reSpinResult.Bonus).State is ReSpinState);
            Assert.AreEqual(reSpinResult.SpinResult.HasBonus, reSpinResult.SpinResult.Bonus != null);
            Assert.AreEqual(reSpinResult.SpinResult.HasBonus == false, ((FortuneKoiBonus)reSpinResult.Bonus).State is Finish);
            Assert.AreEqual(reSpinResult.GameResultType, GameResultType.RespinResult);
        }
Exemple #25
0
 public GameRoomState(UserSession user, GameRoom gameRoom)
 {
     User     = user;
     GameRoom = gameRoom;
 }
 public UserEditorViewModel(UserSession userSession)
     : base(userSession)
 {
 }
Exemple #27
0
 private void CreateSession()
 {
     Session = Manager.CreateSession();
 }
 protected virtual User.User GetLoggedUser()
 {
     return(UserSession.GetInstance().GetLoggedUser());
 }
Exemple #29
0
 public static void SetUserInfo(UserSession user)
 {
     System.Web.HttpContext.Current.Session[key] = user;
 }
Exemple #30
0
        public bool UpdateSession(UserSession session)
        {
            lock (m_syncRoot)
            {
                UserSession existingSession;
                if (m_sessions.TryGetValue(session.User.ID, out existingSession))
                {
                    existingSession.CurrentLookAt = session.CurrentLookAt;
                    existingSession.CurrentPosition = session.CurrentPosition;
                    existingSession.CurrentSceneID = session.CurrentSceneID;
                    existingSession.ExtraData = session.ExtraData;
                    return true;
                }
            }

            return false;
        }
Exemple #31
0
 /*==================================================================================================================================
 * Constructors
 *=================================================================================================================================*/
 public FilterValuesMgr(UserSession userSession)
     : base(userSession)
 {
     initialize();
 }
 private void ConfigureUserSession(IKernel container)
 {
     var userSession = new UserSession();
     container.Bind<IUserSession>().ToConstant(userSession).InSingletonScope();
     container.Bind<IWebUserSession>().ToConstant(userSession).InSingletonScope();
     container.Bind<IAddTaskQueryProcessor>().To<AddTaskQueryProcessor>().InRequestScope();
 }
Exemple #33
0
        public bool TryGetSession(UUID sessionID, out UserSession session)
        {
            lock (m_syncRoot)
            {
                foreach (UserSession curSession in m_sessions.Values)
                {
                    if (curSession.SessionID == sessionID)
                    {
                        session = curSession;
                        return true;
                    }
                }
            }

            session = null;
            return false;
        }
Exemple #34
0
        public JsonResult CreateTraining(Training training)
        {
            const string url = "/Training/Index";

            permission = (RoleSubModuleItem)cacheProvider.Get(cacheKey);
            if (permission == null)
            {
                permission = roleSubModuleItemService.GetRoleSubModuleItemBySubModuleIdandRole(url, Helpers.UserSession.GetUserFromSession().RoleId);
            }

            var isSuccess = false;
            var message   = string.Empty;
            //var isNew = training.Id == 0 ? true : false;
            var trainingObj = trainingService.GetTraining(training.Id);
            var isNew       = trainingObj == null;

            if (isNew)
            {
                if (permission.CreateOperation == true)
                {
                    if (!CheckIsExist(training))
                    {
                        training.RemovedBy = UserSession.GetUserFromSession().Id;
                        training.RemovedOn = DateTime.Now.ToUniversalTime();

                        if (this.trainingService.CreateTraining(training))
                        {
                            if (CreateAttendanceSummary(training))
                            {
                                isSuccess = true;
                                message   = Resources.ResourceTraining.MsgTrainingSaveSuccessful;
                            }
                        }
                        else
                        {
                            message = Resources.ResourceTraining.MsgTrainingSaveFailed;
                        }
                    }
                    else
                    {
                        isSuccess = false;
                        message   = Resources.ResourceTraining.MsgDuplicateTraining;
                    }
                }
                else
                {
                    message = Resources.ResourceCommon.MsgNoPermissionToCreate;
                }
            }
            else
            {
                if (permission.UpdateOperation == true)
                {
                    trainingObj.Id          = training.Id;
                    trainingObj.EmployeeId  = training.EmployeeId;
                    trainingObj.TypeId      = training.TypeId;
                    trainingObj.Description = training.Description;
                    trainingObj.StartDate   = training.StartDate;
                    trainingObj.EndDate     = training.EndDate;
                    trainingObj.RemovedBy   = training.RemovedBy;
                    trainingObj.RemovedOn   = training.RemovedOn;
                    trainingObj.Status      = training.Status;

                    if (this.trainingService.UpdateTraining(trainingObj))
                    {
                        if (CreateAttendanceSummary(training))
                        {
                            isSuccess = true;
                            message   = Resources.ResourceTraining.MsgTrainingUpdateSuccessful;
                        }
                    }
                    else
                    {
                        message = Resources.ResourceTraining.MsgTrainingUpdateFailed;
                    }
                }
                else
                {
                    message = Resources.ResourceCommon.MsgNoPermissionToUpdate;
                }
            }

            return(Json(new
            {
                isSuccess = isSuccess,
                message = message,
            }, JsonRequestBehavior.AllowGet));
        }
Exemple #35
0
        protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
        {
            try
            {
                string absolutePath = Request.Url.AbsolutePath.ToLower();

                if (absolutePath.Equals("/"))
                {
                    Response.Redirect(FormsAuthentication.LoginUrl, false);
                    return;
                }
                bool ajaxRequest = false;

                if (absolutePath.ToLower().Contains("/api/"))
                {
                    ajaxRequest = true;
                }

                string query = Request.Url.Query.ToLower();

                if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
                {
                    if (ajaxRequest == true)
                    {
                        Response.SuppressFormsAuthenticationRedirect = true;
                    }
                    else
                    {
                        if (ByPassFormsAuthentication(absolutePath, query))
                        {
                            return;
                        }
                    }

                    Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    Context.ApplicationInstance.CompleteRequest();
                    return;
                }

                bool SuppressFormsAuthenticationRedirect = ajaxRequest;

                FormsAuthenticationTicket authTicket = null;
                try
                {
                    authTicket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
                }
                catch
                {
                    AuthManager.SignOut(string.Empty, ajaxRequest, "AuthTicketException");
                    return;
                }

                if (authTicket.Expired)
                {
                    AuthManager.SignOut(authTicket.UserData, ajaxRequest, "AuthTicketExpired");
                    return;
                }

                UserProfile user = AuthServices.GetUserProfile(authTicket.Name);
                if (user == null)
                {
                    AuthManager.SignOut(authTicket.UserData, ajaxRequest, "UserNotFound");
                    return;
                }

                UserSession session = AuthServices.GetUserSession(authTicket.UserData);
                if (session == null)
                {
                    if (absolutePath.Equals(FormsAuthentication.LoginUrl) || absolutePath.Equals(FormsAuthentication.LoginUrl + ".aspx"))
                    {
                        return;
                    }

                    AuthManager.SignOut(authTicket.UserData, ajaxRequest, "SessionTimeOut");
                    return;
                }

                if (session.LastAccess.Add(FormsAuthentication.Timeout) > DateTime.UtcNow)
                {
                    if (Request.HttpMethod == "GET" || Request.HttpMethod == "HEAD")
                    {
                        AuthServices.SlideExpiration(session);
                    }

                    AuthServices.SlideExpiration(session);

                    if (RedirectToDefaultUrl(absolutePath))
                    {
                        Response.Redirect(FormsAuthentication.DefaultUrl, false);
                    }

                    return;
                }

                if (authTicket.IsPersistent && session.LastAccess.AddDays(30) > DateTime.UtcNow)
                {
                    // Updating user cache with this call in case user has logged with persistent and has a inactive session.
                    user = AuthServices.GetUserProfile(authTicket.Name, false);
                    if (user.HasVerifiedEmail == false)
                    {
                        AuthManager.SignOut(authTicket.UserData, ajaxRequest, "PersistentNonVerifiedEmail");
                        return;
                    }

                    if (Request.HttpMethod == "GET" || Request.HttpMethod == "HEAD")
                    {
                        AuthServices.SlideExpiration(session);
                    }

                    AuthServices.SlideExpiration(session);

                    if (RedirectToDefaultUrl(absolutePath))
                    {
                        Response.Redirect(FormsAuthentication.DefaultUrl, false);
                    }

                    return;
                }

                AuthManager.SignOut(authTicket.UserData, ajaxRequest, "NotValidSession");
            }
            catch (Exception _ex)
            {
                //EventLogger.Write(_ex);
                //AuthManager.SignOut();
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(""));
                return;
            }
        }
 /*==================================================================================================================================
 * ConstructorsRequisitionListModeler
 *=================================================================================================================================*/
 public ColumnListModeler(HttpRequestBase httpRequestBase, UserSession userSession)
     : base(httpRequestBase, userSession)
 {
     initialize();
 }
 public DatabasesViewModel(UserSession userSession, BaseUserSessionViewModel baseUserSessionViewModel)
     : base(userSession, baseUserSessionViewModel)
 {
 }
 public FilterTableTreeviewViewModel(UserSession userSession, BaseUserSessionViewModel baseUserSessionViewModel)
     : base(userSession, baseUserSessionViewModel)
 {
 }
 public DatabasesViewModel(UserSession userSession)
     : base(userSession)
 {
 }
 /*==================================================================================================================================
 * Constructors
 *=================================================================================================================================*/
 public TablesMgr(UserSession userSession)
     : base(userSession)
 {
     initialize();
 }
 public StoredProceduresListViewModel(UserSession userSession, BaseUserSessionViewModel baseUserSessionViewModel)
     : base(userSession, baseUserSessionViewModel)
 {
     Items = new List <StoredProcedureLineItemViewModel>();
 }
Exemple #42
0
        /*==================================================================================================================================
        * Declarations
        *=================================================================================================================================*/
        #endregion


        #region Constructors

        /*==================================================================================================================================
        * Constructors
        *=================================================================================================================================*/
        public PrivilegeEditorModeler(HttpRequestBase httpRequestBase, UserSession userSession)
            : base(httpRequestBase, userSession)
        {
            initialize();
        }
 public UserEditorViewModel(UserSession userSession, BaseUserSessionViewModel baseUserSessionViewModel)
     : base(userSession, baseUserSessionViewModel)
 {
 }
 public UserInfoViewModel(UserSession userSession)
 {
     this.userSession = userSession;
 }
Exemple #45
0
 public BallotCacher() : base(UserSession.GetNewDbContext())
 {
 }
Exemple #46
0
 protected ForZhuanGuServices(string sessionId)
 {
     currUserSession = SvrUserSession.GetCurrSession(sessionId);
 }
Exemple #47
0
        private async Task Connect()
        {
            // check whether session is expiring
            if (_session != null && (DateTime.Compare(DateTime.UtcNow, _session.lastActiveTime.AddMinutes(_options.ConnectionRefreshIntervalMinutes)) >= 0))
            {
                _logger.LogDebug("Connect():  Session is more than 20 minutes old");

                // renew session because it expires at 30 minutes (maybe 120 minutes on newer vc)
                _logger.LogInformation($"Connect():  renewing connection to {_options.Host}...[{_options.Username}]");
                try
                {
                    var client = new VimPortTypeClient(VimPortTypeClient.EndpointConfiguration.VimPort, $"https://{_options.Host}/sdk");
                    var sic    = await client.RetrieveServiceContentAsync(new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" });

                    var props   = sic.propertyCollector;
                    var session = await client.LoginAsync(sic.sessionManager, _options.Username, _options.Password, null);

                    var oldClient = _client;
                    _client  = client;
                    _sic     = sic;
                    _props   = props;
                    _session = session;

                    await oldClient.CloseAsync();

                    oldClient.Dispose();
                }
                catch (Exception ex)
                {
                    // no connection: Failed with Object reference not set to an instance of an object
                    _logger.LogError(0, ex, $"Connect():  Failed with " + ex.Message);
                    _logger.LogError(0, ex, $"Connect():  User: "******"Connect():  CommunicationState.Opened");
                ServiceContent sic     = _sic;
                UserSession    session = _session;
                bool           isNull  = false;

                if (_sic == null)
                {
                    sic = await ConnectToHost(_client);

                    isNull = true;
                }

                if (_session == null)
                {
                    session = await ConnectToSession(_client, sic);

                    isNull = true;
                }

                if (isNull)
                {
                    _session = session;
                    _props   = sic.propertyCollector;
                    _sic     = sic;
                }

                try
                {
                    var x = await _client.RetrieveServiceContentAsync(new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" });

                    return;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error checking vcenter connection. Disconnecting.");
                    Disconnect();
                }
            }

            if (_client != null && _client.State == CommunicationState.Faulted)
            {
                _logger.LogDebug($"Connect():  https://{_options.Host}/sdk CommunicationState is Faulted.");
                Disconnect();
            }

            if (_client == null)
            {
                try
                {
                    _logger.LogDebug($"Connect():  Instantiating client https://{_options.Host}/sdk");
                    var client = new VimPortTypeClient(VimPortTypeClient.EndpointConfiguration.VimPort, $"https://{_options.Host}/sdk");
                    _logger.LogDebug($"Connect():  client: [{_client}]");

                    var sic = await ConnectToHost(client);

                    var session = await ConnectToSession(client, sic);

                    _session = session;
                    _props   = sic.propertyCollector;
                    _sic     = sic;
                    _client  = client;
                }
                catch (Exception ex)
                {
                    _logger.LogError(0, ex, $"Connect():  Failed with " + ex.Message);
                }
            }
        }
 /*==================================================================================================================================
 * Constructors
 *=================================================================================================================================*/
 public LookupsMgr(UserSession userSession)
     : base(userSession)
 {
     initialize();
 }
 public ColumnListModeler(HttpRequestBase httpRequestBase, UserSession userSession, ColumnListViewModel columnListViewModel)
     : base(httpRequestBase, userSession)
 {
     this._columnListViewModel = columnListViewModel;
     initialize();
 }
        public bool InsertRegister(CustomerModel model, UserSession UISssn)
        {
            bool   bretval = false;
            Object oModel  = new CustomerModel();

            MySqlConnection connection = new MySqlConnection(UISssn.ConnectionString);

            connection.Open();
            bool closeTransaction = false;

            try
            {
                MySqlCommand  cmd   = connection.CreateCommand();
                StringBuilder sbsql = new StringBuilder(1024);
                sbsql.Append(" insert into register_user ");
                sbsql.Append(" values ( ");
                sbsql.Append(0);
                sbsql.Append(",");
                sbsql.Append("'" + model.UserRealName + "', ");
                sbsql.Append("'" + model.Mobile + "', ");
                sbsql.Append("'" + model.Email + "', ");
                sbsql.Append("'" + model.UserName + "', ");
                sbsql.Append("'" + model.Address + "', ");
                sbsql.Append("'" + model.City + "', ");
                sbsql.Append("'" + model.Pincode + "', ");
                sbsql.Append("'" + model.State + "', ");
                sbsql.Append("'" + model.Country + "', ");
                sbsql.Append("'" + model.Dateofbirth + "', ");
                sbsql.Append("'" + model.Gender + "', ");
                sbsql.Append("'" + model.Password + "', ");
                sbsql.Append(model.InsertByUserId + ",");
                sbsql.Append("Now()");
                sbsql.Append(" ) ");
                sbsql.Append(" ; ");



                sbsql.Append(" insert into tbmuser ");
                sbsql.Append(" values ( ");
                sbsql.Append(0);
                sbsql.Append(",");
                sbsql.Append("'" + model.UserName + "', ");
                sbsql.Append("'" + model.Password + "', ");
                sbsql.Append("'" + model.UserRealName + "', ");
                sbsql.Append("'" + model.Email + "', ");
                sbsql.Append(1);
                sbsql.Append(",");
                sbsql.Append(2);
                sbsql.Append(" ) ");
                sbsql.Append(" ; ");

                cmd.CommandText = sbsql.ToString();
                int resultCount = cmd.ExecuteNonQuery();



                if (resultCount == 1)
                {
                    bretval = true;
                }
            }
            catch (Exception)
            {
                bretval = false;
            }
            finally
            {
                connection.Close();
            }
            return(bretval);
        }
Exemple #51
0
        protected static string DecodeCommand(UserSession user, int command)
        {
            //心跳
            if (command == 103)
            {
                TResult(user);
                return string.Empty;
            }

            UserBuffer buffer = user.Buffer;
            if (buffer == null) return null;

            string name = null;
            //检查命令范围
            if (command > 100 && command <= CommandManager.MaxCommand)
            {
                //检查调用频繁度
                int ct = CommandManager.ControlTicks[command];
                if (ct > 0)
                {
                    long interval = buffer.LastInterval(command);
                    if (interval < ct)
                    {
                        if (string.IsNullOrEmpty(user.UserID))
                        {
                            user.Close();
                            return null;
                        }
                        else if (buffer.CallTicks[0]++ > 10000)
                        {
                            //发送操作太快信息
                            try
                            {
                                user.SendAsync(FastErr);
                                LogWrapper.Warn(user.ToString("Operating too fast|"));
                            }
                            finally
                            {
                                user.Close();
                            }
                            return null;
                        }
                        return string.Empty;
                    }
                }
                name = CommandManager.Instance.ReadString(command);
            }

            if (name == null)
            {
                //命令不存在时.如果用户未登录,或登录用户总计16次出错则断开
                if (string.IsNullOrEmpty(user.UserID))
                {
                    user.Close();
                }
                else if (buffer.CallTicks[1]++ > 16)
                {
                    LogWrapper.Warn(user.ToString("Protocol error|"));
                    user.Close();
                }
            }
            return name;
        }
        private void Enregistrer()
        {
            DateTime datenaissaissance;

            datenaissaissance = Convert.ToDateTime(naissTxt.Text);
            try
            {
                if (nomTxt.Text == "" || sex == "" || naissTxt.Text == "" || pereTxt.Text == "" || mereTxt.Text == "" || datenaissaissance.Date >= DateTime.Today)
                {
                    MessageBox.Show("Impossible d'enregistrer, Champs obligatoires vides ou dates supérieur", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else if (UserSession.GetInstance().Fonction == "Secrétaire" || UserSession.GetInstance().Fonction == "SA")
                {
                    int dif = 0;
                    dif = DateTime.Today.Year - datenaissaissance.Year;
                    DateTime daterecpt;
                    daterecpt = Convert.ToDateTime(recptTxt.Text);
                    if (daterecpt > DateTime.Today)
                    {
                        MessageBox.Show("Impossible d'enregistrer une date de réception qui n'est pas encore arriver\n Laisser le champs date réception vide ou bien inserer une date valide", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                    else if (daterecpt.Date <= datenaissaissance.Date)
                    {
                        MessageBox.Show("Impossible d'enregistrer une date de réception inférieur à la date de naissance\n Laisser le champs date réception vide ou bien inserer une date valide", "Stop", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                    else
                    {
                        if (dif < 5)
                        {
                            ReceptionEnfant r = new ReceptionEnfant();

                            r.Id            = id;
                            r.Noms          = nomTxt.Text;
                            r.Sexe          = sex;
                            r.DateNaissance = Convert.ToDateTime(naissTxt.Text);
                            r.DateReception = Convert.ToDateTime(recptTxt.Text);
                            r.ProvOrigine   = provTxt.Text;
                            r.TerrOrigine   = terrTxt.Text;
                            r.Pere          = pereTxt.Text;
                            r.Mere          = mereTxt.Text;
                            r.Pasteur       = pastTxt.Text;

                            r.SaveDatas(r);
                            DynamicClasses.GetInstance().Alert("Enfant save", DialogForms.FrmAlert.enmType.Success);
                            //Initialisation des champs
                            Initialiser();
                            //Message de confirmation
                        }
                        else
                        {
                            MessageBox.Show("Seul les enfants de moins de 5ans sont acceptés", "Information", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 public ActionResult Edit(UserSession usersession)
 {
     if (ModelState.IsValid)
     {
         db.Entry(usersession).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     ViewBag.UserId = new SelectList(db.Users, "Id", "Username", usersession.UserId);
     return View(usersession);
 }
Exemple #54
0
            public void PropagiateLoad(ResourceResolver resourceResolver, UserSession session, string url)
            {
                var playlist = resourceResolver.LoadPlaylistFrom(url, resolver).UnwrapThrow();

                session.Set(SessionConst.Playlist, playlist);
            }
Exemple #55
0
 public bool RemoveSession(UserSession session)
 {
     lock (m_syncRoot)
         return m_sessions.Remove(session.User.ID);
 }
Exemple #56
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="session">UserSession class</param>
 public UserSessionArgs(UserSession session)
 {
     Session = session;
 }
Exemple #57
0
 public bool TryGetSessionByUserID(UUID userID, out UserSession session)
 {
     lock (m_syncRoot)
         return m_sessions.TryGetValue(userID, out session);
 }
Exemple #58
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="session">UserSession class</param>
 /// <param name="page"></param>
 public UserPageViewArgs(UserSession session, PageViewData page)
 {
     Page    = page;
     Session = session;
 }
Exemple #59
0
 public bool AddSession(UserSession session)
 {
     lock (m_syncRoot)
         m_sessions[session.User.ID] = session;
     return true;
 }
 public FilterTableTreeviewViewModel(UserSession userSession)
     : base(userSession)
 {
 }