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

Monitoring a DOM Element for Modification with jQuery

by naspinski 9/29/2011 4:47:00 PM

'watching' an element for any change within it

I recently ran into a situation where I had to modify a site that relied on an incredibly obfuscated and impossible to understand javascript file. I had to add in some elements after everything was populated with some function I didn't get, so I had to wait until a specific element was populated to do anything. Turns out the DOMNodeInserted event is what I needed:
var title = $("b.facility");
var title = $('#title');//the element I want to monitor
title.bind('DOMNodeInserted', function(e) {
    alert('element now contains: ' + $(e.target).html());
});

Pretty simple, but took me forever to figure out...

Currently rated 3.1 by 57 people

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

Tags: , ,

javascript | jquery | steal some code

ReCaptcha - Getting the Challenge Key and/or image with Asp.Net MVC

by naspinski 8/1/2011 11:30:00 AM

Often times you do not need the whole deal, or you are working with a technology that doesn't employ javascript or iframes

Recently I was working on a project that needed to provide (via MVC 3) the ReCaptcha image and/or challenge key only, and not the whole html/javascript portion due to limitations by the data consumer. It took me a while, but there is quite an elegant and simple solution to this.

Here is the controller I came up with:
public class CaptchaController : Controller
{
    public string contentReturnType = "text/plain";
    public string googleChallengeUrl = "http://
        www.google.com/recaptcha/api/challenge?k={0}";
    public string googleImageUrl = "http://
        www.google.com/recaptcha/api/image?c={0}";
    public string googleImageHtml = "<img style=
        \"display: block; \" height=\"57\" width=\"300\" 
         src=\"{0}\"/>";

    [HttpGet]
    public ContentResult GetChallengeKey(
        string proxyIpAndPort = null)
    {
        string http = string.Format(googleChallengeUrl, 
            ReCaptchaValues.PublicKey);
        WebClient client = new WebClient();

        //assuming no proxy on a local machine
        if (!string.IsNullOrEmpty(proxyIpAndPort) && 
            !Request.IsLocal) 
        {
            client.Proxy = 
                new WebProxy(proxyIpAndPort, true);
        }

        string html = client.DownloadString(http);
        int start = html.IndexOf('{');
        int length = html.IndexOf('}') - start + 1;
        string json = html.Substring(start, length);

        ReCaptchaState state = 
            new JavaScriptSerializer()
                .Deserialize(json);
        return this.Content(state.challenge, 
            contentReturnType);
    }

    [HttpGet]
    public ContentResult GetImageUrl()
    {
        return this.Content(string.Format(googleImageUrl, 
            GetChallengeKey().Content), contentReturnType);
    }

    [HttpGet]
    public ContentResult GetImageHtml()
    {
        return this.Content(string.Format(googleImageHtml, 
            GetImageUrl().Content), contentReturnType);
    }
}

This is using json deserializing of the ReCaptcha return string into a .Net object named ReCaptchaState which is covered here.

Now all that you need to do is call one of the urls to get the desired result in a plaintext format (you can change the output if you wish).

Currently rated 2.8 by 31 people

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

Tags: , , , , ,

asp.net | c# | my projects | steal some code

Deserializing ReCaptcha JSON with C#

by naspinski 8/1/2011 11:00:00 AM

Turning a ReCaptcha request into a strongly-typed C# object on the fly

When requesting a ReCaptcha image, you send out this request:
http://www.google.com/recaptcha/api/challenge?k=your_public_key

You then receive this in return:
var RecaptchaState = {
    site : 'your_public_key',
    challenge : 'returned_challenge_key',
    is_incorrect : false,
    programming_error : '',
    error_message : '',
    server : 'http://www.google.com/recaptcha/api/',
    timeout : 18000
};

document.write('<scr'+'ipt type="text/javascript" 
    s'+'rc="' + RecaptchaState.server + 'js/recaptcha.js">
    </scr'+'ipt>');

Looking at that, you can pull the information you need into this object:
[Serializable]
public class ReCaptchaState
{
    [DataMember]
    public string site { get; set; }

    [DataMember]
    public string challenge { get; set; }

    [DataMember]
    public bool is_correct { get; set; }

    [DataMember]
    public string programming_error { get; set; }

    [DataMember]
    public string error_message { get; set; }

    [DataMember]
    public string server { get; set; }

    [DataMember]
    public int timeout { get; set; }
}

By using this code:
WebClient client = new WebClient();
string ret = client.DownloadString(google_url);
int start = ret.IndexOf('{');
int length = ret.IndexOf('}') - start + 1;
string json = ret.Substring(start, length);

ReCaptchaState state = new JavaScriptSerializer()
    .Deserialize<ReCaptchaState>(json);

Now you have a ReCaptchaState .net object you can use the values from; simple.

Currently rated 3.1 by 26 people

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

Tags: , ,

c# | steal some code