IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

Embrace it–JavaScript will Rule the World (Wide Web)

At the moment, we’re witnessing two opposite yet related changes – on the one hand, front-end computers become smaller and more mobile and on the other hand, servers are centralized into large server farms – moved to the cloud.

Web development has changed quite a bit as well – more and more functionality has moved to the client along with the rise of client-side frameworks like JQuery, MooTools and others. Having said that, it seems at the moment that there’s still a lot going on on the server-side of web apps. It does depend on the site, but you can’t deny the fact that postbacks are still a usual practice.

This concerns me. The new cloud era means that we will pay for our server’s computation time, storage and network traffic. Which means that if your developers write inefficient code, you’ll pay more; if your developers consume more network traffic, you’ll pay more; if your designers use high-quality graphics, you’ll pay more; etc.

The immediate effect on web development would be, IMHO, more client-side code. Why? because code that runs on the client doesn’t cost us anything, that’s why.

Postback Vs. AJAX – the Test

To show you what I mean I’ve put up a test – I wrote a very simple page with a form; You write a message inside a textarea box, click submit and your message is written to the server’s event log. Pretty simple.
I implemented this page in two ways:

  • Using a postback.
  • Using JQuery to call a WCF AJAX-enabled service.

The Postback-driven Page

  <%@ Page Title="Home Page" Language="C#" %>

  <script type="text/C#" runat="server">
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
      System.Diagnostics.EventLog.WriteEntry("EventLogger", "Logged: " + tbMessage.Text);
      tbMessage.Text = String.Empty;
      lblThanks.Visible = true;
    }
  </script>

  <html>
    <head>
      <title>DemoApp</title>
    </head>
    <body>    
      <form runat="server">
      <h1>Welcome to Event Logger!</h1>
      <h4><asp:Label runat="server" ID="lblThanks" Text="Thank you!" Visible="false" /></h4>
      Your log message:<br />
      <asp:TextBox runat="server" ID="tbMessage" TextMode="MultiLine" />
      <br />
      <asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" />    
      </form>
    </body>
  </html>

When I click the submit button, about 800 bytes travel to to server and about 1000 bytes travel back – a total of ~1.8Kb (according to Fiddler).

The AJAX-driven Page

The page (I’m using Microsoft’s CDN servers for the JQuery file to reduce network traffic to my cloud-based web server):

<%@ Page Title="Home Page" Language="C#" %>

<html>
  <head>    
    <title>DemoApp</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#submitButton").bind("click", function () {
          $.ajax({
            type: "GET",
            contentType: "application/json",
            url: "LoggerService.svc/Log",
            data: { "message": $("#message").val() },
            dataType: "json",
            success: function () {
              $("#message").val('');
              $("#thanks").show();
            }
          });
        });
      });
    </script>
  </head>
  <body>    
    <form>
      <h1>Welcome to Event Logger!</h1>
      <div id="thanks" style="display:none;"><h4>Thank you!</h4></div>
      Your log message:<br />
      <textarea id="message" rows="4" cols="20"></textarea>
      <br />
      <input type="button" id="submitButton" value="Submit" />      
    </form>
  </body>
</html>

The service:

using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WebApplication4
{
  [ServiceContract(Namespace = "")]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class LoggerService
  {		
    [OperationContract]
    [WebGet]
    public void Log(string message)
    {
      System.Diagnostics.EventLog.WriteEntry("EventLogger", "Logged: " + message);
    }	
  }
}

When I click the submit button, about 550 bytes are sent to the server and about 250 are send back – a total of ~800 bytes (according to Fiddler).

Result

Postback: 1.8Kb <—> AJAX: 800 bytes.
The postback approach took more than twice the network traffic that the AJAX approach took! a 125% addition!!!
Consequently, in the new cloud era, for every dollar you spend on the AJAX approach, you’ll spend 2.25 dollars on the postback approach (for this very simple example)… The situation is even worst actually because outgoing traffic costs more than incoming traffic.
This all might not seem like a big issue at first, but for high traffic sites which would pay $500,000 for the AJAX-based page it would become a huge issue - they’ll have to pay more than $1,000,000 for the same page that uses postbacks. THIS IS C-R-A-Z-Y!!!

Conclusion

This was a very very very very simplified example but it demonstrates my point very well. Postbacks use far more network traffic than AJAX calls; that’s a fact. And this is the reason why, in the future, their usage will be reduced the bare minimum or even disappear entirely.

This was only a single example and I have no doubt that cloud computing will dramatically affect the way we write code. The change won’t be quick, but it will be drastic as we get there. As soon as the big bosses understand that using a different technology/tool/approach within their development teams reduces costs, they will make the needed adjustments to use it.

And if you’re wondering what’s the first tool you need to save money when moving to the cloud then make no mistake – it’s Cloudoscope!

All the best,
Shay.

kick it on DotNetKicks.com Shout it



5 Reasons to be Excited about ASP.NET MVC 3

It’s already been 6 months since ASP.NET MVC 2 was released and version 3 is already taking shape. I, personally, am thrilled about that because this version seems to put ASP.NET MVC, in terms of maturity and functionality, on the first line along with other MVC frameworks out there like RoR.

I’ve put together 5 main reasons why I’m excited about this upcoming version. What about you?

1. The Razor View Engine

I said it before and I’ll say it again – the razor view engine is so cool!!! I really like the clean code I get when using it. In short, the razor view engine uses at signs (@) to indicate code blocks. For example, these are legit lines of code in razor:

@foreach (var item in Model) {
    <b>@item.FullName</b>
}

 

2. New Helpers

Helpers is an area ASP.NET MVC has been lacking at, compared to other MVC frameworks. MVC 3 will have new helpers that tend to close that gap:

  • Chart – helps creating charts. Very nice!
  • WebGrid – renders a collection of objects as a grid including paging and sorting. Should output a plain HTML table. Hopefully that’s all there is to it…
  • WebImage – helps in creating images. This also contains methods for basic image operations like rotating – cool!
  • WebMail – used to send emails.

The next helpers have been referred to as “task-based helpers”. They should have been a part of the beta version but they’re not there… I hope they’ll make it to the release version because they are just pure awesomeness:

  • Video – contains methods like Video.Flash, Video.Silverlight and Video.MediaPlayer which allow adding their corresponding HTML tags with ease.
  • Twitter – contains basic twitter operations like rendering the twitter stream for a specified user or the results of a given search.
  • ReCapcha – helps using the reCAPTCHA service.
  • Gravatar – helps consuming a user’s avatar from the Gravatar service.
  • Analytics – provides different methods like GetGoogleHtml, GetStatCounterHtml or GetYahooHtml that render the required javascript code for the different analytics services.

3. Support for Unobtrusive jQuery-Based Ajax

In ASP.NET MVC 3, Ajax.ActionLink, Ajax.RouteLink, Ajax.BeginForm and Ajax.BeginRouteForm will use JQuery to connect to the server. In addition, they will not use inline javascript, and instead they will call functions placed within javascript files.

Same thing applies to client-side validation.

4. Better Extensibility with new Dependency Injection Support

ASP.NET MVC 3 will contain numerous extensibility possibilities. Almost anything can be extended using DI, which opens so much opportunities. Just what extensibility means!

Read Brad Wilson’s post for a detailed guide to these new extensibility features.

 

5. NuPack Integration

NuPack is Microsoft’s new packaging system and it is fully integrated with ASP.NET MVC 3. Right click on the References folder in the Solution Explorer and choose “Add Package Reference…”:

The new Add Package Reference option

Now the NuPack UI will open and you can choose from the various different libraries on the online gallery:

NuPack

Pretty cool.

Well, these were my 5 reasons. So browse to http://go.microsoft.com/fwlink/?LinkID=191795, download the beta version and get excited too!

All the best,
Shay.

P.S. I’m not an ASP.NET MVP nor ASP Insider. Everything in this post was taken from various official blog posts and public web sites. Although the sources are as official as they can get (Scott Gu, Phill Haack…) this is only the beta version and as you know, in software – it ain’t over until the very last commit. Therefore, I recommend you check the release notes of every new version to see that no breaking changes were included.

kick it on DotNetKicks.com Shout it



Slides and Videos of my Talks at Epicenter and NDC

I’ve just uploaded the slides from my recent sessions at the Epicenter and NDC conferences. They appear on the presentation page as well.

NDC 2010 – Riding IronRuby on Rails (Norway, June 2010)

Abstract: The most famous Ruby–driven framework is, by far, Ruby on Rails. With IronRuby, .NET developers can now take advantage of this incredible web framework without leaving their comfort zone. In this session, Shay Friedman will build an entire Web 2.0 site from scratch while using and explaining the key features of Ruby on Rails.
Come and see what Ruby on Rails is all about and what's made it the success it is today.

You can also watch the session video – streaming, iPod video (320x240), MPEG-4 for QuickTime (1280x480)

NDC 2010 – Practical IronRuby (Norway, June 2010)

Abstract: Ruby has been a home for some great innovative frameworks like Ruby on Rails, Cucumber and Rake. IronRuby version 1.0 has recently been released, unleashing the power of Ruby to the .NET world.
In this session you will get familiar with the Ruby language and its amazing ecosystem and you will learn to take advantage of it in your everyday development tasks.
Come and see how this great new addition to the .NET family makes your development process faster, clearer and happier!

You can also watch the session video – streaming, iPod video (320x240), MPEG-4 for QuickTime (1280x480)

Epicenter 2010 – Ruby on Rails Vs. ASP.NET MVC (Ireland, June 2010)

Abstract: 2010 is the year when two great web development frameworks arrive at the .NET world – ASP.NET MVC 2.0 and Ruby on Rails (via IronRuby). It is the time to get to know these frameworks and learn their advantages and disadvantages. In this session I will walk you through the good, the bad and the ugly of both frameworks providing you points to consider when coming to choose one of them.
Come and see how these two wonderful web development frameworks collide!

Epicenter 2010 – ASP.NET MVC (Ireland, June 2010)

Abstract: Since the early days of ASP and later on ASP.NET, web development has always been a confusing experience. Several different architectures were suggested over the years, all of them struggled with the same goal – to make the code clear, clean and easily maintainable. Eventually, Microsoft took up the glove and created the framework that would change web development in Microsoft environment forever – ASP.NET MVC.
In this session Shay Friedman will take you on a journey to explore the different capabilities of ASP.NET MVC 2.0 by building an entire web application from scratch. Come and see the future of web development in the .NET world!

Epicenter 2010 – Practical IronRuby (Ireland, June 2010)

Abstract: Ruby has been a home for some great innovative frameworks like Ruby on Rails, Cucumber and Rake. IronRuby version 1.0 has recently been released, unleashing the power of Ruby to the .NET world.
In this session you will get familiar with the Ruby language and its amazing ecosystem and you will learn to take advantage of it in your everyday development tasks.
Come and see how this great new addition to the .NET family makes your development process faster, clearer and happier!

Enjoy!
Shay.



“But you need to master HTML for that, don’t you?”

I was talking with a guy the other day about choosing ASP.NET MVC over ASP.NET web forms. I told him why I think ASP.NET MVC is better (I believe it’s the way to go if you’re a .NET web developer) and he, in turn, tried to throw at me reasons of why not use ASP.NET MVC.

This conversation is legit and it’s been going on since the very beginning of the ASP.NET MVC project. However, there are a few things which are NOT legit in this conversation.

One of them is the sentence from the title: “But you need to master HTML for that, don’t you?”. I’m sorry people, but yes, you should know HTML pretty good when developing ASP.NET MVC apps. But guess what, you should know your HTML even when developing ASP.NET web forms applications! or when developing PHP, Ruby on Rails, Django, Seaside or whatever web development framework you’re using.

If you depend on Visual Studio’s visual designer to create your application HTML markup then stop now and go learn some HTML and CSS. Designers are there to help you (even though they tend to do the opposite) and they’re not there to replace your required skills!

Being a web developer without knowing HTML is like being a carpenter without knowing the difference between screws – you can build beautiful chairs but they might break apart very quickly.

So people, arguing if ASP.NET web forms or ASP.NET MVC is the right way to go is great, but as a .NET web developer you owe yourself (and your team) to know:

  • C#/VB.NET
  • HTML
  • JavaScript
  • CSS

These are fundamentals, they are NOT nice-to-know technologies!

All the best,
Shay.



Upcoming Gig: Epicenter 2010

The conference season is coming and it’s time to let you know where and when you can see and meet me!

So…

This June I’ll be speaking at the Epicenter 2010 conference, taking place on June 8th-11th in Dublin, Ireland.

epicenter 2010

The conference will be hosted in the Arts building of Trinity College, which just looks awesome:

Anyways, it’s technology we’re interested in! So I’m going to have two talks in the conference:

When: June 9th, 11:00
Title: Practical IronRuby
Abstract:
Ruby has been a home for some great innovative frameworks like Ruby on Rails, Cucumber and Rake. IronRuby version 1.0 has recently been released, unleashing the power of Ruby to the .NET world.
In this session you will get familiar with the Ruby language and its amazing ecosystem and you will learn to take advantage of it in your everyday development tasks.
Come and see how this great new addition to the .NET family makes your development process faster, clearer and happier!
(Get ready for some crazy demos here!)

When: June 10th, 15:15
Title: Ruby on Rails Vs. ASP.NET MVC
Abstract:
2010 is the year when two great web development frameworks arrive at the .NET world – ASP.NET MVC 2.0 and Ruby on Rails (via IronRuby). It is the time to get to know these frameworks and learn their advantages and disadvantages. In this session I will walk you through the good, the bad and the ugly of both frameworks providing you points to consider when coming to choose one of them.
Come and see how these two wonderful web development frameworks collide!

In addition to these talks I’ll also participate on Wednesday’s evangelist night along with Jamie Van Dyke and Julian Fitzel.

By the way, I’m staying in Dublin for a few days after the conference as well so if you’re in Dublin, let me know and we’ll go grab a pint!

See you there!
Shay.



The Brand New Menu.IncludeStyleBlock Property

Along with the popular new features of ASP.NET 4, some uncommon features have been added as well. One of them is the Menu control which has gone through some changes, good ones.

One of the changes to the control is the new IncludeStyleBlock property. This is a boolean value which indicates whether the control adds its CSS to the page. “Oh well…” you might say, but stop and rethink it – until now, when you used the Menu control you always had the CSS added to the page, whether you liked it or not. For example, the following is a CSS block which is added to the page when a menu with a simple format exists within it:

<style type="text/css">

/* <![CDATA[ */

#Menu1 { background-color:#FFFBD6; }

#Menu1 img.icon { border-style:none;vertical-align:middle; }

#Menu1 img.separator { border-style:none;display:block; }

#Menu1 ul { list-style:none;margin:0;padding:0;width:auto; }

#Menu1 ul.dynamic { background-color:#FFFBD6;z-index:1;margin-left:2px; }

#Menu1 a { color:#990000;font-family:Verdana;font-size:0.8em;text-decoration:none;white-space:nowrap;display:block; }

#Menu1 a.static { padding:2px 5px 2px 5px;text-decoration:none; }

#Menu1 a.popout { background-image:url("/WebResource.axd?d=HGk9oAfq1wga-jOpKNLje9tJtu3SgIdPSvUFv2UWscw1&t=634045276053254044");background-repeat:no-repeat;background-position:right center;padding-right:14px; }

#Menu1 a.dynamic { padding:2px 5px 2px 5px;text-decoration:none; }

#Menu1 a.static.selected { background-color:#FFCC66;text-decoration:none; }

#Menu1 a.dynamic.selected { background-color:#FFCC66;text-decoration:none; }

#Menu1 a.static.highlighted { color:White;background-color:#990000; }

#Menu1 a.dynamic.highlighted { color:White;background-color:#990000; }

/* ]]> */

</style>

This sucks. It isn’t cached by the browser, it increases your page size and it might become even bigger if you have some more complex styles. If this irritates you as it irritates me, the IncludeStyleBlock property is for you. Just set it to false and the above CSS disappears from the page.

However… by setting the IncludeStyleBlock property to false you remove the style completely and we don’t want that.
There are two possible solutions to this issue:

  • Copy the generated CSS to a CSS file (before you set the IncludeStyleBlock to false) and add a link to the file on the page - <link href="Styles/style.css" rel="stylesheet" type="text/css" />
  • Create a custom CSS class for the menu and set its name to the menu’s CssClass property.

In conclusion, the IncludeStyleBlock is a really nice enhancement to the handy Menu control. Notice that this is not the only change to the Menu control in ASP.NET 4, it also uses UL and LI elements instead of tables!
To read more about the changes in the Menu control in ASP.NET 4, look here.

And I say – hallelujah!

All the best,
Shay.

kick it on DotNetKicks.com Shout it



Printing Web Pages – the Cool Way!

When developing web applications we often run into a request to print one or more pages within the applications. In most cases, these pages will contain some type of report.
There are tons of ways to do that. Most of them I don’t like, especially the trivial one that pops to mind - “open a new window with a printer-friendly version of the page and set onload=’window.print()‘”. I find it quite irritating for the user.

There is another solution, which is less popular than its fellow window.open solution, but IMHO is much more user friendly and also might save you a few lines of code. It’s the CSS @media print solution!

What’s it all about?

  1. You get to have a single page that prints in slightly a different way than it’s presented on the browser.
  2. The magic lies within a special CSS block where you define CSS classes that will be used when the page is printed.
  3. This way you can hide parts of the page that don’t need to be printed, change the background image, increase/decrease font size, etc.

 

How to use it

The idea is to declare a different set of CSS styles for the page’s print mode. The great thing about that is that you can also, via CSS, hide elements that are unnecessary for printing.

For example, assuming you have the next HTML document:

<html>
<head>
    <title></title>
</head>
<body>
  <h1>REPORT</h1>
  <form><input type="button" id="printButton" value="Print" onclick="window.print()"/></form>
  <table border="1">
    <thead>
      <tr>
        <td>Column A</td><td>Column B</td><td>Column C</td>
      </tr>
    </thead>
    <tbody>
      <tr><td>1</td><td>2</td><td>3</td></tr>
      <tr><td>4</td><td>5</td><td>6</td></tr>
      <tr><td>7</td><td>8</td><td>9</td></tr>
    </tbody>
  </table> 
</body>
</html>
  1. This page will be presented as follows:
  2. image

Great UI indeed. However, printing this page will be a bit ugly (surprise surprise!), but really, in terms of printing the page, the header shouldn’t be that big and the print button shouldn’t be visible at all.

To do so, all we have to do is to define the styles for printing mode:

<style type="text/css">
  @media print
  {
    /* Here goes all styles to be used when printing */

    #printButton { display: none; } /* hide the print button */
    h1 { font-size: 12px; } /* make the header 12 pixels */
    body, td { 10px; } /* make regular text 10 pixels */
  }
</style>  

That’s it. Now if we print-preview the page, the header will be smaller and the Print button will be hidden:

Print Preview with @media print

Voila! No window.open is needed!

[Side note: I know this approach might be problematic sometimes because the user wouldn’t know what to expect when the page is printed. However, I still think this is a much more elegant way than the window.open approach. Use it wisely though].

ASP.NET developers: be careful when using CSS’s ‘#’ symbol with element IDs. Remember that ASP.NET changes the final HTML element ID of your controls that have the runat=”server” attribute.

All the best,
Shay.

Full source:

<html>
<head>
  <title></title>
  <style type="text/css">
    @media print
    {
      /* Here goes all styles to be used when printing */

      #printButton { display: none; } /* hide the print button */
      h1 { font-size: 12px; } /* make the header 12 pixels */
      body, td { 10px; } /* make regular text 10 pixels */
    }
  </style>  
</head>
<body>
  <h1>REPORT</h1>
  <form><input type="button" id="printButton" value="Print" onclick="window.print()"/></form>
  <table border="1">
    <thead>
      <tr>
        <td>Column A</td><td>Column B</td><td>Column C</td>
      </tr>
    </thead>
    <tbody>
      <tr><td>1</td><td>2</td><td>3</td></tr>
      <tr><td>4</td><td>5</td><td>6</td></tr>
      <tr><td>7</td><td>8</td><td>9</td></tr>
    </tbody>
  </table> 
</body>
</html>


Good to Know: Built-in ASP.NET Http Handlers

Http handlers is a really elegant infrastructure allowing you to provide special behavior to specific paths in your application. You can use them to create RSS  feeds, dynamically generate images, handle requests differently and  more.

Apart from writing new http handlers, there are some built-in handlers that you can take advantage of. The built in handlers are separated into three categories (in my opinion at least): request handlers, error generators and misc. handlers.

Request Handlers

These handlers process requests in a specific way. Although these already have paths configured  for them, you can manually configure them in the web.config (or via  IIS Manager) to run on different  paths. For example, treat ABC files the same as ASPX files. There is one catch here – because ASPX, ASHX and ASMX files are dynamically compiles, you will also need to provide build configurations for the new extensions.

The handlers in this category include:

  • The regular ASP.NET page (ASPX) hander - System.Web.UI.PageHandlerFactory.
  • The generic handler (ASHX) handler - System.Web.UI.SimpleHandlerFactory.
  • The resource handler (WebResource.axd) - System.Web.Handlers.AssemblyResourceLoader.
  • The web service handler (ASMX) - System.Web.Services.Protocols.WebServiceHandlerFactory.
  • The trace handler (trace.axd) – System.Web.Handlers.TraceHandler.

The following web.config  sample enables accessing trace info via MyTrace.aaa (this is web.config configuration for IIS 7 running in Integrated  mode, in other versions or modes the configuration will be a bit different):

    <system.webServer>
      <handlers>
        <add verb="*" path="MyTrace.aaa" name="Trace-handler" type="System.Web.Handlers.TraceHandler"/>
      </handlers>
    </system.webServer>

After this is configured (and tracing is enabled as well), try navigate to MyTrace.aaa page.

    Error Generators

    These handlers generate specific http errors. You can use them to prevent access to specific files, specific extensions or folders. These error generator handlers include:

  • Forbidden – generates a 403 Forbidden http error - System.Web.HttpForbiddenHandler.
  • Not Found – generates a 404 Not Found  http error - System.Web.HttpNotFoundHandler.
  • Method Not Allowed – generates a 405 Method Not Allowed http error - System.Web.HttpMethodNotAllowedHandler.
  • Not Implemented – generates a 501 Not Implemented http error - System.Web.HttpNotImplementedHandler.

The following web.config sample prevents users from accessing all files with secret extensions. Once a user tries to access such file he or she will get a 403 Forbidden page:

<system.webServer>
  <handers>
    <add verb="*" path="*.secret" name="SecretAccess" type="System.Web.HttpForbiddenHandler"/>
  </handlers>
</system.webServer>

Try navigating to top.secret and witness the result.

    Miscellaneous

    The misc. category contains one handler, the static file handler, which can help in various  scenarios. It will present the file content without any processing. With this handler you can, for example, enable users to retrieve lkr file (no special meaning to this extension that I know of) content.

  • Static file – shows the content of a file without any processing - System.Web.StaticFileHandler.

The following  sample configures lkr files to be processed by the static file handler. To test this, create a txt file in your web application root folder, rename its extension to lkr and navigate to it.

<system.webServer>
  <handlers>
    <add verb="*" path="*.lkr" name="lkr-handler" 
              type="System.Web.StaticFileHandler" resourceType="File"/>
  </handlers>
</system.webServer>

 

All  the best,
Shay.

Share it:
Shout it kick it on DotNetKicks.com