.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

Simple jQuery Expand/Contract Functionality

I can’t express enough how much learning jQuery has expanded my ability to simply and dynamically add amazing effects very easily to my User Interfaces. Maybe I should start a jQuery blog? 🙂

One feature I come across a lot is the ability to expand and contract a section of the page, say a <div>. Before when I wanted to do this, I had to resort to either adding markup to my code and importing huge function-specific script files (ie, all they did was perform the expand/contract) or rely on ASP.NET’s AjaxToolkit’s Collapsible Panel Extender. While these solutions… worked… I was never really comfortable using them, and they were hardly reusable or scalable. Enter jQuery.

Let’s say I have a bit of HTML that is like so:

<p class="toggle">Expand/Collapse</p>
    <p>Some text goes here!</p>
<p class="toggle">Expand/Collapse</p>
    <p>Some more text goes here!</p>

If you wanted the ability to show/hide that following div, the jQuery is ridiculously simple:

$(document).ready(function() {
    $(".toggle").click(function () {

Yes, literally that’s it. So long as you keep with the HTML convention above, that’s all the jQuery you would need. You don’t have to add any extra markup or link one ID to another or anything. It’s all done via jQuery, and pretty much in one line ($(this).next("div").slideToggle("fast");).

Of course, sometimes you may want to do more. For instance, what if you wanted to change the text of the toggle button? Assume now that “Expand/Collapse” now reads “View Additional Info”. Here’s your jQuery:

$(document).ready(function() {
    $(".toggle").toggle(function () {
        $(this).text("Hide Additional Info")
        }, function() {
        $(this).text("View Additional Info")

Extremely simple, elegant, and even intuitive! If you ever doubted jQuery’s power before, you may want to reconsider. I sure did.

July 31, 2009 Posted by | 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

Shameless Plug: Quotidian Word

The site is now live! Check it out: http://www.quotidianword.com. For those who know me, you know that I am a perfectionist and that I pour every ounce of me into whatever project I’m in. This site is no exception. It has some very cool technical features as well as simply just being easy, fun, and actually educational if you use it right. My favorite feature is the dynamic signature bar that you can drop in a forum signature:


You should see that this image will change every day, staying current with the current word. It’s a cool way to keep your signature fresh and interesting (at least I think so 🙂 ) Anyways, I hope you enjoy using the site as much as I do, and as much as I enjoyed making it!

June 22, 2009 Posted by | ASP.NET, Portfolio | , , , | 3 Comments

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

Visual Studio/VB.NET: How To Easily Document Your Code

If you’re a routine Visual Studio user like me, I don’t need to tell you how awesome Intellisense is. Not only would some of us be lost without it, but it also helps us be way more efficient programmers either through simple selection of methods or properties or by discovering new object members that maybe we didn’t know about previously. Additionally, one of the main benefits of Intellisense is that it tells you  about the item in question, for instance, that the String.IsNullOrEmpty() function “Indicates whether the specified System.String object is null or an System.String.Empty string.”

Visual Studio Intellisense

When writing my own objects, however, I used to find myself yearning for this kind of help for my own functions. Wouldn’t it be great to get Intellisense to tell me what that “GetUserInfo” function I wrote five weeks ago does rather than me having to go look it up? What about what those parameter names mean? Luckily, there is a way, and it is super easy.

For example, let’s say you have an object that returns its own permalink in a shared function called GetHTMLPermaLink(). To document it, simply place your cursor above the function and press the apostrophe key three times: '''. Automagically, the following pops up:

Function Documentation

All you have to do is fill in the blanks and viola, you have documented code! (NOTE: in C#, I believe the syntax is /// but I’m not sure.) To see this in action, after you fill in the appropriate information, go try to pull up your function somewhere and watch the magic:

Visual Studio Intellisense

More information on Visual Studio Code Documentation (C#)

Happy documenting!

May 20, 2009 Posted by | Tips & Tricks, VB.NET, Visual Studio.NET | , , | 5 Comments

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: Create a User Control Property with Selectable Options

I guess I’ve always taken those little options for granted whenever I want to pick something in a control, say what mode to put a textbox in (text, multiline, or password), because when I wanted to add something similar for a user control, I had no idea how to do it. Thanks to the friendly and extremely helpful people at StackOverflow, I was able to grok the answer.

Intellisense options

Here’s the scenario: you have a user control in your .aspx page with one property, say “addedorapproved” as in the above image. You want the options “Added” and “Approved” to show up as your selectable options. To do so, you must complete the following steps:

  1. Create an enum with your available options:
    Enum AddApproveOptions
    End Enum
  2. Create your private member as your Enum:
    Private _addedapproved As AddApproveOptions
  3. Create your property as your Enum:
    Public Property AddedOrApproved() As AddApproveOptions
    Return _addedapproved
    End Get
    Set(ByVal value As AddApproveOptions)
    _addedapproved = value
    End Set
    End Property

 And that’s it! You should see the little Intellisense box pop up with your options for your new property!

February 5, 2009 Posted by | ASP.NET, Tips & Tricks, VB.NET, Visual Studio.NET | 4 Comments

Google Search Funny

Although a bit unrelated to .NET, this was too funny not to share:

Every morning, I go through my www.columbussupply.com logs to see how products are doing, which are being visited, and where people come from to see how we’re placed and what other products show up. One such referral URL caught my eye: http://www.google.com/search?q=Deluxe+Model+Inflatable+Woman&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Which results in this (Note: I moved the results count to the left in photoshop to keep the image smaller):

Google Screen Shot

Yes, that is someone searching for a blowup doll and found my site. As the first result in Google. At 6am. Hey, traffic is traffic, right?

December 3, 2008 Posted by | Google, Random | 1 Comment

Advertising Update

After speaking some more with the “powers that be” I decided to go forth with the ad units. You can find them on any product page at www.columbussupply.com. I tried to blend the ads into the theme of the site without hiding them entirely. The purpose of the ads is still for them to be clicked, but not to overpower the message of the product description, as the purpose of the product description is still to sell the product. Essentially, we’re trying to monetize the casual browser who is not really intending to buy anything but is rather looking around or comparison shopping. Those who are looking to buy something will buy something, ad click or not, since we really (actually) do have the best prices on the internet for virtually everything we sell.

I’m not new to adsense or the placement of ads. I am aware that the placement of the ad is not optimal for the best clickthroughs, but that’s not the point. I don’t want my customers to see an ad as the first thing on the page, but rather as they work their way down and have already been served the product description message. The primary goal is to sell products, and I feel that some people may get turned off if they are bombarded with ads as soon as they hit the page.

I’m interested to hear feedback on how the ads are placed, if they’re too overbearing, too obvious, not obvious enough, whatever. Do the ads serve their purpose?

November 10, 2008 Posted by | Random | , | 2 Comments