2017 ~ MiTechDev.com

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

Monday, 30 October 2017

How to Read and display HTML file in Windows form application

07:55:00 Posted by raviteja swayampu , No comments
In this tutorial Raviteja Swayampu explained about how to read and display HTML file in windows forms application.In present windows stand alone applications you can see different links that redirects us to different websites and shows some images and video contents.Best example for this is Visual studio start page.

Featured Videos
News Feed

If you observe this images you can easy find that those are html links.When we opens visual studio it fetches the html file from server.In current tutorial we will see how to implement this by using WebBrowser control in windows forms application.

Read and Display HTML file in Windows form

1.Create window form application in visual studio.
2.Prepare a html file with image and some text to input for windows form application.
sample.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title></title>
</head>
<body>
    <p>A famous quote of steev is</p>
    <hr />
    <img src='https://pi.tedcdn.com/r/pe.tedcdn.com/images/ted/0ef62e4df27b4ba7294de889fdbc33e476a08ec9_254x191.jpg' />
</body>
</html>

3.Namespaces need to import for this application is as follows
Imports System.IO
Imports System.Reflection

4.Write below code in Form_Load method.
private void Form1_Load(object sender, EventArgs e)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("WebBrowser_HTML_File_CS.sample.htm"));
            webbrowser.DocumentText = reader.ReadToEnd(); 
        }


5.If you observer the above code the html file is loaded into StreamReader object  using  GetManifestResourceStream method.The contents of stram reader are read using ReadToEnd method and assigned to WebBrowser control to display html file in windows forms application.
6.Final output of the application is look like below.


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


Wednesday, 25 October 2017

TempData in ASP.NET MVC in C#

22:55:00 Posted by raviteja swayampu No comments
In this article raviteja swayampu explained about how to use TempData in ASP.NET MVC with small example.TempData is a dictionary object to store data temporarily. It is a TempDataDictionary class type and instance property of the Controller base class.

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary. It  stays for a subsequent HTTP Request(means it can keep live data between two consecutive HTTP requests both request and redirect) as opposed to other options (ViewBag and ViewData) those stay only for current request. So, TempData can be used to maintain data between controller actions as well as redirects.
It will also help to pass state between action methods also and it uses session variable to store data.It is generally used to store one time messages like error messages and validation messages.

Note:  Just like ViewData, typecasting and null checks required for TempData also in order to avoid errors run time errors while rendering cshtml pages and in other action methods.

Lets see how to use tempdata in a practical scenario from one controller to another.
public ActionResult FirstRequest()
{
    List TempDataTest = new List();
    TempDataTest.Add("Raviteja");
    TempDataTest.Add("Krishna");
    TempDataTest.Add("Sridhar");
    TempData["CustomerName"] = TempDataTest;
    return View();
}

public ActionResult ConsecutiveRequest()
{
    List modelData = TempData["CustomerName"] as List;
    TempData.Keep();
    return View(modelData);
}

In View we will display TempData as below.
@{
  if(TempData["CustomerName"]!=null){
 List<string> list=TempData["CustomerName"] as List<string>
 foreach(var item in list){
  //Writing temp data list in html page
  <h3>@item</h3>
 }
  }
}

Generally we do not think about where tempdata is stored.Obviously, it does not matter for developer to think about where it is stored.I hope this information is good about tempdata to know more like base classes of Dictionary class and methods visit MSDN.


Introduction to RequireJS for Modular Programming

05:44:00 Posted by raviteja swayampu No comments
In this tutorial we are going to look at Requirejs an incredibly powerful AMD(Asynchronous Module Definition) compatible script loader.To achieve this modular programming came into picture.

Modular Programming

Modular programming is used to break large applications into smaller blocks of manageable code. Module based coding eases the effort for maintenance and increases reusability of code. However, managing dependencies between modules is a major concern developers face throughout the application development process. Requirejs is one of the most popular frameworks around for managing dependencies between modules.In this tutorial we will see how requirejs helps us.

Why we need Javascript loaders 

Due to evolution of Single page applications web applications requires large number of script files.Generally they all are loaded one by one using <script> tag.Each file can potentially dependent on other script file.A common example for this is jquery plugins in web applications.For all jquery plugins jquery core library file must be loaded.Let look this using a simple real time example.Let's assume we have 3 javascript files.

purchase.js

function purchaseProduct(){
  //gets credits to purchase product
  var credits = getCredits();
  if(credits > 0){
    //checks the product available or not
    reserveProduct();
    return true;
  }
  return false;
}

product.js

function reserveProduct(){
  alert("Function : reserveProduct()");
  return true;
}

credits.js

function getCredits(){
  alert("Function : getCredits");
  var credits = "100";
  return credits;
}
In above example we are trying to purchase a product.First it checks whether credits available or not.If credits are available it reserves the product.Here purchase.js file depends upon credits.js and product.js files.Now in another script file main.js i am initializing code purchase.js as shown below.
var result=purchaseProduct();
So,credits.js and product.js files need to loaded before purchase.js file.We have to place those script files in order.What would happen if we place files in wrong order as shown below.
<script src="products.js"></script>
<script src="purchase.js"></script>
<script src="main.js"></script>
<script src="credits.js"></script>
Here the initialization of script(main.js) is done before credits.js loaded this will result an error like below.



In current example we just have 3 script files for larger applications the number of script files are also more and things can easily get out of control.That's where requirejs come into picture.

Introduction to Requirejs

1.Requirejs is a popular java script module loader which is supported by all latest version browsers.
2.In requirejs we separate code in modules which can handle single responsibility.
3.And dependencies need to be configured before loading script files.
4.Lets start the implementation of an small application by downloading requirejs.
Lets assume our project directory will look like below.


The file main.js file is used for initializing scripts.Lets see how scripts are included in html page using requirejs.

<script data-main="scripts/main" src="~/Scripts/require.js"></script>

This is the only code required to include files using Requirejs.You might be wondering what happened to the other files and how they are included. The data-main attribute defines the initialization point of the application. In this case, it is main.js. Requirejs uses main.js to look for other scripts and dependencies. In this scenario all the files are located in same folder(Scripts folder). you can move the files to any folder you prefer.

Creating Application with Requirejs

 In Requirejs all script code wrapped into require() and define() functions.Lets look at main.js file.

require(["purchase"], function (purchase) {
    purchase.purchaseProduct();
});

1.In above code the first parameter of the function require() specifies dependencies.We already know the initialization dependent on purchase.js file.
Note: Here see the .js extension is omitted. Requirejs only considers .js file only.
2.Second parameter is an anonymous function which takes an object as parameter which is used to call functions inside dependent script files see in above code.
Note: We can load multiple script dependencies using below syntax.

require(["a","b","c"],function(a,b,c){
});

Now we are going to convert the plain script files into Requirejs like below.

purchase.js

 define(["credits","products"], function(credits,products) {
  console.log("Function : purchaseProduct");
  return {
    purchaseProduct: function() {
      var credit = credits.getCredits();
      if(credit > 0){
        products.reserveProduct();
        return true;
      }
      return false;
    }
  }
});

Here,first we declare that purchase functionality depends on credits and products. Inside the return statement, we can define the functions of each module. Here, we have called the getCredits() and reserveProduct() functions on the objects passed. product.js and credits.js are similar, and are shown below.

products.js

define(function(products) {
  return {
    reserveProduct: function() {
      console.log("Function : reserveProduct");
      return true;
    }
  }
});

credits.js

define(function() {
  console.log("Function : getCredits");
  return {
    getCredits: function() {
      var credits = "100";
      return credits;
    }
  }
});

Both files products.js and credits.js are configured as independent modules(defined with define() function).They are dependent on anything.Here the important thing to notice is the difference between require() and define() functions.

Difference between require() and define()

In Requirejs we can use both require() and define() functions to load dependencies.Understanding the difference between this both is essential in managing dependencies.Lets see the differences,

require() 

require function is used to used to run the immediate functionalities.For example we used require in main.js in above example.

define()

define function is used to define modules that are used for multiple locations.In above example we defined products.js and credits.js with define function.The files which are defined by define() function are reusable modules.

Note: In plain java script example, an error was generated due to the incorrect order of file loading. Now, delete the credits.js file in the Requirejs example and see how it works. The following image shows error in browser inspection tool.


The difference here is that no code has been executed in the Requirejs example.We can confirm it since nothing is printed on the console(we wrote console.log in almost every file). In the plain JavaScript example we had some output printed on the console before generating the error. Requirejs waits until all the dependent modules are loaded before executing the functionality. If any modules are missing, it doesn’t execute any code. This helps us maintain the consistency of our data.

Managing order of dependent files

Requirejs uses Asynchronous module loader for loading files.Each dependent module will start loading through asynchronous requests.Even though files ordered is considered due to synchronous nature we can not guarantee that the first file loaded before second file.For that Requirejs allows us to define the sequence of the files using shim config to load in correct order.
Lets how to use shim config,

requirejs.config({
  shim: {
    'source1': ['dependency1','dependency2'],
    'source2': ['source1']
  }
});

Requirejs allows us to provide configuration options using the config() function. It accepts a parameter called shim which we can use to define the mandatory sequences of dependencies see above code.You can find advanced configuration guide in API Documentation of Requirejs.
Using shim config it is mandatory to load dependent before calling files.

Conclusion

I hope this article may helped you to understand the basics of Requirejs.This tutorial is not enough to manage dependencies.You can find advanced tutorial on requirejs from official site documentation.

Saturday, 21 October 2017

How to open a specific jQuery tab on page load?

09:45:00 Posted by raviteja swayampu , No comments
In this article we will see how to load specific tab in jquery ui tabs when page loads.I will explain it with simple example.Lets assume we have three tabs in jquery ui tabs control as shown below.


In the above example we have 3 tabs.Here my requirement is to load 3 tab when page load.Below is jquery script code to achieve this functionality.
$(document).ready(function() {
        //initializing jquery tabs
	$("#tabs").tabs();
	var tabindex=2;
        //selecting tab based on tabindex.
	$("#tabs").tabs('option','active',tabindex);
  });
Source Code:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Tabs - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="http://resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $(document).ready(function() {
	$("#tabs").tabs();
	var tabindex=2;
	$("#tabs").tabs('option','active',tabindex);
  });
  </script>
</head>
<body>
 
<div id="tabs">
  <ul>
    <li><a href="#tabs-1">Nunc tincidunt</a></li>
    <li><a href="#tabs-2">Proin dolor</a></li>
    <li><a href="#tabs-3">Aenean lacinia</a></li>
  </ul>
  <div id="tabs-1">
    <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
  </div>
  <div id="tabs-2">
    <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
  </div>
  <div id="tabs-3">
    <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
    <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
  </div>
</div>
</body>
</html>

I hope this article may help you..

Thursday, 5 October 2017

How to make jqgrid responsive for all browsers

11:22:00 Posted by raviteja swayampu , No comments
In this tutorial we gonna learn how grid will be resized on resizing the window of the web browser.Setting of CSS width to 100% is the only one implementation, but it's not good in case of jqGrid which set width in px explicitly on many its internal structures.

jqGrid uses fixed width value on many internal structures (divs, tables and so on). So one can't just set CSS width : 100%. Nevertheless there are another way to do the same. One can register resize event handler on window object and to call setGridWidth explicitly. The method adjust all internals structures of jqGrid to new width. So it would be clean method.


If you use autowidth: true then jqGrid set the width of jqGrid to the width of it's parent only once.So,we have to changes the width of grid every time we resizes the browser window. Inside of $(window).resize handler we can get new (the current) width of the parent and reset the value of grid width. The corresponding code will be the following

$(window).on("resize", function () {
    var $grid = $("#tableelement"),
        newWidth = $grid.closest(".ui-jqgrid").parent().width();
    $grid.jqGrid("setGridWidth", newWidth, true);
});

The event handler changes the width of the grid based on the browser window resizes.Here,I used $("#tableelement").closest(".ui-jqgrid") instead of $("#tableelement") because jqGrid build some dives over the main <table> element. $("#tableelement").closest(".ui-jqgrid") gives as the outer div which include all the elements of the grid see below picture.

How to make jqgrid responsive for all browsers



The script code for responsive jqgrid is as follows.

$(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
        //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 }
    });
});
//event handler to resize the width of grid
$(window).on("resize", function () {
    var $grid = $("#grid"),
        newWidth = $grid.closest(".ui-jqgrid").parent().width();
    $grid.jqGrid("setGridWidth", newWidth, true);
});


See the responsive grid for demo at jsfiddle responsive jqgrid.
Related articles on jqgrid as follows,

I hope this article may help you.For more related article follow mitechdev.com.

CRUD operations using angular js and asp.net mvc

02:19:00 Posted by raviteja swayampu , No comments
Hi everyone again in this tutorial i am going to explain CRUD(Create,Read,Update,Delete) operations using Angular js and asp.net mvc.In previous article crud operations using angular js and web api we performed create,read,update and delete operations using web api and angular js. In current article we will do the same with asp.net mvc. Please click on below link to for related articles on angular js Learning angular js with asp.net mvc.


Here in this tutorial the code is almost similar to previous article crud operations using angular js and web api. But,in current article instead of using web api calls we are using mvc controller.Remaining client and server communication is similar for both web api and mvc.
Related posts on crud operations are as follows,

CRUD operations using angular js and asp.net mvc

1.Create a asp.net mvc web application in visual studio 2015.
2.Add sql express data base to project in App_Data folder and create a table with below sql script.

CREATE TABLE [dbo].[Employee] (
    [EmpNo]       INT           IDENTITY (1, 1) NOT NULL,
    [EmpName]     NVARCHAR (50) NOT NULL,
    [Salary]      INT           NOT NULL,
    [DeptName]    NVARCHAR (50) NOT NULL,
    [Designation] NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([EmpNo] ASC)
);

3.Add ADO.NET Entity DataModel to models folder.
4.Add Controller to Controllers folder and name it as HomeController.
5.Replace controller code with below code.

using System.Data;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using WebAPICRUDwithBootstrap.Models;

namespace WebAPICRUDwithBootstrap.Controllers
{
    public class HomeController : Controller
    {
        private DatabaseEntities1 db = new DatabaseEntities1();
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetEmployees()
        {
            return Json(db.Employees.ToList(), JsonRequestBehavior.AllowGet);
        }
        // GET: Employees/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return Json(employee,JsonRequestBehavior.AllowGet);
        }

        // POST: Employees/Create
        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // POST: Employees/Edit/5
        public ActionResult Edit(Employee Employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(Employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(Employee);
        }

        // POST: Employees/Delete/5
        public ActionResult Delete(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return Json(employee,JsonRequestBehavior.AllowGet);
        }

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



6.Now add three script files Controller.js,module.js and Service.js files in scripts folder.
Module.js: Creates an angular module(a module contains controller to perform some actions).

//It acts as a auto bootstraper for angular application.
//We bind this module to view using ng-app directive.
var myapp;
(function () {
    myapp = angular.module('myangularapp', []);
})();

7.Controller.js: It is responsible for all logical operations in angular for example two way data binding.

//Angular controller 
myapp.controller('crudcontroller', function ($scope, crudservice) {
    
    //Loads all Employee records when page loads
    loadEmployees();
    function loadEmployees() {
        var EmployeeRecords = crudservice.getAllEmployees();
        EmployeeRecords.then(function (d) {     //success
            $scope.Employees = d.data;
        },
        function(){
            swal("Oops..","Error occured while loading","error"); //fail
        });
    }

    //save form data
    $scope.save = function () {
        var Employee = {
            EmpNo:$scope.EmpNo,
            EmpName: $scope.EmpName,
            Salary: $scope.Salary,
            DeptName: $scope.DeptName,
            Designation: $scope.Designation
        };
        var saverecords = crudservice.save(Employee);
        saverecords.then(function (d) {
            $scope.EmpNo = d.data.EmpNo;
            loadEmployees();
            swal("Reord inserted successfully");
        },
        function(){
            swal("Oops..","Error occured while saving",'error');
        });
    }

    //get single record by ID

    $scope.get = function (Employee) {
        var singlerecord = crudservice.get(Employee.EmpNo);
        singlerecord.then(function (d) {
            var record = d.data;
            $scope.UpdateEmpNo = record.EmpNo;
            $scope.UpdateEmpName = record.EmpName;
            $scope.UpdateSalary = record.Salary;
            $scope.UpdateDeptName = record.DeptName;
            $scope.UpdateDesignation = record.Designation;
        },
        function(){
            swal("Oops...","Error occured while getting record","error");
        });
    }

    //update Employee data
    $scope.update = function () {
        var Employee = {
            EmpNo: $scope.UpdateEmpNo,
            EmpName: $scope.UpdateEmpName,
            Salary: $scope.UpdateSalary,
            DeptName: $scope.UpdateDeptName,
            Designation:$scope.UpdateDesignation
        };
        var updaterecords = crudservice.update($scope.UpdateEmpNo, Employee);
        updaterecords.then(function (d) {
            loadEmployees();
            swal("Record updated successfully");
        },
        function () {
            swal("Opps...","Error occured while updating","error");
        });
    }

    //delete Employee record
    $scope.delete = function (UpdateEmpNo) {
        var deleterecord = crudservice.delete($scope.UpdateEmpNo);
        deleterecord.then(function (d) {
            var Employee = {
                EmpNo: '',
                EmpName: '',
                Salary: '',
                DeptName: '',
                Designation: ''
            };
            loadEmployees();
            swal("Record deleted succussfully");
        });
    }
});



8.Service.js: It is responsible for communication between controller and server(uses $http service).

//Service to get data from service..
myapp.service('crudservice', function ($http) {
    
    this.getAllEmployees = function () {
        return $http.get("http://localhost:56193/Home/GetEmployees");
    }

    //save
    this.save = function (Employee) {
        var request = $http({
            method: 'post',
            url: 'http://localhost:56193/Home/Create',
            data:Employee
        });
        return request;
    }

    //get single record by Id
    this.get = function (EmpNo) {
        return $http({
            method: 'get',
            url: 'http://localhost:56193/Home/Details?id=' + EmpNo,
            data: JSON.stringify(EmpNo)
        });
    };

    //update Employee records
    this.update = function (UpdateEmpNo, Employee) {
        var updaterequest = $http({
            method: 'post',
            url: "http://localhost:56193/Home/Edit",
            data:Employee
        });
        return updaterequest;
    }

    //delete record
    this.delete = function (UpdateEmpNo) {
        var deleterecord= $http({
            method: 'delete',
            url: "http://localhost:56193/Home/Delete?id=" + UpdateEmpNo
        });
        return deleterecord;
    }
});

9.The final output of the application is look like below.

CRUD operations using angular js and asp.net mvc



10.I hope this article may help you.Download source code for this application from here Download.

Wednesday, 4 October 2017

How to connect mysql database using C#

02:45:00 Posted by raviteja swayampu , No comments
This article shows you how to connect mysql database to asp.net mvc web application using MySql Connector/.Net.In order to connect with mysql database using C# application Mysql provides a series of predefined classes in mysql connector/.Net to perform various operations on mysql database.All the communication between a C# application and the MySQL server is routed through a MySqlConnection Object. So, before your application can communicate with the server, it must instantiate, configure, and open a MySqlConnection object.

Download mysql connector for dot net from mysql official site with free of cost.Click below link to download. Download mysql connector installor.

Before we start using mysql connector we need to add the mysql connector references to our project.
1.Right click on references --> add reference --> browse for 'MySql.Data' and add.

How to connect mysql database using C#

2.Now add MySql Library namespace in C# project like below.
using MySql.Data.MySqlClient;


Specifying Connection string in Mysql

1.mysql connection string in C# application:
string myConnectionString = "server=localhost;database=testDB;uid=root;pwd=pass123;";
2.For multiple servers:
myConnectionString = Server=server1, server2;database=testDB;uid=root;pwd=abc123;";
Note:The above connection string will needed when connect to a server in a replicated server configuration without concern on which server to use.
3.To specify TCP port in connection string:
myConnectionString="Server=myServerAddress;Port=1234;Database=testDB;Uid=root;Pwd=abc123;

The following program creates a object to MySqlConnection class and opens connection.

using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string conString = null;
            MySqlConnection connection;
            conString = "server=localhost;database=testDatabase;uid=root;pwd=passwd123;";
            connection = new MySqlConnection(conString);
            try
            {
                connection.Open();
                MessageBox.Show ("Connection Opened ! ");
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! ");
            }
        }
    }
}

Thursday, 21 September 2017

How to use static keyword in C# with examples

21:30:00 Posted by sridhar thota , No comments
In this article, I am going to explain the static keyword concept with examples. It covers static variable, static method, static constructor and static class. I have explained how to access static variables and static methods with in a static class.

Static Variable:

1.Static keyword can be used with variables, methods, constructor and class.
2.Static variable will be created only once and it can be shared by all objects.
3.If we declare static variable as public, then we can access that variable with classname.static_variable.
4.Static variable is created when class is loaded in to memory .
class sample 
{
public string s="hello";
public static string st="am static";
}
button click
{
sample obj=new sample();
obj.s;  //non static variable so can be accessed with object of class.
obj.st; // this is error. since static variable cannot be accessed with object of class.
sample.s; //this is error. since non static variable cannot be called with classname.variablename.
sample.st;// static variable can be accessed with classname.staticvariablename.
}

Static Method:

1.Static methods are called with classname.method name directly with out creating object.
2.When we have all static methods in a class, then we can declare that class as static class.
3.Some static methods are as follows
Ex: Console.ReadLine(); // consoleclass.methodname
      Console.Write();
      MessageBox.Show();

class static sample2
{
public static void display()
{
MessageBox.Show("Am from static method");
}
button click
{
sample2 obj=new sample2(); // error . As we cannot create object for static class.
obj.display(); // this is error. cannot be accessed with object.
sample2.display(); //works fine as called with classname.methodname
}

Static Constructor:

1.Static constructor is executed only once when the class is loading in to the memory.
2.Static constructor can access only static variables.
class sample3
{
public string s="static constructor example";
public sample3() // normal constructor
{
MesssageBox.Show("Am from normal constructor");
}
static sample3() // static constructor
{
MessageBox.Show("Am from static constructor");
}
}
button click
{
sample3 obj=new sample3();
sample3 obj1=new sample3();
}

Static Class:

1. Static class cannot be instantiated, i.e., we cannot create object for static class.
2. If we have all static methods in our class then we can declare the class as static class.
class static sample4
{
public static string s="hello";
public static string st="am static variable";
public static void display()
{
MessageBox.Show("Am from static method");
MessageBox.Show("Am static class");
}
static sample4() // static constructor
{
MessageBox.Show("Am from static constructor");
}
button click
{
sample4.s;
sample4.st;
sample4.display();
}
I hope this article helped you to understand the static keyword concept in c sharp language.Suggestions and feedback are welcome.

how to validate credit card number in jquery

10:15:00 Posted by raviteja swayampu , No comments
Hi every one welcome again today i came with very useful article How to validate credit card number in jquery. For that here i am not using neither  plugins nor references.I am doing it using pure jquery script code.Here to check whether card is a valid card or not i am using Luhn algorithm or Luhn formula.

What is Luhn Algorithm:

The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in the United States, Canadian Social Insurance Numbers, Israel ID Numbers and Greek Social Security Numbers (ΑΜΚΑ). It was created by IBM scientist Hans Peter Luhn.For more information about Luhn formula visit Luhn algorithm.

Now lets check how to implement luhn test in our web application.In current application i am validating credit card in two steps
1.Checking the format of card using Regular expressions.
2.Validating card number using luhn formula.

How to check format of credit card:

For step1 i used regular expressions to check whether the credit card number is in correct format or not.For example Visa card only starts with digit '4' and contains 16 numeric digits and Master Card starts with digit '5' etc.Below are some valid credit card numbers for testing purpose.

valid credit card numbers for testing

Now come to the current application.I checked the credit card with below regular expression.
/*Regular expressions to validate credit card is in valid format
    */
    var VisaReg = /^4[0-9]{12}(?:[0-9]{3})?$/;
    var AmericanExpressReg = /^3[47][0-9]{13}$/;
    var MasterCardReg = /^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/;



1.Check the format of card with below script using regular expression.
/*Regular expressions to validate credit card is in valid format
    */
    var VisaReg = /^4[0-9]{12}(?:[0-9]{3})?$/;
    var AmericanExpressReg = /^3[47][0-9]{13}$/;
    var MasterCardReg = /^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/;

    var cardnumber = $("#cardNumber").val();
    var cardtype = $("#ddlCardType").val();
    var expirydate = $("#cardExpiry").val();
    var cardholdername = $("#cardHolderName").val();

    if (cardnumber == null || cardnumber == "") {
        $("#spncardNumber").text("Please Enter Card Number");
        $("#spncardNumber").show();
        result = false;
    }
    else if (cardnumber != null && cardnumber != "") {
        if (cardtype == "VISA") {
            if (!VisaReg.test(cardnumber)) {
                $("#spncardNumber").text("Enter Valid Visa Card Number");
                $("#spncardNumber").show();
                result = false;
            }
        }
        else if (cardtype == "AMERICAN EXPRESS") {
            if (!AmericanExpressReg.test(cardnumber)) {
                $("#spncardNumber").text("Enter Valid AE Card Number");
                $("#spncardNumber").show();
                result = false;
            }
        }
        else {
            if (!MasterCardReg.test(cardnumber)) {
                $("#spncardNumber").text("Enter Valid Master Card Number");
                $("#spncardNumber").show();
                result = false;
            }
        }       
    }
2.If you enter an invalid number with starting digit as other than 4 for VISA card(Visa card start with digit 4) and see the validation message in form like below.

Validate format of credit card

3.But these regular expressions checks card format only.They can not validate the card numbers. Luhn formula will take care of it.

How to Validate Credit Card using Luhn Algorithm:

1.Below is java script code to perform luhn formula.
/*checks whether card is valid or not using luhn algoritham
current credit cards in market are following this algoritham*/
function isCardNumberValid(cardNumber, allowSpaces) {
    if (allowSpaces) {
        cardNumber = cardNumber.replace(/ /g, '');
    }
    if (!cardNumber.match(/^\d+$/)) {
        return false;
    }
    var checksum = 0;
    for (var i = 0; i < cardNumber.length; i++) {
        var n = (cardNumber.charAt(cardNumber.length - i - 1) - '0') << (i & 1);
        checksum += n > 9 ? n - 9 : n;
    }
    return (checksum % 10) == 0 && checksum > 0;
}
2.This function accepts two parameters one is card number and another one boolean values(true or false,currently this code is work for card number with spaces).
3.Now check a random number with 16 digits.Luhn algorithm says..

Validate credit card using luhn algorithm

4.In the same ways below is csharp code to check the luhn algorithm.
Luhn alogitham server validation code.

    public static class LuhnUtility
    {
        public static bool IsCardNumberValid(string cardNumber, bool allowSpaces = false)
        {
            if (allowSpaces)
            {
                cardNumber = cardNumber.Replace(" ", "");
            }

            if (cardNumber.Any(c => !Char.IsDigit(c)))
            {
                return false;
            }

            int checksum = cardNumber
               .Select((c, i) => (c - '0') << ((cardNumber.Length - i - 1) & 1))
               .Sum(n => n > 9 ? n - 9 : n);

            return (checksum % 10) == 0 && checksum > 0;
        }
    }


Download the source code for this application from Github.
Download

Conclusion:

I hope this article may help you.Suggestions and feedbacks are always welcome.

Tuesday, 19 September 2017

How to disable past dates in date picker

05:59:00 Posted by raviteja swayampu No comments
In this example we will see how to disable the previous date selection in JQuery UI date picker. To disable the previous dates we need to set the minDate property of date picker.
If you are new to jquery date picker visit How to add date picker to textbox.
We can disable previous dates in two ways
1.By setting minDate option to 0.
2.By passing today date to minDate option in datepicker.
then it will disable all the previous dates.For example see the below picture.
3.Jquery script for this application is
<script language="javascript">
    $(document).ready(function () {
        $("#txtdate").datepicker({
            minDate: 0
        });
    });
</script>
4.Or we can also write code like this using today date.
<script language="javascript">
    $(document).ready(function () { 
        var todayDate=new Date();
        $("#txtdate").datepicker({
            minDate: todayDate
        });
    });
</script>
5.Complete source code for this application is,
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker -With Disabled past date</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var todayDate=new Date();
    $( "#datepicker" ).datepicker({
           minDate:todayDate  //or minDate:0 also works...
    });
  } );
  </script>
</head>
<body>
 
<p>Date: <input type="text" id="datepicker"></p>
 
</body>
</html>
Date picker look like below with disabled date..

how to disable past dates in datepicker

Monday, 18 September 2017

Asynchronous fileupload using jquery in mvc5

21:38:00 Posted by raviteja swayampu , No comments
In today's article i will explain about how to Asynchronously upload file in asp.net mvc web application using jquery with progress bar.In previous articles we saw about uploading file in mvc application in different ways.

Here in current application we can upload files asynchronously to server.

asynchronous file upload using jquery in mvc5

Asynchronous fileupload using jquery

1.Create asp.net mvc web application using empty template.
2.Here in this application i used jquery ajax form plugin from here github.
3.Create a controller and name it as HomeController and add Index action method as below.
public ActionResult Index()
        {
            return View();
        }
4.Add view to index action method to display file upload screen.
@{
    ViewBag.Title = "Index";
}
<h2>Jquery Asychronous file upload</h2>
<style type="text/css">
    .progress-bar{
        max-width:400px;
    }
    .progress{
        max-width:400px;
    }
</style>
<div class="container">
    <div class="row">
        <div class="col-md-5">
            @using (Ajax.BeginForm("Index", "Home", new AjaxOptions() { HttpMethod = "POST" },
            new { enctype = "multipart/form-data" }))
            {
                @Html.AntiForgeryToken();
                <input type="file" class="form-control" name="files" id="fileupload" />
                <input type="submit" class="btn btn-success" value="File upload" />
            }
            <br />
            <div class="progress">
                <div class="progress-bar">0%</div>
            </div>
            <div id="status"></div>
        </div>
    </div>
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
       $(document).ready(function(){
           var bar = $('.progress-bar');
           var percent = $('.progress-bar');
           var status = $('#status');
           
           $('form').ajaxForm({
               beforeSend: function () {
                   status.empty();
                   var percentValue = '0%';
                   bar.width(percentValue);
                   percent.html(percentValue);
               },
               uploadProgress: function (event, position, total, percentComplete) {
                   var percentValue = percentComplete + '%';
                   bar.width(percentValue);
                   percent.html(percentValue);
               },
               success: function (d) {
                   var percentValue = '100%';
                   bar.width(percentValue);
                   percent.html(percentValue);
                   $('#fileupload').val('');
                   alert(d);
               },
               complete: function (xhr) {
                   status.html(xhr.responseText);
               }
           });
       });
</script>

5.In above code i used jquery script to display progress bar based on upload status of the file like above picture.
6.Below method in controller saves the file in server.
 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(IEnumerable files)
        {
            int filecount = 0;
            string msg = "";
            try
            {
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        if (file != null && file.ContentLength > 0)
                        {
                            var filename = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("~/Files"),filename);
                            file.SaveAs(path);
                            filecount++;
                        }
                    }
                    msg = filecount + " Files Uploaded Successfully";
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return Json(msg, JsonRequestBehavior.AllowGet);
        }
7.We can see the saved files in solution(Files folder).

asynchronous file upload using jquery in mvc5


8.To download source code for this application from Github click below.

Download

9.Conclusion

I hope this article will help you.Feedback and suggestions are welcome

How to create pivot table in excel using asp.net mvc

06:00:00 Posted by sridhar thota , No comments
Hi friends today am going to show how to create pivot table in excel sheet using c#. I got the requirement but no clear code is found for the same in the internet. So I would like to post the article with clear c# code. Hope it will be useful for those who is looking for pivot table creation using c#.

Namespaces used in this application to work on Excel files are below.
using Excel=Microsoft.Office.Interop.Excel; //microsoft interlop ddl
using OfficeOpenXml;//eplus dll
Here Microsoft.Office.Interop.dll only available in systems which are installed with micro soft office 2013.Second dll Epplus easily available on web.

How to create pivot table in excel using asp.net mvc

In this application i am creating pivot excel table in two steps.
1.Creating Excel file and storing in server.
2.Converting excel file to pivot excel table.

Creating pivot table in Excel

Step 1:Creating Excel file.
1.Create a asp.net mvc web application using empty web template.
2.Right click on models folder and create a model class name it as TProduct.
TProduct.cs:
public class TProduct
    {
        public string Category { get; set; }
        public string Place { get; set; }
        public string Name { get; set; }
        public long Price { get; set; }
        public long NoOfUnits { get; set; }
    }
3.Create data source code to generate excel file.For that add another class file in models folder and replace it with below code.
pivotdata.cs:
public class pivotdata
    {
        public List PivotData()
        {
            List _list = new List()
            {
                new TProduct {Category="Clothing",Place="Hyderabad",Name="LEVIS",Price=3000,NoOfUnits=52 },
                new TProduct {Category="Clothing",Place="Hyderabad",Name="Buffallo",Price=10000,NoOfUnits=12 },
                new TProduct {Category="Clothing",Place="Banglore",Name="FM",Price=3200,NoOfUnits=5 },
                new TProduct {Category="Clothing",Place="Banglore",Name="PUMA",Price=6400,NoOfUnits=10 },
                new TProduct {Category="Clothing",Place="Banglore",Name="LEVIS",Price=3400,NoOfUnits=20 },
                new TProduct {Category="Clothing",Place="Banglore",Name="Buffallo",Price=34400,NoOfUnits=30 },
                new TProduct {Category="Electronics",Place="Banglore",Name="IPhone",Price=72000,NoOfUnits=1 },
                new TProduct {Category="Electronics",Place="Banglore",Name="LED TV",Price=20000,NoOfUnits=4 },
                new TProduct {Category="Electronics",Place="Banglore",Name="SAMSUNG",Price=300000,NoOfUnits=5 },
                new TProduct {Category="Electronics",Place="Banglore",Name="IPhone",Price=7200,NoOfUnits=1 },
                new TProduct {Category="Electronics",Place="Hyderabad",Name="Fridge",Price=150000,NoOfUnits=10 },
                new TProduct {Category="Electronics",Place="Hyderabad",Name="Laptops",Price=40000,NoOfUnits=15 },
                new TProduct {Category="Electronics",Place="Hyderabad",Name="Laptops",Price=30000,NoOfUnits=6 },
                new TProduct {Category="Electronics",Place="Hyderabad",Name="Laptops",Price=78347,NoOfUnits=8 },
            };
            return _list;
        }
    }
4.Add Controller by right click on controllers folder --> add --> empty controller --> name it as HomeController.cs.
5.Create two action methods to in HomeController render index view and create initial excel file.
HomeController.cs
public ActionResult Index()
        {
            List _listdata = new List();
            pivotdata dal = new pivotdata();
            _listdata = dal.PivotData();
            LoadExcelData(_listdata);
            return View();
        }
        public void LoadExcelData(List _lstproduct)
        {
            string filepath = Server.MapPath("~/Content/ProductReport.xlsx");
            System.Data.DataTable _dt = new System.Data.DataTable();
            try
            {
                if (System.IO.File.Exists(filepath))
                {
                    System.IO.File.Delete(filepath);
                }
                ExcelPackage app = new ExcelPackage();
                var sheet = app.Workbook.Worksheets.Add("ProductReport");
                sheet.Cells[1, 1].LoadFromCollection(_lstproduct, true);
                Stream stream = System.IO.File.Create(filepath);
                app.SaveAs(stream);
                stream.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }       
6.Here Index() method renders the index view and gets the data from data source(from pivotData method) and sends it to LoadExcelData() method.
7.LoadExcelData method exports data came from index method to excel file and saves it on server location(Container folder in solution).

How to create pivot table in excel using asp.net mvc

Step 2: Convert Excel file to Pivot table
1.In this step we are converting the excel to pivot table.
2.Right click solution --> add folder --> name is as Utility.Add class file in utility folder to perform perform exporting excel sheet to pivot excel table.
Export.cs:
public class Export
    {
        //this method will create pivot table in excel file
        public string OfficeDll()
        {
            //gets the excel file from path
            string filepath = System.Web.HttpContext.Current.Server.MapPath("~/Content/ProductReport.xlsx");
            int rows = 0;
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook excelWorkBook = excelApp.Workbooks.Open(filepath);
            Excel.Worksheet excelworksheet = excelWorkBook.ActiveSheet;
            Excel.Worksheet sheet2 = excelWorkBook.Sheets.Add();
            try
            {
                sheet2.Name = "Pivot Table";
                excelApp.ActiveWindow.DisplayGridlines = false;
                Excel.Range oRange = excelworksheet.UsedRange;
                Excel.PivotCache oPivotCache = excelWorkBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);  // Set the Source data range from First sheet
                Excel.PivotCaches pch = excelWorkBook.PivotCaches();
                pch.Add(Excel.XlPivotTableSourceType.xlDatabase, oRange).CreatePivotTable(sheet2.Cells[3, 3], "PivTbl_2", Type.Missing, Type.Missing);// Create Pivot table
                Excel.PivotTable pvt = sheet2.PivotTables("PivTbl_2");
                pvt.ShowDrillIndicators = true;
                pvt.InGridDropZones = false;
                Excel.PivotField fld = ((Excel.PivotField)pvt.PivotFields("CATEGORY"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld = ((Excel.PivotField)pvt.PivotFields("PLACE"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld = ((Excel.PivotField)pvt.PivotFields("NAME"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld = ((Excel.PivotField)pvt.PivotFields("PRICE"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld = ((Excel.PivotField)pvt.PivotFields("NoOfUnits"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlDataField;

                sheet2.UsedRange.Columns.AutoFit();
                pvt.ColumnGrand = true;
                pvt.RowGrand = true;
                excelApp.DisplayAlerts = false;
                excelworksheet.Delete();
                sheet2.Activate();
                sheet2.get_Range("B1", "B1").Select();
                excelWorkBook.SaveAs(filepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excelApp.DisplayAlerts = false;
                excelWorkBook.Close(0);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelWorkBook);
                Marshal.ReleaseComObject(excelApp);
            }
            catch (Exception ex)
            {
                excelWorkBook.Close(0);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelWorkBook);
                Marshal.ReleaseComObject(excelApp);

                return ex.Message;
            }
            return filepath;
        }
    }    
3.The above method OfficeDll converts excel sheet to pivot table in excel.
4.I added another action method in HomeController of type FileResult to return the Pivot excel file as output in browser when we click on button.
 //Returns the pivot excel table      
        public FileResult Export()
        {
            string finalpath = "";
            Export obj = new Utility.Export();
            finalpath= obj.OfficeDll();
            return File(finalpath, "application/vnd.ms-excel");
        }
5.Add view to index action.
index.cshtml page:

How to create pivot table in excel using asp.net mvc

Download the source code for this application from Github.

Conclusion:

I hope this article help you.Feedback and suggestions are welcome.

Sunday, 17 September 2017

How to compare dates using javascript

05:17:00 Posted by raviteja swayampu No comments
Comparing dates is a common task to do as a front end developer is to process Date objects, and frequently that means to compare them.Today we will learn how to compare dates in java script.There are many predefined methods for comparing dates but in this article i am only showing the simplest ways to compare dates in java script.

Setting a Date Object:

1.Date is the predefined class in java script.To perform any operations on dates we have to create object for Date class.
2.There are 4 ways to instantiate date object like below.
new Date() //This will return current date and time.
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
3.The date constructor accepts parameters like above.Lets see some examples of creating date objects and output in browser console.

how to compare dates in javascript

Comparing Dates:

Comparing two dates.Let take two dates and i am comparing both with below java script function CompareDate() below.
     function CompareDate() {
       //Note: 00 is month i.e. January
       var dateOne = new Date(2010, 00, 15); //Year, Month, Date
       var dateTwo = new Date(2011, 00, 15); //Year, Month, Date
       if (dateOne > dateTwo) {
            alert("Date One is greather then Date Two.");
        }else {
            alert("Date Two is greather then Date One.");
        }
    }
    CompareDate();
4.Lets see the output for this function in browser console.

how to compare dates in javascript



5.Similarly compare two dates with time.Now instantiate date objects by passing time values along with date parameters in date constructor.
   function CompareDate() {
       //            new Date(Year, Month, Date, Hr, Min, Sec);
       var dateOne = new Date(2012, 04, 20, 14, 55, 59);
       var dateTwo = new Date(2012, 04, 20, 12, 10, 20);
        //Note: 04 is month i.e. May
       if (dateOne > dateTwo) {
            alert("Date One is greather then Date Two.");
        }else {
            alert("Date Two is greather then Date One.");
        }
       if(dateOne==dateTwo){
           alert("Both dates are equal");
       }else{
           alert("Dates are not equal");
       }
    }
    CompareDate();
The below some useful predefined methods to performs operations on dates in java script.
getDate: Returns the day of the month (1-31) for the specified date according to local time.
getDay: Returns the day of the week (0-6) for the specified date according to local time.
getFullYear: Returns the year (4 digits for 4-digit years) of the specified date according to local time.
getHours: Returns the hour (0-23) in the specified date according to local time.
getMilliseconds: Returns the milliseconds (0-999) in the specified date according to local time.
getMinutes: Returns the minutes (0-59) in the specified date according to local time.
getMonth: Returns the month (0-11) in the specified date according to local time.
getSeconds: Returns the seconds (0-59) in the specified date according to local time.
getTime: Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
getTimezoneOffset: Returns the time-zone offset in minutes for the current locale.
getUTCDate: Returns the day (date) of the month (1-31) in the specified date according to universal time.
getUTCDay: Returns the day of the week (0-6) in the specified date according to universal time.
getUTCFullYear: Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
getUTCHours: Returns the hours (0-23) in the specified date according to universal time.
getUTCMilliseconds: Returns the milliseconds (0-999) in the specified date according to universal time.
getUTCMinutes: Returns the minutes (0-59) in the specified date according to universal time.
getUTCMonth: Returns the month (0-11) in the specified date according to universal time.
getUTCSeconds: Returns the seconds (0-59) in the specified date according to universal time.
getYear: Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear instead.
setDate: Sets the day of the month (1-31) for a specified date according to local time.
setFullYear: Sets the full year (4 digits for 4-digit years) for a specified date according to local time.
setHours: Sets the hours (0-23) for a specified date according to local time.
setMilliseconds: Sets the milliseconds (0-999) for a specified date according to local time.
setMinutes: Sets the minutes (0-59) for a specified date according to local time.
setMonth: Sets the month (0-11) for a specified date according to local time.
setSeconds: Sets the seconds (0-59) for a specified date according to local time.
setTime: Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC, allowing for negative numbers for times prior.
setUTCDate: Sets the day of the month (1-31) for a specified date according to universal time.
setUTCFullYear: Sets the full year (4 digits for 4-digit years) for a specified date according to universal time.
setUTCHours: Sets the hour (0-23) for a specified date according to universal time.
setUTCMilliseconds: Sets the milliseconds (0-999) for a specified date according to universal time.
setUTCMinutes: Sets the minutes (0-59) for a specified date according to universal time.
setUTCMonth: Sets the month (0-11) for a specified date according to universal time.
setUTCSeconds: Sets the seconds (0-59) for a specified date according to universal time.
setYear: Sets the year (usually 2-3 digits) for a specified date according to local time. Use setFullYear instead.
toDateString: Returns the "date" portion of the Date as a human-readable string.

I hope this article helped you.Feedback and suggestions are welcome.

Thursday, 14 September 2017

Jqgrid server side sorting and paging

20:29:00 Posted by raviteja swayampu No comments
In this article we will learn about how to implement server side paging and sorting in jqgrid in asp.net mvc web application.If you are new to jqgrid please refer following articles on jqgrid in this blog.


Now lets see how to implement server side sorting and paging in jqgrid,
To implement sorting and paging on server side first we must set jqgrid property loadonce:false.Now jqgrid depends on server side method to implement paging and sorting otherwise server side sorting and paging will not be performed.
Note: download source code for jqgrid in this blog before going to implement present application.Here in this application i am using previous jqgrid application code.
1.Change the controller code with below csharp code.
public JsonResult GetValues(string sidx, string sord, int page, int rows) 
        {
            DatabaseEntities1 db = new DatabaseEntities1();
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            var Results = db.Users.Select(
                    a => new
                    {
                        a.Id,
                        a.Name,
                        a.Phone,
                        a.Address,
                        a.DOB,
                    }).ToList();
            int totalRecords = Results.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            //sorting the result based on sort index column in jqgrid 
            try
            {
                switch (sidx)
                {
                    case "Name":
                        if (sord.ToUpper() == "ASC")
                            Results = Results.OrderBy(x => x.Name).ToList();
                        else
                            Results = Results.OrderByDescending(x => x.Name).ToList();
                        break;
                    case "Phone":
                        if (sord.ToUpper() == "ASC")
                            Results = Results.OrderBy(x => x.Phone).ToList();
                        else
                            Results = Results.OrderByDescending(x => x.Phone).ToList();
                        break;
                    case "Address":
                        if (sord.ToUpper() == "ASC")
                            Results = Results.OrderBy(x => x.Address).ToList();
                        else
                            Results = Results.OrderByDescending(x => x.Address).ToList();
                        break;
                    case "DOB":
                        if (sord.ToUpper() == "ASC")
                            Results = Results.OrderBy(x => x.DOB).ToList();
                        else
                            Results = Results.OrderByDescending(x => x.DOB).ToList();
                        break;
                    default:
                        Results = Results.OrderByDescending(s => s.Id).ToList();
                        break;
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            //server side paging for grid               
            Results = Results.Skip(pageIndex * pageSize).Take(pageSize).ToList();
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = Results
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
2.Below is the jquery script for jqgrid.


$(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: false, name: 'Id',align:'center',index: 'Id', editable: false,width:50 },
            { key: false, name: 'Name', index: 'Name',align:'center',editable: true,sortable:true },
            { key: false, name: 'Phone', index: 'Phone',align:'center',editable: true,sortable: true },
            { key: false, name: 'Address', index: 'Address',align:'center',editable: true,sortable: true },
            { key: false, name: 'DOB', index: 'DOB', editable: true,align:'center',sortable:true,formatter: 'date', formatoptions: { newformat: 'd/m/Y' } }],
            
        pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [10, 20, 30, 40],
        height: '100%',
        width: 600,
        //loadonce:true,
        sortname: 'Id',
        sortorder:'desc',
        viewrecords: true,
        caption: 'Server side sorting & paging in Jqgrid',
        emptyrecords: 'No records to display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        },
        multiselect: false,
        //loadComplete: function () {
        //    var $this = $(this);
        //    if ($this.jqGrid("getGridParam", "datatype") !== "local") {
        //        setTimeout(function () {
        //            $this.jqGrid("setGridParam", { rowNum: 10 }); // the real value
        //            $this.trigger("reloadGrid");
        //        }, 50);
        //    }
        //},
        //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 },
        {
            // edit options
            zIndex: 100,
            url: '/Jqgrid/Edit',
            closeOnEscape: true,
            closeAfterEdit: true,
            recreateForm: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },
        {
            // add options
            zIndex: 100,
            url: "/Jqgrid/Create",
            closeOnEscape: true,
            closeAfterAdd: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },
        {
            // delete options
            zIndex: 100,
            url: "/Jqgrid/Delete",
            closeOnEscape: true,
            closeAfterDelete: true,
            recreateForm: true,
            msg: "Are you sure you want to delete this task?",
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        });
});

jqgrid server side sorting and paging

3.I hope this article may help you.All feed backs and suggestions are welcome.