July 2017 ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Saturday, 29 July 2017

Integrating Authorize.net payment gateway to ASP.NET MVC Website part-1

19:00:00 Posted by raviteja swayampu No comments
This post explains about Authorize.net Credit card processing integration in ASP.NET MVC Website.

What is Authorize.net:

Authorize.Net is a United States-based payment gateway service provider allowing merchants to accept credit card and electronic check payments through their website and over an Internet Protocol connection.
Recently i had to integrate Authorize.net in my company project which is in ASP.NET MVC technology.I searched internet for this but i find no detailed tutorial which explains about authrize.net integration in asp.net mvc website.After working couple of days i completed the integration.I want to share this to help you in integrating authorize.net.This payment gateway only works for US banks only.

Prerequisites

Create a sandbox account in Authorize.Net https://developer.authorize.net/sandbox/. After you registered, you will get the API Credentials.
1.API Login ID
2.Transaction Key
3.Secret Question

We can do integration in two ways.They are,
1.Using an authorize WEB API calling,
2.By using Hosted file in server.
In current post we see integration using authorize WEB API.In part-2 i will explain about Hosted file.

Authorize.Net Test API Credentials
1.Controller code that communicate with Authorize.net web api gets the response from server.
2.We can see the response contents written by authorize.net in this page..
http://developer.authorize.net/api/reference/#homeresp-charge-a-credit-card
Controller code for integrating authorize.net code:

// GET: /AuthorizePayment/
        public ActionResult AuthorizePayment()
        {
            // By default, this sample code is designed to post to our test server for
            // developer accounts: https://test.authorize.net/gateway/transact.dll
            // for real accounts (even in test mode), please make sure that you are
            // posting to: https://secure.authorize.net/gateway/transact.dll

            String post_url = "https://test.authorize.net/gateway/transact.dll";

            Dictionary post_values = new Dictionary();
            //the API Login ID and Transaction Key must be replaced with valid values

            post_values.Add("x_login", "API_LOGIN_ID");
            post_values.Add("x_tran_key", "TRANSACTION_KEY");

            post_values.Add("x_delim_data", "TRUE");
            post_values.Add("x_delim_char", "|");
            post_values.Add("x_relay_response", "FALSE");

            post_values.Add("x_type", "AUTH_CAPTURE");
            post_values.Add("x_method", "CC");

            //Credit Card Number
            post_values.Add("x_card_num", "4007000000027");

            //Expiration Date Card Number
            post_values.Add("x_exp_date", "1234");

            //Order Amount
            post_values.Add("x_amount", "19.99");

            post_values.Add("x_description", "Sample Transaction");

            post_values.Add("x_first_name", "John");
            post_values.Add("x_last_name", "Doe");
            post_values.Add("x_address", "1234 Street");
            post_values.Add("x_state", "WA");
            post_values.Add("x_zip", "98004");
            // Additional fields can be added here as outlined in the AIM integration
            // guide at: http://developer.authorize.net

            // This section takes the input fields and converts them to the proper format
            // for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
            String post_string = "";

            //preparing values in keyvalue format to send data to web api 
            foreach (KeyValuePair post_value in post_values)
            {
                post_string += post_value.Key + "=" +
                HttpUtility.UrlEncode(post_value.Value) + "&";
            }
            post_string = post_string.TrimEnd('&');            

            // create an HttpWebRequest object to communicate with Authorize.net
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(post_url);
            objRequest.Method = "POST";
            objRequest.ContentLength = post_string.Length;
            objRequest.ContentType = "application/x-www-form-urlencoded";

            // post data is sent as a stream
            StreamWriter myWriter = null;
            myWriter = new StreamWriter(objRequest.GetRequestStream());
            myWriter.Write(post_string);
            myWriter.Close();

            //Response string returned from Authorize.net
            // returned values are returned as a stream, then read into a string
            String post_response;
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
            {
                post_response = responseStream.ReadToEnd();
                responseStream.Close();
            }

            // the response string is broken into an array
            // The split character specified here must match the delimiting character specified above
            Array response_array = post_response.Split('|');

            // the results are output to the screen in the form of an html numbered list.
            var result = "
    \n"; foreach (string value in response_array) { result = result + "
  1. " + value + " 
  2. \n"; } result = result + "
\n"; // individual elements of the array could be accessed to read certain response // fields. For example, response_array[0] would return the Response Code, // response_array[2] would return the Response Reason Code. // for a list of response fields, please review the AIM Implementation Guide return View(); }
Note:
1.The above code work with US based servers only.Authorize.net only accepts the requests from US based servers only based on ip address.for example it won't work for 192.168.1.4 server only work for 68.23.2.58 addresses.why because Authorize.net provides payment gateway facility for US only.

Conclusion:
I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus]

Thursday, 27 July 2017

Dynamically adding and removing form using jquery

23:42:00 Posted by raviteja swayampu , No comments

Hi every one welcome again.It took me long to post on this blog.But i hope this article is very helpful for web developers.
In this article i will get to know about How to create,remove and save dynamically created form like picture above.This task is purely based on JQuery scripting.But,i you will easily understand the code using comments i wrote.And i will share my source code also..
Step1:
1.Create Visual studio solution Web solution(Using ASP.NET MVC template).If you do not know how to create solution refer link: creating-first-application-in-aspnet-mvc.
2.Add a Controller to the solution.
3.Now in controller i prepared a Data source for drop down list and sent that data to view using ViewBag .
HomeController.cs:
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            //preparing dropdownlist data..
            List _ddllist = new List()
            {
                new SelectListItem { Text = "Select", Value = "Select" },
                new SelectListItem { Text = "Student", Value = "Student" },
                new SelectListItem { Text = "Professor", Value = "Professor" },
                new SelectListItem { Text = "Volunteer", Value = "Volunteer" },
                new SelectListItem { Text = "Organizer", Value = "Organizer" }
            };
            //sending using ViewBag..
            ViewBag.RegisterTypes = _ddllist;
            return View();
        }
    }
Step2:
1.Add a  view by right clicking on Index controller.
2.Add Jquery and Jquery UI library file in _Layout page or View page created.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<link href="~/Content/jquery-ui/theme/jquery-ui.1.11.1.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.10.0.min.js"></script>

Step3:
1.Now create view with below code.Here, i am not giving any explanation about how to write code but,you can easily understand by seeing code with documentation comments.

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<link href="~/Content/jquery-ui/theme/jquery-ui.1.11.1.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.10.0.min.js"></script>

@using (Html.BeginForm("", "", FormMethod.Post, new { id = "frmEventAttFee" }))
{
    <div id="DivAddFeeDetails" style="display:block;margin-top:50px;">
        <table id="tblEventAttendeeFee">
            <tbody>
                <tr>
                    <td><span style="width:100px;">Reg Types</span></td>
                    <td><span style="width:70px;">Start Date</span></td>
                    <td><span style="width:70px;">End Date</span></td>
                    <td><span style="width:50px;">Seats Avilable</span></td>
                    <td><span style="width:70px;">Amount</span></td>
                    <td><span style="width:70px;">CodeRequired</span></td>
                    <td><span style="width:70px;">Amount</span></td>
                </tr>
                <tr>
                    <td>
                        @Html.DropDownList("ddlRegTypes_0", ViewBag.RegisterTypes as List<SelectListItem>, new { style = "width:100px",@class="form-control" })
                    </td>
                    <td><input class="form-control" style="width:70px;" id="txtRegStartDate_0" type="text" /></td>
                    <td><input class="form-control" style="width:70px;" id="txtRegEndDate_0" type="text" /></td>
                    <td><input class="form-control" style="width:50px;" id="txtNoOfSeatsAvilable_0" type="text" /></td>
                    <td><input class="form-control" style="width:70px;" id="txtAmount_0" type="text" /></td>
                    <td><input class="form-control" type="checkbox" id="chkPromotionCode_0" /></td>
                    <td><input class="btn btn-primary" type="button" id="btnAddNew" value="Add New" /></td>
                </tr>                
            </tbody>
        </table>
    </div>
    <hr />

    <input type="button" class="btn btn-success btn-lg" id="btnSubmit" name="btnSubmit" value="Submit" />
    <input type="hidden" id="hdnCountOfRows" name="hdnCountOfRows" />
}

<script type="text/javascript">

        $(document).ready(function () {
        
        //getting the checkbox value
        if ($("#chkPromotionCode_0").is(':checked')) {
            $("#chkPromotionCode_0").attr('checked', false);
        }
        //initializing date pickers.
        $("#txtRegStartDate_0").datepicker();
        $("#txtRegEndDate_0").datepicker();
        var count = 1;
        
            //creating dynamic new form when click on 'Add New' button
            //and appending to table
        $("#btnAddNew").on("click", function () {
            //count=1;
            $("#tblEventAttendeeFee").append('<tr id="row_'+count+'">'
            + '<td><select class="form-control" style="width:100px;" id="ddlRegTypes_' + count + '" name="ddlRegType_' + count + '"/></select></td>'
            + '<td><input class="form-control" style="width:70px;" type="text" id="txtRegStartDate_' + count + '" name="txtRegStartDate_' + count + '"/></td>'
            + '<td><input class="form-control" style="width:70px;" type="text" id="txtRegEndDate_' + count + '" name="txtRegEndDate_' + count + '"/></td>'
            + '<td><input class="form-control" style="width:50px;" type="text" id="txtNoOfSeatsAvilable_' + count + '" name="txtNoOfSeatsAvilable_' + count + '"/></td>'
            + '<td><input class="form-control" style="width:70px;" type="text" id="txtAmount_' + count + '" name="txtAmount_' + count + '"/></td>'
            + '<td><input class="form-control" type="checkbox" id="chkPromotionCode_' + count + '" /></td>'
            + '<td><input class="btn-remove btn btn-danger" type="button" id="' + count + '" name="' + count + '" value="Remove" /></td>'
            + '</tr>');

            //copying dropdown list data to a variable
            var ddldata = $("#ddlRegTypes_0").html();
            //appending dropdownlist data to dynamically created Dropdownlist
            $("#ddlRegTypes_" + count + "").append(ddldata);
            //initializing dynamically created datepickers
            $("#txtRegStartDate_"+count+"").datepicker();
            $("#txtRegEndDate_"+count+"").datepicker();
            count++;
            $("#hdnCountOfRows").val(count);
        });
        $("#hdnCountOfRows").val(count);

        //Removing dynamic form when click on remove button.
        $(document).on("click", ".btn-remove", function () {
            count=count - 1;
            var button_id = $(this).attr("id");
            $("#row_" + button_id + "").remove();
        });
    });

    //Saving data ww entered to a javascript list 
    $("#btnSubmit").unbind().click(function () {
        var DataList = [];
        var count = $("#hdnCountOfRows").val();
        for (var i = 0; i < count; i++) {
            if ($("#chkPromotionCode_" + i).prop('checked') == true) {
                $("#chkPromotionCode_" + i).val(true);
            }
            else {
                $("#chkPromotionCode_" + i).val(false);
            }
            if ($("#ddlRegTypes_" + i).val() && $("#txtRegStartDate_" + i).val() && $("#txtRegEndDate_" + i).val() && $("#txtNoOfSeatsAvilable_" + i).val() && $("#txtAmount_" + i).val())
                DataList.push({ RegisterTypeCode: $("#ddlRegTypes_" + i).val(), RegStartDate: $("#txtRegStartDate_" + i).val(), RegEndDate: $("#txtRegEndDate_" + i).val(), NoOfSeatsAvilable: $("#txtNoOfSeatsAvilable_" + i).val(), Amount: $("#txtAmount_" + i).val(), PromotionCodeRequired: $("#chkPromotionCode_" + i).val()});
        }
        if ((DataList != null && DataList.length == 0) || DataList == null) {
            alert('please select RegType, Start date, End date, No of seats avilable and Amount for atlease one entry ');
            return false;
        }
        else {
            //displaying list data in alert box
            alert(JSON.stringify(DataList));
        }
        
        @*
            //We can send data to Controller using ajax
        DataList = JSON.stringify({ 'DataList': DataList });
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: 'AddEventAttendeeFee',
            data: DataList
        }).done(function (Result) {
            if (Result == true) {
                alert("Records Inserted successfully");
                var eventid = $("#hdnEventID").val();
                document.forms[0].action = "@Url.Action("EventFeeLookup", "Admin")?eventid=" + eventid;
                document.forms[0].submit();
            }
        }).error(function (Result) {
            alert("Insertion failed");
        });
            *@
    });

</script>
Note:
1.If your form contains more fields(ex:above 10 fields) it is recommend to create dynamic form by taking a Partial View.because it is not recommend in coding standards.
2.Finally after clicking submit button saved data will come in alert box for two rows like below.

3.Download source code for this application from here.. Download.

Conclusion:
I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Monday, 3 July 2017

How to display custom no records message in jqgrid

20:43:00 Posted by raviteja swayampu No comments
Hi every one welcome again.In this tutorial i am going to explain how to hide jqgrid when there is no records and display an message that states 'no records found'.Recently i come across this problem.I searched for online but i did not find suitable solution to my problem.after searching sometime finally i found this solution.I want to share this solution to help the people who also work with jqgrid.

This solution is understandable for developers who have knowledge on jqgrid.If you are newbie then refer this link to know about jqgrid.Implementing jqgrid in asp.net mvc.

I implemented jqgrid with below code..


JqController.cs:
using System;
using System.Data;
using System.Linq;
using System.Data.Entity;
using System.Web.Mvc;
using Jqgrid.Models;
using System.Collections.Generic;

namespace Jqgrid.Controllers
{
    public class JqgridController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        //sample data to display in jqgrid
        public List GridData()
        {
            List userlist = new List()
            {
                new User {Id=1,Name="Raviteja",Address="Ongole",DOB="10-02-1994",Phone=1200439495 },
                new User {Id=2,Name="Koti",Address="Addanki",DOB="5-02-2017",Phone=1200439495 },
                new User {Id=3,Name="Sridhar",Address="Nellore",DOB="6-02-1997",Phone=1200439495 },
                new User {Id=4,Name="Rajkumar",Address="Kammam",DOB="9-02-1991",Phone=1200439495 },
                new User {Id=5,Name="Avinash",Address="Ongole",DOB="2-02-1994",Phone=1200439495 }
            };
            return userlist;
        }
        //Method to display jqgrid
        public JsonResult GetValues(string sidx, string sord, int page, int rows)  //Gets the todo Lists.
        {
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            List userlist = new List();
            userlist = GridData();
            var Results = userlist.Select(
                    a => new
                    {
                        a.Id,
                        a.Name,
                        a.Phone,
                        a.Address,
                        a.DOB,
                    });
            int totalRecords = Results.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if (sord.ToUpper() == "DESC")
            {
                Results = Results.OrderByDescending(s => s.Id);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            else
            {
                Results = Results.OrderBy(s => s.Id);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = Results
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
    }
}
Index.cshtml:
@{
    ViewBag.Title = "Jqgrid";
}

<h2>Jqgrid Application</h2>
<div id="griddisplaylookup">
    <table id="grid"></table>
    <div id="pager"></div>
</div>

<div id="NoRecordsFound" style="display:none;text-align:center;color:red;">No records found</div>

@*<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">*@
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.jqGrid.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/myjqgrid.js"></script>

1.Jqgrid provides an event called 'gridComplete' will be fired after grid loading completed.
2.I implemented logic to hide and display the 'No records found' message in call back function of this event like below.
//this event fires when grid completes..
        gridComplete: function () {
            debugger;
            //i am getting the number of records in grid...
            var records = parseInt(jQuery("#grid").jqGrid('getGridParam', 'records'));
            //if number of records are 0 then grid will be hided
            //and a div element will showed with 'No records found'
            if (records > 0) {
                $("#griddisplaylookup").show();
                $("#NoRecordsFound").hide();
            }
            else if (isNaN(records)) {
                $("#griddisplaylookup").hide();
                $("#NoRecordsFound").show();
            }
            else {
                $("#griddisplaylookup").hide();
                $("#NoRecordsFound").show();
            }
        }
3.The full script code is like below..



$(function () {
    debugger;
    $("#grid").jqGrid({
        url: "/Jqgrid/GetValues",
        datatype: 'json',
        mtype: 'Get',
        //table header name 
        colNames: ['Id', 'Name', 'Phone', 'Address', 'DOB'],
        //colModel takes the data from controller and binds to grid 
        colModel: [
            { key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
            { key: false, name: 'Name', index: 'Name', editable: true },
            { key: false, name: 'Phone', index: 'Phone', editable: true },
            { key: false, name: 'Address', index: 'Address', editable: true },
            { key: false, name: 'DOB', index: 'DOB', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' } }],

        pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [10, 20, 30, 40],
        height: '100%',
        viewrecords: true,
        caption: 'Jq grid sample Application',
        emptyrecords: 'No records to display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        },
        autowidth: true,
        multiselect: false,
        //this event fires when grid completes..
        gridComplete: function () {
            debugger;
            //i am getting the number of records in grid...
            var records = parseInt(jQuery("#grid").jqGrid('getGridParam', 'records'));
            //if number of records are 0 then grid will be hided
            //and a div element will showed with 'No records found'
            if (records > 0) {
                $("#griddisplaylookup").show();
                $("#NoRecordsFound").hide();
            }
            else if (isNaN(records)) {
                $("#griddisplaylookup").hide();
                $("#NoRecordsFound").show();
            }
            else {
                $("#griddisplaylookup").hide();
                $("#NoRecordsFound").show();
            }
        }
        //pager-you have to choose here what icons should appear at the bottom
        //like edit,create,delete icons
    }).navGrid('#pager', { edit: true, add: true, del: true, search: false, refresh: true });
});
4.Now grid with records look like below...
5.The grid will like below if there is no records in jqgrid.(i commented data in controller).

Download source code for this application from here...Download

Conclusion:
I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].