DCSIMG
May 2009 - Posts - IronShay

May 2009 - Posts

A Handy Extension Method: Retrieving Session Variables

[More handy extension methods: raise events safely, get the current page load mode]

Retrieving session variables is a daily task for web developers. In order to fetch a session variable, we should check if it exists and only then convert it to the expected type and use it. For example:

int myVal;
if (Session["MyVar"] != null)
{
    int.TryParse(Session["MyVar"], out myVal);
}

// ... more code ...

This is an annoying practice which can be easily replaced by extension methods.

So I’ve built a few extension methods, some are generic and some aren’t, which allow grabbing session values with ease (and even define default return values!):

public static class Extensions
{
    /// <summary>
    /// Gets a session value.
    /// </summary>
    /// <typeparam name="T">The type of the value.</typeparam>
    /// <param name="name">The name of the session variable.</param>
    /// <param name="defaultValue">The default value to use if the value is undefined.</param>
    /// <returns>The session value. If undefined or the value is not from the expected type, the default value is returned.</returns>
    public static T GetValue<T>(this HttpSessionState session, string name, T defaultValue)
    {
        if (session[name] == null)
        {
            return defaultValue;
        }

        try
        {
            return (T)Convert.ChangeType(session[name], typeof(T));
        }
        catch { }

        return defaultValue;
    }

    /// <summary>
    /// Gets a session value.
    /// </summary>
    /// <typeparam name="T">The type of the value.</typeparam>
    /// <param name="name">The name of the session variable.</param>
/// <returns> /// The session value. /// If undefined or the value is not from the expected type, the type's default value is returned. /// </returns>
public static T GetValue<T>(this HttpSessionState session, string name) { return session.GetValue<T>(name, default(T)); } /// <summary> /// Gets a session value. /// </summary> /// <param name="name">The name of the session variable.</param> /// <param name="defaultValue">The default value to use if the value is undefined.</param> /// <returns>The session value. If undefined, the default value is returned.</returns> public static object GetValue(this HttpSessionState session, string name, object defaultValue) { if (session[name] == null) { return defaultValue; } return session[name]; } /// <summary> /// Gets a session value. /// </summary> /// <param name="name">The name of the session variable.</param> /// <param name="defaultValue">The default value to use if the value is undefined.</param> /// <returns>The session value. If undefined, null is returned.</returns> public static object GetValue(this HttpSessionState session, string name) { return session.GetValue(name, null); } }

That’s it. Now fetching a session variable is fun! :)

// On an aspx code:
Session["Moo"] = "Yes!";
Session.GetValue("VarName"); // Returns null
Session.GetValue("VarName", 666); // Returns 666
Session.GetValue<String>("VarName"); // Returns null
Session.GetValue<String>("Moo", "LaLaLA"); // Returns "Yes!" (we've defined this variable before)

Enjoy!

All the best,
Shay.

kick it on DotNetKicks.com Shout it

A Handy Extension Method: Raise Events Safely

Raising events is a very common practice. We do that a lot and it’s pretty irritating to check for nullity every time:

if (eventHandler != null)
{
    eventHandler(sender, e);
}

Here comes extensions methods to our aid again. With only two extension methods, we can cover all possible event handlers and raise our events safely in one line. For example:

MyEvent.RaiseSafe(this, EventArgs.Empty);

Or

MyEvent.RaiseSafe<MyEventArgs>(this, new MyEventArgs(someParameter));

In order to achieve that, here are the needed extension methods:

public static class Extensions
{
    /// <summary>
    /// Raises the event in a safe way.
    /// </summary>
    /// <param name="eventHandler">The event handler.</param>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    static public void RaiseSafe(this EventHandler eventHandler, object sender, System.EventArgs e)
    {
        if (eventHandler != null)
        {
            eventHandler(sender, e);
        }
    }

    /// <summary>
    /// Raises the event in a safe way.
    /// </summary>
    /// <typeparam name="T">Type of the event handler.</typeparam>
    /// <param name="eventHandler">The event handler.</param>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The event arguments containg that event data.</param>
    static public void RaiseSafe<T>(this EventHandler<T> eventHandler, object sender, T e)
        where T : System.EventArgs
    {
        if (eventHandler != null)
        {
            eventHandler(sender, e);
        }
    }
}

All the best,
Shay

kick it on DotNetKicks.com Shout it

A Handy Extension Method: Get The Current Page Load Mode

I find myself pretty often write code to find out if I’m on a postback, callback or initial page load. I’ve decided to put an end to that and write an extension method to the ScriptManager class that will tell me the mode I’m in.

This is what I came up with:

public static class Extensions
{ 
    public enum PageLoadMode
    {
        /// <summary>
        /// Occurs when the page is loaded for the first time.
        /// </summary>
        InitialPageLoad,
        /// <summary>
        /// Occurs on a regular postback.
        /// </summary>
        FullPageUpdate,
        /// <summary>
        /// Occurs on a partial postback (aka callback).
        /// </summary>
        PartialPageUpdate
    }

    /// <summary>
    /// Gets the page loading mode.
    /// </summary>    
    /// <returns>A <see cref="PageLoadMode"/> value representing the current load mode.</returns>
    public static PageLoadMode GetLoadMode(this ScriptManager manager)
    {
        if (manager.IsInAsyncPostBack) return PageLoadMode.PartialPageUpdate;

        if (manager.Page.IsPostBack) return PageLoadMode.FullPageUpdate;

        return PageLoadMode.InitialPageLoad;
    }
}

Using it is pretty simple. Assuming you have a ScriptManager control on your page which is called ScriptManager1 and a label called lbl, you can use the extension method this way:

protected void Page_Load(object sender, EventArgs e)
{
    switch (ScriptManager1.GetLoadMode())
    { 
        case Extensions.PageLoadMode.InitialPageLoad:
            lbl.Text = "Initial page load";
            break;
        case Extensions.PageLoadMode.FullPageUpdate:
            lbl.Text = "Full page update";
            break;
        case Extensions.PageLoadMode.PartialPageUpdate:
            lbl.Text = "Partial page update";
            break;
    }
}

Extension methods rulezzzzzz!

All the best,
Shay.

kick it on DotNetKicks.com   Shout it

New IronRuby and IronPython Versions

Good news! IronRuby and IronPython have just been released with new and shiny versions!

IronRuby 0.5

  • Download IronRuby 0.5
  • Adaptive compilation – performance boost!
  • Removes ClrString. CLR strings are referred to as System::String
  • Removes IronRuby library. "require 'IronRuby'" is no longer needed; IronRuby module is now a built-in module.
  • Integer/Float operations for all CLR primitive numeric types
  • System::Char and System::String methods so that they behave like an immutable UTF-8 encoded string
  • Improves handling of BOM in 1.8 mode
  • Debugger visualizer for RubyObject so that VS will display the result of to_s in the Watch window.
  • Adds support for .NET operators (op_* special methods)
  • Implements bitwise operators on flag enums
  • Precompilation of simple Ruby method invocations
  • Improves performance for file IO#read method. Previously we were 10x slower than MRI, now we are approx. 1.5-times faster.
  • Tons of fixes to File, String, Array, and other built-in types to drive up RubySpec and Ruby application test-suite pass-rates. One bug fix is mine!
  • For a detailed description, read Jimmy’s blog post: http://blog.jimmy.schementi.com/2009/05/ironruby-05-released.html

IronPython 2.6 Beta 1

.Net 4.0 CTPs

With the release of VS2010, new IronLanguages CTPs came along. These CTPs make calling dynamic languages from C# 4.0 a very easy task. Give it a try:

IronPython 2.6 CTP for .Net 4.0 Beta 1

IronRuby CTP for .NET 4.0 Beta 1

 

We’re living in exciting times guys!

All the best,
Shay.

kick it on DotNetKicks.com  Shout it

Visual Studio Tip: Keyboard and Mouse Shortcuts

I’ve recently learned a few keyboard\mouse shortcuts in Visual Studio and I thought I would share them with you. Actually some of these tricks will work on every text box in your windows environment (or most of them at least…):

  • Clicking the middle mouse button on a tab closes it.
  • Pressing ALT while selecting text will enable you to select a square area of text:

Result of pressing ALT while selecting text.

  • Ctrl+F3 will search for the current selected text down the current file.
  • Shift+F3 will search for the current selected text up the current file.

All the best,
Shay.

kick it on DotNetKicks.comShout it

Posted by shayf | 4 comment(s)

IronRuby Journey Update #1 – Establishing The Silverlight Environment

OK, so I’ve started up my project to port a Silverlight application from C# to IronRuby. The special thing about this app is that it also makes some webservice calls, something that isn’t as obvious as it is in C# - you don’t have the wsdl tool to create the proxy class for you.

Well, Ruby is a fun language to code in so I’m sure that the lack of a few things here and there will not be much of a problem (I’m sure some of you nod your heads with a “yea right” look on your faces :) ).

Step #1

The first thing I needed to do was to be able to use IronRuby with Silverlight. This is done by the agDLR project which is a pack of tools to help you integrate Silverlight and the DLR. agDLR version is currently 0.5 which means it’s still a beta version and hopefully will improve until V1. It currently supports Silverlight 2 and Silverlight 3 beta.

I downloaded it – first task is done!

Step #2

Next I needed to create an IronRuby-driven Silverlight application. Among the agDLR files, there is a tool named SL. This is a command line tool that generates a simple Silverlight application with code files written in the selected dynamic language (Ruby and Python are supported). You will find it under the scripts folder where you extracted the agDLR files. The command line parameters are simple:

sl [ruby|python] <ApplicationPath>

Running it looks like that:

Running agDLR SL tool

After the tool is done, it generates a folder with the needed files to start with:

  • D:\IronRuby\WeatherWidget
    • \app
      • app.rb
      • app.xaml
    • \css
      • screen.css
    • \js
      • error.js
    • index.html

I have the project files ready – step #2 is complete!

Step #3

Trying to browse to the index.html file that sl has generated for us will not take us to where we want. We  will simply hit an error telling us that the silverlight file could not be downloaded. This is because the index.html file looks for app.xap, which wasn’t generated by the sl tool.

This is when the Chiron tool comes to our aid.

In the Greek mythology, Chiron was a very wise and kind centaur (a man-horse combination) and the teacher of many heroes like Asclepius the God of medicine, Theseus the legendary king of Athens and the greatest warrior Achilles.

In 2009, Chiron is a local web server which runs directly from the command line. It dynamically generates the silverlight xap file from your dynamic language code. You can run it by using the server.bat file that is located under the scripts folder. Chiron has various different startup options which you can view if you execute it with the /? switch: server /?.

In order to run the Silverlight project, you need to run server /b from the project directory (which means you need it on your PATH list) or by passing the directory using the /d switch. I went on and created a batch file to start the server automatically from the project directory, the batch file has a single line inside:

d:\IronRuby\agdlr-0.5.0\script\server /b /d:d:\IronRuby\WeatherWidget

So now all I need to do is run my batch file! Running it starts the web server on port 2060 and opens the browser with the directory listing:

Browser after running Chiron

Looking at the command line, you can see what chiron has fetched:

Chiron running

Clicking on the index.html file will show you the default Silverlight application that sl has generated for us. It has a built in console where you can write IronRuby code and see the changes live (awesome!):

Default agDLR silverlight application

OK – the environment is ready! step 3 is done.

Update #1 Conclusion

Well, I’ve got to say, this wasn’t easy. I think that this process of establishing the Silverlight environment revealed the Achilles heel of the current status of Silverlight and DLR languages. The process is not even nearly as intuitive and fluent as the C# process from Visual Studio (this whole post would have been one line if it was a C# tutorial – choose New->Silverlight Application and click OK).

.Net programmers have gotten used to intuitive, rich and fluent work process which obviously will not be what they’ll get with DLR languages currently.

I guess that these issues will improve with time. Currently, Microsoft spends time on the core things and not on the nice-to-have things. After IronRuby, IronPython and the DLR core development is done, Visual Studio integration will follow.

For me, I’m not planning on giving up. I really believe in these languages and the great things they bring to the programming world.

Stay tuned!

All the best,
Shay.

Share: DotNetKicks | DotNetShoutout | DZone

I’m on Twitter!

Well, I know I’m a bit late with that but I’ve just decided to join the trend and start tweeting.

My twitter account is ironshay and my profile page is http://twitter.com/ironshay.

I hope you’ll find it interesting!

See you there!
Shay.

Posted by shayf | 2 comment(s)
תגים:

C# Tip: Converting Whole Lists in a Single Line of Code

Lately I wanted to convert a list of items from one type to another. There is the straight way of doing so: writing a loop that iterates through the list, converts each item and generates the output list.

There is a shorter way though.

List has a ConvertAll method. You give it the output type and a delegate that converts a single item and that’s it.

Writing this delegate yourself is just annoying… This is where the Convert class comes into action – you can use the Convert.ToXXX as the conversion delegate:

 

// Original list
List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });

// Convert all items to strings
List<string> listOfStrings = list.ConvertAll<string>(Convert.ToString);

// Convert all items to chars
List<char> listOfChars = list.ConvertAll<char>(Convert.ToChar);

// Convert all items to bytes
List<byte> listOfBytes = list.ConvertAll<byte>(Convert.ToByte);

That’s it.

All the best,
Shay.

Share it: DotNetKicks | DotNetShoutout

Posted by shayf | 3 comment(s)