MiTechDev.com

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

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.