Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 
Showing posts with label ASP.NET MVC 4. Show all posts
Showing posts with label ASP.NET MVC 4. Show all posts

Download: ASP.NET mvc4: Get response from authorize.net after payment (Auto redirect)

Tuesday

                 In this post we will learn how to get response from Authorize.Net credit card payment using ASP.NET MVC4

One of my client projects I need to implement Authorize.net payment gateway. So just implemented using SIM (Server Integration Method). But my client wants, if the payment getting success then shown a custom receipt page and save the transaction details in to our own database. In other case if the payment getting fail then provides repayment option.

In SIM method this is not possible (or not advisable) because we using “x_relay_response” to get response from Authorize.net. Note,this is just relay the url, not redirect to the result page. And URL always points to the https://test.authorize.net/gateway/transact.dll. And the response time also only 10 seconds. If your server not responds within 10 seconds then you get time out error like

“An error occurred while trying to report this transaction to the merchant. An email has been sent to the merchant informing them of the error. The following is a result of the attempt to charge your credit card.”

This error indicates that Authorize.Net is unable to connect to the page that you have specified as your relay response URL. To avoid this kind of errors you need to go with Authorize.net’s another one integration method AIM (Advanced Integration Method)


You can get more about AIM method from here http://www.authorize.net/support/AIM_guide.pdf

Implement  AIM :
First create a sandbox account in Authorize.Net. https://developer.authorize.net/sandbox/. After you registered you will get the API Credentials

API Login ID
Transaction Key
Secret Question

Create you view page as per your requirement. Here I'm taking from Authorize.net default payment screen



Then add that details  into your web.config file


<!-- Payment Authorize.NET - Begins --> <add key="Payment.AuthLoginID" value="XXXXXXXXXX" /> <add key="Payment.AuthTransactionKey" value="XXXXXXXXX" /> <add key="Payment.TestMode" value="true" /> <add key="Payment.URL" value="https://test.authorize.net/gateway/transact.dll" /> <!--<add key="Payment.URL" value="https://secure.authorize.net/gateway/transact.dll" />--> <!-- Payment Authorize.NET - End -->


Then call the following function into your post method


private string AuthorizePayment(PaymentDataModel payDataModel)
        {
            
            string AuthNetVersion = "3.1"; // Contains CCV support
            string AuthNetLoginID = System.Configuration.ConfigurationManager.AppSettings["Payment.AuthLoginID"].ToString();
            string AuthNetTransKey = System.Configuration.ConfigurationManager.AppSettings["Payment.AuthTransactionKey"].ToString();
            string AuthNetMode = System.Configuration.ConfigurationManager.AppSettings["Payment.TestMode"].ToString();

            WebClient objRequest = new WebClient();
            System.Collections.Specialized.NameValueCollection objInf = new System.Collections.Specialized.NameValueCollection(30);
            System.Collections.Specialized.NameValueCollection objRetInf = new System.Collections.Specialized.NameValueCollection(30);
            byte[] objRetBytes;
            string[] objRetVals;
            string retMessage;

            objInf.Add("x_version", AuthNetVersion);
            objInf.Add("x_delim_data", "True");
            objInf.Add("x_login", AuthNetLoginID);
            // objInf.Add("x_password", AuthNetPassword);
            objInf.Add("x_tran_key", AuthNetTransKey);
            objInf.Add("x_relay_response", "False");

            // Switch this to False once you go live
            objInf.Add("x_test_request", AuthNetMode);

            objInf.Add("x_delim_char", ",");
            objInf.Add("x_encap_char", "|");

            // Billing Address
            objInf.Add("x_first_name", payDataModel.FirstName);
            objInf.Add("x_last_name", payDataModel.LastName);
            objInf.Add("x_address", payDataModel.Address);
            objInf.Add("x_city", payDataModel.City);
            objInf.Add("x_state", payDataModel.State);
            objInf.Add("x_zip", payDataModel.ZIP);
            objInf.Add("x_country", payDataModel.Country);
            objInf.Add("x_email", payDataModel.Email);
            objInf.Add("x_fax", payDataModel.Fax);
            objInf.Add("x_phone", payDataModel.Phone);

            objInf.Add("x_description", payDataModel.Description);

            // Card Details
            objInf.Add("x_card_num", payDataModel.CardNumber);
            objInf.Add("x_exp_date", payDataModel.CardExpiryDate);

            // Authorisation code of the card (CCV)
            objInf.Add("x_card_code", payDataModel.CCV);

            objInf.Add("x_method", "CC");
            objInf.Add("x_type", "AUTH_CAPTURE");
            objInf.Add("x_amount", payDataModel.Amount);

            // Currency setting. Check the guide for other supported currencies
            objInf.Add("x_currency_code", "USD");

            try
            {
                // Pure Test Server
                objRequest.BaseAddress = System.Configuration.ConfigurationManager.AppSettings["Payment.URL"].ToString().Trim();

                objRetBytes = objRequest.UploadValues(objRequest.BaseAddress, "POST", objInf);
                objRetVals = System.Text.Encoding.ASCII.GetString(objRetBytes).Split(",".ToCharArray());

                if (objRetVals[0].Trim(char.Parse("|")) == "1")
                {
                    // Returned Authorisation Code
                    ViewBag.AuthNetCode = objRetVals[4].Trim(char.Parse("|"));
                    // Returned Transaction ID
                    ViewBag.AuthNetTransID = objRetVals[6].Trim(char.Parse("|"));
                    return retMessage = "1";
                }
                else
                {
                    // Error!
                    retMessage = objRetVals[3].Trim(char.Parse("|")) + " (" + objRetVals[2].Trim(char.Parse("|")) + ")";

                    if (objRetVals[2].Trim(char.Parse("|")) == "44")
                    {
                        // CCV transaction decline
                        retMessage += "Our Card Code Verification (CCV) returned the following error: ";

                        switch (objRetVals[38].Trim(char.Parse("|")))
                        {
                            case "N":
                                retMessage += "Card Code does not match.";
                                break;
                            case "P":
                                retMessage += "Card Code was not processed.";
                                break;
                            case "S":
                                retMessage += "Card Code should be on card but was not indicated.";
                                break;
                            case "U":
                                retMessage += "Issuer was not certified for Card Code.";
                                break;
                        }
                    }

                    if (objRetVals[2].Trim(char.Parse("|")) == "45")
                    {
                        if (retMessage.Length > 1)
                            retMessage += "<br />n";

                        // AVS transaction decline
                        retMessage += "Our Address Verification System (AVS) returned the following error: ";

                        switch (objRetVals[5].Trim(char.Parse("|")))
                        {
                            case "A":
                                retMessage += " the zip code entered does not match the billing address.";
                                break;
                            case "B":
                                retMessage += " no information was provided for the AVS check.";
                                break;
                            case "E":
                                retMessage += " a general error occurred in the AVS system.";
                                break;
                            case "G":
                                retMessage += " the credit card was issued by a non-US bank.";
                                break;
                            case "N":
                                retMessage += " neither the entered street address nor zip code matches the billing address.";
                                break;
                            case "P":
                                retMessage += " AVS is not applicable for this transaction.";
                                break;
                            case "R":
                                retMessage += " please retry the transaction; the AVS system was unavailable or timed out.";
                                break;
                            case "S":
                                retMessage += " the AVS service is not supported by your credit card issuer.";
                                break;
                            case "U":
                                retMessage += " address information is unavailable for the credit card.";
                                break;
                            case "W":
                                retMessage += " the 9 digit zip code matches, but the street address does not.";
                                break;
                            case "Z":
                                retMessage += " the zip code matches, but the address does not.";
                                break;
                        }
                    }

                    // strError contains the actual error
                    ViewBag.ErrorMsg = retMessage;
                    return retMessage;
                }
            }
            catch (Exception ex)
            {
                return retMessage = ex.Message;
            }
        }
That's it. You can download sample  for get response from authorize.net payment gateway using asp,net mvc project. Please share this post to social media if its is help you and also don't forgot to write some comments. 

ASP.NET MVC: Action Names & NonAction method (ambiguous between error the action methods)

MVC Case Sensitivity & Action Names & NonAction Attribute
                                                  In MVC URLs not being case sensitive. For example if you have the request “Home/About” this goes to HomeController and About action, as well as hOmE/AbOUT is going to the same controller and same action method.

Suppose if you have two about action methods in the same controller with different cases such as:

public class HomeController:Controller{
    public ViewResult About()    {
        return View();
   }
    public ViewResult aBOut()
    {
        return View();
    }
}

You will get "ambiguous between the action methods ".
when I call action method About using following url http://your applicationname/Index/ABOUT I got this server error



This means, The framework doesn't determine which "about" function to call, and throws the exception telling that the call is ambiguous. To fix this problem is to change the action name. If for some reason you don’t want to change the action name, and one of these function is not an action, then you can decorate this non action method with NonAction attribute. 

Example:

[NonAction]
public ActionResult aBOut()
{
   return View();
}
Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET MVC 4: Error during serialization or deserialization using the JSON / Changing maxJsonLength property in web.config

JSON serialization error [maxJsonLength property.]
                 In my previous project I need to retrieve ticket from Web service.When I request the web service it return a ticket as JSON format.Some time I need to retrieve more than 10 lacks ticket per requet.In that time I got the following error.

Error:
Exception information:
Exception type: InvalidOperationException
Exception message: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.


Solution:
To solve this issue We need to set Maximum allowed length of json response in Web.config file 
The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k).

You can set the MaxJsonLength property on your web.config like 

<configuration> 
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration> 
Please share this post with your friends. If it's useful to you. Thanks!.

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies in asp.net mvc 4

Sunday

Handling Circular References ASP.NET MVC 4 Json Serialization - asp.net mvc 4
                                     In this post I will explain Circular Reference Serialization Error in MVC Entity frame work. In my latest project I need to get data from database for purpose of Autocomplete.So I need data as JSON format.

When I request the “http://localhost:xxxx/Student/GetStudentJson”

               
My http GetStudentJson Method is bellow
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class StudentController : Controller
    {
        private SchoolDBContext db = new SchoolDBContext();

        public JsonResult GetStudentJson()
        {
      var students = db.Students .Include(s => s.Standard).Include(s => s.StudentAddress);

            return Json(students, JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


My mode class are following
Student.cs
using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class Student
    {
        public Student()
        {
            this.Courses = new List<Course>();
        }

        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public int StandardId { get; set; }
        public virtual Standard Standard { get; set; }
        public virtual StudentAddress StudentAddress { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
    }
}
Standard.cs

using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class Standard
    {
        public Standard()
        {
            this.Students = new List<Student>();
        }

        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }
        public virtual ICollection<Student> Students { get; set; }
    }
StudentAddress.cs

using System;
using System.Collections.Generic;

namespace MvcApplication1.Models
{
    public class StudentAddress
    {
        public int StudentID { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public virtual Student Student { get; set; }
    }
}
Now I will explain How to solve this problem In this error occur because the student entity class includes Standard and StudentAddress class entity. But In GetStudentJson Method tries to convert only Student class object to Json.So that I got the above error. To solve this error we rewrite the GetStudentJson method

Solution One

public JsonResult GetStudentJson()
   {
            db.Configuration.ProxyCreationEnabled = false;
            var students = db.Students;
            return Json(students, JsonRequestBehavior.AllowGet);
   }
The Out Put is Look like bellow
  [{"StudentID":1,"StudentName":"John","StandardId":1,"Standard":null,
     "StudentAddress":null,"Courses":[]}]


Solution Two
In this type we get selected error

 public JsonResult GetStudentJson()
   {
            var students = from s in db.Students select new { s.StudentID, s.StudentName,s.StandardId };

            return Json(students, JsonRequestBehavior.AllowGet);
   }
Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET MVC 4: create dropdownlist from an enum (Enumeration helper)

Thursday

                                                      In one of my previous article I'm explained how to create  a dropdownlist from a controller class. And in this post I'm going to explaine how to create a dropdownlist from an enum.

First create  a helper ennum class with your dropdown items. Here I'm using three options "Daily","Quickly","Weekly".

using System.Reflection;
using System.ComponentModel;
namespace EnumHtmlHelper.Helper
{
    public static class EnumDropDown
    {
        public static string GetEnumDescription<TEnum>(TEnum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.
                   GetCustomAttributes(typeof(DescriptionAttribute), false);
            if ((attributes != null) && (attributes.Length > 0))
                return attributes[0].Description;
            else
                return value.ToString();
        }
        public enum Interval
        {
            [Description("Daily")]
            D = 1,
            [Description("Quick")]
            Q = 2,
            [Description("Weekly")]
            W = 3
        } 
    }    
}

Then add the following code into your (Razor) view to get the dropdown list.

<div class="ddlSmall">
 @{
     var EnumInterval = from Helper.EnumDropDown.Interval n in Enum.GetValues(typeof(Helper.EnumDropDown.Interval))
     elect new SelectListItem
     {
          Value = n.ToString(),
          Text = EnumDropDown.GetEnumDescription(n),
     };
    }
</div>

The output of the above code look like this in page source

<select id="Interval" name="Interval">
         <option value="D">Daily</option>
         <option value="Q">Quick</option>
         <option value="W">Weekly</option>
</select>
The output of the above code look like this in web page


Please share this post with your friends. If it's useful to you. Thanks!.

ASP.NET - MVC 4: How to debug asp.net mvc 4 source code / application in VS 2010?

Wednesday

ASP.NET: MVC 4 Debugging applications/Projects in visual studio 2010:

Below the steps for debug your asp.net mvc 4 source code using visual studio 2010 ultimate:


  1. First close all Visual Studio instances. 
  2. Ensure that you are a member of the local debuggers group (Control Panel, Administrative Tools, Local Security Policy, Security Settings, Local Poliies, User Rights Assignment,  Debug Programs).  
  3. Change the following registry key(got start type “regedit” in “Search program and files”  and click regeedit It will open “registry edit” window) HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger\DisableAttachSecurityWarning from 0 to 1. 
  4. Go to IIS Crate a Virtual directory for your web application 
  5. Open the project in VS editor. Right click in the project and click property, it will open the property window 
  6. Click on Web,on Server tag select Use Custom web service and enter virtual path of our web application
  7. Open virtual path in Any one Browser
  8. In VS IDE click Debug tag and click Attached to process and select W3wp.exe and click attach button 
  9. Then put break point(s) and click start  with debugging. 



ASP.NET: MVC 4 Razor View Get Confirm Message Before Delete

ASP.NET MVC 4: Confirmation alert before delete:
This is the sample code for display a confirmation alert message before  delete an employe detail.
                                               
                                     
In View:

@Html.ActionLink("Delete", "DeleteEmp", new { id = item.Id }, new { onclick = " return DeleteConfirm()" })
In Script:

function DeleteConfirm(){
        if (confirm("Are you sure want to delete record"))
            return true;
        else
            return false;     
    }
In Controller:

   public ActionResult DeleteEmp(int id)
   { 
            var empDelete = (from emp in dbml.M_Employees  where emp.Id == id   select emp).Single(); 
            dbml.M_Employees.DeleteOnSubmit(empDelete); 
            dbml.SubmitChanges(); 
            return RedirectToAction("Index"); 
   }

ASP.NET MVC 4 - Solution: The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Class". or "Scripts"

Friday

ASP.Net MVC 4 Razor: Section Defined But Not Rendered Error:
                            In asp.net mvc 4 project development  you may face an error like "The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Class". and / or "The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "scripts".




It means that you have no definition for  a section in your master Layout.cshtml, but you try to get that section from your View. To resolve this problem, check your view.cshtml has some thing like this

@section Class{
}


and / or

@section scripts{
}


If yes, you must define a section in your master Layout.cshtml like this
To fix this section defined but bot rendered error you just add this lines before the end of body tag in your Layout.cshtml

 @RenderSection("scripts", required: false)

 @RenderSection("Class", required: false)



Please share this post if it's useful to you. Thanks!.

Source: How to create a drop down list in asp.net mvc4

Thursday

Bind data to dropdownlist in Asp.net MVC4:

           This is the basic code for creating a page with a dropdown.

The difference between clasic asp.net web forms and mvc is that mvc doesn't have those events like "selectedIndexChanged", because all the controls are pure html controls.

// in view page model


 public class DropdownViewModel
    {
        public SelectList ProductList { get; set; }
    }

// in controller action 

   public ActionResult Create()
        {
            DropdownViewModel model = new DropdownViewModel();

            List<SelectListItem> listItems = new List<SelectListItem>();
            listItems.Add(new SelectListItem()
            {
                Value = "1",
                Text = "Product 1"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "2",
                Text = "Product 2"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "3",
                Text = "Product 3"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "4",
                Text = "Product 4"
            });
            listItems.Add(new SelectListItem()
            {
                Value = "5",
                Text = "Product 5"
            });
            model.ProductList = new SelectList(listItems, "Value", "Text");

            return View(model);
        }

//And finally this is in view page 

@model YourApplication.Models.DropdownViewModel
 @Html.DropDownList("product", Model.ProductList)

And this is the output of the above code


Create a Foreign Key relationship using Code First Entity Framework and asp.net MVC4

Saturday

Entity Framework Code First: Add a Foreign Key relationship in asp.net MVC 4:

When building an single page application in MVC4 using Entity Framework Code First you might run into the following exception:

Unable to retrieve association information for association 'Models.Product_Parent'. Only models that include foreign key information are supported. See Entity Framework documentation for details on creating models that include foreign key information.

This is due to the way you've defined the relation ships in the dbContext. Lets say me have a dbContextcontaining products which can have child products, you would write the following code:

public class Product
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Product Parent { get; set; }
}
public class ProductContext : DbContext
{
    public DbSet<product> Products { get; set; }
}


This should be enough to let EF know there is a relationship in there, but sadly it's not. We can solving this by following way:

we can create an extra property ParentId give this a ForeighKeyAttribute that links it to the Parent property.

[ForeignKey("Parent")]
public int? ParentId { get; set; }
public virtual Product Parent { get; set; }


 
 
 

RECENT POSTS

Boost

 
Blogger Widgets