Example #1
0
        public void ReadFile(string path, IAddressInfo addressInfo)
        {
            if (!File.Exists(path))
            {
                return;
            }

            if (AddressFileLineCount(path) == 0)
            {
                return;
            }

            StreamReader addressBook = new StreamReader(path);
            var          file        = File.ReadAllText(path);

            addressInfo.Address = addressBook.ReadLine();
            addressInfo.Name    = addressBook.ReadLine();
            addressInfo.Number  = addressBook.ReadLine();
            var AddressInfoText = new List <string> {
                addressInfo.Address, addressInfo.Name, addressInfo.Number
            };

            addressBook.Close();

            ReplaceTextInFile_(path, file, AddressInfoText);
        }
Example #2
0
 protected override void LoadControlState(object savedState)
 {
     if (savedState != null)
     {
         Pair p = savedState as Pair;
         if (p != null)
         {
             base.LoadControlState(p.First);
             AddressState state = p.Second as AddressState;
             if (state != null)
             {
                 _address = state.Address;
                 _showUserSaved = state.ShowUserSaved;
                 _showDescription = state.ShowDescription;
                 _hasChanged = state.HasChanged;
                 Settings = state.Settings;
             }
         }
         else
         {
             if (savedState is AddressState)
             {
                 AddressState state = (AddressState) savedState;
                 _address = state.Address;
                 _showUserSaved = state.ShowUserSaved;
                 _showDescription = state.ShowDescription;
                 _hasChanged = state.HasChanged;
                 Settings = state.Settings;
             }
             else
                 base.LoadControlState(savedState);
         }
     }
 }
Example #3
0
        private void grdAddresses_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            IAddressInfo addressInfo = (IAddressInfo)e.Item.DataItem;

            Image imgPrimary = (Image)e.Item.FindControl("imgPrimary");

            if (imgPrimary != null)
            {
                if (addressInfo.PrimaryAddress)
                {
                    imgPrimary.Visible = true;
                }
                else
                {
                    imgPrimary.Visible = false;
                }
            }

            HyperLink lnkEdit = (HyperLink)e.Item.FindControl("lnkEdit");

            if (lnkEdit != null)
            {
                if (addressInfo.AddressID == 0)
                {
                    //This is the registration address, so the profile editor should be used to modify this address
                    string[] urlparams = { "UserId=" + UserId };
                    lnkEdit.NavigateUrl = Globals.NavigateURL(PortalSettings.UserTabId, "Profile", urlparams);
                }
                else
                {
                    _addressNav.AddressID = addressInfo.AddressID;
                    lnkEdit.NavigateUrl   = _addressNav.GetNavigationUrl();
                }
            }
        }
Example #4
0
        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    IAddressInfo address = addressEdit.Address;

                    address.AddressID     = _addressID;
                    address.PortalID      = PortalId;
                    address.UserID        = UserId;
                    address.CreatedByUser = UserId.ToString();
                    address.CreatedDate   = DateTime.Now;

                    AddressController controller = new AddressController();

                    if (address.AddressID > 0)
                    {
                        controller.UpdateAddress(address);
                    }
                    else
                    {
                        controller.AddAddress(address);
                    }

                    InvokeEditComplete();
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
Example #5
0
 public AddressInfoVm(IAddressInfo addyInfo)
 {
     this.ContactInfoId = addyInfo.ContactInfoId;
     this.IdentityId    = addyInfo.IdentityId;
     this.Preferred     = addyInfo.Preferred;
     this.Verified      = addyInfo.Verified;
     this.Changed       = false;
 }
Example #6
0
        public void WriteFile(string path, IAddressInfo addressInfo)
        {
            StreamWriter addressBook = new StreamWriter(path, true);

            addressBook.WriteLine(addressInfo.Address);
            addressBook.WriteLine(addressInfo.Name);
            addressBook.WriteLine(addressInfo.Number);
            addressBook.Close();
        }
Example #7
0
        public IShippingInfo CalculateShippingFee <T>(int portalId, IAddressInfo billingAddress, IAddressInfo shippingAddress, IEnumerable <T> cartItems) where T : ICartItemInfo
        {
            decimal cartWeight = 0;

            foreach (T itemInfo in cartItems)
            {
                cartWeight += (itemInfo.ProductWeight * itemInfo.Quantity);
            }
            return(CBO.FillObject <ShippingInfo>(DataProvider.Instance().ExecuteReader("Store_ShippingRates_GetShippingRates", portalId, cartWeight)));
        }
Example #8
0
        public string CheckOut(ICard card, IAddressInfo addressInfo)
        {
            bool result = _paymentService.Charge(_cartService.Total(), card);

            if (result)
            {
                _shipmentService.Ship(addressInfo, _cartService.Items());
                return("charged");
            }
            return("not charged");
        }
Example #9
0
 public AddressTokenReplace(string tokenObjectName, IAddressInfo address)
 {
     if (string.IsNullOrEmpty(tokenObjectName) == false && address != null)
     {
         PropertySource[tokenObjectName.ToLower()] = address;
         CurrentAccessLevel = Scope.NoSettings;
     }
     else
     {
         throw new Exception("TokenObjectName and Address parameters cannot be null!");
     }
 }
Example #10
0
 public void Add(string name, IAddressInfo value)
 {
     AddressList.Add(name, new AddressListModelItem()
     {
         Name  = name,
         Value = value,
     });
     if (PropertyChanged != null)
     {
         PropertyChanged.Invoke(this, new PropertyChangedEventArgs("AddressList"));
     }
 }
Example #11
0
        private List <SqlParameter> CreateAddressInfoParams(IAddressInfo info)
        {
            var paramz = new List <SqlParameter>();

            paramz.Add(new SqlParameter("contactInfoId", info.ContactInfoId));
            paramz.Add(new SqlParameter("identityId", info.IdentityId));
            paramz.Add(new SqlParameter("modifiedByIdentityId", info.ModifiedByIdentityId));
            paramz.Add(new SqlParameter("contactInfoLocationType", info.ContactInfoLocationType));
            paramz.Add(new SqlParameter("preferred", info.Preferred));
            paramz.Add(new SqlParameter("verified", info.Verified));
            paramz.Add(new SqlParameter("archived", info.Archived));
            paramz.Add(new SqlParameter("note", info.Note.ToSqlString()));

            return(paramz);
        }
Example #12
0
        private T CreateAddressInfo <T>(IAddressInfo addyinfo)
            where T : IAddressInfo, new()
        {
            var addy = new T();

            addy.ContactInfoId           = addyinfo.ContactInfoId;
            addy.IdentityId              = addyinfo.IdentityId;
            addy.ContactInfoType         = addyinfo.ContactInfoType;
            addy.ContactInfoLocationType = addyinfo.ContactInfoLocationType;
            addy.ModifiedByIdentityId    = addyinfo.ModifiedByIdentityId;
            addy.Preferred = addyinfo.Preferred;
            addy.Verified  = addyinfo.Verified;
            addy.Archived  = addyinfo.Archived;

            return(addy);
        }
Example #13
0
        public void UpdateRegistrationAddress(int portalID, IAddressInfo address)
        {
            UserController controller = new UserController();
            UserInfo       userInfo   = controller.GetUser(portalID, address.UserID);

            userInfo.FirstName          = address.FirstName;
            userInfo.LastName           = address.LastName;
            userInfo.Profile.Street     = address.Address1;
            userInfo.Profile.Unit       = address.Address2;
            userInfo.Profile.City       = address.City;
            userInfo.Profile.Region     = address.RegionCode;
            userInfo.Profile.Country    = address.CountryCode;
            userInfo.Profile.PostalCode = address.PostalCode;
            userInfo.Email             = address.Email;
            userInfo.Profile.Telephone = address.Phone1;
            userInfo.Profile.Cell      = address.Phone2;

            UserController.UpdateUser(portalID, userInfo);
        }
Example #14
0
        private string FormatAddress(IAddressInfo address, Boolean showEmail)
        {
            string formatedAddress = string.Empty;

            if (address != null)
            {
                formatedAddress = address.Format(Localization.GetString("CustomerAddressTemplate", LocalResourceFile)).Replace("\r\n", "<br />");

                if (showEmail)
                {
                    string userEmail = string.Empty;

                    if (address.UserID != UserInfo.UserID)
                    {
                        if (address.UserID == StoreSettings.ImpersonatedUserID)
                        {
                            userEmail = address.Email;
                        }
                        else
                        {
                            UserController controller = new UserController();
                            UserInfo       userInfo   = controller.GetUser(PortalId, address.UserID);

                            if (userInfo != null)
                            {
                                userEmail = userInfo.Email;
                            }
                        }
                    }
                    else
                    {
                        userEmail = UserInfo.Email;
                    }

                    if (userEmail != string.Empty)
                    {
                        formatedAddress += "<br />" + string.Format("<a href=\"mailto:{0}\">{0}</a>", userEmail);
                    }
                }
            }

            return(formatedAddress);
        }
Example #15
0
 public void UpdateAddress(IAddressInfo address)
 {
     DataProvider.Instance().ExecuteNonQuery("Store_Addresses_UpdateAddress",
                                             address.AddressID,
                                             address.UserID,
                                             address.Description,
                                             DataHelper.GetNull(address.FirstName),
                                             address.LastName,
                                             DataHelper.GetNull(address.Address1),
                                             DataHelper.GetNull(address.Address2),
                                             DataHelper.GetNull(address.City),
                                             DataHelper.GetNull(address.RegionCode),
                                             DataHelper.GetNull(address.CountryCode),
                                             DataHelper.GetNull(address.PostalCode),
                                             DataHelper.GetNull(address.Email),
                                             DataHelper.GetNull(address.Phone1),
                                             DataHelper.GetNull(address.Phone2),
                                             address.PrimaryAddress,
                                             address.UserSaved);
 }
Example #16
0
 public int AddAddress(IAddressInfo address)
 {
     return(DataProvider.Instance().ExecuteScalar <int>("Store_Addresses_AddAddress",
                                                        address.UserID,
                                                        address.PortalID,
                                                        address.Description,
                                                        DataHelper.GetNull(address.FirstName),
                                                        DataHelper.GetNull(address.LastName),
                                                        DataHelper.GetNull(address.Address1),
                                                        DataHelper.GetNull(address.Address2),
                                                        DataHelper.GetNull(address.City),
                                                        DataHelper.GetNull(address.RegionCode),
                                                        DataHelper.GetNull(address.CountryCode),
                                                        DataHelper.GetNull(address.PostalCode),
                                                        DataHelper.GetNull(address.Email),
                                                        DataHelper.GetNull(address.Phone1),
                                                        DataHelper.GetNull(address.Phone2),
                                                        address.PrimaryAddress,
                                                        address.UserSaved,
                                                        UserController.Instance.GetCurrentUserInfo().UserID));
 }
        private void LoadShipAddress(int addressId)
        {
            IAddressInfo address = null;

            if (addressId >= 0)
            {
                address = LoadAddress(addressId);
            }

            if (address != null)
            {
                // Get user account email if user is connected and email address is empty
                if (UserId != Null.NullInteger && string.IsNullOrEmpty(address.Email))
                {
                    address.Email = UserInfo.Email;
                }
                ShippingAddress = address;
            }
            else
            {
                ShippingAddress = new AddressInfo();
            }
        }
Example #18
0
        private void ShowOrderDetails(int orderID)
        {
            // Get Order
            OrderInfo order = _orderController.GetOrder(PortalId, orderID);

            // If Order exist and current user is authorized to see it
            if (order != null && (order.CustomerID == UserId || _canManageOrders))
            {
                pnlOrderDetails.Visible = true;
                // Order Header
                lblOrderNumber.Text = order.OrderID.ToString();
                lblOrderDate.Text   = order.OrderDate.ToString(_orderDateFormat);
                // Order Status
                if (_orderStatusList == null)
                {
                    _orderStatusList = _orderController.GetOrderStatuses();
                }
                string orderStatusText = "";
                foreach (OrderStatus orderStatus in _orderStatusList)
                {
                    if (orderStatus.OrderStatusID == order.OrderStatusID)
                    {
                        if (order.OrderStatusID > 1)
                        {
                            orderStatusText = orderStatus.OrderStatusText + " - " + order.ShipDate.ToString(_orderDateFormat);
                        }
                        else
                        {
                            orderStatusText = orderStatus.OrderStatusText;
                        }
                        break;
                    }
                }
                lblOrderStatus.Text = orderStatusText;
                //Cancel button
                btnCancel.Visible = false;
                if (StoreSettings.AuthorizeCancel && _canManageOrders == false)
                {
                    if (order.OrderStatusID == (int)OrderInfo.OrderStatusList.AwaitingPayment ||
                        order.OrderStatusID == (int)OrderInfo.OrderStatusList.AwaitingStock ||
                        order.OrderStatusID == (int)OrderInfo.OrderStatusList.Paid)
                    {
                        btnCancel.CommandArgument = order.OrderID.ToString();
                        btnCancel.Click          += btnCancel_Click;
                        btnCancel.Visible         = true;
                    }
                }
                //Pay Now button
                btnPayNow.Visible = false;
                if (StoreSettings.GatewayName != "EmailProvider")
                {
                    btnPayNow.Click += btnPayNow_Click;
                    if (order.OrderStatusID == (int)OrderInfo.OrderStatusList.AwaitingPayment)
                    {
                        btnPayNow.CommandArgument = order.OrderID.ToString();
                        btnPayNow.Click          += btnPayNow_Click;
                        btnPayNow.Visible         = true;
                    }
                }
                // Billing Address
                IAddressInfo billingAddress = GetAddress(order.BillingAddressID, order.CustomerID);
                if (billingAddress != null)
                {
                    lblBillTo.Text = FormatAddress(billingAddress, _canManageOrders);
                }
                else
                {
                    lblBillTo.Text = string.Format(Localization.GetString("UserDeleted", LocalResourceFile), order.CustomerID);
                }
                // ShippingAddress
                if (order.ShippingAddressID != order.BillingAddressID)
                {
                    if (order.ShippingAddressID != Null.NullInteger)
                    {
                        IAddressInfo shippingAddress = GetAddress(order.ShippingAddressID, order.CustomerID);
                        if (shippingAddress != null)
                        {
                            lblShipTo.Text = FormatAddress(shippingAddress, _canManageOrders);
                        }
                        else
                        {
                            lblShipTo.Text = Localization.GetString("ShipToAddressNotAvailable", LocalResourceFile);
                        }
                    }
                    else
                    {
                        lblShipTo.Text = Localization.GetString("NoShipping", LocalResourceFile);
                    }
                }
                else
                {
                    lblShipTo.Text = Localization.GetString("SameAsBilling", LocalResourceFile);
                }
                // Get Order Details
                List <OrderDetailInfo> orderDetails = _orderController.GetOrderDetails(orderID);
                // If Order detail was found, display it
                if (orderDetails != null)
                {
                    plhForm.Visible = true;

                    // Bind Items to GridControl
                    grdOrderDetails.DataSource = orderDetails;
                    grdOrderDetails.DataBind();
                }
                else
                {
                    // otherwise display an error message
                    lblError.Text          = Localization.GetString("DetailsNotFound", LocalResourceFile);
                    pnlOrdersError.Visible = true;
                    plhForm.Visible        = false;
                }

                // *** Footer ***

                // Total
                if (order.Discount != Null.NullDecimal || order.ShippingCost != 0 || order.TaxTotal != 0)
                {
                    lblTotal.Text = order.OrderTotal.ToString("C", _localFormat);
                }
                else
                {
                    trTotal.Visible = false;
                }
                // Discount
                if (order.Discount != Null.NullDecimal)
                {
                    lblDiscount.Text = order.Discount.ToString("C", _localFormat);
                }
                else
                {
                    trDiscount.Visible = false;
                }
                // Shipping Cost
                if (order.ShippingCost > 0)
                {
                    lblPostage.Text = order.ShippingCost.ToString("C", _localFormat);
                }
                else
                {
                    trShipping.Visible = false;
                }
                // Tax
                if (order.TaxTotal > 0)
                {
                    lblTax.Text = order.TaxTotal.ToString("C", _localFormat);
                }
                else
                {
                    trTax.Visible = false;
                }
                // Grand Total
                lblTotalIncPostage.Text = order.GrandTotal.ToString("C", _localFormat);

                // Status Management
                if (_canManageOrders)
                {
                    OrderStatusManagement.Visible = true;

                    // Bind Order status list...
                    ddlOrderStatus.DataSource     = _orderStatusList;
                    ddlOrderStatus.DataTextField  = "OrderStatusText";
                    ddlOrderStatus.DataValueField = "OrderStatusID";
                    ddlOrderStatus.DataBind();

                    // Select current status
                    ListItem currentStatus = ddlOrderStatus.Items.FindByValue(order.OrderStatusID.ToString());
                    if (currentStatus != null)
                    {
                        currentStatus.Selected = true;
                    }
                }
                else
                {
                    OrderStatusManagement.Visible = false;
                }
            }
            else
            {
                plhForm.Visible = false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get default address description
            _addressDefaultDescription = Localization.GetString("AddressDefaultDescription", LocalResourceFile);

            if (!IsPostBack)
            {
                // Hide shipping address block if no delivery is defined
                fsShippingAddress.Visible = !NoDelivery;

                bool         addressChanged = false;
                IAddressInfo billingAddress = BillingAddress;
                if (billingAddress != null)
                {
                    int          billingAddressID  = billingAddress.AddressID;
                    IAddressInfo shippingAddress   = ShippingAddress;
                    int          shippingAddressID = shippingAddress.AddressID;

                    // If the user is logged
                    if (IsLogged)
                    {
                        //Get the user's addresses
                        List <AddressInfo> addresses = _controller.GetAddresses <AddressInfo>(PortalId, UserId, _addressDefaultDescription);

                        // Bind addresses lists
                        BindBillingAddressList(addresses);

                        // If billing address is not set
                        if (billingAddressID == Null.NullInteger)
                        {
                            // Search for the primary address
                            bool primaryAddressFound = false;
                            foreach (AddressInfo address in addresses)
                            {
                                if (address.PrimaryAddress)
                                {
                                    billingAddress      = address;
                                    primaryAddressFound = true;
                                    break;
                                }
                            }
                            // Define selected addresses
                            if (primaryAddressFound)
                            {
                                billingAddressID  = billingAddress.AddressID;
                                BillingAddress    = billingAddress;
                                shippingAddressID = billingAddressID;
                                ShippingAddress   = billingAddress;
                                addressChanged    = true;
                            }
                        }
                    }
                    else
                    {
                        rowListBillAddress.Visible = false;
                    }

                    // Update billing interface
                    UpdateBillingInterface();

                    // Define shipping mode then update shipping interface
                    if (shippingAddressID != Null.NullInteger && shippingAddressID != billingAddressID)
                    {
                        Shipping            = ShippingMode.Other;
                        radShipping.Checked = true;
                        DisplayShippingAddressSelection(true);
                    }
                    else
                    {
                        Shipping           = ShippingMode.SameAsBilling;
                        radBilling.Checked = true;
                        DisplayShippingAddressSelection(false);
                    }
                }
                // Callback Checkout control to save order with new addresses
                if (addressChanged)
                {
                    SendBillingAddressChangedEvent();
                }
            }
        }
        public TransactionResult ProcessTransaction(IAddressInfo shipping, IAddressInfo billing, 
			OrderInfo orderInfo, object transDetails)
        {
            TransactionResult result = new TransactionResult();

            // Check data before performing transaction
            AuthNetSettings settings = new AuthNetSettings(_gatewaySettings);
            if ((settings == null) || (!settings.IsValid()))
            {
                result.Succeeded = false;
                result.Message = "ErrorPaymentOption";
                return result;
            }

            if (billing == null)
            {
                result.Succeeded = false;
                result.Message = "ErrorBillingAddress";
                return result;
            }

            TransactionDetails trans = new TransactionDetails(transDetails as string);
            if ((trans == null) || (!trans.IsValid()))
            {
                result.Succeeded = false;
                result.Message = "ErrorCardInformation";
                return result;
            }

            // Gather transaction information
            string url = settings.GatewayURL;
            string firstName = string.Empty;
            string lastName = trans.NameOnCard;
            if (lastName.IndexOf(" ") >= 0)
            {
                firstName = lastName.Substring(0, lastName.IndexOf(" ")).Trim();
                lastName = lastName.Substring(lastName.LastIndexOf(" ")).Trim();
            }

            string address = billing.Address1 + " " + billing.Address2;
            address = address.Trim();

            NameValueCollection NVCol = new NameValueCollection();

            //NVCol.Add("x_version",				settings.Version);
            NVCol.Add("x_delim_data",			"True");
            NVCol.Add("x_relay_response",       "False");
            NVCol.Add("x_login",				settings.Username);
            NVCol.Add("x_tran_key",				settings.Password);
            NVCol.Add("x_test_request",			settings.IsTest.ToString());
            NVCol.Add("x_delim_char",			"~");
            NVCol.Add("x_encap_char",			"'");

            NVCol.Add("x_first_name",			firstName);
            NVCol.Add("x_last_name",			lastName);
            NVCol.Add("x_company",				"");
            NVCol.Add("x_address",				address);
            NVCol.Add("x_city",					billing.City);
            NVCol.Add("x_state",				billing.RegionCode);
            NVCol.Add("x_zip",					billing.PostalCode);
            NVCol.Add("x_country",				billing.CountryCode);
            NVCol.Add("x_phone",				billing.Phone1);
            NVCol.Add("x_invoice_num",			orderInfo.OrderID.ToString());

            NVCol.Add("x_amount",				orderInfo.OrderTotal.ToString());
            NVCol.Add("x_method",				"CC");
            NVCol.Add("x_card_num",				trans.CardNumber);
            NVCol.Add("x_card_code",			trans.VerificationCode.ToString());
            NVCol.Add("x_exp_date",				trans.ExpirationMonth.ToString() + "/" + trans.ExpirationYear.ToString());
            NVCol.Add("x_recurring_billing",	"NO");
            NVCol.Add("x_type",					settings.Capture.ToString());

            // Perform transaction
            try
            {
                Encoding enc = Encoding.GetEncoding(1252);
                StreamReader loResponseStream = new StreamReader(PostEx(url, NVCol).GetResponseStream(), enc);

                string lcHtml = loResponseStream.ReadToEnd();
                loResponseStream.Close();

                string[] resultArray = Microsoft.VisualBasic.Strings.Split(lcHtml.TrimStart("'".ToCharArray()), "'~'", -1, Microsoft.VisualBasic.CompareMethod.Binary);

                //TODO: What transaction details to return???
                result.Succeeded = (resultArray[0] == "1");
                result.Message = resultArray[3];
            }
            catch (Exception ex)
            {
                //Return error
                string[] resultArray = Microsoft.VisualBasic.Strings.Split("2|0|0|No Connection Available", "|", -1, Microsoft.VisualBasic.CompareMethod.Binary);

                //TODO: What transaction details to return???
                result.Succeeded = false;
                result.Message = ex.Message;
                //result.Message = resultArray[3];
            }

            return result;
        }
Example #21
0
        protected virtual void GenerateOrderConfirmation()
        {
            OrderInfo order = CheckoutControl.Order;

            if (order != null)
            {
                // Store admin
                string adminDetailTemplate = string.Empty;
                bool   adminDetail         = false;
                // Customer
                string customerDetailTemplate = string.Empty;
                bool   customerDetail         = false;

                IAddressInfo billingAddress  = CheckoutControl.BillingAddress;
                IAddressInfo shippingAddress = CheckoutControl.ShippingAddress;

                // Get Customer Email
                string customerEmail = billingAddress.Email;

                // Get Admin Email
                string adminEmail = StoreSettings.DefaultEmailAddress;

                // Get Store Currency Symbol
                if (!string.IsNullOrEmpty(StoreSettings.CurrencySymbol))
                {
                    order.CurrencySymbol = StoreSettings.CurrencySymbol;
                }

                // Get Order Date Format
                string orderDateFormat = Localization.GetString("OrderDateFormat", LocalResourceFile);
                if (string.IsNullOrEmpty(orderDateFormat) == false)
                {
                    order.DateFormat = orderDateFormat;
                }

                // Customer Order Email Template
                string customerSubjectEmail    = Localization.GetString("CustomerOrderEmailSubject", LocalResourceFile);
                string customerBodyEmail       = Localization.GetString("CustomerOrderEmailBody", LocalResourceFile);
                string customerAddressTemplate = Localization.GetString("CustomerAddressTemplate", LocalResourceFile);

                // Extract Detail Order from Customer EmailTemplate
                Match regCustomerMatch = RegDetails.Match(customerBodyEmail);
                if (regCustomerMatch.Success)
                {
                    customerDetail         = true;
                    customerDetailTemplate = regCustomerMatch.Groups[1].ToString();
                    customerDetailTemplate = RegStripStartNewLine.Replace(customerDetailTemplate, string.Empty);
                    customerDetailTemplate = RegStripEndNewLine.Replace(customerDetailTemplate, string.Empty);
                }

                // Extract or remove IFDISCOUNT token
                Match regCustomerDiscountMatch = RegDiscount.Match(customerBodyEmail);
                if (regCustomerDiscountMatch.Success)
                {
                    if (order.CouponID != Null.NullInteger && order.Discount != Null.NullDecimal)
                    {
                        // Replace IFDISCOUNT token by his content
                        string discountTemplate = regCustomerDiscountMatch.Groups[1].ToString();
                        discountTemplate  = RegStripStartNewLine.Replace(discountTemplate, string.Empty);
                        discountTemplate  = RegStripEndNewLine.Replace(discountTemplate, string.Empty);
                        customerBodyEmail = RegDiscount.Replace(customerBodyEmail, discountTemplate);
                    }
                    else // Remove IFDISCOUNT token
                    {
                        customerBodyEmail = RegDiscount.Replace(customerBodyEmail, string.Empty);
                    }
                }

                // Extract or remove IFSHIPPINGCOST token
                Match regShippingCostMatch = RegShippingCost.Match(customerBodyEmail);
                if (regShippingCostMatch.Success)
                {
                    if (order.ShippingCost > 0)
                    {
                        // Replace IFSHIPPINGCOST token by his content
                        string shippingCostTemplate = regShippingCostMatch.Groups[1].ToString();
                        shippingCostTemplate = RegStripStartNewLine.Replace(shippingCostTemplate, string.Empty);
                        shippingCostTemplate = RegStripEndNewLine.Replace(shippingCostTemplate, string.Empty);
                        customerBodyEmail    = RegShippingCost.Replace(customerBodyEmail, shippingCostTemplate);
                    }
                    else // Remove IFSHIPPINGCOST token
                    {
                        customerBodyEmail = RegShippingCost.Replace(customerBodyEmail, string.Empty);
                    }
                }

                // Replace BillingAddress token (if present) by the the formated Billing Address
                if (customerBodyEmail.IndexOf("[BillingAddress]", StringComparison.InvariantCultureIgnoreCase) != Null.NullInteger)
                {
                    customerBodyEmail = customerBodyEmail.Replace("[BillingAddress]", billingAddress.Format(customerAddressTemplate));
                }

                // Extract or remove Shipping Address Template from Customer Email Template
                if (shippingAddress.AddressID != Null.NullInteger)
                {
                    // Remove Pickup Template
                    customerBodyEmail = RegPickup.Replace(customerBodyEmail, string.Empty);
                    // Replace Shipping Address Template
                    Match regShippingMatch = RegShipping.Match(customerBodyEmail);
                    if (regShippingMatch.Success)
                    {
                        string shippingTemplate = regShippingMatch.Groups[1].ToString();
                        shippingTemplate  = RegStripStartNewLine.Replace(shippingTemplate, string.Empty);
                        shippingTemplate  = RegStripEndNewLine.Replace(shippingTemplate, string.Empty);
                        customerBodyEmail = RegShipping.Replace(customerBodyEmail, shippingTemplate);
                    }

                    // Replace ShippingAddress token (if present) by the the formated Shipping Address
                    if (customerBodyEmail.IndexOf("[ShippingAddress]", StringComparison.InvariantCultureIgnoreCase) != Null.NullInteger)
                    {
                        customerBodyEmail = customerBodyEmail.Replace("[ShippingAddress]", shippingAddress.Format(customerAddressTemplate));
                    }
                }
                else
                {
                    // Remove Shipping Address Template
                    customerBodyEmail = RegShipping.Replace(customerBodyEmail, string.Empty);
                    // Replace Pickup Template
                    Match regPickupMatch = RegPickup.Match(customerBodyEmail);
                    if (regPickupMatch.Success)
                    {
                        string pickupTemplate = regPickupMatch.Groups[1].ToString();
                        pickupTemplate    = RegStripStartNewLine.Replace(pickupTemplate, string.Empty);
                        pickupTemplate    = RegStripEndNewLine.Replace(pickupTemplate, string.Empty);
                        customerBodyEmail = RegPickup.Replace(customerBodyEmail, pickupTemplate);
                    }
                }

                // Admin Order Email Template
                string adminSubjectEmail = Localization.GetString("AdminOrderEmailSubject", LocalResourceFile);
                string adminBodyEmail    = Localization.GetString("AdminOrderEmailBody", LocalResourceFile);

                // Extract Detail Order from Admin EmailTemplate
                Match regAdminMatch = RegDetails.Match(adminBodyEmail);
                if (regAdminMatch.Success)
                {
                    adminDetail         = true;
                    adminDetailTemplate = regAdminMatch.Groups[1].ToString();
                    adminDetailTemplate = RegStripStartNewLine.Replace(adminDetailTemplate, string.Empty);
                    adminDetailTemplate = RegStripEndNewLine.Replace(adminDetailTemplate, string.Empty);
                }

                // Extract or remove IFDISCOUNT token
                Match regAdminDiscountMatch = RegDiscount.Match(adminBodyEmail);
                if (regAdminDiscountMatch.Success)
                {
                    if (order.CouponID != Null.NullInteger && order.Discount != Null.NullDecimal)
                    {
                        // Replace IFDISCOUNT token by his content
                        string discountTemplate = regAdminDiscountMatch.Groups[1].ToString();
                        discountTemplate = RegStripStartNewLine.Replace(discountTemplate, string.Empty);
                        discountTemplate = RegStripEndNewLine.Replace(discountTemplate, string.Empty);
                        adminBodyEmail   = RegDiscount.Replace(adminBodyEmail, discountTemplate);
                    }
                    else // Remove IFDISCOUNT token
                    {
                        adminBodyEmail = RegDiscount.Replace(adminBodyEmail, string.Empty);
                    }
                }

                // Extract or remove IFSHIPPINGCOST token
                Match regAdminShippingCostMatch = RegShippingCost.Match(adminBodyEmail);
                if (regAdminShippingCostMatch.Success)
                {
                    if (order.ShippingCost > 0)
                    {
                        // Replace IFSHIPPINGCOST token by his content
                        string shippingCostTemplate = regAdminShippingCostMatch.Groups[1].ToString();
                        shippingCostTemplate = RegStripStartNewLine.Replace(shippingCostTemplate, string.Empty);
                        shippingCostTemplate = RegStripEndNewLine.Replace(shippingCostTemplate, string.Empty);
                        adminBodyEmail       = RegShippingCost.Replace(adminBodyEmail, shippingCostTemplate);
                    }
                    else // Remove IFSHIPPINGCOST token
                    {
                        adminBodyEmail = RegShippingCost.Replace(adminBodyEmail, string.Empty);
                    }
                }

                // Replace BillingAddress token (if present) by the the formated Billing Address
                if (adminBodyEmail.IndexOf("[BillingAddress]", StringComparison.InvariantCultureIgnoreCase) != Null.NullInteger)
                {
                    adminBodyEmail = adminBodyEmail.Replace("[BillingAddress]", billingAddress.Format(customerAddressTemplate));
                }

                // Extract or remove Shipping Address Template from Admin Email Template
                if (shippingAddress.AddressID != Null.NullInteger)
                {
                    // Remove Pickup Template
                    adminBodyEmail = RegPickup.Replace(adminBodyEmail, string.Empty);
                    // Replace Shipping Address Template
                    Match regShippingMatch = RegShipping.Match(adminBodyEmail);
                    if (regShippingMatch.Success)
                    {
                        string shippingTemplate = regShippingMatch.Groups[1].ToString();
                        shippingTemplate = RegStripStartNewLine.Replace(shippingTemplate, string.Empty);
                        shippingTemplate = RegStripEndNewLine.Replace(shippingTemplate, string.Empty);
                        adminBodyEmail   = RegShipping.Replace(adminBodyEmail, shippingTemplate);
                    }

                    // Replace ShippingAddress token (if present) by the the formated Shipping Address
                    if (adminBodyEmail.IndexOf("[ShippingAddress]", StringComparison.InvariantCultureIgnoreCase) != Null.NullInteger)
                    {
                        adminBodyEmail = adminBodyEmail.Replace("[ShippingAddress]", shippingAddress.Format(customerAddressTemplate));
                    }
                }
                else
                {
                    // Remove Shipping Address Template
                    adminBodyEmail = RegShipping.Replace(adminBodyEmail, string.Empty);
                    // Replace Pickup Template
                    Match regPickupMatch = RegPickup.Match(adminBodyEmail);
                    if (regPickupMatch.Success)
                    {
                        string pickupTemplate = regPickupMatch.Groups[1].ToString();
                        pickupTemplate = RegStripStartNewLine.Replace(pickupTemplate, string.Empty);
                        pickupTemplate = RegStripEndNewLine.Replace(pickupTemplate, string.Empty);
                        adminBodyEmail = RegShipping.Replace(adminBodyEmail, pickupTemplate);
                    }
                }

                // Init Email Order Replacement Tokens
                EmailOrderTokenReplace tkEmailOrder = new EmailOrderTokenReplace
                {
                    StoreSettings   = StoreSettings,
                    Order           = order,
                    BillingAddress  = billingAddress,
                    ShippingAddress = shippingAddress
                };

                // Replace tokens
                customerSubjectEmail = tkEmailOrder.ReplaceEmailOrderTokens(customerSubjectEmail);
                customerBodyEmail    = tkEmailOrder.ReplaceEmailOrderTokens(customerBodyEmail);
                adminSubjectEmail    = tkEmailOrder.ReplaceEmailOrderTokens(adminSubjectEmail);
                adminBodyEmail       = tkEmailOrder.ReplaceEmailOrderTokens(adminBodyEmail);

                // Order Details Template
                if (customerDetail || adminDetail)
                {
                    // Get Order Details
                    OrderController        orderController = new OrderController();
                    List <OrderDetailInfo> orderDetails    = orderController.GetOrderDetails(order.OrderID);
                    if (orderDetails != null)
                    {
                        // Update Stock Products if needed
                        if (StoreSettings.InventoryManagement)
                        {
                            DecreaseStock(orderDetails);
                        }

                        // Replace Order Detail Tokens
                        StringBuilder           customerDetailText = new StringBuilder();
                        StringBuilder           adminDetailText    = new StringBuilder();
                        OrderDetailTokenReplace tkOrderDetail      = new OrderDetailTokenReplace();

                        foreach (OrderDetailInfo detail in orderDetails)
                        {
                            tkOrderDetail.OrderDetail = detail;
                            if (customerDetail)
                            {
                                customerDetailText.AppendLine(tkOrderDetail.ReplaceOrderDetailTokens(customerDetailTemplate));
                            }
                            if (adminDetail)
                            {
                                adminDetailText.AppendLine(tkOrderDetail.ReplaceOrderDetailTokens(adminDetailTemplate));
                            }
                        }
                        if (customerDetail)
                        {
                            customerBodyEmail = RegDetails.Replace(customerBodyEmail, RegStripEndNewLine.Replace(customerDetailText.ToString(), string.Empty));
                        }
                        if (adminDetail)
                        {
                            adminBodyEmail = RegDetails.Replace(customerBodyEmail, RegStripEndNewLine.Replace(adminDetailText.ToString(), string.Empty));
                        }
                    }
                }

                try
                {
                    // Send Customer Email
                    string result = Mail.SendMail(adminEmail, customerEmail, "", customerSubjectEmail, customerBodyEmail, "", HtmlUtils.IsHtml(customerBodyEmail) ? MailFormat.Html.ToString() : MailFormat.Text.ToString(), "", "", "", "");
                    if (!string.IsNullOrEmpty(result))
                    {
                        LogSMTPError(customerEmail, result);
                    }

                    // Send Store Admin Email
                    result = Mail.SendMail(adminEmail, adminEmail, "", adminSubjectEmail, adminBodyEmail, "", HtmlUtils.IsHtml(adminBodyEmail) ? MailFormat.Html.ToString() : MailFormat.Text.ToString(), "", "", "", "");
                    if (!string.IsNullOrEmpty(result))
                    {
                        LogSMTPError(customerEmail, result);
                    }
                }
                catch (Exception ex)
                {
                    Exceptions.ProcessModuleLoadException(this, ex);
                }
            }
        }
Example #22
0
        protected void btnProcess_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
            {
                return;
            }

            PortalSecurity security = new PortalSecurity();

            TransactionDetails transaction = new TransactionDetails
            {
                CardNumber       = security.InputFilter(txtNumber.Text, PortalSecurity.FilterFlag.NoMarkup),
                VerificationCode = security.InputFilter(txtVer.Text, PortalSecurity.FilterFlag.NoMarkup),
                ExpirationMonth  = int.Parse(ddlMonth.SelectedValue),
                ExpirationYear   = int.Parse(ddlYear.SelectedValue)
            };

            if (transaction.IsValid())
            {
                IAddressInfo shippingAddress = CheckoutControl.ShippingAddress;
                IAddressInfo billingAddress  = CheckoutControl.BillingAddress;
                //Adds order to db...
                OrderInfo order = CheckoutControl.GetFinalizedOrderInfo();

                GenerateOrderConfirmation();

                //Process transaction
                AuthNetGatewayProvider provider    = new AuthNetGatewayProvider(StoreSettings.GatewaySettings);
                TransactionResult      orderResult = provider.ProcessTransaction(shippingAddress, billingAddress, order, transaction);
                if (!orderResult.Succeeded)
                {
                    string errorMessage    = string.Empty;
                    string localizedReason = string.Empty;
                    // Try to get the corresponding localized reason message
                    localizedReason = Localization.GetString("ReasonCode" + orderResult.ReasonCode, LocalResourceFile);
                    // If a localized message do not exist use the original message
                    if (localizedReason == string.Empty | localizedReason == null)
                    {
                        localizedReason = orderResult.Message.ToString();
                    }
                    switch (orderResult.ResultCode)
                    {
                    case -5:
                        errorMessage = Localization.GetString("ErrorCardInformation", LocalResourceFile);
                        break;

                    case -4:
                        errorMessage = Localization.GetString("ErrorBillingAddress", LocalResourceFile);
                        break;

                    case -3:
                        errorMessage = Localization.GetString("ErrorPaymentOption", LocalResourceFile);
                        break;

                    case -2:
                        errorMessage = Localization.GetString("ErrorConnection", LocalResourceFile);
                        break;

                    case -1:
                        errorMessage = Localization.GetString("ErrorUnexpected", LocalResourceFile);
                        break;

                    case 2:
                        errorMessage          = string.Format(Localization.GetString("ReasonMessage", LocalResourceFile), Localization.GetString("ResponseCode2", LocalResourceFile), orderResult.ReasonCode, "");
                        CheckoutControl.Order = UpdateOrderStatus(order, OrderInfo.OrderStatusList.AwaitingPayment);
                        CheckoutControl.Hide();
                        pnlProceedToAuthorize.Visible = false;
                        InvokePaymentFailed();
                        CurrentCart.DeleteCart(PortalId, StoreSettings.SecureCookie);
                        ClearOrderIdCookie();
                        break;

                    case 3:
                        errorMessage = string.Format(Localization.GetString("ReasonMessage", LocalResourceFile), Localization.GetString("ResponseCode3", LocalResourceFile), orderResult.ReasonCode, localizedReason);
                        break;

                    case 4:
                        errorMessage          = string.Format(Localization.GetString("ReasonMessage", LocalResourceFile), Localization.GetString("ResponseCode4", LocalResourceFile), orderResult.ReasonCode, localizedReason);
                        CheckoutControl.Order = UpdateOrderStatus(order, OrderInfo.OrderStatusList.AwaitingPayment);
                        CheckoutControl.Hide();
                        pnlProceedToAuthorize.Visible = false;
                        InvokePaymentRequiresConfirmation();
                        CurrentCart.DeleteCart(PortalId, StoreSettings.SecureCookie);
                        ClearOrderIdCookie();
                        break;

                    default:
                        errorMessage = string.Format(Localization.GetString("ReasonMessage", LocalResourceFile), Localization.GetString("ErrorUnexpected", LocalResourceFile), orderResult.ReasonCode, localizedReason);
                        break;
                    }
                    lblError.Visible = true;
                    lblError.Text    = errorMessage;
                }
                else
                {
                    int portalId = PortalSettings.PortalId;
                    // Set order status to "Paid"...
                    CheckoutControl.Order = UpdateOrderStatus(order, OrderInfo.OrderStatusList.Paid);
                    // Add User to Product Roles
                    OrderController orderController = new OrderController();
                    orderController.AddUserToRoles(PortalId, order);
                    // Add User to Order Role
                    StoreInfo storeSetting = StoreController.GetStoreInfo(PortalSettings.PortalId);
                    if (storeSetting.OnOrderPaidRoleID != Null.NullInteger)
                    {
                        orderController.AddUserToPaidOrderRole(portalId, order.CustomerID, storeSetting.OnOrderPaidRoleID);
                    }
                    CheckoutControl.Hide();
                    pnlProceedToAuthorize.Visible = false;
                    lblError.Visible = false;
                    InvokePaymentSucceeded();
                    CurrentCart.DeleteCart(PortalId, StoreSettings.SecureCookie);
                    ClearOrderIdCookie();
                }
            }
            else
            {
                lblError.Visible = true;
                lblError.Text    = Localization.GetString("ErrorCardNotValid", LocalResourceFile);
            }
            btnProcess.Enabled = true;
        }
Example #23
0
        public string TokenReplace(string tokenObjectName, string source, IAddressInfo address)
        {
            AddressTokenReplace tkAddress = new AddressTokenReplace(tokenObjectName, address);

            return(tkAddress.ReplaceAddressTokens(source));
        }
Example #24
0
        /// <summary>
        /// Calculate tax according the country/region of the deliveryAddress.
        /// </summary>
        /// <param name="portalID">ID of the portal</param>
        /// <param name="cartItems">List of ICartItemInfo that need to have taxes calculated on.</param>
        /// <param name="shippingInfo">ShippingInfo in the case that taxes need to be applied to shipping</param>
        /// <param name="billingAddress">The address that the taxes should be applied for.</param>
        /// <returns>ITaxInfo with the total amount of tax due for the cart items shipping cost.</returns>
        public ITaxInfo CalculateSalesTax <T>(int portalID, IEnumerable <T> cartItems, IShippingInfo shippingInfo, IAddressInfo billingAddress) where T : ICartItemInfo
        {
            TaxInfo taxInfo = GetTaxRates(portalID);

            if (taxInfo != null && taxInfo.ShowTax)
            {
                decimal taxRate = taxInfo.DefaultTaxRate / 100;

                if (billingAddress != null && taxInfo.CountryTaxes != null)
                {
                    ListController       listController = new ListController();
                    List <ListEntryInfo> countries      = new List <ListEntryInfo>(listController.GetListEntryInfoItems("Country"));
                    string countryCode = GetEntryValue(billingAddress.CountryCode, countries);
                    string regionCode  = billingAddress.RegionCode;

                    if (!string.IsNullOrEmpty(regionCode))
                    {
                        List <ListEntryInfo> regions = new List <ListEntryInfo>(listController.GetListEntryInfoItems("Region", "Country." + countryCode));
                        regionCode = GetEntryValue(regionCode, regions);
                    }

                    taxRate = GetCountryRegionTaxRate(countryCode, regionCode, billingAddress.PostalCode, taxInfo.CountryTaxes, taxInfo.DefaultTaxRate);
                }

                // Compute Shipping Tax if needed
                taxInfo.ShippingTax = shippingInfo.ApplyTaxRate ? shippingInfo.Cost * taxRate : 0M;
                // Compute Sales Tax
                decimal cartTotal = 0M;
                foreach (T itemInfo in cartItems)
                {
                    cartTotal += (itemInfo.SubTotal - itemInfo.Discount) * taxRate;
                }
                taxInfo.SalesTax = cartTotal + taxInfo.ShippingTax;
            }
            else
            {
                if (taxInfo == null)
                {
                    taxInfo = new TaxInfo();
                }
                taxInfo.ShowTax        = false;
                taxInfo.DefaultTaxRate = 0M;
                taxInfo.SalesTax       = 0M;
                taxInfo.ShippingTax    = 0M;
            }

            return(taxInfo);
        }
Example #25
0
        private void SendOrderStatusChangeEmail(OrderInfo order)
        {
            // Get Store Currency Symbol
            if (!string.IsNullOrEmpty(StoreSettings.CurrencySymbol))
            {
                order.CurrencySymbol = StoreSettings.CurrencySymbol;
            }

            // Get Order Date Format
            string orderDateFormat = Localization.GetString("OrderDateFormat", LocalResourceFile);

            if (!string.IsNullOrEmpty(orderDateFormat))
            {
                order.DateFormat = orderDateFormat;
            }

            // Get Customer Email
            IAddressInfo billingAddress = GetAddress(order.BillingAddressID, order.CustomerID);
            string       customerEmail  = billingAddress.Email;

            // Try to get email address from user account,
            // this could be required for older orders.
            if (string.IsNullOrEmpty(customerEmail))
            {
                UserController userControler = new UserController();
                UserInfo       user          = userControler.GetUser(PortalId, order.CustomerID);
                customerEmail = user.Email;
            }

            // Get Admin Email
            string adminEmail = StoreSettings.DefaultEmailAddress;

            // Customer Order Email Template
            string customerSubjectEmail = Localization.GetString("CustomerStatusChangedEmailSubject", LocalResourceFile);
            string customerBodyEmail    = Localization.GetString("CustomerStatusChangedEmailBody", LocalResourceFile);

            // Extract or remove IFPAID token
            Match regPaidMatch = RegPaid.Match(customerBodyEmail);

            if (regPaidMatch.Success)
            {
                // If Status is Paid
                if (order.OrderStatusID == 7)
                {
                    // Replace IFPAID token by his content
                    string shippingCostTemplate = regPaidMatch.Groups[1].ToString();
                    shippingCostTemplate = RegStripStartNewLine.Replace(shippingCostTemplate, string.Empty);
                    shippingCostTemplate = RegStripEndNewLine.Replace(shippingCostTemplate, string.Empty);
                    customerBodyEmail    = RegPaid.Replace(customerBodyEmail, shippingCostTemplate);
                }
                else // Remove IFPAID token
                {
                    customerBodyEmail = RegPaid.Replace(customerBodyEmail, string.Empty);
                }
            }

            // Admin Order Email Template
            string adminSubjectEmail = Localization.GetString("AdminStatusChangedEmailSubject", LocalResourceFile);
            string adminBodyEmail    = Localization.GetString("AdminStatusChangedEmailBody", LocalResourceFile);

            // Init Email Order Replacement Tokens
            EmailOrderTokenReplace tkEmailOrder = new EmailOrderTokenReplace
            {
                StoreSettings = StoreSettings,
                Order         = order
            };

            // Replace tokens
            customerSubjectEmail = tkEmailOrder.ReplaceEmailOrderTokens(customerSubjectEmail);
            customerBodyEmail    = tkEmailOrder.ReplaceEmailOrderTokens(customerBodyEmail);
            adminSubjectEmail    = tkEmailOrder.ReplaceEmailOrderTokens(adminSubjectEmail);
            adminBodyEmail       = tkEmailOrder.ReplaceEmailOrderTokens(adminBodyEmail);

            try
            {
                // Send Customer Email
                Mail.SendMail(adminEmail, customerEmail, "", customerSubjectEmail, customerBodyEmail, "", HtmlUtils.IsHtml(customerBodyEmail) ? MailFormat.Html.ToString() : MailFormat.Text.ToString(), "", "", "", "");

                // Send Store Admin Email
                Mail.SendMail(adminEmail, adminEmail, "", adminSubjectEmail, adminBodyEmail, "", HtmlUtils.IsHtml(adminBodyEmail) ? MailFormat.Html.ToString() : MailFormat.Text.ToString(), "", "", "", "");
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
Example #26
0
        public TransactionResult ProcessTransaction(IAddressInfo shipping, IAddressInfo billing, OrderInfo orderInfo, TransactionDetails trans)
        {
            TransactionResult result = new TransactionResult();

            CultureInfo ciEnUs = new CultureInfo("en-US");

            // Check data before performing transaction
            AuthNetSettings settings = new AuthNetSettings(_gatewaySettings);

            if (!settings.IsValid())
            {
                result.Succeeded  = false;
                result.ResultCode = -3;

                return(result);
            }

            if (billing == null)
            {
                result.Succeeded  = false;
                result.ResultCode = -4;

                return(result);
            }

            if (trans == null || !trans.IsValid())
            {
                result.Succeeded  = false;
                result.ResultCode = -5;

                return(result);
            }

            // Gather transaction information
            string url = settings.GatewayURL;
            NameValueCollection NVCol = new NameValueCollection
            {
                // Merchant infos
                { "x_login", settings.Username },    //Req
                { "x_tran_key", settings.Password }, //Req
                { "x_version", settings.Version },   //Req
                { "x_test_request", settings.IsTest.ToString().ToUpper() },
                // Init infos
                { "x_delim_data", "TRUE" },
                { "x_delim_char", "|" },
                { "x_encap_char", "" },
                { "x_relay_response", "FALSE" }, //Req
                                                 //New in Store 3.1.10, added by Authorize in February 2014
                { "x_market_type", "0" },        // 0=eCommerce, 1 MOTO, 2 Retail
                                                 // Billing infos
                { "x_first_name", billing.FirstName },
                { "x_last_name", billing.LastName },
                { "x_company", "" },
                { "x_address", (billing.Address1 + " " + billing.Address2).Trim() },
                { "x_city", billing.City },
                { "x_state", billing.RegionCode },
                { "x_zip", billing.PostalCode },
                { "x_country", billing.CountryCode },
                { "x_phone", billing.Phone1 },
                // Shipping infos
                { "x_ship_to_first_name", shipping.FirstName },
                { "x_ship_to_last_name", shipping.LastName },
                { "x_ship_to_company", "" },
                { "x_ship_to_address", (shipping.Address1 + " " + shipping.Address2).Trim() },
                { "x_ship_to_city", shipping.City },
                { "x_ship_to_state", shipping.RegionCode },
                { "x_ship_to_zip", shipping.PostalCode },
                { "x_ship_to_country", shipping.CountryCode },
                // Customer infos
                { "x_cust_id", billing.UserID.ToString() },
                { "x_customer_ip", HttpContext.Current.Request.UserHostAddress },
                // Order infos
                { "x_invoice_num", orderInfo.OrderID.ToString() },
                { "x_amount", orderInfo.GrandTotal.ToString("0.00", ciEnUs) },//Req
                { "x_tax", orderInfo.TaxTotal.ToString("0.00", ciEnUs) },
                { "x_freight", orderInfo.ShippingCost.ToString("0.00", ciEnUs) },
                // Transaction infos
                { "x_method", "CC" },                      //CC=Credit Card could be also ECHECK
                { "x_type", settings.Capture.ToString() }, //Req
                { "x_recurring_billing", "NO" },
                { "x_card_num", trans.CardNumber },        //Req
                { "x_card_code", trans.VerificationCode },
                { "x_exp_date", trans.ExpirationMonth.ToString("00") + "/" + trans.ExpirationYear }//Req
            };
            // Order details
            string                 fieldSep        = "<|>";
            OrderController        orderController = new OrderController();
            List <OrderDetailInfo> orderDetails    = orderController.GetOrderDetails(orderInfo.OrderID);
            ArrayList              items           = new ArrayList(orderDetails.Count);

            foreach (OrderDetailInfo detail in orderDetails)
            {
                string modelNumber = detail.ModelNumber;
                if (modelNumber.Length > 31)
                {
                    modelNumber = modelNumber.Substring(0, 31);
                }

                string modelName = detail.ModelName;
                if (modelName.Length > 31)
                {
                    modelName = modelName.Substring(0, 31);
                }

                items.Add(modelNumber + fieldSep + modelName + fieldSep + fieldSep + detail.Quantity +
                          fieldSep + detail.UnitCost.ToString("0.00", ciEnUs) + fieldSep + "Y");
            }
            // Perform transaction
            try
            {
                Encoding     enc = Encoding.GetEncoding(1252);
                StreamReader loResponseStream = new StreamReader(PostEx(url, NVCol, items).GetResponseStream(), enc);

                string lcHtml = loResponseStream.ReadToEnd();
                loResponseStream.Close();

                string[] resultArray = lcHtml.Split('|');

                result.Succeeded  = (resultArray[0] == "1");
                result.ResultCode = int.Parse(resultArray[0]);
                result.ReasonCode = int.Parse(resultArray[2]);
                result.Message    = resultArray[3];
            }
            catch (Exception ex)
            {
                result.Succeeded  = false;
                result.ResultCode = -2;
                result.Message    = ex.Message;
            }

            return(result);
        }
Example #27
0
 public int AddAddress(IAddressInfo addressInfo)
 {
     return DataProvider.Instance().AddAddress(addressInfo.PortalID, addressInfo.UserID, addressInfo.Description, addressInfo.Name, addressInfo.Address1, addressInfo.Address2, addressInfo.City, addressInfo.RegionCode, addressInfo.CountryCode, addressInfo.PostalCode, addressInfo.Phone1, addressInfo.Phone2, addressInfo.PrimaryAddress, addressInfo.CreatedByUser);
 }
Example #28
0
 public void UpdateAddress(IAddressInfo addressInfo)
 {
     DataProvider.Instance().UpdateAddress(addressInfo.AddressID, addressInfo.Description, addressInfo.Name, addressInfo.Address1, addressInfo.Address2, addressInfo.City, addressInfo.RegionCode, addressInfo.CountryCode, addressInfo.PostalCode, addressInfo.Phone1, addressInfo.Phone2, addressInfo.PrimaryAddress);
 }
Example #29
0
        public void ProcessTransaction(IAddressInfo billing, OrderInfo orderInfo, TransactionDetails transaction)
        {
            PayPalSettings settings = new PayPalSettings(_gatewaySettings);

            if (transaction.IsValid())
            {
                CultureInfo ciEnUs = new CultureInfo("en-US");
                _paymentURL = settings.UseSandbox ? SandboxPaymentURL : settings.PaymentURL;
                RemoteForm paypal = new RemoteForm("paypalform", _paymentURL);
                // Main fields
                paypal.Fields.Add("cmd", "_cart");
                paypal.Fields.Add("upload", "1");
                paypal.Fields.Add("business", settings.PayPalID.ToLower());
                paypal.Fields.Add("charset", settings.Charset);
                paypal.Fields.Add("currency_code", settings.Currency);
                paypal.Fields.Add("invoice", orderInfo.OrderID.ToString());
                paypal.Fields.Add("return", transaction.ReturnURL);
                paypal.Fields.Add("cancel_return", transaction.CancelURL);
                paypal.Fields.Add("notify_url", transaction.NotifyURL);
                paypal.Fields.Add("rm", "2");
                paypal.Fields.Add("lc", settings.Lc);
                paypal.Fields.Add("cbt", transaction.Cbt);
                paypal.Fields.Add("custom", orderInfo.CustomerID.ToString());
                paypal.Fields.Add("email", transaction.Email);
                paypal.Fields.Add("first_name", billing.FirstName);
                paypal.Fields.Add("last_name", billing.LastName);
                if (!string.IsNullOrEmpty(billing.Address1))
                {
                    paypal.Fields.Add("address1", billing.Address1);
                }
                if (!string.IsNullOrEmpty(billing.Address2))
                {
                    paypal.Fields.Add("address2", billing.Address2);
                }
                if (!string.IsNullOrEmpty(billing.City))
                {
                    paypal.Fields.Add("city", billing.City);
                }
                if (!string.IsNullOrEmpty(billing.PostalCode))
                {
                    paypal.Fields.Add("zip", billing.PostalCode);
                }
                // Get ISO country code for specified country name
                string country = GetISOCountryCode(billing.CountryCode);
                if (!string.IsNullOrEmpty(country))
                {
                    paypal.Fields.Add("country", country);
                }
                if (!string.IsNullOrEmpty(billing.Phone1))
                {
                    // Remove all chars but numbers from phone number
                    string phonenumber = Regex.Replace(billing.Phone1, "[^\\d]", "", RegexOptions.Compiled);
                    // If the buyer live in the USA
                    if (country == "US")
                    {
                        // Get US postal code for specified region code and add it to the form
                        paypal.Fields.Add("state", GetUSPostalRegionCode(country, billing.RegionCode));
                        // If the phone number is valid
                        int phoneLength = phonenumber.Length;
                        if (phoneLength > 7)
                        {
                            // Extract area code, three digits prefix and four digits phone number
                            paypal.Fields.Add("night_phone_a", phonenumber.Substring(0, phoneLength - 7));
                            paypal.Fields.Add("night_phone_b", phonenumber.Substring(phoneLength - 7, 3));
                            paypal.Fields.Add("night_phone_c", phonenumber.Substring(phoneLength - 4));
                        }
                    }
                    else
                    {
                        // For International buyers, set country code and phone number
                        //paypal.Fields.Add("night_phone_a", country); HERE PHONE country code is required!
                        paypal.Fields.Add("night_phone_b", phonenumber);
                    }
                }
                // Order details
                OrderController        orderController = new OrderController();
                List <OrderDetailInfo> orderDetails    = orderController.GetOrderDetails(orderInfo.OrderID);
                int itemNumber = 1;
                foreach (OrderDetailInfo detail in orderDetails)
                {
                    paypal.Fields.Add("item_number_" + itemNumber, detail.ProductID.ToString());
                    paypal.Fields.Add("item_name_" + itemNumber, detail.ProductTitle);
                    paypal.Fields.Add("quantity_" + itemNumber, detail.Quantity.ToString());
                    paypal.Fields.Add("amount_" + itemNumber, detail.UnitCost.ToString("0.00", ciEnUs));
                    itemNumber++;
                }
                // If a valid coupon exists
                if (orderInfo.CouponID != Null.NullInteger)
                {
                    decimal discount = Math.Abs(orderInfo.Discount);
                    paypal.Fields.Add("discount_amount_cart", discount.ToString("0.00", ciEnUs));
                }
                // Shipping
                if (orderInfo.ShippingCost > 0)
                {
                    paypal.Fields.Add("handling_cart", orderInfo.ShippingCost.ToString("0.00", ciEnUs));
                }
                // Tax
                if (orderInfo.TaxTotal > 0)
                {
                    paypal.Fields.Add("tax_cart", orderInfo.TaxTotal.ToString("0.00", ciEnUs));
                }
                // Post the form to the client browser then submit it to PayPal using JavaScript
                paypal.Post();
            }
        }
Example #30
0
        public void ProcessTransaction(IAddressInfo billing, OrderInfo orderInfo, TransactionDetails transaction)
        {
            if (transaction.IsValid())
            {
                SystempaySettings settings  = new SystempaySettings(_gatewaySettings);
                RemoteForm        systempay = new RemoteForm("systempayform", settings.PaymentURL);
                // Main fields
                systempay.Fields.Add("vads_version", "V2");
                systempay.Fields.Add("vads_site_id", settings.SiteID);
                systempay.Fields.Add("vads_ctx_mode", settings.UseTestCertificate ? "TEST" : "PRODUCTION");
                if (!string.IsNullOrEmpty(settings.Contracts))
                {
                    systempay.Fields.Add("vads_contracts", settings.Contracts);
                }
                systempay.Fields.Add("vads_page_action", "PAYMENT");
                systempay.Fields.Add("vads_action_mode", "INTERACTIVE");
                systempay.Fields.Add("vads_payment_config", "SINGLE");
                systempay.Fields.Add("vads_capture_delay", "0");
                //systempay.Fields.Add("vads_validation_mode", "0");
                systempay.Fields.Add("vads_trans_id", GetTransactionID());
                systempay.Fields.Add("vads_trans_date", GetTransactionDate());
                systempay.Fields.Add("vads_currency", settings.Currency);
                systempay.Fields.Add("vads_language", settings.Language);
                systempay.Fields.Add("vads_return_mode", "POST");
                systempay.Fields.Add("vads_url_return", transaction.ReturnURL);
                systempay.Fields.Add("vads_url_refused", transaction.RefusedURL);
                systempay.Fields.Add("vads_url_error", transaction.ErrorURL);
                systempay.Fields.Add("vads_url_cancel", transaction.CancelURL);
                systempay.Fields.Add("vads_url_check", transaction.NotifyURL);
                systempay.Fields.Add("vads_shop_name", transaction.ShopName);
                systempay.Fields.Add("vads_theme_config", transaction.Buttons);

                // Customer fields
                systempay.Fields.Add("vads_cust_id", orderInfo.CustomerID.ToString());
                systempay.Fields.Add("vads_cust_first_name", billing.FirstName);
                systempay.Fields.Add("vads_cust_last_name", billing.LastName);
                string address = (billing.Address1 + " " + billing.Address2).Trim();
                if (!string.IsNullOrEmpty(address))
                {
                    systempay.Fields.Add("vads_cust_address", address);
                }
                if (!string.IsNullOrEmpty(billing.PostalCode))
                {
                    systempay.Fields.Add("vads_cust_zip", billing.PostalCode);
                }
                if (!string.IsNullOrEmpty(billing.City))
                {
                    systempay.Fields.Add("vads_cust_city", billing.City);
                }
                // Get ISO country code for specified country name
                string country = GetISOCountryCode(billing.CountryCode);
                if (!string.IsNullOrEmpty(country))
                {
                    systempay.Fields.Add("vads_cust_country", country);
                }
                if (!string.IsNullOrEmpty(billing.Phone1))
                {
                    systempay.Fields.Add("vads_cust_phone", billing.Phone1);
                }
                if (!string.IsNullOrEmpty(billing.Phone2))
                {
                    systempay.Fields.Add("vads_cust_cell_phone", billing.Phone2);
                }
                systempay.Fields.Add("vads_cust_email", transaction.Email);

                // Order fields
                systempay.Fields.Add("vads_order_id", orderInfo.OrderID.ToString());
                // Order details
                OrderController        orderController = new OrderController();
                List <OrderDetailInfo> orderDetails    = orderController.GetOrderDetails(orderInfo.OrderID);
                int itemNumber = 0;
                foreach (OrderDetailInfo detail in orderDetails)
                {
                    string prodRef = !string.IsNullOrEmpty(detail.ModelNumber) ? detail.ModelNumber : detail.ProductID.ToString();
                    systempay.Fields.Add("vads_product_ref" + itemNumber, prodRef);
                    systempay.Fields.Add("vads_product_label" + itemNumber, detail.ModelName);
                    systempay.Fields.Add("vads_product_qty" + itemNumber, detail.Quantity.ToString());
                    systempay.Fields.Add("vads_product_amount" + itemNumber, FormatAmount(detail.UnitCost));
                    itemNumber++;
                }
                systempay.Fields.Add("vads_nb_products", orderDetails.Count.ToString());
                systempay.Fields.Add("vads_amount", FormatAmount(orderInfo.GrandTotal));

                // Shipping
                if (orderInfo.ShippingCost > 0)
                {
                    systempay.Fields.Add("vads_shipping_amount", FormatAmount(orderInfo.ShippingCost));
                }
                // Tax
                if (orderInfo.TaxTotal > 0)
                {
                    systempay.Fields.Add("vads_tax_amount", FormatAmount(orderInfo.TaxTotal));
                }

                // Add computed signature
                systempay.Fields.Add("signature", GetSignature(systempay.Fields, settings.Certificate));
                // Post the form to the client browser then submit it to Systempay using JavaScript
                systempay.Post(true);
            }
        }
Example #31
0
        /// <summary>
        /// Calculate tax according the region in the deliveryAddress argument.
        /// </summary>
        /// <param name="portalID">ID of the portal</param>
        /// <param name="cartItems">List of ICartItemInfo that need to have taxes calculated on.</param>
        /// <param name="shippingInfo">ShippingInfo in the case that taxes need to be applied to shipping</param>
        /// <param name="deliveryAddress">The address that the taxes should be applied for.</param>
        /// <returns>ITaxInfo with the total amount of tax due for the cart items shipping cost.</returns>
        public ITaxInfo CalculateSalesTax <T>(int portalID, IEnumerable <T> cartItems, IShippingInfo shippingInfo, IAddressInfo deliveryAddress) where T : ICartItemInfo
        {
            TaxInfo taxInfo = GetTaxRates(portalID);

            if (taxInfo != null && taxInfo.ShowTax)
            {
                decimal taxRate = (taxInfo.DefaultTaxRate / 100);
                // Compute Shipping Tax if needed
                taxInfo.ShippingTax = shippingInfo.ApplyTaxRate ? shippingInfo.Cost * taxRate : 0M;
                // Compute Sales Tax
                decimal cartTotal = 0M;
                foreach (T itemInfo in cartItems)
                {
                    cartTotal += (itemInfo.SubTotal - itemInfo.Discount) * taxRate;
                }
                taxInfo.SalesTax = cartTotal + taxInfo.ShippingTax;
            }
            else
            {
                if (taxInfo == null)
                {
                    taxInfo = new TaxInfo();
                }
                taxInfo.ShowTax        = false;
                taxInfo.DefaultTaxRate = 0M;
                taxInfo.SalesTax       = 0M;
                taxInfo.ShippingTax    = 0M;
            }
            return(taxInfo);
        }
 public AddressEventArgs(IAddressInfo address)
 {
     this.address = address;
 }
Example #33
0
        private void ConfirmOrder()
        {
            Page.Validate();
            if (Page.IsValid == false)
            {
                return;
            }

            // Adds order to db...
            OrderInfo    order          = CheckoutControl.GetFinalizedOrderInfo();
            IAddressInfo billingAddress = CheckoutControl.BillingAddress;

            GenerateOrderConfirmation();

            CheckoutControl.Hide();
            pnlProceedToSystempay.Visible = false;

            // Set order status to "Awaiting Payment"...
            CheckoutControl.Order = UpdateOrderStatus(order, OrderInfo.OrderStatusList.AwaitingPayment);

            // Clear basket
            CurrentCart.DeleteCart(PortalId, StoreSettings.SecureCookie);

            // Clear cookies
            ClearOrderIdCookie();

            // Process transaction
            string              urlAuthority = Request.Url.GetLeftPart(UriPartial.Authority);
            TransactionDetails  transaction  = new TransactionDetails();
            SystempayNavigation nav          = new SystempayNavigation(Request.QueryString)
            {
                OrderID = order.OrderID,
                // Return URL
                GatewayExit = "return"
            };

            transaction.ReturnURL = AddAuthority(nav.GetNavigationUrl(), urlAuthority);
            // Refused URL
            nav.GatewayExit        = "refused";
            transaction.RefusedURL = AddAuthority(nav.GetNavigationUrl(), urlAuthority);
            // Error URL
            nav.GatewayExit      = "error";
            transaction.ErrorURL = AddAuthority(nav.GetNavigationUrl(), urlAuthority);
            // Cancel URL
            nav.GatewayExit       = "cancel";
            transaction.CancelURL = AddAuthority(nav.GetNavigationUrl(), urlAuthority);
            // IPN URL
            string language = Request.QueryString["language"];

            if (string.IsNullOrEmpty(language))
            {
                language = System.Threading.Thread.CurrentThread.CurrentCulture.ToString();
            }
            transaction.NotifyURL = urlAuthority + TemplateSourceDirectory + "/SystempayIPN.aspx?language=" + language;
            string messages = Localization.GetString("SystempayButtons", LocalResourceFile);

            transaction.Buttons  = string.Format(messages, StoreSettings.Name);
            transaction.ShopName = StoreSettings.Name;
            transaction.Email    = billingAddress.Email;

            SystempayGatewayProvider provider = new SystempayGatewayProvider(StoreSettings.GatewaySettings);

            provider.ProcessTransaction(CheckoutControl.BillingAddress, order, transaction);
        }
Example #34
0
        private void SendOrderStatusChangeEmail(OrderInfo order)
        {
            // Get Store Currency Symbol
            if (!string.IsNullOrEmpty(StoreSettings.CurrencySymbol))
            {
                order.CurrencySymbol = StoreSettings.CurrencySymbol;
            }

            // Get Order Date Format
            string orderDateFormat = Localization.GetString("OrderDateFormat", LocalResourceFile);

            if (!string.IsNullOrEmpty(orderDateFormat))
            {
                order.DateFormat = orderDateFormat;
            }

            // Get Customer Email
            IAddressProvider controler      = StoreController.GetAddressProvider(StoreSettings.AddressName);
            IAddressInfo     billingAddress = controler.GetAddress(order.BillingAddressID);
            string           customerEmail  = billingAddress.Email;

            // Get Admin Email
            string adminEmail = StoreSettings.DefaultEmailAddress;

            // Customer Order Email Template
            string customerSubjectEmail = Localization.GetString("CustomerStatusChangedEmailSubject", LocalResourceFile);
            string customerBodyEmail    = Localization.GetString("CustomerStatusChangedEmailBody", LocalResourceFile);

            // Extract or remove IFPAID token
            Match regPaidMatch = RegPaid.Match(customerBodyEmail);

            if (regPaidMatch.Success)
            {
                // If Status is Paid
                if (order.OrderStatusID == 7)
                {
                    // Replace IFPAID token by his content
                    string paidTemplate = regPaidMatch.Groups[1].ToString();
                    paidTemplate      = RegStripStartNewLine.Replace(paidTemplate, string.Empty);
                    paidTemplate      = RegStripEndNewLine.Replace(paidTemplate, string.Empty);
                    customerBodyEmail = RegPaid.Replace(customerBodyEmail, paidTemplate);
                }
                else // Remove IFPAID token
                {
                    customerBodyEmail = RegPaid.Replace(customerBodyEmail, string.Empty);
                }
            }

            // Admin Order Email Template
            string adminSubjectEmail = Localization.GetString("AdminStatusChangedEmailSubject", LocalResourceFile);
            string adminBodyEmail    = Localization.GetString("AdminStatusChangedEmailBody", LocalResourceFile);

            // Init Email Order Replacement Tokens
            EmailOrderTokenReplace tkEmailOrder = new EmailOrderTokenReplace();

            tkEmailOrder.StoreSettings = StoreSettings;
            tkEmailOrder.Order         = order;

            // Replace tokens
            customerSubjectEmail = tkEmailOrder.ReplaceEmailOrderTokens(customerSubjectEmail);
            customerBodyEmail    = tkEmailOrder.ReplaceEmailOrderTokens(customerBodyEmail);
            adminSubjectEmail    = tkEmailOrder.ReplaceEmailOrderTokens(adminSubjectEmail);
            adminBodyEmail       = tkEmailOrder.ReplaceEmailOrderTokens(adminBodyEmail);

            try
            {
                // Send Customer Email
                string result = Mail.SendMail(adminEmail, customerEmail, "", customerSubjectEmail, customerBodyEmail, "", HtmlUtils.IsHtml(customerBodyEmail) ? MailFormat.Html.ToString() : MailFormat.Text.ToString(), "", "", "", "");
                if (!string.IsNullOrEmpty(result))
                {
                    LogSMTPError(customerEmail, result);
                }

                // Send Store Admin Email
                result = Mail.SendMail(adminEmail, adminEmail, "", adminSubjectEmail, adminBodyEmail, "", HtmlUtils.IsHtml(adminBodyEmail) ? MailFormat.Html.ToString() : MailFormat.Text.ToString(), "", "", "", "");
                if (!string.IsNullOrEmpty(result))
                {
                    LogSMTPError(customerEmail, result);
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }