Thursday, January 31, 2019

Microsoft Fakes Framework - Shim

I was writing the unit test cases using the Microsoft Fakes framework so thought to share my knowledge with you all. I majorly used Shim to write my test cases, so this post mostly focuses on Shim. I will write another post on Stub in coming days.


As most of you know that this is not the only one framework in market to write fake unit test cases the advantage of using this framework on the other is that you have full control on the test case. It will allow you to test your test case if some part of the application is not ready.

Why to use Shim?
The basic question will come in your mind that why to use Shim not the Stub. For me both are same and depend on the design of your application. If you are using any design pattern in your application except singleton then it will be advisable to use the Stub because it work very well with “Interfaces” and it is clearly mentioned in the Microsoft site as well.

Shim basically reduces the burden from the compiler by not making the run time call to the specific methods, it run the Shim code. So, the thumb rule is to use the stubs for the project within the visual studio IDE and use the shim for external libraries where you do not have any control.

If you are on this line then I am hoping that now you have some basic understand and use of Microsoft Fake framework. So let’s get started

Step 1. Create a new project in visual studio. For this post I used the ASP.NET MVC

Step 2. Create a new method


Step 3. Build the project

Step 4. Add Test project

Step 5. Add Microsoft Quality Tools using below nuget command
Install-Package Fakes.Contrib -Version 0.8.18200.2
Step 6. Add project library to test project and right click on the library to add fake assembly.

Step 7.  By doing the step 6, it will add fake assembly to the project

Step 8. Finally, we are ready to write the test case. Add a new class to test project and name it whatever you want and don’t forgot the add namespaces (using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;) and decorate the class with attribute ([TestClass]).
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
{
    [TestClass]
    public class TestClass
    {
        [TestMethod]
        public void StudentExist()
        {
            bool flgStatus = false;
            WebApplication4.Controllers.Fakes.ShimHomeController.AllInstances.StudentExistStringString = (a, b, c) =>
            {
                flgStatus = true;
                return flgStatus;
            };
            WebApplication4.Controllers.HomeController objHome = new WebApplication4.Controllers.HomeController();

            Assert.AreEqual(objHome.StudentExist("First""Last"), true);
        }
    }
}
Step 9. Build the solution

Step 10. The last piece of work is to run the test case. Right click on the test case and select the run test case. If build successful then in test explorer to you see your test successfully executed.






Monday, January 14, 2019

Microsoft SQL Server In A Glance


SQL Server In a glance
Data manipulation Language (DML) – Insert/Update/Delete/Select
Data Dynamic Language (DDL) – Create/Alter/Drop/Truncate
Data Control Language (DCL) – Grant/Revoke
Dynamic Management View (DMV) – Server State/Monitor health of system
Transactional Control Language (TCL) – Commit/Rollback

ACID Properties
A – Atomicity – All or no transaction
C – Consistency – Move a transaction from one state to another
I - Isolation – Keep transaction separate
D – Durability – Make sure no data lost

Keys
Primary Key – Uniquely identifying each row in a table
Foreign Key – It is used to generate the relationship between the tables.
Composite/Compound Key –key that consist of two or more columns that uniquely identify rows in a table.
Unique Key - Uniquely identifying a row in a table. It can also store Null values
Candidate Key – key that consist of two or more columns that uniquely identify rows in a table and one key chosen as primary key.
Surrogate Kay – Identity Column

Joins
Inner Join – return the matching rows present in both the tables
Left Outer Join – return all the rows of left side table
Right Outer Join – return all the rows of right side table
Full Outer Join – Combine the efforts of both left and right outer joins
Cross Join – return the Cartesian result set.
 Self-Join – Joining table to it-self

Normalization
1NF – Only atomic values (Remove the duplicate columns from table)
2NF – Remove subset of data that apply to multiple rows of a table
3NF – Remove non-dependent column
Byce Code – Every determent must have a candidate key
5NF – 3NF and no multivalued dependencies ()

Locks
Shared – Others transaction can read the data but cannot write
Exclusive – Cannot read and write

Index
Cluster Index – Records the way table is physically stored
Non-Cluster Index – create a completely separate object within the table
Key set – Only key store not data
XML – Index on XML column

Data Integrity
Entity – No Duplicate
Domain – Enforce valid entries for a column
Referential – Rows cannot be deleted
User Defined – Enforce specific rule(s)

Function VS Stored Procedure
SNo        Function                                                              Stored Proc
1              Always Return Value                                      Optional
2              Only Input Parameter                                    Input & output parameter
3              Can be called from stored Proc                  Can not call from function

Varchar VS nVarchar
SNo        Varchar                                                                                nVarchar
1              Store data in ANSII and take 1 byte          Store data in Unicode (multilingual) and takes 2 bytes

Temp Table VS Temp Variables
SNo        Temp Table                                                        Temp Variables
1              Transaction Log recorded                             Transaction log not recorded
2              Stored Proc with temp table cannot        Can be precompiled.. Good Performance
be pre compiled
3              Support DDL                                                       Not supper DDL
4              Not allowed in user defined func              Allowed in user defined function

Trigger
Automatically trigger on the occurrence of an event (DDL, DML, Logon)
Before/After/InsteadOf(Perform error, value checking.. Override the standard action of the triggering)

Cursor
Adv – Row by row operation.. Quick and dirty
Dis Adv – Reside in memory (Problem for other process)…Speed & Performance

Other Important Things
Minus – All the rows of first select statement that are not returned by selected select statement.
Union – Combine rows of queries and remove the duplicate records
Union All – Combine rows of queries and keep the duplicate records.
Intersect – Only common rows in both the queries
Except – Keep rows of left query those are not in right query
Implicit Transaction – Auto commit, no begin/end transaction
Coalesce – Return first non-null expression
@@transcount – Active transaction of current connection
@@identity – Last inserted row id.
RAND – Random Number
Transaction – Its take database from one state to another and at the end of transaction system must be in the prior state.

Delete Duplicate
1.       Use of temp table – Take the distinct rows and store them in a temp table then truncate the tale and insert the data back again from the temp table
2.       Using RANK function
Delete from table1
Inner join (select *. RANK() over (partition by key column name(s) order by column name(s)) as RowNum from table1) table2 where table2.RowNum>1


Allow only numbers/decimal in input box

If your requirement is to allow only numeric and decimal numbers in input box using the vanilla javascript then this post will help you in this.


Let’s get started

Step 1 – HTML Code
<input id="txtWinAmt" type="text" class="inputbox" style="width:60px; height:19px;line-height:1px" oninput="ValidateInputIsNumber(this)" />

Step 2 – javascript code
    var regEx = new RegExp(/^\d*\.?\d*$/);
    var lastValid="";
    function ValidateInputIsNumber(controlId)
    {
        if(controlId.value.length==1)
            lastValid="";

        if (regEx.test(controlId.value))
            lastValid = controlId.value;
        else
            controlId.value = lastValid;
    }

Allow only numbers/decimal in input box using AngularJS

If your requirement is to restrict the user input on number and decimal using angularJS then this post will help you in that. If you are using the jQuery then you can visit this post.
Let’s get started
Step 1 – Prerequisites
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.9/angular.js
Step 2 – HTML Code
<input name="NoOfContracts" allow-Decimal-Numbers type="text" id="NoOfContracts" />
<input name="Price" allow-Numbers type="text" id="Price" />

Step 3 – angularJS code
Only Numeric
                var app = angular.module('App', []);
       app.directive('allowNumbers'function () {
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                element.bind('input'function () {
                    var position = this.selectionStart - 1;

                    //remove all but number
                    var fixed = this.value.replace(/[^0-9]/g'');

                    if (this.value !== fixed) {
                        this.value = fixed;
                        this.selectionStart = position;
                        this.selectionEnd = position;
                    }
                });
            }
        }
    });
Decimal
    app.directive('allowDecimalNumbers'function () {
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                element.bind('input'function () {
                    var position = this.selectionStart - 1;

                    //remove all but number and .
                    var fixed = this.value.replace(/[^0-9\.]/g'');
                    if (fixed.charAt(0) === '.')                  //can't start with .
                        fixed = fixed.slice(1);

                    var pos = fixed.indexOf(".") + 1;
                    if (pos >= 0)               //avoid more than one .
                        fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.''');

                    if (this.value !== fixed) {
                        this.value = fixed;
                        this.selectionStart = position;
                        this.selectionEnd = position;
                    }
                });
            }
        }
    });

Export html table data to excel using jQuery



If you are looking for a solution to export the html table data using jQuery, this post will help you in that.



Let’s get started


Step 1 - Prerequisite


            jQuery - https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.9/angular.js


Step 2 – Html Code


<div ><img src="~/Images/Excel.png" class="export" id="exportToExcel" /></div>


<iframe id="frmExcel" style="displaynone"></iframe>





<table id="tblDDeltaDrData">


                    <tr>


                        <th class="tblHeader"> Account</th>


                        <th class="tblHeader">Index</th>


                        <th class="tblHeader">As Of Time</th>


                        <th class="tblHeader">Value</th>


                        <th class="tblHeader">Comments</th>


                    </tr>


<tr>


                        <td class="tblHeader">Abc123</td>


                        <td class="tblHeader">12</td>


                        <td class="tblHeader">18:20</td>


                        <td class="tblHeader">25</td>


                        <td class="tblHeader">Comments</td>


                    </tr>


</table>


Step 3 jQuery code


$(document).ready(function () {


    $('.export#exportToExcel').click(function(){


        var tab_text = ""
;


        var textRange;


        var j = 0, i=0;


           


        //Header Row formatting


        var headerRow = $('[id*=tblDDeltaDrData] tr:first th');


       


        if (headerRow.length > 0) {


            for (i = 0; i < headerRow.length - 1; i++) {


                if (headerRow[i].style.display != 'none')


                    tab_text += '
'
+ headerRow[i].innerHTML + '
';

            }


        else {


            return;


        }




        tab_text += '
';

        i = 0;


        //Table row and cell formatting


        var rows = $('[id*=tblDDeltaDrData] tr:not(:has(th))');




        for (j = 0; j < rows.length; j++) {


            var tds = rows[j].getElementsByTagName('td');


            tab_text += " " ;


            for (i = 0; i < tds.length-1; i++) {


                if (tds[i].style.display != 'none') {


                    tab_text = tab_text + "
"
+tds[i].innerHTML + "
";

                }


            }


            tab_text += "
";

        }




        tab_text = tab_text + "
";

        tab_text = tab_text.replace(/]*>|<\/A>/g""); //remove if u want links in your table


        tab_text = tab_text.replace(/]*>/gi""); // remove if u want images in your table


        tab_text = tab_text.replace(/]*>|<\/input>/gi""); // reomves input params


        var ua = window.navigator.userAgent;


        var msie = ua.indexOf("MSIE ");


        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // For IE


        {


            frmExcel.document.open("txt/html""replace");


            frmExcel.document.write(tab_text);


            frmExcel.document.close();


            frmExcel.focus();


            sa = txtArea1.document.execCommand("SaveAs"true"dDeltaDr.xls");


        }


        else {


            sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));


        }


        return (sa);


    });




    });