Monday, August 31, 2015

Cross Site Request Forgery in MVC

In today's blog post I am going to talk about an important security attack in MVC application i.e. Cross Site Request Forgery (CSRF).

Cross Site Request Forgery

This is an attack whereby the victim is fooled in to taking some unwanted action on his/ her behalf. In order to illustrate the attack, let me first explain how a browser works.

Suppose, we login to our bank account. When the login page appears, we enter our username and password and we get some session information from the server. The browser then stores the session information in a cookie. For the subsequent requests to the same site, browser automatically sends the session info cookie with the request which identifies us. So that we don't have to put our username and password multiple times.

Now, let's see how the attacker can use this browser behavior to facilitate the CSRF attack. Suppose there is a widely used forum or a website which allows people to post links and the attacker has posted the following link at some place:

http://myfakebank.com/transfer?usd=10000&targetaccountnum=123456789

The aim of the attacker is to make the victim click this link while he is logged in to his/ her bank account. And voila, the attacker gets the amount transferred into the account number mentioned. So next time if you browse the web with your bank account logged in, beware! ;)

Usually, the attacker can apply some social engineering skills to make the victim click the link but that's not the point. The point is that the victim has been fooled into some action which he/ she never intended. This is Cross-Site Request Forgery attack.

So here since the user is logged in to the myfakebank website and the request is triggered, the victim transfers 10000 dollars from his/her account without his/her intention.

How to Prevent?

It would be injustice to everyone if we just discuss the attack and do not discuss the ways to prevent it. ASP.NET MVC provides an easy way to avoid this i.e. make sure that the user has submitted the data willingly. This can be accomplished by using a simple hidden value on the form whenever the user requests a form and then on form submit just match the value previously sent. If the values match then it's indeed the correct user who submitted the form otherwise it can be considered a cross site request forgery attack.

This hidden value used to prevent CSRF is called Anti Forgery token. In order to use this, we need to put it on our View like this:

@Html.AntiForgeryToken()

This puts an encrypted value in the form like this:

<input type="hidden" value="encrypted value">

And then, on POST controller action, we can validate it like this:

[ValidateAntiforgeryToken]
public ActionResult Transfer(…)

This anti-forgery token can prevent most of the CSRF attacks and should always be used.

Conclusion

Today we discussed what cross site request forgery attack is and how it can be harmful. We also discussed how anti-forgery token works in ASP.NET MVC and how it prevents CSRF attack.
For future updates to my weekly blog, please subscribe to the blog.
References:
"Professional ASP.NET MVC 5"

Sunday, August 30, 2015

Model and View model in MVC 5

Model

Model usually represent the business domain entities. These entities are used to interact with the database and in a simple system, they usually have one to one relationship with database tables.

Battle of Business Logic

This is something that I see most people get wrong in their interviews. When I ask them where to put the business logic, I usually get the answer as Controller. The best practices say that all business logic should be in Model. However, I will not lie, I do some times put business logic in controller itself if it is something small. I don't want to do it the hard way for smaller code, especially if I know that this won't be needed again or if its a test project. However, if its a substantial code I would recommend putting it in Model only.
The major advantage of keeping the business logic in Model is less duplicated code. I won't be writing the same thing again and again in Views or Controller. Secondly, it helps us in isolating the code for testing. Finally, it also helps in making the view and controller easier to read and understand.

ViewModel

ViewModels are classes that are used for interaction with Views. Views which use such viewModels are called strongly typed views. Let's take an example of Student class.

Suppose the Model looks like:
public class Student
{

      int Student Id { get; set; }
      string FirstName { get; set; }
      string LastName { get; set; }

}


In Add.cshtml we can use this
public class StudentViewModel
{

     [Required] 
     string FirstName;

     [Required] 
     string LastName; 

}


Ideally, ViewModel should only have the fields that are required by the specific View. This not only helps to keep the code clean and easy to understand but also prevents attacks like OverPosting which I will explain in a later post.

ViewModels are also useful in the scenario where a single view needs to show data from multiple models. For example, Student Details page might have Student detail as well as Department Detail.
public class StudentDetailViewModel
{
     [Required] 
     string FirstName;

     [Required] 
     string LastName;

     [Required] 
     string DepartmentName; 
}

So when we are filling the ViewModel, we can map the properties which we need to read explicitly from Student and Department model and have complete control on the system. The fields which are supposed to be hidden should be excluded (or encrypted atleast) from the viewModel so that user cannot get access to them by any chance.

Conclusion

Understanding Model and ViewModel is crucial to have a clean code base esp in an MVC application. Separating them not only helps us to make our code easy to understand but also makes it less prone to bugs.

Saturday, August 29, 2015

Why Comments Are Bad

I recently read this book on Clean Code by Robert C Martin and there he talked about comments in our code which kind of got stuck in my head. So I decided to write a blog post to highlight some of the down sides of very frequently used comments in our code.

Comment

Comments are non-executing statements that we write in our code generally in order to explain the code intent or some other information.

Why Comments are bad

Most of the time we write comments because we do not write clean code. Every time we are in the position to write a comment, we should think it through. We should ask ourselves if there is a better way that we can write the code and demonstrate our intentions in the code itself. And every time we succumb to write comments in the code, we should feel guilty and failure that we couldn't write a self-explanatory code.

Let's take a look at an example:
foreach (var student in students)
        {
         //for late enrollment charge extra fee
         if (student.EnrollmentDate>new DateTime(2015,1, 1))
             enrollmentFee = enrollmentFee + 1000;
         } 

Here, the comment is written to specify the special logic for late enrolled students. Instead, it could have been written like this:
foreach(var student in students)
        {
                if (student.IsLateEnrolled())
                    enrollmentFee = enrollmentFee + 1000;
        }

Here, we just simply created a method with a name which we were writing in comments anyways as plain text. This is much more clear and easy to maintain as compared to a comment.

I know I am being a little harsh on comments but the main reason behind that is that the comments don't get updated. The older the comment, usually farther it is from its intention. It's very difficult to maintain comments. And bad comments are usually big lies and can be frustrating and are often big time-wasters. They make our code look ugly and cluttered. We should always be ready to put some time and effort to try to avoid comments, if possible.

Let's take a look at some of the bad comments in our code.

Bad Comments

Here, the property d is used to denote Start Date.
public DateTime d { get; set; } // Start Date

Instead, the variable could have been named liked this and then the comment won't be needed
public DateTime StartDate { get; set; }

Lying Comments

Everyone must have seen code similar to this.
//always returns true
        public bool IsAdmin()
        {
            return false;
        }

The comment must have been written a long time ago and since then the code has been updated but the comment hasn't. Imagine if the method definition is complex and comment is a lie, how frustrating can it be.

Noise Comment

These are some comments which are not needed. They are possible breeding grounds of turning into bad comments in future. 
public DateTime StartDate { get; set; } // Start Date

This comment should be removed to avoid unnecessary clutter.

Commented-out Code

Having commented code for possible later use should not be needed. We have very good source control systems these days and we should use their power in case we want to see the old code and revert back. We should not clutter our code base by having commented out code.

//public DateTime StartDate { get; set; } 

Useless Comments

This comment s not really telling me anything why this code is written like this.
public bool IsAdmin()
        {
            //shhhh don't tell this to anyone
            return (LastName == "Smith" || Role == "Admin")
        }

Conclusion

In this blog post, I showed a few places where we see bad comments which we can avoid and improve our code base. Having less cluttered and clean code increases productivity.
The intent of this post is to say that comments should not make up for bad code. We should be ready to apply little time and effort if we can to avoid such comments. However, sometimes comments are necessary and are good to have but those cases are rather few as compared to how liberally we use this feature. I am not saying that we should stop writing comments, I just want to say that we should use them more cautiously. Hope this post will motivate everyone to use comments more judiciously.

For future updates to my weekly blog, please subscribe to the blog

Friday, August 28, 2015

Routing in MVC5

In old web frameworks like classic ASP, there used to be a direct relationship between the URL requested and the file on disk. For example, when we requested http://www.mysite.com/index.aspx, we used to get the index.aspx file. In contrast, in ASP.NET MVC, URL is generally mapped to an action method in controller class which decides what is supposed to be the response.


Routing

Routing is the mechanism for URL pattern matching to controller action method. Simplistically, it maintains a list of patterns in a table and when a request comes in, it matches those patterns one by one and returns the first successful match. If none of the patterns match, we get 404 Not Found error.

We can add new routes by adding to the static routes property of RouteTable class. Let's take a look at
the default code we find in RouteConfig.cs file.

public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

            );

        }

In the code above, routes.MapRoute is setting the name of the route to Default. The name is not going to affect the URL mapping, it's just there to uniquely identify the route. The url specifies the pattern to be matched. So, here it says that controller name, action name and id are supposed to be separated by forward slash "/". Then defaults as the names suggests assigns defaults as HomeController and Index action method. The id does not have a default value but it is specified as optional.
So when I run the application for the first time without any controller and action name in URL, I get the response provided by Home Controller's Index Action method.

routes.IgnoreRoute is basically an instruction to routing mechanism to ignore any request that matches this pattern. So the statement will ignore all the requests which have the extension .axd. On such requests normal ASP.NET handling will occur which is dependent on existing HttpHandler mappings.

Considerations for Routing

When routing handles URL requests, it tries to match the URL of the request to a route. Matching a URL request to a route depends on all the following conditions:
  • The route patterns that we have defined or the default route patterns, if any, that are included in our project type.
  • The order in which we added routes to the Routes collection.
  • Default values that we have provided for a route, if any.
  • Constraints that we have provided for a route, if any.
  • Whether we have defined routing to handle requests that match a physical file.

Route Debugger

Debugging routes can be frustrating some times. We might think that this pattern should match but somehow we don't get the expected result. For this purpose, I will highly recommend RouteDebugger. Simply add the Nuget package called RouteDebugger. Once added, we can control the visibility of the table using this entry in web.config file.

<add key="RouteDebugger:Enabled" value="true" />

Conclusion

Routing is pretty easy to start with but it takes a long time to master. Routes are also part of the application interface to the user and having proper intuitive routes improve user experience as well as search engine optimization.
I will cover Attribute Routing in my next post. For future updates to my weekly blog, please subscribe to the blog

Thursday, August 27, 2015

View Method, ViewData and TempData in MVC5

VIEW

Views provide the user interface as response to an action. In general, when the user hits a URL, it gets mapped to a controller action and the controller action then returns a view which contains the HTML supposed to be rendered by the browser.

When we look at the default Home Controller's Index() method, we see that it simply returns the result of the View() method.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
...
}

Let's take a look at what happens under the hood.

Controller.View() Method

The View() method creates an object of type ViewResult and returns it. This object is responsible for rendering the View. Inside the View() method in controller class, we just simply set the properties like: ViewName, masterName and model. The View method in controller class has multiple overloads for different combinations of the aforementioned three properties. For any of the overloads, if some property is not set, it is simply set to null
i)   View()
ii)  View(object model)
iii) View(string viewName)
iv) View(string viewName, object model)
v)  View(string viewName, string masterName)
vi) View(string viewName, string masterName, object model)

viewName is used to pass the name of the view. model is used to pass the viewmodel i.e. data to be rendered in the view. masterName is used to specify the name of the master page to be rendered.
Other than these, there are 2 more overloads of the View method which take the IView object and model:
vii) View(IView view)
viii) View(IView view, object model)

view parameter is used to specify the view to be rendered.
So once these properties are set inside the ViewResult object and returned, the ASP.NET MVC framework calls the ExecuteResult() method of the ViewResult object in order to render it.

Default View Path

About ViewPath, I want to mention one thing i.e. If no view name is passed, by default the MVC framework searches for a view at Views/[Controller]/[Action].cshtml. So for the HomeController's Index Action, we get /Views/Home/Index.cshtml view.


ViewBag, ViewData & ViewDataDictionary

ViewData is of type ViewDataDictionary which is a specialized dictionary. It is used to pass data between controller and view. Inside the controller action method, we can pass value to the view like this:

ViewData["color"] = "red";

And In the View, we can use that value like this:

@ViewData["color"]

Similarly, we can pass the data in reverse direction as well i.e. from view to controller action.

ViewBag is a dynamic wrapper around ViewData. It's just syntactical sugar which allows us to access the same data like this:

ViewBag.color

They both point to the same data in terms of memory. So we can even set value for ViewData["color"] and access it using ViewBag.color, if we want.

TempData

Our discussion won't be complete if we talk about ViewData and don't talk about TempData. This is similar to ViewData in the sense that its also used to send data between controller and view but the key difference is, it is used to send data between current and next HTTP Requests. When we redirect as part of an action method result, a new HTTP request is generated from the browser to the redirected route. In such a case, if we have anything set in the ViewData, it won't be available to us because ViewData is accessible only per request. In such a scenario, we can use TempData. Syntactically, its similar to ViewData.

public ActionResult Index()
        {
            TempData["mycolor"] = "black";
            return Redirect("Home/About");
        }

Conclusion

Overall, Controller's View method's various overloads give us control which view to render and the viewmodel to be passed in. MVC provides us with some default convention to follow for organizing our views in the directory but it also allows us to easily override those if needed. Also, in this post we discussed the underlying structure of ViewData and when to use ViewData and TempData.

For future updates to my weekly blog, please subscribe to the blog.

Secure Cookie in ASP.NET Application

In today's blog post, we will be discussing what the secure flag is on a cookie and why we should keep it set.


Secure Flag on Cookie

There is a boolean flag on the cookie called Secure which decides whether to send the cookie on an HTTP request or not. If the flag is set on the cookie, the cookie will not be sent on a regular Http request; it will be transmitted only on Https request.

Imagine if you have a web application which implements Https to be more secure. Once you login, the Authentication cookie (named as .AspNet.ApplicationCookie in my .NET Application) gets set. This cookie gets sent with each subsequent request to inform the server the identity of the logged in user.

If a man in the middle tries to view those requests, they will not be able to see anything as they are encrypted (Https). However, out of multiple requests, if there is even a single request on Http (for example for some resource like Javascript, image, css, etc), the attacker can see all the cookies (including authentication cookie). The attacker might be able to convince the user to successfully issue an Http Request through other means (social engineering). Such an Http request poses a serious security vulnerability as authentication cookie is exposed.
Using this authentication cookie, attacker can hijack the victim's session without victim ever even knowing about it.

How To Prevent

In an ASP.NET application, we can set the Secure flag by adding this to web.config:

<httpCookies requireSSL=true/>

This will set the Secure flag on all the cookies.
Or if we want to set it at per cookie level, we can set the HttpCookie.Secure property to true.

Conclusion

So we saw what the secure flag is on a cookie and why we should always set it in our application for cookies carrying sensitive information. This flag does not make the cookie secure from all types of attacks, however, this adds another layer of protection to keep our cookies more secure.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right

Wednesday, August 26, 2015

Elements Tab in Chrome Developer Tools

When I see people struggling with Internet Explorer Debug tools, or making a small UI change in the application and re-running the whole solution through visual studio, I feel like it's high time I write a post on Chrome Developer tools. I was discussing the Chrome's power with a friend of mine and he suggested me to write a post on it. Chrome Developer tools are far ahead in features as compared to what's available with any other tool for convenient application development and debugging.

So let's hit the F12 key (or right click Inspect Element) and start rolling. In general, there are 8 tabs, I am going to focus on the Elements tab in this post.


Elements Tab

Editable DOM

The Elements tab shows nicely formatted HTML. We can easily navigate through the DOM structure and understand how the document is laid out. We can see information for any HTML element like the class, id, divs, head etc. You can edit anything like classes or text and see how the page looks. This is great if you are debugging or see how the page will look once its rendered. We don't have to go to Visual studio, change some small text and run the solution again to see how it looks. You have the editor right here in the browser.

You can even see the DOM element structure at the bottom. When we select an element, it's parents are shown to the left. We can select any parent from the bottom line and navigate through the HTML easily.

Search/ Ctrl+F

We can search for any element in the page. We can even use XPath and CSS selectors. I use CSS selectors pretty often. For example, I want to see how many elements use this class I will use ".myClass" in my search box. I think this is really cool.

CSS Styles

On the right hand side, we see the Styles window. We can play with the css right here and see the results immediately. Once we have a satisfactory look and feel, we can just copy the css and paste it into our solution. Doesn't it make our life easy.
The CSS window allows us to check/uncheck any property, search for the properties, add new properties and edit existing ones. One thing that I want to explicitly mention which is very helpful is when I edit the color property, I can use color picker and choose which color I want to use.

Toggle Element State

If we want to see how a specific element looks in different states like focused or active, we can test it by just using these checkboxes as shown in Fig. This is particularly helpful when we have multiple nested elements and we need to see how these elements state affect one another. Hovering a mouse on them activates hover on both the nested elements. But with these we can debug each individual item separately.



New Style Rule

Plus Sign adds css style to the specific class you are currently accessing. We can add css to the specific class and we can examine the results applied to the whole class simultaneously.



Computed Tab

The computed tab shows the final computed style rules that are rendered on screen. If we click on the arrow to the left of the style, it shows the source file and line number.  



DOM Breakpoints

This is yet another useful feature while debugging. If we want to see who is adding, removing or modifying elements to a specific DOM element, we can  put a breakpoint on the DOM element. As shown, we have three options:
i) Subtree Modification 
ii) Attributes Modification
iii) Node Removal



This will stop the application at any point where the specific action is invoked. This helps us in debugging issues related to any kind of dynamic DOM manipulation. 

Properties

This window lets us edit the properties of any HTML element on the fly.  I can edit the innerText property and see the results on the fly.


Event Listeners

This is one feature that I don't like much. This shows the events attached to a specific element. However, clicking on it doesn't always navigate us to the actual callback function. For example, if I used jquery to bind click event to a specific element, navigating to the click event shows me click event in jquery file which is of not much use to me. I think this will improve in future but for now this is helpful sometimes, not always.

Conclusion

This is the power of just the Elements tab of Chrome. I will explain other tabs in future posts. I hope it was useful and you got to learn something new out of this post.

For future updates to my weekly blog, please subscribe to the blog

Tuesday, August 25, 2015

How to create custom configuration in laravel

How to create custom configuration in laravel :-

All configuration files of Laravel framework stored in the app/config directory.
so if we need to create custom configuration values it would be better to keep separate our custom configuration in custom file.
so we need to create custom file in app/config directory. laravel auto read this file as a config file and will auto manage it
In this topic we are working with custom configuration in laravel and get configuration value in controller or view.

Create custom configuration in laravel :-

create a file in app/config/custom.php which have config keys and value like:-

return array(
  'my_val' => 'mysinglelue',
  'my_arr_val' => array('1', '2', '3'),
);
Now need to get these config values in view/controller so we will use Config class get() method for this
syntax :- echo Config::get('filename.arraykey');
where filename is the config file’s name, custom in our case, and key is the array key of the value you’re wanting to access.

echo Config::get('custom.my_val');
Create run time configuration in laravel :-
Configuration values which are set at run-time are will set for the current request, not be carried over to subsequent requests.

Config::set('custom.my_val', 'mysinglelue');
For more information about laravel configuration.

Create Layout in laravel using blade templating

How to create layout in laravel using blade templating (updated with laravel 5):-

We really need template in our any type of site like divide layout in footer, header, middle. called layout or templating. In laravel we are using blade template for making layout. We are using blade template to create a layout in laravel 5 except mess things controller, models etc. Using blade template we can save more html code writing and fast rendering of page it’s a another good feature of blade templating. so it’s easy to create layout in laravel using blade templating.

Blade Templating :-

blade is a simple and powerful templating engine which is inbuilt with laravel. blade templating didn’t use controller layouts, it’s driven by template inheritance and sections. we can create a blade template file using .blade.php extension.
For example :- for creating a “test” file using blade then file name will be “test.blade.php”
To create layout in laravel using blade templating we need to create some blade template files in views.
Views (laravel 4):-

File struture :-

- app
-- views
--- layout
------- default.blade.php
------- header.blade.php
------- footer.blade.php
------- sidebar.blade.php
--- pages
------- home.blade.php
------- about.blade.php
Views (laravel 5):-

File struture :-

- resources
-- views
--- layout
------- default.blade.php
------- header.blade.php
------- footer.blade.php
------- sidebar.blade.php
--- pages
------- home.blade.php
------- about.blade.php
Layout
laravel 4 :- create a new folder in app/views/layout
laravel 5 :- create a new folder in resources/views/layout
default.blade.php :- create a new file in
laravel 4 :- app/views/layout/default.blade.php
laravel 5 :- resources/views/layout/default.blade.php

<!doctype html>
<html>
<head>
<!-- my head section goes here -->
<!-- my css and js goes here -->
</head>
<body>
<div class="container">
  <header> @include('layout.header') </header>
  <div class="sidebar"> @include('layout.sidebar') </div>
  <div class="contents"> @yield('content') </div>
  <footer> @include('layout.footer') </footer>
</div>
</body>
</html>
header.blade.php :- create a new file in
laravel 4 :- app/views/layout/header.blade.php
laravel 5 :- resources/views/layout/header.blade.php

<ul>
  <li><a href="{{URL::to('/')}}">Home</a></li>
  <li><a href="{{URL::to('/about')}}">About</a></li>
</ul>
Note :- {{ $var }} has been deprecated in laravel 5 rather use {!! $var !!}
footer.blade.php :- create a new file in
laravel 4 :- app/views/layout/footer.blade.php
laravel 5 :- resources/views/layout/footer.blade.php

<div>My footer section here</div>
sidebar.blade.php :- create a new file in
laravel 4 :- app/views/layout/sidebar.blade.php
laravel 5 :- resources/views/layout/sidebar.blade.php

<div>My sidebar section here</div>
Pages
Pages :- create a new folder in
laravel 4 :- app/views/pages
laravel 5 :- resources/views/pages
home.blade.php :- create a new file in
laravel 4 :- app/views/pages/home.blade.php
laravel 5 :- resources/views/pages/home.blade.php

@extends('layout.default')
@section('content')
 this is my home page
@stop
about.blade.php :- create a new file in
laravel 4 :- app/views/pages/about.blade.php
laravel 5 :- resources/views/pages/about.blade.php

@extends('layout.default')
@section('content')
 this is my about page
@stop
Now we need to link these pages in laravel routing
Routing :-

Route::get('/', function()
{
 return View::make('pages.home'); // laravel 5 return View('pages.home');
});
Route::get('contact', function()
{
 return View::make('pages.about'); // laravel 5 return View('pages.about');
});
some of code means we are using:-
@yield :- is defining an area in the layout template where sections in views will be placed.It is a placeholder for @section … @stop
@section :- defines the content in the area defined by @yield
@include :- to render a view into another view. The rendered view will automatically inherit all of the data from the current view.
Note:- if you want to exclude any of layout from specific page try in “default.blade.php” like

//match your request route like 'account/login' etc.
@if(!Request::is('login'))
   // sidebar not included on login page.
    @include('layout.sidebar')
@endif
Now we have a simple front-end views for our site. you can add more files for your sidebar etc. Now you have done with Create Layout in laravel using blade templating.
you can learn more from Laravel Blade Templating.

Monday, August 24, 2015

Form validation post and retain form data laravel

Form validation post and retain form data laravel :-

There is a basic thing to make a form, form validation (validate a form), post form data, and retain posted form data (get form data on controller) and save in database.
Below we will see all steps for Form validation, post and retain form data in laravel :-

1. Create forms in laravel

2. From validation in laravel

3. Post form data in laravel

4. Retain post data in controller laravel

first we need to create a form using blade templating then we need to call controller method to submit data and add validation and make routes for both get and post data.
View : Creating forms :-
Create a login.blade.php under view/pages/login.blade.php

@extends('layout.default')
@section('content')
     <div class="text-content">
        <div class="span7 offset1">
          <h1></h1>
           <div class="secure">Secure Login form</div>
           {{ Form::open(array('url'=>'account/login','method'=>'POST')) }}
           <div class="control-group">
            <div class="controls">
              {{ Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email or Customer Reference')) }}
	      <p class="errors">{{$errors->first('email')}}</p>
            </div>
           </div>
           <div class="control-group">
             <div class="controls">
             {{ Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) }}
		<p class="errors">{{$errors->first('password')}}</p>
             </div>
	   </div>
           <div id="success"> </div>
           {{ Form::submit('Login', array('class'=>'send-btn')) }}
           {{ Form::close() }}
      </div>
@stop
Controller : Form validation, get post data:-
Create a AccountController.php under controller/AccountController.php

class AccountController extends BaseController {
	public function login()
	{
	      // Getting posted data.
              $data = Input::all();
              
              // Adding custom messages for validation
	      $messages = array(
			'email.required' => 'please enter email address',
			'password.required' => 'please enter password',
			);
              // apply validation rules to fields
	      $rules = array(
			'email' => 'required|email',
			'password' => 'required',
		       );
              // for default messages no need to pass $messages.
	      $validator = Validator::make($data, $rules, $messages);
	      if ($validator->fails()){
                // validation fails redirect back to page.
		return Redirect::to('/account/login')->withInput()->withErrors($validator);
	      }
	      else{
                // do your insertion stuff/ db stuff and then redirect.
		return Redirect::to('/account/login');
	      }
	}
}
Routes :- setting up routes
Add below code to app/routes.php

Route::get('account/login', function()
{
   return View::make('pages.login');
});
Route::post('account/login', 'AccountController@login');
For more information about validation rules follow Validation
Now we have all set form data submission in laravel, retrieve post data of form validation and routing in laravel.

How to create forms in laravel

How to create forms in laravel 5 using blade templating :-

Form is the basic need for any of web application to enter data then collect and insert. It’s easy to create forms in laravel using blade templating. We doesn’t need to write more code to creating forms in laravel. Laravel supports more handy methods to create form and form fields. laravel provide an excellent form class to make form creation easy. we need to just call form class methods to create forms. we are using blade templating to create forms in laravel 5. so let’s start how to create forms in laravel 5 using blade templating.

Create form in laravel 5 using blade templating :-

Methods, Form opening and close :-

Default method of a form will be POST. In laravel some extra form methods included are PUT and DELETE, HTML forms accepts POST or GET methods. If you use PUT or DELETE methods, A hidden field will be add on your laravel form.
PUT :- method when you want to Update a record,
DELETE :- method when you want to Delete a record.
Just simple add to your form method array to apply any method.

{!! Form::open(array('url'=>'form-submit', 'method'=>'POST', 'accept-charset'=>'UTF-8','files'=>true)) !!}
//form contents here
{!! Form::close() !!}
parameters :-
url:- url to submit a form
method :- GET/POST/PUT/DELETE
files :- if form contain file upload input

Form open routes :-

In laravel there are more way to give a form submit request routes these are named routes and controller actions.

{!! Form::open(array('route' => 'route.name')) !!}
{!! Form::open(array('action' => 'Controller@method')) !!}
Above we have form open and form routes of topic how to create forms in laravel 5. Now are going to explore how to create forms fields in laravel. so below we will see about most of form fields using blade template.
Labels :- To create a forms field label you need to just pass fields name and text for label.

{!! Form::label('username','Username',array('id'=>'','class'=>'')) !!}
Text Inputs :- To generate text input you need to pass name of field, also you can set a default value of input field.

{!! Form::text('nameoffield','default-value',array('id'=>'','class'=>'', 'placeholder' => '')) !!}
Textarea Inputs:- To generate form textarea you need to pass name of textarea field, also you can set a default value of textarea field.

{!! Form::textarea('message','default-value',array('id'=>'','class'=>'', 'placeholder' => '')) !!}
Password Inputs :- To generate password input field just use password method of laravel form class.

{!! Form::password('password',array('id'=>'','class'=>'', 'placeholder' => '')) !!}
Email Inputs :- To generate form email input field just use email method of laravel form class.

{!! Form::email('email','default-value',array('id'=>'','class'=>'', 'placeholder' => '')) !!}
File Inputs :- if you want to upload a file you need to use file form fields Note: The form must have been opened with the files option set to true.

{!! Form::open(array('url'=>'form-submit', 'files'=>true)) !!}
Then just pass your file input name.

{!! Form::file('image') !!}
Selectboxes :- For create select box element pass a name as a first argument then pass an array of options and third parameter will be default value.

{!! Form::select('status',array('enabled'=>'Enabled','disabled'=>'Disabled'),'enabled') !!}
Radio and checkbox also need to use handy methods for creation just pass name, value to set and third parameter will be which you want to default checked.
Radio Buttons :-

{!! Form::radio('status','enabled',true) !!} Enabled
{!! Form::radio('status','disabled') !!} Disabled
CheckBoxes

{!! Form::checkbox('status','1',true) !!} Enabled
Hidden Inputs

{!! Form::hidden('myhidden','1') !!}
Buttons :- you can generate all button easily by calling handy method of laravel forms class and pass name of buttons.

{!! Form::submit('Save', array('id' => '', 'class'=>'')) !!}  
{!! Form::reset('Reset', array('id' => '', 'class'=>'')) !!}
{!! Form::button('Normal') !!}
Now we can create a simple form in laravel using blade templating.
For more know about how to create forms in laravel 5 follow Forms & Html.

Sunday, August 23, 2015

How to install laravel on windows xampp

How to install laravel on windows xampp :-

Now time of frameworks in php like laravel, codeigniter etc and easy to install php frameworks on local server like xampp, wamp etc. Below we will see installation steps of a php framework laravel on windows xampp. Let’s see how to install laravel on windows xmapp. for this we need some server requirements, some of software installation.
Below are the steps of How to install laravel on windows xampp using composer:-
Server requirement:-
PHP >= 5.4
MCrypt PHP Extension
Installation steps :-
1. Laravel requires Composer to manage its dependencies. so first need to download composer.
A. After download composer, install composer on your system using below options:-
a. Shell menus:- Run composer from Windows Explorer by right clicking folder items.(optional)

b. next step require php.exe which is normally in xampp/htdocs/php folder. and continue with more instructions and click next to finish installation.
2. Installation process also requires Git to be installed on the server to successfully complete the installation.
If you not have GIT installed on your system:-
a. Download Git and install it.
3. Now download latest version of laravel and unzip into your local server.
For example you have put into your local server where the directory is D:\xampp\htdocs\laravel\.
Using Shell menus (works if you already selected shell menus option on installation of composer) :-
1. Right click on your laravel folder and click on Use Composer here.
2. will open CMD and enter command composer install and press enter key.
3. Now wait until process completed. it will take few time to download in your computer.
Using CMD with direct download :-
1. Open the CMD (start>serch for “cmd”> click on cmd.exe)in your computer and change the directory according to your laravel directory.(ex:- D:\xampp\htdocs\laravel>)
2. enter command composer install and press enter key.(ex:- D:\xampp\htdocs\laravel>composer install)
3. Now wait until process completed. it will take few time to download in your computer.
Using CMD create project command :-
1. Open the CMD (start>serch for “cmd”> click on cmd.exe)in your computer and run below command. “–prefer-dist” will be preferred location where you want to install laravel.
# install laravel using create project command
composer create-project laravel/laravel --prefer-dist
#composer create-project laravel/laravel d:\xampp\htdocs\laranew
2. Now wait until process completed. and you done.
After successfully installed you can access http://localhost/laravel/public/
Now you have finished installation steps of laravel using composer.

Saturday, August 22, 2015

Command Query Separation

Recently, I was reading about some basic encapsulation concepts and I came across command query separation. So this week I will be talking about what command query separation is and how it is useful.


Command Query Separation (CQS)

The term Command Query Separation was introduced by Bertrand Meyer in his book on object oriented design. The command query separation pattern is not only limited to object oriented design but can also be applied to functional programming or anywhere else.
According to CQS, any operations in the system should be either command or query but not both.

Command: Any operation that has observable side effect on the system. 
Query: Any operation that returns data and does not mutate observable state.

For example, in one of your class, you have

public void SaveName(int employeeId, string name)

This is saving Employee name into the system. Note the return type void. So this is changing the system state and returning nothing. So it's a command.


Another example, suppose you have

public string GetEmployeeName(int employeeId)

This should return the Employee name from the system and should not change the state of the system in any way. Note the return type is string (not void). So it should be query operation. The query operation should be idempotent i.e. no matter how many times you invoke a query, it should return the same response for a given system state.

Why Useful

This makes the code easier to read and helps us in separating the concerns. Imagine if you have some Get method which also changes the system state. The consumer of your code might get different response on calling the same GET operation. Such a system is non-intuitive and prone to errors and difficult to maintain. 

Similarly, if you have some Save method like this:

public string SaveName(int employeeId, string name)

The Save method here is returning a string as well as changing the state of the system. This is against the command query separation principle. Any operation can either return something or change the system state but not both.

By looking at the method signature, we don't know what the string return is. Whether the string returns the Employee name or error message or employeeId casted as string or something else. The consumer of the method will have to look into the method definition to find this out. Imagine if it's a complicated method. So now the consumer will have to either go through all of it or test it by passing different types of values or read through the whole documentation, if any. Any of these is not very favorable and makes us feel that the code sucks.

Having clear separation makes our code more readable, more intuitive and easy to follow. Furthermore, it helps in the maintainability of the code as well. When reading the system state, the consumer should be carefree that he/she is not changing the system state in any way.

Conclusion

CQS gives you a good foundation on which you can build good quality software.
As everything is life, the answer to when to use this principle is: "it depends". This is a generic principle to keep in mind when writing code. Nothing prevents you from disobeying the principle but if it can be followed, we should adhere to it.

However, we might have some exceptions where we can't follow the principle verbatim. For example, if you have an email system, where reading an email marks the email as Read. So here the Query operation could be changing the system state and marking the email as Read. So personally I would prefer to follow the principle when I can but I should be ready to break it when needed.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Friday, August 21, 2015

Open Closed Principle in .NET

In today's blog post, I will be discussing the second principle out of the 5 SOLID principles i.e. Open-Closed principle(OCP). 


Open Closed Principle

According to this principle, a class should be open for extension but closed for modification.
We all know that the only thing that is constant in this world, and more so in software, is change. The requirements change all the time and many times we keep adding new functionality on top of the existing ones. This principle guides us that instead of modifying existing classes, we can extend the existing classes to add new functionality. This makes our code easy to reuse and maintain.

Let's understand this with an example:

Suppose we have a class like this:

public class Product

{

        public decimal Price { get; set; }

        public DiscountType DiscountType { get; set; }

}

where DiscountType is an enum with 2 enumerators:

public enum DiscountType

{

    None = 0,

    Sale = 1

}

And suppose, you have a PriceCalculator class like this:

public class PriceCalculator

{

    public decimal GetTotalPrice(Product[] products)

    {

        decimal sum = 0;

        foreach (var product in products)

        {

            if (product.DiscountType == DiscountType.None)

                sum += product.Price;

            if (product.DiscountType == DiscountType.Sale)

                sum += product.Price*(decimal) 0.9;

        }

        return sum;

    }

}


Now the code works fine and return you the Total Price of the product. For all regular price items, you return the full price. For sale items you provide 10% discount.
Now, the client comes in and says I want to add another type of discount here, say super sale with 20% discount. We can cater to client requirements by adding another enumerator to the DiscountType enum and add another if condition in the PriceCalculator. Now, next time the client comes in and asks for mega Sale and so on. Looking at the price calculator method, you can imagine that this can get pretty ugly and difficult to maintain. So instead of adding to the enum and if conditions in GetTotalPrice(), we can close our PriceCalculator class for modification and extend the existing classes like this:

First, we will need to abstract out our Product class like this:

    public interface IProduct

    {

        decimal Price { get; set; }



        decimal TotalPrice();

    }

Then, we can add specific classes for Regular Product and Sale Product:

public class RegularProduct : IProduct

{

    public decimal Price { get; set; }

    public decimal TotalPrice()

    {

        return Price;

    }

}




 public class SaleProduct : IProduct

 {

      public decimal Price { get; set; }

      public decimal TotalPrice()

      {

          return Price*(decimal) 0.9;

      }

 }

Now, the PriceCalculator class will look like this:

public class PriceCalculator

{

        public decimal GetTotalPrice(IProduct[] products)

        {

         return products.Sum(product => product.TotalPrice());

        }

}

So, we don't need to change this GetTotalPrice() any more. We can keep adding any new product types as the requirements come up by implementing IProduct.

So for adding superSale item, we can simply add SuperSaleProduct which implements IProduct and our GetTotalPrice() will remain unchanged. And similarly, if the amount of discount needs to be changed for existing SaleProduct then also we don't need to change the existing GetTotalPrice().

Conclusion

So we saw how Open-Closed principle can help us write code that is easy to extend and maintain. 
The closure in changes for any class is mostly theoretical. This is a simplified example to illustrate what the principle is and how we can adhere to it. In real world, it might not be so simple or practical to use it all the time. But when we have such a scenario and we can simplify our code using this principle, we should follow it. 

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right.

Single Reponsibility Principle in .NET

Recently, I was reading about SOLID principles and how they can help us write better code. SOLID principles help make our code more supple so it can easily change with change in requirements. It helps us in writing our code more towards object oriented design rather than procedural code. It also helps make our code less rigid as well as less fragile and easy to reuse. I will be discussing all these principles one by one continuing in subsequent posts.

In today's blog post, I will be discussing one of the SOLID principles which can help in better design and implementation of the system, i.e. Single Responsibility Principle (SRP).


Single Responsibility Principle (SRP)

According to this principle, a class should have only one reason to change. If the class is doing too much then there might be multiple reasons for it's changes.
In other words, each class should do only one thing and do it well. It helps in separations of concerns. Let's look at an example to understand this:

For example you have a method like this:

public class Employee

{

      /*

        other properties and methods 

      */

      public ActionResult Details(int? id)

        {

            Log.Debug("Reading Employee " + employeeId);

            if (id == null)

            {

             return new 
             HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Employee employee = db.Employees.Find(id);

            if (employee == null)

            {

                Log.Debug("Employee not Found" + employeeId);

                return HttpNotFound();

            }

            Log.Debug("Returning Employee " + employeeId);

            return View(employee);

        }

      //....

}

By looking at this code, you can clearly see that this method is doing more than intended. For retrieving the employee, it's doing all the logging as well. If in future, we need to change logging mechanism, then we will have to revisit the code, as well as if we change the way employees are retrieved, then also we need to change this code. So there are multiple reasons for this class to change.

So, one way to solve this problem is to have a separate logger like this:


public class EmployeeLogger

    {

        public void Reading(int id)

        {

            Log.Debug("Retrieving Employee " + id);

        }

        public void Returning(int id)

        {

            Log.Debug("Returning Employee " + id);

        }

        public void NotFound(int id)

        {

            Log.Debug("No Employee found " + id);

        }

    }


Now, the Employee class might look like:


public class Employee

{

      private EmployeeLogger _logger = new EmployeeLogger(); 

      /*

        other properties and methods 

      */

public ActionResult Details(int? id)

        {

            _logger.Reading(employeeId);

            if (id == null)

            {

             return new 
             HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Employee employee = db.Employees.Find(id);

            if (employee == null)

            {

                _logger.NotFound(employeeId);

                return HttpNotFound();

            }

            _logger.Returning(employeeId);

            return View(employee);

        }

//... 

}

So now the logging responsibility belongs to EmployeeLogger class. If in future, we need to change the way employee logging is supposed to be done, we can change only the EmployeeLogger and don't need to make changes to the Employee Details method.
Currently, you might think that we have written a lot more code for a very small benefit. But, as the code base grows larger and the requirements change, you will see the benefit of it in the long run. Also, this provides us as a good base for better design and other SOLID principles to apply upon, as we will see in subsequent posts.

Conclusion

The SRP is one of the easiest to understand out of the SOLID principles but it's hard to get it right. Following the principle at each and every time might be an overkill but in general we should try to adhere to it as and when needed. The understanding of when to apply the principle and to what extent comes with experience and practice.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right.

Thursday, August 20, 2015

Liskov Substitution Principle in .NET

In today's blog post, I will be discussing Liskov Substitution principle i.e. "L" in SOLID.

Liskov Substitution Principle

According to LSP, the derived classes should be substitutable for their base classes without altering the correctness of the program. In other words, when implementing inheritance in your application, instead of "Is A" relationship, think in terms of "Is Substitutable For" relationship.
Let's look at the famous sqaure-rectangle example to better understand this:

Geometrically, a square is a rectangle. So this may lead us to derive square class from a rectangle class.

public class Rectangle
{
        public virtual int Height { get; set; }
        public virtual int Width { get; set; }

        public int GetArea()
        {
            return Height*Width;
        }
}


public class Square : Rectangle
{
        public override int Height
        {
            get { return base.Height; }
            set { base.Height = base.Width = value; }
        }

        public override int Width
        {
            get { return base.Width; }
            set { base.Height = base.Width = value; }
}


Imagine, we have a test method like this:

 public void TestRectangles()
{
            var r1 = new Rectangle()

            {

                Height = 2,

                Width = 3

            };

            var r2 = new Rectangle()

            {

                Width = 3,

                Height = 2

            };

            var isHeightEqual = r1.Height == r2.Height;

            var isWidthEqual = r1.Width == r2.Width;
}

 So isHeightEqual & isWidthEqual will be true.

However, if we substitute this test example with Square instead of rectangle, we will have:

public void TestRectangles()

{

            var r1 = new Square()

            {

                Height = 2,

                Width = 3

            };

            var r2 = new Square()

            {

                Width = 3,

                Height = 2

            };

            var isHeightEqual = r1.Height == r2.Height;

            var isWidthEqual = r1.Width == r2.Width;

}


So now isHeightEqual & isWidthEqual will be false. As a client, the correctness of my program has been compromised by substituting base class by derived class. So it is a violation of LSP.

One way that you might wanna structure this is by having a Quadrilateral base class and derive Square and Rectangle class from the Quadrilateral class.

public class Rectangle : Quadrilateral
{

        public int Height { get; set; }

        public int Width { get; set; }

        public int GetArea()

        {

            return Height*Width;

        }
}



public class Square : Quadrilateral
{

        public int Size { get; set; }

        public int Area()

        {

            return Size*Size;

        }
}


So a square and rectangle are substitutable for quadrilateral.

Another way might be to not use square class at all. Just use the rectangle class and set height and width equal manually and use it in your code.

Conclusion

This is a simple example to demonstrate the LSP. If our derived class is not perfectly substitutable for base type, then it means that we should start looking at the restructuring of our classes, if possible. Otherwise, it can lead to side effects and may lead to incorrect behavior in the system. Inheritance is a powerful tool in developer's arsenal but it should be used carefully. We should give thought to external behaviors of the entities we are using in inheritance and be able to substitute one for another.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right.