June 2016 ~ MiTechDev.com

Monday, 27 June 2016

How to integrate Google Maps using angular js in MVC 5 application

23:14:00 Posted by raviteja swayampu , 4 comments
Hello every one thank for your support.Today i came with another real time concept "Integrating Google maps in ASP.NET MVC5 web applications".In previous days we find the contact details in any company or organisation contact pages but now the things are changed.Now we are searching any address through google maps.So,There is a need to integrate map address of our organisation or to show the identity many of the site are sharing their address in the maps and displaying in their websites.
The above is main reason for integrating Maps in websites.Now in this tutorial i am going to explain How to integrate Google Maps in our MVC 5 web application using Angular js.For this Google provides Map API for this problem.we can easily integrate it in our application by passing Coordinates(latititude and Langitude).
The application final output is like below screen shot..

Step 1: Create New Project.

Go to File --> New --> Project --> ASP.NET  Web Application under web section --> Entry Application Name --> Click OK --> Select Empty template --> Checked MVC -->click OK

Step 2: Add a Database to project.

Go to Solution Explorer --> Right Click on App_Data folder --> Add --> New item --> Select SQL Server Database Under Data --> Enter Database name --> Add.

Step 3: Create a table for store data

1.Open Database -->Right Click on Table folder --> Add New Table --> Add Columns --> Save --> Enter table name --> Ok.
2.In this tutorial I have created a table(Locations) to store the Markers Location data.
3.The table contains following columns.
CREATE TABLE [dbo].[Locations] (
    [LocationID] INT           IDENTITY (1, 1) NOT NULL,
    [Title]      VARCHAR (100) NOT NULL,
    [Lat]        VARCHAR (10)  NOT NULL,
    [Long]       VARCHAR (10)  NOT NULL,
    [Address]    VARCHAR (200) NOT NULL,
    [ImagePath]  VARCHAR (200) NOT NULL,
    PRIMARY KEY CLUSTERED ([LocationID] ASC)
);

Step 4: Add Entity Data Model.

1.Go to Solution Explorer -->Right Click on Project name form Solution Explorer --> Add --> New item --> Select ADO.net Entity Data Model under data --> Enter model name --> Add.
2.A popup window will come (Entity Data Model Wizard) --> Select Generate from database -->click Next
3.Chose your data connection --> select your database -->Select Entity framework version(5.0 or 6.0) next --> Select tables -->Enter Model Namespace name-->Click Finish.

Step 5: Add Controller for Index and Get Markers info

1.Create a Controller and name it as HomeController.cs
2.Replace the code with following code...
 public class HomeController : Controller
    {
        //This action displays Maps information
        public ActionResult Index()
        {
            return View();
        }
        //GetAllLocation - for fetch all the location from database and show in the view
        //Shows all the locations in default map here.
        public JsonResult GetAllLocation()
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = dc.Locations.OrderBy(a => a.Title).ToList();
                return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }
        //This method gets the markers info from database.
        public JsonResult GetMarkerData(int locationID)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                Location l = null;
                l = dc.Locations.Where(a => a.LocationID.Equals(locationID)).FirstOrDefault();
                return new JsonResult { Data = l, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }
    }

Step 6: Add Script files to the application

1.Add another script file for writing angular scripts there.
2.Replace it with below code..
var app = angular.module('myapp', ['uiGmapgoogle-maps']); //dependency we should add to angular application
app.controller('mapsController', function ($scope, $http) {
    //this is default coordinates for the map when it loads for first time
    $scope.map = { center: { latitude: 17.406278, longitude: 78.469060 }, zoom: 16 }
    $scope.markers = [];
    $scope.locations = [];
    //to get all the locations from the server
    $http.get('/home/GetAllLocation').then(function (data) {
        $scope.locations = data.data;
    }, function () {
        alert('Error');
    });
    //service that gets makers info from server
    $scope.ShowLocation = function (locationID) {
        $http.get('/home/GetMarkerData', {
            params: {
                locationID: locationID
            }
        }).then(function (data) {
            $scope.markers = [];
            $scope.markers.push({
                id: data.data.LocationID,
                coords: { latitude: data.data.Lat, longitude: data.data.Long },
                title: data.data.title,     //title of the makers
                address: data.data.Address,     //Address of the makers
                image : data.data.ImagePath     //image --optional
            });
            //set map focus to center
            $scope.map.center.latitude = data.data.Lat;
            $scope.map.center.longitude = data.data.Long;
        }, function () {
            alert('Error'); //shows error if connection lost or error occurs
        });
    }
    //Show or Hide marker on map using options passes here
    $scope.windowOptions = {
        show: true
    };
});
3.Here ,Every thing i explained using comments in code.I think you can easily understand by seeing them.
Add Angular Reference files to project in Index page or _Layout page.
4.we can use either CDN links or can install using Nuget Package Manager console.
Using Nuget:


Using CDN links
 @* AngularJS library *@
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
    @* google map*@
    <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script> 
    <script src="//rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>
    <script src="~/Scripts/map.js"></script>

Step 7:Add Index view for UI

1.Add view to the Index action method.And replace below code
<div ng-app="myapp" ng-controller="mapsController">
    <!--It displays the markers links-->
    <div class="locations">
        <ul>
            <li ng-repeat="l in locations" ng-click="ShowLocation(l.LocationID)"><a href="#">{{l.Title}}</a></li>
        </ul>
    </div>
    <div class="maps">
        <!-- Add directive code (gmap directive) for show map and markers-->
        <ui-gmap-google-map style="box-shadow:2px 2px 2px 2px lightgrey" center="map.center" zoom="map.zoom">
            <ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
                <ui-gmap-window options="windowOptions" show="windowOptions.show">
                    <div style="max-width:200px">
                        <div class="header"><strong>{{marker.title}}</strong></div>
                        <div id="mapcontent">
                            <p>
                                <img ng-src="{{marker.image}}" style="width:200px; height:100px" />
                                <div>{{marker.address}}</div>
                            </p>
                        </div>
                    </div>
                </ui-gmap-window>
            </ui-gmap-marker>
        </ui-gmap-google-map>
    </div>
</div>

Styles for Maps:
.angular-google-map-container {
        height: 300px;
        box-shadow:2px 2px 3px 3px lightgrey;
    }
    .angular-google-map {
        width: 80%;
        height: 100%;
        margin: auto 0px;
    }
Finally run the application and see the output in browser ..

Download code of this application here Source code 

Conclusion

I hope this tutorial may helpful for a every reader and you learn how to integrate it in MVC application.Please subscribe and follow this blog for daily updates..


Saturday, 25 June 2016

Concept of Views in Sql server

20:12:00 Posted by raviteja swayampu , No comments

What is View:

A View is a logical collection of tables in SQL server which are stored SQL server database.(A view is a virtual table that is not physically exists but it is created by joining of tables in sql server).
View appears like a table to the user (DB user). These views increases the performance of the sever.Views contains columns,rows just like tables in sql sever.These definitions of the tables are stored in Data base.
Views are used for security purpose in databases, views  restricts the user from viewing certain column and rows means by using view we can apply the restriction on accessing the particular rows and columns for specific user. Views display only those data which are mentioned in the query, so it shows only data which is returned by the query that is defined at the time of creation of the View.
syntax of View:
CREATE VIEW [schema_name.]view_name AS
  [ WITH { ENCRYPTION | SCHEMABINDING | VIEW_METADATA }
  SELECT expressions
  FROM tables
  [WHERE conditions];

1.Here the schema_name is the schema that we want to create(view tables).
2.View_name is the name of the view we are going to create.
3.Encryption is the security that we can apply on view.
4.SCHEMABINDING  ensures that the underlying table definitions can not be modified so as to affect the view.
5.VIEW_METADATA will ensure that SQL Server has metadata about the VIEW.
6.The columns and calculations that you want to add view are added using expressions.
7.tables here we add the tables that defines the View Schema.We must add at least one table here to create a view.
8.In where clause we implement some conditions that should be followed by view.But it is an optional.

A sample example View
CREATE VIEW PRODINVENTION AS
  SELECT products.product_id, products.product_name, inventory.quantity
  FROM products
  INNER JOIN inventory
  ON products.product_id = inventory.product_id
  WHERE products.product_id >= 1000;
9.We can retrieve table using SELECT statement like we select a table.
SELECT * 
FROM PRODINVENTION 

10.We can update the view using ALTER statement and can DROP view using DROP statement.
Note : we can DROP the tables that are used by Views in SQL server.If we delete the those tables the View remains exist in the Database.
Syntax for Update & Drop
---for updation of view
ALTER VIEW [schema_name.]view_name AS
  [ WITH { ENCRYPTION | SCHEMABINDING | VIEW_METADATA }
  SELECT expressions
  FROM tables
  WHERE conditions;
--to drop view
DROP VIEW view_name;

Advantages of Views

Security
We can restrict the user to access the confidential view that contains the important data.

Query Simplicity
A view can draw data from several different tables and present it as a single table, turning multi-table queries into single-table queries against the view.so instead of writing all statements we can retrieve using simple SELECT statements with views.

Structural simplicity
Views can give a user a "personalized" view of the database structure, presenting the database as a set of virtual tables that make sense for that user.

Consistency
A view can present a consistent, unchanged image of the structure of the database, even if the underlying source tables are split, restructured, or renamed.For example if we change the tables that contains view data may changed the view data does not changed.

Data Integrity
If data is accessed and entered through a view, the DBMS can automatically check the data to ensure that it meets the specified integrity constraints.

Logical data independence.

 View can make the application and database tables to a certain extent independent. If there is no view, the application must be based on a table. With the view, the program can be established in view of above, to view the program with a database table to be separated.

Disadvantages of views

Performance
Views create the appearance of a table, but the DBMS must still translate queries against the view into queries against the underlying source tables. If the view is defined by a complex, multi-table query then simple queries on the views may take considerable time(more time).

Update restrictions
When a user tries to update rows of a view, the DBMS must translate the request into an update on rows of the underlying source tables. This is possible for simple views, but more complex views are often restricted to read-only.

Conclusion

This post may help you for better understanding of Views concept in SQL server.If you recommend any changes or modifications to this post please contact me.


Friday, 24 June 2016

Implementing DatePicker using Angular UI in MVC5

06:20:00 Posted by raviteja swayampu , , No comments
Hi every one in this tutorial i am going to explain about How to implement popup date picker using Angular UI in ASP.NET MVC5 application.Previously i shown how to implement date picker using jquery UI.It is very simple and easy to implement.In the same way for Angular enabled websites we implement date pickers using Angular User Interface.
These following are some simple implementations using Angular in MVC5
As a part of the Angular UI series today i am explaining about how to work with angular UI popup date picker.The final UI of Date picker is like below.

Implementing DatePicker using Angular UI in MVC5

Implementing Datepicker

Step 1: Create web application 

1.open visual studio 2013 and create New project.
2.Use MVC template to create necessary files for the project web applicaton.
3.Add below script reference files for Date picker.
Note : we can include these reference files through Nuget package Manager console or can download directly from site.
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <!--application script files for angular components-->
    <script src="~/Scripts/app.js"></script>

Step 2 :create Controller and View

1.Create Controller and name it as HomeController.cs.
2.Create Index action and add a View and name it as Index.cshtml.
3.Replace the Index.cshtml code with the below code
@{
    ViewBag.Title = "Home Page";
}
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <!--application script files for angular components-->
    <script src="~/Scripts/app.js"></script>

    <div ng-app="ui.bootstrap.demo" ng-controller="DatepickerPopupDemoCtrl">
        <h4>Popup</h4>
        <div class="row">
            <div class="col-md-6">
                <p class="input-group">
                    <input type="text" class="form-control"
                           uib-datepicker-popup="{{format}}"    @*format of the date picked*@
                           ng-model="dtpicker"                  
                           is-open="popup1.opened"              @*to show or hide the popup it is used*@
                           popup-placement="bottom-right"       @*display position of the datepicker either bottom/right/right-left/bottom-left etc*@
                           datepicker-options="dateOptions"     @*datepicker options like minDate,maxDate etc*@
                           ng-required="true"
                           close-text="Close"                   @*by deault 'Done' you can chage it*@
                           alt-input-formats="altInputFormats"  @*a list of alternative formats for manual entry*@
                           show-button-bar="true"           @*By default button bar showed at end of datepicker popup*@
                           close-on-date-selection="true" />    @*Closes the popup after selection of date*@
                    @*datepicker-popup-template-url="url of template" --we can over ride popup template url
                    datepicker-template-url="url"  --override datepicker url*@
                    <span class="input-group-btn">
                        <button type="button" class="btn btn-default" ng-click="open()"><i class="glyphicon glyphicon-calendar"></i></button>
                    </span>
                </p>
            </div>
        </div>
        <div class="row">
            <h3>You selected:</h3><br />
            <!--Displays the selected date here-->
            <pre>Selected date is: <em>{{dtpicker | date:'fullDate' }}</em></pre>
        </div>
    </div>
4.Here,in the above code i almost explained about the directives used in the Date picker input element.
5.For more details and options please click here.

Step 3: Add Angular script files 


1.create a script file in the Scripts folder(in this application i named i as app.js).
2.Now replace the code with the below code..
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('DatepickerPopupDemoCtrl', function ($scope) {
    $scope.dateOptions = {
        //dateDisabled: disabled,   disables the popup
        formatYear: 'yy',
        maxDate: new Date(2020, 5, 22),
        minDate: new Date(),
        startingDay: 1,
    };
    /*// Disable weekend selection
    function disabled(data) {
        var date = data.date,
          mode = data.mode;
        return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
    }*/
    $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    $scope.format = $scope.formats[0];
    $scope.open = function () {
        $scope.popup1.opened = true;
    };
    $scope.popup1 = {
        opened: false
    };
    /*we can set date
    $scope.setDate = function (year, month, day) {
        $scope.dtpicker = new Date(year, month, day);
    };*/
});
3.We must include the dependencies ngAnimate and ui.bootstrap to the angular application.
4. we can specify the format,can disable the selection of week ends.
5.Finally run the application and see the output in browser.

Implementing DatePicker using Angular UI in MVC5

Download the source code of the application here Source

Conclusion:

I hope this tutorial may helpful for many readers.Please subscribe to this blog www.mitechdev.com to get posts to your mail inbox.And follow through social networks(Facebook,twitter,google plus) for daily updates...


Thursday, 23 June 2016

Differences between DELETE and TRUNCATE in SQL

21:47:00 Posted by raviteja swayampu , No comments
Differences between DELETE and TRUNCATE is a famous interview question for both freshers and experienced people
There is a little bit difference between this two commands.When i am learning SQL i was also confused a little bit for understanding this two commands.
Now i completely understand the differences between these two commands and to help the fresher people for their interviews i am sharing this in my blog.

TRUNCATE command:

TRUNCATE will removes all the rows from a table and there will be no data in the table after we run the truncate command.
Note:It can not removes the schema of the table also.Schema means the table structure(columns,keys etc).

Features of TRUNCATE:

  • TRUNCATE is faster and uses less system and transaction log resources than DELETE.
  • TRUNCATE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log.
  • TRUNCATE removes all rows from a table, but the table structure(its columns, constraints, indexes and so on, remains)The counter used by an identity for new rows is reset to the seed for the column.
  • You cannot use TRUNCATE on a table referenced by a foreign key constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
  • TRUNCATE cannot be rolled back.
  • TRUNCATE is DDL(Data Definition Language) Command.
  • It can be applied on table level only.
  • DELETE reset identity of the table

Delete Command:

Delete command removes the rows from a table based on the condition that we provide with a WHERE clause.If we did not provided any WHERE clause it removes entire table.
Note:Delete command also can not remove the table definition.If you want to remove Table Definition also use DROP command.It completely removes both table schema and data.DROP is also applied on table level(belongs to DDL).

Features of  DELETE:

  • DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
  • If you want to retain the identity counter, use DELETE instead. 
  • DELETE Can be used with or without a WHERE clause
  • DELETE Activates Triggers.
  • DELETE can be rolled back(in Transaction queries).
  • DELETE is DML(Data Manipulation Language means queries that used to manipulate the data in table like delete,update,insert etc) Command.
  • It can be applied on both table level and row level.
  • DELETE does not reset identity of the table(Here identity means auto increment column in table).

Conclusion 

I hope this post may helpful to readers and freshers who are preparing for interviews.Please follow this blog for daily updates..


Wednesday, 22 June 2016

Differences between stored procedure and function in SQL

22:15:00 Posted by raviteja swayampu , No comments
Stored Proedure:
Stored procedure is a pre-compiled object that are compiled once and can be executed when ever it is called from the application.The compiled format saved in Sql server system objects.And it does not returns any value.
Function:
Functions in Sql server is compiled and executed every time they called.And function should return a value.

Differences between stored procedure and function

1.Function must return a value.Stored procedure need not return a value.
2.Function will allow only Select statements, it will not allow us to use DML statements.But procedures will allow DML commands like insert,update,delete etc.
3.We can not embed a procedure with in SELECT statement but we can use functions in SELECT statements.
4. Procedure can have both input and output parameters.But, function only supports input parameters only.
5.Procedures allows Try-catch block for Exception handling.Functions does not allow.
6.we can implement transactions in procedures but function does not allow transactions.
7.Can use both table variables as well as temporary table in it.(temporary table start with '#' symbols). Functions does not allow temporary variables only allows variables.
8.we can call a function using stored procedure but we can not call a procedure using function.
9.Procedures can’t be called from Select/Where/Having and so on statements. Execute/Exec statement can be used to call/execute Stored Procedure.But we can call a function using any DML statement.
10.JOIN 's can be used in functions but not in procedures.
Benifts of Procedures
1.These are pre compiled no need to compile every time.So,The execution is very faster.
2.we can enhance the security controls by giving the granting and revoking the permissions on procedures.
3.we can implement many functionalities using stored procedures to reduce the code(with out creating new procedures).
Benifits of functions
1.We can implement function once and by storing in database we can call it many times in program.It helpful for modular programmng.
Conclusion:
I hope this article is helpful for freshers or newbies who are learning SQL.For any help feel free to contact me..


How to Implement Auto Complete Textbox using Angular js in MVC5

07:07:00 Posted by raviteja swayampu , , 1 comment
Hi every one in this article i am going to explain about Auto complete text box using Angular JS.I might saw in some search engine and some websites while we are typing the first two letters of word it shows some suggested list to select.This Auto complete text boxes mostly used in real time projects to increase the user interactivity with site.Now in this post we gonna look at how it is implemented in Angular js.
For example see below google auto complete search box..

How to Implement Auto Complete Textbox using Angular js in MVC5
Here the suggested results will come based on the previous search results or most searched results.

Implementing Auto complete Textbox in Angular

To implement auto complete text box in Angular we need a angucomplete-alt directive.And  angucomplete dependency should be added to the angular application.In this application i am getting the data suggestion data from database table.
Steps to implement Auto complete text box..

Step 1: Create New Project.

Go to File --> New --> Project --> ASP.NET  Web Application under web section --> Entry Application Name --> Click OK --> Select Empty template --> Checked MVC -->click OK

Step 2: Add a Database to project.

Go to Solution Explorer --> Right Click on App_Data folder --> Add --> New item --> Select SQL Server Database Under Data --> Enter Database name --> Add.

Step 3: Create a table for store data

1.Open Database -->Right Click on Table folder --> Add New Table --> Add Columns --> Save --> Enter table name --> Ok.
2.In this tutorial I have created a table(Country) to store country list that will appear in the auto suggesstion list(This table contains CountryID,CountryName as columns).

Step 4: Add Entity Data Model.

1.Go to Solution Explorer -->Right Click on Project name form Solution Explorer --> Add --> New item --> Select ADO.net Entity Data Model under data --> Enter model name --> Add.
2.A popup window will come (Entity Data Model Wizard) --> Select Generate from database -->click Next
3.Chose your data connection --> select your database -->Select Entity framework version(5.0 or 6.0) next --> Select tables -->Enter Model Namespace name-->Click Finish.

Step 5: Add Angular reference files

1.Add below reference files in _Layout.cshtml page.(you can download this files from here angucomplete-alt.css and angucomplete-alt.js.
2.Add this files in <head> tag.
<!--Angualr refrence file for auto complete text box starts--><script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<script src="~/Scripts/angucomplete-alt.js"></script>
<link href="~/Content/angucomplete-alt.css" rel="stylesheet" />
<script src="~/Scripts/app.js"></script>
<!--Angualr refrence file for auto complete text box starts-->

Step 6: Add Controller 

1.Add Controller by right click on Controllers folder --> Add --> Controller -->name it as Home Controller
2.Replace the code with below code..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AngularAutoCompleteTextbox.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult getAllCountries()
        {
            using (DatabaseEntities db = new DatabaseEntities()) {
                var countrylist = db.Countries.OrderBy(a => a.CountryName).ToList();
                return new JsonResult { Data=countrylist,JsonRequestBehavior=JsonRequestBehavior.AllowGet};
            }
        }
    }
}
3.Index action is used to render the view.
4.getAllCountries method gets the data from database and sends it to the Angular Controller in Json format.

Step 7: Add Angular scripts to project

1.Right click Scripts folder --> Add Javascript file (i named it app.js).
2.Replace it with the below code..
var app = angular.module('myapp', ['angucomplete-alt']); //add angucomplete-alt dependency in app
app.controller('AutoCompleteController', ['$scope', '$http', function ($scope, $http) {
    $scope.Countries = [];
    $scope.SelectedCountry = null;
    //event fires when click on textbox
    $scope.SelectedCountry = function (selected) {
        if (selected) {
            $scope.SelectedCountry = selected.originalObject;
        }
    }
    //Gets data from the Database
    $http({
        method: 'GET',
        url: '/Home/getAllCountries'
    }).then(function (data) {
        $scope.Countries = data.data;
    }, function () {
        alert('Error');
    })
}]);
3.Here $scope.SelectedCountry stores the selected value in text box.$http service gets data from server.

Step 8: Add view to display UI

1.Right click Index action --> Add View --> name it --> Click Add.
2.Replace the code with below code in Index.cshtml page.
@{
    ViewBag.Title = "Mitechdev.com";
}
<div class="container">
    <h2>Autocomplete textbox in AngularJS</h2>
    <div ng-app="myapp">
        <div ng-controller="AutoCompleteController">
            <div angucomplete-alt id="txtAutocomplete" placeholder="Type country name" pause="100"
                 selected-object="SelectedCountry" local-data="Countries" search-fields="CountryName"
                 title-field="CountryName" minlength="1" input-class="form-control" match-class="highlight">
            </div>
            <!--display selected country-->
            <div ng-show="SelectedCountry">
                Selected Country : {{SelectedCountry.CountryName}}
            </div>
        </div>
    </div>
</div>
3.In div element we must add angucomplete-alt.we bind the data using local-data attribute.
4.After running the application we will get...

auto implement textbox using angular in mvc5

Download the source code from here-- Source code.

Conclusion

I hope this article may help you understand how to implement auto complete textbox using Angular JS in MVC 5.If you recommend any suggestion please contact me..


Tuesday, 21 June 2016

How to find second highest salary from table in SQL

21:34:00 Posted by raviteja swayampu , No comments
My friends asked me in many of the interviews this question was asked.This is first question that is asked in interview from SQL.I am also faced the same question in the interviews two times.So,to help the freshers i decided to write this answer in this blog.For better understanding of this question i am explaining it by creating a simple table.
I created below Employee table in my local database present in my visual studio 2013.And i added below columns in Employee table.

The created table is empty.Now insert some Employee data into table.


Here i am using Local data base so no need to write any queries to insert data.You can do it using query also.To find the second highest salary in the Employee table we need to use Subqueries.(for full details about subqueries click on the link).
Query:
---finding second highest salary
SELECT MAX(Salary) as sal FROM Employee
 WHERE Salary <(SELECT MAX(Salary) as sal FROM Employee)
Here the the sub query returns the highest salary equals to 40000 in above table.In main query we returns the salary less than first one.It is simple and good question for the beginners(freshers).
after running the code we will get the output like below..

Conclusion:
I hope this article is useful for all readers , If you have any suggestion regarding this article then please contact me.


Monday, 20 June 2016

How to create Google Pie charts with MVC 5

21:39:00 Posted by raviteja swayampu , , 2 comments
Hello every one welcome again.In this tutorial i am going to explain about how to implement Google Charts in ASP.NET MVC 5 using Google Charts API.Google charts provides simple way to visualize data in your website. From simple line charts to complex hierarchical tree maps, the chart gallery provides a large number of ready-to-use chart types. The most common way to use Google Charts is with simple JavaScript that you embed in your web page.
In this tutorial i am going to explain about how to implement Pie Chart using Google Charts with data from database.Here i am using Jquery java script library to implement Charts.
The Implemented Pie chart in this tutorial look like below.

Google Pie charts with MVC 5
These google charts libraries are very helpful and easy implemented give very good user interfaces for our web sites.In our future posts i am going to teach each chart(Line charts,bar charts etc) and how to integrate them in our ASP.NET MVC websites.Lets start the tutorial...

Implementing Google Pie chart in MVC 5

Step 1: Create a Table contains Chart Data

1.Create a new table with the following columns that gives the data to the google chart.
2.Here i named the table as GoogleChartData.


3.Now add ADO.NET Entity Data model to the project.
4.Right click --> Models folder --> Add --> New Item --> In Add New Item window select ADO.NET Entity Data Model under Data section -->name it --> click Add.
5.Select 'Generate from Database' in Entity Data Model Wizard --> Click Next.--> Select Database connection and name the connection string --> Select the version of Entity framework --> Select the Data base objects and settings(Tables and procedures.Here only select the GoogleChartData table only) --> click finish.
6.Data source for the application has created successfully.

Step 2: Add Controller 

1.Right click on Controllers folder --> Add --> Controller --> name it(here HomeController).
2. Replace the code in the HomeController with the following code.

using GoogleMapswithAngular.Models;
using System.Web.Script.Services;
using System.Web.Services;
namespace GoogleMapswithAngular.Controllers
{
    public class HomeController : Controller
    {
        DatabaseEntities db = new DatabaseEntities();
        public ActionResult Index()
        {
            return View();
        }
        //Action gets the chart data from the server.
        public ActionResult getMapData()
        {
            List mapdata = new List();         
            mapdata = db.GoogleChartDatas.ToList();
           return Json(mapdata,JsonRequestBehavior.AllowGet);
        }

    }
}
3.Here Index action is to display the Chart User interface.
4.getMapData method used to get the chart data from the server.

Step 3: Add View to display the Chart

1.Right click on the Index Action --> Add view -->Name it as Index.cshtml.
2.Add the following references to the View.
<!--Java script reference files for google charts-->
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
3.The below DIV element displays the chart..
<!--UI element that displays Google Pie chart-->
<div class="container">
    <div class="panel panel-info">
        <div class="panel-heading">
            Google Pie Chart in MVC
        </div>
        <div class="panel-body">
            <div id="chart_display"></div><!--pie chart display DIV-->
        </div>  
        <div class="panel-footer">
            WWW.Mitechdev.com
        </div> 
    </div>
</div>

Step 4 : Add Javascript file to get data from server

1.Add a java script file to the project or add script in index view itself.
2.Create a global variable to hold the chart data.Use below script to initialize the global variables.

//initilize globar variable for hold chart data
    google.load("visualization", "1", { packages: ["corechart"] });

3.Add below code in Index.cshtml page using script tags.
 var chartData;
    // get the chart data from the server.
    $(document).ready(function () {
        $.ajax({
            url: "/Home/getMapData",
            data: "{}",
            dataType: "json",
            type: "POST",
            contentType: "application/json; chartset=utf-8",
            success: function (data) {
                debugger;
                chartData = data;
                // Callback that creates and populates a data table,    
                // instantiates the pie chart, passes in the data and draws it. 
                //Creates a data table for storing the map data .chart api access this data for displaying
                var data = new google.visualization.DataTable();
                //Adding columns to data table to insert the chart data
                data.addColumn('string', 'Product Category');
                data.addColumn('number', 'Revenue Amount');
                //bind the data to the data table using for loop
                for (var i = 0; i < chartData.length; i++) {
                    data.addRow([chartData[i].ProductCategory, chartData[i].RevenueAmount]);
                }
                // Instantiate and draw our chart, passing in some options    
                var chart = new google.visualization.PieChart(document.getElementById('chart_display'));
                chart.draw(data,
                      {
                          title: "Google Pie Chart in MVC", //title of the pie chart
                          position: "top",
                          fontsize: "14px",
                          chartArea: { width: '50%' },
                      });
            },
            // ajax error display 
            error: function () {
                alert("Error loading data! Please try again.");
            }
        });
    });
4.Google API does not understand the data coming from the controller.So, we need to create a visualization DataTable for storing the data.I stored that Table data "data" object in above code.
5.We can pass the customization's to the chart using options like title,position etc check above code..
6.PieChart method draws the required pie chart in div element we specified using ID.
Finally run the application and see the output we get a pie chart
Google Pie charts with MVC 5
Download the source code from here. Source code

Conclusion:

I hope this tutorial may help for every reader and developers who are willing to add Charts to their site.Please subscribe and follow www.Mitechdev.com throght facebook and twitter for daily updates..


Sub Queries in SQL server

04:41:00 Posted by raviteja swayampu , No comments

What is Sub Query:

A SQL query written within another query enclosed with parenthesis is called a Sub-Query or inner query or nested query.Sub query is mainly used to return the data that is going to used by main query.SQL engine executes the sub query first then executes the main query.
A sub query is created on an existing select, insert, update or delete statement along with the operators(like <,>,=,<=,>=,IN,BETWEEN etc). The parent query that contains the inner statement is also called an outer query.

Rules for writing Subqueries:

1.A subquery must be enclosed within parentheses.
2.Subqueries that return more than one row can only be used with multiple value operators(Example:IN operator).
3.ORDER BY can not be used by subquery.
Note:But in that case We can use GROUP BY to perform the same operation.
4.A sub query can not be used in a set function.
5.BETWEEN can not be used with main query but we can use it with in sub query.
6.We can implement upto 32 sub queries in Main query.

Types of sub queries:

There are 3 types of sub queries..
1.single row
2.multiple row
3.multiple column
1.single row:
If a sub query returns a single row then it is called as single row sub query.
for example scalar queries returns single column with value those are comes under this category.
Ex:
select MAX (salary) as Salary from employee
where salary 
 < 
(select MAX (salary) as Salary from employee) 
2.multiple row:
This is a sub query that returns multiple rows.
These are commonly used to generate result sets that will be passed to a DML(like Update,delete) or SELECT statement for further processing.
Both single-row and multiple-row sub queries will be evaluated once, before the parent query is run.
Both single and multiple-row sub queries can be used in the WHERE and HAVING clauses of the parent query.
Ex:
Multiple columns:   
Sub-query returns multiple columns. Now let us see how to use Sub queries with various SQL Statements.
These sub queries are commonly used with Select statements in DRL(Data retrival language).

Now lets see how we use sub queries in oprations like Update,delete,select and insert.
In Delete operation:
Ex: 
DELETE FROM emp
 WHERE (SELECT age FROM emp WHERE age>60)
Here the sub query returns the age of employee greater than 60 and main query deletes the employee record based on the return value of sub query.
In SELECT operation:
Ex:
Ex: SELECT * FROM emp
 WHERE id IN (SELECT id FROM emp WHERE SALARY > 20000) ;
In insert operation:
Ex:
INSERT INTO empcopytable
SELECT * FROM emp
 WHERE code IN (SELECT code FROM emp) 
In above example i am copying emp table into 'empcopytable' with similar structure using below syntax.
In Update operation:
Ex:
UPDATE emp 
 SET salary=salary*20
 WHERE experience IN(SELECT experience FROM emp WHERE experience>=2)
Here we are incrementing the employee salary based on experience(experience greater than 2 years is return by sub query).

Conclusion:

I hope this small tutorial will be understandble for every one reader.Please recommend any modifications to increase the quality of the tutorial...Please subscribe and follow this site for daily updates...


Sunday, 19 June 2016

Query processing in Sql server

00:56:00 Posted by raviteja swayampu No comments
Hello every one welcome again.Up to know i posted some articles that are mainly helpful for developers in a real time developments.From now on wards i focus on the basic concepts of Microsoft web technologies like SQL server development,C sharp,WCF Rest services web API and also regular real time concepts with code snippets.From this tutorial on wards i start SQL server tutorial posts.The below is my first tutorial from SQL server tutorials.

Execution of Query in SQL server

In this tutorial i am going to explain about how SQL SELECT statement works in SQL server.Server performs a couple of internal steps before executing a query. It comes under the DRL(data retrieval language) module in SQL(Structural Query Language). The processing of query is done in two stages
1.Compilation
2.Execution
When SQL Server receives a query for execution, its execution plan
Note: An execution plan is the real work plan generated by the query optimizer to determine how to process or execute a submitted query. The plan is the primary method for any developer or DBA to troubleshoot any performance issue by a query; it can even identify which part of query is causing the issue.
should already be present in memory (the procedure cache); if not, SQL Server will have to compile the query before executing it.
The compilation process is divided into four parts:
1.    Parsing
2.    Normalization
3.    Compilation
4.    Optimization
Parsing:
During this stage, SQL Server checks the query for Syntax errors and transforms it into a compiler-ready structure that it will use later to optimize the query. It does not check for object names or column names.
Normalization:
At this stage, SQL Server checks all references to objects in the query. This is where we typically get the “Object not found” message when an object referenced in the query is not found in the database. SQL Server also checks to see if a query makes sense. For example, we cannot execute a table or select from a stored procedure.
Note: We can optimize the Select,insert,update and delete operations but we can not optimize the clauses(like Group By,From and etc) in sql server.
Compilation:
This is where we start building the execution plan for the query we passed to SQL Server. First, we create a sequence tree. The sequence tree is normalized, again, which includes adding implicit conversions if necessary. Also during this phase, if the query is referencing views, a view definition is placed in the query. If a statement is a DML statement, a special object is created called the query graph. The query graph is the object on which the optimizer works to generate an optimized plan for the query. This is the compiled plan that is stored in the procedure cache for reuse.
Optimization:
SQL Server Optimizer is a cost-based optimizer, which means that it will come up with the cheapest execution plan available for each SQL statement. For each SQL statement to run we need to use resources like CPU, memory, hard disk, etc. The cheapest plan is the one that will use the least amount of resources to get the desired output. For optimizing DML(Data Manipulation Language) statements,
SQL Server will test different indexes and join orders to get the best plan for executing the query. Your index definition helps optimizer by reducing/minimizing resource usage. If the index has a high selectivity then it is most suitable for optimization. Because a complex query will take into account all indexes and joins, there can be many paths to take to execute the query. In such cases, determining the best path for optimization can take a long time. The longer this process takes, the higher the cost that is involved.
So first, a trivial plan is generated. This plan assumes that cost-based optimization is costly; if there is only one path for execution possible, there is no point optimizing the query. For example, when placing a simple insert statement into a table, there is no way that your indexes or join orders can increase optimization, so the trivial plan is used.

Logical query processing order of SQL Query

1.FROM
2.ON
3.OUTER
4.WHERE
5.GROUP BY
6.CUBE/ROLLUP
7.HAVING
8.SELECT
9.DISTINCT
10.ORDER BY
11.TOP.

Conclusion

I hope this tutorial is understandable for every reader.Please give me suggestions if any....


Wednesday, 15 June 2016

Understanding routing in Angular JS

02:29:00 Posted by raviteja swayampu , No comments
Hi every one welcome again.Thank u for suggestions for previous posts.In this tutorial i am going to teash you about how routing is done in angular(Specially in single page applications it is very important).
Description:
In general meaning of routing is "navigating from one page to another page".But in single page applications also we need to route from one page to another page without loading of entire page.
1.In angular js we use 'ngRoute' Module.
2.Routing is also very important in single page applications.
3.ngRoute module routes your angular application to different pages in entire application without reloading page.
4.All this is achieved by internal functions calling how great it is.Due to this the page loading speed and performance of application and the burdon on server also reduced.
5.Implementing routing in Angualr applications is very easy.
Lets see how to implement routing in angular single page applications.

How to implement Routing in Angular JS

1.Off course in this tutorial also i am explaining with a sample application.
2.Before going to applications let look at some basics of routing.

Step 1: Add angular routing reference files to your project.

1.Add angular routing file in _Layout.cshtml page along with angular.js file.
2.See the required files in _Layout page.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
    <!--include angular-route.js file -->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-route.js"></script>

Step 2: add Controllers and corresponding views

1.Here i created a RoutingController and created two Actions methods to display the corresponding view (page1.cshtml,page2.cshtml).
2.After that we must add ng-Route dependency to angular applications when application initilizes.
3.check below syntax:
var app = angular.module("myApp", ["ngRoute"]);

now our applicaton is have access to the routing mdule.to achieve routing angular provides built in routing service.
4.Your angular application needs a container to put the content of the pages that are provided by routing.
5.we can display the container using 'ng-view' directive.
6.Syntax of the ng-view container is like below
syntax:
<div ng-view></div>
 <ng-view></ng-view>
 <div class="ng-view"></div>
7.Create another controller and name it as HomeController and add Index action and corresponding view.
8.Replace the Index.cshtml view code with the following code.
@{
    ViewBag.Title = "Index";
}
<h2>Home page</h2>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
    <!--include angular-route.js file -->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-route.js"></script>
    <script type="text/javascript">
        //add 'ngRoute' as dependency to the application
        var app = angular.module('app', ['ngRoute']);
        //Now your application has access to route module..
        //which provides $routeProvider service helps for routing
        app.config(function ($routeProvider) {
            $routeProvider
   .when('/page1', {
       templateUrl: "Routing/Page1",   //we can add controllers to views also
       controller: "Page1Controller"
   })
   .when('/page2', {
       templateUrl: "Routing/Page2",
       controller: "Page2Controller"
   });
        });
        app.controller('Page1Controller', function ($scope) {
            $scope.msg1 = "This is page 1 buddy!";
        });
        app.controller('Page2Controller', function ($scope) {
            $scope.msg2 = "You are in page 2 Dude";
        });
    </script>
    <div class="container" ng-app="app">
        <div class="jumbotron">
        <h1>This is Default page</h1>
            <p>Click on below buttons to route to another pages</p>
        </div>
        <a href="/#/" class="btn btn-default">Home page</a>
        <a href="/#/page1" class="btn btn-default">page1</a>
        <a href="/#/page2" class="btn btn-default">page2</a>
        <div ng-view></div>
    </div>
9.With help of When method we defined the route of the application.
10.And i also added the controller for two views and passed the $scope.msg1,$scope.msg2 and displayed in page(you can check by downloading the application below).
11.We can also add controllers to views as shown i the application.
12.Code of respective views are as follows:
page1.cshtml:
@{
    ViewBag.Title = "Page1";
    Layout = null;
}
<div class="container" ng-controller="Page1Controller">
    <div class="jumbotron">
        <h1>{{msg1}}</h1>
        <p>
            This is opened because you clicked on Page1 link
        </p>
    </div>
    <p>This is how routing works Man</p>
</div>
page2.cshtml:
@{
    ViewBag.Title = "Page2";
    Layout = null;
}
<div class="container" ng-controller="Page2Controller">
    <div class="jumbotron">
        <h1>{{msg2}}</h1>
        <p>
            This is opened because you clicked on Page2 link
        </p>
    </div>
    <p>This is how routing works Man</p>
</div>

After running of application you will better understand the routing.The pages are loaded to the ng-view container without refresh of the current page.and the scope values are assigned after loading.

Understanding routing in Angular JS
Click on the page1 and page 2 links the output will be like this.

Understanding routing in Angular JS

Download the osurce code Source code

Conclusion:

I hope you like this post.i always welcome for any suggestions from you.Please subscribe and follow this site for valuable daily updates.


Monday, 13 June 2016

Implementing Kendo Grid with CRUD operations in ASP.NET MVC application

21:52:00 Posted by raviteja swayampu , , No comments
Hi every one in this tutorial we are going to learn about the kendo Grid.Thank you previous post responses How to implement modal popup using Angular UI.Previous i explained about some open source grids like Jqgrid,Angular UI grid.If you want to implement these grids follow below links.

Kendo Grid:

The Kendo UI grid is a powerful widget which allows you to visualize and edit data via its table representation. ... To feed the grid with data, you can supply either local or remote data via the Kendo UI DataSource component, used as a mediator.But it is a commercial product.We need to purchase the license from vendor provider for development.
Features of Kendo grid:
1.Implementations is very very easy.
2.easy understanding interface
3.Sorting.
4.Grouping.
5.filtering
6.Virtual display.
7.column resizing.
8.Export to pdf,excel
9.supporting different platforms like Angular and Jquery.
10.supports in different browsers.
11.supports multiple sub grids.
12.Frozen columns.
13.paging,sorting,bath,popup and inline customer editor.
14.insert, delete,update
15.Supports Local,Remote data binding services.
There are many more features provided by kendo UI.This is a very feature rich due to licensed cost.Kendo grid is very easy,customizable with good user experience.And support is also provided from vendor if any bugs are raised.But in open source grids like jqgrid,Angular UI grid we wont get any support.
Kendo grid that we are going to implement in this tutorial is like this.

kendo grid in asp.net mvc application

Implementing Kendo UI grid in MVC

Step 1: Create a web application and add controller

1.Create a web application using ASP.NET MVC web application.
2.Right click on Controllers folder --> Add controller --> name it .
3.Add Index Action Method.
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }  
    }

4.Add Index View -->Right click on Action method --> Add View.

Step 2: Add Kendo grid references in Layout

1.Add below kendo references in _Layout.cshtml page.
2.Here i took the CDN 's as references.
<!--Kendo library references-->
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.dataviz.min.css" />
    <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.dataviz.default.min.css" />
    <script src="http://cdn.kendostatic.com/2014.3.1316/js/jquery.min.js"></script>
    <script src="http://cdn.kendostatic.com/2014.3.1316/js/kendo.all.min.js"></script>

Step 3:Create a table in Database

1.Add a table in database here i am creating table in Local database(Sql Express).
2.I named the table as Student table.
3.You can see the table here....by expanding Server explorer.


Implementing Kendo Grid with CRUD operations in ASP.NET MVC application

Step 4: Add ADO.NET Entity Data Model

1.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 2.Select Database --> give name for web.config. 3.Choose your Database objects(tables) and click finish. 4.Now Model is added to my project.

Step 5: Create Web API controller

1.Right click on Controllers folder --> Add --> Controller --> Select "Wep API2 controller actions with Entity framework" --> click Add --> name the controller(i named it as StudentAPIController) --> Select Model and context class in Add Controller popup wizard --> finally click Add button.
2.Following code is generated by Visual studio.
StudentAPIController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using KendoGrid.Models;
namespace KendoGrid.Controllers
{
    public class StudentAPIController : ApiController
    {
        private DatabaseEntities1 db = new DatabaseEntities1();
        // GET api/StudentAPI
        public IQueryable GetStudents()
        {
            return db.Students;
        }
        // GET api/StudentAPI/5
        [ResponseType(typeof(Student))]
        public IHttpActionResult GetStudent(int id)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return NotFound();
            }
            return Ok(student);
        }
        // PUT api/StudentAPI/5
        public IHttpActionResult PutStudent( Student student)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            //if (id != student.ID)
            //{
            //    return BadRequest();
            //}
            db.Entry(student).State = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(student.ID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return StatusCode(HttpStatusCode.NoContent);
        }
        // POST api/StudentAPI
        [ResponseType(typeof(Student))]
        public IHttpActionResult PostStudent(Student student)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Students.Add(student);
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (StudentExists(student.ID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }
            return CreatedAtRoute("DefaultApi", new { id = student.ID }, student);
        }
        // DELETE api/StudentAPI/5
        [ResponseType(typeof(Student))]
        public IHttpActionResult DeleteStudent(int id)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return NotFound();
            }

            db.Students.Remove(student);
            db.SaveChanges();

            return Ok(student);
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        private bool StudentExists(int id)
        {
            return db.Students.Count(e => e.ID == id) > 0;
        }
    }
}
Note: Here i changed the parameter of the PutStudent because kendo UI script does not send two parameters to api.So,I changed the parameters and done some modifications to method.
You can check it by comparing visual studio generated code with above code.

Step 5: Add View and script to display grid

1.Replace the Index view code with the following code.
@{
    ViewBag.Title = "Home Page";
}  
    <script>
        $(document).ready(function () {
            //data source for kendo grid
            dataSource = new kendo.data.DataSource({    
                transport: {
                    read:
                    {
                        url: "http://localhost:62235/api/StudentAPI/",  
                        dataType: "json",   //reading data
                    },
                    destroy:
                    {
                        url: "http://localhost:62235/api/StudentAPI/",
                        type: "DELETE"      //delete 
                    },
                    create:
                    {
                        url: "http://localhost:62235/api/StudentAPI/",
                        type: "POST"        //create
                    },
                    update:
                    {
                        url: "http://localhost:62235/api/StudentAPI/",
                        type: "PUT",    //update
                       
                        parameterMap: function (options, operation) {
                            //debugger;
                            if (operation !== "read" && options.models) {
                                return {
                                    //here data is sent to update popup by stringify
                                    models: kendo.stringify(options.models)
                                };
                            }
                        }
                    },
                },
                schema:
                {
                    model:
                    {
                        id: "ID",
                        fields: {   //column models and specifying behaviour
                            ID: { editable: true, nullable: true, type: "number" },
                            Name: { editable: true, nullable: true, type: "string" },
                            Department: { editable: true, nullable: false, type: "string" },
                            Phone: { editable: true, nullable: false, type: "number" },
                        }
                    }
                }
            });
            $("#grid1").kendoGrid({               
                dataSource: dataSource, //binging the above data source to grid
                //editable: "inline",   //inline editing
                selectable: true,       //selectable when u click on any row its color may change
                groupable: true,        
                sortable:true,          //sortable
                toolbar: ["create"],    //displays a button in grid toolbar 
                columns: [              //columns in grid
                {
                    field: "ID",
                    title: "StudentID",
                },
                {
                    field: "Name",
                    title: "StudentName"
                },               
                {
                    field: "Department",
                    title:"Department"
                },
                {
                    field: "Phone",
                    title:"Phone Number"
                },
                {
                    command: ["edit",   //grid action buttons
                    {
                        name: "destroy",
                        text: "remove",
                    }
                    ],
                }              
                ],
                editable: "popup",      //edit option with popup
                filterable: true,       //we can filter tae data using filter options   
                columnMenu: true,
                reorderable: true,
                resizable: true,
                height: "500px",
                pageable: {
                    refresh: true,
                    pageSizes: true,
                    buttonCount: 5
                },
            }).data("kendoGrid");
        });
    </script>
<!--Kendo grid display element-->
    <div class="main-content">
        <div id="grid1"></div>
    </div>
2.Run the application and see in browser it look like above first picture..
Add New record popup


Implementing Kendo Grid with CRUD operations in ASP.NET MVC application
Update Record popup


Implementing Kendo Grid with CRUD operations in ASP.NET MVC application
Sorting, Filtering in Grid


Implementing Kendo Grid with CRUD operations in ASP.NET MVC application

Grouping in kendo grid

Implementing Kendo Grid with CRUD operations in ASP.NET MVC application

Download source code of application from here Source Code

Conclusion:

I hope this tutorial is understandable for every one and useful to developers.Please subscribe and follow mitechdev.com social networks for daily updates.I will meet you in next tutorial.If u have any doubts please contact me.


Sunday, 12 June 2016

How to implement Modal popup using Angular UI in ASP.NET MVC

22:32:00 Posted by raviteja swayampu , , 5 comments
Hi every body in this article i am going to teach you How to implement modal popup using Angular js framework in ASP.NET MVC application.I hope you saw already know about Jquery UI Modal  popup.The same thing we are implementing here using Angular UI with Bootstrap as front end.

Angular UI

Angular User Interface is an alternative to the Jquery User interface which uses Angular framework as dependency with Bootstrap.It is a open source project hosted on GitHub.
Angular UI is project that includes UI modules developed to used in AngularJS Applications. It includes UI-bootstrap that is Bootstrap UI elements for AngularJS. It also includes many other Angular variants of famous jquery UI modules
 In future posts i going to explain all the components of angular UI.But, Modal popup is the main part of Web UI development that's why i am explaining separately.The basic UI popup is like below.

modal-popup-window-using-angular-ui
I took this form as an example but it does not shows any form behavior like validation and saving data.

Steps to implement Angular UI Modal popup

Step 1: Create a web application and add controller

1.Create a web application using ASP.NET MVC web application.
2.Right click on Controllers folder --> Add controller --> name it .
3.Add Index Action Method.
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }  
    }

4.Add Index View -->Right click on Action method --> Add View.

Step 2: Add Angular Reference files to project

1.we can add Angular UI reference(library) files to solution using Nuget package(better way).or by downloading from official site here.

How to implement Modal popup using Angular UI in ASP.NET MVC

2.Add below reference files in _Layout.cshtml(present in Views --> Shared folder) page or Index.cshtml page.
 <!--Add angular references here-->
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/Scripts/angular-animate.min.js"></script>
    <script src="~/Scripts/angular-ui/ui-bootstrap-tpls.min.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

Step 3: Add Angular Script file for functionality

1.Right click on Scripts folder --> Add --> Java script file.
2.here i named it as modalapp.js.
3.Replace the code with below java script code.
var app = angular.module('modalapp', ['ngAnimate','ui.bootstrap']);
app.controller('modalcontroller', function ($scope,$uibModal) {
    $scope.msg = "Hi Angular buddy";
    $scope.desc = "this is from desc";
    $scope.animationsEnabled = true;
    //based on size parameter the size of modal chages.
    $scope.openModal = function (size) {
        var ModalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'myModal.html',
            controller: 'InstanceController',
            //appendTo:     //appends the modal to a element
            backdrop: false,  //disables modal closing by click on the background
            //size:size,
            //template: 'myModal.html',
            //keyboard:true,     //dialog box is closed by hitting ESC key
            //openedClass:'nameofClass',  //class styles are applyed after dialog opens.
            resolve: {
                items: function () {
                    //we can send data from here to controller using resolve...
                    return $scope.desc;
                }
            }
            //windowClass:'AddtionalClass',   //class that is added to styles the window template
            //windowTemplateUrl:'Modaltemplate.html',    template overrides the modal template
        });
    };
});
app.controller('InstanceController', function ($scope, $uibModalInstance,items) {
    $scope.ok = function () {
        //it close the modal and sends the result to controller
        $scope.data = "welcome";
        $uibModalInstance.close($scope.data);
    };
    $scope.cancel = function () {
        //it dismiss the modal 
        $uibModalInstance.dismiss('cancel');
    };
});

4. you will understand functionality of above code by reading comments above.

Step 4 : add view to display the popup

1.Upto now background functionality is done.Now its time for UI display.
2.Now replace the code in Index.cshtml using below code.
@{
    ViewBag.Title = "Home Page";
}
<div ng-app="modalapp" ng-controller="modalcontroller">
    <h3>{{msg}}</h3>
    <script type="text/ng-template" id="myModal.html">
        <div class="modal-header">
            <h2 class="modal-title">Sample form in Angular Modal</h2>
        </div>
        <div class="modal-body">
            <div>
                <!--We can implement forms and anything we want here-->
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="text-info">Email: </label>
                        <input type="email" ng-model="email" class="form-control" placeholder="Email" />
                    </div>
                    <div class="form-group">
                        <label class="text-info">Name:</label>
                        <input type="text" ng-model="name" class="form-control" placeholder="Name" />
                    </div>
                    <div class="form-group">
                        <label class="text-info">Password</label>
                        <input type="password" ng-model="password" class="form-control" placeholder="Password" />
                    </div>                  
                    <input type="button" class="btn btn-success" ng-click="ok()" value="Submit" />
                </form>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-default" type="button" ng-click="cancel()">cancel</button> 
        </div>
    </script>
    <button class="btn btn-default" type="button" ng-click="openModal()">Click to Open Modal</button>   
</div>
<script src="~/Scripts/UIModalScripts/modalapp.js"></script>

Finally after running of code you will get a button.Modal popup will be displayed after clicking on that button.
3.The open() method accepts the size parameter we can pass (large:'lg',small:'sm') for small and large windows.
Download the source code from here Source code.
Conclusion
I hope this tutorial is helpful for every reader.I will come with another tutorial.Please subscribe to this blog to get daily updates.Thanks u.