Sunday, December 23, 2012

Creating the .NET Solution Part 4

Redirection

From an OOP point of view, Response.Redirect is about as useful as the session object is (we're starting to see a trend here). It simply provides a way of sending you from one place to another. It would be nice if we could work with it using methods. It would be even better if we could hide some logic in those methods if need be. Our initial implementation is very easy.
  1. We will continue from last post Creating the .NET Solution Part 3 open the Fishbook solution.
  2. Right click in Interfaces project and select Add/New Item.
    Create IRedirector interface
    Create IRedirector interface
    1. Select Interface Item from C# Template and name it IRedirector.cs and then write the following code:

      namespace Fishbook.Interfaces
      {
          public interface IRedirector
          {
              void GoToHomePage();
              void GoToErrorPage();
          }
      }

    2. Right click in Components project and select Add/New Item.
      Create Redirector Class
      Create Redirector Class
      1. Select Class Item from C# Template and name it Redirector.cs and write the following code:
        using System.ComponentModel.Composition;
        using System.Web;
        using Fishbook.Interfaces;

        namespace Fishbook.Components
        {
            [Export(typeof(IRedirector))]
            public class Redirector : IRedirector
            {
                public void GoToHomePage()
                {
                    Redirect("~/Default.aspx");
                }

                public void GoToErrorPage()
                {
                    Redirect("~/Error.aspx");
                }

                private void Redirect(string path)
                {
                    HttpContext.Current.Response.Redirect(path);
                }
            }
        }


      This class, like the others, uses MEF so that it can be stubbed out for testing later. Currently there are two methods—one an example, and another handling redirection. Let's look at the Redirect() method. It takes a path parameter and then uses the HttpContext object to redirect the user to the appropriate location. An
      example is the GoToHomePage() method. It asks the Redirect() method to send the user to the homepage. If the homepage of the application changes later, we need to edit only this method.

      Of course, this class can be expanded with as many new methods as needed to redirect for any purpose. We can extend this object to be a bit more versatile too. We can also perform all sorts of logic inside these methods prior to using the redirection, obviously without degrading the overall design and where actually required.

      No comments:

      Post a Comment

      Automatic Traffic Exchange

      YallaTech Facebook page