A coworker ran into this one today as he was trying to call an old school web service using jQuery Ajax/Post. Keep throwing an exception/returning a 500 error. After some searching, both google and soul, it turns out that services that are expected to be used with scripts (Javascript or Jquery in this case) need the attribute ScriptService. Yeah, that’s it. The silly and cryptic message is really just an attribute needed on the code file above the service class. Go figure.
Author: Sean
ASP.Net MVC2, Dynamic Models, Json, and Javascript
Ok so one thing I fell into while using the dynamic keyword as a model, was an issue with the dynamic model being parsed into json and then back again into javasript using jQuery. Silly me, I thought that the dynamic model would represent itself like any other object, but it turns out the dynamic object is actually a dictionary with a key value pair. Now I’m not going to harp on that since I think that’s kind of how Python does it (And javascript for that matter), but I did want this:
function doSomething(result) { if(result.Success){ alert(result.Value.UserName); } }
Where the result value was:
... //Other junk dynamic returnModel = new ExpandoObject(); returnModel.UserName = _state.CurrentUser.UserName; result.Value = returnModel; ... //set the data on a jSonResult to that result above and return.
But what I got for Value was a dictionary:
result.Value[0].Key "UserName" result.Value[0].Value "test@test.com"
As you can guess, using the javascript from above won’t work. However, there is a way to run the above javascript.
var convertedValue = new Object; for(var i = 0; i < result.Value.length; i++){ convertedValue [result.Value[i].Key] = result.Value[i].Value; }
You see with javascript, like the dynamic object, the objects not only respond to a direct assignment like a property, but can also be manipulated like a dictionary. Where does that code above get me? Well simple, I can now do:
alert(convertedValue.UserName);
Yeah its not perfect and I have to think there will be some way for a better json translation, but for now this is gold.
ASP.Net MVC 2/C# 4… Dynamic Model and Should You Use It?
So there’s a new sheriff in town and its name is dynamic. Actually, its not really that new and that’s a horribly misused cliche. My lack of literary genius aside, I’ve been looking for a reason to use dynamic. Then it came to me: Models. Now the only reason why I started down that path was the use of Python where pretty much anything is dynamic. In using python, I got used to not embracing the rigidity of classes for models and adopted a more “Oh what the f–k” attitude. Back in the .net world though, I was using typed views. Then I readopted the “Oh what the f–k” attitude and applied it to .net mvc.
Here’s an example:
[RequiresAuthentication] public ActionResult ShowBasicInfo() { IState currentState = ObjectFactory.Create(); dynamic returnModel = new ExpandoObject(); returnModel.UserName = currentState.CurrentUser.UserName; return View(AccountActions.ShowBasicInfo, returnModel); }
As you can see, I created a dynamic class and just added a property to it. Now on the view side:
... @model dynamic ... <label id="showBasicInfoEmail" name="showBasicInfoEmail">@Model.UserName</label> ...
So if that’s all you’re here for, well there you go. Now get out.
Ok so the real point to this post was actually the “should I?” Now with .Net, you really have to adopt a “should I?” attitude on anything that is new otherwise it might come back to bite you in the a–. (Update panels anyone?) Just using something because it looks easier is NOT a reason to do so.
The reason why I originally gravitated toward typed views was I didn’t like all the magic sting junk that came with the View dictionary, or whatever the hell it was called. (I’m too lazy to look it up) Typed views gave a sort of concrete nature much like an interface does to a class. You knew exactly WHAT the view could show based on the model. This is good I still think in an environment where you don’t trust people to code correctly or when a person needs an easy place to look up what the incoming model contains. After all, on the second point I mean, its a lot easier to look at a class to find EXACTLY what the model has than looking at a controller action code. Simple for reference.
With that being said, getting stuck in model hell can happen. After all for every action there is an equal and… wait… there is a model. Yeah you can reuse models to cut that down, but its not too hard to imagine it becoming a model infested nightmare. Sometimes you just have to take the good and the bad, but sometimes you’re able to trust people and just go with what is easier.
Why trust? With Python and it overall dynamic nature, it was easy to see that such a tool put in the wrong hands could be a disaster. Anyone who has worked with JavaScript will know this pain. Python is just a fancy way to annihilate your foot, so the concept of allowing dynamic models only made me shiver like a prostitute on Christmas. Sorry, that wasn’t appropriate. I meant a prostitute on a non religious holiday like Thanksgiving or the Chinese New Year. (Sorry non Christian readers)
On the other hand, when in a small group where you have less time and more to do, it could be used as a compromise as it doesn’t use the hated magic string dictionary thing approach, but still had a class like feel. And on top of that, if you wish to create models later, it would be extremely easy to swap the @model dynamic with whatever class type you need. So in that way, I can almost stop my non stop convulsing that is a natural reaction to doing something I deem bad.
Answer is: I don’t f–king know right now, but I’m going to fly with it and see how I like it.
Side note: One drawback of the dynamic route is the lack of intellisense. That could be a deal killer for some.
NUnit Hangs Up When Run Through Nant Using .Net 4.0
Ran into this one yesterday starting with Cruise Control not finishing. At first I just thought Cruise Control just wasn’t that into it, but turns out something was hanging up and that something was N-N-N-UNIT. Well to be more specific it was NUnit while being run through Nant although in the end it wasn’t Nant’s fault. Turns out it has to do the latest stable release of NUnit… 2.5.8.something.whatever.
The fix? Grab 2.5.9.yayayaya from the download page and use the nunit-console from that instead. I guess the whole issue had to do with the latest .Net 4.0 and the latest stable version of NUint. I guess they don’t like each other. They go together like water and something that doesn’t go well with water.
jQuery Validate Date/Check If Is Date
Far as I can tell, and that’s pretty far even though I do wonder if you can actually measure telling in distance, there isn’t a method directly used for validating a date in jquery. I find this rather odd. Not odd like how people keep watching Uwe Bol movies, more like odd that no one has tried to make a time machine to prevent them from ever appearing.
Anyways, bad movies… horrible movies… worst movies of all time aside, there is a date checking method, just not directly in jquery. It’s actually in the jquery.ui.datepicker.js file which is part of the UI files. Basically I grabbed that file and used the parseDate method on it coupled with a try catch. After all, a failure in the parseDate method throws an exception, and we don’t like those. No we don’t. (Which begs the question as why it throws an exception instead of just returning a null date.)
function isValidDate(controlName, format){ var isValid = true; try{ jQuery.datepicker.parseDate(format, jQuery('#' + controlName).val(), null); } catch(error){ isValid = false; } return isValid; }
Very simple, and it works. You could ask why I didn’t just roll my own date method, and then I would ask you how ambitious do you think I am? Then you would punch me because I answered your question with a question like a complete tool bag. Then I would cry. And THEN I would answer your original question. Fact is, I trust that the method created for the DatePicker is in fact well tested, otherwise the whole jquery thing just isn’t worth trusting seeing as it’s a part of their core library. And that I just refuse to believe.
C#: Create Dynamic Image For Byte Array Data
So you have a unit test, but maybe for some reason you need to create an object that has a constructor that needs a byte array. Maybe for some reason that byte array needs to have more than 0 length. Maybe you don’t have any of this and you are just curious. Maybe I’ve said maybe too much.
Well in any case, here’s a way to do this:
using System.Drawing; using System.IO; private byte[] GetBitmapData() { //Create the empty image. Bitmap image = new Bitmap(50, 50); //draw a useless line for some data Graphics imageData = Graphics.FromImage(image); imageData.DrawLine(new Pen(Color.Red), 0, 0, 50, 50); //Convert to byte array MemoryStream memoryStream = new MemoryStream(); byte[] bitmapData; using (memoryStream) { image.Save(memoryStream, ImageFormat.Bmp); bitmapData = memoryStream.ToArray(); } return bitmapData; }
And presto you have a fake image to send through. Can’t get much easier than that. Well maybe it could but not in this example. Why are you judging me? I’m just trying to help. You know what? Go away. I don’t want you around here anymore. You and those beady, judging eyes. Always looking… Never stopping… WHY DON’T YOU LEAVE ME ALONE?!?!?
Awesome Language, Now What?
Let me tell you about my friend Bob. Bob is from the future.
Bob came here from about 300 hundred years from now where time machines are sold at Walmart… which apparently owns everything.
I met Bob just randomly at a plunger convention (Apparently plungers are all the rage in his time but hard to find.) and we struck up a conversation… mainly about plungers. Anyhow, when he finally revealed he was from the future (The trippy multicolor shirt kind of gave it away honestly since by my calculations it will take at least 250 years for pleather to come back in style. Give or take 50 years.) and the first thing he said after revealing this was, “No its not a f—ing utopia so don’t ask.” Oddly enough I was going to ask if Gilligan’s Island was still on repeats in his time, but I just humored him. Long story longer, by the end of the night he was my bffff (Best friend forever from the future) and he decided to give me this awesome device thing from the future and said he’d be back in a week to get it back.
Apparently it was something he bought from Walmart but was going to return before the week long return policy was up. However, he thought I might have fun with it and then just did this sort of wavy, melty, star treky thing and was gone. Odd note: No one watching seemed to be phased by this. Cause you know, that’s something you see everyday.
Anyways, I took said device and set out into the world, determined to enrich my life with the blinking-light-a-tron. Problem was, I had no f—ing clue what it did. So I did what any person would do when faced with a blinking-light-a-tron from the future, I put it through various scientific tests.
After my barrage of highly scientific investigations, I could see that it was applicable to most useful situations. Sounds good right? Except it took me a ton of time to figure out how to use it while doing things I already knew how to do.
Now I have to admit the time difference was a knowledge issue as there wasn’t much documentation and it wasn’t intuitive in use compared to what I was used to. However, it wasn’t until I found out that it can not only make a sandwich but it can make it into a smoothy too that I realized it had some powerful features. It wasn’t long before I started to realize how much it had to offer.
After the E like excitement, there was inevitable crash: When the f–k will I ever really want a turkey sandwich smoothy? I know the thing has something bigger to offer. Something just mind blowing, like somehow being able to combine sharks with an FBI agent to form some kind of super crime fighting force, but hell if I can figure out how.
It was at that point Bob just appeared, punched me, grabbed the blinking-light-a-tron and did his futuristic wavy, melty, star treky thing. I never did find out what that was all about, but I just surmised it was some kind of futuristic way of saying goodbye for good. Or it could be that I used it to find naked pictures of his wife and posted them on the internets. (Apparently there was an app for that)
Either way, the blinking-light-a-tron was gone for good, and I’m not sure if I was better off with knowing it or not. Sure it showed me what was possible but I came back to the same conclusion: When the f–k will I ever really want a turkey sandwich smoothy?
In a weird way, I’ve come to this conclusion with something like Python. I have no doubt it has crazy capabilities to be used, but put in the hands of simpleton it’s a point of confusion. I want so badly to unlock its potential, but the best I can do is make a turkey sandwich smoothy, because I lack the overall grasp of the language and have no idea how to get it through application.
And here’s the thing, it’s not a matter of being too comfortable with C#
Ok, so maybe there is some comfort but honestly it really isn’t that. It really just comes down a frustration of finding something to showcase Python’s abilities. It just plain difficult to come up with some grand plan when I don’t even have a clue what sort of plan I need.
It’s one thing to find a language that is just a horizontal move or even a step back. Then it’s easy to say, “Screw it†and stay with what you know. In the case of Python, I really want to be convinced to move to it. Nothing against C#, I still find it to be a good language, I just have a feeling. Problem is I have no way to back the feeling up.
In order to understand something, you need a reason for it. This is the hill we all must climb at some point and it’s a big hill.
Building Blocks
Obsession
PyCharm 1.0 RC2 is out for Download Yay
Can’t begin to say how much I prefer this over alternatives like Eclipse. It’s really a great product for Python development.