public PaymentOption UpdateOption(PaymentOption paymentOption, long userId)
        {
            var _user = _context.Users.Find(userId);

            if (_user != null)
            {
                if (_user != paymentOption.User)
                {
                    throw new AccessViolationException("You aren't allowed to modify this!");
                }
                try{
                    var _option = _context.PaymentOptions.Find(paymentOption.PaymentOptionId);
                    if (_option == null)
                    {
                        throw new Exception("Wrong parameters!");
                    }
                    _option.OptionType = paymentOption.OptionType;
                    _option.Details    = paymentOption.Details;
                    _context.PaymentOptions.Update(_option);
                    _context.SaveChanges();
                    return(_option);
                }catch (Exception e) {
                    throw e;
                }
            }
            else
            {
                throw new Exception("Bad request parameters!");
            }
        }
        public async Task <IActionResult> PutPaymentOption([FromRoute] int id, [FromBody] PaymentOption paymentOption)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != paymentOption.ID)
            {
                return(BadRequest());
            }

            _context.Entry(paymentOption).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PaymentOptionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Beispiel #3
0
        public static async Task <bool> DeletePaymentOption(PaymentOption paymentOption)
        {
            await Session.GetTokenIfEmptyAsync(AuthTokenType.Simple);

            var token = await Session.GetAuthTokenAsync(AuthTokenType.Simple);

            if (string.IsNullOrEmpty(token))
            {
                throw new UnauthorizedAccessException("User is not logged in to perform the action: Delete Payment option");
            }

            if (paymentOption == null)
            {
                return(false);
            }

            RestWrapper restWrapper = new RestWrapper();

            if (paymentOption.CardType != CardType.UnKnown)
            {
                var response = await restWrapper.Delete(Service.Wallet + "/" + paymentOption.CardNumber.Substring(12, 4) + ":" + paymentOption.Scheme, AuthTokenType.Simple);

                return(response.IsSuccessStatusCode);
            }
            else
            {
                var response = await restWrapper.Delete(Service.Wallet + "/" + paymentOption.Token, AuthTokenType.Simple);

                return(response.IsSuccessStatusCode);
            }

            return(false);
        }
Beispiel #4
0
        public CashPaymentOption SetPaymentOptionAsCash(CashPaymentOptionDomainDto cashPaymentOptionDomainDto)
        {
            var paymentOption = CashPaymentOption.Load(cashPaymentOptionDomainDto);

            PaymentOption = paymentOption;
            return(paymentOption);
        }
Beispiel #5
0
    protected void uxUpdateButton_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                PaymentOption paymentOption = DataAccessContext.PaymentOptionRepository.GetOne(
                    uxLanguageControl.CurrentCulture, PaymentName);
                paymentOption = SetUpPaymentOption(paymentOption);
                paymentOption = DataAccessContext.PaymentOptionRepository.Update(paymentOption);

                AdminAdvancedBaseGatewayUserControl gatewayUserControl = GetGatewayUserControl();
                if (gatewayUserControl != null)
                {
                    gatewayUserControl.Save();
                }

                DataAccessContext.ConfigurationRepository.UpdateValue(DataAccessContext.Configurations["PaymentCurrency"], uxCurrencySelector.SelectedValue);

                uxMessage.DisplayMessage(Resources.PaymentMessages.UpdateSuccess);
                PopulatePermissionWarning();
            }
        }
        catch (Exception ex)
        {
            uxMessage.DisplayException(ex);
        }
    }
Beispiel #6
0
        protected virtual void AddPaymentMethods(Result <BillingModel> result, Cart cart)
        {
            var paymentOption = new PaymentOption
            {
                PaymentOptionType = PaymentOptionType.PayCard
            };

            var paymentMethods = this.PaymentManager.GetPaymentMethods(cart, paymentOption);

            if (paymentMethods.ServiceProviderResult.Success && (paymentMethods.Result != null))
            {
                result.Data.PaymentMethods = new List <PaymentMethodModel>();
                foreach (var paymentMethod in paymentMethods.Result)
                {
                    var model = new PaymentMethodModel();
                    model.Description = paymentMethod.Description;
                    model.ExternalId  = paymentMethod.PaymentOptionId;
                    result.Data.PaymentMethods.Add(model);
                }
            }
            else
            {
                result.SetErrors(paymentMethods.ServiceProviderResult);
            }
        }
Beispiel #7
0
 public Media(string name, string description, double price, double discount, PaymentOption paymentOption, MediaType mediaType, int duration, string objectStorageId) :
     base(name, description, price, discount, paymentOption)
 {
     MediaType       = mediaType;
     Duration        = duration;
     ObjectStorageId = objectStorageId;
 }
Beispiel #8
0
    public string GetSecondaryPaymentName()
    {
        for (int i = 0; i < uxPaymentList.Items.Count; i++)
        {
            RadioButton radio = (RadioButton)uxPaymentList.Items[i].FindControl("uxRadio");
            if (radio.Checked)
            {
                string name = uxPaymentList.DataKeys[i].ToString();

                if (PaymentOption.IsCustomPayment(name))
                {
                    string dropDownValue = GetDropDownValue(i);
                    if (!String.IsNullOrEmpty(dropDownValue))
                    {
                        return(dropDownValue);
                    }
                    else
                    {
                        return(String.Empty);
                    }
                }
            }
        }

        return(String.Empty);
    }
Beispiel #9
0
        public async Task <IActionResult> Create(PaymentOption option)
        {
            if (!ModelState.IsValid)
            {
                return(View(option));
            }

            var identity = (ClaimsIdentity)this.User.Identity;
            var claim    = identity.FindFirst(ClaimTypes.NameIdentifier);
            var team     = await _context.TeamMembers.FirstOrDefaultAsync(t => t.UserID == claim.Value);

            option.CreatedAt = DateTime.Now;
            option.TeamID    = team.TeamID;

            try
            {
                _context.PaymentOptions.Add(option);
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e + ": An error occurred.");
            }

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #10
0
    public bool IsAnyPaymentSelected()
    {
        string paymentName = GetSelectedPaymentName();

        if (String.IsNullOrEmpty(paymentName))
        {
            return(false);
        }
        else
        {
            if (PaymentOption.IsCustomPayment(paymentName))
            {
                string secondaryName = GetSecondaryPaymentName();
                if (String.IsNullOrEmpty(secondaryName))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                return(true);
            }
        }
    }
Beispiel #11
0
    public bool IsPONumberEmpty(out string poNumber)
    {
        poNumber = String.Empty;
        PaymentOption paymentOption = DataAccessContext.PaymentOptionRepository.GetOne(StoreContext.Culture, "Purchase Order");

        for (int i = 0; i < uxPaymentList.Items.Count; i++)
        {
            RadioButton radio = (RadioButton)uxPaymentList.Items[i].FindControl("uxRadio");
            if (radio.Checked)
            {
                if (uxPaymentList.DataKeys[i].ToString().Equals(paymentOption.Name))
                {
                    uxPOpanel.Visible = true;
                    if (String.IsNullOrEmpty(uxPONumberText.Text))
                    {
                        return(true);
                    }
                    else
                    {
                        poNumber = uxPONumberText.Text;
                        return(false);
                    }
                }
            }
        }
        return(false);
    }
Beispiel #12
0
        public CreditCardPaymentOption SetPaymentOptionAsCreditCard(CreditCardPaymentOptionDomainDto creditCardPaymentOptionDomainDto)
        {
            var paymentOption = CreditCardPaymentOption.Load(creditCardPaymentOptionDomainDto);

            PaymentOption = paymentOption;
            return(paymentOption);
        }
Beispiel #13
0
    public void RestorePaymentMethod()
    {
        PaymentOption paymentOption = StoreContext.CheckoutDetails.PaymentMethod.PaymentOption;

        if (paymentOption == null)
        {
            return;
        }
        for (int i = 0; i < uxPaymentList.Items.Count; i++)
        {
            HiddenField nameHidden = (HiddenField)uxPaymentList.Items[i].FindControl("uxPaymentNameHidden");
            if (nameHidden.Value == paymentOption.Name)
            {
                RadioButton radio = (RadioButton)uxPaymentList.Items[i].FindControl("uxRadio");
                radio.Checked = true;

                if (PaymentOption.IsCustomPayment(paymentOption.Name))
                {
                    DropDownList drop = (DropDownList)uxPaymentList.Items[i].FindControl("uxDrop");
                    drop.SelectedValue = StoreContext.CheckoutDetails.PaymentMethod.SecondaryName;
                }
                else if (paymentOption.Name == "Purchase Order")
                {
                    uxPOpanel.Visible   = true;
                    uxPONumberText.Text = StoreContext.CheckoutDetails.PaymentMethod.PONumber;
                }
                break;
            }
        }
    }
Beispiel #14
0
        public static void ReadInput()
        {
            Customer      currentCustomer = CustomerFactory.Instance.ActiveCustomer;
            PaymentOption opt             = new PaymentOption();

            if (currentCustomer == null)
            {
                Console.WriteLine("There must be an active customer first. Press any key to return to main menu.");
            }
            else
            {
                Console.WriteLine("Enter payment type (e.g. AmEx, Visa, Checking)");
                Console.Write("> ");
                opt.Name = Console.ReadLine();

                Console.WriteLine("Enter account number");
                Console.Write("> ");
                opt.AccountNumber = Console.ReadLine();

                opt.IdCustomer = currentCustomer.id;
                opt.save();

                Console.WriteLine("Payment option added. Press any key to return to main menu.");
            }

            Console.ReadLine();
        }
Beispiel #15
0
 public Payment(Customer customer, PaymentOption paymentOption, double amountpaid, double change)
 {
     Customers      = customer;
     PaymentOptions = paymentOption;
     AmountPaid     = amountpaid;
     Change         = change;
 }
Beispiel #16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        PaymentMethod paymentMethod = StoreContext.CheckoutDetails.PaymentMethod;
        PaymentOption paymentOption = DataAccessContext.PaymentOptionRepository.GetOne(StoreContext.Culture, paymentMethod.Name);

        if (!paymentOption.CreditCardRequired)
        {
            uxPaymentInfo.SetCheckoutBillingAddress();

            if (!IsAnonymousCheckout())
            {
                Response.Redirect("OrderSummary.aspx");
            }
            else
            {
                Response.Redirect("OrderSummary.aspx?skiplogin=true");
            }
        }


        if (!IsPostBack)
        {
            uxPaymentInfo.PopulateControls(Master.Controls);
        }
    }
Beispiel #17
0
    private bool SetPaymentAndRedirect()
    {
        if (!uxPaymentMehods.IsAnyPaymentSelected())
        {
            uxPaymentMehods.DisplayError("[$ErrorNoPaymentSelected]");
            return(false);
        }
        else if (uxPaymentMehods.IsPolicyAgreementEnabled() && !uxPaymentMehods.IsAgreeChecked())
        {
            uxPaymentMehods.DisplayPolicyAgreementError("[$ErrorNotCheckPolicyAgreement]");
            return(false);
        }

        string        paymentMethodName = uxPaymentMehods.GetSelectedPaymentName();
        PaymentOption paymentOption     = DataAccessContext.PaymentOptionRepository.GetOne(
            StoreContext.Culture, paymentMethodName);

        PaymentMethod paymentMethod = paymentOption.CreatePaymentMethod();

        paymentMethod.SecondaryName = uxPaymentMehods.GetSecondaryPaymentName();

        string poNumber = String.Empty;

        if (uxPaymentMehods.IsPONumberEmpty(out poNumber))
        {
            uxPaymentMehods.DisplayPOError("[$ErrorPONumberRequired]");
            return(false);
        }

        paymentMethod.PONumber = poNumber;
        StoreContext.CheckoutDetails.SetPaymentMethod(paymentMethod);

        return(true);
    }
 public int Add(PaymentOption entity)
 {
     if (entity == null)
     {
         throw new ArgumentException("parameter cannot be null");
     }
     return(_repo.Add(entity));
 }
        public PaymentOption get_by_id(Int32 id = 0, Int32 languageId = 0)
        {
            // Create the post to return
            PaymentOption post = PaymentOption.GetOneById(id, languageId);

            // Return the post
            return(post);
        } // End of the get_by_id method
Beispiel #20
0
 private void HideCommonData(PaymentOption paymentOption)
 {
     if (paymentOption.ShowButton)
     {
         uxLanguageDependentPlaceHolder.Visible = false;
         uxImageTR.Visible = false;
     }
 }
        public List <PaymentOption> get_all_active(Int32 languageId = 0, string sortField = "", string sortOrder = "")
        {
            // Create the list to return
            List <PaymentOption> posts = PaymentOption.GetAllActive(languageId, sortField, sortOrder);

            // Return the list
            return(posts);
        } // End of the get_all_active method
Beispiel #22
0
 public CatalogItem(string name, string description, double price, double discount, PaymentOption paymentOption)
 {
     Name          = name;
     Description   = description;
     Price         = price;
     Discount      = discount;
     PaymentOption = paymentOption;
 }
        public string Initialize(PaymentForm paymentForm, PaymentOption paymentOption)
        {
            _paymentForm       = paymentForm;
            CanSaveCredentials = _paymentForm.CanSaveCredentials;

            IsWebUsed = true;
            return(paymentOption.Url);
        }
Beispiel #24
0
        public async Task <Authorize3dResponse> Authorize3d(
            string currency,
            string amount,
            PaymentOption paymentOption,
            string relatedTransactionId,
            List <Item> items                   = null,
            string userTokenId                  = null,
            string clientUniqueId               = null,
            string clientRequestId              = null,
            int?isRebilling                     = null,
            AmountDetails amountDetails         = null,
            DeviceDetails deviceDetails         = null,
            CashierUserDetails userDetails      = null,
            UserAddress shippingAddress         = null,
            UserAddress billingAddress          = null,
            DynamicDescriptor dynamicDescriptor = null,
            MerchantDetails merchantDetails     = null,
            Addendums addendums                 = null,
            UrlDetails urlDetails               = null,
            string customSiteName               = null,
            string productId                    = null,
            string customData                   = null,
            string transactionType              = null,
            bool autoPayment3D                  = default,
            string userId                 = null,
            string rebillingType          = null,
            string authenticationTypeOnly = null,
            SubMerchant subMerchant       = null)
        {
            var request = new Authorize3dRequest(merchantInfo, sessionToken, currency, amount, paymentOption, relatedTransactionId)
            {
                Items                  = items,
                UserTokenId            = userTokenId,
                ClientRequestId        = clientRequestId,
                ClientUniqueId         = clientUniqueId,
                IsRebilling            = isRebilling,
                AmountDetails          = amountDetails,
                DeviceDetails          = deviceDetails,
                UserDetails            = userDetails,
                ShippingAddress        = shippingAddress,
                BillingAddress         = billingAddress,
                DynamicDescriptor      = dynamicDescriptor,
                MerchantDetails        = merchantDetails,
                Addendums              = addendums,
                UrlDetails             = urlDetails,
                CustomSiteName         = customSiteName,
                ProductId              = productId,
                CustomData             = customData,
                TransactionType        = transactionType,
                AutoPayment3D          = autoPayment3D,
                UserId                 = userId,
                RebillingType          = rebillingType,
                AuthenticationTypeOnly = authenticationTypeOnly,
                SubMerchant            = subMerchant
            };

            return(await safechargeRequestExecutor.Authorize3d(request));
        }
Beispiel #25
0
        public GetPaymentMethodsResult GetPaymentMethods(Cart cart, PaymentOption paymentOption)
        {
            Assert.ArgumentNotNull(cart, nameof(cart));
            Assert.ArgumentNotNull(paymentOption, nameof(paymentOption));

            var request = new GetPaymentMethodsRequest(cart as CommerceCart, paymentOption);

            return(this.Execute(request, this.paymentServiceProvider.GetPaymentMethods));
        }
Beispiel #26
0
    private PaymentOption SetUpPaymentOption(PaymentOption paymentOption)
    {
        paymentOption.DisplayName  = uxDisplayNameText.Text;
        paymentOption.Description  = uxDescriptionText.Text;
        paymentOption.PaymentImage = uxPaymentImageText.Text;
        paymentOption.IsEnabled    = ConvertUtilities.ToBoolean(uxIsEnabledDrop.SelectedValue);

        return(paymentOption);
    }
Beispiel #27
0
    public override void Refresh()
    {
        PaymentOption paymentOption = DataAccessContext.PaymentOptionRepository.GetOne(StoreContext.Culture, "eWay");

        uxCustomerIDText.Text        = DataAccessContext.Configurations.GetValue("eWayCustomerID");
        uxUseCvnDrop.SelectedValue   = paymentOption.Cvv2Required.ToString();
        uxTestModeDrop.SelectedValue = DataAccessContext.Configurations.GetValue("eWayTest");
        uxTestErrorCodeText.Text     = DataAccessContext.Configurations.GetValue("eWayErrorCode");
    }
Beispiel #28
0
    } // End of the MasterPostExists method

    /// <summary>
    /// Get one payment option based on id
    /// </summary>
    /// <param name="paymentOptionId">A payment option id</param>
    /// <param name="languageId">The language id</param>
    /// <returns>A reference to a payment option post</returns>
    public static PaymentOption GetOneById(Int32 paymentOptionId, Int32 languageId)
    {
        // Create the post to return
        PaymentOption post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql        = "SELECT * FROM dbo.payment_options_detail AS D INNER JOIN dbo.payment_options AS P ON "
                            + "D.payment_option_id = P.id AND D.payment_option_id = @id AND D.language_id = @language_id;";

        // The using block is used to call dispose automatically even if there is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add a parameters
                cmd.Parameters.AddWithValue("@id", paymentOptionId);
                cmd.Parameters.AddWithValue("@language_id", languageId);

                // Create a reader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new PaymentOption(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }

        // Return the post
        return(post);
    } // End of the GetOneById method
Beispiel #29
0
 public async Task AddPaymentOption(PaymentOption paymentOption)
 {
     // update token - card
     var customerService = new CustomerService();
     await customerService.UpdateAsync(paymentOption.CustomerId, new CustomerUpdateOptions()
     {
         Source = paymentOption.Token
     });
 }
        public PaymentOption FindPaymentOptionByName(string paymentOptionName)
        {
            PaymentOption f1 = _context.PaymentOptions.Where(x => x.PaymentOptionName.ToUpper().StartsWith(paymentOptionName.ToUpper())).FirstOrDefault();
            PaymentOption f2 = (from cf in _context.PaymentOptions
                                where cf.PaymentOptionName.ToUpper().StartsWith(paymentOptionName.ToUpper())
                                select cf).FirstOrDefault();

            return(f2);
        }
 public void SetPaymentOption(PaymentOption option)
 {
     switch (option)
     {
         case PaymentOption.DoNotChargeOrCollect:
             UIUtil.DefaultProvider.WaitForDisplayAndClick("ctl00_cph_radDoNotChargeTravel", LocateBy.Id);
             break;
         case PaymentOption.CollectCCInfo:
             UIUtil.DefaultProvider.WaitForDisplayAndClick("ctl00_cph_radCollectTravel", LocateBy.Id);
             break;
         default:
             throw new InvalidOperationException("No such payment option!");
     }
 }
Beispiel #32
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one payment option master post
    /// </summary>
    /// <param name="post">A reference to a payment option post</param>
    public static long AddMasterPost(PaymentOption post)
    {
        // Create the long to return
        long idOfInsert = 0;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.payment_options (product_code, payment_term_code, fee, unit_id, connection) "
            + "VALUES (@product_code, @payment_term_code, @fee, @unit_id, @connection);SELECT SCOPE_IDENTITY();";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@product_code", post.product_code);
                cmd.Parameters.AddWithValue("@payment_term_code", post.payment_term_code);
                cmd.Parameters.AddWithValue("@fee", post.fee);
                cmd.Parameters.AddWithValue("@unit_id", post.unit_id);
                cmd.Parameters.AddWithValue("@connection", post.connection);
                
                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    idOfInsert = Convert.ToInt64(cmd.ExecuteScalar());

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        // Return the id of the inserted item
        return idOfInsert;

    } // End of the AddMasterPost method
        public HttpResponseMessage update(PaymentOption post, Int32 languageId = 0)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }
            else if (Language.MasterPostExists(languageId) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist");
            }
            else if (Unit.MasterPostExists(post.unit_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The unit does not exist");
            }
            else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The value added tax does not exist");
            }

            // Make sure that the data is valid
            post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50);
            post.name = AnnytabDataValidation.TruncateString(post.name, 100);
            post.payment_term_code = AnnytabDataValidation.TruncateString(post.payment_term_code, 10);
            post.fee = AnnytabDataValidation.TruncateDecimal(post.fee, 0, 9999999999.99M);
            post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10);

            // Get the saved post
            PaymentOption savedPost = PaymentOption.GetOneById(post.id, languageId);

            // Check if the post exists
            if (savedPost == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist");
            }

            // Update the post
            PaymentOption.UpdateMasterPost(post);
            PaymentOption.UpdateLanguagePost(post, languageId);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful");

        } // End of the update method
        public HttpResponseMessage add(PaymentOption post, Int32 languageId = 0)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }
            else if (Language.MasterPostExists(languageId) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The language does not exist");
            }
            else if (Unit.MasterPostExists(post.unit_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The unit does not exist");
            }
            else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The value added tax does not exist");
            }

            // Make sure that the data is valid
            post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50);
            post.name = AnnytabDataValidation.TruncateString(post.name, 100);
            post.payment_term_code = AnnytabDataValidation.TruncateString(post.payment_term_code, 10);
            post.fee = AnnytabDataValidation.TruncateDecimal(post.fee, 0, 9999999999.99M);
            post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10);

            // Add the post
            Int64 insertId = PaymentOption.AddMasterPost(post);
            post.id = Convert.ToInt32(insertId);
            PaymentOption.AddLanguagePost(post, languageId);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added");

        } // End of the add method
Beispiel #35
0
    } // End of the AddLanguagePost method

    #endregion

    #region Update methods

    /// <summary>
    /// Update a payment option master post
    /// </summary>
    /// <param name="post">A reference to a payment option post</param>
    public static void UpdateMasterPost(PaymentOption post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.payment_options SET product_code = @product_code, payment_term_code = @payment_term_code, "
            + "fee = @fee, unit_id = @unit_id, connection = @connection WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@product_code", post.product_code);
                cmd.Parameters.AddWithValue("@payment_term_code", post.payment_term_code);
                cmd.Parameters.AddWithValue("@fee", post.fee);
                cmd.Parameters.AddWithValue("@unit_id", post.unit_id); 
                cmd.Parameters.AddWithValue("@connection", post.connection);
                
                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the UpdateMasterPost method
Beispiel #36
0
    } // End of the MasterPostExists method

    /// <summary>
    /// Get one payment option based on id
    /// </summary>
    /// <param name="paymentOptionId">A payment option id</param>
    /// <param name="languageId">The language id</param>
    /// <returns>A reference to a payment option post</returns>
    public static PaymentOption GetOneById(Int32 paymentOptionId, Int32 languageId)
    {
        // Create the post to return
        PaymentOption post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.payment_options_detail AS D INNER JOIN dbo.payment_options AS P ON "
            + "D.payment_option_id = P.id WHERE P.id = @id AND D.language_id = @language_id;";

        // The using block is used to call dispose automatically even if there is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add a parameters
                cmd.Parameters.AddWithValue("@id", paymentOptionId);
                cmd.Parameters.AddWithValue("@language_id", languageId);

                // Create a reader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new PaymentOption(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
        /// <summary>
        /// Translates to payment option.
        /// </summary>
        /// <param name="paymentOptionItem">The payment option item.</param>
        /// <param name="paymentOption">The payment option.</param>
        /// <param name="result">The result.</param>
        protected virtual void TranslateToPaymentOption(Item paymentOptionItem, PaymentOption paymentOption, GetPaymentOptionsResult result)
        {
            paymentOption.ExternalId = paymentOptionItem.ID.Guid.ToString();
            paymentOption.Name = paymentOptionItem.DisplayName;
            paymentOption.ShopName = this.GetShopName();

            int enumValue = MainUtil.GetInt(paymentOptionItem[CommerceServerStorefrontConstants.KnownFieldNames.PaymentOptionValue], 0);
            paymentOption.PaymentOptionType = this.TranslatePaymentOptionType(enumValue, result);
        }
        } // End of the UpdatePaymentStatus method

        /// <summary>
        /// Respond to an updated order status
        /// </summary>
        /// <param name="order"></param>
        /// <param name="paymentOption"></param>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        private string UpdateOrderStatus(Order order, PaymentOption paymentOption, string orderStatus)
        {
            // Create the string to return
            string error_message = "";

            // Get the current domain
            Domain domain = Tools.GetCurrentDomain();

            // Get webshop settings
            KeyStringList webshopSettings = WebshopSetting.GetAllFromCache();

            // Check the order status
            if (orderStatus == "order_status_delivered")
            {
                if(paymentOption.connection == 102) // Payson invoice
                {
                    // Get credentials
                    string paysonEmail = webshopSettings.Get("PAYSON-EMAIL");
                    string userId = webshopSettings.Get("PAYSON-AGENT-ID");
                    string md5Key = webshopSettings.Get("PAYSON-MD5-KEY");
                    bool paysonTest = false;
                    bool.TryParse(webshopSettings.Get("PAYSON-TEST"), out paysonTest);

                    // Create the api
                    PaysonIntegration.PaysonApi paysonApi = new PaysonIntegration.PaysonApi(userId, md5Key, null, paysonTest);

                    // Update the order
                    PaysonIntegration.Data.PaymentUpdateData paymentUpdateData = new PaysonIntegration.Data.PaymentUpdateData(order.payment_token, PaysonIntegration.Utils.PaymentUpdateAction.ShipOrder);
                    PaysonIntegration.Response.PaymentUpdateResponse paymentUpdateResponse = paysonApi.MakePaymentUpdateRequest(paymentUpdateData);

                    // Check if the response is successful
                    if (paymentUpdateResponse != null && paymentUpdateResponse.Success == false)
                    {
                        // Set error messages
                        foreach (string key in paymentUpdateResponse.ErrorMessages)
                        {
                            error_message += "&#149; " + "Payson: " + paymentUpdateResponse.ErrorMessages[key] + "<br/>";
                        }
                    }
                }
                else if(paymentOption.connection == 301) // Svea invoice
                {
                    // Get the order rows
                    List<OrderRow> orderRows = OrderRow.GetByOrderId(order.id);

                    // Create the payment configuration
                    SveaSettings sveaConfiguration = new SveaSettings();

                    // Create the order builder
                    Webpay.Integration.CSharp.Order.Handle.DeliverOrderBuilder inoviceBuilder = Webpay.Integration.CSharp.WebpayConnection.DeliverOrder(sveaConfiguration);

                    // Add order rows
                    for (int i = 0; i < orderRows.Count; i++)
                    {
                        // Get the unit
                        Unit unit = Unit.GetOneById(orderRows[i].unit_id, domain.back_end_language);

                        // Create an order item
                        Webpay.Integration.CSharp.Order.Row.OrderRowBuilder orderItem = new Webpay.Integration.CSharp.Order.Row.OrderRowBuilder();
                        orderItem.SetArticleNumber(orderRows[i].product_code);
                        orderItem.SetName(orderRows[i].product_name);
                        orderItem.SetQuantity(orderRows[i].quantity);
                        orderItem.SetUnit(unit.unit_code);
                        orderItem.SetAmountExVat(orderRows[i].unit_price);
                        orderItem.SetVatPercent(orderRows[i].vat_percent * 100);

                        // Add the order item
                        inoviceBuilder.AddOrderRow(orderItem);
                    }

                    // Get the order id
                    Int64 sveaOrderId = 0;
                    Int64.TryParse(order.payment_token, out sveaOrderId);

                    // Set invoice values
                    inoviceBuilder.SetOrderId(sveaOrderId);
                    inoviceBuilder.SetNumberOfCreditDays(15);
                    inoviceBuilder.SetInvoiceDistributionType(Webpay.Integration.CSharp.Util.Constant.InvoiceDistributionType.POST);
                    inoviceBuilder.SetCountryCode(SveaSettings.GetSveaCountryCode(order.country_code));

                    // Make the request to send the invoice
                    Webpay.Integration.CSharp.WebpayWS.DeliverOrderEuResponse deliverOrderResponse = inoviceBuilder.DeliverInvoiceOrder().DoRequest();
                    
                    // Check if the response is successful
                    if (deliverOrderResponse.Accepted == false)
                    {
                        // Set error messages
                        error_message += "&#149; " + "Svea code: " + deliverOrderResponse.ResultCode.ToString() + "<br/>";
                        error_message += "&#149; " + "Svea message: " + deliverOrderResponse.ErrorMessage + "<br/>";
                    }
                }
                else if (paymentOption.connection >= 400 && paymentOption.connection <= 499) // Payex
                {
                    // Check the transaction
                    Dictionary<string, string> payexResponse = PayExManager.CheckTransaction(order, webshopSettings);

                    // Get response variables
                    string error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : "";
                    string description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : "";
                    string parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : "";
                    string transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : "";
                    string transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : "";

                    // Check if the response was successful
                    if (error_code.ToUpper() == "OK")
                    {
                        if(transaction_status == "3") // Authorize
                        {
                            // Capture the transaction
                            payexResponse = PayExManager.CaptureTransaction(order);

                            // Get response variables
                            error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : "";
                            description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : "";
                            parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : "";
                            transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : "";
                            transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : "";
                            string transaction_number_original = payexResponse.ContainsKey("transaction_number_original") == true ? payexResponse["transaction_number_original"] : "";

                            if(error_code.ToUpper() != "OK" || transaction_status != "6")
                            {
                                // Set error messages
                                error_message += "&#149; " + "Payex code: " + error_code + "<br/>";
                                error_message += "&#149; " + "Payex message: " + description + "<br/>";
                                error_message += "&#149; " + "Payex parameter: " + parameter_name + "<br/>";
                                error_message += "&#149; " + "Payex status: " + transaction_status + "<br/>";
                                error_message += "&#149; " + "Payex number (original): " + transaction_number + "<br/>";
                            }
                            else
                            {
                                // Update the transaction number for the order
                                Order.SetPaymentToken(order.id, transaction_number);
                            }
                        }
                    }
                    else
                    {
                        // Set error messages
                        error_message += "&#149; " + "Payex code: " + error_code + "<br/>";
                        error_message += "&#149; " + "Payex message: " + description + "<br/>";
                        error_message += "&#149; " + "Payex parameter: " + parameter_name + "<br/>";
                        error_message += "&#149; " + "Payex status: " + transaction_status + "<br/>";
                        error_message += "&#149; " + "Payex number: " + transaction_number + "<br/>";
                    }
                }
            }
            else if (orderStatus == "order_status_cancelled")
            {
                if(paymentOption.connection >= 100 && paymentOption.connection <= 199) // Payson
                {
                    // Get credentials
                    string paysonEmail = webshopSettings.Get("PAYSON-EMAIL");
                    string userId = webshopSettings.Get("PAYSON-AGENT-ID");
                    string md5Key = webshopSettings.Get("PAYSON-MD5-KEY");
                    bool paysonTest = false;
                    bool.TryParse(webshopSettings.Get("PAYSON-TEST"), out paysonTest);

                    // Create the api
                    PaysonIntegration.PaysonApi paysonApi = new PaysonIntegration.PaysonApi(userId, md5Key, null, paysonTest);

                    // Get details about the payment status
                    PaysonIntegration.Response.PaymentDetailsResponse paysonResponse = paysonApi.MakePaymentDetailsRequest(new PaysonIntegration.Data.PaymentDetailsData(order.payment_token));

                    // Get the type and status of the payment
                    PaysonIntegration.Utils.PaymentType? paymentType = paysonResponse.PaymentDetails.PaymentType;
                    PaysonIntegration.Utils.PaymentStatus? paymentStatus = paysonResponse.PaymentDetails.PaymentStatus;
                    PaysonIntegration.Utils.InvoiceStatus? invoiceStatus = paysonResponse.PaymentDetails.InvoiceStatus;

                    // Payment update
                    PaysonIntegration.Data.PaymentUpdateData paymentUpdateData = null;
                    PaysonIntegration.Response.PaymentUpdateResponse paymentUpdateResponse = null;

                    if (paymentType == PaysonIntegration.Utils.PaymentType.Direct && paymentStatus == PaysonIntegration.Utils.PaymentStatus.Completed)
                    {
                        // Refund the payment
                        paymentUpdateData = new PaysonIntegration.Data.PaymentUpdateData(order.payment_token, PaysonIntegration.Utils.PaymentUpdateAction.Refund);
                        paymentUpdateResponse = paysonApi.MakePaymentUpdateRequest(paymentUpdateData);
                    }
                    else if (paymentType == PaysonIntegration.Utils.PaymentType.Invoice && invoiceStatus == PaysonIntegration.Utils.InvoiceStatus.OrderCreated)
                    {
                        // Cancel the order
                        paymentUpdateData = new PaysonIntegration.Data.PaymentUpdateData(order.payment_token, PaysonIntegration.Utils.PaymentUpdateAction.CancelOrder);
                        paymentUpdateResponse = paysonApi.MakePaymentUpdateRequest(paymentUpdateData);
                    }
                    else if (paymentType == PaysonIntegration.Utils.PaymentType.Invoice && (invoiceStatus == PaysonIntegration.Utils.InvoiceStatus.Shipped 
                        || invoiceStatus == PaysonIntegration.Utils.InvoiceStatus.Done))
                    {
                        // Credit the order
                        paymentUpdateData = new PaysonIntegration.Data.PaymentUpdateData(order.payment_token, PaysonIntegration.Utils.PaymentUpdateAction.CreditOrder);
                        paymentUpdateResponse = paysonApi.MakePaymentUpdateRequest(paymentUpdateData);
                    }

                    // Check if there was any errors
                    if (paymentUpdateResponse != null && paymentUpdateResponse.Success == false)
                    {
                        // Set error messages
                        foreach (string key in paymentUpdateResponse.ErrorMessages)
                        {
                            error_message += "&#149; " + "Payson: " + paymentUpdateResponse.ErrorMessages[key] + "<br/>";
                        }
                    }
                }
                else if(paymentOption.connection == 201) // PayPal
                {
                    // Get credentials
                    string paypalClientId = webshopSettings.Get("PAYPAL-CLIENT-ID");
                    string paypalClientSecret = webshopSettings.Get("PAYPAL-CLIENT-SECRET");
                    string paypalMode = webshopSettings.Get("PAYPAL-MODE");
                    Dictionary<string, string> config = new Dictionary<string, string> { { "mode", paypalMode } };

                    try
                    {
                        // Create the credential token
                        PayPal.OAuthTokenCredential tokenCredential = new PayPal.OAuthTokenCredential(paypalClientId, paypalClientSecret, config);

                        // Create the api context
                        PayPal.APIContext paypalContext = new PayPal.APIContext(tokenCredential.GetAccessToken());
                        paypalContext.Config = config;

                        // Look up the sale
                        PayPal.Api.Payments.Sale sale = PayPal.Api.Payments.Sale.Get(paypalContext, order.payment_token);

                        if (sale.state == "completed")
                        {
                            // Refund the payment
                            paypalContext.HTTPHeaders = null;
                            PayPal.Api.Payments.Refund refund = sale.Refund(paypalContext, new PayPal.Api.Payments.Refund());

                            if(refund.state != "completed")
                            {
                                error_message += "&#149; " + "PayPal: " + refund.state;
                            }
                        }
                        else
                        {
                            error_message += "&#149; " + "PayPal: " + sale.state;
                        }
                    }
                    catch (Exception ex)
                    {
                        error_message += "&#149; PayPal: " + ex.Message;
                    }
                }
                else if(paymentOption.connection == 301) // Svea invoice
                {
                    // Create the payment configuration
                    SveaSettings sveaConfiguration = new SveaSettings();

                    // Get the order id
                    Int64 sveaOrderId = 0;
                    Int64.TryParse(order.payment_token, out sveaOrderId);

                    // Cancel the order
                    Webpay.Integration.CSharp.Order.Handle.CloseOrderBuilder closeOrder = Webpay.Integration.CSharp.WebpayConnection.CloseOrder(sveaConfiguration);
                    closeOrder.SetOrderId(sveaOrderId);
                    closeOrder.SetCountryCode(SveaSettings.GetSveaCountryCode(order.country_code));
                    Webpay.Integration.CSharp.WebpayWS.CloseOrderEuResponse closeOrderResponse = closeOrder.CloseInvoiceOrder().DoRequest();

                    // Check if the response is successful
                    if (closeOrderResponse.Accepted == false)
                    {
                        // Set error messages
                        error_message += "&#149; " + "Svea code: " + closeOrderResponse.ResultCode.ToString() + "<br/>";
                        error_message += "&#149; " + "Svea message: " + closeOrderResponse.ErrorMessage + "<br/>";
                    }
                }
                else if(paymentOption.connection >= 400 && paymentOption.connection <= 499) // Payex
                {
                    // Check the transaction
                    Dictionary<string, string> payexResponse = PayExManager.CheckTransaction(order, webshopSettings);

                    // Get response variables
                    string error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : "";
                    string description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : "";
                    string parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : "";
                    string transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : "";
                    string transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : "";

                    // Check if the response was successful
                    if(error_code.ToUpper() == "OK")
                    {
                        // Check if we should cancel or credit the order
                        if(transaction_status == "3") // Authorize
                        {
                            // Cancel the transaction
                            payexResponse = PayExManager.CancelTransaction(order, webshopSettings);

                            // Get response variables
                            error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : "";
                            description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : "";
                            parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : "";
                            transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : "";
                            transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : "";

                            if(error_code.ToUpper() != "OK" || transaction_status != "4")
                            {
                                // Set error messages
                                error_message += "&#149; " + "Payex code: " + error_code + "<br/>";
                                error_message += "&#149; " + "Payex message: " + description + "<br/>";
                                error_message += "&#149; " + "Payex parameter: " + parameter_name + "<br/>";
                                error_message += "&#149; " + "Payex status: " + transaction_status + "<br/>";
                                error_message += "&#149; " + "Payex number: " + transaction_number + "<br/>";
                            }
                        }
                        else if(transaction_status == "0" || transaction_status == "6") // Sale or capture
                        {
                            // Get the order rows
                            List<OrderRow> orderRows = OrderRow.GetByOrderId(order.id);

                            // Credit the transaction
                            payexResponse = PayExManager.CreditTransaction(order, orderRows, webshopSettings);

                            // Get response variables
                            error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : "";
                            description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : "";
                            parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : "";
                            transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : "";
                            transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : "";

                            if (error_code.ToUpper() != "OK" || transaction_status != "2")
                            {
                                // Set error messages
                                error_message += "&#149; " + "Payex code: " + error_code + "<br/>";
                                error_message += "&#149; " + "Payex message: " + description + "<br/>";
                                error_message += "&#149; " + "Payex parameter: " + parameter_name + "<br/>";
                                error_message += "&#149; " + "Payex status: " + transaction_status + "<br/>";
                                error_message += "&#149; " + "Payex number: " + transaction_number + "<br/>";
                            }
                        }
                    }
                    else
                    {
                        // Set error messages
                        error_message += "&#149; " + "Payex code: " + error_code + "<br/>";
                        error_message += "&#149; " + "Payex message: " + description + "<br/>";
                        error_message += "&#149; " + "Payex parameter: " + parameter_name + "<br/>";
                        error_message += "&#149; " + "Payex status: " + transaction_status + "<br/>";
                        error_message += "&#149; " + "Payex number: " + transaction_number + "<br/>";
                    }
                }
            }

            // Return the error message
            return error_message;

        } // End of the UpdateOrderStatus method
        /// <summary>
        /// Gets the payment methods.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="paymentOption">The payment option.</param>
        /// <returns>The manager response where the payment method list is returned in the Result.</returns>
        public ManagerResponse<GetPaymentMethodsResult, IEnumerable<PaymentMethod>> GetPaymentMethods([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, PaymentOption paymentOption)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNull(paymentOption, "paymentOption");

            var request = new GetPaymentMethodsRequest(paymentOption);
            var result = this.PaymentServiceProvider.GetPaymentMethods(request);

            if (!result.Success)
            {
                Helpers.LogSystemMessages(result.SystemMessages, result);
            }

            return new ManagerResponse<GetPaymentMethodsResult, IEnumerable<PaymentMethod>>(result, result.PaymentMethods.ToList());
        }
Beispiel #40
0
    } // End of the UpdateMasterPost method

    /// <summary>
    /// Update a payment option language post
    /// </summary>
    /// <param name="post">A reference to a payment option post</param>
    /// <param name="languageId">The language id</param>
    public static void UpdateLanguagePost(PaymentOption post, Int32 languageId)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.payment_options_detail SET name = @name, value_added_tax_id = "
            + "@value_added_tax_id, account_code = @account_code, inactive = @inactive WHERE "
            + "payment_option_id = @id AND language_id = @language_id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@language_id", languageId);
                cmd.Parameters.AddWithValue("@name", post.name);
                cmd.Parameters.AddWithValue("@value_added_tax_id", post.value_added_tax_id);
                cmd.Parameters.AddWithValue("@account_code", post.account_code);
                cmd.Parameters.AddWithValue("@inactive", post.inactive);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the UpdateLanguagePost method