Udemy

How to get First N digits of a number without Converting to String

Thursday, November 05, 2015 0 Comments A+ a-

Few days back i was asked by my senior colleague to make a method which takes two arguments as input, first the number and second the number of digits to be returned from the first argument number.

After sometime i was able to make logic of it, which was to get the number of digits of the input number and then i used that to get the number of digits using second parameter.


Here is the method:

        private static int takeNDigits(int number, int N)
        {
            int numberOfDigits = (int)Math.Floor(Math.Log10(number) + 1);

            if (numberOfDigits >= N)
                return (int)Math.Truncate((number / Math.Pow(10, numberOfDigits - N)));
            else
                return number;

        }


 and use it :

            int Result1 = takeNDigits(666, 4);
            int Result2 = takeNDigits(987654321, 5);
            int Result3 = takeNDigits(123456789, 7);
            int Result4 = takeNDigits(35445, 1);
            int Result5 = takeNDigits(666555, 6);

Output:


Result1 : 666
Result2 : 98765
Result3 : 1234567
Result4 : 3
Result5 : 666555
Udemy

Custom Validation Message Helper in asp.net mvc

Friday, October 23, 2015 0 Comments A+ a-

As i wrote earlier a post about Creating Custom Html Helpers in asp.net mvc which emphasized on how we can write custom html helper extensions in asp.net mvc according to the need, so that we can reuse them in the whole application, instead of writing plan html in View.

The example in that article was using ActionLink, today i am going to tell how we can implement custom Validation Message helper.I wanted to modify the validation message displaying in my application so that it displays * in front of required fields and the error message in tooltip of it like:





For that add a class in the project and add an extension method which will render our custom html that will be displayed for error message:

namespace CustomValidationMessageHelper.Helpers
{
    public static class Validator
    {
        public static MvcHtmlString MyValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
        {

            TagBuilder containerDivBuilder = new TagBuilder("div");
            containerDivBuilder.AddCssClass("tip_trigger");
            containerDivBuilder.InnerHtml = "*";


            TagBuilder midDivBuilder = new TagBuilder("div");
            midDivBuilder.AddCssClass("classic");
            midDivBuilder.AddCssClass("tip");
            midDivBuilder.InnerHtml = helper.ValidationMessageFor(expression).ToString();

            containerDivBuilder.InnerHtml += midDivBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(containerDivBuilder.ToString(TagRenderMode.Normal));
        }
    }

}

and then define following css in a css file in my case it is site.css or you can add it in the view:

.validated {
    border-color: #DCE4EC !important;
}

textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input {
    padding: 3px 3px;
    border: 1px solid #DCE4EC;
}


        
.tip {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 1px solid #808080;
    border-radius: 10px;
    box-shadow: 0 1px 10px rgba(32, 32, 32, 0.5);
    color: red;
    display: none;
    font-size: 12px;
    font-style: normal;
    margin-left: 10px;
    margin-top: -24px;
    padding: 4px;
    position: absolute;
    z-index: 999999;
}

.tip_trigger {
    width: 10px;
    float: right;
    color: red;
    margin-left: 3px;
}

Now we have to add client side code, which i have written in jquery in a js file or directly in view, in my case i have it in CustomValidation.js file:

$(document).ready(function () {
    //Tooltips
    var tip;
    $(".tip_trigger").hover(function () {
        console.log("hovered");
        tip = $(this).find('.tip');
        console.log($(this).find('.tip').find('span').html())
        if ($(this).find('.tip').find('span').html() != '') {
            $(this).find('.tip').show(); //Show tooltip
        }
    }, function () {
        $(this).find('.tip').hide(); //Hide tooltip 

    });

    ////Required fields
    $('input').each(function () {
        var req = $(this).attr('data-val-required');
        if (undefined != req) {
            $(this).css("border-color", "#DA9BA2")

        }
        if ($(this).val() != '') {

            $(this).addClass("validated");

        }

    });

    $('input').blur(function () {

        if ($(this).val() != '') {

            $(this).addClass("validated");
        }
        else {

            $(this).css("border-color", "#DA9BA2")
        }

    });


});


Now in the View add the reference to the related js and css files in the head section of View:

    <link href="@Url.Content("~/Content/site.css")" rel="stylesheet"/>
    <script src="@Url.Content("~/Scripts/jquery-1.9.1.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/CustomValidation.js")" type="text/javascript"></script>


Now in your view add using statement of the namespace and now you can access the Helper method in the View:

@model CustomValidationMessageHelper.ViewModels.SignUpViewModel
@using CustomValidationMessageHelper.Helpers
@{
    Layout = null;
}


@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control input-sm" })
@Html.MyValidationMessageFor(model => model.FirstName)

The sample project can be  downloaded from here
Udemy

Misconceptions regarding Pass By Value and Pass By Reference in C#

Monday, September 21, 2015 0 Comments A+ a-


Introduction:

It is a common question which is asked by interviewers in interviews that "What is Pass By Value and Pass By Reference" or "What is the difference between Pass By Value and Pass By Reference". Most of the beginner level developers and also many of intermediate level developers have misconception on it and they answer it wrong during interview.

When i didn't knew that real difference, i used to answer it like, when we pass primitive types they are passed by value but when we pass reference type, they are passed by reference which i was not aware that it is wrong.

So, today i decided to write on this topic so that readers reading my blog could be aware of the real difference and they can correct their misconception regarding it.

Pass By Value in Value Types:

In .Net Framework all objects are by default passed by value not passed by reference either it is a Value Type (so called Primitive types like int,char,double etc) or Reference Type (class,interface,delegate,string etc).

I will not go in to the details of Value Type and Reference Type definition and concept, you can read about them here.


Consider the following Examples:


First i will show a example using Value Type.

int num1 = 5;
int num2 = num1;
num2 = 10;

Console.WriteLine(num1);



So what will be printed on Console?

If your answer is 5,then you are right, because int is a value type, it is passed by value, which means for the above code num1 has 5 stored in it, when we create num2 and assign it num1 value of num1 is copied to num2 and after that if we change num2 it will not affect num1, ofcourse because we have copied value of num1 to num2, why num1 is to be change.

The same happens when we pass value types to methods. For Example:

We have created a method with sets the value of a int variable to 10.

private void ChangeValue(int i)
{
   i = 10;
}



Now we call it using our previous example:

int num1 = 5;

ChangeValue(num1);
           
Console.WriteLine(num1);



What would be the output on Console now?

Yes it will still output 5 as i already said that value is copied, so when ChangeValue method is called, num1 variable value is copied to so changing i does not changes num1.

Diagrammatic/Pictorial Representation of Pass By Value in Value Types: 

 

Here is diagrammatic representation of Pass By Value.




Pass By Value in Reference Types:

 I have following class of User which is a reference type as classes are reference types :

public class User
{
    public int UserID {get;set;}
    public string Name {get;set;}
}



we create an instance and set its properties then we assign it to another instance and change Name property and then we print Name on Console to check what is printed:

User objUser = new User() 
{ 
     UserID = 1, 
     Name = "Ehsan Sajjad" 
};

User objUser2 = objUser;
objUser2.Name = "Jon Doe";



When we create Instance of class User, an object is create in memory(Heap) and memory is allocated to it and we are storing reference to that memory location in objUser reference memory (mostly Stack) so that we can use it further, otherwise it will get lost in the memory so we need to keep a reference to it for doing different operation in memory.

When we assign objUser to objUser2 reference of object memory location which objUser is holding copied to objUser2 , now we have two seperate copies of reference but they are both are pointing to same memory location which means they both are referencing to same memory location,so changing the value  of Name property will change the value in the object in memory of which we have  reference in objUser and objUser, hence "Jon Doe" will be printed on console and it will be reflected in both references.

Diagrammatic/Pictorial Representation of Pass By Value in Reference Types:




We can see the same behavior using a method,see the following method to change Name property of User object:

public static void ChangeName(User user)
{
    user.Name = "Jon Doe";
}


We call it to change the object state, it will give the same behavior what we saw in assignment case:

User objUser = new User() { UserID = 1, Name = "Ehsan Sajjad" };

ChangeName(objUser);

Console.WriteLine(objUser.Name);



When we are passing reference objUser of User object to method ChangeName, reference of memory location is copied to the local object user of method but they are both are pointing to same memory location which means they both are having reference to same memory location,so changing the value the value of Name property will change the value in the object in memory of which we have  reference in objUser and user, hence "Jon Doe" will be printed on console.


Here is diagramatic representation of it:





When the ChangeName(objUser) is called, as it is referring to same memory location, it will modify the Name property of User object to "Jon Doe".





But think about what would happen if i set the user to null inside ChangeName method like:

public static void ChangeName(User user)
{
    user = null;
}


and now we call it for objUser :

User objUser = new User() 
{ 
     UserID = 1, 
     Name = "Ehsan Sajjad" 
};

ChangeName(objUser);
Console.WriteLine(objUser.Name);


If you are thinking that it will throw Null Reference Exception, then you are wrong, and if you are thinking that it will output Ehsan Sajjad, then you are right and you have understood that reference are passed by value in C# not by reference.

See the pictorial representation to understand better:

 

 

Pass By Reference:

If we want to make objUser null, we will have to pass it to the method via reference which is done in C# using ref Keyword. We will use the above examples again but this time we will pass them by reference and will see what happens so that we can inderstand the difference between these two.

Pass By Reference in Value Types:

We will use the same above example but this time we will be passing by reference. For that first of all we have to change the method signatures of method ChangeValue(int i) to ChangeValue(ref int i), we have added ref keyword with the input parameter which means that when calling this method the argument should be passed by reference to it:
private void ChangeValue(ref int i)
{
   i = 10;
}

 Now we will use the same code as above but we have to use ref keyword at calling side for the parameters that method expect to be passed by reference otherwise you will get compile time error, and your code will not build:

int num1 = 5;

ChangeValue(ref num1);
           
Console.WriteLine(num1);
This will output 10 on the screen, because we are using ref keyword, in the above code when ChangeValue is called the incoming parameter of it has the same memory address of num1 which is passed as argument that's why now modifying the value of i would reflect the change in num1 as well, in pass by reference new memory location is not used for the method parameter so changing the value of it will reflect the variable that is passed from calling side.

Pass By Reference in Reference Types:

We will now check the same thing with reference types, and the behaviour would be same for reference types case as well,first modify the signature of method so that it takes parameter as reference:
public static void ChangeName(ref User user)
{
    user = null;
}


and we will call it simply this way:

User objUser = new User() 
{ 
     UserID = 1, 
     Name = "Ehsan Sajjad" 
};

ChangeName(objUser);
Console.WriteLine(objUser.Name);



Now when we will call it on objUser setting user to null inside ChangeName will also make objUser null because instead of passing the reference by value (in that a new reference memory location is create which points the same object) it is passed by reference, so in this case new copy of reference is not created but the reference of objUser is passed to method which results setting the calling side reference to also change the memory location where it is pointing.
Udemy

How to Convert DataTable to List in C#

Monday, September 14, 2015 0 Comments A+ a-

When writing Data Access Layer, when we get data from the database using ADO.net, most of the times we use DataTable or DataSet to hold the data in memory, then we have to map the DataTable  to List of Model type.


One way is to iterate on the rows of DataTable and create objects of Model and add to List one. Let me show you with example.


I have table in database which has information about Doctors, my table name is Doctor which contains different columns which are for capturing information of Doctor.


I have following Model class on front end which represents Doctor :

public class Doctor
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string ImagePath { get; set; }
    public string Type { get; set; }
}



When we will get Doctors from database in datatable we can create a list of Doctors with following approach in our Data Access:

List<doctor> doctors = new List<doctor>();
for (int i = 0; i < dtDoctors.Rows.Count; i++)
{

    Doctor objDoctor = new Doctor();

    objDoctor.ID = dtDoctors.Rows[i]["DoctorID"].ToString();
    objDoctor.Name = dtDoctors.Rows[i]["Name"].ToString();
    objDoctor.ImagePath = dtDoctors.Rows[i]["Image"].ToString();
    objDoctor.Type = dtDoctors.Rows[i]["Type"].ToString();

    doctorList.Add(objDoctor);
}

It will surely do the job for you, but think that you have many tables in your database and whenever you will fetch data you will have to do a loop the way i showed above and will have to map properties from datatable, which does not look cool as we are rewriting same thing again and again which is against DRY principle.


We can achieve what we have did above using generics,relection and extension methods feature provided by .Net Framework.We can add the following  extension method in our project and just call it to convert DataTable to List of Type which we want to.

Following is the extension method for it:

public static class ExtensionMethods
{
    public static List<T> ToList<T>(this DataTable dt)
    {
        List<T> data = new List<T>();
        foreach (DataRow row in dt.Rows)
        {
            T item = GetItem<T>(row);
            data.Add(item);
        }
        return data;
    }

    private static T GetItem<T>(DataRow dr)
    {
        Type temp = typeof(T);
        T obj = Activator.CreateInstance<T>();

        foreach (DataColumn column in dr.Table.Columns)
        {
            foreach (PropertyInfo pro in temp.GetProperties())
            {
                if (pro.Name == column.ColumnName && dr[column.ColumnName] != DBNull.Value)
                    pro.SetValue(obj, dr[column.ColumnName], null);
                else
                    continue;
            }
        }
        return obj;
    }
}

Now we can call it on instance of DataTable and can specify that convert it to which type of List.

For Example:

List<Doctor> doctors = dtDoctors.ToList<Doctor>();


Now that looks cool, we have just written two extension method for DataTable and now we can reuse it anywhere which enables us to reduce code redundancy.


One thing to consider is that the column names you are returning from your sql query or Stored Procedure should be same as of the properties in the Model class and the datatype should also be matched so that i can be converted.
Udemy

Implementing Repository pattern and Dependency Injection in ADO.net using Generics in C#

Friday, September 04, 2015 1 Comments A+ a-

Nowadays i am trying to learn different design patterns in object oriented paradigm that are pretty useful to implement generic solutions for different scenarios, few weeks back for a job hunt i got an assignment to do which was a web application which would interact with database, so i took it as a challenge and decided to make it loosely coupled using design patterns which were applicable in that scenario.

One of them which implemented in my assignment is repository pattern using generics and with that Dependency Injection using which i injected dependencies of Repository class via constructor.
 


I made generic class which would be inherited by other types against the different tables in the application. in this class i have used different framework features like Reflection and Generics.


My generic class is an abstract class, so it needs to be inherited for making use of it, you will see next how we will use it.


Here is the Repository class:

public abstract class Repository<TEntity> where TEntity : new()
{
    DbContext _context;

    public Repository(DbContext context)
    {
        _context = context;
    }

    protected DbContext Context 
    { 
        get
        {
          return this._context;
        } 
    }

    protected IEnumerable<TEntity> ToList(IDbCommand command)
    {
        using (var record = command.ExecuteReader())
        {
            List<TEntity> items = new List<TEntity>();
            while (record.Read())
            {
                    
                items.Add(Map<TEntity>(record));
            }
            return items;
        }
    }

        
    protected TEntity Map<TEntity>(IDataRecord record)
    {
        var objT = Activator.CreateInstance<TEntity>();
        foreach (var property in typeof(TEntity).GetProperties())
        {
            if (record.HasColumn(property.Name) && !record.IsDBNull(record.GetOrdinal(property.Name)))
                property.SetValue(objT, record[property.Name]);


        }
        return objT;
    }


}

Now i have table in database User whose schema is :

CREATE TABLE [dbo].[tblUser] (
    [UserID]    INT           IDENTITY (1, 1) NOT NULL,
    [FirstName] NVARCHAR (25) NULL,
    [LastName]  NVARCHAR (25) NULL,
    [UserName]  NVARCHAR (25) NULL,
    [Password]  NVARCHAR (25) NULL,
    [IsActive]  BIT           NULL,
    [IsDeleted] BIT           NULL,
    [CreatedBy] INT           NULL,
    [CreatedAt] DATETIME      NULL,
    [UpdatedBy] INT           NULL,
    [UpdatedAt] DATETIME      NULL,
    [Email]     NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([UserID] ASC)
);



Against this table i have Model class for mapping from table to that type which looks :

public class User
{
    public int UserID { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }

    public bool IsActive { get; set; }

    public bool IsDeleted { get; set; }

    public DateTime CreatedAt { get; set; }

    public int CreatedBy { get; set; }

    public DateTime UpdatedAt { get; set; }

    public int UpdatedBy { get; set; }

    public string Email { get; set; }
}

We want to fetch data from User table for which we will create a Repository class for User type and the we will write implementation to fetch records from User table from database. Our all methods that need to get data, insert data,update data or delete data from User table will reside in the UserRepository class.

Here is the implementation of User Repository class:

public class UserRepository : Repository<User>
{
    private DbContext _context;
    public UserRepository(DbContext context)
        : base(context)
    {
        _context = context;
    }


    public IList<User> GetUsers()
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandText = "exec [dbo].[uspGetUsers]";

            return this.ToList(command).ToList();
        }
    }

    public User CreateUser(User user)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspSignUp";

            command.Parameters.Add(command.CreateParameter("@pFirstName", user.FirstName));
            command.Parameters.Add(command.CreateParameter("@pLastName", user.LastName));
            command.Parameters.Add(command.CreateParameter("@pUserName", user.UserName));
            command.Parameters.Add(command.CreateParameter("@pPassword", user.Password));
            command.Parameters.Add(command.CreateParameter("@pEmail", user.Email));

            return this.ToList(command).FirstOrDefault();


        }

    }


    public User LoginUser(string id, string password)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspSignIn";

            command.Parameters.Add(command.CreateParameter("@pId", id));
            command.Parameters.Add(command.CreateParameter("@pPassword", password));

            return this.ToList(command).FirstOrDefault();
        }
    }


    public User GetUserByUsernameOrEmail(string username, string email)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspGetUserByUsernameOrEmail";

            command.Parameters.Add(command.CreateParameter("@pUsername", username));
            command.Parameters.Add(command.CreateParameter("@pEmail", email));

            return this.ToList(command).FirstOrDefault();
        }
    }


}


We are done for the UserRepository for new, i have added methods are wrote Stored Procedure to complete the assignment and now i will tell how to make use of it in the Service Layer or in Business Rule to do operations.




First create an interface namely IUserService:

[ServiceContract]
public interface IUserService
{

    [OperationContract]
    IList<User> GetUsers();

    [OperationContract]
    User RegisterUser(User user);

    [OperationContract]
    User Login(string id, string password);

    [OperationContract]
    bool UserNameExists(string username, string email);


}


Here is my WCF Service for User that calls the UserRepository for doing operations:

public class UserService : IUserService
{
    private IConnectionFactory connectionFactory;

    public IList<User> GetUsers()
    {
        connectionFactory = ConnectionHelper.GetConnection();

        var context = new DbContext(connectionFactory);

        var userRep = new UserRepository(context);

        return userRep.GetUsers();
    }

    public User RegisterUser(User user)
    {
        connectionFactory = ConnectionHelper.GetConnection();

        var context = new DbContext(connectionFactory);

        var userRep = new UserRepository(context);

        return userRep.CreateUser(user);
    }


    public User Login(string id, string password)
    {
        connectionFactory = ConnectionHelper.GetConnection();

        var context = new DbContext(connectionFactory);

        var userRep = new UserRepository(context);

        return userRep.LoginUser(id, password);
    }

    public bool UserNameExists(string username, string email)
    {
        connectionFactory = ConnectionHelper.GetConnection();

        var context = new DbContext(connectionFactory);

        var userRep = new UserRepository(context);

        var user = userRep.GetUserByUsernameOrEmail(username, email);
        return !(user != null && user.UserID > 0);

    }
}

You can see that when creating instance of UserRepository i am injecting database context via constructor and then i am calling different methods from userReposiory according to need.

Now in future when i add another table in database, i would create another Repository type and implement its Data Access logic and will call it same way, so applying Dependency Injection and Repository pattern we are following DRY principle to some extent, but i am sure we can make it more better than this.
Udemy

Check If username/email already registered using Remote Validation attribute in asp.net mvc

Tuesday, September 01, 2015 0 Comments A+ a-

When we create Registration form on a web application, we have to check that the email address and username that user is entering is unique and is not already. In asp.net mvc we have Validation Attribute feature in under System.ComponentModel.DataAnnotations and System.Web.Mvc which we can use for different type of Validations before sending data to be saved in persistent location.

In System.Web.Mvc we have Remote attribute which is available in asp.net mvc 4 in which i am implementing it for  this post, i am not sure if it is available in the earlier version of asp.net mvc.


So i have this ViewModel:

    public class SignUpViewModel
    {
        
        public int UserID { get; set; }

        [Required(ErrorMessage = "First Name is required")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last Name is Required")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Username is Required")]
        [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "user name must be combination of letters and numbers only.")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Password is Required")]
        public string Password { get; set; }

        [Required(ErrorMessage = "Password is Required")]
        [System.Web.Mvc.Compare("Password",ErrorMessage="Both Password fields must match.")]
        public string ConfirmPassword { get; set; }

        [Required(ErrorMessage = "Email Address is required")]
        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        public string Email { get; set; }
    }

As you can see there are laready attributes on the properties of ViewModel like Required which are mandatory fields, RegularExpression attribute for Email Address format validation and Compare attribute for comparing two properties values which is useful here for Password and Repeat Password textbox for making sure that user has verified what password he is setting.

Now what will happen if user enters a username or Email Address which is already registered, one way is to check in post action for username and Email Address  and show user error message that username or Email Address is already taken which does not looks though, as validation should be done before posting data to action using unobtrusive validtion.

Now here we will use Remote attribute which will check for both UserName and Email Address field, here is how it will be done:

 [Required(ErrorMessage = "Username is Required")]
 [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "user name must be combination of letters and numbers only.")]
 [Remote("UsernameExists","Account",HttpMethod="POST",ErrorMessage="User name already registered.")]
 public string UserName { get; set; }


[Required(ErrorMessage = "Email Address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
[Remote("EmailExists", "Account", HttpMethod = "POST", ErrorMessage = "Email address already registered.")]
 public string Email { get; set; }

Remote Attribute has different parameters to be specified:

  1. Action Name which will be called which will have input parameter for this property value
  2. Controller Name of which action will be executed
  3. HttpMethod (Get or Post)
  4. ErrorMessage (Error Message that will be displayed if validation fails)  
Let's come to the action part we need to write action method in the Account controller for Validation, for this post just for clearing to readers i am just checking for specific username and email (my name and dummy email address), but in your project you will need to check in your database for that particular criteria and return true or false respectively.


Here is the action code:

public JsonResult UsernameExists(string username)
{    
     return Json(!String.Equals(username,"ehsansajjad",StringComparison.OrdinalIgnoreCase));
}

public JsonResult EmailExists(string email)
{
     return Json(!String.Equals(email, "ehsansajjad@yahoo.com", StringComparison.OrdinalIgnoreCase));
}

Here is the complete View code:

@model CustomValidationMessageHelper.ViewModels.SignUpViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>SignUp</title>
    <link href="@Url.Content("~/Content/jquery.qtip.css")" rel="stylesheet" />

    <script src="@Url.Content("~/Scripts/jquery-1.9.1.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.qtip.min.js")" type="text/javascript"></script>

</head>
<body>
    <div>
        @using (Html.BeginForm("SignUp", "Account", FormMethod.Post, new { @class = "form-inline", role = "form" }))
        {
          @Html.AntiForgeryToken()
    
    <div class="row">
        <div class="span8 offset5 aui-page-panel">

            <div>
                    <h2>Sign Up</h2>
                </div>
            <fieldset style="margin-bottom: 40px;">
                

                                <legend style="border-bottom: 1px solid gray; font-size: 16px;">Basic Information</legend>

                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr id="tr_basic">
                        <td style="vertical-align: top;" width>
                            <div id="basicinfo" style="width: 100%">
                                <div style="height: auto !important; overflow-y: visible;">
                                    <table cellpadding="3">

                                        <tbody>
                                            <tr>
                                                <td width="150">
                                                    @Html.LabelFor(model => model.FirstName, new { @class = "sr-only" })
                                                </td>
                                                <td>
                                                    @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control input-sm" })
                                                    @Html.ValidationMessageFor(model => model.FirstName)
                                                </td>

                                            </tr>
                                            <tr>
                                                <td>
                                                    @Html.LabelFor(model => model.LastName)
                                                </td>
                                                <td>
                                                    @Html.TextBoxFor(model => model.LastName, new { @class = "input-xsmall" })
                                                    @Html.ValidationMessageFor(model => model.LastName)
                                                </td>
                                            </tr>

                                            
                                            <tr>
                                            </tr>

                                        </tbody>
                                    </table>

                                </div>
                        </td>
                    </tr>

                </table>


                <legend style="border-bottom: 1px solid gray; font-size: 16px;">Account Information</legend>
                <table cellpadding="5">
                    <tr>
                        <td width="150">
                            @Html.LabelFor(model => model.UserName)
                        </td>
                        <td>
                            @Html.TextBoxFor(model => model.UserName)
                            @Html.ValidationMessageFor(model => model.UserName)
                        </td>
                        <td id="tdValidate">
                            <img id="imgValidating" src="@Url.Content("~/Images/validating.gif")" style="display:none;" /></td>

                    </tr>
                    <tr>
                        <td>
                            @Html.LabelFor(model => model.Password)
                        </td>
                        <td>
                            @Html.PasswordFor(model => model.Password)
                            @Html.ValidationMessageFor(model => model.Password)


                        </td>

                    </tr>


                    <tr>
                        <td>
                            @Html.LabelFor(m => m.ConfirmPassword, new { @class = "control-label" })
                        </td>

                        <td>
                            @Html.PasswordFor(model => model.ConfirmPassword)
                            @Html.ValidationMessageFor(model => model.ConfirmPassword)

                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.LabelFor(m => m.Email, new { @class = "control-label" })
                        </td>

                        <td>
                            @Html.TextBoxFor(model => model.Email)
                            @Html.ValidationMessageFor(model => model.Email)


                        </td>

                    </tr>
                    <tr>
                    <td>
                        <p>
                            <div class="control-group">
                                <div class="controls">
                                    <input id="btnRegister" type="submit" class="btn btn-primary" value="Register" />
                                </div>
                            </div>

                        </p>
                    </td>
                    <td></td>
                </tr>
                </table>
    </div>
     </div>
            }
            </div>
        
</body>
</html>

Now when i will enter username "ehsansajjad" or Email Address "ehsansajjad@yahoo.com" validation will get fired that user already exists :





You can download the sample project from here.

Udemy

Mapping ViewModel to Model in asp.net mvc using implicit operator in C#

Thursday, August 27, 2015 0 Comments A+ a-


Background:

In asp.net mvc we have three important things in which we are moving all the time which is Model, View and Controller. Sometimes we want specific information of model to be passed from View to action, but if we use the Model classes that are mapped to our database tables make things messy, as all the model is round tripping from View to action or vice versa.


Consider the following model class which is mapped to the user table in my database.

namespace JIRA.Domain.Models
{
    public class User
    {
        public int UserID { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public bool IsActive { get; set; }

        public bool IsDeleted { get; set; }

        public DateTime CreatedAt { get; set; }

        public int CreatedBy { get; set; }

        public DateTime UpdatedAt { get; set; }

        public int UpdatedBy { get; set; }

        public string Email { get; set; }
    }
}

Here is my database table :

CREATE TABLE [dbo].[tblUser] (
    [UserID]    INT           IDENTITY (1, 1) NOT NULL,
    [FirstName] NVARCHAR (25) NULL,
    [LastName]  NVARCHAR (25) NULL,
    [UserName]  NVARCHAR (25) NULL,
    [Password]  NVARCHAR (25) NULL,
    [IsActive]  BIT           NULL,
    [IsDeleted] BIT           NULL,
    [CreatedBy] INT           NULL,
    [CreatedAt] DATETIME      NULL,
    [UpdatedBy] INT           NULL,
    [UpdatedAt] DATETIME      NULL,
    [Email]     NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([UserID] ASC)
);


So what happens normally is developers strongly type their view with the model class that is mapped with the table in our db which is not a good approach, as our View don't needs all information of the table every time.

Scenario:

Now consider the scenario of Register/SignUp of user in which we have different fields form which some will map to the User class but as User is registering so some properties of Model are useless here which will be posted when user submits form and there are some properties that we may need additional but they are not mapped in the table, you can take example when user registers we take Password from user two times for Confirming, in that case we don't want to change our Model that represents our Entity in the database, so ViewModel comes in.

ViewModels and Models:

ViewModels are specific to the Views, we put information in View Model that we need on the particular View.Here is the snippet that  is not a preferred way,So now we will create a ViewModel for Register View which will have properties specific to that View that it needs to post and we will map the ViewModel properties to Entity Model that represents our table and will insert it in the database.

Example:

Following is the ViewModel for the current use case that i explained above:

namespace JIRA.ViewModels
{
    public class RegisterViewModel
    {
        public int UserID { get; set; }

        [Required(ErrorMessage = "First Name is required")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last Name is Required")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Username is Required")]
        [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "user name must be combination of letters and numbers only.")]
        [Remote("UsernameExists","Account",HttpMethod="POST",ErrorMessage="User name already registered.")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Password is Required")]
        public string Password { get; set; }

        [Required(ErrorMessage = "Password is Required")]
        [System.Web.Mvc.Compare("Password",ErrorMessage="Both Password fields must match.")]
        public string ConfirmPassword { get; set; }

        [Required(ErrorMessage = "Email Address is required")]
        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        [Remote("EmailExists", "Account", HttpMethod = "POST", ErrorMessage = "Email address already registered.")]
        public string Email { get; set; }

    }
}




Now we will strongly type our View with the RegisterViewModel type which only contains properties that are related with the Register View:

@model JIRA.ViewModels.RegisterViewModel

using (Html.BeginForm("SignUp", "Account", FormMethod.Post, new { @class = "form-inline", role = "form" }))
        {
    @Html.AntiForgeryToken()
    
    <div class="row">
        <div class="span8 offset5 aui-page-panel">

            <div>
                    <h2>Sign Up</h2>
                </div>
            <fieldset style="margin-bottom: 40px;">
                

                                <legend style="border-bottom: 1px solid gray; font-size: 16px;">Basic Information</legend>

                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr id="tr_basic">
                        <td style="vertical-align: top;" width>
                            <div id="basicinfo" style="width: 100%">
                                <div style="height: auto !important; overflow-y: visible;">
                                    <table cellpadding="3">

                                        <tbody>
                                            <tr>
                                                <td width="150">
                                                    @Html.LabelFor(model => model.FirstName, new { @class = "sr-only" })
                                                </td>
                                                <td>
                                                    @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control input-sm" })
                                                    @Html.MyValidationMessageFor(model => model.FirstName)
                                                </td>

                                            </tr>
                                            <tr>
                                                <td>
                                                    @Html.LabelFor(model => model.LastName)
                                                </td>
                                                <td>
                                                    @Html.TextBoxFor(model => model.LastName, new { @class = "input-xsmall" })
                                                    @Html.MyValidationMessageFor(model => model.LastName)
                                                </td>
                                            </tr>
                                            @*<tr>
                                                <td>
                                                    @Html.LabelFor(model => model.Email)
                                                </td>
                                                <td>
                                                    @Html.TextBoxFor(model => model.Email, new { @class = "required" })
                                                    @Html.MyValidationMessageFor(model => model.Email)
                                                </td>
                                            </tr>*@
                                            
                                            <tr>
                                            </tr>

                                        </tbody>
                                    </table>

                                </div>
                        </td>
                    </tr>

                </table>


                <legend style="border-bottom: 1px solid gray; font-size: 16px;">Account Information</legend>
                <table cellpadding="5">
                    <tr>
                        <td width="150">
                            @Html.LabelFor(model => model.UserName)
                        </td>
                        <td>
                            @Html.TextBoxFor(model => model.UserName)
                            @Html.MyValidationMessageFor(model => model.UserName)
                        </td>
                        <td id="tdValidate">
                            <img id="imgValidating" src="@Url.Content("~/Images/validating.gif")" style="display:none;" /></td>

                    </tr>
                    <tr>
                        <td>
                            @Html.LabelFor(model => model.Password)
                        </td>
                        <td>
                            @Html.PasswordFor(model => model.Password)
                            @Html.MyValidationMessageFor(model => model.Password)


                        </td>

                    </tr>


                    <tr>
                        <td>
                            @Html.LabelFor(m => m.ConfirmPassword, new { @class = "control-label" })
                        </td>

                        <td>
                            @Html.PasswordFor(model => model.ConfirmPassword)
                            @Html.MyValidationMessageFor(model => model.ConfirmPassword)

                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.LabelFor(m => m.Email, new { @class = "control-label" })
                        </td>

                        <td>
                            @Html.TextBoxFor(model => model.Email)
                            @Html.MyValidationMessageFor(model => model.Email)


                        </td>

                    </tr>
                    <tr>
                    <td>
                        <p>
                            <div class="control-group">
                                <div class="controls">
                                    <input id="btnRegister" type="submit" class="btn btn-primary" value="Register" />
                                </div>
                            </div>

                        </p>
                    </td>
                    <td></td>
                </tr>
                </table>





            </fieldset>
        </div>
    </div>

        }
    }

and our action would look like:

  [HttpPost]
  [AllowAnonymous]
  public ActionResult SignUp(RegisterViewModel registerVM)
  {
      if (ModelState.IsValid)
      {
          // save to database
      }
    return View(registerVM);
  }



Our service method takes object of type User as input which is our Domain or Entity Model so we will have to convert RegisterViewModel object to User  object, a quick and dirty way is to create an instance of type User and map it to RegisterViewModel before calling service method.

Here it is:

   [HttpPost]
   [AllowAnonymous]
   public ActionResult SignUp(RegisterViewModel registerVM)
   {
       if (ModelState.IsValid)
       {


          User user = new User
          {
             FirstName = registerVM.FirstName,
             LastName = registerVM.LastName,
             UserName = registerVM.UserName,
             Email = registerVM.Email,
             Password = registerVM.Password
          };

        var result = authenticateService.RegisterUser(user);



The above code will obviously work but it will cause code redundancy and in result it will be violation of DRY principle,because in future there is possibility of mapping ViewModel instance to Model instance or vice versa and we will end up writing same code again and again at different places where it is needed which is not good.

implicit operator in c#:


Here comes in the implicit operator feature provide by c#, we will write our operator for RegisterViewModel and User class so that they can be implicitly converted to each other where ever needed. We will have to modify the implementation of RegisterViewModel for this:

We will have to add these two operators in the RegisterViewModel class:

 public static implicit operator RegisterViewModel(User user)
 {
     return new RegisterViewModel
     {
         UserID = user.UserID,
         FirstName = user.FirstName,
         UserName = user.UserName,
         Password = user.Password,
         ConfirmPassword = user.Password,
         Email = user.Email
     };
 }

 public static implicit operator User(RegisterViewModel vm)
 {
     return new User
     {
         FirstName = vm.FirstName,
         LastName = vm.LastName,
         UserName = vm.UserName,
         Email = vm.Email,
         Password = vm.Password
      };
  }

So we have written the implicit conversion between these two types at one place and we will be reusing it everywhere we need.

yes i mean that, now these two types can be implicitly convertible / cast-able in to each other.

My action would look like this now:

  [HttpPost]
  [AllowAnonymous]
  public ActionResult SignUp(RegisterViewModel registerVM)
  {
      if (ModelState.IsValid)
      {

          var result = authenticateService.RegisterUser(registerVM);  // implicit conversion from RegisterViewModel to User Model

          RegisterViewModel vm = result; // see implicit conversion from User model to RegisterViewModel

          return View(vm);

       }
     return View(registerVM);
  }

Summary:

By implementing implicit operator for Model to ViewModel mapping and vice versa,we can see that our action is more cleaner now, as conversion is being moved to a central place due to which our code is reusable as well, and we are trying to follow DRY principle to some extent.

You can read more about implicit operator at MSDN here.
Udemy

Image ActionLink Html Helper in asp.net mvc

Sunday, July 12, 2015 1 Comments A+ a-

For creating a link in asp.net mvc we use Link Extension provided by  the mvc framework. For creating a simple anchor tag we use Html.ActionLink() helper which generates anchor tag for us.

For Example:

@Html.ActionLink("Link Display Text","Index","Home")

This will render following html:

<a href="/Home/Index">Link Display Text</a>

Now if we want to create a image link, we can use html to create image link this way:

<a href="/Home/Index">
<img src="/images/untitled.png">
</a>

This will work obviously,but what if we want to do it with Html Helper method as we do using Html.ActionLink, but we do not have any helper for image link provided by framework, so one can do it using html as i wrote above or will have to write custom html helper.

It's the beauty of asp.net mvc that we can extend exisiting helpers according to our needs and can also add new html helpers in case we need to used it at many places , in that case better approach is to create a helper extesnion and use it every where in the project.

Now for creating helper extension first of all we need to create a static class, as its the pre-requisite for creating extesnion methods that the method should be static, and it  should be inside a static class.

Here is the code for extension method for ImageActionLink helper extension:

namespace MyApplication.Helpers
{
  public static class CustomHtmlHelepers
  {
    public static IHtmlString ImageActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes,string imageSrc)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var img = new TagBuilder("img");
        img.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc));
        var anchor = new TagBuilder("a") { InnerHtml = img.ToString(TagRenderMode.SelfClosing) };
        anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
        anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        return MvcHtmlString.Create(anchor.ToString());

    }
  }
}



The first parameter with this keyword is used in extension methods see this article on Extension Method for understanding what are extesnion methods.

and now we can call it from View for creating Image Link. But remember that we will have to include the namespace in the View in which we have create the class and extension method,but if you have create it in the same namespace, then it will be accessible without adding any using statement in View.

In my case i have seperated all Extension Methods in seperate namespace named Helpers so i will have to include it in View via using statement:

@using MyApplication.Helpers;

@Html.ImageActionLink("Link Display Text","Index","Home",null,null,"~/images/untitled.png")

It will render the same html which i wrote above which is :

<a href="/Home/Index">
<img src="/images/untitled.png">
</a>

I hope it makes you understand how you can write you own custom html helpers in asp.net mvc.

Udemy

Disable textbox cut copy paste in asp.net and asp.net mvc using javascript,jquery

Thursday, June 18, 2015 0 Comments A+ a-

In some scenarios, we don't want user to be able to cut or copy the value of text box and we also want to restrict user to not be able to paste value from clipboard in text box.


User have couple of options, he can use short cut keys , for example Ctrl + C for copying and Ctrl + V , or user can right click inside the control and can use use context menu buttons which are mostly Cut, Copy and Paste available for doing desired operation on control.


One way is to write java-script events  for cut,copy and paste so that whenever user do one of these operations on control we handle them to override the default implementation of these commands.



In asp.net mvc we can use the htmlAttributes parameter of Html Helper method do it.

Disabling Using  JavaScript:


Here is an example code using javacript:

@Html.TextBoxFor(model => model.Question, 
          new {
                       @class="form-control",
                       oncut="return false"
                       oncopy="return false", 
                       onpaste="return false"
                     }
                 )

Here is the Live DEMO Fiddle of it.


Disabling Using JQuery:


We can do the same using jquery as well this way:

@Html.TextBoxFor(model => model.Question, 
          new {
                       @class="form-control",
                       id="txtQuestion"
                       oncut="return false"
                       oncopy="return false", 
                       onpaste="return false"
                     }
                 )

and in jquery :

$("#txtQuestion").on("cut copy paste",function(e) {

   e.preventDefault();
    // it will cause to stop default behaviour ofcommand
   // or we can use return false as well, as we did in js

}

 You can do it same way in asp.net web forms as well, for example:

<asp:TextBox ID="txtQuestion" 
             runat="server"
             CssClass="form-control"
             oncut="return false"
             oncopy="return false" 
             onpaste="return false">
</asp:TextBox>
Udemy

Difference between static and sealed class in c#

Saturday, June 13, 2015 0 Comments A+ a-


What is static class

A static class is very similar to non-static class, however there's one difference: a static class  can't be instantiated. In different words, you can not use the new keyword to make a variable of that class type. As a result of there's no instance variable, you access the static class members  by using class name. 

For Example,we have following static class which has a static method which adds two number.This is just as example, we already have a Math class in System namespace which framework has provided which has all the commonly used Math functions available:


public static class MathUtility
{
  public static int Add(int a, int b)
  {
   return a+b;
  }
}


We can call it this way:


int result = MathUtility.Add(2,5);


A static class will be used as a convenient instrumentation for sets of ways that simply treat input parameters and don't got to get or set any internal instance fields. for instance, in the .NET Framework class Library, the static System.Math class contains functions/methods that perform mathematical operations, with none demand to store or retrieve knowledge that's distinctive to a specific instance of the Math class. That is, you apply the members of the class by specifying the class name and also the methodology name, as shown within the following example.



double dub = -3.14;
Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));

Output:

3.14

-4

3


As is that the case with all class types, the data for a static class is loaded by the .NET Framework common language runtime (CLR) once the program that references the class is loaded. The program cannot specifically tell when the class is loaded. However, it's certain to be loaded and to own its fields initialized and its static constructor referred to as before the class is documented for the primary time in your program. A static constructor is called just once, and a static class remains in memory for the time period of the applying domain during which your program resides.



Features of Static Class:

  1. It can only have static members.
  2. It cannot have instance members as static class instance cannot be created.
  3. It is a sealed class.
  4. As static class is sealed, so no class can inherit from a static class.
  5. we cannot create instance of static class that's the reason we cannot have instance members in static class, as static means shared so one copy of the class is shared to all.
  6. static class also cannot inherit from other classes.


What is sealed class


A sealed class cannot be inherited(means it cannot be used as a base class). It stops/restricts other classes from inheriting from it. Yes, when a class is marked sealed no other classes could inherit from it.

Consider the following example in which  class SealedClass inherited from class BaseClass but as we have marked SealedClass sealed using sealed modifier, it cannot be used as base class by other classes.

Consider the following example:

class BaseClass 
{

}    

sealed class SealedClass : BaseClass
{

}

We can also make methods and properties sealed. We can also mark overridden methods or properties  of base class in child class sealed so that they cannot be overridden further sub-classes that inherit from this subclass.

class A
{
 protected virtual void Foo()
 {
  Console.WriteLine("A.Foo");
 }

 protected virtual void Bar()
 {
  Console.WriteLine("A.Bar");
 }
}

class B : A
{
 sealed protected override void Foo()
 {
  Console.WriteLine("B.Foo");
 }

 protected override void Bar()
 {
  Console.WriteLine("B.Bar");
 }
}

Now see this :

class C : B
{
 // Attempting to override Foo causes compiler error CS0239. 
 // protected override void Foo() { Console.WriteLine("C.Foo"); }
 // Overriding F2 is allowed. 
 protected override void Bar()
 {
  Console.WriteLine("C.Bar");
 }
}

you cannot use abstract and sealed modifier together with a class because abstract class has to be inherited by some sub-class that gives implementation of  abstract methods/properties.

Also when using sealed modifier with methods/properties that method should be override.In .Net Framework structs are implicitly sealed which means they cannot be inherited.

Some run-time optimization are also done when sealed class members are called, so calling of  sealed class members is slightly faster than other.

The following are the points to keep in mind about sealed class:

  1. sealed class can be instantiated.
  2. It can inherit from other classes.
  3. It cannot be inherited
Udemy

User Friendly Display Text For Enum in C#

Wednesday, June 10, 2015 0 Comments A+ a-

When using Enum sometime we dont want to show the enum name that we have in code to user but instead of that we want to show some text that is understanable for end user.I will share today how we can set display text on Enum values that we can use to show to end-user.

Consider this Enum:


public enum eUserRole : int
 {
    SuperAdmin = 0,
    PhoenixAdmin = 1,
    OfficeAdmin = 2,
    ReportUser = 3,
    BillingUser = 4
  }



So, it is obvious that one would not like to show user SuperAdmin in this way without space, one would expect it to be displayed like "Super Admin" at front end.


For that first of all we will have to create a custom DisplayName attribute for Enum:

public class EnumDisplayNameAttribute : Attribute
{
  private string _displayName;
  public string DisplayName
  {
      get { return _displayName; }
      set { _displayName = value; }
  }
}

Now we can use this attribute to decorate it on our Enum values:

public enum eUserRole : int
{
    [EnumDisplayName(DisplayName="Super Admin")]
    SuperAdmin = 0,
    [EnumDisplayName(DisplayName = "Phoenix Admin")]
    PhoenixAdmin = 1,
    [EnumDisplayName(DisplayName = "Office Admin")]
    OfficeAdmin = 2,
    [EnumDisplayName(DisplayName = "Report User")]
    ReportUser = 3,
    [EnumDisplayName(DisplayName = "Billing User")]
    BillingUser = 4
}

For getting the DisplayName atttribute we have wrote an extension method on Enum which will return us the DisplayName attribute value:


public static class EnumExtensions
{

   public static string DisplayName(this Enum value)
   {
       FieldInfo field = value.GetType().GetField(value.ToString());

       EnumDisplayNameAttribute attribute
               = Attribute.GetCustomAttribute(field, typeof(EnumDisplayNameAttribute))
                   as EnumDisplayNameAttribute;

       return attribute == null ? value.ToString() : attribute.DisplayName;
   }
}
and now we can call it on Enum values to get the DisplayName attribute value simply:


      Console.WriteLine(eUserRole.SuperAdmin.DisplayName());


This will output on Console:

           Super Admin 
Udemy

OOP Difference between Shadowing and Overriding

Sunday, June 07, 2015 0 Comments A+ a-

Introduction:

In this post, we will discuss the concept of Shadowing in OOP using c# and we will see how it works which will give you some idea that where we can use it and hopefully you will be able to decide when working practically in c# where it can be useful.

What is Shadowing:

Shadowing is a concept of  OOP (Object Oriented Programming) paradigm. Using Shadowing we can  provide a new implementation to base class member without overriding it, which means that original implementation of base class member gets shadowed (hidden) with the new implementation of base class member provided in derived class.

Consider a scenario where you have an external assembly which you have added in your project. You have a class in that assembly and it has a method which is not defined as virtual and you want to override that method(define your own implementation for that method) in the derived class. What would you do?
This is the scenario where you can use shadowing concept to override the method in the derived class

Definition:

 Following are few definitions of it

 According to MSDN:

  • Shadowing is concept of using Polymorphism in Object Oriented Programming. When two programming elements share the same name, one of them can hide, or shadow, the other one. In such a situation, the shadowed element is not available for reference; instead, when your code uses the element name, the compiler resolves it to the shadowing element. 
  •  Shadowing is actually hiding overridden method implementation in derived class and call the parent call implementation using derived class object

Difference between Overriding and Shadowing 

There is a major difference in shadowing and overriding which is normally when we override a virtual method in derived class and create instance of derived class and then if we hold reference to derived class object as base class object, and call that member, it always calls derived class implementation which is supposed to happen, but in shadowing the case is different, if for the same virtual member we shadow it in the derived class using new keyword and we call the implementation as above it will call base class implementation when we have reference to object of type base class and if we have reference to same object of derived type it will call derived type implementation so base class and derived class implementation are hidden from each other, method of which implementation to be called depends upon we are calling the member using reference of base type or derived type.

Example:

Suppose, I have a base class BaseLogger which has two virtual methods(means they can be overridden in subclass) defined:

public abstract class BaseLogger
{
    public virtual void Log(string message)
    {
        Console.WriteLine("Base: " + message);
    }

    public virtual void LogCompleted()
    {
        Console.WriteLine("Completed");
    }
}

Now i create a class Logger that inherits from BaseLogger class. Logger class looks like this:

public class Logger : BaseLogger
{
    public override void Log(string message)
    {
        Console.WriteLine(message);
    }

    public new void LogCompleted()
    {
        Console.WriteLine("Finished");
    }
}

Now i want my Console to Print following lines:

Log started!

Base: Log Continuing

Completed



What should i write in Main Program to get the above output ? Here is the code we will need to write:

public class Program
{
    public static void Main()
    {

        BaseLogger logger = new Logger();

        logger.Log("Log started!");
        logger.Log("Base: Log Continuing");
        logger.LogCompleted();
    }
}

The first call to Log method is OK, it has called Derived Logger class Log method and it should because we have overridden it in the Logger class.

The second call is also same.

Now note the third call, it has called  the base class LogCompleted() method not derived class, it is because we have defined derived class method with new keyword which is hiding the derived class method when we are calling it with object of type BaseLogger which is our base class.

If we want to call the derived class LogCompleted() method our object reference should be of type Logger not BaseLogger.While in method overriding this is not the case.

In method overriding if we cast object of derived class to base  class and call method, it will call overridden implementation of derived class.

Udemy

Should i use Abstract Class or Interface ? (abstract class vs Interface)

Tuesday, April 28, 2015 0 Comments A+ a-

Most of the time developers get confused about abstract class and interface. while interview most of the time interviewer asks the difference between abstract class and interface, we give answer that we read on internet and what we have understanding, but it gets messed up always.


Also when developing applications, we are not sure often that it is the scenario to use abstract class or create interface.

I am posting text from CLR via C# book where Jeffery Richter is trying to explain when should we use abstract class and when interface. Here is the text from book:

I often hear the question "Should i design a base type or interface ?" The answer is not always clear cut.

Here are some guidelines that might help you:


  • IS - A VS CAN-DO relationship : A type can inherit only one implementation If the Derived type can't claim  IS-A relationship with the base type, don't use a base type, use an interface. interfaces imply a CAN-DO relationship. If the CAN-DO functionality appears to belong with various object types, use an interface. For example, a type can convert instances of itself to another type (IConvertible), a type can serialize an instance of itself (ISerializable), etc. Note that value types must be derived from System.ValueType, and therefore, they cannot be derived from an arbitrary base class. In this case, you must use a CAN-DO relationship and define an interface.
  • Ease of Use: It’s generally easier for you as a developer to define a new type derived from a base type than to implement all of the methods of an interface. The base type can provide a lot of functionality, so the derived type probably needs only relatively small modifications to its behavior. If you supply an interface, the new type must implement all of the members.
  • Consistent Implementation:No matter how well an interface contract is documented, it’s very unlikely that everyone will implement the contract 100 percent correctly. In fact, COM suffers from this very problem, which is why some COM objects work correctly only with Microsoft Word or with Windows Internet Explorer. By providing a base type with a good default implementation, you start off using a type that works and is well tested, you can then modify parts that need modification.
  • Versioning:If you add a method to the base type, the derived type inherits the new method, you start off using a type that works, and the user’s source code doesn't even have to be recompiled. Adding a new member to an interface forces the inheritor of the interface to change its source code and recompile.
Udemy

Extension Methods Feature in C# with Simple Example

Monday, April 27, 2015 0 Comments A+ a-

Introduction:


Extension methods are special type of methods which were introduced in C# 3.0. They are used to extend the functionality of  any existing type in .Net.Using extension method we can add new methods to a class/type without modifying original source code of  Type, recompiling, or creating a new derived type.

Normally when we use linq standard query operators that add query functionality to the existing IEnumerable and System.Collections.Generic.IEnumerable<T> types. For using the standard query operators,first bring them in scope by writing using System.Linq in the code file.

Now you can call for example GroupBy,OrderBy etc like instance methods on any type that implement IEnumerable<T>

According to MSDN :


Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Syntax of writing Extension Method :


As extension method is a special method, it is defined little differently than normal method.Here is the points to be noted when writing extension method:

  1. It should be a static method.
  2. It should be written in a static class.
  3. its first parameter starts with this keyword followed by type parameter
  4. Extension method should be in the same namespace otherwise you will need to inculde namespace of the class with a using statement. 

Simple Example:


We can write extension method for any existing type in our code.Most of the time we write extension method for types that we cannot modify which are built-in in the .Net Framework.

I will make a simple extension method on string type to convert string to integer.


public static class StringExtensions
{
 public static int ToInt32(this string value)
 {
  int result;
  if (int.TryParse(value, out result))
  {
   return result;
  }

  return 0;
 }
} 

and we can use it to convert string to integer if string contains numeric value in. We can call it this way:


public class Program
{
 public static void Main()
 {
  
  Console.WriteLine("123".ToInt32());
  
 }
}

You can see running example in  this fiddle