Sunday, 30 November 2014

FileLoadException was unhandled by user code(Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040))

I'm getting following error when I'm using NewtonSoft.Json with WebApi client. 

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Solution: To everyone having problems with Newtonsoft.Json v4.5 version try using this in web.config or app.config:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json"
            publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>

  </runtime>

Thursday, 6 November 2014

Skip and Take record from 'N' to 'M' in SQL Sever

Hi Guys! In last weekend I was thinking let's write something on SQL Server database. So I was just thinking which topics should I covered or on which topics should I write...... thinking......thinking...., suddenly I got an idea lets write on some common questions or something which will more efficient during ours interviews or related to our project. So I've decided let's write on  "How to skip N to M records during table record selection?", I think this is very common question., So let's see how to do that in SQL Server database. 

Scenario: Suppose that, I've a table ABC and this table having following records,

Table: ABC
Id          Name       Address
1           Peter          XYZ
2           John           PQR
3           Scott B'u     CBT
4          Allen           123-TPO
5          Belly           986-PYT


So here question is Do we select 2 rows starting from 3rd row?

Solution:  I think the most elegant is to use the ROW_NUMBER function to resolve this problem.

WITH NumberedMyTable AS
(
    SELECT
        Id,
        Value,
        ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber
    FROM
        MyTable
)
SELECT
    Id,
    Value
FROM
    NumberedMyTable
WHERE
    RowNumber BETWEEN @From AND @To
So in this way you can resolve this problem. Please feel free comment for 
any assistance or query.

11 Crazy World Records That Only Indians Could Have Held.

Indians are a competitive breed, which is proven by their obsession of breaking records. According to Guinness Indians rank 3rd in setting world records behind USA and UK and what’s interesting is the bizarre nature of these records. Here are a few world record set by Indians which cross the threshold of conventional.
For more information please follow the following link. http://www.rookiestew.com/11-crazy-world-records-that-only-indians-could-have-held/

Wednesday, 5 November 2014

Exception: ASP.NET Web API - No 'MediaTypeFormatter' is available to read an object of type T

Questions: ASP.NET Web API - No 'MediaTypeFormatter' is available to read an object of type T where T is a primitive type or class type.
Scenarios: I've created a WebAPI as follows:

[RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
        private AuthRepository _repository;

        public AccountController()
        {
            _repository = new AuthRepository();
        }

        // POST  api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        [HttpPost]
        public async Task<IHttpActionResult> Register(UserModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            IdentityResult result = await _repository.RegisterUser(model);
            IHttpActionResult errorResult = GetErrorResult(result);
            if (errorResult != null)
            {
                return errorResult;
            }
            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _repository.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Private Methods
        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }
            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
                if (ModelState.IsValid)
                {
                    return BadRequest();
                }
                return BadRequest(ModelState);
            }
            return null;
        }
        #endregion

    }
Now I calling this API register method through the POSTMAN Extension like as follows:
But I'm getting "ASP.NET Web API - No 'MediaTypeFormatter' is available to read an object of type T where T is a primitive type or class type" error. Please suggest me where am I doing wrong.

Answer/Solutions: Actually 'MediaTypeFormatter' is responsible for this exception when you didn't included media type in Request Header. So to fix the problem just add MediaType in header like this way.
{
content-type: "application/json"
}
or in case of POSTMAN extension you can add as follows:

I hope it might be helpful. Please feel free comment for any suggestion.

Monday, 3 November 2014

StyleBundle Index was outside the bounds of the array

Problem Scenarios: I want to include all files in directory like this:
bundles.Add(new StyleBundle("~/Content/ABCJS").Include(
    "~/Content/simpliq/*.js"
));
But I got this error Index was outside the bounds of the array
and red line is:
@Styles.Render("~/Content/ABCJS")
Solution: So there is very simple way you can resolve this problem by just updating two package WEB OPTIMIZATION and WEBGREASE using package manager console or nuget page.

Wednesday, 27 August 2014


How to integrate PayPal in Asp.Net
This article discusses integration of PayPal payment gateway in asp.net web application. Nowadays PayPal is the most popular payment gateway worldwide because it is totally free to integrate and PayPal does not charge anything for opening an account, you will pay PayPal when you get paid. And the amount is also lower than other payment gateways.
For this topic I’ve trouble too much on internet but I could not found a single crucial article which explained all of the required part to integration PayPal payment gateway for naïve users. In this article I will explain thoroughly all the requirements and techniques for integrating PayPal in your web application step by step.
Basic requirement to Integration PayPal payment in Asp.Net application:
1.       Should have PayPal Sandbox account (URL: https://developer.paypal.com/ ) for developer testing code.
2.       Should have one buyer (Personal Account) and one seller account (Business Account) PayPal account.
3.       PayPal API token (Signature) key
4.       PayPal business account email id
5.       Integrate PayPal payment with Application
Now let’s start step by step work to integrate PayPal payment.
Create PayPal account on PayPal Sandbox: Basically, PayPal provides an environment to developer that how they can integrate PayPal payment in their website. So just open URL: https://developer.paypal.com/ and click on SignUp option.


Fill all the required information and click on button ‘Agree and Submit’,

Now first step has been completed and I am moving on second step (Create buyer and seller or personal and business account). After logged in PayPal payment panel, there is a preconfigured account option visible through which you can complete second step..   



Now check out these two account information by selecting Test Account option logged in panel.


Now you have been completed second step successfully. Now I’m moving on third step (Having a valid PayPal API Token Key).

Now select ‘API and Payment Card Credential’ option from PayPal home.
Here you’ve a valid email id too, so all of the necessary things are over related with PayPal Account and payment API. Now I’m moving on Integration step.
So just create your web application in which you’re going to integrate PayPal payment. Here I’m just creating an application which contains some product information such as Product description, product price, product name and user can purchase it, simply, by clicking on ‘BuyNow’ button.
Aspx Page Code:
 <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div>
        <table width="700" align="center" cellpadding="0" cellspacing="0">
            <tr>
                <td height="60">
                    <b>Paypal Integration in ASP.NET</b>
                </td>
            </tr>
            <tr>
                <td height="40" align="center">
                    <asp:GridView ID="gvPayPal" runat="server"AutoGenerateColumns="False" OnRowCommand="gvPayPal_RowCommand"
                        BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"BorderWidth="1px"
                        CellPadding="3" CellSpacing="2">
                        <RowStyle ForeColor="#8C4510" BackColor="#FFF7E7" />
                        <Columns>
                            <asp:TemplateField HeaderText="Product Name">
                                <ItemTemplate>
                                    <asp:Label ID="lblName" runat="server"Text='<%#Eval("prodName") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Product Description">
                                <ItemTemplate>
                                    <asp:Label ID="lblDescription" runat="server"Text='<%#Eval("prodDesc") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Product price">
                                <ItemTemplate>
                                    <asp:Label ID="lblProductPrice" runat="server"Text='<%#Eval("prodPrice") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Buy Now">
                                <ItemTemplate>
                                    <asp:ImageButton ID="ImageButton1" runat="server"ImageUrl="~/images/buy.png"
                                       Width="64" Height="64" CommandName="buy"CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                        <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True"ForeColor="White" />
                        <HeaderStyle BackColor="#A55129" Font-Bold="True"ForeColor="White" />
                        <SortedAscendingCellStyle BackColor="#FFF1D4" />
                        <SortedAscendingHeaderStyle BackColor="#B95C30" />
                        <SortedDescendingCellStyle BackColor="#F1E5CE" />
                        <SortedDescendingHeaderStyle BackColor="#93451F" />
                    </asp:GridView>
                </td>
            </tr>
        </table>
        <!-- PayPal Logo -->
        <table border="0" cellpadding="10" cellspacing="0" align="center">
            <tr>
                <td align="center">
                </td>
            </tr>
            <tr>
                <td align="center">
                    <a style="cursor:pointer;" title="Paypal payment gateway center"onclick="javascript:window.open('https://www.paypal.com/cgi-bin/webscr?cmd=xpt/Marketing/popup/OLCWhatIsPayPal-outside','olcwhatispaypal','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=400, height=350');">
                        <imgsrc="https://www.paypal.com/en_US/i/bnr/horizontal_solution_PPeCheck.gif" border="0"
                            alt="Solution Graphics"></a>
                </td>
            </tr>
        </table>
        <!-- PayPal Logo -->
    </div>
</asp:Content>
CS Page Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection Con = newSqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    DataRow dr;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //Add some column to datatable display some products information           
            dt.Columns.Add("prodName");
            dt.Columns.Add("prodDesc");
            dt.Columns.Add("prodPrice");

            //Add rows with datatable and bind in the grid view
            dr = dt.NewRow();
            dr["prodName"] = "MindStick Cleaner";
            dr["prodDesc"] = "Cleans all system dummy data";
            dr["prodPrice"] = "$100.00";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["prodName"] = "MindStick DataConverter";
            dr["prodDesc"] = "Helps to import export data in different format";
            dr["prodPrice"] = "$120.00";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["prodName"] = "MindStick SurveyManager";
            dr["prodDesc"] = "Helps creating survey page with specified format dll";
            dr["prodPrice"] = "$140.00";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["prodName"] = "MindStick TeraByte Importer";
            dr["prodDesc"] = "Data transfer utility";
            dr["prodPrice"] = "$30.00";
            dt.Rows.Add(dr);

            gvPayPal.DataSource = dt;
            gvPayPal.DataBind();
        }
    }

    protected void gvPayPal_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "buy")
        {
            ImageButton ib = (ImageButton)e.CommandSource;
            int index = Convert.ToInt32(ib.CommandArgument);
            GridViewRow row = gvPayPal.Rows[index];

            //Get each Column label value from grid view and store it in label
            Label pName = (Label)row.FindControl("lblName");
            Label pDescription = (Label)row.FindControl("lblDescription");
            Label pPrice = (Label)row.FindControl("lblProductPrice");

            //Here store that person name who are going to make transaction
            Session["user"] = "Arun Singh";

            // make query string to store logged in user information in sql server table         
            string query = "";
            query = "insert into purchase(pname,pdesc,price,uname) values('" + pName.Text + "','" + pDescription.Text + "','" + pPrice.Text.Replace("$""") + "','" + Session["user"].ToString() + "')";
            Con.Open();
            cmd = new SqlCommand(query, Con);
            cmd.ExecuteNonQuery();
            Con.Close();

            //Pay pal process Refer for what are the variable are need to send http://www.paypalobjects.com/IntegrationCenter/ic_std-variable-ref-buy-now.html

            string redirectUrl = "";

            //Mention URL to redirect content to paypal site
            redirectUrl += "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" + ConfigurationManager.AppSettings["paypalemail"].ToString();

            //First name I assign static based on login details assign this value
            redirectUrl += "&first_name=Arun_Seller";
           
            //Product Name
            redirectUrl += "&item_name=" + pName.Text;

            //Product Amount
            redirectUrl += "&amount=" + pPrice.Text;

            //Business contact paypal EmailID
            redirectUrl += "&business=arunse_1358772383_biz@gmail.com";

            //Shipping charges if any, or available or using shopping cart system
            redirectUrl += "&shipping=5";

            //Handling charges if any, or available or using shopping cart system
            redirectUrl += "&handling=5";

            //Tax charges if any, or available or using shopping cart system
            redirectUrl += "&tax=5";

            //Quantiy of product, Here statically added quantity 1
            redirectUrl += "&quantity=1";

            //If transactioin has been successfully performed, redirect SuccessURL page- this page will be designed by developer
            redirectUrl += "&return=" +ConfigurationManager.AppSettings["SuccessURL"].ToString();

            //If transactioin has been failed, redirect FailedURL page- this page will be designed by developer
            redirectUrl += "&cancel_return=" +ConfigurationManager.AppSettings["FailedURL"].ToString();

            Response.Redirect(redirectUrl);
        }
    }
} 
Page Design:
To save the product information simply, I’m using a SQL table with following format or design.
USE [MyDatabase]
GO

/****** Object:  Table [dbo].[purchase]    Script Date: 01/27/2013 09:26:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[purchase](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [PName] [nvarchar](100) NULL,
      [PDesc] [nvarchar](100) NULL,
      [Price] [money] NULL,
      [Uname] [varchar](50) NULL,
 CONSTRAINT [PK_purchase] PRIMARY KEY CLUSTERED
(
      [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


 There are some changes are necessary to web.config file, so please make some following changes in your config file.

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="ApplicationServices" connectionString="data source=Arun-PC;Integrated Security=true; Initial Catalog= MyDatabase; User Id= Arun-PC; Password= mindstick;"providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
    </authentication>
    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider"type="System.Web.Security.SqlMembershipProvider"connectionStringName="ApplicationServices" enablePasswordRetrieval="false"enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6"minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"applicationName="/"/>
      </providers>
    </membership>
    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider"type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices"applicationName="/"/>
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"connectionStringName="ApplicationServices" applicationName="/"/>
        <add name="AspNetWindowsTokenRoleProvider"type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
      </providers>
    </roleManager>
  </system.web>
  <appSettings>
    <add key="token" value="An5ns1Kso7MWUdW4ErQKJJJ4qi4-As2ovQR55m2h23ipWTc1rpRXWbGb "/>
    <add key="paypalemail" value="arunse_1358772383_biz@gmail.com"/>
    <!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->
    <add key="PayPalSubmitUrl" value="https://www.sandbox.paypal.com/cgi-bin/webscr"/>
    <add key="FailedURL" value="http://localhost:49666/PayPalIntegration/Failed.aspx"/> <!--Failed Page URL-->
    <add key="SuccessURL" value="http://localhost:49666/Default.aspx"/> <!--Success Page URL-->
  </appSettings>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration> 

Note: Make sure you are logged in the https://developer.paypal.com/  with your email id in the same browser during testing. It only working fine if you logged in such as deduct amount, add amount etc. Only Sandbox site we must logged in developer site during testing but not in live https://www.paypal.com  after hosted it.
Now this is show time, executes web application and clicked on BuyNow button and follow the instruction.

Now I’m clicking on MindStick Cleaner product to purchase.

To make a payment you can use paypal account or any other credit or debit international card. Here I’m using personal account to purchase this product.

After clicking button Login you’ve got some credential notification.

Now accept the term and condition and clicking on button ‘Agree and Continue’.

Now pay the amount and wait.

Your amount has been payed or debited. There will be three options visible after successfully payment, that options are Return to ArunSeller Test Store, Go to Paypal account overview and add funds from your bank. When you clicked on ArunSeller Test Store then it will return you on success URL page which are you specified in web.config file. Let’s have look of these GUI.
Arun Seller Test Store:
Go to Paypal account overview:
Add funds from your bank:
I hope this article is helping you to know about integrate PayPal in your website.