Friday, 26 August 2016

Robobank Omnikassa Payment Processing with ASP.NET MVC5 C#

Many websites are using RoboBank Omnikassa Payment Processing. It is very easy to use with your ASP.NET MVC application. Simply follow the following steps and get ready.

Download Code from Here

Step 1:
Create a controller in your web application "RobobankController"
and setup the following constants inside the class

  // Test  
     private const String PostUrl = @"https://payment-webinit.simu.omnikassa.rabobank.nl/paymentServlet";  
     // Production  
     //private const String PostUrl = https://payment-webinit.omnikassa.rabobank.nl/paymentServlet  
     private const String SecurityKey = @"002020000000001_KEY1";  
     private const String MerchantId = @"002020000000001";  
     private const String SecurityKeyVersion = "1";  
     private const String CurrencyCode = "978"; // Euro  
     private const String LanguageCode = "EN"; // Euro    

Step 2:
Create a Modelview inside models "RobobankViewModel"


 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 namespace RoboBankOmniKassa.Models  
 {  
   public class RobobankViewModel  
   {  
     public string OrderID { get; set; }  
     public double Amount { get; set; }  
     public string Response { get; set; }  
   }  
 }  

Step 3:
Create Pay Action

// GET: Robobank
        public ActionResult Pay()
        {
            RobobankViewModel VM = new RobobankViewModel();
            VM.Amount = 500;
            VM.OrderID = DateTime.Now.Ticks.ToString();

            return View(VM);
        }

Step 4: 
Create View for above action.

@model RoboBankOmniKassa.Models.RobobankViewModel

@{
    ViewBag.Title = "Pay";
}

Pay

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() @Html.LabelFor(item => item.Amount) @Html.EditorFor(item => item.Amount) @Html.LabelFor(item => item.OrderID) @Html.EditorFor(item => item.OrderID) < input class="btn btn-default csg_buttonBlue" id="Savedata" type="submit" value="Save" /> }

Step 5:
Handle post request of above view (Create Post Action for Pay)



        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Pay(RobobankViewModel model)
        {
            if(ModelState.IsValid)
            {
                string data = String.Format("merchantId={0}", MerchantId)
              + String.Format("|orderId={0}", model.OrderID)
              + String.Format("|amount={0}", model.Amount)
              + String.Format("|customerLanguage={0}", LanguageCode)
              + String.Format("|keyVersion={0}", SecurityKeyVersion)
              + String.Format("|currencyCode={0}", CurrencyCode)
                    // + String.Format("|PaymentMeanBrandList={0}", "IDEAL")
              + String.Format("|normalReturnUrl={0}", "http://www."+ Request.Url.Host + "/Robobank/RedirectResponse")
              + String.Format("|automaticResponseUrl={0}", "http://www." + Request.Url.Host + "/Robobank/RedirectResponse")
              + String.Format("|transactionReference={0}", model.OrderID + "x" + DateTime.Now.ToString("hhmmss"));

                // Seal-veld berekenen
                SHA256 sha256 = SHA256.Create();
                byte[] hashValue = sha256.ComputeHash(new UTF8Encoding().GetBytes(data + SecurityKey));

                // POST data samenstellen
                NameValueCollection postData = new NameValueCollection();
                postData.Add("Data", data);
                postData.Add("Seal", ByteArrayToHexString(hashValue));
                postData.Add("InterfaceVersion", "HP_1.0");

                // Posten van data 
                byte[] response;
                using (WebClient client = new WebClient())
                    response = client.UploadValues(PostUrl, postData);

                TempData["Response"] = Encoding.UTF8.GetString(response);
                return RedirectToAction("Confirm", "Robobank");

            }

            return View(model);
        }

// Converteer een String naar Hexadecimale waarde
        public string ByteArrayToHexString(byte[] bytes)
        {
            StringBuilder result = new StringBuilder(bytes.Length * 2);
            const string hexAlphabet = "0123456789ABCDEF";

            foreach (byte b in bytes)
            {
                result.Append(hexAlphabet[b >> 4]);
                result.Append(hexAlphabet[b & 0xF]);
            }

            return result.ToString();
        }
        List< KeyValuePair< String, String >> ParseData(String data)
        {
            return (from part in data.Split('|')
                    let key = part.Split('=')[0]
                    let value = part.Split('=')[1]
                    select new KeyValuePair(key, value)).ToList();
        }

        static String GetTransactionStatus(String transactionCode)
        {
            switch (transactionCode)
            {
                case "00":
                    return "SUCCESS";
                case "60":
                    return "PENDING";
                case "97":
                    return "EXPIRED";
                case "17":
                    return "CANCELLED";
            }
            return "FAILED";
        }


Step 6:
Create Confirmation and Return action and Views


        public  ActionResult Confirm(string response)
        {
            ViewBag._Response = TempData["Response"];
            return View();
        }

       
        public ActionResult Report()
        {
            
            return View();
        }

        public ActionResult RedirectResponse()
        {
        
            return View();
        }
        [HttpPost]
        public ActionResult RedirectResponse(string Data,string Seal)
        {
            String data = Data;
            String seal = Seal;

            // Verifieer de Seal
            SHA256 sha256 = SHA256.Create();
            byte[] hashValue = sha256.ComputeHash( new UTF8Encoding( ).GetBytes (data + SecurityKey ) );

            if (seal.ToLower() == ByteArrayToHexString( hashValue).ToLower()) // Seal is goed
            {
                // Lees de gewenste waarden uit de server response
                List< KeyValuePair < String, String >> dataItems = ParseData(data);
                String transactionCode = dataItems.Where(i => i.Key == "transactionReference " ).First().Value;
                var responseCode = dataItems.Where(i => i.Key == "responseCode").First().Value;
                String transactionStatus = GetTransactionStatus( responseCode);
                
                ViewBag._transactionCode = transactionCode;
                ViewBag._transactionStatus = transactionStatus;
            }
            else // Hash BAD
            {
                ViewBag._HashBad = "Invalid response from Rabo OmniKassa server";
            }
            return View();
        }


Step 7:
Create confirm View


    @{
    Layout = null;
    }

    @Html.Raw(ViewBag._Response)


Step 8:
Create Response View



@{
    ViewBag.Title = "RedirectResponse";
}

RedirectResponse

@ViewBag._Url @ViewBag._transactionCode @ViewBag._transactionStatus

@ViewBag._HashBad


Thats all.

Thanks for reading.

Wednesday, 10 February 2016

MS SQL Server Queries

Microsoft SQL Server is a database to store information. Today I am going to spark some light on MS SQL Queries. This article is dedicated to beginners. Please have a look at the queries and cross verify with official documents.

Let's start with basics

1. Create Database: Create a new database with your name

Create database NameofDababase
Create Database SQLDemoDB
2. Use database: Select a database where you want to work.

Use database NameofDatabase
Use database SQLDemoDB
3.  Rename Database: If you want to rename a particular database then use following query

EXEC sp_renamedb 'oldname','newname'
EXEC sp_renamedb 'SQLDemoDB','DemoDB'

Monday, 20 October 2014

Customized login sample in ASP.NET MVC4/5 using SQL Server 2012

Today's I am going to create a customized log in form in asp.net MVC4. This sample will help you to understand how to authenticate your users by using form authentication.
This sample cover following things:
1. Register a new user
2. Log in for registered users.
3. Log out after log in.
4. Use Linq to validate user.
5. Create table to store and validate users information.

  First of all create database (MVCSampleLogin) in SQL Server with  following tables.
1. Classes
ClassID int PK Auto increment by 1
Name varchar(50)

2. Users
UserID int PK Auto increment by 1
Username varchar(50)
Password varchar(50)
Email  varchar(500)
FirstName varchar(50)
Lastname varchar(50)
ClassID FK with Classes ID

Or I made this for you just run this query in your query window.
 create database [MVCSampleLogin]  
 USE [MVCSampleLogin]  
 GO  
 /****** Object: Table [dbo].[Classes]  Script Date: 16/09/2014 18:50:41 ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 SET ANSI_PADDING ON  
 GO  
 CREATE TABLE [dbo].[Classes](  
  [ClassID] [int] IDENTITY(1,1) NOT NULL,  
  [Name] [varchar](50) NULL,  
  CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED   
 (  
  [ClassID] 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  
 /****** Object: Table [dbo].[Users]  Script Date: 16/09/2014 18:50:42 ******/  
 SET ANSI_NULLS ON  
 GO  
 SET QUOTED_IDENTIFIER ON  
 GO  
 SET ANSI_PADDING ON  
 GO  
 CREATE TABLE [dbo].[Users](  
  [UserID] [int] IDENTITY(1,1) NOT NULL,  
  [Username] [varchar](50) NULL,  
  [Password] [varchar](50) NULL,  
  [Email] [varchar](500) NULL,  
  [FirstName] [varchar](50) NULL,  
  [Lastname] [varchar](50) NULL,  
  [ClassID] [int] NOT NULL,  
  CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED   
 (  
  [UserID] 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  
 SET IDENTITY_INSERT [dbo].[Classes] ON   
 GO  
 INSERT [dbo].[Classes] ([ClassID], [Name]) VALUES (1, N'English')  
 GO  
 INSERT [dbo].[Classes] ([ClassID], [Name]) VALUES (2, N'Math')  
 GO  
 INSERT [dbo].[Classes] ([ClassID], [Name]) VALUES (3, N'SST')  
 GO  
 SET IDENTITY_INSERT [dbo].[Classes] OFF  
 GO  
 SET IDENTITY_INSERT [dbo].[Users] ON   
 GO  
 INSERT [dbo].[Users] ([UserID], [Username], [Password], [Email], [FirstName], [Lastname], [ClassID]) VALUES (1, N'Admin', N'123456', N'admin@gmail.com', N'admin', N'admin', 1)  
 GO  
 INSERT [dbo].[Users] ([UserID], [Username], [Password], [Email], [FirstName], [Lastname], [ClassID]) VALUES (2, N'ABC', N'123456', N'ac@gmail.com', N'abc', N'bec', 2)  
 GO  
 INSERT [dbo].[Users] ([UserID], [Username], [Password], [Email], [FirstName], [Lastname], [ClassID]) VALUES (3, N'rupin', N'new', N'rupindersingh456@ymail.com', N'rupinder', N'singh', 1)  
 GO  
 SET IDENTITY_INSERT [dbo].[Users] OFF  
 GO  
 ALTER TABLE [dbo].[Users] WITH CHECK ADD CONSTRAINT [FK_Users_Users] FOREIGN KEY([ClassID])  
 REFERENCES [dbo].[Classes] ([ClassID])  
 GO  
 ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_Users_Users]  
 GO  

Now your database has been created. Lets move to coding .

Create new project in visual studio

File > New > Project

Select MVC 4 Project and give a name MVCCustomLogin
 
Press  OK  and then select Basic Template from next window
Press OK,  It will take some time.
Now your basic project has been created. First of all create a home page:
Go to Solution Explorer > Controllers > Right Click > ADD > Controller
Click on Controller and give name Home.
Right click on action method and add view .


Click on Add button
This is your home page

Go to View > Shared > Layout.chtml

Write following code in layout page

 <!DOCTYPE html>  
 <html>  
 <head>  
   <meta charset="utf-8" />  
   <meta name="viewport" content="width=device-width" />  
   <title>@ViewBag.Title</title>  
 </head>  
 <body>  
   <div>  
     <div style="width: auto; background-color: #728ea7;">  
     @if (Request.IsAuthenticated) {  
       <strong>@Html.Encode(User.Identity.Name)</strong>  
       @Html.ActionLink("Sign Out", "Logout", "Accounts")  
     }  
     else {  
       @Html.ActionLink("Register", "Register", "Accounts")  
       <span> | </span>  
       @Html.ActionLink("Sign In", "Login", "Accounts")  
     }  
   </div>  
   @RenderBody()  
   </div>  
 </body>  
 </html>  
Click On Model and new ASP.NET Entity Data Model Click on generate from database and select MVCSampleLogin , then select both tables. (If you don't know please refer my first blog). Now create a new controller and give it name Accounts and paste this code here
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using SampleLoginMVC.Models;  
 using System.Web.Security;  
 namespace SampleLoginMVC.Controllers  
 {  
   public class AccountsController : Controller  
   {  
     //  
     // GET: /Accounts/  
     MVCSampleLoginEntities db = new MVCSampleLoginEntities();  
     //Show Register Controller  
     public ActionResult Register()  
     {  
       ViewBag.ClassID = new SelectList(db.Classes, "ClassID", "Name");  
       return View();  
     }  
     //Handle Register form post back  
     [HttpPost]  
     public ActionResult Register(User users)  
     {  
       // Check if state is valid  
       if (ModelState.IsValid)  
       {  
         //Save data in database  
         db.Users.Add(users);  
         db.SaveChanges();  
         return RedirectToAction("Index","Home");  
       }  
       ViewBag.ClassID = new SelectList(db.Classes, "ClassID", "Name");  
       return View();  
     }  
     [HttpGet]  
     public ActionResult Login()  
     {  
       //Show login page  
       return View();  
     }  
     [HttpPost]  
     public ActionResult Login(User user, bool RemberMe=false)  
     {  
       if (ModelState.IsValid)  
       {  
         //Get user from database where user name and password is match   
         var usr = db.Users.Where(x=>x.Username==user.Username && x.Password==user.Password).FirstOrDefault();  
         if (usr!=null)  
         {  
           //set user authCookies  
           FormsAuthentication.SetAuthCookie(user.Username, false);  
           //Redrect to Dashboard.  
           return RedirectToAction("Index", "Dashboard");  
         }  
         else  
         {  
           //Show error  
           ModelState.AddModelError("", "Login data is incorrect!");  
         }  
       }  
       return View(user);  
     }  
     public ActionResult Logout()  
     {  
       //Set Sign Out   
       FormsAuthentication.SignOut();  
       return RedirectToAction("Index", "Home");  
     }  
   }  
 }  
Add this line of code in web.config file

<authentication mode="Forms">

      <forms loginUrl="~/Account/Login" timeout="2880"></forms>

    </authentication>

Right click on register and add a view and add following code in this
 @model SampleLoginMVC.Models.User  
 @{  
   ViewBag.Title = "Register";  
 }  
 <h2>Register</h2>  
 @using (Html.BeginForm()) {  
   @Html.ValidationSummary(true)  
   <fieldset>  
     <legend>User</legend>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Username)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Username)  
       @Html.ValidationMessageFor(model => model.Username)  
     </div>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Password)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Password)  
       @Html.ValidationMessageFor(model => model.Password)  
     </div>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Email)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Email)  
       @Html.ValidationMessageFor(model => model.Email)  
     </div>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.FirstName)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.FirstName)  
       @Html.ValidationMessageFor(model => model.FirstName)  
     </div>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Lastname)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Lastname)  
       @Html.ValidationMessageFor(model => model.Lastname)  
     </div>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.ClassID)  
     </div>  
     <div class="editor-field">  
       @Html.DropDownList("ClassID", "Select")  
     </div>  
     <p>  
       <input type="submit" value="Create" />  
     </p>  
   </fieldset>  
 }  
Right click on Login action method in accounts controller and add login view ,paste folowing code
 @model SampleLoginMVC.Models.User  
 @{  
   ViewBag.Title = "Login";  
 }  
 <h2>Login</h2>  
 @using (Html.BeginForm()) {  
   @Html.ValidationSummary(true, "Login failed. Check your login details.");  
   <fieldset>  
     <legend>Login</legend>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Username)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Username)  
       @Html.ValidationMessageFor(model => model.Username)  
     </div>  
     <div class="editor-label">  
       @Html.LabelFor(model => model.Password)  
     </div>  
     <div class="editor-field">  
       @Html.EditorFor(model => model.Password)  
       @Html.ValidationMessageFor(model => model.Password)  
     </div>  
       <input type="checkbox" name="RemberMe" checked="checked" />  
     <p>  
       <input type="submit" value="Login" />  
     </p>  
   </fieldset>  
 }  
Add a new controller Dashboard and add index view, paste this code in dashboard/index view
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Dashboard : After Login. </h2>  
Now your custom login is ready

Monday, 15 September 2014

Import data in Oracle from .dmp file

Import data from dump file in oracle. I am using windows 8 and its command prompt to complete is task.

Step 1: Open CMD in windows.

Step 2 : Type this imp command and then dump file path. as shown in image.
Step 3: Enter Username and password.

Any problem please contact to me.