Wednesday, June 28, 2017

JQuery - Dynamically Add or Remove CSS

In this blog, we will discuss about add or remove CSS class by JQuery and you can easily apply or remove CSS style class on DOM element dynamically.

JQuery provides several methods for CSS class manipulation:
·         addClass()
·         removeClass()
·         toggleClass()
·         css()

CSS Class
.hideDom
        {
            display: block;    
        }

Add CSS:
You have several way to add CSS class or apply CSS property on element.

addClass() :  the addClass() method add the CSS class on the selected DOM element.
Syntax:
  $('jQuery selector'). addClass ({"css class name"});

Example: hide ddlEmployee dropdown element
$('#ddlEmployee').addClass(".hideDom")

css() : the css() method set CSS style class on the selected DOM element
Syntax:
$('jQuery selector').css({"css property name":"css property value"});

Example: Change Paragraph text color to blue
$('p').css({"color":"blue"});

Remove CSS:
You have several way to remove the applied CSS class or CSS property from element.

removeClass() :  the removeClass() method remove the CSS class from the selected DOM element.
Syntax:
  $('jQuery selector'). removeClass ({"css class name"});

Example:
$('#ddlEmployee').removeClass(".hideDom")

css() : the css() method set blank value applied CSS property
Syntax:
$('jQuery selector').css({"css property name":"css property value"});

Remove the CSS style property ‘Color’ from DOM element
$('p').css({"color":""})

Thanks for visiting!!

Tuesday, June 27, 2017

C# Entity Framework BULK update

Entity Framework is Object-Relational Mapping (ORM) .net framework library, which is used to update, create or delete record from table. This ORM framework allows to perform bulk updates of records in efficient manner without making unnecessary database calls.

In EF, when you want to update any record, first you have to load record in memory and then you can only update the entity and in bulk update scenario, it creates extra overload on database server and also degrade performance.

In this post we will covers below points:
·          How does the entity framework work?
·          How does it impacts performance in bulk update scenario?
·          How at some level we can overcome this problem?

What is Entity Framework ?

Entity Framework definition as per MSDN:

“Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects”

Entity Framework works as a layer between database and business layer (application code) and entity framework maps each database table to entity class ( C# CLR class) and with help of this entity class, developer can perform SQL DML operation like create, modify and delete on mapped database table.

Single Record Update by using Entity Framework: 

Single record update in Entity framework, is very simple and straight forward
·          Open DB context
·          Load record into DB context
·          Update the record’s properties
·          Save DB Context

C#  Entity Framework single record update

Bulk Update (Multiple Record Update) by using Entity Framework: 

In bulk record update, we need to pull records, which are needed to be updated and update each record properties and at last call SaveChanges() method of DBContext to save all changes.

C#  Entity Framework BULK  update


It looks pretty and but it will generate SQL update script for each records and its known problem in Entity framework for bulk operation ( Update or Delete ) and at this time Microsoft does not have any recommended solution instead of using third party entity framework like EntityFramework.Extended.

Other Entity framework related Links:









Monday, June 19, 2017

C# Unit Testing: How to write unit test in C# with Moq

This blog will demonstrates how to write the unit test for business object and how to use Moq framework to mock the unit code or dependency of business object and how the DI makes testable unit of code.

basically Unit Test is used to test the unit of work i.e. method and a good unit test should not cross class boundaries and it certainly should not cross network boundaries to access external resource such as Database.

Practicing writing of unit test always enforce to better design and quality of code and also it reduce the cost of project. You can read more benefit of unit testing  



We should design service/component so carefully, it should be testable. If your service have any dependency and it should be abstracted and replaced by interface and resolved by DI.

The below picture depict, how Class X depends on Class Z and Class Y to make external Service call and Database call. To write unit test for Class X method, we need to stub or mock the depended class object behavior by using any mock framework.

C# Unit Testing - Dependency Injection


Here is a business Object – TulipBusiness, which has a method to get yearly sales figure

Abstract Type – Interface

  public interface ITulipBusiness
    {
        decimal GetTulipAnnualSales(int year);
    }
  
Concreate Class

public class TulipBusiness : ITulipBusiness
    {
        ITulipRepository _tulipRepository;

        public TulipBusiness(ITulipRepository tulipRepository)
        {
            _tulipRepository = tulipRepository;
        }
        public decimal GetTulipAnnualSales(int year)
        {
           decimal salesAmount = _tulipRepository.GetTulipYearSales(year);
            if(salesAmount == 0)
            {
                throw new Exception("No Sales Found");
            }
            return salesAmount;
        }
    }
  
In above class, we can see business object depends on repository object to make database call and get yearly sales figure.

As per DI rule, the dependency ‘TulipRepository’ should be abstract and replaced by interface ‘ITulipRepository’

Abstract Type – Interface
  
public interface ITulipRepository
    {
        decimal GetTulipYearSales(int year);

        decimal GetTulipMonthlySales(int year);
    }
  
Concreate Class
  
  public class TulipRepository : ITulipRepository
    {
        public decimal GetTulipMonthlySales(int year)
        {
            throw new NotImplementedException();
        }

        public decimal GetTulipYearSales(int year)
        {
            throw new NotImplementedException();
        }
    }



TulipRepository repository class will be responsible to make database call and get yearly sales figure but it is not implemented yet.

But if you see business class, the dependency of TulipBusiness class is already replaced by interface ITulipRepository and now can easily code the business object based on ITulipRepository type and with help of Moq framework, we can easily mock the repository class behavior and write the unit test for business class.

Here are  few basic unit tests of Business class
  
    [TestClass]
    public class TulipBusinessTest
    {
        TulipBusiness business;
        Mock _repository;

        [TestInitialize]
        public void init()
        {
            _repository = new Mock(MockBehavior.Strict);

            // Mocking Repository Class Methods

            _repository.Setup(x => x.GetTulipYearSales(2014)).Returns(1050.0M);
            _repository.Setup(x => x.GetTulipYearSales(2015)).Returns(1250.0M);

            // For 2016 Years, No Sales
            _repository.Setup(x => x.GetTulipYearSales(2016)).Returns(0);

            // Initlize the business object and inject mocked repostory object through constructor
            business = new TulipBusiness(_repository.Object);
        } 
        
        [TestMethod]
        public void GetTulipSales_20014()
        {
            decimal result = business.GetTulipAnnualSales(2014);

            // expected value, as per mock should be 1050.0M
            Assert.AreEqual(result, 1050.0M); 
        }

        [TestMethod]
        public void GetTulipSales_20015()
        {
            decimal result = business.GetTulipAnnualSales(2015);

            // expected value, as per mock should be 1250.0M
            Assert.AreEqual(result, 1250.0M); 
        }

        [TestMethod]      
        public void GetTulipSales_2016()
        {
            // expecting Exception
            Assert.ThrowsException<Exception>(() => business.GetTulipAnnualSales(2016));

        }
    }
  
In above unit test for business class TulipBusiness, Moq framework is allowed us to create the mimic behavior of Repository object.

Example:

_repository = new Mock(MockBehavior.Strict);

_repository.Setup(x => x.GetTulipYearSales(2014)).Returns(1050.0M); 

GetTulipYearSales method of ITulipRepository repository type is mocked and it always return 1050.0 sales figure, when we pass year as 2014 and in this way we can easily write the unit test and run the unit test without making any database call.


Here is unit test result: 

C# Unit Testing


Tuesday, June 6, 2017

KnockoutJS - Dirty Check - Observable Pattern

KnockoutJS and Its observable feature which help us to track each field's changes and notify to user un-saved data before leaving screen.


KnockoutJS (KO) is basically a JS library that enables Declarative Bindings using an ‘Observable’ ViewModel on the html view and follow observer pattern approach, enable UI to bind and refresh itself automatically whenever the data bound is modified

KnockoutJS two way binding - Observer pattern


Here is an example of knockoutJS  - observer pattern:


HTML View notify to model JS object, if any change occurred vice versa




KnockoutJS - Dirty Check - Observable Pattern
Dirty Check Message


ViewModel Js File:

Here is a viewmodel js file, which has set of observable fields, which will be bind with view.

function ProductViewModel(model)
{
    this.Price = ko.observable(0);
    this.ID = ko.observable(model.ID);
    this.Name = ko.observable(model.Name);
    this.Email = ko.observable(model.Email);
    this.Price = ko.observable(model.Price);
    this.Product = {
        ID: this.ID(),
        Name: this.Name(),
        Email: this.Email(),
        Price: this.Price()
    };

    this.initialState = ko.toJSON(this.Product);
    this.isDirty = ko.computed(function () {
        this.Product = {
            ID: this.ID(),
            Name: this.Name(),
            Email: this.Email(),
            Price: parseFloat(this.Price())
        };

        var newvalue = ko.toJSON(this.Product);

        if (this.initialState !== newvalue) {
            return true;
        }
        else {
            return false;
        }
    });
}

ViewModel Binding with View:

Here is code, which explains how to bind the viewmodel with HTML view.

<script type="text/javascript">
    var submitted = false;
    $(document).ready(function () {
        submitted = false;
        var data = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
        ko.applyBindings(new ProductViewModel(data));
        $("form").submit(function () {
            submitted = true;
        });

        $(window).bind('beforeunload', function () {
            var dirty = $("#IsDirty").val();
            if (dirty == "true" && submitted == false) {
                return "You haven\'t saved your changes";
            }
        });
    }
    );
</script>

HTML View:

Here is an HTML code, which defines the layout of screen and define control on page.

@using (Html.BeginForm("DirtyView", "Home", FormMethod.Post, new { ID = "form", @class = "form-horizontal" }))
{
    @Html.ValidationSummary(false, "Please resolve the following errors and click'Save Changes' again :",
    new { @class = "alert alert-danger" })
    @Html.HiddenFor(m => m.ID)

    <input type="hidden" data-bind="value : IsDirty" id="IsDirty" />
    <div class="form-group">
        @Html.LabelFor(m => m.Name, new { @class = "control-label col-sm-2" })
        <div class="cpl-sm-10">
            @Html.TextBoxFor(m => m.Name, new { data_bind = "value: Name", @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "control-label col-sm-2" })
        <div class="cpl-sm-10">
            @Html.TextBoxFor(m => m.Email, new { data_bind = "value: Email", @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Price, new { @class = "control-label col-sm-2" })
        <div class="cpl-sm-10">
            @Html.TextBoxFor(m => m.Price, new { data_bind = "value: Price", @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
       <div class="col-sm-offset-2 col-sm-10">
           <button type="submit" class="btn, btn-success">Submit</button>
       </div>
    </div>
    <p>Dirty : <strong data-bind="text: IsDirty"></strong></p>
    <div>
        <strong>OLD Product</strong>
        <span data-bind="text: initialState"></span>
    </div>
}


Thanks for Visiting!!

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...