loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Using a Custom Controller Class in Asp.Net MVC to Simplify Coding

by naspinski 12/15/2011 1:23:00 PM

Controllers often have some repetitive code, implementing your own Controller class can help eliminate a lot of this

Here is a small snippet and how I use some simple tricks to help clean up my Controllers in Asp.Net MVC (using MVC 4 at the moment):
public class MyController : Controller
{
    public MyEntities Db { get; set; }

    protected override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        if (filterContext.IsChildAction)
            return;
        this.Db = new MyEntities();
        base.OnActionExecuting(filterContext);
    }

    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        string srch = form["Search"] ?? string.Empty;
        return RedirectToAction("Index", 
            new { search = srch });
    }

    protected void AttachToDb(EntityObject obj, 
        bool save = false, string entityKeyField = "Id")
    {
            obj.EntityKey = new EntityKey(
                obj.ToPluralizedString(), entityKeyField, 
                obj.GetType().GetProperty("Id")
                .GetValue(obj, null));
            Db.Attach(obj);
            Db.ObjectStateManager.ChangeObjectState(
                obj, System.Data.EntityState.Modified);
            if (save) Db.SaveChanges();
    }
}

The first thing in the code is simple declaration of an EntityContext - this is implemented directly, but could (and usually should) be implemented differently for dependency injection, but you get the idea. Here is where I also like to include stuff that is often used and could be vital (and centralized) for an application like an output type for web services (JSON, XML, etc.).

Next the OnActionExecuting is over-ridden and the Context is initialized. Here is where you can initialize the properties you set above.

The next method, the HttpPost Index method is just an example of how often times you can consolidate a commonly used method. For this example, it was from an application that had searches on all index pages. Instead of repeating this code in every controller, you can just put it here.

The final method has become very useful. A use I often find, is when taking in a large model after an Asp.Net MVC POST event, I can attach the model to the Db generically without any extra work

This method is a bit confusing, but it is simply attaching the new model to the Db without a Db lookup. In my tables, I generally have a field 'Id' that houses the Primary Key of every table, whether it is an Int or Guid. This way, I can simply pass in whatever object I am currently working with, and by using the pluralize method, and reflection, the method can figure out which table to attach the model to - eliminating the need for me to do extra coding. Alternatively, if I want to change the Key from 'Id', I can pass that in as well.

Now when I get a model being POSTed, it is easy to deal with:
[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        AttachToDb(model, true);
        //do stuff
    }
    else { /*do other stuff*/ }
}

This avoids the need to take another trip to the DB, change the properties on the object, then submit - streamlining the process very much and cutting down a lot of code.

This would be an example of how this would be done manually with the normal Controller class:
[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        MyEntities db = new MyEntities();
        Widget w = db.Widgets.Single(x => x.Id == model.Id);
        w.Name = model.Name;
        w.Serial = model.Serial;
        db.SaveChanges();
        //do stuff
    }
    else { /*do other stuff*/ }
}

Not a huge difference when you are just getting 2 values, but you could see how a model with 20 or 30 fields can be cut down from 30+ lines to just 1 or 2.

Currently rated 3.2 by 19 people

  • Currently 3.157894/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

asp.net | c# | mvc | steal some code

Pluralize a String or Class Name in C# and .Net

by naspinski 12/8/2011 10:13:00 PM

Sometimes you need to pluralize names like when you are working with Entity Framework or countless other sitautaions

When you auto-generate from tables in Entity Framework, it will make the table names plural, and the objects singular. Often times, when you are trying to use more generic functions like creating EntityKey objects for attaching to an unknown table, you will need to pluralize a class name, so for this, I came up with a couple static methods to simply return a plural version of an Object's name or a string itself:
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;

public static string Pluralize(this string s)
{
    PluralizationService plural = 
        PluralizationService.CreateService(
            CultureInfo.GetCultureInfo("en-us"));
    return plural.Pluralize(s);
}

Simple enough, now I make this specifically to get the table name of an EntityObject:
public static string GetTableName(this EntityObject obj)
{
    return obj.GetType().Name.Pluralize();
}

In use:
//returns "Cats":
string cats = "Cat".Pluralize();

//now specifically for EntityObjects:
string tableName = MyEntityObject.GetTableName();

Currently rated 3.3 by 18 people

  • Currently 3.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

c# | entities | linq-to-sql | mvc | steal some code

Constraining Routes in MVC to an Enum the Easy Way

by naspinski 10/6/2011 5:40:00 PM

simple way to constrain a route to only allow enum values

Say I have the following enum:
public enum SearchType { Facilities, Courses, Exercises};

And I only want those the be available in route Search/{SearchType}. I could constrain it manually with a string, but then what if the enum changes and I have this in a bunch of routes? Here is a simple way to accomplish this constraint:
public static void RegisterRoutes(RouteCollection routes)
{
    List searchTypeL = new List();
    foreach (Enums.SearchType type in 
        Enum.GetValues(typeof(Enums.SearchType))) 
    { searchTypeL.Add(type.ToString()); }
    string searchTypes = string.Join("|", searchTypeL);
    
    routes.MapRoute(
        "Searches",
        "Search/{type}",
        new { controller = "Search", action = "Index" },
        new { type = searchTypes }
    )
    ...

Very basic, all this does is enumerate through your enum and create a simple string to filter with.

Currently rated 3.1 by 49 people

  • Currently 3.081633/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

asp.net | c# | mvc

Adding Custom Exception Handling Attributes to Your Asp.Net MVC Actions

by naspinski 3/7/2011 12:00:00 PM

Attributes are a simple way to run common handling across many actions without repeating yourself

I ran into a position where I was handling exceptions and pushing them to xml ContentResults the same way on multiple actions across many controller repeating a lot of code. I was working on a REST interface that always was to return xml. All Exception were to be returned in xml as well. I found myself writing a lot of actions like this:
public ContentResult Fidget()
{
    try
    {
        //do a bunch of stuff
        //throw exceptions if I need to
    }
    catch(Exception ex) //now catch them and display xml
    {
        // turn the exception into xml
        return this.Content(myXmlException, "text/xml");
    }
    
    // if it made it here, return success xml
    return this.Content(successXml, "text/xml");
}

This worked great, but after a bunch of actions, the code was very redundant. I want to handle exception the same on a lot of actions, but not all, so I decided to go to an Attribute, specifically ActionFilterAttribute and the IExceptionFilter. If I override the OnException, I can automatically handle the Exceptions in the painted actions, so this is what I came up with:
[HttpGet]
public class XmlExceptionAttribute : 
    ActionFilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext 
        filterContext)
    {
        if (filterContext.Exception == null) return;
        filterContext.ExceptionHandled = true;
        var response = filterContext.Controller
            .ControllerContext.HttpContext.Response;
        response.ContentType = "text/xml";
        response.Write((new Status(
            filterContext.Exception)).ToXmlString());
    }
}

*Note that the Status object is a just an object I made to be serializeable and .ToXmlString() is an extension method I came up with a while back to convert objects into xml strings on the fly.

Now, if the attribute is applied, all I have to do for the above behavior in an action is simply this:
[HttpGet]
[XmlException]
public ContentResult Fidget()
{
    //do a bunch of stuff, throw exceptions if I need to
    
    // if it made it here, return success xml
    return this.Content(successXml, "text/xml");
}

The behavior is now the EXACT same!

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

c# | mvc | xml

Learning Ruby on Rails for a .Net MVC C# Coder

by naspinski 9/15/2010 12:07:00 PM

quick reference for equivalent methods/approaches

I am learning RoR for a new project that requires the ability to truly run cross-platform (don't even say Mono...). That said, I love .net, but Ruby on Rails is a fantastic MVC framework. I am learning a lot about MVC programming in general and here is my contribution to others trying to learn RoR in my situation.

And yes, I know there are many more syntax options than the ones I show, but this is just a quick reference -if you want them all, check out the API.

Everything presented here will render the same html in the respective languages, as well as behave the same as data access (ORM):

stylesheet/javascript links

Asp.Net MVC
<link rel="stylesheet" type="text/css" 
 href="<%=Url.Content("~/public/stylesheets/style.css") %>"
/>
<script type="text/javascript" 
 src="<%=Url.Content("~/public/javascripts/jquery.js") %>"
></ script>

RoR
<%= stylesheet_link_tag 'style' %>
<%= javascript_include_tag 'jquery' %>


hyperlinks

Asp.Net MVC
<%= Html.ActionLink("View Widgets", "Index", "Widget") %>
<%= Html.ActionLink("Widget 5", "Show", "Widget",
  new {id = 5}) %>

RoR
<%= link_to 'View Widgets', widgets_path %>
<%= link_to 'Widget 5', widget_path(5) %>


forms

Asp.Net MVC
<% using(Html.BeginForm()) { %>
 <%= Html.LabelFor(x => x.Name) %>
 <%= Html.TextBoxFor(x => x.Name) %>
 <input type="submit" value="submit" />
<% } >

RoR
<% form_for(@widget) do |f| %>
 <%= f.label :name %>
 <%= f.text_field :name %>
 <%= f.submit 'submit' %>
<% end %>


rendering partials

Asp.Net MVC
<%= Html.Partial("form") %>

RoR
<%= render :partial => 'form' %>


looping

Asp.Net MVC
<% foreach(var widget in Model.Widgets) { %>
  <%= widget.Name %>
<% } %>

RoR
<% for widget in @widgets %>
  <%= widget.name %>
<% end %>


validation

Asp.Net MVC
[MetadataType(typeof(WidgetValidation))]
public partial class Widget { }

public class WidgetValidation
{
  [Required(ErrorMessage = "Name is Required")]
  [RegularExpression("[\\S]{5,}", ErrorMessage = "Min 5 chars")]
  [StringLength(30, ErrorMessage = "Max 30 chars")]
  public string Name { get; set; }
}

RoR
class Widget < ActiveRecord::Base
  validates_presence_of :name
  validates_length_of :name, :in => 5..30
end


orm data access

Asp.Net MVC (Linq-to-Sql)
var db = new MyDataContext();
var widgets = db.Widgets;
var widget = db.Widgets.SingleOrDefault(x => x.Id == 5);
var components = widgets.Components.OrderBy(x => x.name);

RoR (ActiveRecord)
@widgets = Widget.all
@widget = Widget.find(5)
@components = @widget.components.sort_by{|w| w.name}


saving a model

Asp.Net MVC (Linq-to-Sql)
public ActionResult Create(Widget widget)
{
  db.InsertOnSubmit(widget);
  db.SubmitChanges();
}

RoR (ActiveRecord)
def create
  @widget = Widget.new(params[:widget])
  @widget.save
end


helper methods

Asp.Net MVC
// define it:
public static string DivThis(this HtmlHelper html, string text)
{
  return "<div>" + text + "</div>";
}

<!-- call it: -->
<= Html.DivThis("hello") %>

RoR
# define it
def div_this(text)
  '<div>' + text + '</div>'
end

<!-- call it: -->
<%= div_this('hello') %>



temporary data

Asp.Net MVC
// set it
TempData["someKey"] = "hello"

<!-- use it -->
<%= TempData["someKey"].ToString() %>

RoR
# set it
flash[:some_key] = 'hello'

<!-- use it -->
<%= flash[:some_key] %>


That's all I have for now, hopefully I will be adding more in the near future. I think I like RoR...

Currently rated 3.8 by 9 people

  • Currently 3.777778/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

c# | mvc