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!

Ternary Operator in SQL

by naspinski 2/3/2012 1:32:00 PM

there technically isn't one, but an equivalent isn't too hard to do

This ternary in C#:
(str.Length > 0 ? "yes" : "no");

Is equivalent to this in SQL:
(CASE WHEN LEN(@str) > 0 THEN "yes" ELSE "no" END);

Currently rated 2.2 by 5 people

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

Tags:

sql

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

My Case For Using Both UNIQUEIDENTIFIER (Guid) -and- INT Ids in every database table

by naspinski 11/7/2011 5:39:00 PM

Case for dual database accessors (not keys) - Guid vs Int/UniqueIdentifier vs Int

Let's face it, you never know what exactly is going to end up with your next application. Has an application ever ended up exactly where it was planned in the beginning? I would say never.

There is an insane amount of writing on the debate of int vs guid, both have their pros and cons, both have storage, index and coding implications and we know (or can find) almost all of them with a simple search. Yet there is no consensus on which is the best, I am not here to add to that discussion.

Therefore I propose using BOTH - hear me out.

I propose that the best solution is to provide ONE of the two as your primary key, I prefer Guid as the PK, as it can be referenced more universally (think recycle bin, etc.), but it does have the added indexing cost of being larger; then simply add the auto-incrementing integer as an additional field. Whichever one you choose as your alternative (integer in my case) is simply as a just-in-case means of accessing your data - also indexed. This provides you the best of both worlds, without too much sacrifice. For example, you get the ubiquity of being able to generate a Guid anywhere (without a DB trip), but also have the ability to access your data by a clean 4-bit integer. If for some reason, the code is accessed by software that relies on integers, you are not stuck without one, and vice-versa.

Yes, this will obviously cause more data to be stored for every entry in a table (I am talking about main tables here, not necessarily lookup tables, etc.). This will cause extra index storage as well, but in the long run, I feel it provides enough advantage and future-proofing to justify the sacrifice. Now tell me how wrong I am...

Currently rated 3.2 by 17 people

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

Tags: ,

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