Monday, 24 April 2017

Class implementing two interfaces having same method c#

Example Here
When using explicit 
interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type. You can implement one or both of those interfaces explicitly.


interface IControl
{
    void Paint();
}
interface ISurface
{
    void Paint();
}
class SampleClass : IControl, ISurface
{
    // Both ISurface.Paint and IControl.Paint call this method. 
    public void Paint()
    {
        Console.WriteLine("Paint method in SampleClass");
    }
}
class Test 
{
    static void Main()
    {
        SampleClass sc = new SampleClass();
        IControl ctrl = (IControl)sc;
        ISurface srfc = (ISurface)sc;

        // The following lines all call the same method.
        sc.Paint();
        ctrl.Paint();
        srfc.Paint();
    }
}
// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass

If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces. It is possible to implement an interface member explicitly—creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period. For example:

public class SampleClass : IControl, ISurface
    {
        void IControl.Paint()
        {
            System.Console.WriteLine("IControl.Paint");
        }
        void ISurface.Paint()
        {
            System.Console.WriteLine("ISurface.Paint");
        }
    }

// Call the Paint methods from Main.

        SampleClass obj = new SampleClass();
        //obj.Paint();  // Compiler error.

        IControl c = (IControl)obj;
        c.Paint();  // Calls IControl.Paint on SampleClass.

        ISurface s = (ISurface)obj;
        s.Paint(); // Calls ISurface.Paint on SampleClass.

        // Output:
        // IControl.Paint
        // ISurface.Paint


----------------------------end----------------------------------------------------
Source Reference
I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.
What I don't understand is when you create a variable that is of one of your Interface types:
IMyInterface somevariable;
Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:
somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface - you are creating an instance of something that implements the interface.
The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
So now, using your example, you could have:
MyNiftyClass : IMyInterface
{
    public void CallSomeMethod()
    {
        //Do something nifty
    }
}

MyOddClass : IMyInterface
{
    public void CallSomeMethod()
    {
        //Do something odd
    }
}
And now you have:
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.
public void ThisMethodShowsHowItWorks(IMyInterface someObject)
{
    someObject.CallSomeMethod();
}
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.
public void AnotherClass()
{
    IMyInterface nifty = new MyNiftyClass()
    IMyInterface odd = new MyOddClass()

    // Pass in the nifty class to do something nifty
    this.ThisMethodShowsHowItWorks(nifty);

    // Pass in the odd class to do something odd
    this.ThisMethodShowsHowItWorks(odd);

}
EDIT
This addresses what I think your intended question is - Why would you declare a variable to be of an interface type?
That is, why use:
IMyInterface foo = new MyConcreteClass();
in preference to:
MyConcreteClass foo = new MyConcreteClass();
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:
public void AMethod()
{
    // Why use this?
    IMyInterface foo = new MyConcreteClass();

    // Why not use this?
    MyConcreteClass bar = new MyConcreteClass();
}
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
  • I typically inject dependencies so the polymorphism is needed
  • Using the interface clearly states my intent to only use members of the interface
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.
Borrowing an example from itowlson, using concrete declaration you could not do this:
public void AMethod(string input)
{               
    IMyInterface foo;

    if (input == "nifty")
    {
        foo = new MyNiftyClass();
    }
    else
    {
        foo = new MyOddClass();
    }
    foo.CallSomeMethod();
}

Sunday, 23 April 2017

Action Filtering in ASP.NET MVC Applications

MVC Action Filter Types


ASP.NET MVC provides the following types of action filters:
  • Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request. The AuthorizeAttribute class is one example of an authorization filter.
  • Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
  • Result filter, which wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter.
  • Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page. The HandleErrorAttribute class is one example of an exception filter.

How To Apply an Action Filter


Typically, an action filter is an attribute that implements the abstract FilterAttribute class. Some action filters, such as AuthorizeAttribute and HandleErrorAttribute, implement the FilterAttribute class directly. These action filters are always called before the action method runs.
Other action filters, such as OutputCacheAttribute, implement the abstract ActionFilterAttribute class, which enables the action filter to run either before or after the action method runs.
You can use the action filter attribute to mark any action method or controller. If the attribute marks a controller, the action filter applies to all action methods in that controller.
The following example shows the default implementation of the HomeController class. In the example, the HandleError attribute is used to mark the controller. Therefore, the filter applies to both action methods in the controller.

Sample Example Action Filter for MIME type content:
Class:
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Project.CustomFilter
{
    public class ValidateMimeFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
        }

    }
}

In Your controller
using Project.CustomFilter;
        [ValidateMimeFilter]
       //its validate the request contains Mime Multipart Content
        [HttpPost]
        [Route("api/ActionName")]
        public async Task<IHttpActionResult> ActionName()
            {
            }