Friday, February 03, 2012

Delete local commits in Mercurial

I've faced a problem in mercurial source control, simply i've added some commits and discovered that they are unwanted to be pushed.
A simple way to find is the command STRIP. Strip required to install mqExtension to mercurial to enable it.
To install and configure it look here http://mercurial.selenic.com/wiki/MqExtension#Configuration

Then use the following command
hg strip changeset
Where changeset is the hash of the commit you want to delete
Use hg -v help strip changeset to view detailed options of the command.
Note: deleting any changeset will delete all its children. By default strip takes a backup of the deleted changeset.

Thursday, December 22, 2011

Stripe Payment using MVC3


What is Stripe?
It is an online tool for developers to develop e-commerce payments over the web in an easy way. Stripe allows developers to send secure requests with billing information. Stripe responses with a known result of transaction status.
Stripe contains management and monitoring for: Payments, Customers, Transfers, Plans and Coupons.
Stripe supports all card types; Visa, MasterCard, American Express, Discover, JCB, and Diners Club cards.

Creating a stripe account
It is very easy to create an account at stripe. Creating an account is the first step you have to do to use stripe online services.
To create a stripe account, you should follow these steps:
  • Visit Stripe web site
  • Scroll down and find "Get started with stripe" button.
  • Fill your registration information and click "Create your stripe account"
You now have a stripe account, you can easily manage your account.


Stripe account settings
To start using Stripe, you should enable Test mode. You can do this easily by sliding the slider at the top left of the management page. Slide it from Live to Test.
For development usage, you need a couple of keys to identify your account in stripe; Secret Key and Publishable key. To find these keys just click on Your Account menu and navigate to Account Settings item. In the popup screen click on API Keys header button, you will find Secret and Publishable keys for both Test and Live mode. Later, we will know how to use API keys in our application to identify a specific Stripe account.

Management and monitoring
Stripe lets you manage and monitor your account. Open dashboard page, you can see an overview of transactions' volume, successful charges and customers growing. You can filter also these statistics by date range. 
At the right menu, click on the Payments menu item. Payments page contains list of all transactions that are done on your account. You can easily view payment details and also refund the payment.
Click on customers menu item, you will view all customers that are created. You can add, delete, edit and view payments of any customer. Customer creation is optional for doing a payment; you can allow customer to make a payment without saving his details in Stripe customers database.
Click on Plans, here you can manage your payment plans. It will be useful in case of multiple pricing packages.
You can manage also: Transfers and Coupons 

Using Stripe API
It is so simple to use Stripe API. You can find full documentation here.
For fast beginning, i have created a simple project that interacts with a test stripe account, you can download the source code from here
Note: we may need to use an external library to act with requests and responses from stripe sever. Here we will use Stripe.Net (you can see examples of using this liberary from here).

OK, lets start now. We will need to have the following requirements:
Open Microsoft Visual Studio and start a new MVC3 project. Add a refernece for the downloaded Stripe.net.dll library. Let's add a new model in the models folder, lets name it "BuyViewModel" which contains buyer's info. BuyerViewModel fields are: Email, FullName, CardNumber, CVC, ExpirationMonth and Expirartion year. Let's add a new controller to controllers folder, let's name it "PaymentController". Add a new action called Buy() with an empty definition. Add a view for the Buy() action and BuyerViewModel model with scaffold "Create", which will be named by default "buy.chtml".

Stripe.js
Stripe.js makes a request to stripe server in client side and responses with a token that identify your credit info. You now need to add stripe.js reference to your view. add to your page head the following line:
    <script type="text/javascript" src="https://js.stripe.com/v1/"></script> 

 At your page head, add a script tag and add the following line inside:
      Stripe.setPublishableKey('Your_Publishable_Key');


 For sure, you will replace 'Your_Publishable_Key' with your publishable key either in Test of Live mode. The above line identifies your account in stripe. You have to add reference for jquery if it is not added yet in the view or the containing layout.
 The scenario now is to send a request to stripe server using stripe js with credit card info and receives a token that will be used in server side API invokes. To send the request we need to handle form submission event to send the request before posting back.

 Add the following lines to your script tag to handle form submission:

  $(document).ready(function () {
            $("#payment-form").submit(function (event) {
                // disable the submit button to prevent repeated clicks
                $('.submit-button').attr("disabled", "disabled");
                // createToken returns immediately - the supplied callback submits the form if there are no errors
                Stripe.createToken({
                    number: $('#CardNumber').val(),
                    cvc: $('#CVC').val(),
                    exp_month: $('#ExpirationMonth').val(),
                    exp_year: $('#ExpirationYear').val()
                }, stripeResponseHandler);
                return false; // submit from callback
            });
        });


 The above code block handles the submission behavior of "payment-form" form. Remeber that, you just need to set the id of your form to "payment-form". This can be done by overriding the Html.BeginForm() method in the view to be:

  @using (Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object> { { "id", "payment-form" }, { "enctype", "multipart/form-data" } }))


 Stripe.CreateToken() method sends a request to stripe using the publishable key which is set before. As you can see we disabled the submit button first to prevent multiple requests. Note: the jquery selector finds the submit button using a css class "submit-button", you can either add this css class to your submit button or change the selector to find other attribute value.
 By looking to CreateToken() method parameters, you can notice that the first parameter is a JSON object that contains credit card information. The second parameter is stripeResponseHandler, this handler - which will be created soon- is responsible for handling the response returned from the sent Stripe request.
 Let's now write the definition of the stripeResponseHandler. In the script tag, write the following script block:

function stripeResponseHandler(status, response) {

            if (response.error) {

                // re-enable the submit button

                $('.submit-button').removeAttr("disabled");

                // show the errors on the form

                $(".payment-errors").html(response.error.message);

            } else {

                var form$ = $("#payment-form");

                // token contains id, last4, and card type

                var token = response['id'];

                // insert the token into the form so it gets submitted to the server

                form$.append("<input type='hidden' id='stripeToken' name='stripeToken' value='" + token + "' />");

                // and submit

                form$.get(0).submit();

            }

        }

 As you see above, we checked first for errors, and if exist we display error message in a div has a css class "payment-errors". So, you need to add this div to your view which may look like this:
   <span class="payment-errors"></span>

 In case of no errors we catch the response id into a variable called token. Make a hidden field "stripeToken" to carry the token value. Now we have the token saved in the form, this means we can post this token to the server in the next postbacks. So, we are ready for submitting the form.

Stripe.Net API
It is the time now to write our server side code which makes the real payment operations. Stripe.Net needs from you to identify your account in stripe by setting your secret key. You secret key is to be set into the application's web config in appSettings section, which will look like that:
   <appSettings>
            <add key="StripeApiKey" value="Your_Secret_Key" />
   </appSettings>


 We have to write the post action which handles the form postback. Open PaymentController and add a new action and name it "Buy" with [httpPost] attribute. Below is the full definition of the Buy() action:
      [HttpPost]
        public ActionResult Buy(FormCollection form)
        {
            var customerToken = form["stripeToken"];
            var buyerModel = new BuyerViewModel();
            UpdateModel(buyerModel, form.ToValueProvider());
            // create customer
            var customerOptions = new StripeCustomerCreateOptions
            {
                Email = buyerModel.Email,
                Description = buyerModel.FullName,
                TokenId = customerToken
            };
            var service = new StripeCustomerService();
            var customer = service.Create(customerOptions);            
            // create a charge for the added customer
            var myCharge = new StripeChargeCreateOptions
            {
                AmountInCents = 1000,
                Currency = "usd",
                CustomerId = customer.Id
            };
            var chargeService = new StripeChargeService();
            var stripeCharge = chargeService.Create(myCharge);
            return RedirectToAction("PaymentComplete", "Payment", new RouteValueDictionary { { "chargeId", stripeCharge.Id } });
        }

 As you can see, We get the stripeToken hidden field value to be used in our request. After getting the token, we may need to take the inputs value into an empty BuyerViewModel model. 
     UpdateModel(buyerModel, form.ToValueProvider());

 Note: Make sure that you are using namespace "Stripe"
     using Stripe;

  Now, it is the time to create the customer. To do that we can make an object of StripeCustomerCreateOptions and set Email, Description and Token of customer's credit card info. Note: The StripeCustomerCreateOptions has different initializers (e.g set credit card info instead of token, look at https://github.com/jaymedavis/stripe.net Create customer section).
Note: I preferred to set description as customer full name, but you may have other representation of customer description. 

 As you can see, customer creation is completed by:
  var customer = service.Create(customerOptions);

 At this moment, you can see the customer in your customers page in stripe management web site.

 We can now use customer.id to make an actual payment. All we need is to determine the amount to be charged in cents and pass the added customer id to the StripeChargeCreateOptions initialiazer. Then complete the creation by:
    var stripeCharge = chargeService.Create(myCharge);

 At this moment, you can see the payment that has been done. You can see it in either your payments page or in the added customer page; at payments section.

 In our example, we redirects the buyer to another page that inform him that the payment has been done successfully if it really does :). So, we created a new action for PaymentComplete to redirect the buyer to it after completing payment and inform him with the charge id. You may choose any other behavior after buyer completes his/her payment. PaymentComplete() action presented by a view that contains just a successful message and charge id.

  Now we have made a completed payment operation - as you can see - in an easy way and with a little number of lines.

What else you can do?
You can do some other stripe operations like: Refunding, Editing customers, Editing plans, Editing subscriptions, Editing coupons and Retrieving token details. 
You can find very useful examples here:
https://github.com/jaymedavis/stripe.net scroll to Examples section




Ok, I've finished. I hope this article be useful for you. Enjoy using stripe.



Wednesday, November 09, 2011

MVC3 :: Multiple Submit button

You may need a form with more than one submit button.
Here you have the buttons at the Razor markup


 <input type="submit" value="Back" name="actionType" class="btn medium secondary" />
 <input type="submit" value="Save draft" name="actionType" class="btn medium secondary" />
 <input type="submit" value="Publish" name="actionType" class="btn medium primary" />



You have one action to submit the form to which name is "Edit" for example.
The solution is as you noticed above I've added name="actionType" for all submit buttons.
Now in the Edit action you have to add one extra parameter for actionType as below:

 public ActionResult Edit(string actionType)
{
    switch(actionType)
     {
               // add ur cases here
      }
}


Welcome

Welcome to my technical blog.
Here i hope to be able to share my technical experience overall the world.
You are welcomed to visit, read, share and contribute with your ideas and comments.
Good luck