Asp.Net MVC online training from hyderabad Microsoft .Net technologies includes ASP.NET, ASP.NET MVC, C#.NET, Web API, WCF, Web Services Microsoft Sql Server Web technologies includes HTML, Javascript, JQuery, AngularJS


GETTING STARTED

if you are getting started with your new IT carrier, It’s the right time to become robust and confident in your journey.

We will provide on line training in

Microsoft .Net technologies includes ASP.NET, ASP.NET MVC, C#.NET, Web API, WCF, Web Services

Microsoft Sql Server

Web technologies includes HTML, Javascript, JQuery, AngularJS

 

IMPROVE YOUR SKILLS

Get ready for challenging IT carrier with real time examples and Corporate trainers in your course.

ONLINE COURSE

Start a creative and exciting career with
our online programs

WHY ONLY WE

  1. We will teach you self learning techniques, so that you can complete your challenges in-time even in newer platforms

blog-image-02

2. We will teach you, how to make impossible solutions as possible

blog-image-01

3. We will make you think innovative, creative

blog-image-03

LEARN FROM THE BEST.
ANYTIME. ANYWHERE.

Advance and build on existing skills with our
Professional Development programs

Last but not least : we will do real time project with you.

For details: dotnetcornerofficial@gmail.com

 

 

 

 

Deserializing JSON object to runtime type or dynamic types using JsonConvert.DeserializeObject and reflection


JsonConvert.DeserializeObject method has 8 overloaded methods one of them will full fill our requirement.

If we want to deserialize Json object to a runtime type or dynamic type we can use 3rd overload method of JsonConvert.DeserializeObject

these are the 8 overloaded methods of JsonConvert.DeserializeObject

 

Screenshot_10

Screenshot_13

Screenshot_14

Screenshot_15

Screenshot_16

Screenshot_17

Screenshot_18

Screenshot_19

If we want to deserialize Json object to a runtime type or dynamic type we can use 3rd overload method of JsonConvert.DeserializeObject

string jsonData = "{\"key\":\"value\"}";
string typeName = "SampleNamespace.SampleClassName";
Type requestType = Type.GetType(typeName);
var result = JsonConvert.DeserializeObject(jsonData, requestType);

In the above code typeName is class name which is matching json properties.

then create the type using Type.GetType() method.

then pass this type to our JsonConvert.DeserializeObject method.

Happy Coding SmileComputer

How can we force clients to refresh JavaScript files?


Q: How can we force web clients to refresh or load latest version javascript files from the web server.

This is the problem most of the web developers facing after deploying their newer versions of javascript files.

We normally ask the customer to hit Ctrl + F5 to ensure that all the latest javascript files loaded from server not from the cache.

But we can solve this in different ways as follows

Solution 1: If you are maintaining javascript versioning

If you are using javascript versions, it’s easy to solve the issue. i.e we just need to add the version to javascript file path as follows

<script src="~/scripts/demojs.js?100"></script>
<script src="~/scripts/demojs.js?version=100"></script>

so If the version of the file changed then the url also change. so if the url is different than the file which is already in cache, the browser (client) will request to get latest file from the server.

So these file will render to clients as follows

Loading from cache

image

Loading from server

image

Solution 2: If you are not using versioning use Asp.Net MVC datetime object ticks

In this case we just use ticks from C# datetime object as follows

<script src="~/scripts/demojs.js?@DateTime.Now.Ticks"></script>
<script src="~/scripts/demojs.js?currentTime=@DateTime.Now.Ticks"></script>

image

Solution 3: Restart application and Recycle Application pool in IIS

Please do following steps after completion of your deployment in IIS

  1. Restart your website

image

2. Then find the applicationpool of your website and recycle it.

image

In case of Microsoft Azure websites

Screenshot_10

Thanks

Happy coding ComputerSmile

Introduction to AngularJS filters to format and transform and sort


AngularJS is providing set of filters to Format and Transform and Sort the data.

If we want to filter the data inside javascript objects or properties we need to write hundreds of lines of code. In order to archive this we need to spend number of resources and time, But in case of AngularJS it’s completely reverse.

AngularJS is providing in-built filters to format and transform and sort the data.

AngularJS format and transform filters

AngularJS format filters help us to format and transform our data using the following filters.

  1. currency:

    • We can use this currency filter to format currency into specific format

    • for example a decimal property is having just number (300), and now if you want to display that number in currency format like $300.

  2. date:

    • We will use this filter to format date into specific format like “DD/MM/YYYY” or “MM/DD/YYYY” …

  3. filter:

    • We will use this filter to get specific or subset of data from a json object or array

  4. json:

    • This filter allows you to convert a javascript object to JSON string.

    • most of the times we will use this in debugging.

  5. limitTo:

    • we will use this filter to limit a javascript array or string into a specific number of elements.

  6. lowercase:

    • we will use this filter to transform our string to lower case

  7. uppercase:

    • we will use this filter to transform our string to upper case

  8. number:

    • we will use this filter to format a number to string and limit number of decimal

AngularJS sorting filters

we will use sortBy filter to sort the data.

$watch and $watchCollection is not firing/working on data change in angularJS


if $watch and $watchCollection is not firing on data change we need to use 3rd parameter i.e objectEquality parameter (type of boolean)

$watch(watchExpression, listener, [objectEquality])

above statement is the $watch signature with three parameters

in these three parameters third one (objectEquality) is optional and of type boolean

Example 1:

$scope.$watch(‘userProfile.userName’,
function (newValue, oldValue) {
$scope.userName = newValue;
}, true);

Example 2:

$scope.$watch(function () {
return authenticationService.userProfile;
},
function (newValue, oldValue) {
$scope.userProfile = newValue;
}, true);

Happy CodingComputerSmile

invalid uri: the uri string is too long. XDocument load


The reason for the error

invalid uri: the uri string is too long. XDocument load

is the issue with parameter we are passing. It is expecting file path or textreader or xmlreader depends on the method signature we are using.

The parameter we are following should not be the XML data in string.

XDocument.Load method is having 8 overloaded functions as shown below.

//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a System.IO.TextReader.
//
// Parameters:
//   textReader:
//     A System.IO.TextReader that contains the content for the System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified System.IO.TextReader.
public static XDocument Load(TextReader textReader);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from an System.Xml.XmlReader.
//
// Parameters:
//   reader:
//     A System.Xml.XmlReader that contains the content for the System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified System.Xml.XmlReader.
public static XDocument Load(XmlReader reader);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument instance by using the specified stream.
//
// Parameters:
//   stream:
//     The stream that contains the XML data.
//
// Returns:
//     An System.Xml.Linq.XDocument object that reads the data that is contained in
//     the stream.
public static XDocument Load(Stream stream);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a file.
//
// Parameters:
//   uri:
//     A URI string that references the file to load into a new System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified file.
public static XDocument Load(string uri);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a System.IO.TextReader, optionally
//     preserving white space, setting the base URI, and retaining line information.
//
// Parameters:
//   textReader:
//     A System.IO.TextReader that contains the content for the System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies white space behavior, and whether
//     to load base URI and line information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the XML that was read from the specified
//     System.IO.TextReader.
public static XDocument Load(TextReader textReader, LoadOptions options);
//
// Summary:
//     Loads an System.Xml.Linq.XDocument from an System.Xml.XmlReader, optionally setting
//     the base URI, and retaining line information.
//
// Parameters:
//   reader:
//     A System.Xml.XmlReader that will be read for the content of the System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies whether to load base URI and line
//     information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the XML that was read from the specified
//     System.Xml.XmlReader.
public static XDocument Load(XmlReader reader, LoadOptions options);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a file, optionally preserving white
//     space, setting the base URI, and retaining line information.
//
// Parameters:
//   uri:
//     A URI string that references the file to load into a new System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies white space behavior, and whether
//     to load base URI and line information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified file.
public static XDocument Load(string uri, LoadOptions options);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument instance by using the specified stream,
//     optionally preserving white space, setting the base URI, and retaining line information.
//
// Parameters:
//   stream:
//     The stream containing the XML data.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies whether to load base URI and line
//     information.
//
// Returns:
//     An System.Xml.Linq.XDocument object that reads the data that is contained in
//     the stream.
public static XDocument Load(Stream stream, LoadOptions options);

The parameter we are following should not be the XML data in string.

If you want to load xml from string to XDocument use XDocument.Parse as shown in below picture

Screenshot_3

Happy Coding ComputerSmile

How to implement cascading dropdownlist in asp.net mvc using angularJS


 

Here we will learn how to implement cascading dropdown list using angularjs and asp.net mvc.

Should have knowledge on:

You should have knowledge on html , javascript , angularJS and C#.net and asp.net MVC

Preparation:

1. In this article we will use asp.net mvc as service provider and angularJS as client side framework.

2. In asp.net mvc we will build 3 services to get Company Locations, Departments and Managers data.

3. We will use AngularJS $http service to get data from these services.

4. We will use scope object to bind data to UI

Execution:

Open visual Studio and select new project from file menu

and select Asp.Net web application template and enter name then click on OK button.

image

Click on empty tile and select MVC checkbox to create Asp.net MVC empty project then click on OK button

image

Add Content folder and bootstrap.min.css file in it, as shown in below screenshot

Add Scripts folder and angular.min.js file in it, as shown in below screenshot

image

Add app.js file in Scripts folder and write the following code in it.

var MyModule = angular.module('MyModule', []);

 

above code creates angularjs module.

image

Next Create angular Controller for this module as follows

MyModule.controller('myController', ['$scope', '$http', function (scope, http) {
    //Get Locations
    scope.getLocations = function () {
        //Get Locations service call
        http({
            method: 'Get',
            url: '/Home/GetCompanyLocations'
        }).success(function (data, status, headers, config) {
            //assign locations data to scope
            scope.locations = data;
            //setting default value
            if (scope.locations.length > 0) {
                scope.selectedLocation = scope.locations[0];
            }
        }).error(function (data, status, headers, config) {
            alert("Error occured");
        });
    };
    //Get Departments   
    scope.getDepartments = function () {
        if (scope.selectedLocation.Id > 0) {
            scope.departments = null;
            scope.managers = null;
            //Get Departments service call
            http({
                method: 'POST',
                url: '/Home/GetDepartments',
                data: { locationId: scope.selectedLocation.Id }
            }).success(function (data, status, headers, config) {
                //assign departments data to scope
                scope.departments = data;
                //setting default value
                if (scope.departments.length > 0) {
                    scope.selectedDepartment = scope.departments[0];
                }
            }).error(function (data, status, headers, config) {
                alert("Error occured");
            });
        }
        else {
            scope.departments = null;
            scope.managers = null;
        }
    };
    //Get Managers
    scope.getManagers = function () {
        if (scope.selectedDepartment.Id > 0) {
            //Get Managers service call
            http({
                method: 'POST',
                url: '/Home/GetManagers',
                data: { deptId: scope.selectedDepartment.Id }
            }).success(function (data, status, headers, config) {
                //assign managers data to scope
                scope.managers = data;
                //setting default value
                if (scope.managers.length > 0) {
                    scope.selectedManager = scope.managers[0];
                }
            }).error(function (data, status, headers, config) {
                alert("Error occured");
            });
        }
        else {
            scope.managers = null;
        }
    };
}]);

 

Explanation:

In the above code we have 3 service calls for three dropdowns

1. getLocations

This service get called when the page loads, we can use ngInit directive to call some method on load.

In this service call we will get all the company locations and in success call back, we are assigning the locations to scope.locations object and setting default value for the dropdown using selectedLocation model

2. getDepartments

This service get called when the locations dropdown selection changed, we can use ngChnage directive to call some method on change.

In this service call we will get all the location departments and in success call back, we are assigning the departments to scope.departments object and setting default value for the dropdown using selectedDepartment model

2. getManagers

This service get called when the departments dropdown selection changed, we can use ngChnage directive to call some method on change.

In this service call we will get all the department managers and in success call back, we are assigning the managers to scope.managers object and setting default value for the dropdown using selectedManager model

Add Home controller to controllers folder and one model to models folder and add one action method in home controller and generate a view for it.

image

Write models code in Model (CompanyLocation.cs)

namespace CascadingDropdownList.Models
{
    public class CompanyLocation
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int LocationId { get; set; }
    }
    public class Manager
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int DepartmentId { get; set; }
    }
}

 

Write 3 services 1. GetCompanyLocations 2. GetDepartments 3. GetManagers as follows

        public JsonResult GetCompanyLocations()
        {
            var locations = new List<CompanyLocation>() {
                new CompanyLocation() { Id=0,Name="–select–"},
                new CompanyLocation() { Id=1,Name="Hyderabad"},
                new CompanyLocation() { Id=2,Name="Chennai"},
                new CompanyLocation() { Id=3,Name="Delhi"},
                new CompanyLocation() { Id=4,Name="Bangalore"}
            };
            return Json(locations, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult GetDepartments(int locationId)
        {
            var departments = new List<Department>() {
                new Department() { Id=1,Name="Accounts",LocationId=1},
                new Department() { Id=2,Name="Software",LocationId=1},
                new Department() { Id=3,Name="CustomerCare",LocationId=1},
                new Department() { Id=4,Name="IT",LocationId=1},
                new Department() { Id=5,Name="Software",LocationId=2},
                new Department() { Id=6,Name="CustomerCare",LocationId=2},
                new Department() { Id=7,Name="IT",LocationId=2},
                new Department() { Id=8,Name="Accounts",LocationId=3},
                new Department() { Id=9,Name="CustomerCare",LocationId=3},
                new Department() { Id=10,Name="IT",LocationId=4}
            };
            var result = departments.Where(d => d.LocationId == locationId).ToList();
            result.Insert(0, new Department() { Id = 0, Name = "–select–" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult GetManagers(int deptId)
        {
            var locations = new List<Manager>() {
                new Manager() { Id=1,Name="Venki",DepartmentId=1},
                new Manager() { Id=2,Name="Sri",DepartmentId=5},
                new Manager() { Id=3,Name="Balu",DepartmentId=6},
                new Manager() { Id=4,Name="Gopi",DepartmentId=10},
                new Manager() { Id=5,Name="Ramesh",DepartmentId=3},
                new Manager() { Id=6,Name="Ganesh",DepartmentId=2},
                new Manager() { Id=7,Name="Shiva",DepartmentId=7},
                new Manager() { Id=8,Name="Naidu",DepartmentId=2},
                new Manager() { Id=9,Name="ThataRao",DepartmentId=3},
                new Manager() { Id=10,Name="Bala",DepartmentId=4},
                new Manager() { Id=11,Name="Chandu",DepartmentId=8},
                new Manager() { Id=12,Name="Chaitanya",DepartmentId=9}
            };
            var result = locations.Where(d => d.DepartmentId == deptId).ToList();
            result.Insert(0, new Manager() { Id = 0, Name = "–select–" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

 

Then write following code in View(Index.cshtml)

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/app.js"></script>
<div ng-app="MyModule">
    @* using ng-init getLocations() method invoked when the div loads*@
    <div ng-controller="myController" ng-init="getLocations()">
        <div class="row">
            <div class="form-group col-md-offset-2 col-md-2">
                <label for="loc">Select Location:</label>
                <select ng-model="selectedLocation" ng-change="getDepartments()" class="form-control" id="loc"
                        ng-options="location.Name for location in locations track by location.Id"></select>
                <br />
                <label for="dept" ng-show="departments">Select Department:</label>
                <select ng-model="selectedDepartment" ng-change="getManagers()" ng-show="departments" class="form-control" id="dept"
                        ng-options="department.Name for department in departments track by department.Id"></select>
                <br />
                <label for="mng" ng-show="managers">Select Manager:</label>
                <select ng-model="selectedManager" ng-show="managers" class="form-control" id="mng"
                        ng-options="manager.Name for manager in managers track by manager.Id"></select>
                <br />
            </div>
        </div>
    </div>
</div>

Output:

image

image

image

image

Happy Coding ComputerSmile

Screenshot_18