2016 ~ MiTechDev.com

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

Thursday, 29 December 2016

Working with Arrays in C Sharp Programming

22:43:00 Posted by raviteja swayampu No comments

Programming in C Sharp

Programming in C Sharp is a Series of self taught article.Till now i shared my experience in the form of small applications and code samples.From now on wards i want to share Technologies(C Sharp,ASP.NET MVC,Angular Js,Jquery) knowledge step by step in series of tutorials to help the beginner people who want to start their career in web development using Microsoft Web Technologies .I will start this series with Arrays Concept in C Sharp Programming.

Introduction

In this article i will focus on Arrays.Arrays is the most wanted concept in C Sharp Programming.This article starts with the basic definition of arrays and ends with Arrays classes and how to search,sort with arrays items.For better readability i am diving this tutorial into two parts.


Array is a data structure that stores the multiple variables of same type.Unlike other data structures arrays are fixed in size.It's index start with 0 and end with (n-1). Where n=number of elements in array.For Example if an array contains 5 elements it's index start with 0 th element and ends with 4 th index element.

Why we need Arrays

Consider a situation where we need to store five integer numbers. If we use programming's simple variable and data type concepts, then we need five variables of int data type.with variables the program will look like below.
   main() {
   int  num1;
   int  num2;
   int  num3;
   int  num4;
   int  num5;
   
   num1 = 10;      
   num2 = 20;   
   num3 = 30;   
   num4 = 40; 
   num5 = 50;     

   printf( " num1: %d\n", num1);
   printf( " num2: %d\n", num2);
   printf( " num3: %d\n", num3);
   printf( " num4: %d\n", num4);
   printf( " num5: %d\n", num5);
}
It was simple, because we had to store just five integer numbers. Now let's assume we have to store 5000 integer numbers. Are we going to use 5000 variables?

To handle such situations, almost all the programming languages provide a concept called array. An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Memory allocation in arrays:



Defining Arrays: 
In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator. The following code snippet defines arrays of double, char, bool, and string data type.
double[] doubleArray = new double[5];
char[] charArray = new char[5];
bool[] boolArray = new bool[2];
string[] stringArray = new string[10];

Initializing Array:
1.In above code snippet we have declared arrays with different data types.Now we have to initialize that arrays with some actual data.
int[] numArray=int[5]{1,2,3,4,5};
2.In above line of code i initialized the 'numArray' with 5 integer elements.
3.we can also add this one item at a time in array like below.
int[] numArray= new int[5];
numArray[0] = 1;
numArray[1] = 2;
numArray[2] = 3;
numArray[3] = 4;
numArray[4] = 5;
4.OR we can dynamically initialize an array(with specifying size) using actual data.
string[] monthArray=string[]{'january','feb','march'};

Accessing Arrays:
5.We can access those array items with help of index.for example i will print above 'monthArray' in program like below.
Note: This approach is suited when you know the exact element to access.
Console.WriteLine("First Month: "+monthArray[1]);
Console.WriteLine("Second Month: "+monthArray[2]);
Console.WriteLine("Third Month: "+monthArray[3]);
6.Ok,accessing array using index is fine but if there are hundreds of elements present in array how you are going to access those elements.In that case we will go to Foreach loop.Foreach loop is best suited for arrays.The following code snippet shows how to print all elements in 'monthArray' array.
//Read all elements in array
foreach(var item in monthArray){
  Console.WriteLine(item);
}

Note: This approach is best suited when you do not know the exact index of element in array.
vTypes of Arrays
Arrays are divided into four types.
1.Single Dimensional or linear arrays
2.Multi dimensional or rectangular arrays.
3.Jagged arrays.

Single Dimensional Arrays:
Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored contiguously starting from 0 to the size of the array -1.
The following code declares an integer array that can store 3 items. As you can see from the code, first I declare the array using [] bracket and after that I instantiate the array by calling the new operator.
int[] intArray;
intArray = new int[3];
Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared.
The following code declares and initializes an array of three items of integer type.
int[] staticIntArray = new int[3] {1, 3, 5};

//declares and initializes an array of 5 string items.
string[] strArray = new string[5] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
//You can even directly assign these values without using the new operator.
string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
//You can initialize a dynamic length array as follows:
string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };

Multi Dimensional Arrays:
A multi-dimensional arrays are also known as a rectangular array contains more than one dimension. The form of a multi-dimensional array is a matrix.It can be fixed-sized or dynamic sized.
A multi dimension array is declared as following:
string[,] mutliDimStringArray;
Initialization:
See following code snippet is an example of fixed-sized multi-dimensional arrays that defines two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array can store 4 items. Both of these arrays are initialized during the declaration.
int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[2, 2] { { "Ravi", "Anu" }, { "Gopal", "Thomas" } };
We can declare in run time also.The following code snippet creates matrix array with unlimited size.
int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] { { "Ravi", "Anu" }, { "Gopal", "Thomas" } };
we can also omit the new operator also
int[,] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
We can also initialize the array items one item at a time. The following code snippet is an example of initializing array items one at a time.
int[,] numbers = new int[3, 2];
numbers[0, 0] = 1;
numbers[1, 0] = 2;
numbers[2, 0] = 3;
numbers[0, 1] = 4;
numbers[1, 1] = 5;
numbers[2, 1] = 6;
Accessing Multi Dimensional Arrays:
A multi-dimensional array items are represented in a matrix format and to access it's items, we need to specify the matrix dimension. For example, item(1,2) represents an array item in the matrix at second row and third column.
Check the below lines of code for detail.


Console.WriteLine(numbers[0, 1]);
Console.WriteLine(numbers[2, 0]);
Console.WriteLine(numbers[2, 2]);
 
Jagged Arrays:
Jagged arrays are arrays of arrays or we can also called as nested arrays.Because here the elements of the Jagged arrays are arrays.
Initializing Jagged Arrays:
Before a jagged array can be used, its items must be initialized. The following code snippet i initialized a jagged array.The first item with an array of integers that has two integers and second item with an array of integers that has 4 integers.
int[][] JaggedArray[0] = new int[2];
int[][] JaggedArray[1] = new int[4];
We can also initialize a jagged array's items by providing the values of the array's items(during the declaration).
int[][] JaggedArray[0] = new int[2]{2, 12};
int[][] JaggedArray[1] = new int[4]{4, 14, 24, 34};
Accessing Jagged array Elements
we can access jagged arrays individually using below code.
Console.Write(intJaggedArray3[0][0]);
Console.WriteLine(intJaggedArray3[2][5]);
To access more elements at we can loop the array using foreach loop.For this the arrays properties help a lot(Ex:Length property).
Following code loops the Jagged array elements and displays output.
for (int i = 0; i < intJaggedArray3.Length; i++)
{
    System.Console.Write("Element({0}): ", i);
    for (int j = 0; j < intJaggedArray3[i].Length; j++)
    {
        System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" : " ");
    }
    System.Console.WriteLine();
}

Conclusion

This is about different types of arrays in C sharp programming.I hope this tutorial may helpful for understanding Arrays concept in C Sharp for beginners.In next tutorial i will explain about Array Classes and array class properties and methods.
If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Friday, 7 October 2016

Google organization chart using Angularjs in asp.net mvc5

00:04:00 Posted by raviteja swayampu , No comments
Hi every one thank for the comments,support and mails for previous posts.In this tutorial i am going to implement Organization Chart using Google API.This is very good API provided by the Google for rich web experiences.Thanks google for providing these API.Showing an organization structure based on roles and responsibilities is an complex task for a web developer but using API like Google Orgchart it is pretty simple.In this following tutorial we are gonna learn how to do it using Angular JS framework(a most popular java script framework for front end development).
the below are some of my previous posts on Angular JS.
Now come to this tutorial we are going to implement this orgchart using Angular js in asp.net mvc5 web application.

Implementing organizational chart

1.Create a ASP.NET MVC web application using Empty MVC template.
2.Create a Employee table and insert some data for displaying it on orgchart.
3.Use below Database code implementing Table Schema.
CREATE TABLE [dbo].[Employee] (
    [EmployeeID]   INT          NOT NULL,
    [EmployeeName] VARCHAR (50) NOT NULL,
    [Title]        VARCHAR (50) NULL,
    [BirthDate]    DATETIME     NULL,
    [ReportTo]     INT          NULL,
    PRIMARY KEY CLUSTERED ([EmployeeID] ASC)
);

---insert some data into table
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [Title], [BirthDate], [ReportTo]) VALUES (1, N'Fuller', N'Vice Presidet, Sales', N'1952-02-19 00:00:00', 0)
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [Title], [BirthDate], [ReportTo]) VALUES (2, N'Davolio', N'Sales Maager', N'1948-12-08 00:00:00', 1)
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [Title], [BirthDate], [ReportTo]) VALUES (3, N'Leverlig', N'Sales Represetative', N'1963-08-30 00:00:00', 2)
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [Title], [BirthDate], [ReportTo]) VALUES (4, N'Peacock', N'Sales Represetative', N'1937-09-19 00:00:00', 2)
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [Title], [BirthDate], [ReportTo]) VALUES (5, N'Buchaa', N'Sales Represetative', N'1955-03-04 00:00:00', 2)
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [Title], [BirthDate], [ReportTo]) VALUES (6, N'Suyama', N'Sales Maager', N'1963-07-02 00:00:00', 1)
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [Title], [BirthDate], [ReportTo]) VALUES (7, N'Kig', N'Sales Represetative', N'1960-05-29 00:00:00', 6)
INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName], [Title], [BirthDate], [ReportTo]) VALUES (8, N'Callaha', N'Sales Represetative', N'1958-01-09 00:00:00', 6)


4.Now Create a Controller and name it as HomeController.cs.
5.I crated Index action method to display the View and GetEmployeesData method to send json data to Google orgchart.
6.HomeController.cs
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AngularGoogleOrg.Models;

namespace AngularGoogleOrg.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        //Renders the Index view 
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetEmployeesData()
        {
            //send data to orgchart in json format
            using (OrgDbEntities db=new OrgDbEntities())
            {
                List data = new List();
                data = db.Employees.ToList();
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
7.Add a View to Index action method to display chart.
8.Right click on Index action -->  Add View--> name it --> add.
9.Replace the View code with below code.
@{
    ViewBag.Title = "www.mitechdev.com";
}

<h2>Angular OrgChart</h2>

<!--API reference files-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart','orgchart']}]}"></script>
<script src="~/Scripts/myscript.js"></script>

<div ng-app="myapp" ng-controller="orgController">
    <div id="chart" ng-model="chartData" org-chart="chartData" style="text-align:center">
       
    </div>
</div>


Add below angular script code for orgchart

1.Add another script file to Script folder and copy below code there.
//angular app 
var app = angular.module('myapp', []);
app.controller('orgController', ['$scope', '$http', function ($scope, $http) {

    $scope.chartData = [['Name', 'ReportTo', 'tooltip']];
    //service gets data from server
    $http.get('/home/GetEmployeesData').then(function (response) {
        //creating new object
        var newobject = [['Name', 'ReportTo', 'tooltip']];
        //push the server data into newObject
        angular.forEach(response.data, function (val) {
            newobject.push(
                [
                    {
                        v: val.EmployeeID.toString(),
                        f: f: '
' + (val.EmployeeName) + '
' + val.Title + '
' }, (val.ReportTo.toString() == "0" ? "" : val.ReportTo.toString()), (val.EmployeeName) ] ); }) //assign data to $scope object $scope.chartData = newobject; }) }]) //creating a new angular directive for orgchart app.directive('orgChart', function () { function link($scope, element, attrs) { var chart = new google.visualization.OrgChart(element[0]); $scope.$watch('chartData', function (value, oldvalue) { if (!value) { return; } var data = google.visualization.arrayToDataTable(value); var options = { 'title': '', 'allowHtml': true } chart.draw(data, options); }) } return { link: link }; })
2.Now run the application and see the output as shown below.

3.Use below styles in index page.

#chart table {
        border-spacing: 0;
        border-collapse: separate;
    }

    #chart tr td {
        line-height: 15px;
    }

    .title {
        color: red;
    }

    .google-visualization--orgchart-node-medium {
        font-size: 13px;
    }
4.Download source code for this application(source vs2015) for reference only.

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Tuesday, 4 October 2016

How to export table data to Microsoft excel in asp.net mvc application

21:35:00 Posted by raviteja swayampu , 2 comments
Hi every one welcome again to our Microsoft Technology Developments programming tutorials.In previous tutorial we learned about How to read the Microsoft Excel data file using ExcelDataReader library and How to display that data in asp.net mvc web application.read here
How to Read and Display Excel file in asp.net MVC application
Now in this tutorial we gonna implement How to export that Database(SQL) table data to Excel file using asp.net mvc web application.
for this we need to import some namespaces into our application..
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;

Steps to implement Exporting Data

1.Create a table in Local Sql express database.
2.Right click on App_Start folder in solution --> Add --> New Item --> Select Sql Database under Data section.
3.Double click on Database which you added it will be opened in Server explorer --> right click on Tables --> Add New Table.
4.I created table and inserted some data into table using below server code.
CREATE TABLE [dbo].[Exports] (
    [UserID]   INT            IDENTITY (1, 1) NOT NULL,
    [UserName] NVARCHAR (MAX) NULL,
    [Contact]  INT            NOT NULL,
    [Address]  NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_dbo.Exports] PRIMARY KEY CLUSTERED ([UserID] ASC)
);

---Insert data into table

SET IDENTITY_INSERT [dbo].[Exports] ON
INSERT INTO [dbo].[Exports] ([UserID], [UserName], [Contact], [Address]) VALUES (1, N'Raviteja', 908988377, N'Hyderabad')
INSERT INTO [dbo].[Exports] ([UserID], [UserName], [Contact], [Address]) VALUES (2, N'MarkTwain', 93384387, N'Chennai')
INSERT INTO [dbo].[Exports] ([UserID], [UserName], [Contact], [Address]) VALUES (3, N'Thomas', 98374374, N'Kochin')
INSERT INTO [dbo].[Exports] ([UserID], [UserName], [Contact], [Address]) VALUES (4, N'Rajkumar', 90988743, N'Canada')
INSERT INTO [dbo].[Exports] ([UserID], [UserName], [Contact], [Address]) VALUES (5, N'Gopal', 89788777, N'Kolkata')
SET IDENTITY_INSERT [dbo].[Exports] OFF

Add ADO.NET Entity DataModel

1.It creates all Models classes,Context classes and Connection string of application.
2.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
3.Select Database --> give name for web.config.
4.Choose your Database objects(tables) and click finish.

Create Controller to display View

1.Right click on Controllers folder --> Add --> controller --> Name it and add.
2.Right click on Index Action method -->  add view --> name it --> Add.
3.Replace view code with below code.
@{
    ViewBag.Title = "www.mitechdev.com";
}

<h3>Exporting Database table data to Excel</h3>
<p class="text-info">Click on below button to export table to Microsoft Word</p>
@Html.ActionLink("ExportToExcel", "ExportToExcel");
4.When we click on this action link it calls a action method "ExportToExcel".This method gets all the records in table and returns to Excel file using GridView class.
5.See all Controller code here.
using System.Linq;
using System.Web.Mvc;
using ExportDataToExcel.Models;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;

namespace ExportDataToExcel.Controllers
{
    public class ExportController : Controller
    {
        // GET: Export
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ExportToExcel()
        {
            using (DbEntities db=new DbEntities())
            {
                //get data from db
                var data = db.Exports.ToList();
                GridView grid = new GridView();
                //assign data to gridview
                grid.DataSource = data;
                //bind data
                grid.DataBind();
                Response.ClearContent();
                Response.Buffer = true;
                //Adding name to excel file
                Response.AddHeader("content-disposition", "attachment;filename=sampleExcel.xls");
                //specify content type of file
                //Here i specified "ms-excel" format
                //you can also specify it "ms-word" to get word document
                Response.ContentType = "application/ms-excel";
                Response.Charset = "";
                using (StringWriter sw=new StringWriter())
                {
                    using (HtmlTextWriter htwriter=new HtmlTextWriter(sw))
                    {
                        grid.RenderControl(htwriter);
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.Close();
                    }
                }
            }
                return RedirectToAction("Index");
        }
    }
}



6.Now run the application and see the output in browser window.
7.After clicking on link "ExportToExcel" we will get this.


8.Download the source code for this application from here(source vs15).This code is for reference only.Try to implement this application on your own.

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Monday, 3 October 2016

How to Read and Display Excel file in ASP.NET MVC5 web application

05:27:00 Posted by raviteja swayampu , 8 comments
In this post we are going to implement How to read Microsoft Excel file and How to display excel excel data in asp.net mvc 5 web application.To read that data from Excel file we need install a package in our application is called "ExcelDataReader" package.We can install it using Nuget package manager or using Package manager console using command.
Install-Package ExcelDataReader
1.Search package in Nuget package and install after creation of Empty web application.

installing-ExcelDataReader-in-visualstudio

What is ExcelDataReader

1.ExcelDataReader is a light weight and fast library written in C Sharp language for reading Microsoft Excel files.
2.It is a open source library developer no need to pay for licenses.
3.We can import the this library using below statement into our application.
Using System.Excel;

Reading Excel file

1.First create a Excel file with sample data like below.

reading table data to excel

2.After Add a Controller to Controllers folder.
3.And Add a Index.cshtml page to upload Excel file.In this application we gonna read and display the uploaded  excel file.(we can also read a file in some destination also by specifying path).
4.Add below code for uploading file.
@{
    ViewBag.Title = "Read Excel File and Display in mvc5";
}

<h2>Read Excel File and Display in mvc5</h2>
@using (Html.BeginForm("Index", "ReadExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken();
    @Html.ValidationSummary();

    <label class="text-info">Upload Excel File</label>
    <input type="file" class="form-control" name="uploadfile" id="uploadfile" />
    <input type="submit" value="submit" class="btn btn-default" />
}
5.The output of view is like this.
reading and displaying excel data

6.Now upload sample excel file to read the data from PC.
7.After clicking on Submit button the file come to Index (Post) action.
8.Implement below logic in Index Post action.
ReadExcelController.cs
using System.Web;
using System.Web.Mvc;
using Excel;
using System.IO;
using System.Data;

namespace ReadAndDisplayExcel.Controllers
{
    public class ReadExcelController : Controller
    {
        // GET: ReadExcel
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(HttpPostedFileBase uploadfile)
        {
            if (ModelState.IsValid)
            {
                if (uploadfile != null && uploadfile.ContentLength > 0)
                {
                    //ExcelDataReader works on binary excel file
                    Stream stream = uploadfile.InputStream;
                    //We need to written the Interface.
                    IExcelDataReader reader = null;
                    if (uploadfile.FileName.EndsWith(".xls"))
                    {
                        //reads the excel file with .xls extension
                        reader = ExcelReaderFactory.CreateBinaryReader(stream);
                    }
                    else if (uploadfile.FileName.EndsWith(".xlsx"))
                    {
                        //reads excel file with .xlsx extension
                        reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                    }
                    else
                    {
                        //Shows error if uploaded file is not Excel file
                        ModelState.AddModelError("File", "This file format is not supported");
                        return View();
                    }
                    //treats the first row of excel file as Coluymn Names
                    reader.IsFirstRowAsColumnNames = true;
                    //Adding reader data to DataSet()
                    DataSet result = reader.AsDataSet();
                    reader.Close();
                    //Sending result data to View
                    return View(result.Tables[0]);
                }
            }
            else
            {
                ModelState.AddModelError("File","Please upload your file");
            }
            return View();
        }
    }
}

Displaying Data in View

1.From above controller we read all the data in Microsoft Excel file and we return the data to View also using Strongly typed view concept.
2.Now display the data in model object in Table.
Index.cshtml
@{
    ViewBag.Title = "Read Excel File and Display in mvc5";
}
@model System.Data.DataTable
@using System.Data

<h2>Read Excel File and Display in mvc5</h2>
@using (Html.BeginForm("Index", "ReadExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken();
    @Html.ValidationSummary();

    <label class="text-info">Upload Excel File</label>
    <input type="file" class="form-control" name="uploadfile" id="uploadfile" />
    <input type="submit" value="submit" class="btn btn-default" />

    if (Model != null)
    {
        <table class="table table-responsive table-bordered">
            <thead>
                <tr>
                    @foreach(DataColumn column in Model.Columns)
                    {
                        <th>@column.ColumnName</th>
                    }
                </tr>
            </thead>
            <tbody>
                @foreach(DataRow row in Model.Rows)
                {
                    <tr>
                        @foreach(DataColumn col in Model.Columns)
                        {
                            <td>@row[col.ColumnName]</td>
                        }
                    </tr>
                }
            </tbody>
        </table>
    }
}
3.Finally after uploading excel file we will get a table like this in View...

displaying microsoft excel data in mvc application

Download source for this application from here(source VS2015 code)this code is for reference only.Try to implement this application on your own.

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Securing ASP.NET MVC application using Authorize attribute

02:16:00 Posted by raviteja swayampu 1 comment
Authorization is the process of determining the rights of an authenticated user for accessing the application's resources. The Asp.Net MVC Framework has a Authorize Attribute filter for filtering the authorized user to access a resource.Here the resource may be Controller content or action method content that are responsible to display some pages of the Asp.Net MVC web application.
Properties of Authorize attribute:
1.Roles
    Using roles property we can get/set the required access to the controller or action method.
2.Users
    Using users property we can get/set the required access to the controller or action method by user names.

Filtering Using Roles property

1.For example you want to allow the access to 'Admin Profile action in Controller' to only Admin and Sub Admin roles.
2.Then you can specify the authorize roles list to Users property as shown below.
[Authorize(Roles = "Admin,NetworkAdmin")]
public ActionResult AdminProfile()
{
 return View();
}
3.In above code i given access to the roles 'Admin' and 'NetworkAdmin'.
4.This "AdminProfile" action method is only accessible for Admin and NetworkAdmin roles only(Note: Only the user having admin roles can access).No other user can not access this action method.

Filtering Users by User property

1.Suppose you want to allow the access of AdminProfile to only henry and ravi users then you can specify the authorize users list to Users property as shown below.
[Authorize(Users = "Henry,ravi")]
public ActionResult AdminProfile()
{
 return View();
}
2.Now Henry and ravi under admin roles can only access the AdminProfile action.No other users having admin roles can not access it.

Conclusion

I hope this small tutorial is useful for you.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].And please mail([email protected]) me for requested tutorial...


Friday, 16 September 2016

Filters and attributes in asp.net mvc5

22:48:00 Posted by raviteja swayampu No comments
The main goal of this tutorial is explain about basic understanding of Action filters in asp.net mvc5. ASP.NET MVC framework provides a simple way to inject your piece of code or logic either before or after an action is executed. This is achieved by decorating the controllers or actions with ASP.NET MVC attributes or custom attributes. An attribute or custom attribute implements the ASP.NET MVC filters(filter interface) and can contain your piece of code or logic. You can make your own custom filters or attributes either by implementing ASP.NET MVC filter interface or by inheriting and overriding methods of ASP.NET MVC filter attribute class if available.
Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC application.
  1. Custom Authentication
  2. Custom Authorization(User based or Role based)
  3. Error handling or logging
  4. User Activity Logging
  5. Data Caching
  6. Data Compression

Types of Filters

The ASP.NET MVC framework provides five types of filters.
  1. Authentication filters (New in ASP.NET MVC5)
  2. Authorization filters
  3. Action filters
  4. Result filters
  5. Exception filters
  6. Authentication Filters
This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create CustomAuthentication filter. The definition of this interface is given below-
public interface IAuthenticationFilter
{
 void OnAuthentication(AuthenticationContext filterContext);

 void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below-
public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
 public void OnAuthentication(AuthenticationContext filterContext)
 { 
 //Logic for authenticating a user
 }
 //Runs after the OnAuthentication method
 public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
 { 
 //TODO: Additional tasks on the request
 }
}

Authorization Filters

The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below-
public interface IAuthorizationFilter
{
 void OnAuthorization(AuthorizationContext filterContext);
}
The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
 protected virtual bool AuthorizeCore(HttpContextBase httpContext);
 protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
 public virtual void OnAuthorization(AuthorizationContext filterContext);
 protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
}
In this way you can make your CustomAuthorize filter attribute either by implementing IAuthorizationFilter interface or by inheriting and overriding above methods of AuthorizeAttribute class.
Action Filters
Action filters are executed before or after an action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.
public interface IActionFilter
{
 void OnActionExecuting(ActionExecutingContext filterContext);
 void OnActionExecuted(ActionExecutedContext filterContext);
}

 Result Filters

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.
public interface IResultFilter
{
 void OnResultExecuted(ResultExecutedContext filterContext);
 void OnResultExecuting(ResultExecutingContext filterContext);
}

 Exception Filters

Exception filters are executed when exception occurs during the actions execution or filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method which will be executed when exception occurs during the actions execution or filters execution.
public interface IExceptionFilter
{
 void OnException(ExceptionContext filterContext);
}
ASP.NET MVC HandleErrorAttribute filter is an Exception filter which implements IExceptionFilter. When HandleErrorAttribute filter receives the exception it returns an Error view located in the Views/Shared folder of your ASP.NET MVC application.
Order of Filter Execution
All ASP.NET MVC filter are executed in an order. The correct order of execution is given below:
  1. Authentication filters
  2. Authorization filters
  3. Action filters
  4. Result filters

Configuring Filters in application

You can configure your own custom filter into your application at following three levels:
Global level
By registering your filter into Application_Start event of Global.asax.cs file with the help of FilterConfig class.
protected void Application_Start()
{
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
Controller level
By putting your filter on the top of the controller name as shown below-
[Authorize(Roles="Admin")]
public class AdminController : Controller
{
 //
}
Action level
By putting your filter on the top of the action name as shown below-
public class UserController : Controller
{
 [Authorize(Users="User1,User2")]
 public ActionResult LinkLogin(string provider)
 {
 // TODO:
 return View();
 }
}

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Wednesday, 14 September 2016

How to optimize performance using Bundling and Minification in mvc5

22:49:00 Posted by raviteja swayampu No comments

What is Bundling

Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load  performance.

Minification

Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space and comments and shortening variable names to one character.
To implement  bundling and minification in ASP.NET 4.5 version first we need to add the references of System.Web.Optimization.dll and WebGrease.dll to your MVC3 and Asp.Net 4.5 projects.

What is a Bundle

A bundle is a logical group of files that is loaded with a single HTTP request. You can create style and script bundle for css and javascripts respectively by calling BundleCollection class Add() method with in BundleConfig.cs file.In Dot net framework System.Web.Optimization class offers the bundling and minification techniques that is exist with in the Microsoft.Web.Optimization dll.
1.To implement bundling we create a BundleConfig.cs file in App_start folder.
2.Add reference dll files from nuget package manager console.

microsoft web optimization
webgrease

3.Now import reference class in  BundleConfig.cs.
4.I added some styles and script bundles using static RegisterBundles methods.
5.See below..
using System.Web;
using System.Web.Optimization;

namespace BundlingDemo
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

We can also add CDN files to the bundling using below code..
public static void RegisterBundles(BundleCollection bundles)
{
    //enable CDN support
    bundles.UseCdn = true;   

    //add link to jquery on the CDN
    var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";

    bundles.Add(new ScriptBundle("~/bundles/jquery",
                jqueryCdnPath).Include(
                "~/Scripts/jquery-{version}.js"));
}
Note:Here in above code you may come across this symbol"*".It is wildcard character is used to combines the files that are in the same directory and have same prefix or suffix with its name. Suppose you want to add all the scripts files that exist with in "~/Script" directory and have "jquery" as prefix then we can simply represent them with wildcard symbol like below.
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery*.js"));
6.This is process is same for css files also.Ex:
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));
7.To register all bundles in Application_Start event in Global.asax file.we need to add line of code
BundleConfig.RegisterBundles(BundleTable.Bundles);
protected void Application_Start()
{
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 // Other Code is removed for clarity
}
8.Now you can add the above created style and script bundles to the Layout page or where you want to use as shown below.
@System.Web.Optimization.Styles.Render("~/Content/css")
@System.Web.Optimization.Scripts.Render("~/bundles/jquery")

Minification

1.There are so many tools for minifying the js and css files online. JSMin and YUI Compressor are two most popular tools for minifying the js and css files or you can also install WebEssential extension tool to visual studio to minify the files.

Lets check the performance optimization with and without Bundling and minification in asp.net mvc sample web application.I done test performance test using Chrome web developer tools with below css and script files in _Layout.cshtml page.


<link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/Site.css" rel="stylesheet" />
    <script src="~/Scripts/bootstrap.js"></script>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Scripts/respond.js"></script>
2.It took below time to load without bundling and minification.

without optimization-in-mvc5
3.With optimization...

with web optimization
4.In first test there are 13 requests and load time is 5.42seconds.
5.When using optimizations the requests are 11 and load time decreased to 454 milli seconds what a change there is lot of reduction in load time..
6.And it also improves the browser caching ..

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Understanding Scaffolding in ASP.NET MVC

02:37:00 Posted by raviteja swayampu No comments

What is Scaffolding

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications to facilitate the rapid application development.From Visual Studio 2013 and newer versions of visual studio  includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.

This scaffolding is also used by many other MVC frameworks like Ruby on Rails, Cake PHP and Node.JS etc to generate code for basic CRUD (create, read, update, and delete) operations against your database effectively. Further you can edit or customize this auto generated code according to your need


Prerequisites for Scaffolding

To use ASP.NET Scaffolding, you must have below tools installed in system.Do not bother about this these are automatically installed while visual studio(from VS13 on wards) installation.For older versions like vs 2010,2008 need to be manually installed.
  • Microsoft Visual Studio 2013 or higher
  • Web Developer Tools (part of default Visual Studio 2013 installation)
  • ASP.NET Web Frameworks and Tools 2013 (part of default Visual Studio 2013 installation)
In ASP.NET MVC these scaffolding code is generated against the database with help of Entity Framework (a Object relational mapping framework to work with DB logic).These templates use the Visual Studio T4 templating system to generate views for basic CRUD operations with the help of Entity Framework.

Steps to add Scaffolding to create CRUD operations in MVC

1.Add a Controller to web application.

adding-scaffolding-item

2.Select below template from Visual studio 2013.

adding-controller-with-actions-and-views
3.Select Model class and context class from Drop downs in Add Controller window.

Adding-Model-class-and-Datacontextclass
4.After that visual studio automatically creates all actions methods and view for CRUD operations with help of entity framework.
5.See the folder created in solution explorer below.

scaffoladed-view-with-actions

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Tuesday, 13 September 2016

A Brief discussion on Render,Layout pages in ASP.NET MVC

06:35:00 Posted by raviteja swayampu No comments
Hi Every one Welcome again with new tutorial.In this tutorial i am going to tell a brief description about Layout pages,Render pages,Will explain about What is Render.Body() and Render Section etc.

Layouts are used to maintain a consistent look and feel across multiple views within ASP.NET MVC application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer a simple syntax and greater flexibility.
The below is HTML markup is the Basic structure of Layout page
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width" />
 <title>@ViewBag.Title</title>
 @Styles.Render("~/Content/css")
 @Scripts.Render("~/bundles/modernizr")
</head>
<body>
 @RenderBody()

 @Scripts.Render("~/bundles/jquery")
 @RenderSection("scripts", required: false)
</body>
</html>
In Asp.Net MVC, at application level we have _ViewStart file with in Views folder for defining the default Layout page for your ASP.NET MVC application.

Styles.Render and Scripts.Render

Style.Render is used to render a bundle of CSS files defined within BundleConfig.cs files. Styles.Render create style tag(s) for the CSS bundle. Like Style.Render, Scripts.Render is also used to render a bundle of Script files by rendering script tag(s) for the Script bundle.
Example:
public class BundleConfig
{
 public static void RegisterBundles(BundleCollection bundles)
 {
 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
 "~/Scripts/jquery.unobtrusive*",
 "~/Scripts/jquery.validate*",
"~/Scripts/jquery.min.js"));
 
 bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
 "~/Content/themes/base/jquery.ui.core.css",
 "~/Content/themes/base/jquery.ui.resizable.css",
 "~/Content/themes/base/jquery.ui.theme.css"));
 }
} 
Important :
1.Styles.Render and Scripts.Render generate multiple style and script tags for each item in the CSS bundle and Script bundle when optimizations are disabled.
2.When optimizations are enabled, Styles.Render and Scripts.Render generate a single style and script tag to a version-stamped URL which represents the entire bundle for CSS and Scripts.
3.You can enable and disable optimizations by setting EnableOptimizations property of BundleTable class to true or false with in Global.asax.cs file as shown below.
protected void Application_Start()
{
 //Other code has been removed for clarity
 System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
RenderBody()
RenderBody method exists in the Layout page to render child page/view. It is just like the ContentPlaceHolder in master page. A layout page can have only one RenderBody method.
RenderPage()
RenderPage method also exists in the Layout page to render other page exists in your application. A layout page can have multiple RenderPage method.
Example:
Example for Rendering page syntax is below.
@RenderPage("~/Views/Shared/_Header.cshtml")

What is Section

A section allow you to specify a region of content within a layout. It expects one parameter which is the name of the section. If you don’t provide that, an exception will be thrown. A section in a layout page can be defined by using the following code.
Ex: For example we can make<head> as one section and <body> as another section like that.see below example syntax.
@section header{
<h1>Header Content</h1>
}

<!--we can render above code using below-->
@RenderSection("header")
5.We can make this sections are optional(by default they are mandatory sections) by specifying passing a Boolean (false) parameter in RenderSection() method.

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].


Wednesday, 7 September 2016

Angular Text Editor in asp.net mvc5 web application

18:51:00 Posted by raviteja swayampu , No comments
Hi every one welcome again thank yo for  comments and recommendations for previous post.In today's tutorial i am going to teach you How to integrate Angular Text Editor in asp.net mvc5 web application.This Text Editor is an angular plugin that can make a text area html element into Text Editor.This is WYWIWYS type of Text Editor.
In computing, a WYSIWYG editor is a system in which content (text and graphics) displayed onscreen during editing appears in a form closely corresponding to its appearance when printed or displayed as a finished product, which might be a printed document, web page, or slide presentation. WYSIWYG is an acronym for "what you see is what you get".
Let see some of  my previous posts,
Now see how to implement Angular Text Editor in our asp.net mvc web application.
1.Create asp.net web application using empty mvc template.

Create a Controller

1.Right click on Controllers folder --> add --> Controller--> name it.
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
2.Add View to the Index action method by right click on index action --> Add View --> name it --> add.
3.Add below reference files that are required for Angular Text editor.
<!--Angular Text Editor Reference files-->
<link href="http://jqueryte.com/css/jquery-te.css" rel="stylesheet"/>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.9/angular-sanitize.min.js"></script>
<script type="text/javascript" src="http://jqueryte.com/js/jquery-te-1.4.0.min.js"></script>

Add angular script code for Text Editor

4.Add below angular script to make text area as Text Editor.
5.Here,i am storing the text editor data in $scope.descriptionzone and displaying HTML output of the data in below Text Editor.
 function Controller($scope) {
        //object that stores the editor (textbox) data.
        $scope.descriptionzone = undefined;
        //resets the Editor data
        $scope.reset = function () {
            $scope.descriptionzone = null;
        }
    };

    angular.module('angularteexample', []).directive('angularte', function () {
        return {
            restrict: 'A',
            require: '^ngModel',
            link: function (scope, element, attrs, ngModel) {
                $(function () {
                    element.jqte({
                        // On focus show the toolbar
                        focus: function () {
                            scope.$apply(function () {
                                element.parents(".jqte").find(".jqte_toolbar").show();
                                element.parents(".jqte").click(function () { element.parents(".jqte").find(".jqte_toolbar").show(); });
                            });
                        },
                        // On blur hide the toolar
                        blur: function () {
                            scope.$apply(function () {
                                element.parents(".jqte").find(".jqte_toolbar").hide();
                            });
                        },
                        // On change refresh the model with the textarea value
                        change: function () {
                            scope.$apply(function () {
                                ngModel.$setViewValue(element.parents(".jqte").find(".jqte_editor")[0].innerHTML);
                            });
                        }
                    });
                    element.parents(".jqte").find(".jqte_toolbar").hide();
                });

                // On render refresh the textarea with the model value 
                ngModel.$render = function () {
                    element.parents(".jqte").find(".jqte_editor")[0].innerHTML = ngModel.$viewValue || '';
                };
            }
        }
    });

6.See the complete code of the Index below.
@{
    ViewBag.Title = "www.mitechdev.com";
}
<h3>Angular Text Editor in asp.net mvc5 application</h3>
<!--Angular Text Editor Reference files-->
<link href="http://jqueryte.com/css/jquery-te.css" rel="stylesheet"/>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.9/angular-sanitize.min.js"></script>
<script type="text/javascript" src="http://jqueryte.com/js/jquery-te-1.4.0.min.js"></script>

<script>
    function Controller($scope) {
        //object that stores the editor (textbox) data.
        $scope.descriptionzone = undefined;
        //resets the Editor data
        $scope.reset = function () {
            $scope.descriptionzone = null;
        }
    };

    angular.module('angularteexample', []).directive('angularte', function () {
        return {
            restrict: 'A',
            require: '^ngModel',
            link: function (scope, element, attrs, ngModel) {
                $(function () {
                    element.jqte({
                        // On focus show the toolbar
                        focus: function () {
                            scope.$apply(function () {
                                element.parents(".jqte").find(".jqte_toolbar").show();
                                element.parents(".jqte").click(function () { element.parents(".jqte").find(".jqte_toolbar").show(); });
                            });
                        },
                        // On blur hide the toolar
                        blur: function () {
                            scope.$apply(function () {
                                element.parents(".jqte").find(".jqte_toolbar").hide();
                            });
                        },
                        // On change refresh the model with the textarea value
                        change: function () {
                            scope.$apply(function () {
                                ngModel.$setViewValue(element.parents(".jqte").find(".jqte_editor")[0].innerHTML);
                            });
                        }
                    });
                    element.parents(".jqte").find(".jqte_toolbar").hide();
                });

                // On render refresh the textarea with the model value 
                ngModel.$render = function () {
                    element.parents(".jqte").find(".jqte_editor")[0].innerHTML = ngModel.$viewValue || '';
                };
            }
        }
    });
</script>
<div ng-app="angularteexample">
    <div ng-controller="Controller">
        <p>
            <!--Text Editor element-->
            <textarea angularte ng-model="descriptionzone"></textarea>
        </p>
        <p>Test: 
            <!--it shows the data we entered in Editor-->
            <!--Here it shows the Html output of the Editor data-->
            <div style="background-color:darkgreen;color:white;">{{descriptionzone}}</div>
        </p>
        <p>Click Reset button to reset the Editor: <button type="button" class="btn btn-default" ng-click="reset()">Reset Editor</button></p>
    </div>
</div>
7.For more information about this Angular TextEditor visit official page www.jqueryte.com.
8.See the output of the application.
Angular Text Editor in asp.net mvc5 web application

9.The below is html output of the text editor data.
10.when click on Reset Edior button the in editor is erased.
11.Downlaod the source code of the application Source Code (VS15).

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Tuesday, 6 September 2016

How to display attrative tooltips using Tispo jquery plugin in mvc5

22:12:00 Posted by raviteja swayampu , , No comments
In this article i am going to introduce a new jquery plugin for attractive tool tips.we are seeing tool tips in many of the websites to simplify user understand of the application.So,I searched for jquery plugin that is best suitable for web applications which are build by asp.net mvc framework.we can also use this Tispo jquery plugin in non microsoft technologies like JAVA,PHP.It is very easy to use.We can also apply animations,effects and can bind actions also.
Now see how we are going to use this plugin in our asp.net mvc web application.

Required Files:

<!--Jquery script plugins-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!--Tipso plugin references-->
<link rel="stylesheet" href="http://tipso.object505.com/tipso.css">
<script src="http://tipso.object505.com/tipso.js"></script>
<link rel="stylesheet" href="http://tipso.object505.com/animate.css">
Note: Before adding this files in view remove the jquery reference from _Layout.cshtml page in Shared folder in Views  folder.

Create Controller and add view

1.Right click on Controllers folder --> add -->Controller(i named as HomeController).
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
2.Add View to Index action method with empty view template.
3.Add above reference files to the Index view.
$("#top-right").tipso({
            //position where we should display the tooltip on link
            position: 'top-right',
            //background color of the text
            background: 'rgba(0,0,0,0.8)',
            //color of title
            titleBackground: 'tomato',
            //Content should display in title
            titleContent: 'Top Right',
            useTitle: false,
            //enabling hover effect
            tooltipHover: true,
            //animation occurs when we place cursor on link
            animationIn: 'tada',
            //animation occurs when we remove the cursor on link
            animationOut: 'flash'
        });
4.Replace the complete view code with below code.
@{
    ViewBag.Title = "Index";
}

<h2>Jquery attractive Tooltips using Tispso plugin</h2>
<!--Jquery script plugins-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!--Tipso plugin references-->
<link rel="stylesheet" href="http://tipso.object505.com/tipso.css">
<script src="http://tipso.object505.com/tipso.js"></script>
<link rel="stylesheet" href="http://tipso.object505.com/animate.css">

<script type="text/javascript">
    $(document).ready(function () {
        $("#top-right").tipso({
            //position where we should display the tooltip on link
            position: 'top-right',
            //background color of the text
            background: 'rgba(0,0,0,0.8)',
            //color of title
            titleBackground: 'tomato',
            //Content should display in title
            titleContent: 'Top Right',
            useTitle: false,
            //enabling hover effect
            tooltipHover: true,
            //animation occurs when we place cursor on link
            animationIn: 'tada',
            //animation occurs when we remove the cursor on link
            animationOut: 'flash'
        });
        $("#top-left").tipso({
            position: 'top-left',
            background: 'rgba(0,0,0,0.8)',
            titleBackground: 'tomato',
            titleContent: 'Top',
            useTitle: false,
            tooltipHover: true,
            animationIn: 'tada',
            animationOut: 'flash'
        });
        $("#right").tipso({
            position: 'right',
            background: 'rgba(0,0,0,0.8)',
            titleBackground: 'green',
            titleContent: 'Top',
            useTitle: false,
            tooltipHover: true,
            animationIn: 'bounceIn',
            animationOut: 'bounceOut'
        });
        $("#destroy-tooltip").tipso({
            position: 'bottom',
            background: 'rgba(0,0,0,0.8)',
            titleBackground: 'green',
            titleContent: 'Top',
            useTitle: false,
            tooltipHover: true,
            animationIn: 'fadeIn',
            animationOut: 'shake'
        });
        //destroy tooltip
        $("#btn-destroy").on('click', function (e) {
            $("#destroy-tooltip").tipso('destroy');
            e.preventDefault();
        });
    });
</script>
<div>
    <p>
        1.<a id="top-right" href="www.mitechdev.com" data-tipso="This is top right tooltip buddy using Tipso plugin">         
              www.mitechdev.com</a> is a good programming blog(Top-right)
    </p>
    <p>
        2.<a id="top-left" href="www.mitechdev.com" data-tipso="This is top right tooltip buddy using Tipso plugin">
            www.mitechdev.com
        </a> is a good programming blog(Top-left)
    </p>
    <p>
        3.<a id="right" href="www.mitechdev.com" data-tipso="This is top right tooltip buddy using Tipso plugin">
            www.mitechdev.com
        </a> is a good programming blog
    </p>
    <p>
        4.<a id="destroy-tooltip" href="www.mitechdev.com" data-tipso="This is top right tooltip buddy using Tipso plugin">
            www.mitechdev.com
        </a> is a good programming blog<input type="button" class="btn btn-default" id="btn-destroy" value="destroy tooltip"/>
    </p>
</div>

5.To destroy the tool tip use below code..
 //destroy tooltip
        $("#btn-destroy").on('click', function (e) {
            $("#destroy-tooltip").tipso('destroy');
            e.preventDefault();
        });
6.Finally run the application and see the output in browser.
How to display attrative tooltips using Tispo jquery plugin in mvc5
7.for right and top-left will be like this..

How to display attrative tooltips using Tispo jquery plugin in mvc5
Download source code for this application Source Code(VS2015).

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].