.NET Discussion

.NET Issues, Problems, Code Samples, and Fixes

Javascript: How To Implement Callback Functionality

I know I haven’t posted for a while, so for all 1 of my loyal readers (ha, kidding. Friend.), I apologize. Mostly the reason why is that I’ve been super busy (a good thing)! Anyways, this isn’t a personal blog, so I’ll spare you the details and get down to business.

As you may well know from my previous few posts, I’ve been dipping my toes into the jQuery and Javascript¬†world for quite some time now. I actually learned jQuery first before I had any real experience with Javascript (yes, that’s how freakishly easy it is to learn and use), so a lot of what jQuery did I took for granted: DOM manipulation, event binding, and, as mentioned in the title of this post, callbacks. If you’re not TOTALLY familiar with how Javascript works (don’t worry, it took me a while, too), digest this:

In static languages such as VB.NET or C#, a variable at its most basic level contains an instance of an object, such as a String object or an instantiated class of some sort. In dynamic languages (e.g., Javascript), not only can variables house objects (which may or may not be instantiated), but they can store functions as well. As in, the whole function itself. This function can be anonymous or a predefined named function. For instance:

var myFunction = function () { 
    //do work here 

Which, depending on how it’s referenced, can do two different things. Let’s say you have a function called callingFunction() that needs to pass a parameter of some sort. Using the myFunction() example above as the parameter, calling callingFunction(myFunction()) and callingFunction(myFunction) do two different things.

callingFunction(myFunction()) passes the value returned by myFunction as the parameter, which means that myFunction must first run before callingFunction does so that it may pass along its result. If myFunction returns, say, the number 2, this is effectively the same as calling callingFunction(2). (Assuming that myFunction has no other functionality than doing some work and returning a number. If myFunction does anything else, it will run before callingFunction, as described.)

callingFunction(myFunction) passes the function myFunction to be used at a later time by callingFunction. This means the function being passed along as a parameter has not run yet. This is how callback functionality is created. Essentially, once callingFunction has successfully run, a typical control flow would be to run the callback function passed along (after checking if one exists). This is convenient (and more dynamic than, well, static languages) because you don’t have to hard-code which functionality occurs after a certain process finishes. You can just pass in whatever functionality you want, which leads to the beauty of anonymous functions. Example:

function callingFunction(someFunction) {
    var someVar;
    //do some work here
    //after work is done:
    if (someFunction != null) {

Viola! Callback functionality.

In jQuery, if you want to add click handler functionality, it’s as simple as $('.myClass').click(function() { //some work });. That function() is just an anonymous (nameless) function passed along to dictate the functionality that must happen once your selector has been clicked. The beauty of jQuery is in its abstraction. You don’t have to try to wire up the actual event listeners for the clicking of the mouse, you just tell jQuery what to do after the mouse has clicked on your selector.

IMHO, this couldn’t be any easier. As a newbie, it took me a while to wrap my head around it, but I hope that these examples may help someone save a bit of time trying to figure this out.

December 21, 2009 Posted by | Javascript, jquery, Tips & Tricks | 3 Comments

Javascript: Setting the Month on a Date Object

While working with dates in Javascript I came across some weirdness that was messing with my date parsing. Apparently in Javascript, years and days are 1-based, but months are 0-based. To set the correct date:

var someDate = new Date(yourYear, yourMonth - 1, yourDay);

Crazy, I know, but hopefully this helps someone out.

July 28, 2009 Posted by | Javascript, Tips & Tricks | | Leave a comment

jQuery: Awesome

Back in the day, I discovered jQuery, but never really did anything with it. I always wanted to learn, but really never had the time. I do now. Let me tell you something:

jQuery is friggin awesome.

Let me preface with the fact that I know little to no JavaScript. I once wrote one function to add the current date to a textbox in JS and it took me around half the day. However, in that same amount of time about two weeks ago, I was able to nearly completely understand how jQuery works. After a week, I was helping out others with their problems.

Don’t get me wrong, jQuery can’t do everything, but it sure can do some powerful stuff. For instance, AJAX is a breeze. For one project I had to make an AJAX call to check to see if someone was posting a comment as someone else while logged in as themselves, so I had to write my AJAX function myself. It took me 53 lines of JS and maybe 3 days to get it working right (along with a TON of research). When I wanted to apply that same function to my new project, I thought I would give jQuery a chance.

Eight lines of code. Actually, technically one line of code because I broke it into several lines:

function MakeCall(url,doAsync,callback) {
url: url,
async: doAsync,
dataType: "text",
success: callback

Of course I have to handle the “callback” in the function that’s calling the MakeCall() function, but the actual making the call has been reduced by 85%. And it’s easier to maintain and reuse! This isn’t all that jQuery is good for. I believe jQuery’s strongest feature is its document manipulation. If you want to change something, all you have to do is select the element or class and, well, change it. For instance, if you have a div with an id of “myDiv”, to change the CSS class on it, you just do:


Really, that’s it. If you wanted to do that when something is clicked, you could do:

$("#myLink").click(function () { $("#myDiv").addClass("someClass"); });

No, for real. That’s all you have to do. You can also manipulate things on page load:

$.(document).ready( function () { //run functions here });

The last and I think one of the most important aspects of jQuery is that it is VERY well documented, VERY ardently followed, and VERY well supported. You can even get Intellisense in Visual Studio 2008! I couldn’t possibly go through all the cool stuff that jQuery can do. You’ll have to see for yourself. It truly is amazing, and it is, as I was told, “brain-dead-stupid easy to learn”.

June 12, 2009 Posted by | AJAX, CSS, Javascript, jquery, Tips & Tricks, Visual Studio.NET | 1 Comment

My Foray into Regular Expressions with ASP.NET

I know it’s been a while since I posted here. I’ve been working pretty diligently on my newest creation, Quotidian Word, which will essentially be a “word-a-day” site that encourages users to actually learn the word and use it actively in everyday speech or writing. Right now it’s only an email harvester so that I can send an email to those interested when it’s ready, but I’m nearing the launch point every day ūüôā

Anyways, the point of this post is to discuss my dip into the world of Regular Expressions. I needed to come up with a way to find the word I wanted in a sentence. Easy enough, right? Just mySentence.Contains("myword") and there you go. It would be nice if that’s all I had to do, but English is a funny language. Every word can assume many forms. For instance, if I want to find the word “entry” in a sentence, I also would like to find “entries”. Or more simply, if i’m looking for “dog” I also want to find “dogs”. Using the mySentence.Contains() method, I would not find “entries” and I would find only the “dog” in “dogs”.

Enter regular expressions.

I had previously shied away from them because when one looks at a regular expression (aka “regex”), it can be rather intimidating. Take this stock regular expression that comes with Visual Studio as a default for finding an email address:


Your reaction may be the same as mine was: WTF. But when you try to enter an email in a textbox validated by this regex, it knows if you are or not. So my problem was still, how do I find all forms of any word I choose? I took a couple factors into mind, such as, I will mostly be using more obscure words with less common roots, so that will help a bit, and I won’t be using too many really short words that can be blended into other words in a sentence.

My first thought was ok, how about I first try to find the whole word, then the whole word plus a suffix, then the whole word minus a letter plus a suffix, then a the whole word minus two letters plus a suffix:


I used the word “entry” as an example here. “\b” means either the beginning or the end of a word and “|” means “or”. The rest is just separated by parens. This worked out ok for a while until I realized that the English language has something like a thousand suffixes. I knew regexes were more powerful than that. There had to be an easier way.

And there was! I was sort of on the right track with the losing of the last two letters. In English, most words either simply append a suffix (dog -> dogs), drop one letter and append a suffix (happy -> happiness) or drop two letters and append a suffix (cactus -> cacti). Aside from the word “person” (person -> people) I could not think of an instance where a word dropped three or more and would profide me with enough remaining information to actually distinguish it from other words in the sentence. If you can, let me know.

So after a bit more research, and the testing from a handy regex tool called Expresso, my regex eventually evolved into: (?:ent(?:r|ry)?).+?\b

Explanation: “ent” is what I called the “root” of the word, essentially the letters remaining after the last two have been stripped off. “(?:” is a grouping that means “find whatever’s here, but don’t actually match it alone”. This way it doesn’t find only “ent” or “r” or “ry” and match it, but rather matches the whole thing all together. The clause “(?:r|ry)?” means find “r” OR “ry” (in addition to what comes before it, so “entr” or “entry”). The “?” at the end means the whole clause before it is optional, meaning if it’s not there, it’s ok. The “.+” means find any character after the previous clause for as many repetitions as you can, so for instance, if the word in the sentence is “entries” it will first find the “ent” then the “r” then any characters that follow “ies” up until the end of the word, “\b”. The “?” at the end of the “.+” just means take as few characters as possible up to the next clause, which is the “\b”.

Whew! That’s a lot. I found that this found about 99% of the words that I would be using in all their various forms. But then I got to thinking, what about prefixes? What if someone used something like “anti” or “pre” or something in front of a word to change it just slightly? Hence, my (nearly) final product:


where {1} is the word minus the last two letters, {2} is the penultimate letter, and {3} is the last two letters. The optional clause at the beginning takes care of any prefix if it happens to exist.

Great! All done. It can pull it out of a string, no problem. Now if someone enters the word in a sentence in my textbox it will find…it… crap. It doesn’t work as is with the RegexValidator in ASP.NET on textboxes. Why? Because the validator is looking at the whole string in the textbox to see if it fits the regular expression. For instance, the email regular expression assumes that whatever you enter into that textbox is going to be an email, nothing else. If you enter a sentence into a textbox, it assumes that whatever you enter into that textbox is going to fit the regex.

In order to counter this problem, I put in a simple fix: I prepended and appended my regex for textboxes with “.*”, which means that it will find any characters before or after the word we’re looking for. Done! … Right?

So I thought, until I realized that when people enter sentences, usually they do so in multiline textboxes, as they’re easier to see everything you’re doing. This regex works until the user hits the “Enter” key and inserts a new line. After much research and hair pulling, I eventually found the solution:


with {1},{2}, and {3} meaning the same thing. The interesting thing about the “.” character in regexes is it means “match any character…..except new lines and carriage returns”, which means if you’re using multiline textboxes, you have to account for that. So I had to prepend “^(.|\r|\n)*” and append “(.|\r|\n)*$” to my already unwieldy regex. “\r” is a carriage return and “\n” is a new line. The “^” symbol means start at the beginning of the string, and the “$” means continue to the end of the string, with the “*” symbols meaning repeat as often as necessary.

To finalize the product, I simply plugged all of this information into a shared function that returns the proper regex (based on a parameter that determines if I’m using it on a regular string, a textbox, or a multiline textbox) and set my validator’s ValidationExpression at runtime based on the word I was looking for. It actually works pretty well… so far…. ūüôā

All in all, I think I like regexes. They are undoubtedly powerful and can save many programming hours if you know how to use them. I know the initial function I was using to find words in a sentence took me maybe two hours to write and it didn’t even work all the time. It was also about 200ish lines of code. My new function using regexes is 17 lines of actual code, and 7 of that is a Select statement for string/textbox/multiline textbox.

While the initial learning curve is quite steep for regexes, if you’re serious about programming, I highly suggest that you take a day or two to learn them, as that day or two investment could save you weeks or months down the line of your programming career.

Some regex resources:

What’s your craziest regex?

May 15, 2009 Posted by | ASP.NET, Javascript, Regex, VB.NET, Visual Studio.NET | 1 Comment

ASP.NET: Images in DropDownLists?

I am having a major dilemma; apparently there is no easy way to add images to list items in a DropDownList. This to me seems ludicrous. I would like my user to be able to pick an icon from a dropdown and afterwards be able to grab that value to update my database. I’ve seen it done elsewhere, I just don’t remember where. I’ve seen solutions like EasyListBox, but I’m not about to shell out $100 for this little bit of functionality, and I’ll be damned if I’m gonna stare at their advertisements in their demo version. I’ve also seen people suggest a DHTML (CSS/Javascript) solution from¬†DynamicDrive.com, but I was unable to find any sort of applicable solution.

THERE MUST BE A WAY. Please help!

Status: Unsolved
Solution: None yet.

March 15, 2008 Posted by | ASP.NET, CSS, Javascript, VB.NET | | 3 Comments

ASP.NET and AJAX: Error Making Forms Visible With UpdatePanel

While converting a site to a MasterPage-driven site, I ran across an issue involving UpdatePanels, Panels and Forms. The scenario is that in my MasterPage, I have an UpdatePanel that wraps my ContentPlaceHolder, thereby applying the AJAX functionality to all pages associated with that MasterPage. The content page in question has a panel that is invisible until a button is pressed. The contents of the panel are two non-server forms for PayPal and Google Checkout. Before I converted the site to MasterPages and AJAX, the functionality performed correctly, but afterwards, the site would hang (ie, not complete the server side action), and the browser would produce the Javascript error:

“Unknown runtime error”

I tried many different combinations of contents for the panel, but the only one that seemed to produce the error was whenever a form was present inside the panel. This was very frustrating, as no one around the internet community really seemed to have run across this error, and modifying the MasterPage to account for this single scenario would be a nightmare.

A working solution I came up with for this rare error is to wrap your content (on your .aspx page) with another UpdatePanel and set your triggers to post back when the button is pressed. While the client may have to suffer another postback, it’s not as bad as a total loss of functionality.

If you can find a more elegant solution to this problem, I would love to hear it!

EDIT (2/29/08): I believe the error occurs¬†whenever you are using nested HTML forms within your runat=”server”. If you’re looking to post to another form, please see my article on integrating PayPal and Google Checkout.

January 18, 2008 Posted by | AJAX, ASP.NET, Errors, Google, Javascript, MasterPages, PayPal, UpdatePanel | Leave a comment

Javascript: jQuery. Interesting.

I do not know Javascript at all. I know, I know, you say, “How can you consider yourself a real developer and not know any Javascript?” Well, I don’t not know Javascript; I can work within it. I just couldn’t create a document using it.¬†This is probably due to the paradigm of “Javascript is evil” being pounded into my head during my nascent developer years.

Regardless, I would at some point like to learn. For those who are like me and don’t know any Javascript, maybe this is the place to start: jQuery. While it is in no way close to actual Javascript syntax, it is somewhat similar to .NET syntax, which should probably help reduce the learning curve a bit. Basically it’s a library that enables you to circumvent common Javascript pitfalls while providing you with the ability to code more while actually writing less.¬†It has some built in functions and abilities, and appears as though it will simplify the application of true AJAX.

Sound interesting? I thought so.

December 11, 2007 Posted by | AJAX, Javascript, Tips & Tricks | | 1 Comment

ASP.NET Nested MasterPages: ID Mangling

After I implemented the ASP.NET PayPal solution for the order submission part of my site, I noticed that my color picker (which relies heavily on Javascript) wasn’t working anymore.¬† I did a bit of digging in my code¬†and eventually discovered the source of the problem: ID mangling.¬†While I was aware that ASP.NET mangled control IDs, I was not aware that each time you nest a MasterPage, you change the way the ID is mangled.

For example, my original post-mangling ID was “ctl00_cphMain_txtBackgroundColor”, and after I nested my MasterPages, the ID changed to “ctl00_ctl00_cphMain_cphMain_txtBackgroundColor”.¬† So, when using the document.getElementByID() function,¬†it couldn’t locate the control, and thus threw me a yellow triangle.¬†

This really shouldn’t affect anyone who doesn’t include much Javascript in their code, but should be a good FYI for those who do.¬† I guess the silver lining is that at least the IDs are mangled predictably ūüôā

kick it on DotNetKicks.com

October 19, 2007 Posted by | ASP.NET, Javascript, MasterPages, Tips & Tricks | 2 Comments

ASP.NET: How To Get Browser Dimensions?

I’ve run across the issue of how to pull up the browser dimensions without using javascript.¬† One would think that Request.Browser.ScreenPixelsHeight and .ScreenPixelsWidth would suffice, right?¬† Well, no. Unfortunately, this only returned 640 x 480 every time I refreshed the page in different dimensions of browser window and at different resolutions.¬† What exactly does this “640 x 480” actually mean? I can’t seem to put my finger on it.¬†

It would be nice to know (without depending on Javascript) what the user’s dimensions are for a certain image of which I want to show a blowup using the ModalPopupExtender.¬† As it is, since the ModalPopupExtender freezes the panel in place regardless of scrolling, if my image is too big, some browsers won’t see everything, so I would like to give users with smaller browsers a scaled-down blowup image.¬† I suppose a little¬†Javascript to determine these dimensions wouldn’t hurt since they have to have it on to use the ModalPopupExtender anyways, but I try not to depend on Javascript for functionality.¬† Anyone have any insight?¬† Thanks!

August 22, 2007 Posted by | ASP.NET, Javascript, ModalPopupExtender | 1 Comment

ASP.NET and Javascript: Accessing Server Side Code?

While writing some code today, I had an idea to improve user experience with a smidge of Javascript. Basically, click on a picture to show its enlarged version (using a ModalPopupExtender), and then on close, run some Javascript to have the appropriate radio button be selected for the image the user just looked at.¬† No problem, two lines of Javascript, and I don’t even know it that well (although, ASP.NET makes it a pain in the arse to match up control ID’s since they mangle them at run time.¬† If you’re having problem with ASP.NET changing control ID’s, run your app and check the source code.¬† Usually your control’s ID is something like “ctl00_somePanel_yourControlID”).¬†

However, I wanted to run some additional events when certain radio buttons were selected, like hiding or showing¬†certain other panels.¬† This is easy on the back end, but since I’m already running the ModalPopupExtender, the server side “OnClick” event for the button doesn’t actually fire.¬† Rather than write some more Javascript to cover all the different permutations of possibilities that could occur, I would rather invoke the server side code once the Javascript has stopped running.¬† I found this article about Remote Scripting¬†at the Code Project, but it seems far too complex for what I want to do.

Anyone have any ideas on how to call server side code via Javascript?¬† Or should I just suck it up and have my viewers suffer a postback?¬† Or better yet, is there a way to get the “OnCheckedChanged” (for the radio button) event to fire from the Javascript, rather than actually calling the server side code?

August 20, 2007 Posted by | ASP.NET, Javascript, ModalPopupExtender | 3 Comments