Tuesday, 3 January 2017

Learning Angular Js in ASP.NET MVC

Leave a Comment

Introduction

Angular Js is an open source framework developed by Tech giant Google.AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you would otherwise have to write.

Angular supports the MVC based approach for developing Single page applications.It also support twoway data binding.

Here in this blog i am going to cover all angular js components(from data binding to expressions,controllers,services etc) with help of simple applications in step by step using ASP.NET MVC as a server side programming language.We will learn about angular js by going through below tutorials.


Angular tutorials start here

1.Introduction to angular js
2.How to setup Angular js in ASP.NET MVC
3.How to get Data from Database using Angular js in MVC 5 application
4.How to create a Login page using Angular JS
5.How to create a Registration form using Angular JS
6.how to get and display table data from database using angular
7.CRUD operations using angular js (Most viewed tutorial in this blog).
8.Implementing Cascading Dropdownlist
9.How to implement Angular UI Grid in ASP.NET MVC 5
10.How to implement Modal popup using Angular UI in ASP.NET MVC
11.Understanding routing in Angular JS
12.How to Implement Auto Complete Textbox using Angular js in MVC5
13.Implementing DatePicker using Angular UI in MVC5
14.How to integrate Google Maps in MVC 5 application
15.Implementing Star Rating using AngularJS
16.MultiBar Horizonthal Chart using Angular JS(nvd3.js)
17.Angular nvd3 Force Direction Graph in MVC5 application
18.Implementing Event Scheduling in Angular UI calendar part1
19.CRUD operations on Angular UI Calendar(Event Scheduling) part-2
20.Kendo Grid implementation using Angular
21.Tree View implementation in Angular JS
22.Integrating Angular Text Editor in ASP.NET MVC application
23.Google Organization Chart using Angular js

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].

Sunday, 1 January 2017

Working with arrays in C Sharp Programming part-2

Leave a Comment
In previous tutorial i explained about What are arraya and Different types of arrays(Working with arrays in C Sharp Programming) in C Sharp Programming.In present tutorial i am going to explain about Array class,How we are going to use this array class and its method and properties in C Sharp programming.
Note: If you new to arrays please click on above link to know basics of arrays.

What is Array Class

Array class is the parent class of all arrays and it provides functionality for creating, manipulating, searching, and sorting arrays in .NET Framework.

The definition for array class is defined in System Namespace (arrays class definitions are imported using Using System namespace).It is the base class for arrays in C#. Array class is an abstract base class that means we cannot create an instance of the Array class.

Creating an Array Using array class

1.Array class provides the CreateInstance method to construct an array. The CreateInstance method takes first parameter as the type of items and second and third parameters are the dimension and their range. Once an array is created, we use SetValue method to add items to an array.
2.The following are different overriding methods for CreateInstance method.
public static Array CreateInstance(Type elementType, int length);        
public static Array CreateInstance(Type elementType, params int[] lengths);      
public static Array CreateInstance(Type elementType, params long[] lengths);     
public static Array CreateInstance(Type elementType, int length1, int length2);     
public static Array CreateInstance(Type elementType, int length1, int length2, int length3);
3.The following code snippet creates an array and adds three items to the array. As you can see the type of the array items is string and range is 3. You will get an error message if you try to add 4th item to the array.
Array stringArray = Array.CreateInstance(typeof(String), 3);
stringArray.SetValue("Mahesh Chand", 0);
stringArray.SetValue("Raj Kumar", 1);
stringArray.SetValue("Neel Beniwal", 2);
Note: Calling SetValue for existing value in array overrides the previous value in array.
4.To create an multi dimensional array we will use foreach loop as follows.
Array intArray3D = Array.CreateInstance(typeof(Int32), 2, 3, 4);
for (int i = intArray3D.GetLowerBound(0); i <= intArray3D.GetUpperBound(0); i++)
    for (int j = intArray3D.GetLowerBound(1); j <= intArray3D.GetUpperBound(1); j++)
        for (int k = intArray3D.GetLowerBound(2); k <= intArray3D.GetUpperBound(2); k++)
        {
            intArray3D.SetValue((i * 100) + (j * 10) + k, i, j, k);
        }
 
foreach (int ival in intArray3D)
{
    Console.WriteLine(ival);
}


Array Class Properties

IsFixedSize: Return a value indicating if an array has a fixed size or not.

IsReadOnly: Returns a value indicating if an array is read-only or not.

LongLength: Returns a 64-bit integer that represents total number of items in all the dimensions of an array.
Length: Returns a 32-bit integer that represents the total number of items in all the dimensions of an array.
Rank: Returns the number of dimensions of an array.
The following code snippet shows how we use array properties.
int[] intArray = new int[3] {0, 1, 2};
if(intArray.IsFixedSize)
{
    Console.WriteLine("Array is fixed size");
    Console.WriteLine("Size :" + intArray.Length.ToString());
    Console.WriteLine("Rank :" + intArray.Rank.ToString());
}

Searching for an Item in an Array

The BinarySearch static method of Array class can be used to search for an item in an array. This method uses the binary search algorithm to search for an item in array. The method takes at least two parameters. First parameter is the array in which you would like to search and the second parameter is an object that is the item you are looking for. If an item is found in the array, the method returns the index of that item (based on first item as 0th item). Otherwise method returns a negative value.
syntax:
public static int BinarySearch(Array array, object value);
Example for Binary search in array.
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
 
// Find an item
object name = "Neel";
int nameIndex = Array.BinarySearch(stringArray, name);
if (nameIndex >= 0)
    Console.WriteLine("Item was at " + nameIndex.ToString() + "th position");
else
    Console.WriteLine("Item not found");


Note: But to perform search on array we must sort an array before searching.

Sorting Items in an Array

The Sort static method of the Array class can be used to sort array items. This method has many overloaded forms. The simplest form takes as a parameter the array you want to sort. Listing 5 uses the Sort method to sort array items. Using the Sort method, you can also sort a partial list of items.
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
 
// Find an item
object name = "Neel";
int nameIndex = Array.BinarySearch(stringArray, name);
if (nameIndex >= 0)
    Console.WriteLine("Item was at " + nameIndex.ToString() + "th position");
else
    Console.WriteLine("Item not found");
 
Console.WriteLine();
 
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Sorted Array");
Console.WriteLine("---------------------");
Array.Sort(stringArray);
foreach (string str in stringArray)
{
    Console.WriteLine(str);
} 
Alternatively the Sort method takes starting index and number of items after that index. The following code snippet sorts 3 items starting at 2nd position.
Array.Sort(stringArray, 2, 3);

Getting and Setting Values of Array

The GetValue and SetValue methods of the Array class can be used to get and set values of an array's items. The code listed in Listing 4 creates a 2-dimensional array instance using the CreateInstance method. After that I use the SetValue method to add values to the array.
Array names = Array.CreateInstance(typeof(String), 2, 4);
names.SetValue("Rosy", 0, 0);
names.SetValue("Amy", 0, 1);
names.SetValue("Peter", 0, 2);
names.SetValue("Albert", 0, 3);
names.SetValue("Mel", 1, 0);
names.SetValue("Mongee", 1, 1);
names.SetValue("Luma", 1, 2);
names.SetValue("Lara", 1, 3);
int items1 = names.GetLength(0);
int items2 = names.GetLength(1);
for (int i = 0; i < items1; i++)
    for (int j = 0; j < items2; j++)
        Console.WriteLine(i.ToString() + "," + j.ToString() + ": " + names.GetValue(i, j));
In end of the program i got the values and names of array using GetValue method.

Reverse an array items

In similar to sort method we use Reverse method to reverse the array items.
Array.Reverse(stringArray);
//  Array.Sort(stringArray, 2, 3);
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}

Clear items of array

The Clear static method of the Array class removes all items of an array and sets its length to zero. This method takes three parameters - first an array object, second starting index of the array and third is number of elements. The following code clears two elements from the array starting at index 1 (means second element of the array).
syntax:
Array.Clear(array name, startindex, endindex);
Note: Keep in mind, the Clear method does not delete items. Just clear the values of the items.

Get the size of an array

The GetLength method returns the number of items in an array. The GetLowerBound and GetUppperBound methods return the lower and upper bounds of an array respectively. All these three methods take at least a parameter, which is the index of the dimension of an array. The following code snippet uses all three methods.
Console.WriteLine(stringArray.GetLength(0).ToString());
Console.WriteLine(stringArray.GetLowerBound(0).ToString());
Console.WriteLine(stringArray.GetUpperBound(0).ToString()); 

Copying an array

The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types. 
Array oddArray = Array.CreateInstance(Type.GetType("System.Int32"), 5);
oddArray.SetValue(1, 0);
oddArray.SetValue(3, 1);
oddArray.SetValue(5, 2);
oddArray.SetValue(7, 3);
oddArray.SetValue(9, 4);
// Creates and initializes a new Array of type Object.
Array objArray = Array.CreateInstance(Type.GetType("System.Object"), 5);
Array.Copy(oddArray, oddArray.GetLowerBound(0), objArray, objArray.GetLowerBound(0), 4);
int items1 = objArray.GetUpperBound(0);
for (int i = 0; i < items1; i++)
    Console.WriteLine(objArray.GetValue(i).ToString());
You can even copy a part of an array to another array by passing the number of items and starting item in the Copy method. The following format copies a range of items from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
public static void Copy(Array, int, Array, int, int);

Cloning an Array

Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to. The following code snippet creates a cloned copy of an array of strings.
string[] clonedArray = (string[])stringArray.Clone();
These are the main array methods that we daily use in C Sharp programming.

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].

Thursday, 29 December 2016

Working with Arrays in C Sharp Programming

Leave a Comment

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

Leave a Comment
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

1 comment
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].