private void Page_Load(object sender, System.EventArgs e)
        {
            Response.CacheControl = "private";
            Response.Expires      = 0;
            Response.AddHeader("pragma", "no-cache");
            Response.Cache.SetAllowResponseInBrowserHistory(false);

            Customer ThisCustomer = ((AspDotNetStorefrontPrincipal)Context.User).ThisCustomer;

            ThisCustomer.RequireCustomerRecord();
            int CustomerID = ThisCustomer.CustomerID;

            Address UseBillingAddress = new Address();

            UseBillingAddress.LoadFromDB(ThisCustomer.PrimaryBillingAddressID);

            CustomerSession customerSession = new CustomerSession(CustomerID);

            FormPostUrl = customerSession["Moneybookers_3DSecure_RedirectUrl"];
            System.Text.StringBuilder formFields = new System.Text.StringBuilder();

            foreach (var key in customerSession["Moneybookers_3DSecure_ParameterKeys"].Split(';'))
            {
                formFields.AppendFormat("<input type='hidden' name='{0}' value='{1}' />\r\n", key.Substring("Moneybookers_3DSecure_Parameter_".Length), customerSession[key]);
            }

            litFormFields.Text = formFields.ToString();
        }
Example #2
0
        public IHttpActionResult GetCustomer()
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var session = HttpContext.Current.Request.Cookies.Get("sessionId");

            if (session == null)
            {
                return(BadRequest("请先登录!"));
            }

            var customerId = CustomerSession.GetCustomerIdFromSession(int.Parse(session.Value));

            if (customerId < 0)
            {
                return(BadRequest("请先登录!"));
            }

            var customer = _db.Customers.Find(customerId);


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

            return(Ok(customer));
        }
Example #3
0
        public void OnSuccess(Token token)
        {
            try
            {
                // Send token to your own web service
                //var stripeBankAccount = token.BankAccount;
                //var stripeCard = token.Card;
                //var stripeCreated = token.Created;
                tokenId = token.Id;
                //var stripeLiveMode = token.Livemode;
                //var stripeType = token.Type;
                //var stripeUsed = token.Used;
                var currencyCode = ListUtils.SettingsSiteList?.StripeCurrency ?? "USD";

                CustomerSession.InitCustomerSession(this);
                CustomerSession.Instance.SetCustomerShippingInformation(this, new ShippingInformation());
                CustomerSession.Instance.AddProductUsageTokenIfValid(tokenId);

                // Create the PaymentSession
                PaymentSession = new PaymentSession(this);
                PaymentSession.Init(this, GetPaymentSessionConfig());

                var priceInt = Convert.ToInt32(Price) * 100;
                Stripe.CreateSource(SourceParams.CreateAlipaySingleUseParams(priceInt, currencyCode.ToLower(), EtName.Text, UserDetails.Email, "stripe://payment_intent_return"), this);
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
                AndHUD.Shared.Dismiss(this);
            }
        }
Example #4
0
        public IHttpActionResult CustomerGetAllAddresses()
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var session = HttpContext.Current.Request.Cookies.Get("sessionId");

            if (session == null)
            {
                return(BadRequest("Not Login"));
            }

            int customerId = CustomerSession.GetCustomerIdFromSession(int.Parse(session.Value));

            if (customerId < 0)
            {
                return(BadRequest("Not Login"));
            }

            CustomerAddress[] customerAddresses = AddressService.CustomerGetAllAddresses(customerId);
            if (customerAddresses.Length == 0)
            {
                return(BadRequest("No Address"));
            }

            return(Ok(customerAddresses));
        }
        private Customer AuthoriseRequest()
        {
            try {
                string authId = GetAuthId();
                //logger.Debug("Authorising request for sessionid=" + authId + ".");

                if (authId != null)
                {
                    CustomerSession customerSession = CRMSessionManager.Authenticate(authId);
                    if (customerSession == null)
                    {
                        logger.Warn("SIPProvisioningWebService AuthoriseRequest failed for " + authId + ".");
                        throw new UnauthorizedAccessException();
                    }
                    else
                    {
                        Customer customer = CRMCustomerPersistor.Get(c => c.CustomerUsername == customerSession.CustomerUsername);
                        return(customer);
                    }
                }
                else
                {
                    logger.Warn("SIPProvisioningWebService AuthoriseRequest failed no authid header.");
                    throw new UnauthorizedAccessException();
                }
            }
            catch (UnauthorizedAccessException) {
                throw;
            }
            catch (Exception excp) {
                logger.Error("Exception AuthoriseRequest. " + excp.Message);
                throw new Exception("There was an exception authorising the request.");
            }
        }
        protected string GetLastAccessInfo(CustomerSession customerSession)
        {
            string info = string.Format(GetLocaleResourceString("Admin.CustomerShoppingCart.CustomerColumn.LastAccess"),
                                        DateTimeHelper.ConvertToUserTime(customerSession.LastAccessed, DateTimeKind.Utc));

            return(info);
        }
Example #7
0
        public string ObtainSagePayPiMerchantSessionKey()
        {
            var customer            = HttpContext.Current.GetCustomer();
            var session             = new CustomerSession(customer.CustomerID);
            var useLiveTransactions = AppConfigProvider.GetAppConfigValue <bool>("UseLiveTransactions");
            var url = (useLiveTransactions
                                ? $"{AppConfigProvider.GetAppConfigValue("SagePayPi.LiveUrl")}merchant-session-keys"
                                : $"{AppConfigProvider.GetAppConfigValue("SagePayPi.TestUrl")}merchant-session-keys");
            var jsonObject = new JObject(
                new JProperty("vendorName", AppConfigProvider.GetAppConfigValue("SagePayPi.VendorName"))
                );

            var apiResponse       = SagePayPiApiCall(jsonObject.ToString(), url, "POST");
            var formattedResponse = JObject.Parse(apiResponse);
            var responseHasError  = ResponseHasError(formattedResponse, "merchantSessionKey", string.Empty);

            if (responseHasError)
            {
                return(null);
            }

            var formattedResponseString = formattedResponse
                                          .Children()
                                          .Last()
                                          .Last()
                                          .ToString()
                                          .Replace("\"", string.Empty)
                                          .Replace("\"", "'")
                                          .ToString();

            session[AppLogic.SagePayPiMerchantSessionKey] = formattedResponseString;

            return(formattedResponseString);
        }
Example #8
0
        public IHttpActionResult CustomerGetAllTransacts()
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            //var a = new BookSearch();
            var session = HttpContext.Current.Request.Cookies.Get("sessionId");

            if (session == null)
            {
                return(BadRequest("请重新登录!"));
            }

            var customerId = CustomerSession.GetCustomerIdFromSession(int.Parse(session.Value));

            if (customerId < 0)
            {
                return(BadRequest("请先登录!"));
            }


            Transact[] transacts = TransactService.CustomerGetAllTransacts(customerId);
            if (transacts.Length == 0)
            {
                return(BadRequest("没有订单信息!"));
            }
            return(Ok(transacts));
        }
Example #9
0
 private void AddNewSession(CustomerSession newSession)
 {
     lock (this.SyncRoot)
     {
         m_customerSessions.AddLast(newSession);
     }
 }
Example #10
0
 private void RemoveSession(CustomerSession session)
 {
     lock (this.SyncRoot)
     {
         m_customerSessions.Remove(session);
     }
 }
Example #11
0
 public void ReportSessionShutdown(CustomerSession session)
 {
     lock (this.SyncRoot)
     {
         m_customerSessions.Remove(session);
     }
 }
Example #12
0
        public void InitiateCallback(
            Customer customer,
            string callbackTargetUri,
            string callbackTargetDisplayName)
        {
            string logMessage =
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Callback Initiation: Customer {0} Target {1}",
                    callbackTargetUri,
                    callbackTargetDisplayName);

            this.Logger.Log(Logger.LogLevel.Info, logMessage);

            CustomerSession newSession = null;

            lock (this.SyncRoot)
            {
                if (this.IsTerminatingTerminated)
                {
                    return;
                }

                newSession = new CustomerSession(this, customer, callbackTargetUri, callbackTargetDisplayName);
                this.AddNewSession(newSession);
            }

            Debug.Assert(newSession != null, "newSession should not be null");

            // Start up the customer session outside of the lock to avoid deadlocks
            this.StartupCustomerSession(newSession);
        }
Example #13
0
        /// <summary>
        /// Gets customer session
        /// </summary>
        /// <param name="createInDatabase">Create session in database if no one exists</param>
        /// <param name="sessionId">Session identifier</param>
        /// <returns>Customer session</returns>
        public CustomerSession GetSession(bool createInDatabase, Guid?sessionId)
        {
            CustomerSession byId = null;
            object          obj2 = Current[CONST_CUSTOMERSESSION];

            if (obj2 != null)
            {
                byId = (CustomerSession)obj2;
            }
            if ((byId == null) && (sessionId.HasValue))
            {
                byId = CustomerManager.GetCustomerSessionByGUID(sessionId.Value);
                return(byId);
            }
            if (byId == null && createInDatabase)
            {
                byId = SaveSessionToDatabase();
            }
            string customerSessionCookieValue = string.Empty;

            if ((HttpContext.Current.Request.Cookies[CONST_CUSTOMERSESSIONCOOKIE] != null) && (HttpContext.Current.Request.Cookies[CONST_CUSTOMERSESSIONCOOKIE].Value != null))
            {
                customerSessionCookieValue = HttpContext.Current.Request.Cookies[CONST_CUSTOMERSESSIONCOOKIE].Value;
            }
            if ((byId) == null && (!string.IsNullOrEmpty(customerSessionCookieValue)))
            {
                CustomerSession dbCustomerSession = CustomerManager.GetCustomerSessionByGUID(new Guid(customerSessionCookieValue));
                byId = dbCustomerSession;
            }
            Current[CONST_CUSTOMERSESSION] = byId;
            return(byId);
        }
Example #14
0
        public ActionResult InsertCoin(double coin)
        {
            var             amount          = new Random().Next(1, 4);
            CustomerSession customerSession = new CustomerSession();

            switch (amount)
            {
            case 1:
                customerSession.Wallet += 0.05;
                break;

            case 2:
                customerSession.Wallet += 0.10;
                break;

            case 3:
                customerSession.Wallet += 0.25;
                break;

            case 4:
                Console.WriteLine("We do not accept this coin!");
                break;
            }

            return(View("Vend"));
        }
        string ProcessNativeThreeDSecureReturn(Customer customer)
        {
            var paReq = customer.ThisCustomerSession["3Dsecure.paReq"];
            var paRes = CommonLogic.FormCanBeDangerousContent("PaRes")
                        .Replace(" ", "")
                        .Replace("\r", "")
                        .Replace("\n", "");
            var merchantData  = CommonLogic.FormCanBeDangerousContent("MD");
            var transactionId = customer.ThisCustomerSession["3Dsecure.XID"];
            var orderNumber   = customer.ThisCustomerSession.SessionUSInt("3Dsecure.OrderNumber");

            if (!string.IsNullOrEmpty(paRes))
            {
                customer.ThisCustomerSession["3Dsecure.PaRes"] = paRes;
            }

            if (merchantData != customer.ThisCustomerSession["3Dsecure.MD"] ||
                orderNumber == 0 ||
                string.IsNullOrEmpty(paReq) ||
                string.IsNullOrEmpty(transactionId))
            {
                NoticeProvider.PushNotice(StringResourceProvider.GetString("secureprocess.aspx.1"), NoticeType.Failure);
                ClearThreeDSecureSessionInfo(customer);
                return(Url.Action(ActionNames.Index, ControllerNames.Checkout));
            }

            var cart   = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var status = Gateway.MakeOrder(string.Empty, AppLogic.TransactionMode(), cart, orderNumber, string.Empty, string.Empty, string.Empty, string.Empty);

            // The session may have changed in MakeOrder, so get the latest values from the DB
            CustomerSession cSession = new CustomerSession(customer.CustomerID);

            if (status == AppLogic.ro_OK)
            {
                if (!string.IsNullOrEmpty(cSession["3DSecure.LookupResult"]))
                {
                    // the data in this session variable will be encoded, so decode it before saving to the database
                    var decodedBytes = Convert.FromBase64String(cSession["3DSecure.LookupResult"]);
                    var lookupResult = Encoding.UTF8.GetString(decodedBytes);

                    DB.ExecuteSQL("UPDATE Orders SET CardinalLookupResult = @CardinalLookupResult WHERE OrderNumber = @OrderNumber",
                                  new SqlParameter[] {
                        new SqlParameter("@CardinalLookupResult", lookupResult),
                        new SqlParameter("@OrderNumber", orderNumber)
                    });

                    cSession["3DSecure.LookupResult"] = string.Empty;
                }

                ClearThreeDSecureSessionInfo(customer);
                return(Url.Action(
                           ActionNames.Confirmation,
                           ControllerNames.CheckoutConfirmation,
                           new { orderNumber = orderNumber }));
            }

            NoticeProvider.PushNotice(string.Format(StringResourceProvider.GetString("secureprocess.aspx.5"), status), NoticeType.Failure);
            ClearThreeDSecureSessionInfo(customer);
            return(Url.Action(ActionNames.Index, ControllerNames.Checkout));
        }
Example #16
0
 /// <summary>
 /// Initialize a new instance of AuthenticationDialog
 /// </summary>
 /// <param name="customerSession">Customer session</param>
 /// <param name="configuration">AuthenticationConfiguration</param>
 public AuthenticationDialog(CustomerSession customerSession, AuthenticationConfiguration configuration)
 {
     this.CustomerSession = customerSession;
     this.Configuration   = configuration;
     m_speechGrammar      = new List <Grammar>();
     m_dtmfGrammar        = new List <Grammar>();
 }
Example #17
0
        }         // Ip

        private void IpAgainstList(List <SessionInfo> thisCustomerSessions, IEnumerable <Customer> otherCustomers)
        {
            foreach (Customer otherCustomer in otherCustomers)
            {
                foreach (CustomerSession otherCustomerSession in otherCustomer.Session)
                {
                    CustomerSession ocs = otherCustomerSession;                     // Avoid "access foreach variable in closure".

                    IEnumerable <SessionInfo> suspicious = thisCustomerSessions.Where(tcs => tcs.IsSuspicious(ocs));

                    foreach (SessionInfo tcs in suspicious)
                    {
                        this.fraudDetections.Add(Helper.CreateDetection(
                                                     "Customer IP",
                                                     this.customer,
                                                     otherCustomer,
                                                     "Customer IP",
                                                     null,
                                                     string.Format(
                                                         "{0} (this) and (id {2}) {1} (other)",
                                                         tcs.Ip,
                                                         otherCustomerSession.StartSession.ToString(
                                                             "d/MMM/yyyy H:mm:ss",
                                                             CultureInfo.InvariantCulture
                                                             ),
                                                         otherCustomerSession.Id
                                                         )
                                                     ));
                    } // for each session of this.customer
                }     // for each other customer's session
            }         // for each other customer
        }             // IpAgainstList
Example #18
0
        public IHttpActionResult InsertCustomerAddress(CustomerAddress data)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var session = HttpContext.Current.Request.Cookies.Get("sessionId");

            if (session == null)
            {
                return(BadRequest("请先登录!"));
            }

            int customerId = CustomerSession.GetCustomerIdFromSession(int.Parse(session.Value));

            if (customerId < 0)
            {
                return(BadRequest("请先登录!"));
            }

            if (_db.CustomerAddresses.Find(data.AddressIndex) == null)
            {
                CustomerAddress address = new CustomerAddress
                {
                    ReceiverName  = data.ReceiverName,
                    ReceivePhone  = data.ReceivePhone,
                    Province      = data.Province,
                    City          = data.City,
                    Block         = data.Block,
                    DetailAddress = data.DetailAddress,
                    ZipCode       = data.ZipCode,
                    CustomerId    = customerId,
                };


                _db.CustomerAddresses.Add(address);



                _db.SaveChanges();

                return(Ok("Insert Success"));
            }
            var updateCustomerAddress = _db.CustomerAddresses.FirstOrDefault(ca => ca.AddressIndex == data.AddressIndex);

            if (updateCustomerAddress == null)
            {
                return(BadRequest("Unable to Insert and Update"));
            }
            updateCustomerAddress.ReceiverName  = data.ReceiverName;
            updateCustomerAddress.ReceivePhone  = data.ReceivePhone;
            updateCustomerAddress.Province      = data.Province;
            updateCustomerAddress.City          = data.City;
            updateCustomerAddress.Block         = data.Block;
            updateCustomerAddress.DetailAddress = data.DetailAddress;
            updateCustomerAddress.ZipCode       = data.ZipCode;
            _db.SaveChanges();
            return(Ok("Update Success"));
        }
Example #19
0
 public static void RespondToCustomerActivity()
 {
     if (activityState == "energy save mode")
     {
         activityState = "Operating";
         customer      = new CustomerSession(DateTime.Now);
     }
 }
Example #20
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="customerSession"></param>
 /// <param name="configuration"></param>
 public GetBuddyDialog(CustomerSession customerSession, GetBuddyConfiguration configuration)
 {
     this.Configuration   = configuration;
     this.CustomerSession = customerSession;
     this.avCall          = this.CustomerSession.CustomerServiceChannel.ServiceChannelCall;
     speechGrammar        = new List <Grammar>();
     dtmfGrammar          = new List <Grammar>();
 }
Example #21
0
 public void Update(CustomerSession customerSession)
 {
     if (customerSession != null)
     {
         _repository.Entry <Sql.CustomerSession>(customerSession).State = System.Data.Entity.EntityState.Modified;
         //  _repository.SaveChanges();
     }
 }
Example #22
0
 public void Add(CustomerSession customer)
 {
     if (customer != null)
     {
         _repository.CustomerSessions.Add(customer);
         //   _repository.SaveChanges();
     }
 }
Example #23
0
        public override String ProcessCard(int OrderNumber, int CustomerID, Decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, String CardExtraCode, Address UseShippingAddress, String CAVV, String ECI, String XID, out String AVSResult, out String AuthorizationResult, out String AuthorizationCode, out String AuthorizationTransID, out String TransactionCommandOut, out String TransactionResponse)
        {
            String AVSAddr = String.Empty;
            String AVSZip  = String.Empty;

            AuthorizationCode     = String.Empty;
            AuthorizationResult   = String.Empty;
            AuthorizationTransID  = String.Empty;
            AVSResult             = String.Empty;
            TransactionCommandOut = String.Empty;
            TransactionResponse   = String.Empty;

            // Generate payment request
            Customer customer = new Customer(CustomerID, true);

            GatewayMoneybookers.IPaymentType paymentType;
            if (TransactionMode == TransactionModeEnum.auth)
            {
                paymentType = GatewayMoneybookers.PaymentType.Preauthorisation;
            }
            else
            {
                paymentType = GatewayMoneybookers.PaymentType.Debit;
            }

            string customerIpAddress = CommonLogic.CustomerIpAddress();

            if (customerIpAddress == "::1")
            {
                customerIpAddress = "127.0.0.1";
            }
            else if (customerIpAddress.Contains(":"))
            {
                throw new Exception("The Skrill (Moneybookers) payment gateway does not support IPv6.");
            }

            string cardType = UseBillingAddress.CardType;

            if (cardType.ToUpper() == "MASTERCARD")
            {
                cardType = "MASTER";
            }

            string          result;
            CustomerSession customerSession = new CustomerSession(CustomerID);

            if (customerSession.SessionUSInt("Moneybookers_3DSecure_OrderNumber") == OrderNumber)
            {
                result = ProcessOrderThrough3DSecure(OrderNumber, CustomerID, OrderTotal, TransactionMode, UseBillingAddress, CardExtraCode, ref AuthorizationResult, ref AuthorizationCode, ref AuthorizationTransID, ref TransactionCommandOut, ref TransactionResponse, customer, paymentType, customerIpAddress, cardType, customerSession);
            }
            else
            {
                result = ProcessOrderThroughGateway(OrderNumber, CustomerID, OrderTotal, TransactionMode, UseBillingAddress, CardExtraCode, ref AuthorizationResult, ref AuthorizationCode, ref AuthorizationTransID, ref TransactionCommandOut, ref TransactionResponse, customer, paymentType, customerIpAddress, cardType);
            }

            return(result);
        }
 public AddressSelection(
     CustomerSession customerSession,
     CartCookieManager cartCookieManager,
     ShippingInfoCookieManager shippingInfoCookieManager)
 {
     this.customerSession           = customerSession;
     this.cartCookieManager         = cartCookieManager;
     this.shippingInfoCookieManager = shippingInfoCookieManager;
 }
Example #25
0
        public ActionResult SagePayPiCreditCard(FormCollection collection)
        {
            var cardErrorSegments = collection["sagePayPiCardError"]
                                    .ParseAsDelimitedList('|');

            if (cardErrorSegments.FirstOrDefault() == "ERROR")
            {
                var error = cardErrorSegments
                            .Skip(1)
                            .FirstOrDefault();

                if (string.IsNullOrEmpty(error) || error.Contains("\"httpErrorCode\":401"))
                {
                    NoticeProvider.PushNotice(StringResourceProvider.GetString("sagepaypi.payment.addingdetailserror"), NoticeType.Failure);
                    return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
                }

                var sagePayPi    = new SagePayPi();
                var errorObject  = Newtonsoft.Json.Linq.JObject.Parse(error);
                var errorDetails = sagePayPi.GetResponseError(errorObject, "errors");
                var errorMessage = string.Format("{0} {1}", StringResourceProvider.GetString("sagepaypi.payment.carderrorprompt"), errorDetails);

                NoticeProvider.PushNotice(errorMessage, NoticeType.Failure);
                return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
            }

            var customer = HttpContext.GetCustomer();
            var session  = new CustomerSession(customer.CustomerID);

            session[AppLogic.SagePayPiMerchantSessionKey] = collection["sagePayPiMerchantSessionKey"];

            var updatedPersistedCheckoutContext = new PersistedCheckoutContextBuilder()
                                                  .From(PersistedCheckoutContextProvider.LoadCheckoutContext(customer))
                                                  .WithCreditCard(new CreditCardDetails(
                                                                      name: null,
                                                                      number: null,
                                                                      issueNumber: null,
                                                                      cardType: collection["sagePayPiCardType"],
                                                                      expirationDate: null,
                                                                      startDate: null,
                                                                      cvv: null))
                                                  .WithSagePayPi(new SagePayPiDetails(
                                                                     cardIdentifier: collection["sagePayPiCardIdentifier"],
                                                                     merchantSessionId: collection["sagePayPiMerchantSessionKey"],
                                                                     paymentMethod: Gateway.SagePayPiCreditCardKey, //This is the Sage Pay PI payment method, not ours
                                                                     threeDSecureApproved: false))
                                                  .WithoutOffsiteRequiredBillingAddressId()
                                                  .WithoutOffsiteRequiredShippingAddressId()
                                                  .Build();

            PersistedCheckoutContextProvider.SaveCheckoutContext(customer, updatedPersistedCheckoutContext);

            customer.UpdateCustomer(requestedPaymentMethod: AppLogic.ro_PMCreditCard);

            return(RedirectToAction(ActionNames.Index, ControllerNames.Checkout));
        }
Example #26
0
        /// <summary>
        /// Clears the target customer's session data
        /// </summary>
        protected void btnClearSession_OnClick(object sender, EventArgs e)
        {
            if (CustomerId == null)
            {
                return;
            }

            CustomerSession.StaticClear(CustomerId.Value);
            AlertMessageDisplay.PushAlertMessage("admin.customer.CustomerSessionCleared".StringResource(), AlertMessage.AlertType.Success);
        }
Example #27
0
        protected VoiceService(CustomerSession customerSession) : base(customerSession.AppFrontEnd.AppPlatform)
        {
            Debug.Assert(customerSession != null);
            if (customerSession == null)
            {
                throw new ArgumentNullException("customerSession");
            }

            this.CustomerSession = customerSession;
        }
Example #28
0
        }         // constructor

        public bool IsSuspicious(CustomerSession cs)
        {
            if (cs == null)
            {
                return(false);
            }

            return
                ((Ip == cs.Ip) &&
                 (Math.Abs((StartSessionTime - cs.StartSession).TotalDays) <= 30));
        }         // IsSuspicious
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            customerSession =
                (CustomerSession)context.HttpContext.RequestServices.GetService(typeof(CustomerSession));

            Customer customerFromSession = customerSession.GetLoggedInCustomer();

            if (customerFromSession == null)
            {
                context.Result = new RedirectToActionResult("Login", "Home", new { area = "Customer" });
            }
        }
        /// <summary>
        /// Gets shopping cart
        /// </summary>
        /// <param name="CustomerID">Customer identifier</param>
        /// <param name="ShoppingCartType">Shopping cart type</param>
        /// <returns>Cart</returns>
        public static ShoppingCart GetCustomerShoppingCart(int CustomerID, ShoppingCartTypeEnum ShoppingCartType)
        {
            CustomerSession customerSession = CustomerManager.GetCustomerSessionByCustomerID(CustomerID);

            if (customerSession == null)
            {
                return(new ShoppingCart());
            }
            Guid CustomerSessionGUID = customerSession.CustomerSessionGUID;

            return(GetShoppingCartByCustomerSessionGUID(ShoppingCartType, CustomerSessionGUID));
        }
Example #31
0
 /// <summary>
 /// Save customer session to data source
 /// </summary>
 /// <returns>Saved customer ssion</returns>
 private CustomerSession SaveSessionToDatabase()
 {
     Guid sessionId = Guid.NewGuid();
     while (CustomerManager.GetCustomerSessionByGUID(sessionId) != null)
         sessionId = Guid.NewGuid();
     CustomerSession session = new CustomerSession();
     int CustomerID = 0;
     if (this.User != null)
     {
         CustomerID = this.User.CustomerID;
     }
     session.CustomerSessionGUID = sessionId;
     session.CustomerID = CustomerID;
     session.LastAccessed = DateTime.UtcNow;
     session.IsExpired = false;
     session = CustomerManager.SaveCustomerSession(session.CustomerSessionGUID, session.CustomerID, session.LastAccessed, session.IsExpired);
     return session;
 }
        protected string GetCustomerInfo(CustomerSession customerSession)
        {
            string customerInfo = string.Empty;
            Customer customer = customerSession.Customer;

            if (customer != null)
            {
                if (customer.IsGuest)
                {
                    customerInfo = string.Format("<a href=\"CustomerDetails.aspx?CustomerID={0}\">{1}</a>", customer.CustomerId, GetLocaleResourceString("Admin.CustomerShoppingCart.CustomerColumn.Guest"));
                }
                else
                {
                    customerInfo = string.Format("<a href=\"CustomerDetails.aspx?CustomerID={0}\">{1}</a>", customer.CustomerId, Server.HtmlEncode(customer.Email));
                }
            }
            else
            {
                customerInfo = GetLocaleResourceString("Admin.CustomerShoppingCart.CustomerColumn.Guest");
            }
            return customerInfo;
        }
        /// <summary>
        /// Updates the customer session
        /// </summary>
        /// <param name="customerSession">Customer session</param>
        protected void UpdateCustomerSession(CustomerSession customerSession)
        {
            if (customerSession == null)
                throw new ArgumentNullException("customerSession");

            if (!_context.IsAttached(customerSession))
                _context.CustomerSessions.Attach(customerSession);

            _context.SaveChanges();
        }
        /// <summary>
        /// Inserts a customer session
        /// </summary>
        /// <param name="customerSession">Customer session</param>
        protected void InsertCustomerSession(CustomerSession customerSession)
        {
            if (customerSession == null)
                throw new ArgumentNullException("customerSession");

            _context.CustomerSessions.AddObject(customerSession);
            _context.SaveChanges();
        }
 /// <summary>
 /// Saves a customer session to the data storage if it exists or creates new one
 /// </summary>
 /// <param name="customerSessionGuid">Customer session GUID</param>
 /// <param name="customerId">Customer identifier</param>
 /// <param name="lastAccessed">The last accessed date and time</param>
 /// <param name="isExpired">A value indicating whether the customer session is expired</param>
 /// <returns>Customer session</returns>
 public CustomerSession SaveCustomerSession(Guid customerSessionGuid,
     int customerId, DateTime lastAccessed, bool isExpired)
 {
     var customerSession = GetCustomerSessionByGuid(customerSessionGuid);
     if (customerSession == null)
     {
         customerSession = new CustomerSession()
         {
             CustomerSessionGuid = customerSessionGuid,
             CustomerId = customerId,
             LastAccessed = lastAccessed,
             IsExpired = isExpired
         };
         InsertCustomerSession(customerSession);
     }
     else
     {
         customerSession.CustomerSessionGuid = customerSessionGuid;
         customerSession.CustomerId = customerId;
         customerSession.LastAccessed = lastAccessed;
         customerSession.IsExpired = isExpired;
         UpdateCustomerSession(customerSession);
     }
     return customerSession;
 }
 /// <summary>
 /// Save customer session to data source
 /// </summary>
 /// <returns>Saved customer ssion</returns>
 private CustomerSession SaveSessionToDatabase()
 {
     var sessionId = Guid.NewGuid();
     while (IoC.Resolve<ICustomerService>().GetCustomerSessionByGuid(sessionId) != null)
         sessionId = Guid.NewGuid();
     var session = new CustomerSession();
     int customerId = 0;
     if (this.User != null)
     {
         customerId = this.User.CustomerId;
     }
     session.CustomerSessionGuid = sessionId;
     session.CustomerId = customerId;
     session.LastAccessed = DateTime.UtcNow;
     session.IsExpired = false;
     session = IoC.Resolve<ICustomerService>().SaveCustomerSession(session.CustomerSessionGuid, session.CustomerId, session.LastAccessed, session.IsExpired);
     return session;
 }
 protected string GetLastAccessInfo(CustomerSession customerSession)
 {
     string info = string.Format(GetLocaleResourceString("Admin.CustomerShoppingCart.CustomerColumn.LastAccess"),
         DateTimeHelper.ConvertToUserTime(customerSession.LastAccessed, DateTimeKind.Utc));
     return info;
 }