Child IFrame Page Interacting with Parent Page… Yeah I went there.
File this under "Why?" but I wanted to see if a child could talk to a parent and then receive information back from the parent to update itself with. As usual, my lack of intelligent wording probably has you scratching your head... if you do that. Personally I don't get that expression as when I'm confused I more than likely will grab a jar of peanut butter and start lathering up with it, but to each his own.
So here's the idea, and this post is only the start.
You have a parent page, Parent.htm, with an iframe and you want the parent to do something and alert the child that something happened. For now, it's actually really simple.
On the parent I have a method:
function callMethod(text, methodDelgate) { if (methodDelgate != null) { methodDelgate(text); } }
And this simple markup:
<iframe id="myFrame" src="Child.htm"></iframe>
Wow huh? Well on the child I have this:
function callParent(text) { if (top.callMethod != null) { top.callMethod(text, changeText); } }
This is easy. If the parent has the method, send the text through and a method to call when finished. What is this method? Well its:
function changeText(text) { jQuery('#returnText').text(text); }
Which simply sets the text on some div to show it actually worked.
What happens when I click a button that calls callParent? It talks to the parent, the parent calls the passed in method, and the child updates itself.
Not sure this is rocket science, but there will be more on it as I add in the idea of a dynamically created pop up on the parent being used by the child. Until then, try not to be yourself. You embarrass your mother.
Get the jQuery DatePicker to Work With jQuery Modal Dialog
Being that I am the man, I thought I would share this little thingy with you because... well I'm the man.
So here's the issue: You have a date picker, a modal dialog, and you can't see the calendar when you click on the icon and/or textbox. First thought, 'WHY DOES THIS HAPPEN TO ME???!?!' Second though, 'I wonder if that tool knows how to get past this.' Good news! I do. Turns out it has to do with the z-index. The modal dialog by default has a z-index of 1000ish when showing. (And any modal dialog "above that" will increase it's z-index to match.) If the calendar isn't higher than that, no go.
Now you might be using the jquery styles from the jquery site and might be putting your through your keyboard thinking about having to deal with that mess. However, it's actually a simple fix in there... there being the ui.datepicker.css file.
.ui-datepicker { width: 17em; padding: .2em .2em 0; z-index:9000; }
And there you have it. Now the calendar will show up in front of anything lower than 9000, and as everyone knows: Anything over 9000 is impossible.
jQuery Validation: Adding Errors to the Error Containter… With Love!
Hello again, my wonderful audience, I have something great and fun planned for this post. If you read this post you might have been left wondering how to add custom messages to the error holder. It's ok if you did, there's nothing wrong with being confused all the time. It's what makes you so adorable.
Say you have a form like this, and if you don't I cry endlessly for your loss. My heart goes out to you.
<form id="ILoveEverythingForm"> <div id="NotSoNiceThingsDiv" style="display:none;"></div> ... </form>
As you can see, there is an error div to hold mean things that we have to print out because the system just doesn't like the user. As we both know, the user can't help but be dumb. It's just in his cute little nature. And that nature is just so darned cute.
Now let's assume that you have something that sent back a bunch of mean messages when you tried to validate server side after all the cute client side validation was done. You might have a method to take in those jerk face messages. How do you display them in the bad place?
function updateErrorDivContentWithLove(messages) { if(messages.length > 0) { var validator = jQuery('#ILoveEverythingForm').validate(); for(var loopCounter = 0; loopCounter < messages.length; loopCounter ++) { validator.showErrors ( { 'SomeWonderfulElementName' : messages[loopCounter].Message } ); } } }
Awwww kitties!
Only thing that may seem odd (And if it doesn't, don't worry you are still very special and loved in this world):
'SomeElementName' : messages[loopCounter].Message
Not sure what element really needs to be here, basically anything in the form with a name tag. So if you're good like I know you are, you have at least one element in that little old form with a name property set. I would say that this is pretty useless in situations where all the errors are shown in one div, as opposed to right next to the element, but that would be mean and I don't do that.
Now I know you wanted something special from this post so I just wanted you to know that even though most of the world considers you hideous, I say you should be proud of being hideous because it makes you who you are. A unique miracle that only really has issues with dogs and small children. Embrace yourself in whatever way you take that!
Data Annotations, MVC, and Why You Might Like Them
So if you were like me before I knew what Data Annotations were, you most likely would be thinking, "What are Data Annotations?". Well I'm glad I can read your mind and therefore I am glad you asked.
Now the fun part about this post is that I might have to admit I was wrong. Why would that be? Well in this post I suggested that validation rules would be set in the controller. Turns out, there is possibly a better place, on the model itself. How can this be done??? Well that's what you're about to find out.
Say you have a user create model:
public class AddUserModel { public String UserName { get; set; } public String Password { get; set; } public String RepeatPassword { get; set; } }
Now you could have a method on the controller like:
public ActionResult AddUser(AddUserModel model) { if(IsValid(model)) { ... } }
Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them...) Or you can have this:
public ActionResult AddUser(AddUserModel model) { if(ModelState.IsValid) { ... } }
And that is already built in so no validation method needed. But how is that possible? Attributes on the model or namely the ValidationAttribute class.
First off you have to include the System.ComponentModel dll in the project. Simple enough. Please say you know how to do that or do me a favor and remind yourself to blink. OK done? Good.
Now you can use some of the built in attributes which is good. Things like required are nice:
public class AddUserModel { [Required] public String UserName { get; set; } ... }
There you go. Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:
ModelState.IsValid
Now you might wonder what the error message will be for that? Honest answer: I have no f--king clue. That's why you can actually set it. Those guys at Microsoft thought of everything.
public class AddUserModel { [Required(ErrorMessage = "ENTER A USERNAME IDIOT!"] public String UserName { get; set; } ... }
The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn't use the one above. Whatever.
Now you might want to actually pass the errors back, and why wouldn't you? You're a fine, upstanding, and thoughtful person and I lie like a crook. The errors, if there are any, are in here:
ViewData.ModelState.Values
And you can use two loops to get to all of them, but I think the parent loop will only run once.
foreach (ModelState state in ViewData.ModelState.Values) { foreach (ModelError error in state.Errors) { messageList.Add(error.ErrorMessage); } }
Pretty nice huh? Maybe if you're an idiot who just learned about this. For cool people like me, it's old news.
What's the point this? If "this" is data annotations: Well it helps move some of the validation off the controller if you are looking for a more "Fat model, skinny controller" design which I'm told is a good idea. This also gets rid of all the validation methods and saves time because of it.
If "this" is your life? I have no idea. But if you're to the point that you're asking me about the meaning of your life, you are in some serious trouble.
jQuery Validation – How to Use to Get Rid Of Even The Toughest Stains
So you want to use jQuery validation, huh?
What is it? Something that was added to the holy jquery site and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to send anything to the server. So how do ya do it?
Well to start, you need some files:
jquery-1.3.2.js and jquery.validate.js.
Now oddly enough the validation file isn't hosted on the holy jquery site but how to use it is.
Ok now you have the files, what's next? Well you need form, and I can do that for you.
So basically it's a simple form with one input that is required.
jQuery(document).ready
(
function()
{
jQuery("#PrimaryForm").validate
(
{
errorLabelContainer: "#ErrorDiv",
wrapper: "div",
rules:
{
FirstName :
{
required : true
}
},
messages:
{
FirstName:
{
required : 'First Name is required.'
}
},
onfocusout : false,
onkeyup: false,
submitHandler: function(label)
{
postSubmit();
}
}
);
}
jQuery("#PrimaryForm").validate
Real simple, just setting the validator to the primary form on the page.
errorLabelContainer: "#ErrorDiv",
This sets the errors to show up in the ErrorDiv. Now this is optional, as you can have it show the errors next to the FirstName text box but personally I think that looks horrible. Setting up the ErrorDiv puts all the errors in one central location and allows for styling the actual div.
rules:
{
FirstName :
{
required : true
}
},
This matches an element with the id of FirstName to the required rule, meaning that FirstName is required. Rocket science.
messages:
{
FirstName:
{
required : 'First Name is required.'
}
},
If you can't figure this out, I hear circus is hiring for the "World's Dumbest Person". You'll fit in with Jub Jub the Dog Boy.
onfocusout : false, onkeyup: false,
Basically this prevents the validation when leaving the textbox or on every key press. This is just another preference.
submitHandler: function(label)
{
postSubmit();
}
If the submit is successful, call this method.
But... BUT WHAT IF IT'S AN EMAIL?!??! WHAT WILL I DO???!?!?
Well for one, stop being such a child. And two, look here.
Some what different, as you can see it's now email and there is one extra requirement in the rules:
rules:
{
EmailAddress :
{
email : true,
required : true
}
},
messages:
{
EmailAddress:
{
required : 'Yo, email fool.',
email : 'So not an email address.'
},
},
See? It has nice built in rule for email. Simple.
BUT WHAT IF I NEED A REGULAR EXPRESSION?!??! WHAT WILL I DO???!?!?
I swear if you don't stop that, I'm turning this post around and going home.
jQuery.validator.addMethod
(
"isZipCode",
function(value, element)
{
return value.match(new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/));
}
);
Just have to create a method and "add it" to the validator itself. And then there's the use:
rules:
{
ZipCode :
{
required : true,
isZipCode : true
}
},
messages:
{
ZipCode:
{
required : 'For the love of me, enter a zip code!.',
isZipCode : 'Serioulsy? Do you know what a zip code is?'
},
},
Woo hoo right?
Don't do it... Don't you yell.
But what if one input depends on another?
Much better. Well that's not as hard as it may seem and here's the example.
rules:
{
InputB :
{
required :
{
depends : function(element) { return jQuery('#InputA').val() != "" }
}
}
},
As you can see, you can change how the required method works by adding in a depends handler. Works out pretty well.
Yes I will show you how to make sure two inputs match. I swear you ask for a lot.
rules:
{
Password :
{
equalTo : "#ConfirmPassword"
},
},
Couldn't be easier unless I wrote it out for you. Wait, I did.
So here you've either learned a bit about jQuery validation or have just spent the last few minutes drooling uncontrollably. Either way, I'm done with this post and you're left to do whatever it is you do, you sick f---.
Side note: I haven't actually been to Htmlgoodies since eh college? but wow did that place sell out. How fitting that an introduction to html page now looks like it was designed by someone just starting out... in the 90s.
.Net 4.0 Beta 2 Entity Framework – How To Set Up Complex Types, Now With More POCO
So something I've seen but just have now conquered is the whole complex type thing in Entity Framework. Not only that, but with the cool new Persistence Ignorance thing all the kids are talking about. (And boy am I glad there's a new kind of ignorance on this site now.) You might ask: What's a complex type? Course you might ask: Why is it so hard to make a decent movie about huge robots that transform into cool vehicles and have really big guns? Well I can answer the first question.
Complex types, in the simple minded way I see them, are a way to split information retrieved from a table into a object within an object. Confused yet? I hope so.
Say you have a User table and on that table you have the typical user information including a bunch of stuff like Name, Sex, City, State, and Zip. Now you could set up the user class to look like this:
public class User { public String Name { get; set; } public String City { get; set; } public String State { get; set; } public String Zip { get; set; } }
Nothing wrong with that, but what if you have an Address class:
public class Address { public String City { get; set; } public String State { get; set; } public String Zip { get; set; } }
That you wanted to map the values from the User table to the User class to so that the User class looked more like this:
public class User { public String Name { get; set; } public Address Address { get; set; } }
Well I'm here to tell you that you can and I have plenty of pictures to back it up.
Keeping with the design from this guy, I am going to add a new class called AdDimension which will have Height and Width, effectively replacing the Height and Width properties on the Ad class.
RECAP - Old class diagram:
So the first thing I have to do is is create the complex type in the Model Browser. That's pretty easy. There's a section called "Complex Types" and you just add one.
See, there's a picture. Next step is adding properties to the newly created complex type.
Another picture! Ok so now you've created on, big deal. Now what? Well you have to add a complex type property to the main class, Ad in this case.
Now if you have more than one complex type, you might have to set the property type to the correct one. Just right click the complex property and click on properties:
Now, you'll have to adjust the mapping for the entity itself. So click on the object and bring up mapping properties. From there, select the correct mapping for the correct column. In this example it's width and as you can see in the drop down there is a AdDimension.Width property to set it to. Cool huh?
And that's it for the object model. Next you have to add the AdDimension class and add a property to the Ad class.
public class AdDimension { public Int32 Height { get; set; } public Int32 Width { get; set; } }
public class Ad { ... public AdDimension AdDimension { get; set; } ... }
And then how do you set it?
someAd.AdDimension = new AdDimension(); someAd.AdDimension.Height = 10; someAd.AdDimension.Width = 10;
And it can even be used in queries:
context.Ads.Where(ad => ad.Width > 10);
Now there are things to be aware of. Complex types can't inherit from other complex types and the property can't be null when saving. Just be aware of that.
I'm telling you man, this s-- is the s--- man. It's the s---.
.Net 4.0 Beta 2 Entity Framework – Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue
So the next step in the New Entity Framework saga was to make a many to one relationship and get it to save. After all, with the last version I had far more issues with many to one than any other kind of relationship. Turns out, the steak is still in tact.
Taking the structure from the last post, I added an AdType. It's very simple. Columns are AdTypeId (Int Primary) and Description (Varchar). I added a AdTypeId column to the Ad table and created a foreign key to the AdType table with it.
Basically Many Ads to One AdType.
Then I did the usual Update Model From Database with the .edmx file. Same old same old. Well this added the AdType class and the relationship:
So far, so good. Now with this it also means that I need to create the AdType class and add the AdType property to the Ad class along with the AdTypeId property.
Side Note:
Far as I can tell, you need the AdTypeId property despite also having the AdType property. Don't forget this.
Here's the AdType class:
public class AdType { public Int32 Id { get; set; } public String Description { get; set; } public virtual IList<Ad> Ads { get; set; } }
And on the Ad class I had to "Ad" (HARHRHARHR) the AdType property along with the AdTypeId property:
public class Ad { public Int32 Id { get; set; } public DateTime CreatedDate { get; set; } public String Name { get; set; } public DateTime? LastUpdated { get; set; } public Int32 Height { get; set; } public Int32 Width { get; set; } //Interesting note: Works even if this is private and non virtual private Int32 AdTypeId { get; set; } public virtual AdType AdType { get; set; } //Note: //If properties are to be lazy loaded, must be virtual public virtual IList<Newpaper> Newspapers { get; set; } }
Classes are done. Should be good to go right? WRONG YOU ARE SO F-ING WRONG! Just try this, I dare you:
Ad ad = new Ad(); ... ad.AdType = someAdType(); context.Ads.Add(ad); context.SaveChanges();
DUN DUN DUUUUN INSERT statement conflicted with the FOREIGN KEY constraint.
You try it? Idiot. You just got stuffed by a foreign key error. Why? Well The Big M has an answer:
In this example, Customer is a pure POCO type. Unlike with EntityObject or IPOCO based entities, making changes to the entity doesn't automatically keep the state manager in sync because there is no automatic notification between your pure POCO entities and the Entity Framework. Therefore, upon querying the state manager, it thinks that the customer object state is Unchanged even though we have explicitly made a change to one of the properties on the entity.
Basically because these objects aren't really being watched by the State Manager, it has no idea anything has changed and should be persisted. Therefore, it has no idea that the AdType property has changed and that the AdTypeId should be updated to reflect this. That's right, it just ignored the AdType property and left the AdTypeId to it's default... 0 (That's a Zero or as the English say, Zed). How do you get around this? This little option.
context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
This tells it to persist the changes that it didn't know about. Now I'm still picking this up as I go so bare with me as I might have the best explanations yet on why things work with the New Entity Framework. Then again, this is a site by a tool.
.Net 4.0 Beta 2 Entity Framework – How To Start
So I just recently turned my laptop into a 4.0 workstation since it is kind of expendable and I won't feel inclined to nerd rage if it gets tooled. With this step forward, I decided that I probably won't be doing much with the old Entity Framework version since the new one is supposed to be the end all/be all until the next end all/be all version comes out. What does this mean for you? This post could be filled with useful information or f--- all. Just depends on what you care about.
After doing a little reading, and by little I mean as little as humanly possible while still having an idea of what I'm doing, I got the new EF to persist an object. Mind you, it took a bit of patience followed by slamming my head into my desk and then more patience, but I did it.
First off, the actual creating of the edmx file is the same, there's really no difference. You still go through the wizard, you still go through the connection set up, and you still grab the tables you want. No change there.
However, once you have it created, click on the .edmx file in your solution explorer, right click, then click properties. You'll see something like this:
You can see where there is nothing in the Custom Tool area of properties. That's because I deleted the text. That's the first part of what you need to do. Next is creating the needed classes. For this example I have two, Ad and Newspaper:
namespace Beta2Test.Data.Entity { public class Ad { public Int32 Id { get; set; } public DateTime CreatedDate { get; set; } public String Name { get; set; } public DateTime? LastUpdated { get; set; } public Int32 Height { get; set; } public Int32 Width { get; set; } //Note: //If properties are to be lazy loaded, must be virtual public virtual IList<Newspaper> Newspapers { get; set; } } }
and
namespace Beta2Test.Data.Entity { public class Newspaper { public Int32 Id { get; set; } public Int32 Circulation { get; set; } public DateTime CreatedDate { get; set; } public DateTime LastUpdated { get; set; } public String Name { get; set; } //Note: //If properties are to be lazy loaded, must be virtual public virtual IList<Ad> Ads { get; set; } } }
Three things you might notice:
- The classes don't inherit from anything. Yay
- The namespace is Beta2Test.Data.Entity. Fact is, I left it there to show that the namespace can now be anything. Yay
- Both collection properties are virtual. This is a must when dealing with collections that represent a relationship and you have lazy loading enabled (See below context class). For this, there is a many to many relationship between Ads and Newpapers. The Ads and Newspapers collection represent that. Why do that have to be virtual? Has to do with Entity Framework needing a way to override the properties so it can tell when they are accessed. (Read: Lazy Loading)
- There is no fourth thing. You are wrong if you think there is.
So far so good, but what about that like whole linking to that persistence layer stuff. You know like them entity objects yo.
Thank you for that poorly worded inquiry, but valid none the less. Remember those entity context classes that it used to generate for you? Well that whole "custom tool" dohickey I removed would have built it for me. However, that's not the path we're going down anymore. It's now time to brave the unknown. We, yes we, will build the context. Yes the context.
using System.Data.Objects; using Beta2Test.Data.Entity; namespace Beta2Test.Data { public class Beta2TestContext : ObjectContext { private ObjectSet<Ad> _ads; private ObjectSet<Newspaper> _newspapers; public Beta2TestContext() : base("name=InterviewDemoEntities", "InterviewDemoEntities") { _ads = CreateObjectSet<Ad>(); _newspapers = CreateObjectSet<Newspaper>(); //This makes sure the context lazy loads by default ContextOptions.LazyLoadingEnabled = true; } /// /// This is used to set up the "queryable" collection. /// public ObjectSet<Ad> Ads { get { return _ads; } } public ObjectSet<Newspaper> Newspapers { get { return _newspapers; } } /// /// This creates an ad that allows it "to be used with the Entity Framework." /// /// public Ad CreateAttachedAd() { return EntityContext.Context.CreateObject<Ad>(); } public Newspaper CreateAttachedNewspaper() { return EntityContext.Context.CreateObject<Newspaper>(); } } }
The CreateAttached methods aren't needed on the Context class itself, I just put them there. They could go on the Ad/Newspaper class but at this point I'm not sure if that blurs the lines or not. Haven't gotten into best practices mode yet.
You may notice the ObjectSet collections on the context. These are the collections you will query to get items most likely, much like the old context class from the last version:
Context.Ads.Where(ad => ad.Id == 1)
Pretty nice, huh?
Also, I noted above about the virtual properties on the Ad/Newspaper classes and how it had to do with lazy loading.
ContextOptions.LazyLoadingEnabled = true;
That line and the virtual properties ensure that lazy loading will occur when the property is used. Both have to be used together. Now you don't have to put that line in the constructor if you do create a context every time you are retrieving things, you could just set it on a case by case basis. Up to you. I use a singleton like context so I just set it true in the constructor and don't worry about it.
The main thing I had trouble with was this line:
public Beta2TestContext() : base("name=InterviewDemoEntities", "InterviewDemoEntities")
Because I wasn't sure what the second string should be. First one is easy, it's whatever the key in the config file for the connection string. Second, chances are, is the same depending on how you set it all up in the wizard. I think it's the same name when you right click on the opened .edmx file and view properties. There should be a property named "Entity Container Name".
Here's a method I used for testing to create an Ad:
public Ad CreateAd(Boolean persist) { Ad ad = null; if (persist) { ad = EntityContext.Context.CreateAttachedAd(); //This is the CreateAttachedAd method above in use } else { ad = new Ad(); } ad.CreatedDate = DateTime.UtcNow; ad.Height = RandomTool.RandomInt32(0, 10); ad.LastUpdated = DateTime.UtcNow; ad.Name = RandomTool.RandomString(10); ad.Width = RandomTool.RandomInt32(0, 10); if (persist) { AddEntityForRemoval(ad); //Ignore, for persistence removal after testing is completed EntityContext.Context.Ads.AddObject(ad); //Ad the ... ad to the context EntityContext.Context.SaveChanges(); //Persist } return ad; }
There are some things you can ignore because I didn't feel like removing code. As you can see though, it's not very complicated. Use the CreateAttachedAd, fill in the properties, ad to the Ad collection on the context, and save.
The End
Sure you had to do more work than in the earlier version of Entity Framework, but on the other hand I have a fully detached class that can inherit from any class I WANT it to as opposed to the EntityObject class. Not to mention I now have an easy way to do lazy loading. Far cleaner than the old way I did it. The other interesting thing to note, and this may not be a big deal to anyone else, but above I have a note about this:
AddEntityForRemoval(ad); //Ignore, for persistence removal after testing is completed
This method just adds the object to a collection of EntityObjects that later I use to delete the object from the database on test cleanup. After moving to this version of EF, I had to change it to a collection of Objects. Interesting thing is:
EntityContext.Context.DeleteObject(currentObject);
Didn't care. It still knew that the object was attached to the context somehow, despite the CLASS not being an EntityObject. Just an odd note.
Two Errors I came across:
System.InvalidOperationException: Mapping and metadata information could not be found for EntityType 'Beta2Test.Data.Ad'.
If you get this, there is a really good chance you screwed up a property name or are missing it completely. If the property name doesn't exactly match one in the .edmx class designer template, you're screwed. If you don't have it on the class but it's on the class designer template, you're screwed. If you add it to the class designer template, it has to be on the class as far as I can tell. Now, it doesn't have to be public. I have tested it as private and it works just fine.
The required property 'Newspapers' does not exist on the type 'Beta2Test.Data.Ad'.
This most likely happens if you didn't remember to make it a property:
public IList<Newpaper> Newpapers; //Forgot the { get; set; }
public IList<Newpaper> Newpapers { get; set; }; //Forgot the Virtual
Opps.
ASP.Net MVC: Attributes, ActionFilterAttribute, and Why You Might Want To Use Them
So if you've used MVC, and I know you have because you want to be cool like me, you've most likely run into an error like this:
Certain parameter wasn't found. Make [parameter] nullable.
In other words, the parameter didn't show up in the URL and therefor MVC can't assign a value to it. This would of course happen with anything that isn't nullable. Now you could do this:
void SomeAction(Int32? pageNumber) { if(someParameter.HasValue) { .. } }
But do you really feel like putting that in every stupid method that happens to have the same parameter? Say the parameter is something simple like pageNumber. Taking the above code, you would have to see if pageNumber has a value and if it doesn't, continue to set some variable to a default. Kind of annoying to have to repeat that over and over again when you know you will be looking for pageNumber on many actions. Well Attributes, or more importantly ActionFilterAttribute, are the way to get around this.
Say with the pageNumber example you want a default of 1 if it doesn't exist. Well that's easy to do, it would be something like this:
public sealed class CheckPageNumberAttribute : ActionFilterAttribute { private const String DefaultPageNumber = 0; //This will fire automatically on page load. public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //ActionParameters.Values holds all the request parameters after the ? as in ?pageNumber=1 //See if it exists first. If not, add it if (!filterContext.ActionParameters.ContainsKey("pageNumber")) { filterContext.ActionParameters.Add(RequestConstants.PageNumber, null); } //Set to default if it's not null filterContext.ActionParameters["pageNumber"] = filterContext.ActionParameters["pageNumber"] ?? DefaultPageNumber; } }
So the method looks more like this now:
[CheckPageNumberAttribute] void SomeAction(Int32 someParameter) { ... }
And you can now do your ... without worry.
But what if the url is like this?
ShowMeACoolRoom/Index/1/
And you have your route set up like:
{controller}/{action}/{roomId}
And you want to make sure that not only does that userId exist in the url, but the user actually exists. Well you don't look to the ActionParameters.
public sealed class RoomExistsAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); ChatRoom foundRoom = null; //RouteData.Values holds all the values in the url it was able to match to a route //Check the Values list in the RouteData for the id if(context.RouteData.Values.ContainsKey("id")) { //Convert to an integer, ConvertTo is just a method I've made. Int32? roomId = Convert.ToString(context.RouteData.Values["id"]).ConvertTo(); if(roomId.HasValue) { foundRoom = ChatRoom.GetRoomByID(roomId.Value); } } //If the room isn't found, handle the error. if (foundRoom == null) { //redirect on error... context.Result = new RedirectToRouteResult ( GeneralConstants.RouteName, new RouteValueDictionary { { "controller", "sharedError" }, { "action", "error" }, { "name", "someErrorKey" } } ); } } }
Now the new method looks something like this:
[RoomExistsAttribute] [CheckPageNumberAttribute] void SomeAction(Int32 roomId, Int32 someParameter) { ... }
And once again you are free to ... without worry of the room not existing. Next post I plan on adding some more "advanced" attributes... hahaha advanced? This site? hahahaha sorry. But I will be adding a new post about certain attribute solutions I've found that work well.
ASP.Net MVC: Routes, Route Contraints, and My Love Hate Relationship
So something that has been somewhat of an uphill climb as of late is routing in MVC. I think part of it is the way it works and part of it is that I've approached MVC like a 10 year old with a new game; F- the instructions, I'm all up in this.
What goes out must come in...
The biggest misconception I had with routes is that the route definitions meant something when a page is loading. This is bad. Now before the nerd rage starts to build, I will qualify that statement. Route definitions mean nothing beyond a simple mapping of values. What? Well suppose I have two routes:
routes.MapRoute
(
...
"{controller}/{action}/{roomId}/{name}",
...
);
and
routes.MapRoute
(
...
"{controller}/{action}/{userId}/{name}",
...
);
Now on the way out, the system can find the route easy if you supply the correct route data: (Lets say for the second route)
routeValues = new RouteDicationary() routeValues.Add("controller", "Room"); routeValues.Add("action", "Index"); routeValues.Add("userId", 1); routeValues.Add("name", "ProgramminTool"); neededHelper.RouteUrl("SecondRoute", routeValues);
Which will give me a wonderful address of:
/User/Index/1/ProgramminTool
Awesome, the routing system did what I wanted. Problem is, I assumed too much coming in, ie when the page is loading from the url. (Say from a clicked link) I kept getting an error like:
RoomId doesn't exist. Make roomId nullable. Blah blah blah I hate you and you should quit programming and do something more equal to your ability level like spinning in circles.
Though I might have take some artist license on the error, the meaning was simple: it was trying to run that url against the Room controller and it couldn't find the roomId parameter in the request. Well that doesn't make sense, after all it's obvious that it should be looking for the user controller and use the route with the userId paramter. Sadly, it doesn't work that way and not sure it could. Why? Well look at the url.
/User/Index/1/ProgramminTool
Now if you were too look at that, what would you think? You have four values, values that you can't really guess the type since you have no real context. After all there could easily be a method that takes in a string userId as opposed to an integer userId. On top of that, it has no idea what the 1 is. There's no userId=1 to tell it what it is. So what does it do? It goes down the route table and finds the best fit. Now you tell me, which does this url fit better?
"{controller}/{action}/{roomId}/{name}"
Or
"{controller}/{action}/{userId}/{name}"
It's kind of a trick question since the answer is neither. It will just fit it to the first one that it likes, and in this example it's the roomId one. Problem is, now the user controller method that is looking for the userId fails because there is no userId. Uhg.
Computers are dumb, they can only do what we tell them.
Fact is, in this situation I have to make some rules for the routing system to take in and start digesting the url properly, and there's a way to do this: IRouteConstraint.
Say that you have certain controllers or actions you don't want to use the first route. For this example I'll use user actions from my current project. On the room index view there is a button for adding the room as a favorite. Now the action/method it needs is on the user controller, not the room controller. Therefore I have to post some information to the user controller using a route that looks like this:
"{controller}/{action}/{userId}/{roomId}"
But it is preceded by one that looks like:
"{controller}/{action}/{id}/{name}"
See the issue? Now when MVC generates the url, everything is fine. After all it uses the route name and the parameters to pick the correct route. On the way in, not so good. It naturally tries to conform the url to the id/name route. BOOM HEADSHOT! Now the solution.
public class NotGivenAction : IRouteConstraint { //This is the action that we want to prevent from the route accepting private String GivenAction { get; set; } public NotGivenAction(String givenAction) { GivenAction = givenAction; } public Boolean Match(HttpContextBase httpContext, Route route, String parameterName, RouteValueDictionary values, RouteDirection routeDirection) { String parameterValue = values[parameterName].ToString(); //Make sure the parameter exists and it doesn't match the bad action return values.ContainsKey(parameterName) && parameterValue != GivenAction; } }
The IRouteConstraint interface has a method Match that has to be given life. The short of it is take in the parameter name and find it's value and then see if the value is the same as the action it's looking for. For example, if I had an action of AddToFavorites, this would go through and make sure it isn't that action. If it is, it knows to not use the current route for this action.
routes.MapRoute ( GeneralConstants.RouteIdName, "{controller}/{action}/{id}/{name}", new { controller = "Room", action = "Index", id = "0", name = "None" }, new { action = new NotGivenAction(UserControllerConstants.AddToUserFavorite) } ); routes.MapRoute ( GeneralConstants.RouteUserIdRoomId, "{controller}/{action}/{userId}/{roomId}", new { controller = GeneralConstants.ControllerUser, action = UserControllerConstants.AddToFavorites, userId = "-1", roomId = "-1" } );
So now it will skip the first and push to the second when the url looks like:
/User/routes.MapRoute/AddToFavorites/1/2/
Take that you f-ing routes. KING KONG AIN'T GOT S- ON ME!










