25 October 2014

MVC Model Binding Vulnerability

MVC Model Binding Vulnerability
Reference Link:
For example User Entity
public class User
{
    public string FirstName { get; set; }
    public bool IsAdmin { get; set; }
}
When you want to let a regular user change their first name, you give them the following form.
@using (Html.BeginForm()) {
   
     @Html.EditorFor(model => model.FirstName)
        
    
}
There is no input in the form to let a user set the IsAdmin flag, but this won't stop someone from crafting an HTTP request with IsAdmin in the query string or request body. Maybe they saw the "IsAdmin" name somewhere in a request displaying account details, or maybe they just got lucky and guessed the name.
composing the attack
If you use the MVC model binder with the above request and the previous model, then the model binder will happily move the IsAdmin value into the IsAdmin property of the model. Assuming you save the model values into a database, then any user can become an administrator by sending the right request. It's not enough to leave an IsAdmin input out of the edit form.
Fortunately, there are at least 6 different approaches you can use to remove the vulnerability. Some approaches are architectural, others just involve adding some metadata or using the right API.

Weakly Typed Approaches

The [Bind] attribute will let you specify the exact properties a model binder should include in binding (a whitelist).
[HttpPost]
public ViewResult Edit([Bind(Include = "FirstName")] User user)
{
    // ...
}
Alternatively, you could use a blacklist approach by setting the Exclude parameter on the attribute.
[HttpPost]
public ViewResult Edit([Bind(Exclude = "IsAdmin")] User user)
{
    // ...
}
If you prefer explicit binding with the UpdateModel and TryUpdateModel API, then these methods also support whitelist and blacklist parameters.
[HttpPost]
public ViewResult Edit()
{
    var user = new User();
    TryUpdateModel(user, includeProperties: new[] { "FirstName" });
    // ...
}

Strongly Typed Approaches

TryUpdateModel will take a generic type parameter.  You can use the generic type parameter and an interface definition to restrict the model binder to a subset of properties.
[HttpPost]
public ViewResult Edit()
{
    var user = new User();
    TryUpdateModel<IUserInputModel>(user);

    return View("detail", user);
}
This assumes your interface definition looks like the following.
public interface IUserInputModel
{
    string FirstName { get; set; }
}
Of course, the model will also have to implement the interface.
public class User : IUserInputModel
{
    public string FirstName { get; set; }
    public bool IsAdmin { get; set; }
}
There is also a [ReadOnly] attribute the model binder will respect. ReadOnly metadata might be want you want to use if you never want to bind the IsAdmin property. (Note: I remember ReadOnly not working in MVC 2 or MVC 1, but it is working in 3 & 4 (beta)).
public class User 
{
    public string FirstName { get; set; }

    [ReadOnly(true)]
    public bool IsAdmin { get; set; }
}

An Architectural Approach

Put user input into a model designed for user input only.
public class UserInputViewModel
{
    public string FirstName { get; set; }
}
In this approach you'll never bind against business objects or entities, and you'll only have properties available for the input you expect. Once the model is validated you can move values from the input model to the object you use in the next layer of software.
Based upon our convenience we can choose the approach.

12 October 2014

Revealing Module Pattern in Javascript

Revealing Module Pattern in Javascript


JavaScript Module pattern provides a way to wrap public, private methods (and variable) into a single entity and exposing only the public members to the world outside of module. This allows faster namespace resolution, avoid collision of the methods/variables with other global APIs since the namespace isn't populated with all many functions, and obviously provides cleaner code.

CalcModule = (function(){
            var mem = new Array(); //private variable

            var storeInMemory = function(val) {  //private function
                mem.push(val);
            };

            var add = function(a, b) {
                        var result = a + b;
                        storeInMemory(result); //call to private function
                        return result;
                    };

            var sub = function(a, b) {
                        var result = a - b;
                        storeInMemory(result); //call to private function
                        return result;
                    };

            var retrieveFromMemory = function() {
                        return mem.pop();
                    };

            return {
                add: add,
                sub: sub,
                popMemory: retrieveFromMemory
            };
})();

Instead we define all the functions public or not in the same way, and then in the return statement create a new object and add properties to it.

Advantages of Revealing Module pattern in Javascript
1. Consistent coding style inside the module for both private and public members.
2. Better control on the name of the public API, i.e., if it is required to change the name of add()         method to addition(), all we need to do is change the name in the return statement without effecting    the function name inside the module.
3.Control on what to make public, just adding/removing the properties in return statement is sufficient.
4.As always, cleaner code.

reference : http://viralpatel.net/blogs/javascript-module-pattern/

26 July 2014

Restrict MVC actions to be invoked only by GET or POST

Restrict MVC actions to be invoked only by GET or POST

We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.


[HttpGet]
public ViewResult DisplayCustomer(int id)
{
    Customer objCustomer = Customers[id];
    return View("DisplayCustomer",objCustomer);
}


Routing in MVC

Routing in MVC

Routing helps you to define a URL structure and map the URL with the controller.

The route mapping code is written in the “global.asax” file.

For Example

routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer",

id = UrlParameter.Optional }); // Parameter defaults

When a user types “http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invokes the DisplayCustomer action. This is defined by adding an entry in to the routes collection using the maproute function. Below is the underlined code which shows how the URL structure and mapping with controller and action is defined.

Note:
We can map multiple URL'S to the same action.
Add two entries with different key names and specify the same controller and action.





Difference between HTML.TextBox vs HTML.TextBoxFor

Difference between HTML.TextBox vs HTML.TextBoxFor

Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” is not strongly typed

Html.TextBox("Name")

Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘Name” from object “m”.


HTML helpers in MVC

HTML helpers in MVC

MVC includes standard helpers for the most common types of HTML elements.

HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state

For example 

@Html.ActionLink("About this Website", "About")

The Html.ActionLink() helper above, outputs the following HTML:

< a href="/Home/About" > About this Website< / a >

MVC 3 and MVC 4 New Features

MVC 3 and MVC 4 New Features

MVC 3 New Features

1.New View engine Razor is introduced.
2.Readymade Project templates
3.HTML 5 Enabled Templates
4.Support for multiple view engines, Javascript and Ajax

5.Model Validation Improvements

MVC 4 New Features
1.Asp.net Web Api [application programming interface] is introduced
2.Many new features to support mobile apps
3.Enhanced support for asynchronous methods

4.Refreshed and modernized default project templates New mobile project templates.



MVC ,MVVM and MVP in Dotnet

MVC ,MVVM and MVP in Dotnet

Model View Controller - [MVC] architecture is suitable for web application.
Model View View Model - [MVVM] -  suitable for WPF and Silverlight.
MVP -  [Model View Presenter] suitable for Window application.


1 June 2014

What is KnockoutJS

What is KnockoutJS

Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates. The underlying principles are therefore:

A clear separation between domain data, view components and data to be displayed the presence of a clearly defined layer of specialized code to manage the relationships between the view components.

The latter leverages the native event management features of the JavaScript language.

These features streamline and simplify the specification of complex relationships between view components, which in turn make the display more responsive and the user experience richer.

Knockout was developed and is maintained by Steve Sanderson, a Microsoft employee. The author stresses that this is a personal open-source project, and not a Microsoft product

Knockout includes the following features:

Automatic UI refresh (when the data model's state changes, the UI updates automatically)
Dependency tracking
Templating (using a native template engine although other templating engines can be used, such as jquery.tmpl)

Example:

http://learn.knockoutjs.com/#/?tutorial=intro

MVC Techniques with jQuery, JSON, Knockout, and C#

MVC Techniques with jQuery, JSON, Knockout, and C#








Enums in C#

Enums in C#

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.

For Detail Explanation

http://www.codeproject.com/Articles/18809/Enums-in-C


$( document ).ready() in Jquery

$( document ).ready() in Jquery

$( document ).ready(function() {
    console.log( "ready!" );
});


is equal to

// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
});


$( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM.



20 April 2014

SQL Server Max Datetime

SQL Server Max Datetime

9999-12-31 23:59:59.997


Return SQL Server Min DateTime

Return SQL Server Min DateTime

Example
select cast('1753-1-1' as datetime)

or

select cast(-53690 as datetime)


Symmetric Key vs Asymmetric Key Cryptography in SQL Server

Symmetric Key vs Asymmetric Key Cryptography in SQL Server

Symmetric Key – In Symmetric cryptography system, the sender and the receiver of a message share a single, common key that is used to encrypt and decrypt the message. This is relatively easy to implement, and both the sender and the receiver can encrypt or decrypt the messages.

Asymmetric Key – Asymmetric cryptography, also known as Public-key cryptography, is a system in which the sender and the receiver of a message have a pair of cryptographic keys – a public key and a private key – to encrypt and decrypt the message. This is a relatively complex system where the sender can use his key to encrypt the message but he cannot decrypt it. The receiver, on the other hand, can use his key to decrypt the message but he cannot encrypt it. This intricacy has turned it into a resource-intensive process.

Examples in the below link
http://blog.sqlauthority.com/2009/04/28/sql-server-introduction-to-sql-server-encryption-and-symmetric-key-encryption-tutorial-with-script/

MSDN
http://technet.microsoft.com/en-us/library/ms188357.aspx

http://technet.microsoft.com/en-us/library/ms174430.aspx


COALESCE Ignore Parameter if it is null in SQL Server Queries or Stored Procedure

COALESCE Ignore Parameter if it is null in SQL Server Queries or Stored Procedure

Example :
SELECT Employee, City, DateHired
FROM Employees
WHERE Employee = COALESCE(@Employee, Employee)

If @Employee is null, it displays all the Employee details and if it is not null, it filters and displays the record.


15 March 2014

IEnumerable VS IQueryable

IEnumerable VS IQueryable

IEnumerable
1.IEnumerable exists in System.Collections Namespace.
2.IEnumerable is best to query data from in-memory collections like List, Array etc.
3.While query data from database, IEnumerable execute select query on server side, load data in-memory    on client side and then filter data.
4.IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
5.IEnumerable supports deferred execution.
6.IEnumerable doesn’t supports custom query.
7.IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
8.Extension methods supports by IEnumerable takes functional objects.

StudentContext studcontext= new StudentContext();
IEnumerable objEmp = studcontext.Student.Where(a => a.StudName.StartsWith("A"));
objEmp = objEmp.Take(5); 

When you check the above execution using Sql Profiler, it looks like below

SELECT [t0].[StudID], [t0].[StudName], [t0].[StudentAddress] FROM [Student] AS [t0]
WHERE [t0].[StudName] LIKE @p0

In the above Query "top 5" is missing since IEnumerable filter the records on client side.

Accessing database using IEnumerable is not recommended.

IEnumerable is inherited by IQueryable

IQueryable
1.IQueryable exists in System.Linq Namespace.
2.IQueryable can move forward only over a collection, it can’t move backward and between the items.
3.IQueryable is best to query data from out-memory (like remote database, service) collections.
4.While query data from database, IQueryable execute select query on server side with all filters.
5.IQueryable is suitable for LINQ to SQL queries.
6.IQueryable supports deferred execution.
7.IQueryable supports custom query using CreateQuery and Execute methods.
8.IQueryable support lazy loading. Hence it is suitable for paging like scenarios.

StudentContext studcontext= new StudentContext();
IQueryable objEmp = studcontext.Student.Where(a => a.StudName.StartsWith("A"));
objEmp = objEmp.Take(5);

When you check the above execution using Sql Profiler, it looks like below

SELECT Top 5 [t0].[StudID], [t0].[StudName], [t0].[StudentAddress] FROM [Student] AS [t0]
WHERE [t0].[StudName] LIKE @p0

In the above query top 5 is exists and it filters the record in database itself.

Note:
1. Both IEnumerable and IQueryable can move forward only over a collection, it can’t move backward and    between the items.
2. While accessing database and Paging in Grid , IQueryable is recommended over IEnumerable.


2 February 2014

Alert Message in Window.Close in Jquery

Alert Message in Window.Close in  Jquery

window.onbeforeunload = function(){
    alert('You are closing the window');
}

Unload fires every time the current page is unloaded, that includes clicking on links, so you have to remove the event for them:
Code:
$(function () {
  $("btnSubmit").click(function {
    window.onbeforeunload = null;
  });
});


27 January 2014

Why Select is DML statement in SQL?

Why Select is DML statement in SQL?

DML - Data Manipulation Language

The purely read-only SELECT query statement is classed with the 'SQL-data' statements 

The SELECT ... INTO form is considered to be DML because it manipulates (i.e. modifies) data.

SELECT Column1, Column2
INTO DestinationTable

FROM SourceTable

Copy Coumn1,Column2 From SourceTable to DestinationTable.


So Select is dml statement

Other DML Statement are
Insert, Update and Delete


19 January 2014

Session Add, Remove, Clear, RemoveAll and Abandon in ASP.NET

Session Add, Remove,  Clear, RemoveAll  and Abandon in ASP.NET

1. Session Add

To add in the Session
For ex
Session.Add("UserID",1);
   or
Session["UserID"]=1;

UserID is Session ID
1 is Session value

2. Session Remove

Session.Remove(“UserID”);
It removes the specific session’s specific key value i.e) It removes the SessionID UserID


3. Session Clear

Session.Clear()
It clears all session value i.e) It clears all the key value pairs stored in the session state collection.

4. Session RemoveAll

Session.RemoveAll();
This Method calls above clear method in its implementation,
public sealed class HttpSessionState : ICollection, IEnumerable
{
   .....
   public void RemoveAll()
   {
       this.Clear();
   }
   .....
}

5. Session Abandon

Session.Abandon() destroy everything in the session. While logout you have to clear everything in session.




Handling Session in Common Class in ASP.NET WebForms or ASP.NET MVC

Handling Session in Common Class in ASP.NET WebForms or  ASP.NET MVC

SessionVariables.cs
using System;
using System.Web;
namespace WebApplication1
{
    public class SessionVariables
    {

        ///
        ///  Store EmpID in Session
        ///
        public static Int64 EmpID
        {
            get
            {
                return (Int64)HttpContext.Current.Session["EmpID"];
            }

            set
            {
                HttpContext.Current.Session["EmpID"] = value;
            }
        }
       
       
        ///
        /// Store EmpName in Session
        ///
        public static string EmpName
        {
            get
            {
                return (string)HttpContext.Current.Session["EmpName"];
            }

            set
            {
                HttpContext.Current.Session["EmpName"] = value;
            }
        }
     
    }

}

You can get or set the session variables in Webforms or MVC

using System;
using System.Web.UI;

namespace WebApplication1
{
    public partial class HandlingSession : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SessionVariables.EmpID = 1;

            SessionVariables.EmpName = "ArunPrakash";
        }
    }
}

Advantages:
1. Reduces duplicate Session variables declaration
2. Type conversion is in common functions.

ActionResult in MVC 4

ActionResult in MVC 4

The ActionResult class is the base class for action results.

An action method responds to user input by performing work and returning an action result. An action result represents a command that the framework will perform on behalf of the action method.

The following types derive from ActionResult:

ContentResult - Represents a user-defined content type that is the result of an action method.

EmptyResult - Represents a result that does nothing, such as a controller action method that returns nothing.

FileResult - Represents a base class that is used to send binary file content to the response.

HttpUnauthorizedResult - Represents the result of an unauthorized HTTP request.

JavaScriptResult - Sends JavaScript content to the response.

JsonResult - Represents a class that is used to send JSON-formatted content to the response.

RedirectResult - Controls the processing of application actions by redirecting to a specified URI.

RedirectToRouteResult - Represents a result that performs a redirection by using the specified route values dictionary.

ViewResultBase - The ViewResultBase class is the abstract base class for both the ViewResult and PartialViewResult classes. The class contains methods for finding the view to be rendered and for executing the result. This class also contains properties that identify the view to be rendered, the name of the view, view data, temporary data, and a collection for view engines for the application.

Reference
http://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult(v=vs.118).aspx

9 January 2014

Set the selected item in an ASP.NET dropdown via the display text

Set the selected item in an ASP.NET dropdown via the display text

Method 1:
ddlItemdetails.Items.FindByText("Shirts").Selected = true;

Method 2:

ddlItemdetails.SelectedValue = ddItems.Items.FindByText("Shirts").Value;


Consistency level in Azure cosmos db

 Consistency level in Azure cosmos db Azure Cosmos DB offers five well-defined consistency levels to provide developers with the flexibility...