.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

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

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

BlogEngine.NET: How To Customize Your Blog With New Class Objects

I’ve been working pretty extensively with BlogEngine.NET¬†over the past few months and have learned a lot about its inner workings. My project (www.madcowultimate.com) has essentially used the BlogEngine.NET platform (connected to a MySQL database) as a base to create a full-fledged website. Of course, all of the customization I’ve done to the core would mean that I am stuck with this version ( of the platform, but so far I am okay with that. It serves my purposes for the most part, and everything else I can make work to fit my needs.

One of the major parts of customizing the core to shape the BE.NET platform into your custom solution is creating your own business classes. For instance, in my site, I needed a way for my teammates to check the status of practice, since some of them come in from out of town and would probably prefer to know if practice is on or off for that day before driving in. Thus, I created the Practice class in the BlogEngine.Core namespace to populate a widget displaying the status.

How did I do this? Well, I wish it was as easy as 1, 2, 3, but this project is a little more complex than that. I have definitely learned a lot by wading through the code, but I have also made some mistakes and wasted some time trying things out that did not work. I will break it down for you into manageable chunks, but you will still need to know certain things, like SQL (or MySQL), data table architecture, how classes and objects fundamentally work, and a little bit about inheritance and abstraction.

The following will assume that you have successfully created your blog on your webserver and that you are hooked up to a database (I will use MySQL in this example). I would highly recommend you back up your entire project before embarking on any changes that may affect your blog (especially changes to the core).

First things first, open BE.NET in Visual Studios and expand BlogEngine.Core. You should see a list of familiar-looking classes like Post.cs, Page.cs, and Category.cs. To create your own class, you will essentially need to model your class after these. Right-click on BlogEngine.Core and go to Add > Class… and type the name for your new class. For the purposes of this article, we’ll call it MyObject.cs.

At the top where you import classes, you will need to add at least “using BlogEngine.Core.Providers”, in addition to any other classes you will need (you can, of course, add any you need later). This will make it easier to hook your object up to the data provider. Next, put your object in the “BlogEngine.Core” namespace and have your object inherit the BusinessBase, like so:

namespace BlogEngine.Core
public class MyObject: BusinessBase

Inheriting the BusinessBase will do a lot of your work for you when it comes to managing your object, like knowing which properties have been changed and saving your data. Next you’ll want to create your constructor. You won’t use this very frequently (more on that later), but you still need to have it:

public MyObject(int id)
base.Id = id;

After this, create whatever properties you need using the following template:

private bool _myproperty;
public bool MyProperty
get { return _myproperty; }
if (value != _myproperty) MarkChanged(“MyProperty”);
_myproperty= value;

This alerts the BusinessBase when something has been changed so that it may take the appropriate action when you need to save your data. You can (and should) also create a read-only ID property by just returning the base ID:

public int MyObjectID
get { return Id; }

Of course you may create your own methods if you would like, but they are not required. The last step in your basic class construction is to override the base methods for data retrieval/storage/deletion. These are abstract methods delineated by the BusinessBase you inherited, so they are required by your class. When you are done, they should look like this:

protected override void ValidationRules()

protected override MyObject DataSelect(int id)
return BlogService.SelectMyObject(id);

protected override void DataUpdate()

protected override void DataInsert()
if (IsNew)

protected override void DataDelete()

You may have noticed at this point that your Intellisense isn’t coming up with the methods “SelectMyObject” or “UpdateMyObject” when you type in BlogService. This is because we need to add them to your BlogService class. This class is created to separate data access and business so any kind of data provider can be used without any change to how the class functions, therefore making it extremely flexible.

Before you modify your BlogService.cs class, you will need to add the abstract methods to your BlogProvider.cs class, which is in the “Providers” folder. This is where you create the outline for the methods you just outlined in your class. You probably can do this before the last step in your class construction (so that Intellisense will show up, thereby preventing any typos) but it’s not necessary so long as you’re keeping track of what you’re doing. Go ahead and add the following somewhere in that class file:

public abstract MyObject SelectMyObject(int id);
public abstract void InsertMyObject(MyObject obj);
public abstract void UpdateMyObject(MyObject obj);
public abstract void DeleteMyObject(MyObject obj);

This will create the framework for data access to your object that will be inherited by the respective providers.

Now go ahead and open your BlogService.cs class located in the “Providers” folder. Don’t worry too much about what is going on here, just know that a lot of work has been done on your behalf so that it is this simple (two lines of code!) to hook up your object to your data provider of choice per action required by your object. If you really want to look, expand the region in this file called “Provider Model” and look at the details. When you’re done adding your static methods for your object, it should look something like this:

public static MyObject SelectMyObject(int id)
return _provider.SelectMyObject(id);

public static void InsertMyObject(MyObject obj)

public static void UpdateMyObject(MyObject obj)
public static void DeleteMyObject(MyObject obj)

Finally, once all your structures are completed, you’ll need to add the actual functionality to your data access. This is done in the DbBlogProvider.cs file, also located in the “Providers” folder. As you will see, because this class inherits the BlogProvider class, it is mandatory that it include (and provide the behavior for) the methods you just described in the BlogProvider.cs. This becomes most obvious when you start typing your methods and Intellisense finishes the rest of your method signature.

This is the point at which you should start creating your data tables that are going to be accessed and modified by your blog, as you will need to know what tables to access and what fields to call in your SQL string!

After you have created your tables, you should go back to the DbBlogProvider file and create a region for your object’s data access methods and start filling them in with the appropriate SQL. Since I don’t know what your objects requirements are, I can’t really help you any further than this, other than to tell you to take a look at how other objects’ data is being accessed for the same behavior (for example, look at how a post is selected, inserted, updated, and deleted) and model yours off of theirs. This part probably takes the longest, since you need to know what to get and how to get it, but if you follow the other objects’ examples, you’ll see that you can benefit from a lot of copy and paste action.

After you complete all of your data access functions, you’re pretty much done! Now, how do you get an instance of the object you just built? Not in the typical manner, which would be to use the “new” keyword, but rather using the BusinessBase’s static .Load() function, or MyObject.Load(id);. Of course, once you’re done modifying the core, don’t forget to build it (right-click on BlogEngine.Core > Build)! If you get any errors, be sure to fix them, as your project will not work until the Core can compile.

I’m somewhat certain this covers the basic complexity involved in the creation of a new, custom object. I hope this saves someone some time! I wish I had known this before going into this project, as I know it would have saved me a lot of time and figuring out. Good luck, and let me know if I forgot anything, as I will gladly add it.

kick it on DotNetKicks.com

September 30, 2008 Posted by | ASP.NET, BlogEngine.NET, C#, MySQL, Tips & Tricks, Visual Studio.NET | , , , , | 2 Comments

AutoHotKey: The Greatest Program of All Time

Ok, so I know that this is a .NET blog, but people reading this are most likely programmers anyways, so I figured this would be at least somewhat relevent. If you missed the title of the post, AutoHotKey is the greatest program of all time.

If you are unfamiliar with what it does, basically you can create little shortcuts for yourself using their very simple and well-documented series of symbols and functions that will perform repetitive tasks for you.¬† For instance, I send a lot of emails every day to customers. Rather than type out “[Columbus Supply] Order: X[whatever] Thank you for buying from Columbus Supply!” into the subject line every time, I have created what’s called a “HotString” that types all that for me automatically! All I do is type “psubj” (a HotString I came up with) and it will type all of that out and then move the mouse to the left right in front of the X. This saves me maybe 10-15 mins a day, which may not seem like a lot, but it does a few things: it ensures there are no misspellings/typos, it reminds you to put the correct order number in, and it ensures consistency in subject lines. I have almost 20 of these scripts ranging from simple to complex (one script I have loads my entire purchase response letter into an email!). With all of these scripts used in a day, I’ve shaved a good 2-3 hours a day off of how long it takes me to process orders (and my typing is pretty good for the most part). Think about what you could do with an extra 2-3 hours a day.

My favorite new script that I came up with is a huge time-saver. I use Excel a lot to keep track of orders and I have several tabs in a templated order form. If you are an Excel user, you may well know that moving between tabs is not as easy as ctl+Tab, as that will simply move you between open Excel files. You actually need to hit ctl+PgUp/Dn to move between tabs. This is a bit awkward on the keyboard (especially on a laptop w/no easy NumPad), so I built a script that will move between tabs when I type ctl+right/left arrow key. I say “built” but it was really really simple. Here’s the whole script:

#IfWinActive ahk_class XLMAIN

Yep, three lines of code to create immensely easier tab paging that only works in Excel when Excel is the active window. The possibilities are literally endless.¬† There is some minor setup involved, but if you are somewhat computer-inclined (ie, you understand what’s going on in the contents of this blog), it should be fairly simple and straightforward.

What scripts have you come up with that have made your life incredibly easier?

August 26, 2008 Posted by | Tips & Tricks | | 2 Comments

State of the Coder: Code Complete 2, Promo Codes, BlogEngine.NET

I just recently purchased Code Complete 2¬†by Steven McConnell, and am quite excited to read it, especially after all the coding I’ve done recently.¬† I’ve heard some great things about the book, and being a self-taught programmer, I’m pretty excited to learn the right way to do and think about some things.¬† I can’t really review it yet (as I’ve read maybe 4 paragraphs in the preface as of this writing), but I will share some of the tips that I glean from this work as I get through it (more regularly than I have been doing).

I’ve been working on a few projects here, some for business and others for pleasure, and they’ve kept me busy. One of which is the building of a Promo Code engine into my site at www.columbussupply.com. Let me tell you, it’s no easy task, especially since PayPal does not accept negative amounts (pretty hard to apply a discount!), but I’m sure I’ll figure it out in time.¬† The problem has three parts: 1) how to display the discount to the user (easy), 2) how to track the promo/prevent it from being abused¬†(harder), and 3) how to transfer the information to PayPal/Google Checkout so that the transaction appears seamless to the user (hardest).

This third part has gotten me stuck a little.¬†I don’t want to change the display to the user, but I need to find a way to transmit the discount to PayPal. One idea was apply the discounted amount to the last item in the cart (that has a price higher than the discount) with a note on it that mentions the promo code. That may work, but it may be confusing and is definitely kludgy. Anyone have any ideas how to combat this?

As for my pleasure work, I’ve been hacking away furiously at the newly released version of BlogEngine.NET, which has been pretty fun, for my Ultimate Frisbee team’s website, www.madcowultimate.com (as of this writing, there’s nothing there, but there will be very soon).¬†BE.NET is¬†a great open-source blogging framework that is very¬†well-designed and somewhat easily customizable. The official version is in C#, but there’s also a VB.NET version floating around. I considered the VB.NET version for a bit, but I decided to stick with the C# version for a few reasons, the main being I realize I need to learn C#, and that some of the techniques they use in this app are so advanced that I wouldn’t know what they were in VB.NET or C# or even English. So far I’ve had pretty good success and I’ve learned a whole bunch about the language as well as good coding practices. I would suggest that even if you don’t want to use it, you should download it¬†just to look at how it was built (how often do you get to peek at the work of professional .NET coders?).¬†

I’ve discovered (reported, and corrected!) a few bugs, added some new features, built my own theme, and created my own widgets (somewhat) successfully. I’ve also opted to use the MySQL option included with the app, which has been awesome for me because that’s the DB I’m most comfortable with.¬† Overall, I’d rate this app very highly because there are a ton of features that you can use (even though I probably won’t use half of them) and it is so easy to modify.¬† Occasionally you may have to dip into the Blogengine.Core if you REALLY want to customize things (such as create your own data access methods), but so long as you don’t mess around too much, you should be fine.

Anyone else having a good ol’ time with BE.NET? I’d like to see your work!

August 15, 2008 Posted by | ASP.NET, Books, C#, Google, MySQL, PayPal, Tips & Tricks | | Leave a comment

Visual Studio.NET: How To Comment/Uncomment Large Blocks of Code

Just a quick tip that I find extremely useful: To comment a large block of code (at least for VB.NET, I don’t know if it works in C#, but I assume it does), highlight the area you want to comment out and hold Ctrl and press K and then C. To uncomment, highlight the commented area and hit Ctrl + K + U. The mass uncommenting merely removes the forward-most apostrophe, so if you have actual comments in your commented code that were included in your initial highlighted region, they will remain comments upon uncommenting.

I use this technique a lot for debugging large areas of code.

April 14, 2008 Posted by | ASP.NET, Tips & Tricks, Visual Studio.NET | 9 Comments