ASP.Net MVC: Button Post Is Losing QueryString Values And Getting Paramters From A URL

I was going to start this post with a rousing ARE YOU READY FOR SOME PROGRAMMING?, but my lawyer suggested it might cause the NFL to take action against me. He suggested something more simple like PROGRAMMING HAPPENS HERE! since he had high doubts the NBA will sue me. After all they’d have to admit they actually came up with that f-ing slogan in the first place. It’s a win/win situation for me.

So one of the things I’ve run into with MVC is this situation… Say I have a form and a button, and the form has an action that looks like this:

  <form action="/Tools/AddTool/1?redirect=/Tools/ViewTool/1" method="post">
    < button type="submit">GO!</button>
  </form>

Really simple. The idea is that I want to post to the AddTool action, do some stuff, then have the action redirect back to the ViewTool action. Seems like it should be easy right? Well not so much. Because when you view the ActionParameters (Like in this example) for the “redirect” key, it finds the key but loses the value. This may result in a failure if have an attribute making sure it exists or possiblly you just have it set to a default that’s useless like a fourth foot. Either way, not good.

Now I haven’t figured out the reason for this (Don’t act so surprised, you aren’t a very good actor), but I have figured out a way around it. Basically for the form to keep the values, you need to add hidden values. I know, it’s a pain. Good thing I have a method that makes it easier. Also, this post is a prerequisite for a method I have for creating buttons… but that in the future. ITS A TEASER! THIS POST IS A TEASER! THERE I SAID IT! CAN I GO NOW?

public static String CreateHiddenValuesFromUrl(String baseUrl)
{
  StringBuilder html = new StringBuilder();

  if(!String.IsNullOrEmpty(baseUrl))
  {
    //Have to find the ? to know where to begin
    Int32 indexOfQuestionMark = baseUrl.IndexOf('?');

    //If the question mark exists and there is something after it, keep going
    if (indexOfQuestionMark > -1 && baseUrl.Length >= indexOfQuestionMark + 1)
    {
      //Get everything AFTER the ?, something I didn't think of first time around
      //Caused many test failures and much shame to my family.
      String request = baseUrl.Substring(indexOfQuestionMark + 1);

      //Cut up the string by the & since every parameter after the first
      //is divided by &.. I know, Duh.
      String[] splitList = request.Split('&');

      //Go through the list of possible request items
      foreach (var requestItem in splitList)
      {
        String[] splitItem = requestItem.Split('=');
        //This is to make sure the parameter actually has a value to send in
        //the hidden values.  I supposed you could create an empty hidden
        //value to preserve the parameter, but remember the parameter
        //isn't being lost from the form action, just the value
        if (splitItem.Length == 2 && !String.IsNullOrEmpty(splitItem[1]))
        {
          //Create a hidden input with the key name and the value
          html.Append("<input type=\"hidden\" name=\"" + splitItem[0] + "\" value=\"" + splitItem[1] + "\" >");
        }
      }
    }
  }

  return html.ToString();
}

And it’s just that simple. Mind you I could probably make this an extension method for the HtmlHelper, but I don’t really use it for that.

Next up will be more razzle and dazzle using this to make an optional image button. I bet you can’t wait. I know I can.

ASP.Net MVC: Create a link method… ie JUST GIVE ME THE STUPID URL

One thing that kind of annoys me is the situation where you just want a url, but you don’t want one of the prepackaged links using:

   Html.RouteLink
Or
   Html.ActionLink

Mostly because you want to be able to create your own html and you only want the created url. Well turns out there’s a method for this: The RouteUrl method on the UrlHelper class. Down side is that it’s not static and takes a few lines to use, so not cool UI design side. Well here’s a method that uses that method and gives you a method to exact a method of victory. I think that sentence had promise, but fell short of complete failure.

Anyways, here it is… The “Just give me the stupid url” method, CreateUrl for short.

        public static String CreateUrl
        (
          RequestContext context,
          RouteCollection routeCollection,
          String routeName,
          String controller,
          String action,
          RouteValueDictionary routeValues
        )
        {
            //Create the helper
            UrlHelper neededHelper = new UrlHelper(context, routeCollection);

            //get the route to check what it is holding at far
            //as defaults go
            var neededRoute = (Route)routeCollection[routeName];

            //this might be overkill honestly.  Basically in case the
            //Route contains the "controller" key only then add it to the
            //values for the route.  Otherwise just ignore.  It's possible
            //someone might pass in a controller/action but the route
            //doesn't take them. At which point you'll
            //be showing the "Aw maaaaan" face.

            if (!String.IsNullOrEmpty(controller) && neededRoute.Defaults.ContainsKey("controller"))
            {
                routeValues.Add("controller", controller);
            }

            if (!String.IsNullOrEmpty(action) && neededRoute.Defaults.ContainsKey("action"))
            {
                routeValues.Add("action", action);
            }

            //And then the call to create the url string.
            return neededHelper.RouteUrl(routeName, routeValues);
        }

And in use View side:

  <a href="
  <%
  CreateUrl
  (
    Html.ViewContext.RequestContext,
    Html.RouteCollection,
    GeneralConstants.RouteDefault,
    "SomeController",
    "SomeAction",
    new RouteValueDictionary { { "id", 1 } }
  )
  %>"
  >
  Something is linked
  </a>

Now mind you I did use a link there so it seems like a silly example. However, you can do many other things now that you just have the url itself.

Paging and the Entity Framework, Skip, and Take Part 4

Get the total count of pages. | Get the real page number. | Using Skip and Take to Page | The Actual Paging Controls

Now onto the fourth part of this epic saga that George Washington once called, “The most astounding exercise in futility”

Ok so let’s say you have a grid, items to fill it with, and four buttons. Each button has a direction, say one back, all the way back, one forward, all the way forward. No big deal. Now you want them to page correctly when used. After all, it’s always a bonus when things go right. First you need to set the CommandArguments on the buttons themselves to whatever page they are responsible for.

private void SetAndBind(Int32 pageNumber)
{
  Int32 realPage;
  Int32 totalCount;

  IList<ToolItem> inviteList =
    ToolClass
    .GetSomeTools("Sean", 20, pageNumber, out realPage, out totalCountOfPages);

  btnFullBack.CommandArgument = Convert.ToString(0);
  btnOneBack.CommandArgument = Convert.ToString(realPage - 1);
  btnOneForward.CommandArgument = Convert.ToString(realPage + 1);
  btnFullForward.CommandArgument = Convert.ToString(totalCountOfPages);

  BindGrid(inviteList);
}

First off, GetSomeTools is just a method that is the same as I presented in the third installment of this epic saga that George Washington once called, “The most astounding exercise in futility”. If you’ve been reading up to this point, then you’ll know that. If not, you might have some reading to do.

So, here’s a simple method used to get the info we need (using the page number) and set the buttons. As seen before, realPage is the actual possible page (In case someone passed in page 21 when there are only 20 pages) and totalCountOfPages gives us how many possible pages there are. This makes setting the button CommandArguments cake. Now for the button event:

  private void btnPaging_Click(Object sender, EventArgs e)
  {
    SetAndBind(Convert.ToInt32(((Button)sender).CommandArgument));
  }

And then you just set all the click events to that:

  btnFullBack.Click += btnPaging_Click;
  btnOneBack.Click += btnPaging_Click;
  btnOneForward.Click += btnPaging_Click;
  btnFullForward.Click += btnPaging_Click;

And boom, you’re pretty much set.

Paging and the Entity Framework, Skip, and Take Part 3

Get the total count of pages. | Get the real page number. | Using Skip and Take to Page | The Actual Paging Controls

Ok so the last two posts have been arguably useless, maybe more so than anything else here, but they were somewhat needed because now I am going to show how to Linq, the Entity Framework, and well that’s it I think.

public static IList<ToolItem> GetSomeTools(String name, Int32 numberToShow, Int32 pageNumber, out Int32 realPage, out Int32 totalCountOfPages)
{
  //EntityContext.Context is just a singletonish version of the
  //Entities class.  Most people would use
  //  using (ToolEntities context = new ToolEnties())
  Int32 totalCount = EntityContext.Context.ToolItems
		   .Count(item => item.Name == name);
  //This is the method from the first post of this series
  //Just getting the count of pages based on numberToShow and
  //item totalCount
  totalCountOfPages = TotalCountOfPages(totalCount, numberToShow);
  //This is the method from the second post of this series
  //Basically getting the best possible page if the page number
  //is higher than the totalCountOfPages or lower than 0
  realPage = GetRealPage(totalCountOfPages, pageNumber);

  returnValue = EntityContext.Context.ChatRooms
			  .Where(item => item.Name == name )
			  .OrderBy(item => item.Name)
			  .Skip(numberToShow * realPage)
			  .Take(numberToShow)
			  .ToList();

  return returnValue.ToList();
}

Really simple yes? It follows like this:

Say I’m on page 1, which for this would be zero or pageNumber – 1. So I want to grab the first 20 items from the database. Well that means I want to start at 0 and grab 20. Now if you want this all to be done with some kind of conditional thing that either handles the first page or the other pages, you actually want to skip the same way no matter what the page number is. This is taken care of by numberToShow * realPage since even at 0 this works. After all 0 * anything is 0 and therefore you will be Skipping 0 items. So in other words, you’re at the start. Next you want to Take the amount of items you need, which is 20. Next time around you’ll start at 20 Skip(numberToShow 20 * realPage 1) and take the next 20. Nice thing is, even if you say Take 20 and there are only 2 left, it doesn’t care. It will just grab those two.

And there you have it, how to page with the Entity Framework and minimal amount of work. I know I hate taking other people’s methods (Like the TotalCountOfPages and GetRealPage methods), don’t know why. So sorry if I am forcing you to do so. However, the two methods I gave are semi important to this.

You might wonder why realPage and totalCountOfPages, well this is useful stuff when knowing what page is next for paging controls. Next post I’ll show those off but I’ll warn you, they are nothing spectacular.

Paging and the Entity Framework, Skip, and Take Part 2

Get the total count of pages. | Get the real page number. | Using Skip and Take to Page | The Actual Paging Controls

So in part one I posted the method to find the total count of pages you’ll need so that you don’t go too far while paging. Now it’s about trying to get the best possible page number despite what’s passed in.

Here’s the situation, when you are paging up or down, you want to make sure you don’t go lower than 0 or higher than whatever the total count of pages is. Sometimes though, things go wrong. They go very wrong. It’s possible that your ui design will allow for any number to be passed in as the page number (Too many reasons this could happen to bother with). Say you have only 10 possible pages but the number 12 gets passed in. Well you either allow it to grab a non existant page 12 or you have a method to determine the best possible choice at this point (10). Turns out it’s idiot simple… what? Were you expecting anything different?

public static Int32 GetRealPage(Int32 totalCountOfPages, Int32 pageNumber)
{
  //pageNumber and totalCountOfPages have to be above 0 or problems
  if (pageNumber > 0 && totalCountOfPages > 0)
  {
    //If page number is higher than the possible count of pages,
    //then you just need the total count to be the new page number...
    //but there's one more step
    pageNumber = totalCountOfPages < pageNumber ? totalCountOfPages : pageNumber;
    //If by chance the pageNumber now is the same as totalCountOfPages
    //(Meaning it was larger than totalCountOfPages originally)
    //1 has to be subtracted to make sure it's inline with a 0 based system where
    //page 1 is actually 0.  This will make more sense when using skip and take in
    //the next post.
    pageNumber = totalCountOfPages != pageNumber ? pageNumber : totalCountOfPages - 1;
  }
  else
  {
    pageNumber = 0;
  }

  return pageNumber;
}

Ok so I’m going to claim this is amazing stuff, but it will come in handy with the next post.

Paging and the Entity Framework, Skip, and Take Part 1

Get the total count of pages. | Get the real page number. | Using Skip and Take to Page | The Actual Paging Controls

So something I’ve been doing a lot of lately is making quite possibly the best thing ever: String cheese wrapped in turkey bacon. But when I’m not doing that, I am working with a lot of ListViews and the entity framework. Now I know there are “built in” paging controls but I just haven’t liked what I’ve seen. So I took it upon myself one day to develop a repeatable system for paging. Say you have users and a bunch of invites that are attached to the users. You want to show a list of invites for a particular user, but you want a ListView that doesn’t show every invite… ie you need a pager. Well just so happens I have a solution, but as always you should consult a doctor before use.

First off you need a method to get the total count of pages meaning what the ceiling is when you page upwards. After all, if you go over the possible count of pages, you’ll just get no items returned and look kind of dumb.

There are three situations you have to look out for: You have less items that the required items per page (Say 10 rows but you display 20 row per page), you have a perfect division (20 rows and 20 row per page or 40 rows and 20 rows per page, ect), you have an uneven division (21 rows and 20 rows per page). First two are easy, third isn’t hard exactly but there are some catches.

public static Int32 TotalCountOfPages(Int32 rowCount, Int32 neededPageSize)
{
  Int32 returnValue;
  if(rowCount > 0)
  {
    if (rowCount <= neededPageSize)
    {
      returnValue = 1;
    }
    else
    {
      if ((rowCount % neededPageSize) == 0)
      {
        returnValue = rowCount / neededPageSize;
      }
      else
      {
        Decimal convertedPageSize =
         Convert.ToDecimal(neededPageSize);
        Decimal convertedRowCount =
         Convert.ToDecimal(rowCount);
        Decimal resultRounded =
          Math.Round(convertedRowCount / convertedPageSize);
        Decimal resultNonRounded =
          convertedRowCount / convertedPageSize;

        if (resultRounded < resultNonRounded)
        {
           returnValue =
            Convert.ToInt32(resultRounded + 1);
        }
        else
        {
           returnValue =
            Convert.ToInt32(resultRounded);
        }
      }
    }
  }
  else
  {
    returnValue = 0;
  }
  return returnValue;
}

Ok so first off, I assume this one is pretty obvious:

  if(rowCount > 0)

If there aren’t any rows, the there can’t be a page count.

Next take care the less rows than being shown per page:

  if (rowCount <= neededPageSize)
  {
    returnValue = 1;
  }

Simple enough. Now for the second part, a perfect division between rows and rows to show:

 if ((rowCount % neededPageSize) == 0)
 {
    returnValue = rowCount / neededPageSize;
 }

Basically, for those who don’t know mod or the % operator, that means there is no remainder. If there were, the result of rowCount % neededPageSize would not be 0 since Mod basically means “Give me what’s left over when I divide something by something else.”

Ok, this is where it gets a little messy as I have yet to find a good way to round a number up since, far as I know, there’s no way to do it with the .Net lib’ary. So, I had to come up with something clever… and when that failed I came up with this:

 Decimal convertedPageSize =
    Convert.ToDecimal(neededPageSize);
 Decimal convertedRowCount =
    Convert.ToDecimal(rowCount);
  Decimal resultRounded =
    Math.Round(convertedRowCount / convertedPageSize);
  Decimal resultNonRounded =
    convertedRowCount / convertedPageSize;

  if (resultRounded < resultNonRounded)
  {
      returnValue =
          Convert.ToInt32(resultRounded + 1);
  }
  else
  {
     returnValue =
       Convert.ToInt32(resultRounded);
  }

Ok so what’s going on here? First off, because trying to divide an integer by an integer gives me an integer, I had to covert some stuff to decimal. Why is that? When I divide them, I need to know if the number after the decimal is between 1 and 1.5 since Math.Round will round down in that case killing my ability to tell if I have enough pages.

Example: 19 rows and 10 per page will give me a 1.9 which Round will make 2. This is perfect since I need two pages to show the 19 rows. What if I have 14 rows and 10 per page? I get 1 from rounding. Uh oh. I really need two pages.

How do I get around this? Get the rounded version and the unrounded version. From there I know that if the unrounded version is greater than the rounded version I need an extra page.

So 14 rows / 10 per page = 1.4 unrounded and 1 rounded. 1.4 > 1, so that 1 page isn’t going to do it. I need to add one more page. Now if it 19 rows/10 per page I’ll get 1.9 unrounded and 2 rounded. 2 pages is exactly what I need and I don’t have to add anything.

Next post I’ll show the next needed method: How to tell if the page number being sent in (From the pager/UI) is actually valid. If not, then grab the last possible amount of records.

Duck Typing my way to a Universal String Convert

So being the beacon of ignorance in the fog of brilliance, I had no idea what Duck Typing was. In short it’s the idea of assuming a class’s type based on the methods it holds.

Say you have 5 different classes, none of which share an inheritance tree. Now let’s say you have a method that takes in any object and uses the SeanIsAwsome method on the object. You could make sure that every object sent in has that method by using an interface that all the objects sent in share.

    public void SomeMethod(ISeanRules inParameter)

What if you want to send in a bunch of objects that don’t share the same interface/base class? Well you base it on what methods the class holds. If the class has the SeanIsAwsome method, then you call it. If not, well you could throw an exception, do nothing, go jogging, eat bacon, ect. That part is up to you.

The problem was that I wanted to create a universal convert that would take in a string and convert it to the 8 billion (ballpark figure) value types in C#. Now what I wanted to do is use the famous TryParse method so my first hope was that TryParse was a method on an interface they all shared. Yeah no. So next thought was to use the Duck Typing principle and say, “Hey jackass, you have a TryParse method? Yeah? Good. Use it.” ‘Course I had to find a way to do that. Turns out it wasn’t too bad.

public static class ConvertFromString
{
  public static T? ConvertTo<T>(this String numberToConvert) where T : struct
  {
    T? returnValue = null;

    MethodInfo neededInfo = GetCorrectMethodInfo(typeof(T));
    if (neededInfo != null && !numberToConvert.IsNullOrEmpty())
    {
      T output = default(T);
      object[] paramsArray = new object[2] { numberToConvert, output };
      returnValue = new T();

      object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);

      if (returnedValue is Boolean && (Boolean)returnedValue)
      {
        returnValue = (T)paramsArray[1];
      }
      else
      {
        returnValue = null;
      }
    }

    return returnValue;
  }
}

A whaaaa?

Ok this might look odd, but it’s really simple. If it doesn’t look odd then chances are you’re smarter than me and you shouldn’t be here anyhow. First part is simple:

  public static T? ConvertTo<T>(this String numberToConvert) where T : struct

Due to this being a extension method (Opps forgot to tell you that part) I have to declare this static method in a static class. Basically I am taking in a string and returning a nullable version of whatever type I specific in the call.

    T? returnValue = null;

    MethodInfo neededInfo = GetCorrectMethodInfo(typeof(T));

Remember that MethodInfo method I had explained in the last post? The next part you might remember too, but I’m not betting on it.

    if (neededInfo != null && !numberToConvert.IsNullOrEmpty())
    {
      T output = default(T);
      object[] paramsArray = new object[2] { numberToConvert, output };
      returnValue = new T();

      object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);

Ok so I have the method info, now I have to create the list of parameters to send in with the invoke. Pretty straight forward. If things went well, returnedValue should be a boolean. However, just incase:

    if (returnedValue is Boolean && (Boolean)returnedValue)
    {
      returnValue = (T)paramsArray[1];
    }
    else
    {
      returnValue = null;
    }

So if the returnValue is true and boolean, then the tryParse was successful. With that in mind, I still have to get the converted value. If it had not been successful than I am just going to return null since this is just meant for converting and not for whether or not it could be. It is just assumed that if it’s null, then it could not be converted at this time.

And now for the use:

  decimal? converted = someString.ConvertTo<decimal>()

An boom, you have a universal convert. YAY!

  using System;
  using System.Reflection;

Convert Enum to Dictionary: Another Silly Method

So what if you want the names and values from an Enum, but wanted them in dictionary form. Well shoot, a little bit of linq and little bit of that and you got this:

public static IDictionary<String, Int32> ConvertEnumToDictionary<K>()
{
 if (typeof(K).BaseType != typeof(Enum))
 {
   throw new InvalidCastException();
 }

 return Enum.GetValues(typeof(K)).Cast<Int32>().ToDictionary(currentItem => Enum.GetName(typeof(K), currentItem));
}

As you might see, pretty simple.

Ok so ToDictionary is kind of odd looking maybe, but really isn’t that big of a deal. Basically it assumes the items in the list are the value, but you need to tell it what the key is. In this case, the int values for the enum are the value for the dictionary where the name that matches said int value will become the key for the dictionary.

So basically, get the values for the enum. Turn that into an IEnumerable list of Int32, create a Dictionary from that.

USINGS!!111

 using System;
 using System.Collections.Generic;
 using System.Linq;

Yeah SessionTryParse

So I got tired of seeing If Session[“SomeKey”] != null… blah blah blah and thought it would be a semi worthwhile task to create a TryParse method because I’m bad like that. Not a Bad Enough Dude to Save the President, but bad.

 public static Boolean SessionTryParse<K&gt;(HttpSessionState session, String key, out K itemToSet) where K : class
 {
     itemToSet = null;

     if (session[key] != null)
     {
        itemToSet = session[key] as K;
     }

     return itemToSet != null;
 }

And for structures… which I have to cheat and only allow them to be nullable.

public static Boolean SessionTryParse<K>(HttpSessionState session, String key, out K? itemToSet) where K : struct
{
     itemToSet = null;

     if (session[key] != null && session[key] is K)
     {
        itemToSet = (K)session[key];
     }

     return itemToSet != null;
}

The idea is simple, pull in the Session, the needed Session key, and something to throw the value in. After that, just check to see if the Session + Key is null and if Session + Key is the same type of said something. That’s how it’s done Detroit greater metropolitan area style… punk.

USE THIS:

   using System;
   using System.Web.SessionState;

Convert a String to a Number String With Linq… YAY

Really stupid little thing I came up with today… but I wanted to use Linq to strip any non number from a string and return the string with only numbers. I told you this was a stupid little thing.

public static String CreateNumberOnlyString(String textToCheck)
{
  String returnText;

  var queryForIntegers = from currentChar in textToCheck
                         where Char.IsNumber(currentChar)
                         select currentChar;

  returnText = new String(queryForIntegers.ToArray());

  return returnText;
}