Wednesday, July 29, 2015

The Open Closed Principle of SOLID

The Open Closed Principle of SOLID Principle

 

image

SOLID principles are like the backbone of OOP, I've gone through with this and obtained a good understanding of this and I thought to share it so that anyone can understand this principle at MAX.
Here is the list of SOLID principles.

SRP

The Single Responsibility Principle

A class should have one, and only one, reason to change.

OCP

The Open Closed Principle

You should be able to extend a classes behavior, without modifying it.

LSP

The Liskov Substitution Principle

Derived classes must be substitutable for their base classes.

ISP

The Interface Segregation Principle

Make fine grained interfaces that are client specific.

DIP

The Dependency Inversion Principle

Depend on abstractions, not on concretions.

Today I am hilighting the Open Closed Principle of SOLID.
Software entities should be open for extension, but closed for modification: Robert Martin
The preceding statement may be a bit confusiing to understand for those who are not very familiar with these principles.


Open for Extension: A class should be open for extension only (for example a derived class or subclasses).
Closed for modification: A class shouldn't be open of modification (for example we should not add code on demand whenever required).


One thing is sure in all software development, most software changes during its life cycle. So, it requires assurance that developers design software that is stable.
For example, let's say you are creating a class to represent an Export. The Export class will export the information/dataset to the desired format like a list of employees and related information to a CSV and text format on behalf of the specified provider. The following sample example is for illustrative purposes only:

  1: public enum ProviderName
  2: {
  3:     SQlServer
  4: }
  5: class Export
  6: {
  7:     public bool ExportFileToDesiredFormat(Provider objProvider)
  8:     {
  9:         if (objProvider == ProviderName.SQlServer)
 10:         {
 11:             //Export to CSV,text,.pdf format code segment which depands     on provider
 12:             return true;
 13:         }
 14:         return true;
 15:     }
 16: }
Now everything looks great. Suppose we come up with one more desired export format. Then at development time it will look like this that is connected with an OLEDB connection:
  1: public enum ProviderName
  2: {
  3:     SQlServer,
  4:     OLEDB,
  5:     Oracle
  6: }
  7: 
  8: class Export
  9: {
 10:     public bool ExportFileToDesiredFormat(string objProvider)
 11:     {
 12:         if (objProvider == ProviderName.SQlServer.ToString())
 13:         {
 14:             //Export to CSV,text,.pdf format code segment which depands on provider
 15:             return true;
 16:         }
 17:         else if (objProvider == ProviderName.OLEDB.ToString())
 18:         {
 19:             //Export to CSV,text,.pdf format code segment which depands on provider
 20:             return true;
 21:         }
 22:         else if (objProvider == ProviderName.Oracle.ToString())
 23:         {
 24:             //Export to CSV,text,.pdf format code segment which depands on provider
 25:             return true;
 26:         }
 27:         else 
 28:         { }
 29:         return true;
 30:     }
 31: }
Here if you can see from the code above, we are modifying the class Export rather than extending, in other words whenever we add a new export format then we are modifying the existing class that violates the OCP.
It's time to remember OCP: entities should be open for extension and closed for modification.
Here is the code segment after considering OCP in mind. The sample example is for illustrative purposes only.

  1: interface IProvider
  2: {
  3:     bool connect(string objProviderName);
  4: }
  5: 
  6: class ExportFileFromSQLProvider : IProvider
  7: {
  8:     public bool connect(string objProviderName)
  9:     {
 10:         //write code on behalf of provider to get connect with SQLProvider and export dataset to desired format such as .csv,.pdf,.text
 11:         return true;
 12:     }
 13: }
 14: 
 15: class ExportFileFromOLEDBProvider : IProvider
 16: {
 17:     public bool connect(string objProviderName)
 18:     {
 19:         //write code on behalf of provide to get connect with OLEDBProvider and export dataset to desired format such as .csv,.pdf,.text
 20:         return true;
 21:     }
 22: }
 23: 
 24: class ExportFileFromOracleProvider : IProvider
 25: {
 26:     public bool connect(string objProviderName)
 27:     {
 28:         //write code on behalf of provide to get connect with OracleProvider and export dataset to desired format such as .csv,.pdf,.text
 29:         return true;
 30:     }
 31: }
 32: 
 33: 
The main method will look like:
  1: class Program
  2: {
  3:     static void Main(string[] args)
  4:     {
  5:         IProvider objSQLIProvider = new ExportFileFromSQLProvider();
  6:         bool sucess = objSQLIProvider.connect("sqlprovider");
  7:         IProvider objOLEDBIProvider = new ExportFileFromOLEDBProvider();
  8:         bool result = objOLEDBIProvider.connect("OLEDBProvider");
  9:     }
 10: }

Using this approach we can add as many ProviderName to export a file as needed. Thus the IProvider interface implements the idea of open for extension but closed for modifications.
It's very easy to understand, especially for those who are not familiar with this principle. Hope you enjoyed this demonstration.


Enjoy Coding and Have wonderful day ahead Smile


To know more MVC and WebApi Kindly go through with these links

MVC Articles & WCF and WebApi

Thanks.
Enjoy coding and reading.


Tuesday, July 28, 2015

Difference between ROW_NUMBER () OVER () & PARTITION BY clause

 

 

This is one of the main basic and needed terms which you may have used in your daily uses in SQL Server and off course one of the main interview question.

image

 

Before jumping into code indeed lets understand what it means by ROW_NUMBER() & PARTITION BY clause.

Order by is required clause for using ROW_NUMBER(), as row number is generated on the basis of the column used along with ROW_NUMBER()

Example: Suppose there are 7 employees in your table 3 are from city Roorkee and others 4 are from city Rohtak and Noida respectively.

Now, if you would use "Order By empid" only, it would assign ROW_NUMBER() on the basis of empid in ascending order from 1, 2, 3, 4,5,6,7

But, if you want to generate row numbers differently for cities then use PARTITION BY in that case.

Please have a look on the example depicted below:

  1: declare @table table(
  2: 
  3: empid varchar(10),Name varchar(20), city char(10)
  4: 
  5: )
  6: 
  7: insert into @table 
  8: 
  9: select 'EMP001','Sachin Kalia', 'RoorKee'
 10: 
 11: union all select 'EMP002', 'Rohit Kalia', 'RoorKee'
 12: 
 13: union all select 'EMP003', 'Yogendra', 'RoorKee'
 14: 
 15: union all select 'EMP004', 'Ravish Sindhwani', 'Rohtak'
 16: 
 17: union all select 'EMP005', 'Parvinder', 'Rohtak'
 18: 
 19: union all select 'EMP006', 'Abhinav Singh', 'Noida'
 20: 
 21: union all select 'EMP006', 'Anshu Agarwal', 'Noida'
 22: 
 23: Select * from @table
 24: 
 25: 
After running the above sql statements here is the result.Now we will apply Order By and Partition By clause seperatly in order to understand the facts.

clip_image002

Now execute the given below lines one by one and see the actual facts.

  1: declare @table table(
  2: 
  3: empid varchar(10),Name varchar(20), city char(10)
  4: 
  5: )
  6: 
  7: insert into @table 
  8: 
  9: select 'EMP001','Sachin Kalia', 'RoorKee'
 10: 
 11: union all select 'EMP002', 'Rohit Kalia', 'RoorKee'
 12: 
 13: union all select 'EMP003', 'Yogendra', 'RoorKee'
 14: 
 15: union all select 'EMP004', 'Ravish Sindhwani', 'Rohtak'
 16: 
 17: union all select 'EMP005', 'Parvinder', 'Rohtak'
 18: 
 19: union all select 'EMP006', 'Abhinav Singh', 'Noida'
 20: 
 21: union all select 'EMP006', 'Anshu Agarwal', 'Noida'
 22: 
 23: --Select * from @table
 24: 
 25: SELECT *, ROW_NUMBER() OVER (ORDER BY empid ) As Counter
 26: 
 27: FROM @table
 28: 

The above given query will give the the following output :

clip_image003

One more clause that can be used with Over is PARTITION BY in case when you want to set one more level of filtration while generating Row_Number.Here is an example given below:

  1: declare @table table(
  2: 
  3: empid varchar(10),Name varchar(20), city char(10)
  4: 
  5: )
  6: 
  7: insert into @table 
  8: 
  9: select 'EMP001','Sachin Kalia', 'RoorKee'
 10: 
 11: union all select 'EMP002', 'Rohit Kalia', 'RoorKee'
 12: 
 13: union all select 'EMP003', 'Yogendra', 'RoorKee'
 14: 
 15: union all select 'EMP004', 'Ravish Sindhwani', 'Rohtak'
 16: 
 17: union all select 'EMP005', 'Parvinder', 'Rohtak'
 18: 
 19: union all select 'EMP006', 'Abhinav Singh', 'Noida'
 20: 
 21: union all select 'EMP006', 'Anshu Agarwal', 'Noida'
 22: 
 23: SELECT *, ROW_NUMBER() OVER (PARTITION BY city ORDER BY empid) As CounterByCityName FROM @table
 24: 
 25: 
clip_image004

This is the beauty of these keywords and may utilize to make the rows sequential in manner.

Kindly find an attached SQL file.

Thanks



Monday, July 27, 2015

Select data of a table from another database in SQL Server 2008R2

In this short snippet blog I’ve demonstrate a condition to use two databases / schemas on the same database server, you can query across databases with the given below syntax :

  1: select * from database1.dbo.table1 t1 join database2.dbo.table2 t2 on t1.column_Name= t2.column_Name
e.g. select * from DBEncrypt.[dbo].TestTable
 
image
 
Sachin Kalia

Wednesday, July 22, 2015

Controller to Controller Communication Using $RouteScope in AngularJS

Here I've merely thought to write my thoughts and hands-on experience with Angular. This is another article that tells you how to get your hands dirty with Controller to Controller communication using $RouteScope in AngularJs AngularJs.
I've designed a program to help you become familiar with just a few keywords that you may be confronting in the future. Those keywords are shown below in the article.
As a newbie to Angular you must be familiar with a few main keywords that you will be using in an application:

  • ng-app: This directive ng-app tells that this element is the "owner" of an AngularJs application.
  • ng-model: This directive ng-model binds the value of the input field to the application variablefirstName.
  • ng-bind: This directive ng-bind binds the innerHTML of the specific element to the application variable firstName.

The Application Life Cycle of this program is shown below:

Life cycle of Basic application

I've created an HTML page as the View and named it FirstAngularApp.html that keeps a reference of an Angular.min.js file. You can download and add it to the solution as well.

  1: Here I have a HTML page that keeps the following code segment.
  2: 
  3: <!DOCTYPE html>  
  4: <html>  
  5:     <head>  
  6:         <title>DotNetPiper.com</title>  
  7:         <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>  
  8:         <script type="text/javascript" src="Scripts/Main1.js"></script>  
  9:         <!--<script src="Scripts/Main1.js"></script>-->  
 10:         <script></script>  
 11:     </head>  
 12:     <body ng-app="myApp" ng-controller="Myctrl">  
 13:         <div ng-controller="Myctrl1">  
 14:             <strong>Custom information :</strong> {{message}}  
 15:             <br />  
 16:             <strong>Custom information provide by Controller 2 is :</strong> {{ CompName(message) }}  
 17:             <br />  
 18:         </div>  
 19:         <!--   
 20:     <div ng-controller="Myctrl3"></div> -->  
 21:     </body>  
 22: </html> 
 

Please have a look at the image shown below:
image
In the code segment shown above it has <strong>{{ CompName(message) }} <br /><br />. This code calls the function CompName defined in the Controller Myctrl1. As soon as this line executes it goes to the controller and performs the required actions.
Please refer to the image shown below that keeps the code segment for the Main1.js file.



code
$rootScope

The $rootScope is the top-most scope and acts like a global variable. An app can have only one $rootScope that will be shared among all the components. All other $scopes are children of the $rootScope.
Code segment for main1.js


  1: /// <reference path="angular.intellisense.js" />
  2: /// <reference path="angular.js" />
  3: /// <reference path="angular.min.js" />
  4: 
  5: 
  6: var app = angular.module('myApp', []);  
  7: 
  8: app.controller('Myctrl', function ($scope, $rootScope) {  
  9: //debugger;
 10:     $scope.firstName = "Sachin Kalia";  
 11:     $scope.lastName = "DotnetPiper.com";  
 12: 
 13: 
 14:     $rootScope.testProp = "sachin";  
 15: 
 16:     $rootScope.CompDetail2 = function CompDetail2(data) {  
 17: return "I am called from Controller1 RootScope(Global) method name CompDetail2  =>=> " + data;  
 18: 
 19:     };  
 20: 
 21:     $scope.CompDetails = function CompDetails() {  
 22: return "Welcome to DotnetPiper.com " + $scope.firstName + " " + $scope.lastName;  
 23: 
 24:     };  
 25: });  
 26: 
 27: 
 28: app.controller('Myctrl1', function ($scope, $rootScope) {  
 29:     alert("Welcome");  
 30:     $scope.message = " Welcome to DotnetPiper.com!!!";  
 31:     $scope.CompName = function CompName(data) {  
 32: 
 33: return $rootScope.CompDetail2(data);  
 34: 
 35: //alert(returnValue + "i Have added this value ");
 36: // $rootScope.CompDetail(data);
 37: // alert("passing value to next controller" + data);
 38:     };  
 39: });  
 40: 


As soon as you run BasicAngularApp.html it shows you the result as shown below in the image.
custom information
If you noticed from the image, it has main1.js shown above that calls the method compName() that accepts data as the parameter sent by the view page. Further it again tries to access the method CompDetail2() that is already defined in another controller named Myctrl and accessible using the $routeScope global variable.
$routeScope methods and property should be defined/written prior to the calling method otherwise it will provide an “undefined” error since JavaScript finds the reference line by line.
Kindly have a look at the Life cycle of the basic application as depicted below:
Life cycle of Basic application
I hope it'll help you some day.
You can download a sample application from here : Controller to Controller Communication Using $RouteScope in AngularJS


Kindly inform me if having any query.


Cheers, .Net
Sachin Kalia

Thursday, July 16, 2015

Integration of Google ReCaptcha With MVC4 Application

It is in trend these days to verify that a user is a human or not and the easiest and most used option to do this is to have Google ReCaptcha in your application. This article elaborates how to integrate Google reCaptcha in a MVC4 application. After going through with this article you may get the benefit of this rich feature.
ReCaptcha

To understand what reCaptcha is we first need to define the term “Captcha“.
Captcha is a test made of an image and distorted text that must be solved by human users when they want to subscribe to websites that want to ensure the user is a human being and not a bot or a computer (= preventing spam). Excerpt taken from link.
The initial step to integrate Google reCaptcha is to register your site/domain to receive public/private keys. To reach that level merely paste this URL in a browser.
As soon as you hit the preceding given URL it gives you given the following screen.


site
I have registered mine as shown in the following screen shot:
screen shot
This is how it looks after registering this feature and provides public/private keys along with a reference file and API to use further.
reference file and API
You have registered and now ready to use this excellent feature.
Step 1
Kindly put you public key and private key in the web.config file as shown in the following image:
shown below in image
Step 2

Kindly ensure a few points in order to integrate Google reCaptcha on the .cshtml page as shown in the following image:
image
Source Code Create.cshtml page is given below:

      1: @model MVCSample.Models.EmpRegistration  
      2: @{  
      3:     ViewBag.Title = "Create";  
      4: }  
      5: <h2>  
      6:     Create</h2>  
      7: <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>  
      8: <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>  
      9: 
     10: <script type="text/javascript" src='https://www.google.com/recaptcha/api.js'></script>  
     11: 
     12: @using (Html.BeginForm())  
     13: {  
     14:     @Html.ValidationSummary(true)  
     15:     <fieldset>  
     16:         <legend>EmpRegistration</legend>  
     17:         <div class="editor-label">  
     18:             @Html.LabelFor(model => model.Id)  
     19:         </div>  
     20:         <div class="editor-field">  
     21:           @*  @Html.EditorFor(model => model.Id)  
     22:             @Htm*@l.ValidationMessageFor(model => model.Id)  
     23:         </div>  
     24:         <div class="editor-label">  
     25:             @Html.LabelFor(model => model.Name)  
     26:         </div>  
     27:         <div class="editor-field">  
     28:             @Html.EditorFor(model => model.Name)  
     29:             @Html.ValidationMessageFor(model => model.Name)  
     30:         </div>  
     31:         <div class="editor-label">  
     32:             @Html.LabelFor(model => model.Address)  
     33:         </div>  
     34:         <div class="editor-field">  
     35:             @Html.EditorFor(model => model.Address)  
     36:             @Html.ValidationMessageFor(model => model.Address)  
     37:         </div>  
     38:         <div class="editor-label">  
     39:             @Html.LabelFor(model => model.City)  
     40:         </div>  
     41:         <div class="editor-field">  
     42:             @Html.EditorFor(model => model.City)  
     43:             @Html.ValidationMessageFor(model => model.City)  
     44:         </div>  
     45:         <div class="g-recaptcha"  data-sitekey=@System.Configuration.ConfigurationManager.AppSettings["recaptchaPublicKey"]></div>  
     46: 
     47:         <p>  
     48:             <input type="submit" value="Create" />  
     49:         </p>  
     50:     </fieldset>  
     51: }  
     52: <div>  
     53:     @Html.ActionLink("Back to List", "Index")  
     54: </div>

Step 3

Verify that the user response as reCAPTCHA is generated and resolved by a user. The following API URL is used to verify the user response.
In the preceding API URL the secret and response parameters are required and whereas the remoteip is optional. We have a response class to verify the user response.
response parameters
I have created a POST method in the Index action in the RegisterController to verify the user response.
Here the code segment is shown below:

  1: [HttpPost]  
  2: public ActionResult Create(EmpRegistration modelEmpRegistration)  
  3: {  
  4: bool isCapthcaValid = ValidateCaptcha(Request["g-recaptcha-response"]);  
  5: 
  6: try
  7:     {  
  8: if (isCapthcaValid)  
  9:         {  
 10: if (ModelState.IsValid)  
 11:             {  
 12: //dbContext.AddToEmpRegistrations(modelEmpRegistration);
 13: //dbContext.SaveChanges();
 14: 
 15:             }  
 16: return RedirectToAction("Create");  
 17:         }  
 18: else
 19:         {  
 20: return Content("You have put wrong Captcha,Please ensure the authenticity !!!");  
 21:         }  
 22: //return RedirectToAction("Index");
 23:     }  
 24: catch
 25:     {  
 26: return View();  
 27:     }  
 28: }  
 29: 
 30: public static bool ValidateCaptcha(string response)  
 31: {  
 32: //secret that was generated in key value pair
 33: string secret = WebConfigurationManager.AppSettings["recaptchaPrivateKey"];  
 34: 
 35:     var client = new WebClient();  
 36:     var reply =  client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));  
 37: 
 38:     var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);  
 39: 
 40: return Convert.ToBoolean(captchaResponse.Success);  
 41: 
 42: }  
 43: 
Step 4

Run the application and press F5. It'll open a page as shown in the image below:
Run the application
Click on “Create New” => It will open a page as depicted below:
Create New
Case 1
Fill in the desired details and check the checkbox. Just prefix the I'm not a robot. It will open the popup to select the choice.
select food
If you have provide the correct details it will consider you to be a human and shows the following screen as confirmation.
Create
Click on the Create button and it reaches the code segment and executes the code.
Create button
As you can see from the image above it has returned “success” from the server meaning it worked perfectly.
Note: After executing successfully it returns to the create page again. I've used this page for demonstration purposes only.
Case 2
If you don't check the checkbox prefix to the message “I'm not a robot” and press Enter. It goes to the code and verifies the authenticity and it returns false. It means you are not a valid user.
authenticity
valid user
Please find the source code as an attachment.
Integration of Google ReCaptcha with MVC4 Application - Running Application.
I hope it will help to resolve your issue.



Thanks.