Do It Yourself

A question came up about an earlier post on how I construct my grids shown in a few examples.


Now as you can see, it looks like a table, acts like a table, so it must be a table right? Well it isn’t. It’s actually done with divs and styles, something I’ve worked hard on getting right since moving to MVC.

I’m not bagging on the question asked because I’m probably a mutant and the only person that thinks the way I do (and have written below). I just have a philosophy that if you can do it yourself, do it yourself.

For starters, I’m not against new stuff, I think that’s pretty obvious. I’m also not completely against third party stuff seeing as a lot of my newer posts deal with jQuery. I do, however, avoid third party tools I don’t need, namely grid builders or things of that nature. I figure that if I can do it myself, I’ll do it myself. This kind of hits on the debate of using Visual Studios’s drag and drop feature for designing pages or not. Sure it’s easy and for the most part works, but you are really doing yourself a disservice. Why? Because most of the time you can get away with it, it’s those few times that it just won’t do what you want it to do that kill you.

When you use helper tools, you could be cheating yourself out of knowledge

Now I’m not saying that you should develop your own tools for rendering 3d graphs. Some things you just don’t have the time or the ability to create, but when it comes to simple things like markup, do the work. The knowledge you gain from this is substantial. Hell, I used to hate style sheets. I used to hate javascript. Quite frankly, they were a pain in the a– at first. However, taking the road less travelled has given me a new perspective on both. I no longer fear them and in fact would rather just type the markup out myself than trust some third part thing that I can’t fix when something goes wrong. I know that if I have to create a quick mock up that looks like the real deal, I can do that with notepad and a browser. I know that if I have to teach someone how to use style sheets or javascript, I can do that without just telling them to go to some page or to use some random tool. I have confidence in my knowledge.

More time now, less time later.

Now I know in Perfectworld, there is always enough time allotted to doing what needs to be done. In Realworld (Not the stupid MTV show) everyone is running around, heads a blaze. So the biggest excuse to not learn proper markup is that there isn’t time. A company isn’t going to pay you to learn when things need to be done. Well sure, but flash forward a couple months when someone tells you that you have to adjust the grid you didn’t build yourself to add something you have no idea how to add or else the world is going to end. Last thing that person will want to hear is “It can’t be done.” In fact, most business people have some crazy allergic reaction to that phrase that causes them to turn really, really red. It’s weird but happens a lot. At this point you can either:

Laugh and lose your job.

Go on the forums and hope there is a solution.

Die a quick and painful death.

Always expect people to want 20% more than what was originally written. Unless you have one of the best project managers that says the phrase “Work request form” on instinct, you will run into this situation. That’s where doing it yourself comes in real handy. It may have taken you a while to figure it all out, but you will for certain be able to fix the issue quickly.

You never know when you’ll actually have to know how to build things from scratch

Tech Interviews. When looking for a job, you’ll probably run into these. Best way to be prepared for these? Have the real world knowledge. How do you get that? By doing a lot of the work yourself. I have been through interviews where I was given a simulated work item and told to produce code for it on the spot. Some of it had to do with the actual markup needed to display the data. (This was before MVC days, WebForm stuff) The people were far more impressed that I was typing out the mark up than if I had just done drag and drop stuff. Why? Because there is a stigma, fair or not, that drag and drop people are displaced VB Weenies, and the real programmers don’t bother with it. Knowing how to hand code mark up on the spot is far more impressive than using visual tools or completely blanking out because you’ve had to rely on third party software.

At this point I realize I’ve mostly talked about markup, but this whole idea extends to a lot of the programming world. Digging in and forcing yourself to do the work will substantially improve you abilities over time. If you can’t do this at work then find some time on your own to work on a side project to learn. Build your own error handling system. Build your own pager creating method. Build your own Url creating method for MVC. I promise that you will be in a much better position.

Final Note

You could argue that coming to a site like this and using copy/paste is against my spiel. Fact is, I’ve copy and pasted plenty of code to get to where I want to go. Difference between this and third party tools is you can learn from what you copy and paste. Actually I would argue that you have the responsibility to learn about what you are copying before you do anything with it. If you copy AND you take time to understand what you are copying, that can be just as helpful. If nothing else, it’s better than just using some third party method.

ASP.Net MVC: Attibute to Check if Route Value Exists and… and Means Something!

Get ready for a roller coaster ride around the insanity that is me. You might actually find it amusing but most likely you’ll just leave sick or underwhelmed. Don’t feel bad if you do, you wouldn’t be the first and, thanks to somehow being impervious to Natural Selection, you won’t be the last. Be proud.

Here’s what this post is about: Say you have a url like eh:

/User/View/1

Where 1 represents a UserId to a user that exists in some matter of context. (Does that makes sense?) Well there are a couple of things that could go wrong here. For one, if you don’t want to have a nullable id in your signature:

  public ActionResult View(Int32? userId)

This could cause ouch:

/User/View/

But this problem is deeper. Much deeper. In fact so deep it deeper than even Piper Perabo has ever deeped before. Yrraaaahh!

What if the id doesn’t even refer to anything? Say the id is 101 but there’s no user with the id of 101? Beyond that, what if the id could be Id in some routes but UserId in others? WHAT WOULD YOU DO???

The idea here is to have something neato like this:

  [UserExistsById]
  public ActionResult View(Int32 userId)

And if that id is junk, then you redirect to an error page. Well if this sounds interesting, I’d be surprised, but read on in the event that it does.

Now this isn’t accomplished in the most simple manor, but for good reason: The more time in means the less time repeating. First method we need is something to simply check the route data to see if something exists:

  public static Boolean RouteDataValueExists(ActionExecutingContext filterContext, String idToCheck)
  {
    return filterContext.RouteData.Values.ContainsKey(idToCheck);
  }

Real easy. It either has been digested by MVC and regurgitated into some kind of route value or it hasn’t. Basically this is the first check. After all, if it doesn’t exist why bother going further?

Next is the method that will be calling this one. Mainly one that uses the RouteDataValueExists and if returns true, then it actually checks the value against where ever the user is persisted.

  public static Boolean ValueFoundAndItemExists
  (
    ActionExecutingContext filterContext,
    Enum idToUse,
    Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,
    Func<Int32, Boolean> exists
  )
  {
    Boolean checksOut = false;
    String convertedId = idToUse.ToString();

    if (RouteDataValueExists(filterContext, convertedId))
    {
      checksOut = check(filterContext, idToUse, exists);
    }

    return checksOut;
  }

Ok so kind of a lot at first and it’s hard to decide how to present this system, so just go with it.

  Enum idToUse,

This is a design choice. In reality this will be turned into a string anyhow, but the idea is it will be what to check the route values for. So if you are checking for UserId, you will pass in UserRequestTypes.UserId. Again this was a choice on my part as I hate passing text around.

  Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,

This is the method that will be used by ValueFoundAndItemExists to delegate out the actual checking if the id is an integer and is a real user.

Func<Int32, Boolean> exists

This will be the method that you will use to delegate the whole checking if it exists in the database. Something like:

  class User
  {
    public Exists(Int32 id)
    {
       return EntityContext.Context.User.Any(user => user.Id == id);
    }
  }

Still with me? No? Greeeeat. Next up is the base class that contains the

  Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,

parameter from above.

public abstract class BaseExistsAttribute : ActionFilterAttribute
{
  protected Boolean Exists
  (
    ActionExecutingContext filterContext,
    Enum idToUse,
    Func<Int32, Boolean> exists
  )
  {
    Int32? id = Convert.ToString(filterContext.RouteData.Values[idToUse.ToString()]).ConvertTo<Int32>();
    return id.HasValue && exists(id.Value);
  }
}

Ok so something might look familiar like well basically all the parameters. The reason for this is that there is a little bit of delegate passing going on with this whole system. One method passes on methods to other method in some kind of crazy method hoe down without the flanel shirts.

You will notice the use of the enum in this part:

  idToUse.ToString()

Again, you can easily just pass in a string instead of an enum, I just did this to stay away from strings.

Only thing that might be of interest is the ToConvert method that you can find here. You don’t have to use it, you can simply just do a try parse on the

  filterContext.RouteData.Values[idToUse.ToString()])

To get an integer. That’s up to you. I could have just put that in the code for you to see but then I couldn’t randomly plug another post of mine.

Finally you have the actual attribute class:

  [AttributeUsage(AttributeTargets.Method)]
  public class QuoteExistsByQuoteId : BaseExistsAttribute
  {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      base.OnActionExecuting(filterContext);

      if
      (
        !MvcMethods.ValueFoundAndItemExists
        (
          filterContext,
          UserRequestTypes.UserId,
          Exists,
          UserEntity.Exists
        )
      )
      {
        filterContext.Result = SiteMethods.ErrorOut(ErrorNames.General_PageError);
      }
    }
  }

And now it all comes together.

  UserRequestTypes.UserId

This is the enum I’ve been talking about this entire post! Now that I think of it, not really exciting.

  Exists

That’s the method on the base class that checks for everything.

  UserEntity.Exists

And that’s the method I need to check the persistence if the user is real. Remember? Takes in an integer and returns a boolean? Yes? Yes? No?

What’s ErrorOut? Again this is just a method I made to create an ActionResult that is an redirect to an error page. Not hugely important. It’s just what handles the situation when the value is bogus…. dude.

  [UserExistsById]
  public ActionResult View(Int32 userId)

And there you have it. Hopefully it was useful in some way but I’m not of touch with reality.

jQuery: Find All Checked Checkboxes

So this is sort of a repeat of another post, but I figured it has some use on its own.

Say you have this:

  <div>
    <input type="checkbox" name="JqueryIdList" value="1"  />
    <input type="checkbox" name="JqueryIdList" value="2" />
    <input type="checkbox" name="JqueryIdList" value="3" />
    <input type="checkbox" name="JqueryIdList" value="4" />
  </div>
  <div onclick="getIds('JqueryIdList');">
    CLICK
  </div>

And you need the getIds method to find all the checked checkboxes from that markup. Well it’s actually fairly simple, or at least it wil be once I enlighten you. I should get paid for this…

  function getIds(checkList)
  {
    var idList = new Array();
    var loopCounter = 0;
    //find all the checked checkboxes
    jQuery("input[name=" + checkList + "]:checked").each
    (
      function()
      {
        //fill the array with the values
        idList[loopCounter] = jQuery(this).val();
        loopCounter += 1;
      }
    );
    ...
  }

The important part is this:

 jQuery("input[name=" + checkList + "]:checked").

As you can see, it is very simple. Give it the name of the checkboxes, add on the “:checked” and boom you have a list of checked checkboxes. Could it be more simple? I think not.

jQuery, Hidden Elements, and Why At Times I Hate It

So this is your situation, or at least it might be someday if you use jQuery:

You have a comment area that allows a user to view comments. Now this comment area is created using javascript (Read jQuery) only. When a user clicks on some kind of pager, a method is called to get a list of comments and recreate the comment table. Now you would think it would be a good idea to hide the table, recreate it, and then show it. Sounds like a decent way to go. So you try something like this:

  ...

  jQuery(commentTable).hide("slide", { direction: "up" }, 200 );

  ...

  //Get the comments and call a method to build the table.

  ...

  function buildTable(commentList, commentTable)
  {
    ...

    //Take the list and iterate.  Create a row

   ...

     jQuery(commentTable).appendChild(someCreatedDivRowWithAComment)  //BOOM

   ...
  }

Then you run it and bam you get an error saying that basically commentTable doesn’t exist. Now if this were WebForms and you did some kind of visible=”false” you would know that the markup for that table wouldn’t exist. However, in javascript style=”display:none;” doesn’t remove the element from the markup, it just hides it from the viewer. If you look at the source (Provided it’s not dynamically created) you will still see it in the mark up. So what’s the deal?

Well for some reason the creators of jQuery decided that there is a difference between a hidden element and a non hidden element to the point where you have to change your search (the jQuery() method is basically a search that looks for the element within the parenthesis) by adding on a “parameter”.

  jQuery(".someElement:hidden")

So if you do use the hide() method (Or fadeOut for that matter) you have to use the :hidden addon to find the stupid element. This can cause a big problem when things aren’t timed correctly. What does that mean? Well that 200 value I have in the hide method, that’s the time I want it to take to hide the element. Far as I can tell, and I’ve done some testing on this, the element is not :hidden until the animation completes. Which means there are 200 time units where it is not :hidden. Now if the time that it takes to get your comment list and start building the table is less than the time it takes to hide the element you’ve got an issue. Or conversely, if the 200 time units are up and it is now hidden, you’re really screwed because the normal search won’t work. You can try something like this:

   if(jQuery(this).children(".categoryBlockContainer").is(":hidden"))
  {
    categoryBlockContainer = jQuery(this).children(".categoryBlockContainer:hidden");
  }
  else
  {
    categoryBlockContainer = jQuery(this).children(".categoryBlockContainer");
  }

And this works ok most of the time, but you still might run into a situation where it’s still trying to finish the hide animation. Beyond that, it seems kind of asinine to have something like that in the code. It should find the element at all times, hidden or not.

This really kills the whole idea of animation.

Between this and javascript’s bizarre variable scope, I’ve had some thoughts of changing my profession.

ASP.Net MVC How To Handle Multiple Checkboxes With Views/Actions… jQuery too!

Just a note, this is kind of an add on to this post but it’s a much more simple (HOSTED) example and also deals with doing the whole check box thing with jQuery.

So one of the things I ran into some what recently was a grid… a grid with a death wish and a thirst for revenge. It also has a bunch of check boxes to allow multiple row deletes.

Now there might be a moment of panic and doubt (Or doubt and panic, everyone reacts differently) when you realize you no longer have those cushy grid postback events. WHAT ARE YOU GOING TO DO???? Well first you’re going to feel disgust over your profuse sweating, cause lets be honest you’re pretty gross. Then you’re going to read on and find that all your panic, fun as it can be, was for nothing. Why? Because you have me… and not in some weird love kind of way because I don’t even know you. More of a “You can count on me because I’m like that cool older brother you never had and because of which you ended up a social degenerate ie a programmer” kind of way.

Now to start I’ve already hosted both the code and a working example:

Actual running thing on teh webz.

Hosted code

Because I’m such a nice guy. (And that’s true, I can list at least five people who aren’t my mom who can attest to that.) However, I wouldn’t be the nice guy that I am if I weren’t going to at least explain some of the code.

There are two ways I handle this situation in the example I hosted, one is with a form, action, and post back. The other is with jquery and an asynchronous call. Both are actually pretty easy to pull off.

First let’s look at the post back version. The mark up looks a little somethin’ like dis:

  <form action="/Test/CheckForIds/" method="post">
    <div>
      <input type="checkbox" name="IdList" value="1"  />
      <input type="checkbox" name="IdList" value="2" />
      <input type="checkbox" name="IdList" value="3" />
      <input type="checkbox" name="IdList" value="4" />
    </div>
    <div>
      <input type="submit" value="go" />
    </div>
  </form>

Looks like your standard form and if you’ve used MVC at all, you should be used to seeing something like that. The only thing of interest is that the checkboxes don’t have ids and do share the same name. There’s a good reason for the second one. Here’s the action method:

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult CheckForIds(Int32[] idList)
  {
     return View(idList);
  }

Now it makes more sense, doesn’t it? The name attribute on the checkbox directly corresponds to the name of the array parameter. THAT’S AMAZING!!!1 Actually, kidding aside it is kind of nice. Not only does it match the checkboxes to the parameter, it also treats the values of the checkboxes (Checked ones) as a list of integers. Pretty slick.

And honestly, that’s about all it takes for traditional posting.

Now for the jQuery part:

  <div>
    <input type="checkbox" name="JqueryIdList" value="1"  />
    <input type="checkbox" name="JqueryIdList" value="2" />
    <input type="checkbox" name="JqueryIdList" value="3" />
    <input type="checkbox" name="JqueryIdList" value="4" />
  </div>
  <div onclick="getIds('JqueryIdList');">
    CLICK
  </div>

Wow, looks about the same. Go figure. Well that’s pretty much because the way hard part is the javascript itself.

  function getIds(checkList)
  {
    var idList = new Array();
    var loopCounter = 0;
    //find all the checked checkboxes
    jQuery("input[name=" + checkList + "]:checked").each
    (
      function()
      {
        //fill the array with the values
        idList[loopCounter] = jQuery(this).val();
        loopCounter += 1;
      }
    );
    //Send the list off
    jQuery.getJSON("/Test/CheckForIdsJson/", { idList: idList }, idsGotten);
  }

Ok maybe it wasn’t that hard or hard at all. But um… And here’s the action method:

  [AcceptVerbs(HttpVerbs.Get)]
  public ActionResult CheckForIdsJson(Int32[] idList)
  {
    JsonResult result = new JsonResult();
    result.Data = idList;

    return result;
  }

So again, the same signature. Amazing huh?

Side note:

When I was eating this morning in front of the television (Chocolate shredded mini wheats if you must know.) I came upon the good ole classic Iron Eagle. I never really thought about how utterly f-ing insane that movie was until now though, mostly because I haven’t seen it since I was a kid. I guess back then I could completely buy into the idea of some 17 year old, who can’t make it into the Air Force Academy, suiting up and learning to use (At the time) the most complicated fighter the US had to offer within what? one whole montage, steal a 18 million dollar plane (Planes were cheap back then), fly into crazy dangerous territory, get past who knows how many trained professionals, save his dad, and nothing really comes of it. Actually I think if I remember (as I didn’t get to watch the whole thing this time) he gets a place in the academy from this. IT’S A COMPLETELY BELIEVABLE STORY! The best part about it is that apparently between the time of the first and second movie his skills had depleted so fast that he gets popped at the beginning of the second one. I guess without the Saving Dad mojo, he’s just not the same. Tip your glass to good ole Thumper.

I really miss the 80s where movies didn’t really need to make any sense as long as they had some soundtrack filled with crazy obscure bands playing at random times in the movies itself followed by the movie characters commenting how great the music is.

ASP.Net MVC: Multiple Checkboxes and Strongly Typed Views

This might be a first, but I actually stole this from myself off Stackoverflow. Posted it and thought it might be useful to share with the 1 live person who reads this blog and the 90 other bots… And I’m not sure about the 1 live person.

So here’s the situation, it’s late, you’ve got a strongly typed view that has a checkbox list, and you are desperate for an answer on how to handle it…. and now you’re scraping the bottom of the barrel. Well, good news is, I have the answer.

Let’s say you have a Book class that has a list of Categories. The Category class is simple, just has an id and name.

  public class Book
  {
    public Int32 BookId { get; set; }
    public IList<Category> Categories { get; set; }
  }

  public class Category
  {
    public Int32 Id { get; set; }
    public String Name { get; set; }
  }

Now you could try and figure out a way to create a typed view using the Book class. You could also stomp on your left foot until it bleeds. Who am I to judge you for liking pain? (Sick f—) For those who don’t want to go through that nightmare, I have an alternative: Create two new classes, one to set the view and one to handle the post back.

public class ViewBookModel
{
  public ViewBookModel(Book book, IList<Categories> categoryList)
  {
    BookId = book.Id;
    CategoryList = categoryList;
  }

  public Int32 BookId { get; private set; }
  IList<Categories> CategoryList { get; set; }
}

First the class to set the view. As you can see, there is a book id that corresponds to a book object’s id (DUH) and the category list which you will set in the original action.

  [AcceptVerbs(HttpVerbs.Get)]
  public ActionResult EditBook(Int32 bookId)
  {
     Book foundBook = Book.GetById(bookId);
     IList<Category> categoryList = Category.GetAll();
     ViewBookModel model = new ViewBookModel(foundBook, categoryList);
     return View(model);
  }

And then your markup for the checkbox list will be something like this:

  <%
    foreach(var category in Model.CategoryList)
    {
  %>
      <input type="checkbox" name="CategoryIds" value="<%= category.Id %>" />
  <%
    }
  %>

Notice that the name for every input is CategoryIds. This is because this will be the name of the collection of ids on the model for posting:

  public class ViewBookInModel
  {
    public String BookId { get; set; }
    public Int32[] CategoryIds { get; set; }
  }

And the action method would look like:

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult UpdateBook(ViewBookInModel book)
  {
    foreach(Int32 id in book.CategoryIds)
    {
      ...
    }
  }

And boom, problem solved. You can now use a strongly typed View with a checkbox list. Go forth and be fruitful.

ASP.Net MVC: PhotoView Lessons – Getting Around A Master Page Model

Original About PhotoView Here

I’ve started to take the PhotoView site and move it toward a full blow site application. Not sure why, but then again why shouldn’t I? Don’t have a good reason? Pbbbbbbtttt jog off.

One thing I ran into yesterday while working on it, as I’ve added authentication to the site (An update I’ll post sometime this week I think), is having a menu show or not show based on the user being logged in or and admin or whatever. What I don’t like doing is having to call methods from the “framework” if I can just add a property to a model. There are various reasons why, ranging from the fact mark up errors don’t blow up compile time to the idea that the model should take care of those things. Now you can’t always follow this rule as it’s obvious I use the CreateUrl method like it’s a bat in a shed. (I have no idea what that means) However, a certain amount of lock down is nice and the Create method is an extension method so it doesn’t look like I’m cheating… Am I right?

So here’s the situation, I would like to have a model that has two properties UserIsLoggedIn and UserIsAdmin so I can do magic like:

  <%
    if(Model.UserIsAdmin)
    {
  %>
      <a href="Admin/DoStuff" > Admin Stuff </a>
  <%
    }
  %>

Now this would seem to be simple, you would think having the master page inherit from the generic version of ViewMastePage:

  Inherits="System.Web.Mvc.ViewMasterPage<SomeModelClass>"

And the class would be something like this:

  public class SomeModelClass()
  {
    public Boolean UserIsAdmin { get; set; }
    public Boolean UserIsLoggedIn { get; set; }
  }

And the flowers would bloom, the sun would shine, and dogs and cats would live in harmony. And it works that way up until you actually run any given page with a strongly typed view. Then you get this error:

Sorry bro, but you need a hella cool model that is all like “Hey mom” to SomeModelClass.

I think I’m paraphrasing a bit but the idea to take from this is that all view models will have to inherit from the same model the master page is using. Yeah, basically a bit “go f— yourself” written into MVC. So either you follow this obviously easy and unhindering design choice or you do what all programmers must do at some point: Compromise. And I mean that in the real sense, not the in the relationship, better to bend than break even though you’re already broken sort of way.

Remember that little bit of self comfort I gave myself for the HtmlHelper extension CreateUrl, well it’s time to do that once again. So in a He’s Just Not That In To You sort of way (Yes I saw that movie. That’s the other version of compromise), I’m going to tell myself that it’s ok and that though it may be bad for most situations, I’ve heard that Sally’s friend in New York who is a programmer got away with it so I’ll most like get away with it too.

  public static class ViewMasterPageExtension
  {
    public static String CurrentUrl(this ViewMasterPage page)
    {
      return SiteMethods.GetCurrentUrl();
    }

    public static Boolean UserIsAdmin(this ViewMasterPage page)
    {
      return State.CurrentUser != null && State.CurrentUser.UserType == PhotoViewUserType.GetAdminType();
    }

    public static Boolean UserIsLoggedIn(this ViewMasterPage page)
    {
      return State.CurrentUser != null;
    }
  }

Yes it’s not on a model, yes it’s a work around, but I’d rather do this:

  if(this.UserIsAdmin())

Than this:

  if(State.CurrentUser != null && State.CurrentUser.UserType == PhotoViewUserType.GetAdminType();)

And in the end, isn’t what make my life easier the main goal of existence?

Is it me or does Sam Neil look beyond creepy in this imdb photo?

ASP.Net MVC: Show Picture Dynamically Using jQuery

Ready for the next step to this guy? Can’t sleep lately because of it? Ignoring your day to day tasks due to anticipation? Well wait no longer. I have just the cure for you. In fact, steady use has shown to improve both self esteem and popularity. Behold Jquepictuax:

function showPicture(imageHolder, id)
{
  jQuery(imageHolder).attr("src", "/Photo/ShowPhoto/" + id);
}

And you can’t forget to try:

<img id="holder" alt="" />
<div onclick="showPicture('#holder', '79');">Show!</div>

And with that your life will be far better than it was before. You can once again start enjoying the simple things in life. Enjoy the birds singing, the sun setting, and those noisy little things that run around your house.

Disclaimer: Id may vary. Image results also very. Though proven to be better when tested again a placebo, Jquepictuax may not improve your self esteem or make you more popular. Jquepictuax is not guaranteed to improve your life in any way. Use Jquepictuax in small quantities. People with low blood pressure or who are pregnant should avoid using Jquepictuax. If you consume more than 3 alcoholic drinks per day, please seek medical attention before use. May cause certain side effects such as dizziness, nausea, overwhelming chills, headaches, muscle soreness, dry mouth, light headedness, sleepiness, drop in appetite, and death. If you notice any these side effects, stop use of Jquepictuax immediately and seek medical attention. Please consult physician before Jquepictuax use.

You happiness is right around the corner, why not turn it with Jquepictuax?

ASP.Net MVC: Upload Image to Database and Show Image “Dynamically” Using a View

Oddly enough this came about from me wanting to do this, figuring it out, and then deciding not to bother with it. So there’s a possibility this will happen to you too. Well that’s not completely true. The first half where I was uploading and showing from a database, but showing an image through a view to mimic the .ashx functionality of WebForms is still pretty useful.

Saving the Image

First off, here’s the look of the table:

Table

So pretty simple table. Most important parts are the ImageData and ContentType. Why? Well let’s look at the action needed to save the image:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload(PhotoForSingleItem photo)
{
  //PhotoForSingleItem is just a class that has properties
  // Name and Alternate text.  I use strongly typed Views and Actions
  //  because I'm not a fan of using string to get the posted data from the
  //  FormCollection.  That just seems ugly and unreliable to me.

  //PhotoViewImage is just a Entityframework class that has
  // String Name, String AlternateText, Byte[] ActualImage,
  //  and String ContentType
  PhotoViewImage newImage = new PhotoViewImage();
  HttpPostedFileBase file = Request.Files["OriginalLocation"];
  newImage.Name = photo.Name;
  newImage.Alt = photo.AlternateText;

  //Here's where the ContentType column comes in handy.  By saving
  //  this to the database, it makes it infinitely easier to get it back
  //  later when trying to show the image.
  newImage.ContentType = file.ContentType;

  Int32 length = file.ContentLength;
  //This may seem odd, but the fun part is that if
  //  I didn't have a temp image to read into, I would
  //  get memory issues for some reason.  Something to do
  //  with reading straight into the object's ActualImage property.
  byte[] tempImage = new byte[length];
  file.InputStream.Read(tempImage, 0, length);
  newImage.ActualImage = tempImage ;

  newImage.Save();

  //This part is completely optional.  You could redirect on success
  // or handle errors ect.  Just wanted to keep this simple for the example.
  return View();
}

And here’s the mark up to get this ball a rollin’:

<form method="post" enctype="multipart/form-data" action="Photo/Upload">
  <div>
    <span>
     Name:
   </span>
   <span>
     <input type="text" id="Name" name="Name" />
   </span>
  </div>
  <div>
    <span>
      Alternate Text:
    </span>
    <span>
     <input type="text" id="AlternateText" name="AlternateText" />
    </span>
  </div>
  <div>
    <span>
      Image
    </span>
    <span>
      <input type="file" id="OriginalLocation" name="OriginalLocation" />
    </span>
  </div>
  <div>
    <input type="submit" value="Upload" />
  </div>
</form>

Biggest thing to notice in the markup is the enctype=”multipart/form-data”. This is a must to upload images. It was something I was missing originally and annoyed the hell out of me.

Showing the Image

So now that we have a we to upload the image, how the hell do you use it? Well that’s not too hard. It just involves a new type of result, an action, and an img element.

So the first thing you need is an image result, and in using my superior intellect I came up with such a thing. And by superior intellect I mean I used StackOverflow. Oddly enough though, it’s actually the second post that I got it from and I changed it a little. However, it was very useful.

using System.Web;
using System.Web.Mvc;
using System.IO;

public class ImageResult : ActionResult
{
  public String ContentType { get; set; }
  public byte[] ImageBytes { get; set; }
  public String SourceFilename { get; set; }

  //This is used for times where you have a physical location
  public ImageResult(String sourceFilename, String contentType)
  {
    SourceFilename = sourceFilename;
    ContentType = contentType;
  }

  //This is used for when you have the actual image in byte form
  //  which is more important for this post.
  public ImageResult(byte[] sourceStream, String contentType)
  {
    ImageBytes = sourceStream;
    ContentType = contentType;
  }

  public override void ExecuteResult(ControllerContext context)
  {
    var response = context.HttpContext.Response;
    response.Clear();
    response.Cache.SetCacheability(HttpCacheability.NoCache);
    response.ContentType = ContentType;

    //Check to see if this is done from bytes or physical location
    //  If you're really paranoid you could set a true/false flag in
    //  the constructor.
    if (ImageBytes != null)
    {
      var stream = new MemoryStream(ImageBytes);
      stream.WriteTo(response.OutputStream);
      stream.Dispose();
    }
    else
    {
      response.TransmitFile(SourceFilename);
    }
  }
}

And here’s how you use the actual result.

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ShowPhoto(Int32 id)
{
  //This is my method for getting the image information
  // including the image byte array from the image column in
  // a database.
  PhotoViewImage image = PhotoViewImage.GetById(id);
  //As you can see the use is stupid simple.  Just get the image bytes and the
  //  saved content type.  See this is where the contentType comes in real handy.
  ImageResult result = new ImageResult(image.ActualImage, image.ContentType);

  return result;
}

And the markup would go a little sumthin’ like dis:

  <img src="/Photo/ShowPhoto/1" alt="" />

And now you too can upload an image to a database, show it, and then decide just to physically host the images anyway. Next post will be about how to use this with jQuery and asynchronously. I bet you can’t wait!

jQuery: Holy Smokes I Like This Link

Good old Stackoverflow. Wasn’t sure how to post this without looking like I’m trying to get search engine hits. However, wanted to pass this one on anyhow.

How to center a div using jQuery.

Have used it. Works brilliantly. Although the:

  this.css("position","absolute");

May be overkill since any “pop up” div I create already has that in the style where personally I think it should be.

How does it work? Well break down the “top” part:

  this.css("top", ( jQuery(window).height() - this.height() ) / 2+jQuery(window).scrollTop() + "px");

To

   jQuery(window).height() - this.height() ) / 2

But why not just divide the height by 2? Well say the height of the window is 800 and your item is 600 high. If you just placed the item at 800 / 2, the bottom of the item would end up 1000. (800/2 = 400… 600 tall item + 400 starting point = 1000). So subtracting the item’s height from the window height and THEN dividing by two ensures that that item, provided it is no taller than the window, will end up within the 800 tall window.

  + jQuery(window).scrollTop()

Now what if the user has scrolled the widow down? Well adjust for that. using the scrollTop(), the item can be started at the correct point adjusted with the scroll. Nice huh?