Showing posts with label mvc. Show all posts
Showing posts with label mvc. Show all posts

Developing MVC applications using SOLID principles

0

Category : ,

my thanks to: Developing MVC applications using SOLID principles http://www.codeguru.com/csharp/csharp/writing-c-code-using-solid-principles.htm

MVC in a nutshell

0

Category :

Getting Data from Controller to View

  1. ViewData - Assign a value with a key in the controller and read the value using the key in the View page
    public ActionResult Index()
    {
      ViewData["Message"] = "Hello, World";
      return View();
    }
    
  2. ViewBag - allows an object to dynamically have properties added to it. So with a ViewBag, you can use the “.” notation.
    public ActionResult Index()
    {
      ViewBag.Message = "Hello, World";
      return View();
    }
    
  3. TempData - is another dictionary for storing temporary data like the “ViewBag“ but is deleted at the end of the HTTP request
    //  marks the specified key in the dictionary for retention
    public void Keep(string key)
    // returns an object without marking the key for deletion
    public Object Peek(string key)
    
  4. Strongly-Typed View Model Object – WebFormViewEngine
    <%@ Page Inherits="System.Web.Mvc.ViewPage" %>
    

    Product Name: <%: Model.Name %>

  5. Strongly-Typed View Model Object – Razor
    @model Mvc3App.Models.Product
    

    Product: @Model.Name


Getting Data from View to Controller

  1. Traditional Approach - HttpRequestBase
  2. FormCollection Object
  3. Action Parameters
  4. Strongly type model binding to view

ActionResult() response types:

There are 11 different response types which can be sent to the end user :-
  1. ViewResult - Renders a specified view to the response stream
  2. PartialViewResult - Renders a specified partial view to the response stream
  3. EmptyResult - An empty response is returned
  4. RedirectResult - Performs an HTTP redirection to a specified URL
  5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  6. JsonResult - Serializes a given object to JSON format
  7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  8. ContentResult - Writes content to the response stream without requiring a view
  9. FileContentResult - Returns a file to the client
  10. FileStreamResult - Returns a file to the client, which is provided by a Stream
  11. FilePathResult - Returns a file to the client

Passing Data From View to Controller

0

Category :

Using Traditional Approach

In the traditional approach we use the request object of the HttpRequestBase class. The request object has view input field values in name/value pairs.
[HttpPost]
public ActionResult CalculateSimpleInterestResult()
{
    decimal principle = Convert.ToDecimal(Request["txtAmount"].ToString());
    decimal rate = Convert.ToDecimal(Request["txtRate"].ToString());
    int time = Convert.ToInt32(Request["txtYear"].ToString());

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("Interest : " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

Using the FormCollection Object

We can also get post requested data by the FormCollection object. The FormCollection object also has requested data in the name/value collection as the Request object. To get data from the FormCollection object we need to pass it is as a parameter and it has all the input field data submitted on the form.
[HttpPost]
public ActionResult CalculateSimpleInterestResult(FormCollection form)
{
    decimal principle = Convert.ToDecimal(form["txtAmount"].ToString());
    decimal rate = Convert.ToDecimal(form["txtRate"].ToString());
    int time = Convert.ToInt32(form["txtYear"].ToString());

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("Interest : " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

Using the Parameters

We can pass all input field names as a parameter to the post action method. The input field name and parameter name should be the same. These parameters have input field values that were entered by the user. So we can access view input field values from these parameters. The input field takes a string value from the user so the parameter should be a string type. There is no need to define a parameter in any specific sequence.
[HttpPost]
public ActionResult CalculateSimpleInterestResult(string txtAmount, string txtRate, string txtYear)
{
    decimal principle = Convert.ToDecimal(txtAmount);
    decimal rate = Convert.ToDecimal(txtRate);
    int time = Convert.ToInt32(txtYear);

    decimal simpleInteresrt = (principle*time*rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("Interest : " + simpleInteresrt);
    return Content(sbInterest.ToString());
}

Strongly typed model binding to view

We bind a model to the view; that is called strongly type model binding.
namespace CalculateSimpleInterest.Models
{
    public class SimpleInterestModel
    {
        public decimal Amount { get; set; }
        public decimal Rate { get; set; }
        public int Year { get; set; }
    }
}
[HttpPost]
public ActionResult CalculateSimpleInterestResult(SimpleInterestModel model)
{
    decimal simpleInteresrt = (model.Amount*model.Year*model.Rate)/100;

    StringBuilder sbInterest = new StringBuilder();
    sbInterest.Append("Interest : " + simpleInteresrt);
    return Content(sbInterest.ToString());
}
my thanks to: http://www.codeproject.com/Articles/639709/Getting-Data-From-View-to-Controller-in-MVC

Gang of Four Design Patterns

0

Category : , ,

What are Design Patterns?

Design patterns provide solutions to common software design problems. In the case of object-oriented programming, design patterns are generally aimed at solving the problems of object generation and interaction, rather than the larger scale problems of overall software architecture. They give generalised solutions in the form of templates that may be applied to real-world problems.

Design patterns are a powerful tool for software developers. However, they should not be seen as prescriptive specifications for software. It is more important to understand the concepts that design patterns describe, rather than memorising their exact classes, methods and properties. It is also important to apply patterns appropriately. Using the incorrect pattern for a situation or applying a design pattern to a trivial solution can overcomplicate your code and lead to maintainability issues.


Creational Patterns

The first type of design pattern is the creational pattern. Creational patterns provide ways to instantiate single objects or groups of related objects. There are five such patterns:

Abstract Factory. The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.

Builder. The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.

Factory Method. The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.

Prototype. The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.

Singleton. The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.


Structural Patterns

The second type of design pattern is the structural pattern. Structural patterns provide a manner to define relationships between classes or objects.

Adapter. The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.

Bridge. The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.

Composite. The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.

Decorator. The decorator pattern is used to extend or alter the functionality of objects at run-time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.

Facade. The facade pattern is used to define a simplified interface to a more complex subsystem.

Flyweight. The flyweight pattern is used to reduce the memory and resource usage for complex models containing many hundreds, thousands or hundreds of thousands of similar objects.

Proxy. The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. The proxy provides the same public interface as the underlying subject class, adding a level of indirection by accepting requests from a client object and passing these to the real subject object as necessary.

Behavioural Patterns

The final type of design pattern is the behavioural pattern. Behavioural patterns define manners of communication between classes and objects.

Chain of Responsibility. The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
Command. The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.

Interpreter. The interpreter pattern is used to define the grammar for instructions that form part of a language or notation, whilst allowing the grammar to be easily extended.

Iterator. The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.

Mediator. The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
Memento. The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.

Observer. The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.

State. The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.

Strategy. The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.

Template Method.
The template method pattern is used to define the basic steps of an algorithm and allow the implementation of the individual steps to be changed.

Visitor. The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.


my thanks to:
http://www.blackwasp.co.uk/GofPatterns.aspx

C# Field vs Property

0

Category : ,

Property is a function call. Field is not a call - just access into a memory of the class.

Properties are more maintainable than fields. Some properties do not have the equivalent field - you need to write some code to set/get them.

Simple example: say you have a car object. It has a mileage and a gallons as fields. You can make a property MPG by dividing these fields. Notice that there is no MPG field inside an object - you do it on the fly by using a property. And that property is read-only - you cannot set it. It can only be changed by changing mileage field or gallons field.

From the other hand - the critical code path (large loops, for example) should avoid using a lot of properties or get the properties once before the loop.

Take a look here:
http://msdn.microsoft.com/en-us/library/w86s7x04(VS.80).aspx

Log4Net Tutorial in C#

0

Category : , ,

Logging Levels

There are seven logging levels, five of which can be called in your code. They are as follows (with the highest being at the top of the list):
  1. OFF - nothing gets logged (cannot be called)
  2. FATAL
  3. ERROR
  4. WARN
  5. INFO
  6. DEBUG
  7. ALL - everything gets logged (cannot be called)

These levels will be used multiple times, both in your code as well as in the config file. There are no set rules on what these levels represent (except the first and last).

Add the following code to the Assembly.cs file.

// Configure log4net using the .config file
 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
 // This will cause log4net to look for a configuration file
 // called TestApp.exe.config in the application base
 // directory (i.e. the directory containing TestApp.exe)
 // The config file will be watched for changes.

Add the following section to the web/app.config file in the node:



    

Create a new section in the web/app.config using log4net as the node name:


 
   
   
   
  
   
 
 
   
   
 
  

Define a static logger variable at the top of your class. Something like this will work:

private static readonly ILog log = LogManager.GetLogger(typeof(Program));

Altogether then, your class might look something like this:

using System;
using System.Collections.Generic;
using System.Text;
using log4net;

namespace log4netDemo
{
  class Program
  {
   // Define a static logger variable so that it references the name of your class
   private static readonly ILog log = LogManager.GetLogger(typeof(Program));

   static void Main(string[] args)
   {
    log.Info("Entering application.");

    for (int i = 0; i < 10; i++)
    {
     log.DebugFormat("Inside of the loop (i = {0})", i);
    }

    log.Info("Exiting application.");
   }
  }
}

my thanks to:
http://www.justinrhinesmith.com/blog/2008/05/12/quick-and-easy-log4net-setup/