October 2016 ~ MiTechDev.com

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 , 7 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(ravitejaswayampu@gmail.com) me for requested tutorial...