jQuery–Preventing default link behaviour

 

This sample shows you how to hijack the default behaviour of the anchor tag and do something different.
The interesting part is that we use the event arg in the click function, once we have this actual arg we can call preventDefault(); on it to stop the navigation if necessary.

In this sample I just toggle the visibility of my div with a default animation (now you see it now you don’t)

 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
   <script type="text/javascript">
       $(function () {
           $("a").click(function (event) {
               event.preventDefault();
               $("div").toggle("slow");               
           });
       });     
   </script>
 <style type="text/css">
    div.test { width:362px; height:20; background-color:Red; }
 </style>
 
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
     <div  class="test">
     <p>this is a test</p>
     </div>
 </body>
 </html>

MVC Scaffolding and EF4CodeFirst–A data driven website in under a minute!

.

 

Here’s a run through on how to create a data driven web application in under a minute. I’m going to create a simple part tracking system as to manage the vast amount of helicopter parts lying about my garage. Some parts I’ll never use, some parts are missing little comprising bits, the idea is to deploy the application as part of the club website allowing members to quickly find a part in a hurry for the big upcoming competition

Lets get started:

1) Install MVC Scaffolding if you’ve not done so before, go to the package console and type Install-Package MvcScaffolding

image

  • Create a class for the part

image

image

Now type Scaffold Controller PartModel

image

 

Here you see that all the views get created, hey and they are even DRY

If you want to make unit testing easier or suport Ioc etc you can use the –Repository flag.
If you need to rescaffold then use –Force.

 

Ok so we’re 50 seconds into this at this stage, and we could just run the application now provided we’ve got sqlexpress installed. However if you won’t we can use SqlCompact version.

Drop back into the Package Manager Consoler and

Install-Package EFCodeFirst.SqlServerCompact
 
 

image

That’s it, Q.E.D.

“Knock, knock.” -- “Who’s there?” -- long wait... -- “Java.”

 

So whose faster? Well C# or Java if you are talking “RAD”, but who executes faster?

IMO, C# and Java can be just as fast or faster because the JIT compiler (JIT or just in time is a compiler that compiles your IL the first time it's executed). JIT compiler can make optimizations that a C++ compiled program cannot because it can query the machine. It can determine if the machine is Intel or AMD; Pentium 4, Core Solo, or Core Duo; or if supports SSE4, etc.

A C++ program has to be compiled beforehand usually with mixed optimizations so that it runs decently well on all machines, but is not optimized as much as it could be for a single configuration (i.e. processor, instruction set, other hardware).

Additionally certain language features allow the compiler in C# and Java to make assumptions about your code that allows it to optimize certain parts away that just aren't safe for the C/C++ compiler to do. When you have access to pointers there's a lot of optimizations that just aren't safe.

Also Java and C# can do heap allocations more efficiently than C++ because the layer of abstraction between the garbage collector and your code allows it to do all of its heap compression at once (a fairly expensive operation).

Now I can't speak for Java on this next point, but I know that C# for example will actually remove methods and method calls when it knows the body of the method is empty. And it will use this kind of logic throughout your code.

So as you can see, there are lots of reasons why certain C# or Java implementations will be faster.

Now this all said, specific optimizations can be made in C++ that will blow away anything that you could do with C#, especially in the graphics realm and anytime you're close to the hardware. Pointers do wonders here.

Of course, C# (or Java, or VB) is usually faster to produce viable and robust solution than is C++ (if only because C++ has complex semantics, and C++ standard library, while interesting and powerful, is quite poor when compared with the full scope of the standard library from .NET or Java), so usually, the difference between C++ and .NET or Java JIT won't be visible to most users, and for those binaries that are critical, well, you can still call C++ processing from C# or Java (even if this kind of native calls can be quite costly in themselves).

Keyboard window shortcuts Win7

 

If like me you prefer to learn keyboard shortcuts and sell your soul in order to avoid moving the mouse, then you’ll like these shortcuts that I’ve stumbled upon this evening.

  • Win]+[Left Arrow] : Dock the active window to the left of the screen
  • [Win]+[Right Arrow] : Dock the active window to the right of the screen
  • [Win]+[Up Arrow] : Maximize the active window
  • [Win]+[Down Arrow] : Restore from the Maximized Position, or Minimize as an active window

And for the multi monitor people out there………

[Win]+[Shift} +[Right or Left Arrow] : Move the active window from once screen to the other

.NET 4.0 Code Contracts

 

Yesterday I read an interesting article on a flight home from Amsterdam and though I would share it with you.

One of the generally excepted approaches of writing functions is to validate you input arguments before using them, If-Then-Throw pattern.

Now .Net 4.0 supports Design by Contract approach to software design .NET 4 code contracts. Lets dive straight in (as always Smile)

 

   1:  using System.Diagnostics.Contracts;
   2:   
   3:  public class Calculator
   4:  {   
   5:      public Int32 Sum(Int32 x, Int32 y)
   6:      {        
   7:          Contract.Requires<ArgumentOutOfRangeException>(x >= 0 && y >= 0); 
   8:          Contract.Ensures(Contract.Result<Int32>() >= 0);         
   9:          
  10:          if (x == y)            
  11:          return 2 * x;         
  12:          return x + y;    
  13:      }  
  14:      
  15:      public Int32 Divide(Int32 x, Int32 y)    
  16:      {
  17:          Contract.Requires<ArgumentOutOfRangeException>(x >= 0 && y >= 0);       
  18:          Contract.Requires<ArgumentOutOfRangeException>(y > 0);
  19:          Contract.Ensures(Contract.Result<Int32>() >= 0);      
  20:          return x / y;    
  21:      }
  22:  }

Here we see just how powerful contracts can be, have a look at Dino Esposito’s article above for more information.

jQuery Template Example

 

Straight to screenshot

image

Ok so I’m here in a hotel in Germany, been stuck in java all day so I needed .net like a drug this evening.

Let me describe what you see above.

The screenshot is from WebMatrix it shows the default webpage where I’m presenting some JSON data to the user. The data itself is just a list of model helicopter types and ratings out of 10 for each (subjective of course). The JSON in this case is hardcoded client side but could of course come from aywhere e.g. a server side MVC action called with jQuery.ajax etc.

The real good stuff comes from the following lines

<script id="modelHeliCoptersTemplate" type="text/x-jquery-tmpl">
    <li>
        <b>${Name}</b> (${OutOfTen})
    </li>
</script>

 

Here we define the template that is basically some html littered with prop Names e.g. $(Name}, note the script type that is used for jQuery templates.

The load function is quite simple, it basically says: select the helicopter jQuery template and apply the helis JSON to it and put the result into the “results” unordered list.

Have a look at the jQuery template documentation for some more samples and have fun Smile

The Ultimate Top 25 Chuck Norris “The Programmer” Jokes.

 

1. When Chuck Norris throws exceptions, it’s across the room.
2. All arrays Chuck Norris declares are of infinite size, because Chuck Norris knows no bounds.
3. Chuck Norris doesn’t have disk latency because the hard drive knows to hurry the hell up.
4. Chuck Norris writes code that optimizes itself.
5. Chuck Norris can’t test for equality because he has no equal.
6. Chuck Norris doesn’t need garbage collection because he doesn’t call .Dispose(), he calls .DropKick().
7. Chuck Norris’s first program was kill -9.
8. Chuck Norris burst the dot com bubble.
9. All browsers support the hex definitions #chuck and #norris for the colors black and blue.
10. MySpace actually isn’t your space, it’s Chuck’s (he just lets you use it).
11. Chuck Norris can write infinite recursion functions…and have them return.
12. Chuck Norris can solve the Towers of Hanoi in one move.
13. The only pattern Chuck Norris knows is God Object.
14. Chuck Norris finished World of Warcraft.
15. Project managers never ask Chuck Norris for estimations…ever.
16. Chuck Norris doesn’t use web standards as the web will conform to him.
17. “It works on my machine” always holds true for Chuck Norris.
18. Whiteboards are white because Chuck Norris scared them that way.
19. Chuck Norris doesn’t do Burn Down charts, he does Smack Down charts.
20. Chuck Norris can delete the Recycling Bin.
21. Chuck Norris’s beard can type 140 wpm.
22. Chuck Norris can unit test entire applications with a single assert.
23. Chuck Norris doesn’t bug hunt as that signifies a probability of failure, he goes bug killing.
24. Chuck Norris’s keyboard doesn’t have a Ctrl key because nothing controls Chuck Norris.
25. When Chuck Norris is web surfing websites get the message “Warning: Internet Explorer has deemed this user to be malicious or dangerous. Proceed?”.

Ajax with jQuery

 

Hi all,

I’m sitting here waiting for a 50meg upload to finish,,, god my internet is slow.

May as well add a post ey Smile

So I’ll show you how you can request some JSON data from a MVC action using jQuery, You are probably familiar with AJAX.BeginForm extension from Microsoft, but lets do this the jQuery way.

  • Set up your action method to return some JSON
public ActionResult GetJson()
{
     return Json(new { Id = 1, value = "First" }, JsonRequestBehavior.AllowGet);
}
 

 

  • Set up a div to hold the json data and some jQuery to request it on document load,
    the getJSON takes the action url and when it returns it places the formatted JSON into the DIV.
    pretty simple ey..
   1:  @{
   2:      ViewBag.Title = "Home Page";    
   3:  }
   4:   
   5:   
   6:  @section head {
   7:   
   8:  }
   9:   
  10:  <h2>@ViewBag.Message</h2>
  11:   
  12:   
  13:  <DIV id=json></DIV>
  14:   
  15:   
  16:  @section footer {
  17:   
  18:  <script type="text/javascript">
  19:      $(function () {
  20:          
  21:          $.getJSON('@Url.Action("GetJson")', function (obj) {
  22:              $('#json').html(obj.Id.toString() + " : " + obj.value.toString());
  23:          });
  24:         
  25:      });
  26:  </script>
  27:   
  28:  }

The happy life of a web developer

 

Spent some of the weekend mucking about with getting a website to go with an iPhone and WP7 app I’m developing with one mister Tomas McGuinness, the whole idea is a wonderful combination of the MS stack of love with a bit of xcode thrown in for good measure.

What better way to experience new tech than to come up with a pet project and get stuck in, so far we’ve gotten down and dirty with

  • MS Sync Framework: the backbone of our interoperability using OData and WCF Services.
  • WP7 Silverlight : The windows phone app
  • Silverlight Ria services: The rich internet application that also runs OOB (out of the browser on the desktop)
  • MVC JQuery Ajax.
  • Html 5: (low level stuff just now but really excited about this)
  • XCode: iPhone app.
  • IE9 Jump lists: quick site navigation.

  • Dusted off the old Photoshop shortcut, to modify a template and apply it to our MVC application, and it’s been a hell of a lot of fun, jQuery is pretty impressive at the visual end too, animations etc. are trivial and a joy to play with.

Site coming to an internet near you soon (if we manage to get some free time).

image

Now the techie bit, a sample how to slide in a panel/div.

@{
    ViewBag.Title1 = "Grass";
    ViewBag.Title2 = "Manager";   
}
 
@section head {    
    @*BEK: Add some animation using jquery*@
    <script>
        $(function () {            
 
            $("#wel_topd").hide();            
            $("#wel_topd").slideDown('slow', function () {
                // Animation complete.
            });
        });
    </script>
}

@section is used to inject some scripts into the head of the html page.

Then you see a little bit of jQuery that hides the div “Welcome to iFarm” in the screenshot above and slide it in from top

RIA Service in 5 minutes

 

Hi all,

 

I’ve previously blogged about how mind blowing WCF RIA Services are here

This week i found myself working with RIA Services again and this time I’ve got to show you just how easy it is (is case you didn’t take my advise and go look it up Punk

So, fire up VS2010 and create a new Silverlight Business Application

image

Two projects will be created for you, the Web project is where your DataAccess and Business logic lies, the other project is your Silverlight application.

Create an entity framework model ORM for your data (you know how to do this right?)

Next create a new Domain Service Class in the Web/Services folder

image

image

Compile.. that’s your server ready to serve up your data.

Now lets move into the Silverlight app, and add the following mark-up to your xaml

First add the domain datasource, set it to auto load and set the Query name to the name of the query that has been injected into your client app, (let intellisense help you; it will be in the Web.Services namespace context object.

        <domainControls:DomainDataSource x:Name="dataPads" LoadSize="20" AutoLoad="True" QueryName="GetPadocks">
            <domainControls:DomainDataSource.DomainContext>
                <data:FarmContext />
            </domainControls:DomainDataSource.DomainContext>
        </domainControls:DomainDataSource>

 

Add a datagrid use ElementBinding to the domainDataSource above (i’ve also put it in a telerik busyindicator to provide feedback that the data is loading)

<telerik:RadBusyIndicator IsBusy="{Binding ElementName=dataPads, Path=IsLoadingData}">
    <dataControls:DataGrid x:Name="padocksGrid" MinHeight="100"
         ItemsSource="{Binding ElementName=dataPads, Path=Data}"  />
</telerik:RadBusyIndicator>
 

 

Ok I’ve once again skimped on some of the detail but it’s a really nifty approach and i encourage you to give it a go.

(Also seeming your service is a DomainContext you can expose your data as OData a post for another day Secret telling smile )