Saturday, May 14, 2011

JavaScript: Get your console on…

Since I have been listening to both the “Official jQuery Podcast” and the “yayQuery podcast” JavaScript and jQuery have been on my mind lately.  It doesn’t hurt that some bugs I have fixed at work required mucking around in some jQuery.  Someone from one of those podcasts referenced some things that you can do with the console in both IE and Firefox (with Firebug). Today I wanted to show some of the power of playing with the console.

I will be using IE 9 as my example browser today but you can do these things in Firefox and Google Chrome.  So first lets open IE 9 and go to www.devdave.com.  Press F12 to open up the developer tools of IE (documentation).  You should notice an explorer bar, usually across the bottom of the screen.

image
  1. In the HTML tab press the arrow button. (This will allow you to select an html element on the screen.)
  2. Move the mouse and click the div containing the random quotes displayed on the site.
  3. Note that there is a tree view that represents the document object model and it is now highlighting the object that you selected.  Note that here you can see the class that this object has applied to it.  We are going to use that along with some jQuery to make that div slide up without having to write the code in the page.

Now that we know the class assigned to the div we can use that as a selector in jQuery.  Two tabs over from the HTML tab there is a Console tab clicking that will open up a new part of the developer tools.

image At the bottom of the screen you should see >> .  This is where you can type some JavaScript.  In order for the following to work the page you are working with needs to already have loaded jQuery.  Since this page has already done that lets go ahead and type

$(".tm-section")

into the console and press enter.  Note that the console is displaying a bunch of information regarding the object you selected.  If the selector you typed was correct you should see that the length property returns a value of 1.  If we had mistyped the selector then the length would be 0.

This would be a great way to practice using different types of selectors.

Since we have the correct selector we can type this to make the selected object slide up.

$(".tm-section").slideUp("slow")

And then we can type this to make it slide down.

$(".tm-section").slideDown("slow")

 

image So one line to write code might not be enough. Lets say you wanted to write a function or two. The console window has a button on the far right of where you type commands it’s the chevron symbol next to the green play button.  Clicking that will open a text area where you can write multiple lines of code.  Write the following in the script area and click the Run Script button.

 

function toggle(){
   $(".tm-section").slideToggle('slow', function(){
     alert("done");    
   });
}

toggle();

Pressing the Run Script button multiple times will cause the slide to toggle and an alert message to be displayed when its done.

As you can see this technique can really help in debugging or interrogating already running JavaScript. I have used this technique to debug asynchronous data paging issues, Google map marker issue.or just figuring out the correct selector syntax to select one or more objects in the DOM.

Podcasts I listen to

I know, not really a technical post but I would like to list out the podcasts I listen to.  Since I started working at a new job my commute takes just about an 1 hour to get to work.  The good thing about that is it gives me more time to listen to a full podcast instead of having to break it up between the drive to and from work.

Here is the list of podcasts along with links to their websites:

Friday, April 15, 2011

JavaScript, the revealing module pattern

Lately I have been doing a lot of things with JavaScript and jQuery.  After doing some research I found some information on the revealing module pattern.  This pattern has really helped me to organize the work I do in JavaScript.  I find this to be very easy to read and debug.

  1. var Module1 = function () {
  2.     var selectors = {
  3.         nameTextBox: '#nameTextBox',
  4.         cancelButton: '#cancelButton'
  5.     }
  6.  
  7.     var urls = {
  8.         cancelUrl: 'http://homepage.com'
  9.     }
  10.  
  11.     var privateFunction1 = function (msg) {
  12.         alert(msg);
  13.     }
  14.  
  15.     var privateFunction2 = function (msg) {
  16.         privateFunction1(msg);
  17.     }
  18.  
  19.     var init = function () {
  20.         $(selectors.cancelButton).click(function () {
  21.             window.location = urls.cancelUrl;
  22.         });
  23.     }
  24.  
  25.     return {
  26.         selectors: selectors,
  27.         urls: urls,
  28.         init: init,
  29.         publicFunction: privateFunction2
  30.     }
  31. } ();
  32.  
  33. $(document).ready(function () {
  34.     Module1.init();
  35.  
  36.     Module1.publicFunction("Testing 123");
  37. });

The module consists of lines 1 – 31, you can see that all items defined in the module are locally scoped to the module.  Lines 25 – 30 define what will be publicly accessible outside of the module.  Note that line 29 defines a different public name in comparison to its internal name.  Also note that objects inside of the module can access each other.  Line 16 is calling the private function on line 11.  Trying to call privateFunction1 from outside the module would not be possible.

Also in this example I am showing some common things I like to do.  For example lines 2 – 5 define an object for selectors.  I make this selector object public incase the page that consumes this module needs to change the values.  Everywhere else in the module I call the selectors from the selector object.  This way if I need to change a value either manually in this script or dynamically from the page it is only done in one place.  Note lines 7 – 9 define the same thing although this time its urls.  Since I do a lot of my work in MVC I assign the url values on the consuming page using the url helpers.

In another post I will go over the organization and utilization of this pattern in an MVC 3 application.

Sunday, March 20, 2011

Modifying the jQuery UI Calendar Date Selection

While working on an application I had a need to modify the way dates where selected from the jQuery UI calendar control.  I needed to only allow the end user the capability of selecting a Monday.  After some searching of the internet I found the following solution.

/* date picker week */
$(".dateweek").datepicker({
    showOn: 'both',
    buttonImage: '/Content/Images/ui/calendar.png',
    buttonImageOnly: true,
    firstDay: 1,
    beforeShowDay: function (date) { return [date.getDay() == 1, ""] }
});

I can’t remember where exactly I got it although I did make some modifications to it.  The code I actually used is above.

Thursday, February 24, 2011

Fun with the SQL Output clause

The other day I was brushing up on my SQL skills by watching some training videos on Pluralsight. As I was watching, the presenter showed how the Output clause works. After playing around with it some more I decide to do this blog post.

So lets get started.  First lets create a temp table to work with.

create table #temptable (
    ID int not null identity primary key,
    FirstName nvarchar(100) null,
    LastName nvarchar(100) null,
    Cartoon nvarchar(100) null
)

Now lets insert some data using the output clause as part of the insert.  Note the script below is using the Table Row Constructor syntax.  This becomes extremely powerful when used with the output clause.

insert into #temptable
output inserted.ID, inserted.FirstName, inserted.LastName, inserted.Cartoon
values
('Fred','Flintstone', 'The Flinsones'),
('Wilma','Flintsone', 'The Flinsones'),
('Pebbles','Flintstone', 'The Flinsones'),
('Dino','', 'The Flinsones'),
('Barney','Rubble', 'The Flinsones'),
('Betty','Rubble', 'The Flinsones'),
('Bamm-Bamm','Rubble', 'The Flinsones'),
('George','Jetson', 'The Jetsons'),
('Jane','Jetson', 'The Jetsons'),
('Judy','Jetson', 'The Jetsons'),
('Elroy','Jetson', 'The Jetsons')

When this script is ran in SQL it will insert the rows into the temp table and return a result set that looks like this:

ID FirstName LastName Cartoon
1 Fred Flintstone The Flinsones
2 Wilma Flintsone The Flinsones
3 Pebbles Flintstone The Flinsones
4 Dino   The Flinsones
5 Barney Rubble The Flinsones
6 Betty Rubble The Flinsones
7 Bamm-Bamm Rubble The Flinsones
8 George Jetson The Jetsons
9 Jane Jetson The Jetsons
10 Judy Jetson The Jetsons
11 Elroy Jetson The Jetsons

The inserting of data and the returned result set is done as a single transaction or round trip to the server.  The other benefit to this is the result set included the ID (identity) of each row.  Normally I would have re-queried the data to get this information.

Now let me show you an update using the output clause.  In the script below I am fixing the misspelling of Flintstone.

update #temptable
set Cartoon = 'The Flintstones'
output inserted.ID, deleted.Cartoon OldCartoonValue, inserted.Cartoon NewCartoonValue
where Cartoon = 'The Flinsones'

When the script is ran in SQL it will update the rows and return a result set that looks like this:

ID OldCartoonValue NewCartoonValue
1 The Flinsones The Flintstones
2 The Flinsones The Flintstones
3 The Flinsones The Flintstones
4 The Flinsones The Flintstones
5 The Flinsones The Flintstones
6 The Flinsones The Flintstones
7 The Flinsones The Flintstones

Note that once again a single transaction to the server and a result set that references the ID’s that where updated along with the old cartoon value and the new cartoon value.  Keep reading below to learn more about the inserted and deleted column prefixes.

Now let me show you a delete with the output clause.  In this script below I am deleting any rows that have the last name of “Rubble”.

delete #temptable
output deleted.ID, deleted.FirstName, deleted.LastName, deleted.Cartoon
where LastName = 'Rubble'

When the script is ran in SQL it will delete the rows and return a result set that looks like this:

ID FirstName LastName Cartoon
5 Barney Rubble The Flintstones
6 Betty Rubble The Flintstones
7 Bamm-Bamm Rubble The Flintstones

Not that once again a single transaction to the server and a result set that references the rows that where deleted.  Imagine if you used this in some sort of logging situation.

When using the output clause there are two special column prefixes to use:

  • Deleted: Is a column prefix that specifies the value added by the insert or update operation. Columns prefixed with INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed but before triggers are executed. (DELETED cannot be used with the OUTPUT clause in the INSERT statement.)
  • Inserted: Is a column prefix that specifies the value added by the insert or update operation. Columns prefixed with INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed but before triggers are executed.(INSERTED cannot be used with the OUTPUT clause in the DELETE statement.)

Wednesday, February 2, 2011

Getting custom extension methods to work in ASP.NET MVC 3 & Razor View Engine

I am going through the process of converting my site to use ASP.NET MVC 3 with the new razor view engine.  I use many extension methods that I have added to the HtmlHelper.  I store all these helpers in the following namespace “DevDave.Infrastructure.Helpers”.

In MVC 2 I added the namespace “DevDave.Infrastructure.Helpers” to the web.config file in the root of my MVC project like so:

<pages>
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="DevDave.Infrastructure.Helpers"/>
  </namespaces>
</pages>

This allowed me to use my custom helpers in all of my pages. So naturally I figured that the same thing would work for the MVC 3 application.  As it turns out it doesn’t, I get this stupid error instead:

image

As you can see it can’t seem to find my extension method “MainMenu”.  Now I did figure out that you could just add a using statement to the top of each page like this:

@using DevDave.Infrastructure.Helpers

Well I don’t want to have to put this in every view so then I tried to add the using statement into the _ViewStart file in the root of the views folder.  Like so:

@{
    using DevDave.Infrastructure.Helpers;
    
    Layout = "~/Views/Shared/_Layout.cshtml";
}

This did not work either something about having a using statement inside a code nugget.  So I moved it to its own line like so:

@using DevDave.Infrastructure.Helpers

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

This still did not work.

To fix this I had to add the name space to the web.config inside of the views folder instead.  Like so:

<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <add namespace="DevDave.Infrastructure.Helpers"/>
    </namespaces>
  </pages>
</system.web.webPages.razor>

This fixed the problem.

Getting Ninject to work with MVC 3

Before getting started lets make sure everyone is on the same page.  The screenshots and descriptions below assume the use of the following products and tools.

  • Visual Studio 2010
  • ASP.NET MVC 3
  • .NET 4.0 framework

Lets start by creating a new ASP.NET MVC 3 Web Application

image

Lets go ahead and choose the Empty template.  We can bypass using a Test Project at this time.

image

Once the solution is created lets add the following folder structure:

image