How/Best way to check the string is Palindrome or not in Javascript


What is palindrome

Palindrome is a word, phrase, or sequence that reads the same backwards as forwards as shown in the below example.

palindrome example

Example 1 palindrome using reverse function

var profile = 'madam';
if (profile == profile.split('').reverse().join(''))
    console.log(profile + " is a palindrome");
else
    console.log(profile + " is not a palindrome");

Using reverse is overkill because you don’t need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.

The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.

Example 2 palindrome without using reverse

var profile = 'madam';

function isPalindrome(profile) {
    var n = profile.length;
    for (var i = 0; i < (n / 2) ; ++i) {
        if (profile.charAt(i) != profile.charAt(n – i – 1))
            return false;
    }
    return true;
}

var isit = isPalindrome(profile);
if(isit)
    console.log(profile + " is a palindrome");
else
    console.log(profile + " is not a palindrome");

Happy coding

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

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

How to get dropdown list or select list selected value and selected text in angularJS :: asp.net mvc


We can get dropdown list selected value or text using ng-model attribute as shown in the below example

How to get dropdown list or select list selected value and selected text in angularJS asp.net mvc

        public JsonResult GetColorsData()
        {
            List<Colors> colors = new List<Colors>()
            {
                new Colors() { Id=1,Name="Red"},
                new Colors() { Id=2,Name="White"},
                new Colors() { Id=3,Name="Blue"},
                new Colors() { Id=4,Name="Green"},
            };
            return Json(colors, JsonRequestBehavior.AllowGet);
        }

@{
    ViewBag.Title = "How to get dropdown list or select list selected value and selected text in angularJS :: asp.net mvc";
}

<h3>Colors</h3>
<script src="~/Scripts/angular.min.js"></script>

<div ng-app="ddlExample">
    <div ng-controller="ddlController">

        <select ng-model="selectedColor"
                ng-options="color.Name for color in colors track by color.Id">
        </select>

        <br/>
        Selected Color Name : {{selectedColor.Name}} <br/>
        Selected Color Id : {{selectedColor.Id}}
    </div>
</div>

<script>
    angular.module('ddlExample', [])
      .controller('ddlController', ['$scope', '$http', function ($scope, $http) {
          $http({
              method: 'Get',
              url: '/Home/GetColorsData'
          }).success(function (data, status, headers, config) {
              //adding colors to model
              $scope.colors = data;
              //set selected color
              $scope.selectedColor = $scope.colors[1];
          }).error(function (data, status, headers, config) {
              $scope.message = 'Error';
          });
      }]);
</script>

Output:

Dynamic data binding to dropdown list in angularjs mvc

Happy coding…