Example #1
1
        /// <summary>
        /// Gets the unique session ID for the current session.
        /// </summary>
        private static string GetSessionId( ISession session )
        {
            var sessionHelper = new SessionHelper( session );

            var sessionId = sessionHelper.SessionId;

            if ( null == sessionId )
            {
                sessionId = CreateSessionId( session );
                sessionHelper.SessionId = sessionId;
            }

            return sessionId;
        }
    /// <summary>
    /// 檢查密碼是否正確
    /// </summary>
    /// <param name="pw"></param>
    /// <returns></returns>
    public static bool CheckPassoword(string pw)
    {
        SessionHelper shelper = new SessionHelper();

        LoginUserVO user = shelper.LoginUser;

        if (user == null)
        {
            return false;
        }
        else
        {
            return user.Password.Equals(pw);
        }
    }
        /// <summary>
        /// 覆寫AuthorizeAttribute類別的AuthorizeCore方法
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            SessionHelper sessionHelper = new SessionHelper();

            if (!httpContext.Request.IsAuthenticated)
            {
                return false;
            }

            if (sessionHelper.LoginUser == null)
            {
                return false;
            }

            //// 必須通過功能權限檢核                      
            //// 從Sigleton機制取LoginUser,防止後台更新權限後,已登入使用的人不會異動到權限
            return ACUtility.CheckAuthorization(LoginUserContainer.GetInstance().GetUser(sessionHelper.LoginUser.Account), (int)AppFunction, (int)Operation);
        }
        private static void Handler( NancyContext context )
        {
            var sessionHelper = new SessionHelper( context );

            if ( null != context.CurrentUser )
            {
                var user = database.GetUserByName( context.CurrentUser.UserName );

                context.ViewBag[ViewBagKeys.CurrentUser] = user;
            }

            var currentGameId = sessionHelper.CurrentGameId;
            if ( null != currentGameId )
            {
                var currentGame = database.GetGameById( currentGameId.Value );
                context.ViewBag[ViewBagKeys.CurrentGame] = currentGame;
            }
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (filterContext.RequestContext.HttpContext.Request.IsAuthenticated)
            {
                IFormsAuthenticationService FormsService = new FormsAuthenticationService();
                SessionHelper session = new SessionHelper(filterContext.HttpContext);

                if (session.SessionEndTime == null)
                    session.SessionEndTime = DateTime.Now;
                else if (DateTime.Now - session.SessionEndTime > TimeSpan.FromMinutes(1))
                {
                    FormsService.SignOut();
                    filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Account", action = "Logon" }));
                }
            }
        }
 public PublicationsController(IPublicationRepository publicationRepository, IAuthorsRepository authorRepository, SessionHelper helper, IDataContext dataContext)
     : base(dataContext)
 {
     _publicationRepository = publicationRepository;
     _authorsRepository = authorRepository;
     _sessionHelper = helper;
 }
Example #7
0
        protected override void Execute(System.Web.Routing.RequestContext requestContext)
        {
            Session = new SessionHelper(requestContext.HttpContext);

            if (!requestContext.HttpContext.Request.Url.AbsoluteUri.ToLower().Contains("service"))
            {

                if (requestContext.HttpContext.Request.IsAuthenticated)
                {
                    IFormsAuthenticationService FormsService = new FormsAuthenticationService();

                    if (DateTime.Now - Session.SessionEndTime > TimeSpan.FromMinutes(20))
                    {
                        FormsService.SignOut();
                        requestContext.HttpContext.Response.Redirect(requestContext.HttpContext.Request.Url.AbsoluteUri, true);
                    }
                    else
                    {
                        Session.SessionEndTime = DateTime.Now;
                    }
                }
            }

            base.Execute(requestContext);
        }
Example #8
0
        public void connected(SessionHelper session)
        {
            // If the session has been reassigned avoid the
            // spurious callback.
            if(session != _session)
            {
                return;
            }

            Ice.Object servant = new ChatCallbackI(this);

            Demo.ChatCallbackPrx callback = Demo.ChatCallbackPrxHelper.uncheckedCast(_session.addWithUUID(servant));
            _chat = Demo.ChatSessionPrxHelper.uncheckedCast(_session.session());
            _chat.begin_setCallback(callback).whenCompleted(delegate()
                                              {
                                                  closeCancelDialog();
                                                  input.IsEnabled = true;
                                                  status.Content = "Connected with " + _loginData.routerHost;
                                              },
                                              delegate(Ice.Exception ex)
                                              {
                                                  if(_session != null)
                                                  {
                                                      _session.destroy();
                                                  }
                                              });
        }
Example #9
0
 public static void AddLoss(SessionHelper.Difficulty diff)
 {
     if (diff == SessionHelper.Difficulty.Common)
         Properties.Settings.Default.commonlosses += 1;
     else
         Properties.Settings.Default.hardlosses += 1;
     Save();
 }
Example #10
0
        protected void Session_Start(object sender, EventArgs e)
        {
            SessionHelper helper = new SessionHelper();
            helper.Initialize();

            VisitRepo visit = new VisitRepo();
            visit.removeOldVisits(DateTime.Now);
            visit.addVisit(helper.SessionID, helper.Start);
        }
 public ActionResult AddProduct(int id)
 {
     ProductRepo products = new ProductRepo();
     ShoppingCartEntities db = new ShoppingCartEntities();
     SessionHelper session = new SessionHelper();
     var prodVisit = db.ProductVisits.Where(pv => pv.productID == id && pv.sessionID == session.SessionID).FirstOrDefault();
     ViewBag.Qty = (prodVisit != null) ? prodVisit.qtyOrdered : 1;
     return View(products.GetProduct(id));
 }
        public ActionResult MyCart()
        {
            ShoppingCartEntities db = new ShoppingCartEntities();

            SessionHelper session = new SessionHelper();
            string id = session.SessionID;

            CartItemRepo cir = new CartItemRepo();
            return View(cir.GetCartItemsBySession(id));
        }
        public ActionResult MyCart()
        {
            ShoppingCartEntities db = new ShoppingCartEntities();

            SessionHelper session = new SessionHelper();
            //string id = session.SessionID;

            CartItemRepo cir = new CartItemRepo();
            return View(cir.GetCartItemsByUser(User.Identity.Name));
        }
Example #14
0
        protected void Session_Start(object sender, EventArgs e)
        {
            SessionHelper sessionHlp = new SessionHelper();

            A00964856_ShoppingCartEntities db = new A00964856_ShoppingCartEntities();

            VisitRepo visitRepo = new VisitRepo(db);
            visitRepo.ClearVisitsOlderThan(sessionHlp.Expired);
            visitRepo.RemoveSessionID(sessionHlp.SessionID);
            visitRepo.RegisterNewVisit(sessionHlp.SessionID, sessionHlp.Start);
        }
Example #15
0
        public ActionResult Add(int prodId)
        {
            SessionHelper sessonHlp = new SessionHelper();
            int qty = sessonHlp.GetProductQtyFromCart(prodId);

            A00964856_ShoppingCartEntities db = new A00964856_ShoppingCartEntities();
            ProductRepo prodRepo = new ProductRepo(db);
            CartItemRepo cartItemRepo = new CartItemRepo(prodRepo);
            CartItemModel item = cartItemRepo.GetCartItem(prodId, qty);

            return View(item);
        }
        public ActionResult CancelOrder()
        {
            SessionHelper session = new SessionHelper();
            string id = session.SessionID;

            ProductVisitRepo pvr = new ProductVisitRepo();
            pvr.removeProductVisit(id);

            //VisitRepo visitRepo = new VisitRepo();
            //visitRepo.removeVisit(id);

            return RedirectToAction("Index", "Cart");
        }
 public ActionResult Add(int id)
 {
     if (TempData["error"] != null)
     {
         ViewBag.Error = TempData["error"].ToString();
     }
     CartProductRepo products = new CartProductRepo();
     ShoppingCartEntities db = new ShoppingCartEntities();
     SessionHelper session = new SessionHelper();
     //Stores qty of product added in the cart for display in the view
     var prodVisit = db.ProductVisits.Where(pv => pv.productID == id && pv.sessionID == session.SessionID).FirstOrDefault();
     ViewBag.Qty = (prodVisit != null) ? prodVisit.qtyOrdered : 1;
     return View(products.getProduct(id));
 }
 public UnauthorizedModel(bool isAuthenticated)
 {
     SessionHelper sessionHelper = new SessionHelper();
     this.Timeout = 3;
     this.Title = "未獲授權";
     if (isAuthenticated && sessionHelper.LoginUser != null)
     {
         Msg = "您未被授權查看該頁,即將返回系統首頁。";
         string url = RouteTable.Routes.GetVirtualPath(HttpContext.Current.Request.RequestContext, new RouteValueDictionary(new { controller = "Admin", action = "Index" })).VirtualPath;
         ReturnUrl = url;
     }
     else
     {
         Msg = "您尚未登入或登入已逾期,即將前往登入頁。";
         string url = RouteTable.Routes.GetVirtualPath(HttpContext.Current.Request.RequestContext, new RouteValueDictionary(new { controller = "LogOn", action = "LogOn" })).VirtualPath;
         ReturnUrl = url;
     }
 }
        public ActionResult ViewCart(int productId, int qty)
        {
            if (qty < 1)
            {
                TempData["error"] = "A positive quantity must be used";
                return RedirectToAction("Add", "Cart", new { id = productId });
            }

            ShoppingCartEntities db = new ShoppingCartEntities();

            SessionHelper session = new SessionHelper();
            string id = session.SessionID;

            ProductVisitRepo pvRepo = new ProductVisitRepo();
            pvRepo.addProductVisit(id, productId, qty, DateTime.Now);

            return RedirectToAction("MyCart", "Cart");
        }
Example #20
0
        private bool UpdateCart(CartItemModel cartItem)
        {
            if (cartItem.Quantity < 1) {
                return false;
            }

            SessionHelper sessionHlp = new SessionHelper();
            sessionHlp.AddProductToCart(cartItem.ProductID, cartItem.Quantity);

            A00964856_ShoppingCartEntities db = new A00964856_ShoppingCartEntities();

            ProductRepo prodRepo = new ProductRepo(db);
            VisitRepo visitRepo = new VisitRepo(db);
            ProductVisitRepo prodVisitRepo = new ProductVisitRepo(db);

            Visit visit = visitRepo.GetVisit(sessionHlp.SessionID);
            Product product = prodRepo.GetProduct(cartItem.ProductID);
            prodVisitRepo.AddProductVisit(visit, product, cartItem.Quantity);

            return true;
        }
    /// <summary>
    /// 傳回whomak
    /// </summary>
    /// <returns></returns>
    public static string GetWhoMake()
    {
        SessionHelper shelper = new SessionHelper();

        LoginUserVO user = shelper.LoginUser;

        if (user == null)
        {
            return "";
        }
        else
        {
            if (user.UserId.Length > 10)
            {
                return user.UserId.Substring(0, 10);
            }
            else
            {
                return user.UserId;
            }
        }
    }
    /// <summary>
    /// 檢查權限
    /// </summary>
    /// <param name="application"></param>
    /// <param name="uri"></param>
    /// <param name="rawUrl"></param>
    private void CheckAuth(HttpApplication application, Uri uri, string rawUrl)
    {
        SessionHelper sHelper = new SessionHelper();

        LoginUserVO loginUser = sHelper.LoginUser;

        string applicationPath = application.Request.ApplicationPath;

        string mamagePath = String.IsNullOrEmpty(applicationPath) ? "/admin" : applicationPath + "/admin";
        mamagePath = mamagePath.Replace("//", "/");

        if (rawUrl.StartsWith(mamagePath) == true)
        {
            AuthFactory authFactory = new AuthFactory();
            IAuthService authService = authFactory.GetAuthService();

            if (loginUser == null)
            {
                toLoginPage(application.Response);
                return;
            }

            string userId = loginUser.UserId;

            //判斷只有主路徑是否有權限
            //if (!PathHasRight(UserMenuFuncContainer.GetInstance().GetUser(userId), uri, UserMenuFuncContainer.GetInstance().PathFunc))
            //{
            //    toLoginNoAuthPage(application.Response);
            //}

            //判斷所有路徑是否有權限
            if (!authService.PathHasAuth(UserMenuFuncContainer.GetInstance().GetUser(userId), uri))
            {
                toLoginNoAuthPage(application.Response);
            }
        }
    }
Example #23
0
        public String TaiKhoang()
        {
            var session = SessionHelper.GetSession();

            return(session.UserName);
        }
    /// <summary>
    /// 加入 system log
    /// </summary>
    /// <param name="action">異動行為</param>
    public void AddSystemLog(MsgVO.Action action, object obj)
    {
        SessionHelper sHelper = new SessionHelper();

        LoginUserVO userVO = sHelper.LoginUser;
        LogSystemVO logVO = sHelper.LogVO;

        if (!String.IsNullOrEmpty(logVO.Fucntion))
        {

            if (userVO != null)
            {
                logVO.UpdateId = userVO.UserId;
            }

            logVO.UpdateDate = DateTime.Now;
            logVO.Action = action.ToString();
            logVO.UpdateClassName = obj.GetType().ToString();
            logVO.IpAddress = m_HttpHelper.GetUserIp(HttpContext.Current);

            m_LogService.CreateLogSystem(logVO);

        }
        else
        {
            // log.Debug("logVO.Function is null ,updateClassName "+obj.ToString());
        }
    }
Example #25
0
        public IActionResult Cart()
        {
            var cart = SessionHelper.GetObjectAsJson <List <item> >(HttpContext.Session, "cart");

            return(View(cart));
        }
 private void AddProductToWishlist()
 {
     SessionHelper.SetValue("ShoppingCartUrlReferrer", URLHelper.CurrentURL);
     URLHelper.Redirect(WishlistUrl + "?productid=" + SKUID);
 }
Example #27
0
        public IActionResult Login()
        {
            string strUserName = Request.Form["username"];
            string strPassWord = Request.Form["password"];

            if (strUserName.Length % 8 != 0)
            {
                tip.Message = "请输入用户名不合法!";
                return(Json(tip));
            }
            if (strPassWord.Length % 8 != 0)
            {
                tip.Message = "请输入密码不合法!";
                return(Json(tip));
            }
            //判断并解密
            string key = SessionHelper.GetSession("des_key").ToString();

            if (string.IsNullOrEmpty(key))
            {
                tip.Message = "页面访问超时,请刷新页面重新登录!";
                tip.Other   = "reload";
                return(Json(tip));
            }
            //解密
            string username = "";
            string password = "";

            try
            {
                username = MyDES.uncMe(strUserName, key);
                password = MyDES.uncMe(strPassWord, key);
            }
            catch (Exception exp)
            {
                NewLife.Log.XTrace.WriteException(exp);
                tip.Message = "页面访问超时,请刷新页面重新登录!";
                tip.Other   = "reload";
                return(Json(tip));
            }

            //验证用户
            if (string.IsNullOrEmpty(username))
            {
                tip.Message = "请输入用户名!";
                return(Json(tip));
            }
            if (string.IsNullOrEmpty(password) || Utils.GetStringLength(password) < 5)
            {
                tip.Message = "登录密码不能为空或者长度小于5!";
                return(Json(tip));
            }
            //如果15分钟内有10次失败登录,则提示错误
            string     ip = Utils.GetIP();
            Expression ex = AdminLog._.IsLoginOK == 0 & AdminLog._.LoginIP == ip & AdminLog._.LoginTime >= DateTime.Now.AddMinutes(-15);

            if (AdminLog.FindCount(ex, null, null, 0, 0) >= 10)
            {
                tip.Message = "错误登录次数限制!";
                return(Json(tip));
            }
            //执行登录操作
            if (Admin.AdminLogin(username, password))
            {
                tip.Status    = JsonTip.SUCCESS;
                tip.Message   = "登录成功";
                tip.ReturnUrl = "/AdminCP";
                return(Json(tip));
            }
            else
            {
                tip.Message = "用户名或者密码错误!请重新登录!";
                return(Json(tip));
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        RegisterESCScript = false;

        clientId = QueryHelper.GetString("clientid", "");

        SetTitle(GetString("conditionbuilder.title"));
        PageTitle.HelpTopicName = HELP_TOPIC_LINK;

        Save += btnSave_Click;

        designerElem.RuleCategoryNames = QueryHelper.GetString("module", "");
        designerElem.DisplayRuleType   = QueryHelper.GetInteger("ruletype", 0);
        designerElem.ShowGlobalRules   = QueryHelper.GetBoolean("showglobal", true);

        // Set correct resolver to the control
        string resolverName = ValidationHelper.GetString(SessionHelper.GetValue("ConditionBuilderResolver" + clientId), "");

        if (!string.IsNullOrEmpty(resolverName))
        {
            designerElem.ResolverName = resolverName;
        }

        // Set correct default condition text
        string defaultText = ValidationHelper.GetString(SessionHelper.GetValue("ConditionBuilderDefaultText" + clientId), "");

        if (!string.IsNullOrEmpty(defaultText))
        {
            designerElem.DefaultConditionText = defaultText;
        }

        if (!RequestHelper.IsPostBack())
        {
            string condition = MacroProcessor.RemoveDataMacroBrackets(ValidationHelper.GetString(SessionHelper.GetValue("ConditionBuilderCondition" + clientId), ""));
            designerElem.Value = condition;
        }

        CurrentMaster.PanelContent.RemoveCssClass("dialog-content");
    }
Example #29
0
    /// <summary>
    /// Get values from session and set it to controls
    /// </summary>
    private void TrimPreviewValues()
    {
        if (String.IsNullOrEmpty(PreviewObjectName))
        {
            return;
        }

        string[] parameters = null;

        // For dialog mode first time load or when preview is initialized - set actual settings, not stored
        if (LoadSessionValues)
        {
            // Get values from session
            parameters = SessionHelper.GetValue(PreviewObjectName) as string[] ?? PreviewObjectPreferredDocument;
        }

        if ((parameters != null) && (parameters.Length == 4))
        {
            // Store SiteID for path selector
            ucPath.SiteID = String.IsNullOrEmpty(parameters[1]) ? SiteContext.CurrentSiteID : ValidationHelper.GetInteger(parameters[1], 0);
            if (!RequestHelper.IsPostBack() || SetControls)
            {
                ucPath.Value = parameters[0];
            }

            ucSelectCulture.SelectedCulture = String.IsNullOrEmpty(parameters[2]) ? LocalizationContext.PreferredCultureCode : parameters[2];
        }
        else
        {
            if ((parameters == null) || (parameters.Length != 4))
            {
                // First time load
                parameters    = new String[4];
                parameters[1] = SiteContext.CurrentSiteID.ToString();
                parameters[3] = DeviceContext.CurrentDeviceProfileName;

                if (!RequestHelper.IsPostBack() || SetControls)
                {
                    parameters[2] = LocalizationContext.PreferredCultureCode;
                    parameters[0] = DefaultPreviewPath;
                }
            }

            // First try get alias path from property
            String aliasPath = DefaultAliasPath;
            if (String.IsNullOrEmpty(aliasPath))
            {
                // Then get path settings from query string (used in CMS Desk)
                aliasPath = QueryHelper.GetString("aliaspath", String.Empty);
            }

            if (!String.IsNullOrEmpty(aliasPath))
            {
                parameters[0] = aliasPath;
            }

            // Set selectors by parameters value
            ucPath.Value  = parameters[0];
            ucPath.SiteID = ValidationHelper.GetInteger(parameters[1], SiteContext.CurrentSiteID);
            ucSelectCulture.SelectedCulture = parameters[2];
        }

        // Store new values for dialog mode
        if (!LoadSessionValues)
        {
            SessionHelper.SetValue(PreviewObjectName, parameters);
            StoreNewPreferredDocument(parameters);
        }

        ucPath.Config.ContentSites           = AvailableSitesEnum.All;
        ucSelectCulture.SiteID               = ucPath.SiteID;
        ucPath.PathTextBox.WatermarkText     = GetString("general.pleaseselectdots");
        ucPath.PathTextBox.WatermarkCssClass = "WatermarkText";

        if (ucProfiles != null)
        {
            ucProfiles.SetValue("SelectedDevice", parameters[3]);
        }
    }
    /// <summary>
    /// Shows correct properties according to the settings.
    /// </summary>
    private void ShowProperties()
    {
        Properties.Config = Config;

        // Save session data before shoving properties
        Hashtable dialogParameters = SessionHelper.GetValue("DialogSelectedParameters") as Hashtable;

        if (dialogParameters != null)
        {
            dialogParameters = (Hashtable)dialogParameters.Clone();
        }

        DisplayProperties();

        MediaItem mi = new MediaItem();

        mi.Url = txtUrl.Text;
        if (mWidth > 0)
        {
            mi.Width = mWidth;
        }
        if (mHeight > 0)
        {
            mi.Height = mHeight;
        }

        // Try get source type from URL extension
        string ext   = null;
        int    index = txtUrl.Text.LastIndexOfCSafe('.');

        if (index > 0)
        {
            ext = txtUrl.Text.Substring(index);
        }

        if (Config.OutputFormat == OutputFormatEnum.HTMLMedia)
        {
            switch (drpMediaType.SelectedValue)
            {
            case "image":
                propMedia.ViewMode = MediaTypeEnum.Image;
                mi.Extension       = String.IsNullOrEmpty(ext) ? "jpg" : ext;
                break;

            case "av":
                propMedia.ViewMode = MediaTypeEnum.AudioVideo;
                mi.Extension       = String.IsNullOrEmpty(ext) ? "avi" : ext;
                break;

            case "flash":
                propMedia.ViewMode = MediaTypeEnum.Flash;
                mi.Extension       = String.IsNullOrEmpty(ext) ? "swf" : ext;
                break;

            default:
                plcHTMLMediaProp.Visible = false;
                break;
            }
            if (URLHelper.IsPostback())
            {
                Properties.LoadSelectedItems(mi, dialogParameters);
            }
        }
        else if ((Config.OutputFormat == OutputFormatEnum.BBMedia) && (URLHelper.IsPostback()))
        {
            mi.Extension = String.IsNullOrEmpty(ext) ? "jpg" : ext;
            Properties.LoadSelectedItems(mi, dialogParameters);
        }
        else if ((Config.OutputFormat == OutputFormatEnum.URL) && (URLHelper.IsPostback()))
        {
            Properties.LoadSelectedItems(mi, dialogParameters);
        }
        // Set saved session data back into session
        if (dialogParameters != null)
        {
            SessionHelper.SetValue("DialogSelectedParameters", dialogParameters);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!StopProcessing)
        {
            if (Config.OutputFormat == OutputFormatEnum.URL)
            {
                plcMediaType.Visible = false;
                plcRefresh.Visible   = false;

                if (String.IsNullOrEmpty(QueryHelper.GetString(DialogParameters.IMG_ALT_CLIENTID, String.Empty)))
                {
                    pnlProperties.CssClass = "DialogWebProperties DialogWebPropertiesTiny";
                }
            }

            if (Config.UseSimpleURLProperties)
            {
                plcAlternativeText.Visible = false;
            }

            drpMediaType.SelectedIndexChanged += new EventHandler(drpMediaType_SelectedIndexChanged);

            imgRefresh.ImageUrl = GetImageUrl("Design/Controls/Dialogs/refresh.png");
            imgRefresh.ToolTip  = GetString("dialogs.web.refresh");
            imgRefresh.Click   += new ImageClickEventHandler(imgRefresh_Click);

            // Get reference causing postback to hidden button
            string postBackRef = ControlsHelper.GetPostBackEventReference(hdnButton, "");
            ltlScript.Text  = ScriptHelper.GetScript("function RaiseHiddenPostBack(){" + postBackRef + ";}\n");
            plcInfo.Visible = false;

            // OnChange and OnKeyDown event triggers
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "txtUrlChange", ScriptHelper.GetScript("$j(function(){ $j('" + txtUrl.ClientID + "').change(function (){ $j('#" + imgRefresh.ClientID + "').trigger('click');});});"));
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "txtUrlKeyDown", ScriptHelper.GetScript("$j(function(){ $j('#" + txtUrl.ClientID + "').keydown(function(event){ if (event.keyCode == 13) { $j('#" + imgRefresh.ClientID + "').trigger('click'); return false;}});});"));

            InitializeDesignScripts();

            if (!RequestHelper.IsPostBack())
            {
                InitFromQueryString();
                DisplayProperties();

                if (Config.OutputFormat == OutputFormatEnum.BBMedia)
                {
                    // For BB editor properties are always visible and only image is allowed.
                    plcBBMediaProp.Visible      = true;
                    propBBMedia.NoSelectionText = "";
                    drpMediaType.Items.Remove(new ListItem(GetString("dialogs.web.select"), ""));
                }

                Hashtable selectedItem = SessionHelper.GetValue("DialogParameters") as Hashtable;
                if ((selectedItem != null) && (selectedItem.Count > 0))
                {
                    LoadSelectedItem(selectedItem);
                    SessionHelper.SetValue("DialogParameters", null);
                }
                else
                {
                    // Try get selected item from session
                    selectedItem = SessionHelper.GetValue("DialogSelectedParameters") as Hashtable;
                    if ((selectedItem != null) && (selectedItem.Count > 0))
                    {
                        LoadSelectedItem(selectedItem);
                    }
                }
            }
        }
    }
    /// <summary>
    /// Handles btnOkNew click, creates new user and joins it with openID token.
    /// </summary>
    protected void btnOkNew_Click(object sender, EventArgs e)
    {
        if (response != null)
        {
            // Validate entered values
            string errorMessage = new Validator().IsRegularExp(txtUserNameNew.Text, "^([a-zA-Z0-9_\\-\\.@]+)$", GetString("mem.openid.fillcorrectusername"))
                                  .IsEmail(txtEmail.Text, GetString("mem.openid.fillvalidemail")).Result;
            string siteName = SiteContext.CurrentSiteName;
            string password = passStrength.Text;

            // If password is enabled to set, check it
            if (plcPasswordNew.Visible && (errorMessage == String.Empty))
            {
                if (password == String.Empty)
                {
                    errorMessage = GetString("mem.liveid.specifyyourpass");
                }
                else if (password != txtConfirmPassword.Text.Trim())
                {
                    errorMessage = GetString("webparts_membership_registrationform.passwordonotmatch");
                }

                // Check policy
                if (!passStrength.IsValid())
                {
                    errorMessage = AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName);
                }
            }

            // Check whether email is unique if it is required
            if (string.IsNullOrEmpty(errorMessage) && !UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), siteName, 0))
            {
                errorMessage = GetString("UserInfo.EmailAlreadyExist");
            }

            // Check reserved names
            if (string.IsNullOrEmpty(errorMessage) && UserInfoProvider.NameIsReserved(siteName, txtUserNameNew.Text.Trim()))
            {
                errorMessage = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(txtUserNameNew.Text.Trim()));
            }

            if (string.IsNullOrEmpty(errorMessage))
            {
                // Check if user with given username already exists
                UserInfo ui = UserInfoProvider.GetUserInfo(txtUserNameNew.Text.Trim());

                // User with given username is already registered
                if (ui != null)
                {
                    plcError.Visible = true;
                    lblError.Text    = GetString("mem.openid.usernameregistered");
                }
                else
                {
                    string error = DisplayMessage;
                    // Register new user
                    ui             = AuthenticationHelper.AuthenticateOpenIDUser((string)response["ClaimedIdentifier"], ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, true, false, ref error);
                    DisplayMessage = error;

                    // If user successfully created
                    if (ui != null)
                    {
                        // Set additional information
                        ui.UserName = ui.UserNickName = ui.FullName = txtUserNameNew.Text.Trim();
                        ui.Email    = txtEmail.Text;

                        // Load values submitted by OpenID provider
                        // Load date of birth
                        DateTime birthdate = (DateTime)response["BirthDate"];
                        if (birthdate != DateTime.MinValue)
                        {
                            ui.UserSettings.UserDateOfBirth = birthdate;
                        }
                        // Load default country
                        var culture = (System.Globalization.CultureInfo)response["Culture"];
                        if (culture != null)
                        {
                            ui.PreferredCultureCode = culture.Name;
                        }
                        // Nick name
                        string nick = (string)response["Nickname"];
                        if (!String.IsNullOrEmpty(nick))
                        {
                            ui.UserSettings.UserNickName = nick;
                        }
                        // Full name
                        string full = (string)response["FullName"];
                        if (!String.IsNullOrEmpty(full))
                        {
                            ui.FullName = full;
                        }
                        // User gender
                        var gender = (int?)response["UserGender"];
                        if (gender != null)
                        {
                            ui.UserSettings.UserGender = (int)gender;
                        }
                        // Set password
                        if (plcPasswordNew.Visible)
                        {
                            UserInfoProvider.SetPassword(ui, password);

                            // If user can choose password then is not considered external(external user can't login in common way)
                            ui.IsExternal = false;
                        }

                        // Set user
                        UserInfoProvider.SetUserInfo(ui);

                        // Clear used session
                        SessionHelper.Remove(SESSION_NAME_URL);
                        SessionHelper.Remove(SESSION_NAME_USERDATA);

                        AuthenticationHelper.SendRegistrationEmails(ui, ApprovalPage, true, SendWelcomeEmail);

                        // Notify administrator
                        bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
                        if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue);

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);

                        // Set authentication cookie and redirect to page
                        SetAuthCookieAndRedirect(ui);

                        if (!String.IsNullOrEmpty(DisplayMessage))
                        {
                            lblInfo.Visible = true;
                            lblInfo.Text    = DisplayMessage;
                            plcForm.Visible = false;
                        }
                        else
                        {
                            URLHelper.Redirect("~/Default.aspx");
                        }
                    }
                }
            }
            // Validation failed - display error message
            else
            {
                lblError.Text    = errorMessage;
                plcError.Visible = true;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (!StopProcessing)
        {
            plcError.Visible = false;

            // Check renamed DLL library
            if (!SystemContext.IsFullTrustLevel)
            {
                // Error label is displayed when OpenID library is not enabled
                lblError.Text      = ResHelper.GetString("socialnetworking.fulltrustrequired");
                plcError.Visible   = true;
                plcContent.Visible = false;
            }

            // Check if OpenID module is enabled
            if (!SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOpenID") && !plcError.Visible)
            {
                // Error label is displayed only in Design mode
                if (PortalContext.IsDesignMode(PortalContext.ViewMode))
                {
                    StringBuilder parameter = new StringBuilder();
                    parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembership") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> ");
                    parameter.Append(GetString("settingscategory.cmsopenid"));
                    if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
                    {
                        // Make it link for Admin
                        parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(ApplicationUrlHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">");
                        parameter.Append("</a>");
                    }

                    lblError.Text      = String.Format(GetString("mem.openid.disabled"), parameter.ToString());
                    plcError.Visible   = true;
                    plcContent.Visible = false;
                }
                // In other modes is webpart hidden
                else
                {
                    Visible = false;
                }
            }

            // Display webpart when no error occured
            if (!plcError.Visible && Visible)
            {
                if (!AuthenticationHelper.IsAuthenticated())
                {
                    plcPasswordNew.Visible  = AllowFormsAuthentication;
                    pnlExistingUser.Visible = AllowExistingUser;

                    // Initialize OpenID session
                    response = (Dictionary <string, object>)SessionHelper.GetValue(SESSION_NAME_USERDATA);

                    userProviderUrl = ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null);

                    // Check that OpenID is not already registered
                    if (response != null)
                    {
                        UserInfo ui = OpenIDUserInfoProvider.GetUserInfoByOpenID((string)response["ClaimedIdentifier"]);

                        // OpenID is already registered to some user
                        if (ui != null)
                        {
                            plcContent.Visible = false;
                            plcError.Visible   = true;
                            lblError.Text      = GetString("mem.openid.openidregistered");
                        }
                    }

                    // There is no OpenID response object stored in session - hide all
                    if (response == null)
                    {
                        if (HideForNoOpenID)
                        {
                            Visible = false;
                        }
                    }
                    else if (!RequestHelper.IsPostBack())
                    {
                        LoadData();
                    }
                }
                // Hide webpart for authenticated users
                else
                {
                    Visible = false;
                }
            }
        }
        // Hide control when StopProcessing = TRUE
        else
        {
            Visible = false;
        }
    }
Example #34
0
 protected void Application_AuthorizeRequest(object sender, System.EventArgs e)
 {
     SessionHelper.SetUser();
 }
    /// <summary>
    /// Adds product to the shopping cart.
    /// </summary>
    private void AddProductToShoppingCart()
    {
        // Validate input data
        if (!IsValid() || (SKU == null))
        {
            // Do not proces
            return;
        }

        if (RedirectToDetailsEnabled)
        {
            if (!ShowProductOptions && !ShowDonationProperties)
            {
                // Does product have some enabled product option categories?
                bool hasOptions = !DataHelper.DataSourceIsEmpty(OptionCategoryInfoProvider.GetSKUOptionCategories(SKUID, true));

                // Is product a customizable donation?
                bool isCustomizableDonation = ((SKU != null) &&
                                               (SKU.SKUProductType == SKUProductTypeEnum.Donation) &&
                                               (!((SKU.SKUPrice == SKU.SKUMinPrice) && (SKU.SKUPrice == SKU.SKUMaxPrice)) || SKU.SKUPrivateDonation));

                if (hasOptions || isCustomizableDonation)
                {
                    // Redirect to product details
                    URLHelper.Redirect("~/CMSPages/GetProduct.aspx?productid=" + SKUID);
                }
            }
        }

        // Get cart item parameters
        ShoppingCartItemParameters cartItemParams = GetShoppingCartItemParameters();

        string error = null;

        // Check if customer is enabled
        if ((ShoppingCart.Customer != null) && (!ShoppingCart.Customer.CustomerEnabled))
        {
            error = GetString("ecommerce.cartcontent.customerdisabled");
        }

        // Check if it is possible to add this item to shopping cart
        if ((error == null) && !ShoppingCartInfoProvider.CheckNewShoppingCartItems(ShoppingCart, cartItemParams))
        {
            error = String.Format(GetString("ecommerce.cartcontent.productdisabled"), SKU.SKUName);
        }

        if (!string.IsNullOrEmpty(error))
        {
            // Show error message and cancel adding the product to shopping cart
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(error));
            return;
        }

        // If donation properties are used and donation properties form is not valid
        if (donationProperties.Visible && !String.IsNullOrEmpty(donationProperties.Validate()))
        {
            return;
        }

        // Fire on add to shopping cart event
        CancelEventArgs eventArgs = new CancelEventArgs();

        if (OnAddToShoppingCart != null)
        {
            OnAddToShoppingCart(this, eventArgs);
        }

        // If adding to shopping cart was cancelled
        if (eventArgs.Cancel)
        {
            return;
        }

        // Get cart item parameters in case something changed
        cartItemParams = GetShoppingCartItemParameters();

        // Log activity
        LogProductAddedToSCActivity(SKUID, SKU.SKUName, Quantity);

        if (ShoppingCart != null)
        {
            bool updateCart = false;

            // Assign current shopping cart to current user
            CurrentUserInfo ui = CMSContext.CurrentUser;
            if (!ui.IsPublic())
            {
                ShoppingCart.User = ui;
                updateCart        = true;
            }

            // Shopping cart is not saved yet
            if (ShoppingCart.ShoppingCartID == 0)
            {
                updateCart = true;
            }

            // Update shopping cart when required
            if (updateCart)
            {
                ShoppingCartInfoProvider.SetShoppingCartInfo(ShoppingCart);
            }

            // Add item to shopping cart
            ShoppingCartItemInfo addedItem = ShoppingCart.SetShoppingCartItem(cartItemParams);

            if (addedItem != null)
            {
                // Update shopping cart item in database
                ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(addedItem);

                // Update product options in database
                foreach (ShoppingCartItemInfo option in addedItem.ProductOptions)
                {
                    ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(option);
                }

                // Update bundle items in database
                foreach (ShoppingCartItemInfo bundleItem in addedItem.BundleItems)
                {
                    ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(bundleItem);
                }

                // Track 'Add to shopping cart' conversion
                ECommerceHelper.TrackAddToShoppingCartConversion(addedItem);

                // If user has to be redirected to shopping cart
                if (RedirectToShoppingCart)
                {
                    // Set shopping cart referrer
                    SessionHelper.SetValue("ShoppingCartUrlReferrer", URLHelper.CurrentURL);

                    // Ensure shopping cart update
                    SessionHelper.SetValue("checkinventory", true);

                    // Redirect to shopping cart
                    URLHelper.Redirect(ShoppingCartUrl);
                }
                else
                {
                    // Localize SKU name
                    string skuName = (addedItem.SKU != null) ? ResHelper.LocalizeString(addedItem.SKU.SKUName) : "";

                    // Check inventory
                    ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);
                    string checkInventoryMessage        = checkResult.GetFormattedMessage();

                    // Get prodcut added message
                    string message = String.Format(GetString("com.productadded"), skuName);

                    // Add inventory check message
                    if (!String.IsNullOrEmpty(checkInventoryMessage))
                    {
                        message += "\n\n" + checkInventoryMessage;
                    }

                    // Count and show total price with options
                    CalculateTotalPrice();

                    // Register the call of JS handler informing about added product
                    ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartItemAddedHandler", "if (typeof ShoppingCartItemAddedHandler == 'function') { ShoppingCartItemAddedHandler(" + ScriptHelper.GetString(message) + "); }", true);
                }
            }
        }
    }
 public void disconnected(SessionHelper session)
 {
     // If the session has been reassigned avoid the
     // spurious callback.
     if(session != _session)
     {
         return;
     }
     closeCancelDialog();
     _session = null;
     _chat = null;
     input.IsEnabled = false;
     status.Content = "Not connected";
 }
Example #37
0
 public ActionResult Logout()
 {
     SessionHelper.DestroyUserSession();
     return(Redirect("~/"));
 }
Example #38
0
        });                                                                                                  //TODO: Remover quando implementar autenticação.

        public ProdutoController()
        {
            empresa     = (Empresa)SessionHelper.Get(SessionKeys.Empresa);
            gerenciador = new GerenciadorProduto();
        }
Example #39
0
        public IActionResult LoadDataUser2()
        {
            try
            {
                var draw = HttpContext.Request.Form["draw"].FirstOrDefault();

                // Skiping number of Rows count
                var start = Request.Form["start"].FirstOrDefault();

                // Paging Length 10,20
                var length = Request.Form["length"].FirstOrDefault();

                // Sort Column Name
                var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();

                // Sort Column Direction ( asc ,desc)
                //var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();

                // Search Value from (Search box)
                var searchValue = Request.Form["search[value]"].FirstOrDefault();

                //Paging Size (10,20,50,100)
                int pageSize = length != null?Convert.ToInt32(length) : 0;

                int skip = start != null?Convert.ToInt32(start) : 0;

                int recordsTotal = 0;

                // Getting all supplier data
                var x = SessionHelper.GetSession <User>(HttpContext.Session, "Login2");


                var orderData = (from o in _dbcontext.Orders
                                 join u in _dbcontext.Users on o.UserId equals u.UserId
                                 join s in _dbcontext.Statuses on o.StatusId equals s.Id
                                 orderby o.OrderId descending
                                 where o.IsDelete == false && o.UserId == x.UserId
                                 select new { o.OrderId, u.Username, o.OrderDate, s.StatusName });
                ////Sort data
                //if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
                //{
                //    orderData = orderData.OrderBy(sortColumn + " " + sortColumnDirection);
                //    //(sortColumn + " " + sortColumnDirection);
                //}
                //Search
                if (!string.IsNullOrEmpty(searchValue))
                {
                    orderData = orderData.Where(m => m.Username.Contains(searchValue));
                }

                //total number of rows count
                recordsTotal = orderData.Count();

                //Paging
                var data = orderData.Skip(skip).Take(pageSize).ToList();

                //Returning Json Data
                var json = Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
                return(json);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #40
0
        public static void PageCopyDo(Guid id)
        {
            PSCPortal.Engine.Page page = PageList.Where(p => p.Id == id).Single();
            PageList.PageCopy(page, ((PageArgs)PSCDialog.DataShare));
            //// check subdomain
            Guid subId = SessionHelper.GetSession(SessionKey.SubDomain) == string.Empty ? Guid.Empty : new Guid(SessionHelper.GetSession(SessionKey.SubDomain));

            if (!(subId == Guid.Empty))
            {
                SubDomainInPage sip = new SubDomainInPage();
                sip.PageId      = ((PageArgs)PSCDialog.DataShare).Page.Id;
                sip.SubDomainId = subId;
                sip.AddDB();
            }
        }
Example #41
0
 public CompanyNewsService(ICompanyNewsRepository _companyNewsRepo, SessionHelper sessionHelper) : base(sessionHelper)
 {
     repo = _companyNewsRepo;
 }
Example #42
0
 public ActionResult Logout()
 {
     SessionHelper.RemoveSession();
     return(RedirectToAction("Index", "Login"));
 }
Example #43
0
        public ActionResult DoLogin(UsersModel model)
        {
            try
            {
                UserSessionDetailsModel objUser         = new UserSessionDetailsModel();
                LoginService            objLoginService = new LoginService();
                objUser = objLoginService.ValidateUserLogin(model);

                if (objUser != null)
                {
                    //if (objUser.UserId > 0 && objUser.UserStatus == 1)
                    //{
                    if (model.RememberMe == true)
                    {
                        SessionHelper.RememberLoginDetails(Security.Encrypt(model.EmailAddress), Security.Encrypt(model.Password));
                    }
                    else
                    {
                        SessionHelper.ClearCookie("UrbanUserLoginDetails");
                    }
                    SessionHelper.UserId   = objUser.UserId;
                    SessionHelper.UserName = objUser.UserName;
                    //SessionHelper.UserDesignation = objUser.DesignationName;
                    //SessionHelper.UserDesignationId = objUser.DesignationId;
                    // SessionHelper.UserRoleId = objUser.RoleId;

                    if (TempData["ReturnURL"] != null && TempData["ReturnURL"].ToString() != "")
                    {
                        return(Redirect(TempData["ReturnURL"].ToString()));
                    }
                    else
                    {
                        return(RedirectToAction("Index", ControllerHelper.Dashboard));

                        //if (objUser.RoleId == 1)
                        //{
                        //    return RedirectToAction("Index", ControllerHelper.Home);
                        //}
                        //else
                        //{
                        //    return RedirectToAction("Index", ControllerHelper.Customer);
                        //}
                    }
                    //}
                    //else
                    //{
                    //    ViewBag.Message = Message.UserNoLongerActive;
                    //}
                }
                else
                {
                    ViewBag.Message = Message.InvalidLoginDetails;
                }

                return(View(ViewHelper.Login, model));
            }
            catch (Exception ex)
            {
                NotificationMessage msg = new NotificationMessage(Message.SystemErrorOccurred, Enums.NotifyType.SystemErrorMessage);
                TempData["Message"] = msg;
                return(View(ViewHelper.Login, model));
            }
        }
Example #44
0
        public JsonResult LoginAjax(LoginModel model)
        {
            JsonResult msg = null;

            if (!ModelState.IsValid)
            {
                var errorList = ValidationFields.GetModelStateErrors(ModelState);
                msg = Json(new { success = false, errors = errorList, responseText = "<strong>" + @RGlobal.UnableLogin + "</strong>" },
                           JsonRequestBehavior.AllowGet);
                return(msg);
            }

            try
            {
                EmployeeDto _employee;

                _employee = _employeeService.FindByUserName(
                    new EmployeeDto
                {
                    UserName = model.UserName,
                    Password = model.Password,
                    TCompany = new CompanyDto {
                        CompanyID = Convert.ToInt32(model.CompanyID)
                    }
                });

                if (_employee != null)
                {
                    _employee.RoleName = _employee.RoleID.ToEnumById <EnumsHelper.UserRoles>().ToString();

                    try
                    {
                        _employee.NameUserRole = _employee.TCompany.Name + " " + _employee.FirstName + " (" +
                                                 _employee.RoleName + ")";

                        SessionHelper.DefineValue(SessionName._userLogged, _employee);

                        msg = Json(new { success = true, responseText = "<strong>Successful!</strong> Employee Logged." },
                                   JsonRequestBehavior.AllowGet);
                    }
                    catch
                    {
                        msg = Json(new
                        {
                            success      = false,
                            responseText =
                                "<strong>Unable to login</strong>.<br/>The user name or password provided is incorrect.",
                        },
                                   JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    msg = Json(new
                    {
                        success      = false,
                        responseText =
                            "<strong>Unable to login</strong>.<br/>The user name or password provided is incorrect.",
                    },
                               JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                msg = Json(
                    new { success = false, responseText = "<strong>" + RGlobal.Forbidden + " : <br></strong>. " + ex.Message },
                    JsonRequestBehavior.AllowGet);
            }

            return(msg);
        }
Example #45
0
 public IActionResult Logout()
 {
     SessionHelper.DestroyUserSession(_http);
     return(RedirectToAction("Index", "Home"));
 }
    protected override void OnPreRender(EventArgs e)
    {
        // Register add product script
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "AddProductScript",
                                               ScriptHelper.GetScript(
                                                   "function setProduct(val) { document.getElementById('" + hidProductID.ClientID + "').value = val; } \n" +
                                                   "function setQuantity(val) { document.getElementById('" + hidQuantity.ClientID + "').value = val; } \n" +
                                                   "function setOptions(val) { document.getElementById('" + hidOptions.ClientID + "').value = val; } \n" +
                                                   "function setPrice(val) { document.getElementById('" + hdnPrice.ClientID + "').value = val; } \n" +
                                                   "function setIsPrivate(val) { document.getElementById('" + hdnIsPrivate.ClientID + "').value = val; } \n" +
                                                   "function AddProduct(productIDs, quantities, options, price, isPrivate) { \n" +
                                                   "setProduct(productIDs); \n" +
                                                   "setQuantity(quantities); \n" +
                                                   "setOptions(options); \n" +
                                                   "setPrice(price); \n" +
                                                   "setIsPrivate(isPrivate); \n" +
                                                   Page.ClientScript.GetPostBackEventReference(btnAddProduct, null) +
                                                   ";} \n" +
                                                   "function RefreshCart() {" +
                                                   Page.ClientScript.GetPostBackEventReference(btnAddProduct, null) +
                                                   ";} \n"
                                                   ));

        // Register dialog script
        ScriptHelper.RegisterDialogScript(Page);

        // Hide columns with identifiers
        gridData.Columns[0].Visible = false;
        gridData.Columns[1].Visible = false;
        gridData.Columns[2].Visible = false;
        gridData.Columns[3].Visible = false;

        // Hide actions column
        gridData.Columns[5].Visible = (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems) ||
                                      (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrder);

        // Disable specific controls
        if (!Enabled)
        {
            lnkNewItem.Enabled       = false;
            lnkNewItem.OnClientClick = "";
            selectCurrency.Enabled   = false;
            btnEmpty.Enabled         = false;
            btnUpdate.Enabled        = false;
            txtCoupon.Enabled        = false;
            chkSendEmail.Enabled     = false;
        }

        // Show/Hide dropdownlist with currencies
        pnlCurrency.Visible &= (selectCurrency.HasData && selectCurrency.DropDownSingleSelect.Items.Count > 1);

        // Check session parameters for inventory check
        if (ValidationHelper.GetBoolean(SessionHelper.GetValue("checkinventory"), false))
        {
            checkInventory = true;
            SessionHelper.Remove("checkinventory");
        }

        // Check inventory
        if (checkInventory)
        {
            ShoppingCartCheckResult checkResult = ShoppingCartInfoProvider.CheckShoppingCart(ShoppingCart);

            if (checkResult.CheckFailed)
            {
                lblError.Text = checkResult.GetHTMLFormattedMessage();
            }
        }

        // Display messages if required
        lblError.Visible = !string.IsNullOrEmpty(lblError.Text.Trim());
        lblInfo.Visible  = !string.IsNullOrEmpty(lblInfo.Text.Trim());

        base.OnPreRender(e);
    }
    /// <summary>
    /// 加入 system log
    /// </summary>
    /// <param name="action">異動行為</param>
    public void AddSystemLog(MsgVO.Action action, object obj, string function, string note)
    {
        SessionHelper sHelper = new SessionHelper();

        LoginUserVO userVO = sHelper.LoginUser;

        LogSystemVO logVO = new LogSystemVO();

        if (userVO != null)
        {
            logVO.UpdateId = userVO.UserId;
        }

        logVO.UpdateDate = DateTime.Now;
        logVO.Action = action.ToString();
        logVO.UpdateClassName = obj.GetType().ToString();
        logVO.Fucntion = function;
        logVO.SubFucntion = logVO.SubFucntion;
        logVO.Note = note;
        logVO.IpAddress = m_HttpHelper.GetUserIp(HttpContext.Current);
        m_LogService.CreateLogSystem(logVO);
    }
Example #48
0
 public static SessionHelper GetInstance()
 {
     return _instance ?? (_instance = new SessionHelper());
 }
    private void doLogin(string id, string pw)
    {
        //帳號皆改為小寫
        if (!string.IsNullOrEmpty(id))
        {
            id = id.ToLower();
        }

        LoginUserVO loginUser = m_AuthService.Login(id, pw);

        if (loginUser != null)
        {
            SessionHelper sHelper = new SessionHelper();

            sHelper.LoginUser = loginUser;
            sHelper.IsAdmin = m_AuthService.IsAdmin(loginUser);
            //sHelper.LoginUserBelongToBranchNo = loginUser.BelongToBranch[0].BranchNo;
            //加入log
            webLogService.AddSystemLogLogin(loginUser.UserId);

            //NHibernateUtil.Initialize(loginUser.BelongRoles);

            //清除快取
            UserMenuFuncContainer.GetInstance().ReloadAllMenu();

            //HttpHelper httpHelper = new HttpHelper();
            //string referer = httpHelper.GetReferer(HttpContext.Current);

            Response.Redirect("~/admin/index.aspx", false);

            return;
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "js", JavascriptUtil.AlertJSAndRedirect(MsgVO.LOGIN_ERROR, "Login.aspx"), false);
        }
    }
        public async void connected(SessionHelper session)
        {
            // If the session has been reassigned avoid the
            // spurious callback.
            if(session != _session)
            {
                return;
            }

            Ice.Object servant = new ChatCallbackI(this);

            ChatCallbackPrx callback = Demo.ChatCallbackPrxHelper.uncheckedCast(_session.addWithUUID(servant));
            _chat = ChatSessionPrxHelper.uncheckedCast(_session.session());
            try
            {
                await _chat.setCallbackAsync(callback);
                closeCancelDialog();
                input.IsEnabled = true;
                status.Content = "Connected with " + _loginData.routerHost;
            }
            catch(Exception)
            {
                if(_session != null)
                {
                    _session.destroy();
                }
            }
        }
Example #51
0
 public static ELUsuario ObtenerUsuarioLogeado()
 {
     return(new BLUsuario().Obtener(SessionHelper.GetUser()));
 }
Example #52
0
        public IActionResult OnePayPayment([Bind("vpc_Customer_Phone,vpc_Customer_Email,vpc_Customer_Id,vpc_Customer_Name")] VPC vpc)
        {
            string value = SessionHelper.GetObjectFromJson <string>(HttpContext.Session, "User");
            var    user  = eMarketContext.TaiKhoan.Include(p => p.ThongTinTaiKhoan).Where(p => p.UserName == value).FirstOrDefault();

            List <GioHang> danhsachhang = SessionHelper.GetObjectFromJson <List <GioHang> >(HttpContext.Session, "cart");
            double         total        = 0;

            foreach (var x in danhsachhang)
            {
                total += x.HangHoa.Gia * x.SoLuong;
            }
            total = VPCRequest.USD_VND * total;
            var current_invoice = CreateInvoice(danhsachhang, vpc.vpc_Customer_Name, vpc.vpc_Customer_Email, vpc.vpc_Customer_Address, vpc.vpc_Customer_Phone);

            HttpContext.Session.SetString("cart", "");

            foreach (var item in danhsachhang)
            {
                var topselling = eMarketContext.TopSelling.Where(p => p.HangHoaId == item.HangHoa.HangHoaId).FirstOrDefault();
                if (topselling == null)
                {
                    var newcolumn = new TopSelling();
                    newcolumn.HangHoaId = item.HangHoa.HangHoaId;
                    newcolumn.SoLan     = 1;
                    eMarketContext.Add(newcolumn);
                    eMarketContext.SaveChanges();
                }
                else
                {
                    topselling.SoLan += 1;
                    eMarketContext.Update(topselling);
                    eMarketContext.SaveChanges();
                }
            }

            //Send request to OnePay
            string     returnURL = Url.Action("OnePayResult", "GioHang", null, Request.Scheme);;
            VPCRequest conn      = new VPCRequest();

            conn.SetSecureSecret(VPCRequest.SECURE_SECRET);
            conn.AddDigitalOrderField("Title", "onepay paygate");
            conn.AddDigitalOrderField("vpc_Locale", "vn");//Chon ngon ngu hien thi tren cong thanh toan (vn/en)
            conn.AddDigitalOrderField("vpc_Version", "2");
            conn.AddDigitalOrderField("vpc_Command", "pay");
            conn.AddDigitalOrderField("vpc_Merchant", VPCRequest.MERCHANT_ID);
            conn.AddDigitalOrderField("vpc_AccessCode", VPCRequest.ACCESS_CODE);
            conn.AddDigitalOrderField("vpc_MerchTxnRef", "HoaDon_" + current_invoice.HoaDonId);
            conn.AddDigitalOrderField("vpc_OrderInfo", "HoaDon_" + current_invoice.HoaDonId);
            conn.AddDigitalOrderField("vpc_Amount", total + "00");
            conn.AddDigitalOrderField("vpc_Currency", "VND");
            conn.AddDigitalOrderField("vpc_ReturnURL", returnURL);

            // Thong tin them ve khach hang. De trong neu khong co thong tin
            conn.AddDigitalOrderField("vpc_Customer_Phone", vpc.vpc_Customer_Phone);
            conn.AddDigitalOrderField("vpc_Customer_Email", vpc.vpc_Customer_Email);
            conn.AddDigitalOrderField("vpc_Customer_Id", "" + user.TaiKhoanId);

            // Dia chi IP cua khach hang
            string ipAddress = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

            conn.AddDigitalOrderField("vpc_TicketNo", ipAddress);

            // Chuyen huong trinh duyet sang cong thanh toan
            string url = conn.Create3PartyQueryString();

            return(Redirect(url));
        }
Example #53
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    var candId  = Session["CandId"].ToString();
                    var batchId = Session["BatchId"].ToString();
                    var tenant  = SessionHelper.GetTenantID(Session);
                    using (QuizBookDbEntities1 _db = new QuizBookDbEntities1())
                    {
                        if (string.IsNullOrEmpty(tenant))
                        {
                            ErecruitHelper.SetErrorData(new NullReferenceException("There must be a valid Organisation"), Session);
                            Response.Redirect("ErrorPage.aspx", false);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(candId))
                            {
                                ErecruitHelper.SetErrorData(new NullReferenceException("There must be a valid candidate"), Session);
                                Response.Redirect("ErrorPage.aspx", false);
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(batchId))
                                {
                                    ErecruitHelper.SetErrorData(new NullReferenceException("There must be a valid Batch"), Session);
                                    Response.Redirect("ErrorPage.aspx", false);
                                }
                                else
                                {
                                    var cid = long.Parse(candId);
                                    var bid = long.Parse(batchId);
                                    var tid = long.Parse(tenant);

                                    var repM   = _db.TestResultReports.FirstOrDefault(s => s.candId == cid && s.batchId == bid && s.tenantId == tid);
                                    var repSum = _db.TestReportSummaries.FirstOrDefault(x => x.ReportId == repM.Id);
                                    var repAns = _db.TestReportAnswers.Where(x => x.ReportId == repM.Id).ToList();



                                    logoCt.Src = GetUrl("book.png");

                                    //var result = _db.IndividualTestResult_sp(bid, cid, tid).ToList();
                                    //var cand = result.FirstOrDefault();

                                    candidateId.Text   = repM.candidateId.ToUpper();
                                    candidateName.Text = repM.candidateName.ToUpper();
                                    batchName.Text     = repM.batchName.ToUpper();
                                    tenantName.Text    = repM.tenantName.ToUpper();
                                    tstDate.Text       = repM.tstDate;


                                    var forList = repAns.Select(x => new
                                    {
                                        sn            = x.sn,
                                        question      = x.question,
                                        Mark          = x.Mark,
                                        Score         = x.Score,
                                        chosenAnswer  = x.chosenAnswer,
                                        correctAnswer = x.correctAnswer,
                                        Status        = x.correct == "Correct" ? "<span style='color:#008000;'>Right</span>":x.correct == "Partial"? "<span style='color:#ffb400;'>Partial</span>": " <span style='color:#f00;'>Wrong</span>",
                                    }).ToList();



                                    //var forList = result.Select((s, i) => new
                                    //{
                                    //    sn = (i + 1).ToString(),
                                    //    Question = s.QuestionDetails,
                                    //    Answer = string.IsNullOrEmpty(s.ChosenAnswerDetails) ? "Unanswered" : s.ChosenAnswerDetails,
                                    //    CorrectAnswer = s.CorrectAnswer,
                                    //    Status = s.Correct.HasValue ? s.Correct.Value ? "<b style='color:green;'>Right</b>" : "<b style='color:red;'>Wrong</b>" : "<b style='color:red;'>Wrong</b>"
                                    //}).ToList();

                                    ResultList.DataSource = forList;
                                    ResultList.DataBind();

                                    var summary = new ResultModel
                                    {
                                        Correct           = repSum.Correct.Value,
                                        Partial           = repSum.Partial.Value,
                                        Wrong             = repSum.Wrong.Value,
                                        Unanswered        = repSum.Unanswered.Value,
                                        CorrectPercent    = repSum.CorrectPercent.Value,
                                        PartialPercent    = repSum.PartialPercent.Value,
                                        WrongPercent      = repSum.WrongPercent.Value,
                                        UnansweredPercent = repSum.UnansweredPercent.Value,
                                        CorrectCount      = repSum.CorrectCount.Value,
                                        PartialCount      = repSum.PartialCount.Value,
                                        WrongCount        = repSum.WrongCount.Value,
                                        UnansweredCount   = repSum.UnansweredCount.Value,
                                        questionCount     = repSum.questionCount.HasValue ? repSum.questionCount.Value:0,
                                        questionTotalMark = repSum.questionTotalMark.HasValue? repSum.questionTotalMark.Value:0,
                                        testDate          = repSum.testDate.Value
                                    };

                                    var totalQustionMark = forList.Sum(x => x.Mark);

                                    Correct.Text           = repM.Correct.ToString();
                                    Wrong.Text             = repM.Wrong.ToString();
                                    Partial.Text           = repM.Partial.ToString();
                                    Unanswered.Text        = repM.Unanswered.ToString();
                                    percentage.Text        = repM.percentage.ToString();
                                    result_correct.Text    = summary.Correct.ToString();
                                    result_partial.Text    = summary.Partial.ToString();
                                    result_wrong.Text      = summary.Wrong.ToString();
                                    result_unanswered.Text = summary.Unanswered.ToString();
                                    sumation_result.Text   = (summary.Correct + summary.Partial).ToString() + " out of " + totalQustionMark;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WSProfile filter = new WSProfile(System.Reflection.Assembly.GetExecutingAssembly().FullName.Split(',')[0], Path.GetFileName(Request.Url.AbsolutePath) + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name, ApplicationType.WebApplication);
                    filter.LogError(ex);
                    //ErecruitHelper.SetErrorData(ex, Session);
                    //Response.Redirect("ErrorPage.aspx", false);
                }
            }
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var cart = SessionHelper.GetObjectFromJson <List <OrderDetail> >(HttpContext.Session, "cart");

            return(View(cart));
        }
        public void connectFailed(SessionHelper session, Exception ex)
        {
            // If the session has been reassigned avoid the
            // spurious callback.
            if(session != _session)
            {
                return;
            }

            closeCancelDialog();
            status.Content = ex.GetType();
        }
Example #56
0
        public ActionResult CheckLogin(string username, string password, string code)
        {
            string ss = Md5.GetMD5(code.ToLower());

            try
            {
                if (SessionHelper.GetSession(SessionKey.session_verifycode.ToString()) == string.Empty || Md5.GetMD5(code.ToLower()) != SessionHelper.GetSession(SessionKey.session_verifycode.ToString()))
                {
                    string dds = SessionHelper.GetSession(SessionKey.session_verifycode.ToString());
                    string dd  = Session[SessionKey.session_verifycode.ToString()].ToString();
                    throw new Exception("验证码错误,请重新输入");
                }
                LoginInputDto inputDto = new LoginInputDto(username, Md5.GetMD5(password));
                UserDto       userDto  = _sysUser.CheckLogin(inputDto);
                if (userDto != null)
                {
                    UserInfo info = new UserInfo();
                    info.UserID   = userDto.Id;
                    info.UserName = userDto.UserName;
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket
                                                               (1, JsonConvert.SerializeObject(info), DateTime.Now, DateTime.Now.AddMinutes(20), true, "role");
                    string     encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                }
                return(Json(new AjaxResult {
                    state = ResultType.success.ToString(), message = "登录成功。"
                }));
            }
            catch (Exception ex)
            {
                return(Json(new AjaxResult {
                    state = ResultType.error.ToString(), message = ex.Message
                }));
            }
        }
 public void createdCommunicator(SessionHelper session)
 {
 }
    /// <summary>
    /// Checks status of current user.
    /// </summary>
    protected void CheckStatus()
    {
        // Get current site name
        string siteName = SiteContext.CurrentSiteName;
        string error    = null;

        // Check return URL
        string returnUrl = QueryHelper.GetString("returnurl", null);

        returnUrl = HttpUtility.UrlDecode(returnUrl);

        // Get current URL
        string currentUrl = LinkedInHelper.GetPurifiedUrl().ToString();

        // Get LinkedIn response status
        switch (linkedInHelper.CheckStatus(RequireFirstName, RequireLastName, RequireBirthDate, null))
        {
        // User is authenticated
        case LinkedInHelper.RESPONSE_AUTHENTICATED:
            // LinkedIn profile Id not found  = save new user
            if (UserInfoProvider.GetUserInfoByLinkedInID(linkedInHelper.MemberId) == null)
            {
                string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSRequiredLinkedInPage").Trim();

                // No page set, user can be created
                if (String.IsNullOrEmpty(additionalInfoPage))
                {
                    // Register new user
                    UserInfo ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, true, true, ref error);

                    // If user was successfully created
                    if (ui != null)
                    {
                        if (linkedInHelper.BirthDate != DateTimeHelper.ZERO_TIME)
                        {
                            ui.UserSettings.UserDateOfBirth = linkedInHelper.BirthDate;
                        }

                        UserInfoProvider.SetUserInfo(ui);

                        // If user is enabled
                        if (ui.Enabled)
                        {
                            // Create authentication cookie
                            AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "linkedinlogin" });

                            MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);
                        }

                        // Notify administrator
                        if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress))
                        {
                            AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress);
                        }

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue);

                        MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument);
                    }

                    // Redirect when authentication was successful
                    if (String.IsNullOrEmpty(error))
                    {
                        if (URLHelper.IsLocalUrl(returnUrl))
                        {
                            URLHelper.Redirect(returnUrl);
                        }
                        else
                        {
                            URLHelper.Redirect(currentUrl);
                        }
                    }
                    // Display error otherwise
                    else
                    {
                        lblError.Text    = error;
                        lblError.Visible = true;
                    }
                }
                // Additional information page is set
                else
                {
                    // Store user object in session for additional use
                    string response = (linkedInHelper.LinkedInResponse != null) ? linkedInHelper.LinkedInResponse.OuterXml : null;
                    SessionHelper.SetValue(SESSION_NAME_USERDATA, response);

                    // Redirect to additional info page
                    string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage);

                    if (URLHelper.IsLocalUrl(returnUrl))
                    {
                        // Add return URL to parameter
                        targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl));
                    }
                    URLHelper.Redirect(UrlResolver.ResolveUrl(targetURL));
                }
            }
            // LinkedIn profile id is in DB
            else
            {
                // Login existing user
                UserInfo ui = AuthenticationHelper.AuthenticateLinkedInUser(linkedInHelper.MemberId, linkedInHelper.FirstName, linkedInHelper.LastName, siteName, false, true, ref error);

                if ((ui != null) && (ui.Enabled))
                {
                    // Create authentication cookie
                    AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "linkedinlogin" });

                    MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument);

                    // Redirect user
                    if (URLHelper.IsLocalUrl(returnUrl))
                    {
                        URLHelper.Redirect(UrlResolver.ResolveUrl(URLHelper.GetAbsoluteUrl(returnUrl)));
                    }
                    else
                    {
                        URLHelper.Redirect(currentUrl);
                    }
                }
                // Display error which occurred during authentication process
                else if (!String.IsNullOrEmpty(error))
                {
                    lblError.Text    = error;
                    lblError.Visible = true;
                }
                // Otherwise is user disabled
                else
                {
                    lblError.Text    = GetString("membership.userdisabled");
                    lblError.Visible = true;
                }
            }
            break;

        // No authentication, do nothing
        case LinkedInHelper.RESPONSE_NOTAUTHENTICATED:
            break;
        }
    }
Example #59
0
    /// <summary>
    /// Get user information and logs user (register if no user found)
    /// </summary>
    private void ProcessLiveIDLogin()
    {
        // Get authorization code from URL
        String code = QueryHelper.GetString("code", String.Empty);

        // Additional info page for login
        string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSLiveIDRequiredUserDataPage");

        // Create windows login object
        WindowsLiveLogin wwl = new WindowsLiveLogin(siteName);

        // Windows live User
        WindowsLiveLogin.User liveUser = null;
        if (!WindowsLiveLogin.UseServerSideAuthorization)
        {
            if (!RequestHelper.IsPostBack())
            {
                // If client authentication, get token displayed in url after # from window.location
                String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location");
                ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script));
            }
            else
            {
                // Try to get full url from event argument
                string fullurl = Request[postEventArgumentID];

                // Authentication token - use to get uid
                String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&");

                // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it
                String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-]+)&");

                if (token != String.Empty)
                {
                    // Return context from session
                    GetLoginInformation();

                    // Authenticate user by found token
                    liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken);
                    if (liveUser != null)
                    {
                        // Set info to refresh to parent page
                        ScriptHelper.RegisterWOpenerScript(Page);
                        CreateCloseScript("");
                    }
                }
            }
        }
        else
        {
            GetLoginInformation();

            // Process login via Live ID
            liveUser = wwl.ProcessLogin(code, relativeURL);
        }

        // Authorization sucesfull
        if (liveUser != null)
        {
            // Find user by ID
            UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id);

            string error = String.Empty;

            // Register new user
            if (winUser == null)
            {
                // Check whether additional user info page is set
                // No page set, user can be created/sign
                if (additionalInfoPage == String.Empty)
                {
                    // Create new user user
                    UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                    // Remove live user object from session, won't be needed
                    Session.Remove("windowsliveloginuser");

                    // If user was found or successfuly created
                    if ((ui != null) && (ui.Enabled))
                    {
                        // Send registration e-mails
                        // E-mail confirmation is not required as user already provided confirmation by successful login using LiveID
                        AuthenticationHelper.SendRegistrationEmails(ui, null, null, false, false);

                        double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0);

                        // Log user registration into the web analytics and track conversion if set
                        AnalyticsHelper.TrackUserRegistration(siteName, ui, conversionName, resolvedConversionValue);

                        Activity activity = new ActivityRegistration(ui, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables);
                        if (activity.Data != null)
                        {
                            activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            activity.Log();
                        }

                        SetAuthCookieAndRedirect(ui);
                    }
                    // User not created
                    else
                    {
                        if (WindowsLiveLogin.UseServerSideAuthorization)
                        {
                            WindowsLiveLogin.ClearCookieAndRedirect(loginPage);
                        }
                        else
                        {
                            CreateCloseScript("clearcookieandredirect");
                        }
                    }
                }
                // Required data page exists
                else
                {
                    // Store user object in session for additional info page
                    SessionHelper.SetValue("windowsliveloginuser", liveUser);

                    if (WindowsLiveLogin.UseServerSideAuthorization)
                    {
                        // Redirect to additional info page
                        URLHelper.Redirect(URLHelper.ResolveUrl(additionalInfoPage));
                    }
                    else
                    {
                        CreateCloseScript("redirectToAdditionalPage");
                    }
                }
            }
            else
            {
                UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error);

                // If user was found
                if ((ui != null) && (ui.Enabled))
                {
                    SetAuthCookieAndRedirect(ui);
                }
            }
        }
    }
Example #60
0
        public static void PageAdd()
        {
            PageArgs pageArgs = (PageArgs)PSCDialog.DataShare;
            Page     page     = pageArgs.Page;

            PageList.AddDB(page);
            page.UpdatePageLayout(page.LayoutId);
            // check subdomain
            Guid subId = SessionHelper.GetSession(SessionKey.SubDomain) == string.Empty ? Guid.Empty : new Guid(SessionHelper.GetSession(SessionKey.SubDomain));

            if (!(subId == Guid.Empty))
            {
                SubDomainInPage sip = new SubDomainInPage();
                sip.PageId      = page.Id;
                sip.SubDomainId = subId;
                sip.AddDB();
            }
        }