IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

I’m a Microsoft MVP!

I’ve just received an email from Microsoft saying I’m a new Microsoft MVP!!!
The MVP award is officially in Visual C# but it is mainly for my IronRuby activities (there’s no specific IronRuby MVP award yet).

I'm a Microsoft MVP!

I’d like to thank Sela, Guy Burshtein, IronRuby and you for helping me in the process of becoming a Microsoft MVP.

I’m very excited and looking forward to MVPing!

All the best,
Shay.



Rock Stars Vs. Programming Stars

Recently I thought about this comparison… In the programming world there is this level of people who are a kind of “celebrities” within the developer community - they’re widely known, they have thousands of readers of their blogs, they have thousands of followers on Twitter, they speak on public events in front of thousands of people around the world… All of that just screams for a comparison with the equivalent in the show biz world - rock stars!

So… I’m proud to present the first EVER comparison between rock stars and programming stars! afterwards judge for yourself what you wanna be.

Comparison Rock Star Programming Star
Look Rock stars (this is a picture of Motley Crue) Programming Stars (this is a picture of Microsoft's early days)
Shown in public on Concerts, TV, Radio, newspapers, magazines Conferences, podcasts, programming magazines
Known internationally Yes Yes
Chances of being recognized in the grocery store Almost with complete certainty Rarely
Charisma Yes Yes
Tools Microphone/Guitar/Drums/other instrument Microphone + computer + projector
Write Lyrics Code
Average annual salary Millions of dollars Hundreds of thousands of dollars
# of Twitter followers Millions Tens of thousands
# of people attending a single show/talk Tens of thousands Thousands
Way to the top Hard work for years/American Idol Hard work for years
(Simon Fuller, if you read this, what about a “Programming Idol” show?)
Sex So much that they’re sorry about that when they grow old. I don’t know. Unlike rock stars, they don’t share this information.
Drugs Yes. A lot. No. Geeks do not do drugs. Most of them at least.
Alcohol Yes Drink beer from time to time
Tour the world A few months a year A few days/weeks a year
Own A crib, a private jet, a collection of cool cars A powerful laptop with SSD and two 24’ screens
Can install Win7 No Of course, they’ve done that multiple times already
Eat bats during shows/talks Yes No
Have tattoos Yes Mostly not, it hurts to get them done.
Have two eyes, two ears, one mouth and one nose Yes Yes

And the winner is………… I don't know, do you?

Anyway in the end we’re all human and therefore have a chance to become stars.

Go ahead and shine!

Shay.

Share: Digg it | DZone it | Reddit it



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



A List of Essential Tools for a new Computer

This week I got my new laptop and it’s AWESOME!

It is a 64-bit Dell Studio XPS 16 with the following specification (the main features):

  • Processor: Intel® Core™ i7-720QM Quad Core Processor 1.6GHz (2.8GHz Turbo Mode, 6MB Cache)
  • Screen: 16' inch RGBLED Full HD 1080p
  • RAM: 8Gb 1333Mhz DDR3 Dual channel
  • HD: 500Gb 7200RPM
  • Graphics: 1GB ATI Radeon  HD 4670

And this is how it looks like:

My new Dell Studio XPS 16 My new Dell Studio XPS 16

It’s so much fun to work like that! everything just works and you don’t need to wait for operations to get done. They just do.

So after praising my new laptop, let’s move on to the main subject of this post – the tools I take with me to every computer I work on:

  • Reflector – in my opinion, every .NET developer must have Reflector installed on his or her computer. There is no way you can understand the internals of the technologies you work with without going through their code, at least flutter through it. And if you don’t want to understand the internals, go to a shrink and figure out why do you settle for mediocrity.
  • IronRuby – I use IronRuby’s REPL console as my main method of doing quick POCs, check what methods return and how to use them, etc. I used to use Snippet Compiler but IronRuby is so much faster and much more fun so I moved to it.
  • GacView – I use it as a replacement to the “assembly” folder viewer that is provided by Windows Explorer. GacView shows you the assemblies in the Global Assembly Cache (GAC), provides information about them and most important – lets you copy them to a different location and to delete them.
  • ViewStateDecoder – let you view what your page stores inside its view state hidden fields.
  • Fiddler – A very simple to use and powerful network sniffer.
  • SciTE – A light-weight editor with syntax highlighting and a simple code completion mechanism. I use it to change C# code quickly instead of opening the heavy Visual Studio, to write IronRuby code and to edit XML files.
  • Process Explorer – I use it as a replacement to Windows Task Manager. I like the UI more and the ability to find handles and remove them becomes very helpful every now and then.
  • ZoomIt – An awesome tool for presentations. If you speak occasionally and use a projector or a big screen, this tool is a must for you.
  • PicPick – a light-weight tool to capture screenshots. Very easy to use and comes with some more handy features like a color picker.
  • foobar2000 – A very light-weight music player which does exactly what it needs – play music. It comes with an easy to use music library viewer and can even show a balloon tip with the current playing song.

I highly recommend each of these tools because of my great experience with them. They make irritating tasks simpler and faster and eventually make me happier.

I hope they’ll make you happier too!
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>


Announcement: IronRuby Unleashed has been Released!

Good times!

Right after IronRuby RC2 was released and a bit before IronRuby 1.0 RTM is out, my book, IronRuby Unleashed, is available!

The print book is available from today on the InformIT web site (Sams Publishing’s book store) and will be available shortly on Amazon as well (and other book stores too).

IronRuby Unleashed by Shay Friedman

In short, IronRuby Unleashed contains all you need to start developing IronRuby applications. From Ruby language introduction, through the fundamentals of IronRuby programming (like implementing CLR interfaces, using generic methods, overriding CLR events and more) to using IronRuby with several different development frameworks like WPF, ASP.NET MVC, Silverlight, Ruby on Rails and more. The book also includes some advanced IronRuby topics like a chapter that explains how to develop IronRuby extensions.

 

I’d be glad to hear comments about the book, so don’t hesitate to contact me!

Shay.



Use .NET Built-in Methods to Save Time and Headaches

During our everyday programming tasks we run into several repetitive code blocks that after the 20th time you implement them become really annoying. The worst case is to re-implement these code blocks every time, and the better case is to create a central class library with helper classes and methods. However, a large amount of these tasks can be achieved easily with built-in .NET methods.

In this post I will go through several repetitive code blocks and show you how to implement them using built-in .NET method. If you want to add your suggestions, comment! I’ll add your suggestions to the post periodically.

Disclaimer: I’m sure some of the code blocks I use in the NOT Recommended sections can be written much better. These code blocks are here just for demonstration purposes.

Code Block #1 – Check string for nullity or emptiness

NOT Recommended

str = "something"
if (str == null || str == String.Empty)
{
	// Oh no! the string isn't valid!
}

Recommended

str = "something"
if (String.IsNullOrEmpty(str))
{
	// Oh no! the string isn't valid!
}

Code Block #2 – Check string for nullity or emptiness (spaces only string is invalid too)

NOT Recommended

str = "something"
if (str == null || str.Trim() == String.Empty)
{
	// Oh no! the string isn't valid!
}

Recommended (C# 4.0 Only)

str = "something"
if (String.IsNullOrWhiteSpace(str))
{
	// Oh no! the string isn't valid!
}

Code Block #3 – Copy an Array

NOT Recommended

string[] source = new string[] { "a", "b", "c" };
string[] dest = new string[3];
for (int i=0; i < source.Length; i++)
{
	dest[i] = source[i];
}

Recommended

string[] source = new string[] { "a", "b", "c" };
string[] dest = new string[3];
Array.Copy(surce, dest, source.Length);

Code Block #4 – Check if a char is a digit

NOT Recommended

char c = '1';
if (c == '1' || c == '2' || c == '3' ||
	c == '4' || c == '5' || c == '6' ||
	c == '7' || c == '8' || c == '9' ||
	c == '0')
{
	// It's a digit!
}

Recommended

char c = '1';
if (Char.IsDigit(c))
{
	// It's a digit!
}

Code Block #5 – Combine Paths

NOT Recommended

string folder = @"C:\MyDir";
string file = "MyFile.docx";
// Combine to make a path
string path = folder + @"\" + file;

Recommended

string folder = @"C:\MyDir";
string file = "MyFile.docx";
// Combine
string path = System.IO.Path.Combine(folder, file);

Code Block #6 – Get file extension out of a file path

NOT Recommended

string path = @"C:\MyDir\MyFile.docx";
string extension = path.Substring(path.LastIndexOf("."));

Recommended

string path = @"C:\MyDir\MyFile.docx";
string extension = System.IO.Path.GetExtension(path);

Code Block #7 – Get MyDocuments Path

NOT Recommended

// Probably some nasty stuff here

Recommended

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

Code Block #8 – Check if object is of a specific type

NOT Recommended

object obj = "str";
if (obj.GetType() == typeof(String))
{
	// It's a string!
}

Recommended

object obj = "str";
if (obj is String)
{
	// It's a string!
}

As Adrian Aisemberg has pointed out, these samples are not entirely the same. The is keyword will return true also if obj is of a derivative type of String (in this sample).

Code Block #9 – Set default enum value

NOT Recommended

public class MyClass
{
	private enum Sample 
	{
		A,
		B,
		C
	}
	static Sample s = Sample.B; // Set default value explicitly
	public static void Run()
	{	
		Console.WriteLine(s); // Prints B
	}
}

Recommended

public class MyClass
{
	private enum Sample 
	{
		A,
		B = 0, // Make B the default value
		C
	}
	static Sample s; // Default value will be used
	public static void Run()
	{	
		Console.WriteLine(s); // Prints B
	}
}

Code Block #10 – Check if a string starts with another string

NOT Recommended

string str = "Hello World";
if (str.Substring(0, 5) == "Hello")
{
	// String starts with Hello!			
}

Recommended

string str = "Hello World";
if (str.StartsWith("Hello"))
{
	// String starts with Hello!		
}

Code Block #11 – Convert list of items of one type to a list of items of a different type

NOT Recommended

List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
List<string> convertedList = new List<string>();
foreach (int item in list)
{
	convertedList.Add(item.ToString());
}

Recommended

List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
List<string> convertedList = list.ConvertAll<string>(Convert.ToString);

Code Block #12 – Check if a string contains a number and get the number

NOT Recommended

string str = "4";

int num = 0;
bool success = false;
try 
{
	num = Convert.ToInt32(str);
	success = true;
}
catch
{
	success = false;
}

if (success)
{
	// Do something with the number
}

Recommended

string str = "4";

int num = 0;
if (Int32.TryParse(str, out num))
{
	// Do something with the number
}

Code Block #13 – Writing a string to a file (courtesy of Yaron Naveh)

NOT Recommended

const string str = "put me in a file";
const string file = @"c:\logs\file.txt";

var fs = new FileStream(file, FileMode.Create);          
var sw = new StreamWriter(fs);
sw.Write(str);

sw.Close();
fs.Close();

Recommended

const string str = "put me in a file";
const string file = @"c:\logs\file.txt";

File.WriteAllText(file, str);

Code Block #14 – Pick value if not null and a different on if it is (courtesy of Abhishek)

NOT Recommended

string input = "sdfds";
string result = null;
if (input == null)
{
	result = "Input is null!";
}
else
{
	result = input;
}

Recommended

string input = "sdfds";
string result = input ?? "Input is null!";

 

This is it for now. If you have more, comment and I’ll add your suggestions to the list (with credits).

All the best,
Shay.

kick it on DotNetKicks.com Shout it


Vote to See IronRuby in MIX10

Do you want to hear about IronRuby in the upcoming MIX10 conference? If so, make sure to vote for my IronRuby session - IronRuby - the Development Booster Machine.

In the session I plan to talk a bit about the Ruby language and its strengths and then move on and show how .NET developers can take advantage of these stengths in several different scenarios like testing, debugging and Silverlight.

YOU have the power to make it happen! Go ahead and vote!
http://visitmix.com/opencallvote/Entry?entryId=IRONRU127

See you all there,
Shay.

A New Year, A New Beginning

2010!

It’s a new year and the wind of change is in the air. This year is a big year for me – IronRuby Unleashed will be published (est. FEB 15th), another big project is coming (more details in a few weeks) and I changed jobs!

In the last 4 years I worked at a startup named ActionBase. I learned a lot at this place and managed to work with various platforms – Office addins, WinForms, Silverlight and ASP.NET. After 4 years it was a time for a change and I decided to move on. Starting from 1/1/2010 I’m a .NET technologies consultant and instructor at Sela. My main field is dynamic languages but I’ll be doing other stuff too. I’m really thrilled and excited to get started, help customers and spread my knowledge.

If you want me to come to your company to run a course or consult, don’t hesitate to contact me. This is my job now, not a hobby anymore, so go ahead and use me! :)

I wish you all a wonderful and happy new year. May this year will be the one you were waiting and hoping for!

Peace and love,
Shay.



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