Sunday, July 12, 2015

Image ActionLink Html Helper in asp.net mvc

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.

Thursday, June 18, 2015

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

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>

Saturday, June 13, 2015

Difference between static and sealed class in c#

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

Wednesday, June 10, 2015

User Friendly Display Text For Enum in C#

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 

Sunday, June 7, 2015

OOP Difference between Shadowing and Overriding

I have read many stuff on internet regarding shadowing concept of Object Oriented Programming.Today i will try to explain the shadowing in OOP using C# with examples.

Using Shadowing we can  provide a new implementation to base class member without overriding it.


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 at run-time. I will explain it with example next.

Following are few definition of shadowing.

What is Shadowing:

Here are a few definitions of it:

Accroding to MSDN:

1) 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.

2) Shadowing is actually hiding overridden method implementation in derived class and call the parent call implementation using derived class object.


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 dervied class to base  class and call method, it will call overridden implementation of dervied class. For example, the following line will output "Log started!" not "Base : Log started!":


Tuesday, April 28, 2015

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

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.

Monday, April 27, 2015

Extension Methods Feature in C# with Simple Example

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