Tuesday, December 30, 2008

Call a method only if a supplied argument is not Null

Suppose you have a C# method which only works correctly if its parameter value is not Null, otherwise it either throws an exception or returns wrong value. Sometimes you cannot guarantee that a parameter value is not Null, because it was passed from outside, was read from DB, etc. Instead of writing your custom code again and again, which checks a parameter value and only calls a method if it is not Null, it may be more convenient to re-use a common helper method. Overloaded CallIfArgumentNotNull() methods shown below are such helpers. I was somehow inspired by reading this article by Jon Skeet (lazy evaluation) .

    // If a first argument of type int? is not Null, a supplied method (second argument)
    // is called with a first argument passed in and its return value is returned.
    // If a first argument is Null, a default(T) is returned
    // (null for reference types, 0 from Integer, etc.)
    public static T CallIfArgumentNotNull<T>(int? arg, Func<int, T> func) {
      return (arg != null) ? func((int)arg) : default(T);
    }
 
    // If a first argument of type int? is not Null, a supplied method (second argument)
    // is called with a first argument passed in and its return value is returned.
    // If a first argument is Null, a third argument value is returned.
    public static T CallIfArgumentNotNull<T>(int? arg, Func<int, T> func, T defResult) {
      return (arg != null) ? func((int)arg) : defResult;
    }
 
    // If a first argument of type A? is not Null, a supplied method (second argument)
    // is called with a first argument passed in and its return value is returned.
    // If a first argument is null, a third argument value is returned.
    public static T CallIfArgumentNotNull<A, T>(Nullable<A> arg, Func<A, T> func, T defResult)
      where A : struct {
      return (arg != null) ? func((A)(arg)) : defResult;
    }

Thursday, November 20, 2008

An easy way to override Chrome bookmarks

It is quite easy to manually override Chrome “Other Bookmarks” with your Firefox bookmarks:
1) In Chrome, click on “Other Bookmarks” and, if you have any, right click on each bookmark and delete it.
2) Use “Import Bookmarks and Settings”, switch to import from Firefox, clear all checkboxes except ‘Bookmarks’ one and hit ‘Import’.
3) This will keep all imported bookmarks in one ‘folder’, which is actually good, because next time when you decide to override Chrome bookmarks, you will need to delete only one Other Bookamrks ‘folder’ by right-clicking on it.

(On WinXP machine Chrome keeps bookamrks in C:\Documents and Settings\-your-name-\Local Settings\Application Data\Google\Chrome\User Data\Default\Bookmarks file. This is a text file which looks similar to XML. )

Thursday, November 13, 2008

Configuring MS DTC on WinXP, Server 2003, and Server 2008 machines

Our N-Tier ASP.NET (C# 2008 / SQL Server)  application uses MS DTC transactions for database integrity. This allows a transaction to embrace several BL or DL method calls without sharing the same database connection.
A usage is simple:

using System.Transactions; 

using (TransactionScope myTransactionScope = new TransactionScope()) {
  // Do any database related work you need: call methods, open and close connections, update multiple tables.
  // Database integrity is preserved  even if one of methods which update database fails.

     myTransactionScope.Complete();
}

To support MS DTC all servers which run our application (including developers' machines) and servers which host a databases were properly configured. (Configuring developers' machines allowed to work properly with your local copy of application and with a remote database.

1) To configure DTC on Windows XP, Windows Server 2003 machine follow these instructions to open Component Services window and configure DTC.
Make sure that "Use local coordinator" check box is checked on MSDTC tab of computer properties window.
Make sure that "Network DTC access" is checked on MSDTC=>Security Configuration window, that both "Allow Inbound" and "Allow Outbound" are checked, and DTC Logon Account is set to "NT AUTHORITY\NetworkService".
2) On Windows Server 2008 machine it's pretty much the same, except that in Component Services window has My Computer -> Distributed Transaction Coordinator -> Local DTC node, on which you'll need to right-click and choose Properties.
3) After configuring DTC restart your machine.
4) Open Control Panel -> Administrative Tools -> Services and make sure that DTC is set to start automatically and is started.




Reference on using DTC with N-Tier application: http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=419

Sunday, November 02, 2008

The best of F# and C# -- Nemerle? Scala? various approaches to mixed OOP - functional languages

Today I was pointed out to yet another mixed OOP and functional language: Nemerle. I looked at the Nemerle features and immediately spotted something very familiar, "Probably the most important feature of Nemerle is the ability to mix object oriented and functional programming styles. The top-level program structure is object oriented, while in the body of methods one can (but is not forced to) use functional style. In some programming problems this is very handy." It sounds exactly the same as what is stated about Scala programming language, "Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages." A main platform for Scala is JVM, but it's CLR variant already exists and is planned to be fully developed.

I think that both C# and Java in their pursuit of simplicity dropped too many functional features which existed in their common parent - C++. I've just blogged about it today. So, both communities felt the need for more functional OOP languages. It looks like that both Scala and Nemerle chose the same approach which creators of Java used: to build up on the base of familiar and wide-spread language in a hope that it gives an immediate advantage of huge number of programmers who are familiar with the syntax and want to try new language. I don't know about Nemerle yet and I still know too little about F#, but Scala language found a very natural and consistent way of combining object oriented and functional features and is even better OOP language than Java.

I think people are absolutely right, when they are saying, that it's hard to catch up with F#, "because the syntax of the ML - derivative languages is just too foreign for those with only imperative language experience". I felt it by myself when I was trying to start learning language using "Expert F#" book, having no prior ML experience.
But there is a flip side: now, when - thanks to an excellent "Real World Functional Programming" book by Tomas Petricek I started to understand both functional concepts and beauty of ML syntax, I feel that more graduate approach taken by Scala (and probably - Nemerle) may in fact postpone real understanding of a functional nature of new languages. It's possible to program in Scala as in "improved Java" and never learn its functional features. And thanks to more steep approach of F# I now better understand and try to pursue functional approach in Scala and better understand ideas behind LINQ...

Learning languages in comparison. How Scala re-introduces what was dropped in C++ to create Java.

An update (30/11/2008): I realize that a title of this post sounds silly. I never tried to say something like "Scala has C++ roots" or so. Scala is "an attempt to come up with a decent statically typed language that is both functional and object-oriented and that interoperates on standard VMs" (Martin Odersky in a comment here). My point is: too much (including some functional features) was dropped when C++ was "simplified" by Java creators. 

Scala allows to pass variable length argument list to a function defined like

def echo(args: String*) =
  for (arg <- args) println(arg)

In "Programming in Scala" authors says that,
'... Thus, the type of args inside the echo function, which is declared as type "String*"  is actually Array[String]'

It immediatelly reminds me C++, which uses similar syntax of passing array arguments. I'm pretty sure Martin Odersky chose asterisk, because it is used in C/C++, although in C/C++ it allows to pass array parameters, not a variable length argument list, and denotes a pointer to a first element of array.

There is definitely a feel, that C++ is more functional language than Java, for example a name of a function is a pointer (reference) variable pointing to a function itself, which allows to pass a function to another function as parameter and return as return value. First-class functions, isn't it?
So, Scala feels partly as a consistent attempt to re-introduce to Java functional features which were dropped when Java creators used C++ to produce new [over?]simplified language.

Personally, I always loved when authors of books described new languages in comparison to existing ones, like Trey Nash is doing in his "Accelerated C# 2008", comparing C# to C++, like David Flanagan is doing in "JavaScript. The Definite Guide", comparing JavaScript to C/C++, and like Bruce Eckel is doing in "Thinking in Java", comparing it to... C++ again. (By the way, Bruce is considering Scala as a next "big" language, which will gradually and partially replace Java the same way Java did to C++.) One fresh and excellent example is "Real World Functional programming in .NET" by Tomas Petricek. This book introduces F# language (a merge of OCaml and .NET platform) and functional concepts in constant comparison to limited functional features of C# 3.0. It helps a lot to understand both F# and functional features of C#. It even helps to understand Scala, because functional concepts are the same in both F# and Scala.
To learn programming languages in comparison is not an easy task. But it is, in my opinion, a most powerful way to obtain real understanding of languages. Footnotes or special text blocks, describing similarities and diffrence between languages make a programming book shine.

Friday, September 12, 2008

How to decoratively set an attribute of a server-side control to some public property/value?

Have you ever tried to decoratively set an attribute of a server-side control to some public property/value defined in code-behind code (or in a Business Layer)? Here's a simple example:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPage.aspx.cs"
 Inherits="TestPage" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:TextBox ID="TextBox1" runat="server" Text="<%=hitest %>" />
    </div>
    </form>
</body>
</html>

And in a code-behind file:

public partial class TestPage : System.Web.UI.Page {
 
  public string hitest = "Hello";

This example doesn't work, ASP.NET engine does not process hitest and displays a text box with <%=hitest %> inside.

I know, I'm doing something stupid and show everybody that I understand nothing about ASP.NET, but here's a reasoning behind my attempts:
In our application we use AjaxControlToolkit, and in particular - MaskedEditExtender. There is a complicated WebForm with a ListView and numerous text boxes for entering phones, there were millions of MaskEditExtenders with identical masks set to @"(9{3}) 9{3}-9{4}". (The same story for emails.) I don't like clattering a code with "magic" strings and numbers, so I decided to declare constants and toplace them into our common class sitting in App_Code:

namespace CoTs.Partners.Common {
  public static class Util {
    public const string MailRegEx = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
    public const string PhoneMask = @"(9{3}) 9{3}-9{4}";
Then, I thought, I would set
<cc1:MaskedEditExtender Mask="<%#CoTs.Partners.Common.Util.PhoneMask %>"
- and voila. For some reason it worked fine for a ListView's "Edit", but bombed with an empty Mask in "Add". I started to investigate and decided that using of <%# is probably incorrect, because <%# implies data binding. But, as I said, <%= doesn't work either. Sure, I can assign values to Maks properties programmatically in code-behind file, but it sounds crazy, given the fact that MaskEditExtender controls are scattered inside many other controls in a complicated page.

So, again: is there a way to decoratively set an attribute of a server-side control to some public property/value (defined in code-behind code or in a Business Layer)?
Suprizingly, I couldn't find any information on a Web....

Thursday, September 04, 2008

Custom ViewState storage and multiple browser tabs/windows

I'm thinking about implementing a custom ViewState storage, most likely - in a database, like it is described in this article. It may do several good things: make pages more lightweight, together with Cross Page Post Back allow for implementing Post/Redirect/Get (PRG) pattern in ASP.NET application, maybe even allow for some custom history / breadcrumb solutions for application / page lifecycle...

However, I have one concern: having multiple browser's Tabs or windows. When you work in Internet Explorer, you can open a new tab and have it to work with the same ASP.NET application, it will share session. With Firefox, you can even open a new window and it will share session. Now, if we use links (GET operation) to go from page to page, GUID is not passed between pages, and custom history / breadcrumb cannot work correctly with multiple Tabs. The only (ugly) solution I see is to modify every link on ASP.NET page to include GUID.

Tuesday, August 19, 2008

Delegates and events. What does `event` keyword actually mean in C#

In a very interesting "Accelerated C# 2008" book, its author Trey Nash described the role of C# events (page 262):
"... .NET runtime designers were so generous as to define a formalized built-in event mechanism. When you declare an event within a class, internally the compiler implements some hidden methods that allow you to register and unregister delegates, which are called when a specific event is raised. In essence, an event is a shortcut that saves you the time of having to write the register and unregister methods that manage a delegate chain yourself."
Then, on a page 265 he is saying:
"... events are ideal for implementing a publish/subscribe design pattern, where many listeners are registering for notification (publication) of an event. Similarly, you can use .NET events to implement a form of the Observer pattern, where various entities register to receive notifications that some other entity has changed."

Often, when some material is not clear to me, I try to read another book to clarify a matter. So, I found the following description of events in "C# 3.0 in a Nutshell" book (page 112:
"When using delegates, two emergent roles commonly appear: broadcaster and subscriber.
The broadcaster is a type that contains a delegate field. The broadcaster decides when to broadcast, by invoking the delegate.
The subscribers are the method target recipients. A subscriber decides when to start and stop listening, by calling += and -= on the broadcaster's delegate. A subscriber does not know about, or interfere with, other subscribers.
Events are a language feature that formalizes this pattern. An event is a wrapper for a delegate that exposes just the subset of delegate features required for the broadcaster/subscriber model. The main purpose of events is to prevent subscribers from interfering with each other."

This is quite opposite to what Trey said about events! They are introduced to prevent subscribers from interfering with each other, not as a shortcut that saves you the time of having to write the register and unregister methods.
+= and -= operators are defined for non-event delegates as well as for event delegates, while non-event delegates also expose assignment (=) operator and GetInvocationList() method which are too dangerous for subscribers. They allow a particular subscriber to investigate which other classes also subscribed to the same delegate and even allow to remove other independent subscribers. That's exactly what we prevent by adding an `event` keyword to a delegate.

Here's a modified code snippet from "C# 3.0 in a Nutshell" which proves what I said above (note, that it does not use famous EventHandler<TEventArgs> delegates; events could actually be used with any delegates):


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Chp04_events {
 
  internal delegate void PriceChangedHandler( decimal oldPrice, decimal newPrice );
 
  /// <summary>
  /// "Broadcaster" class
  /// </summary>
  internal class Stock {
    string _symbol;
    decimal _price;
 
    public Stock( string symbol ) { this._symbol = symbol; }
 
    // If you comment out this line and uncomment next line,  "myStock.PriceChanged = ..." and "Delegate[] chain = " statements
    // below in public void SetStockToWatch( Stock myStock ) methods would become legal, compromising an independence of event subscribers.
    // That's why we use an `event` keyword, rather than simpli a delegate.
    public event PriceChangedHandler PriceChanged;
    //public PriceChangedHandler PriceChanged;
 
    public decimal Price {
      get { return _price; }
      set {
        if (_price == value) return;
        if (PriceChanged != null) {
          // Code within the Broadcaster type has full access to event and can treat it as delegate:
          Delegate[] chain = PriceChanged.GetInvocationList();
          Console.WriteLine( "There is/are {0} subscribers watching for event I'm broadcsting", chain.Length );
          Console.WriteLine( "The first subscriber has a type of {0}", chain[0].Target.GetType() );
          if (chain.Length > 1) {
            Console.WriteLine( "The second subscriber has a type of {0}", chain[1].Target.GetType() );
          }
 
          PriceChanged( _price, value );
        }
        _price = value;
      }
    }
  }
 
  /// <summary>
  /// "Subscriber" class
  /// </summary>
  internal class StockWatcher {
    protected string _watcherName = String.Empty;
 
    public StockWatcher( string watcherName ) {
      this._watcherName = watcherName;
    }
 
    public string WatcherName {
      get { return _watcherName; }
    }
 
    public void SetStockToWatch( Stock myStock ) {
      myStock.PriceChanged += new PriceChangedHandler( myStock_PriceChanged );
      // Code outside the Broadcaster type can only perform += an -=. "Subscriber" does not know about other "subscribers".
      // The following line of code won't compile: 
      // Error: The event 'Chp04_events.Stock.PriceChanged' can only appear on the left hand side of += or -=
      // (except when used from within the type 'Chp04_events.Stock')
      myStock.PriceChanged = new PriceChangedHandler( myStock_PriceChanged );
      // The same error:
      Delegate[] chain = myStock.PriceChanged.GetInvocationList();
    }
 
    public void myStock_PriceChanged( decimal oldPrice, decimal newPrice ) {
      Console.WriteLine( "{0}: Stock price was changed from {1} to {2}", WatcherName, oldPrice, newPrice );
    }
  }
 
  internal class NewStockWatcher : StockWatcher {
    public NewStockWatcher( string watcherName ) : base( watcherName ) { }
  }
 
  class Program {
    static void Main( string[] args ) {
      decimal myDecPrice;
 
      var myStock = new Stock( "Napster" );
      var myStockWatcher1 = new StockWatcher( "First Watcher" );
      var myStockWatcher2 = new NewStockWatcher( "Second Watcher" );
 
      myStockWatcher1.SetStockToWatch( myStock );
      myStockWatcher2.SetStockToWatch( myStock );
 
      while (1 == 1) {
        Console.WriteLine( "Please enter new stock price:" );
        string newStockPrice = Console.ReadLine();
        if (newStockPrice == String.Empty) break;
        if (Decimal.TryParse( newStockPrice, out myDecPrice ))
          myStock.Price = myDecPrice;
      }
    }
  }
}

Friday, August 15, 2008

"ASP.NET gets no Respect" by Rick Strahl

There is a good ASP.NET gets no Respect article just posted by well-known ASP.NET developer Rick Strahl. Read it! I commented there too :)

Thursday, August 14, 2008

A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans. Debugger and for () yield {}

I continue my Scala IDE mini series I described my experience with installation of Eclipse, IntelliJ IDEA, and Netbeans applications and installation of Scala plugins in those environments.

The following simple code (from Programming in Scala, chapter 7) poses certain challendges to Scala debuggers. Some debuggers cannot stop on breakpoint placed, for example, on "val prod = (i * j).toString" line.
As Alexander Podkhalyuzin from JetBRAINS/Intellij IDEA Scala Plugin team said, "This problem goes to Java debugger problem with anonymous classes, because it's compile in different class file. So, we must to understand what name of this class files, and to set to each line, line in this class file. In Eclipse developers do this work, we have not implemented this yet, but you must be sure, it will be, because it is not convenient to work without for debugger."

As of today, Eclipse Scala plugin debugger can stop, the latest Intellij IDEA Scala Plugin debugger can stop as well. Both go even to a library Seq.class; Eclipse shows its code, IntelliJ IDEA shows interface, saying that it is "IntelliJ API Decompiler stub source generated from a class file. Implementation of methods is not available".
The latest and greatly improved NetBeans Scala plugin debugger still cannot stop here.


package chp7multitable
object Main {
/**
* @param args the command line arguments
*/
def main(args: Array[String]) = {
val multi = {
val table = for (i <- 1 to 10) yield {
val row = for (j <- 1 to 10) yield {
° val prod = (i * j).toString
String.format("%4s", Array(prod))
}
row.mkString + "\n"
}
table.mkString
}
println(multi)
}
}



1. Eclipse vs. IntelliJ IDEA vs. Netbeans. Installation.
2. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with Eclipse.
3. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with IntelliJ IDEA.
4. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with Netbeans.
5. A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans.
6. A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans. Debugger and for () yield {}.

Thursday, August 07, 2008

Effective Java Programming

Here's an interesting speech by Joshua Bloch (the author of Effective Java) on YouTube.

(I use ScribeFire with Firefox to post on Blogger. Unfortunately, ScribeFire always posts as Draft, regardless of me selecting or un-selecting post-to-draft option.)

Saturday, August 02, 2008

A couple of excellent Scala resources

Here's a very live and professional Scala forum. I asked a question there and immediately got a qualified answer from this wonderful Scala pro.

BTW.: I'm writing this post using this tool. Seems to be more convenient that Blogger itself.

Thursday, July 31, 2008

A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans.

1. Eclipse vs. IntelliJ IDEA vs. Netbeans. Installation.
2. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with Eclipse.
3. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with IntelliJ IDEA.
4. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with Netbeans.
5. A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans.

In this final post here's a short summary for Eclipse vs. IntelliJ IDEA vs. Netbeans:

Eclipse plugin for Scala.

Positive: Works. Is free. Customizable environment. Has predefined templates for Scala Project, Scala object, Scala Class, Scala file. Good debugger.

Negative: A very little documentation. Does not appear to be actively developed. There are news groups and Artima forum, but there is not too much live in there. No hotline support. Does not automatically create a project folder, so you need to remember to create it. Inconvenient manual process of setting run-time configuration and running. You need to manually switch from "Debug perspective" to "Scala perspective" after you finished debugging (although it's just one mouse click.)



Intellij IDEA plugin for Scala.

Positive: Works. Customizable environment. Has predefined templates for Scala Project and file. Good debugger. Being developed very actively. Excellent, friendly hotline support on Scala plugin forum. Sokoban plugin works fine with "Diana EAP" beta of Intellij IDEA


Negative: Intellij IDEA is quite expensive, unless you qualify for a free version as established Open Source developer. "Diana EAP" beta of Intellij IDEA is very fragile. Installing any plugin could ruin it. But Scala plugin does not work under stable editions of Intellij IDEA. No predefined templates for Scala object, Scala Class, although user can create them. Almost no Scala plugin documentation. Does not automatically create a project folder, so you need to remember to create it. Inconvenient manual process of setting run-time configuration and running.



Netbeans plugin for Scala.

Positive: Works. Is free. Very easy to use, really automated. Customizable environment. Has predefined templates for everything. Being developed very actively.Good debugger.

Negative: Almost no Scala plugin documentation, but it's so easy to use, I didn't have any problem. I didn't find any live people to discuss Netbeans Scala plugin or Scala itself, although you can post bugs.


I would probably choose Netbeans by Scala development, but there is one thing which might over weigh its maturity and ease of use: an excellent user-friendly and responsive Scala Plugin forum on IntelliJ IDEA. It feels like a team where you can get immediate help not only with installation issues, but also discuss advanced Scala features and patterns.

A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with Netbeans.

In a first post in this Scala mini series I described my experience with installation of Eclipse, IntelliJ IDEA, and Netbeans applications and installation of Scala plugins in those environments.
In a second post I explained how would I create, set up, run and debug Scala project in Eclipse.
In a third post I explained how would I create, set up, run and debug Scala project using IntelliJ IDEA.
Now, let's now follow the process of creating, configuring, running, and debugging a simple Scala project with Netbeans. As a test project I will use the same "Rational" class defined in chapter three of the wonderful Programming in Scala book written by Martin Odersky, Lex Spoon, and Bill Venners.

VII. A process of creation Scala application with Netbeans plugin is not described anywhere (I haven't found it; this page explains how to setup environment), but Netbeans is highly automated and interface is really intuitive. I didn't have any problem with it.
1. Start Netbeans. Use File | New Project menu to start process. Choose "Scala Application", then, on the following screen set the name of Project, Project Location, Main Class Name (as PackageName.ObjectName) and hit Finish. That's it! Everything is automatically created; nice folder structure is created too. There are templates for adding more classes / objects. (Note, that
Netbeans does not automatically create a project folder, as opposed to both Eclipse and IntelliJ IDEA. You don't need to do it manually.) You don't need to select application type as Java Module. You don't need to manually point to a right Scala SDK installation. Much easier to use, than Eclipse or IntelliJ IDEA.











2. Add necessary classes/objects. Save everything.






VIII. There is no need for complex setup run-time environment. It works fine right away and by default in Netbeans.

1.
Click on a Run or Debug button and enjoy. Breakpoints are set by clicking on a gray area to the left from code.

Wednesday, July 30, 2008

A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with IntelliJ IDEA.

In a first post in this Scala mini series I described my experience with installation of Eclipse, IntelliJ IDEA, and Netbeans applications and installation of Scala plugins in those environments.
In a second post I explained how would I create, set up, run and debug Scala project in Eclipse.
Now, let's now follow the process of creating, configuring, running, and debugging a simple Scala project with IntelliJ IDEA. As a test project I will use the same "Rational" class defined in chapter three of the wonderful Programming in Scala book written by Martin Odersky, Lex Spoon, and Bill Venners.

V. A process of creation Scala application with Intellij IDEA plugin is slightly touched on IntelliJ IDEA Scala Plugin page and in corresponding forum.
1. Start IntelliJ IDEA. Use File | New | Project menu and create chp6Rational Scala project in an appropriate folder. Choose Project Name, Project File Location. Note, that
IntelliJ IDEA does not automatically create a project folder, so you would need to create chp6Rational (you name it) folder in your Scala work folder. Make sure you selected application type as Java Module. On a next screen check "Create Source Directory" and name it as "src". On a yet next screen, make sure that "Scala" check box is checked and a proper Scala SDK appears in a box to the right. Finish this long process.











2. Expand the "chp6Rational" project tree, select "src"folder, right click and choose New | Package. Name it "rational".



3. Expand the project tree, select "rational" package, right-click and choose New | Scala File. There are no predefined templates for Scala Object or Scala Class creation (you can add your own). Add an appropriate code from "Programming in Scala".


4. Save everything.


VI. Here's how to set, compile, run or debug Scala application with IntelliJ IDEA.

1.
Click on a small arrow-down button on a toolbar under Run menu to set up run configurations or use Run | Add new configuration / Edit configuration menu. Set application name and main Class name (PackageName.MainObjectName format). Hit "Run".
2. What really drives me crazy is the fact, you'll need to at least two mouse click every time you need to run your Scala application. Although system already remember settings from previous run, it asks you again.





3. Debugger works nicely with Scala application. You can set breakpoints by double-clicking white area to the left of your code, execute code line-by-line, see values of variables.
Hit debug button (right arrow) on a toolbar, confirm app settings and debug. You don't need to manually switch from "Debug perspective" to "Scala perspective" after you finish debugging, as you need with Eclipse.


A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with Eclipse.

In a previous Scala post I described my experience with installation of Eclipse, IntelliJ IDEA, and Netbeans applications and installation of Scala plugins in those environments. Now, let's now follow the process of creating, configuring, running, and debugging a simple Scala project with Eclipse. As a test project I will use "Rational" class defined in chapter three of the wonderful Programming in Scala book written by Martin Odersky, Lex Spoon, and Bill Venners.

III. A process of creation Scala application with Eclipse plugin is roughly described on Scala Plugin for Eclipse page.
1. Start Eclipse. Use File New Scala Project menu and create chp6Rational Scala project in an appropriate folder. Eclipse automatically create a project folder with a name of your project, so you would just need to specify chp6Rational as a project name. When Scala project is created, Eclipse automatically creates "src" sub folder.





2. Expand the "chp6Rational" project tree in "Package Explorer", select "src"folder, right click and choose New Package. Name it "rational".



3. Expand the project tree, select "rational" package, right-click and choose New Scala Class. name it "Rational". Add an appropriate code from "Programming in Scala".
Do it again, this time creating new "MyApp" Scala Object and add def main(args: Array[String]) { } code.

4. Save everything.


IV. Here's how to set, compile, run or debug Scala application with Eclipse.

1. Select "chp6Rational" project in Package Explorer, click Run Run Configurations..., double-click or right-click on Scala Application to create a new one. Name your application, type chp6Rational as Project name, type fully qualified main class name as PackageName.ObjectWithMainMethodName (rational.MyApp in my case).
2. Hit "Run" button to compile and run your Scala application. What really drives me crazy is the fact, you'll need to repeat steps 1-2 (except naming application, project, and main class) every time you want to run your Scala application. "Run" button on Eclipse toolbar doesn't work correctly with Scala.





3. Debugger works nicely with Scala application. You can set breakpoints by double-clicking gray area to the left of your code, execute code line-by-line, see values of variables.
Repeat steps 1-2 above, but instead of Run Run Configurations... start from Run Debug Configurations... After you finish debugging in Eclipse, close Debug Perspective by clicking on "Scala" perspective in the top right corner.

Friday, July 25, 2008

Sokoban

Sokoban, according to Wikipedia, is a "transport puzzle in which the player pushes boxes around a maze, viewed from above, and tries to put them in designated locations". It was a first and only computer game I ever enjoyed (except sort period of Prince of Persia :) ).

It's quite a complicated scientific problem to solve. I re-discovered it as a plugin for IntelliJ IDEA development environment.

Thursday, July 24, 2008

A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans. Installation.

1. Eclipse vs. IntelliJ IDEA vs. Netbeans. Installation.
2. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with Eclipse.
3. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with IntelliJ IDEA.
4. Eclipse vs. IntelliJ IDEA vs. Netbeans. Creating and running Scala project with Netbeans.
5. A novice Scala programmer: Eclipse vs. IntelliJ IDEA vs. Netbeans.

This is a first article in a mini-series.

The Scala Programming Language
is a beautiful modern statically typed general usage language, combining object-oriented and functional programming approaches. It was originally developed for Java platform, but also exists for .NET. "During a meeting in the Community Corner (java.net booth) with James Gosling, a participant asked an interesting question: "Which Programming Language would you use *now* on top of JVM, except Java?". The answer was surprisingly fast and very clear: - Scala."

I. Which Integrated Development Environments support Scala?


Until recent time, it was impossible to find an acceptable IDE for Scala development. How could you expect any substantial usage of a language, if you almost have to write code in Notepad and then compile it from command line?

Fortunately, it looks like that things are changing. Right now there are [at least] three different development environments which has Scala plug-ins available: Eclipse, IntelliJ IDEA, and Netbeans. Unfortunately, all of them are for Java's breed of Scala, I didn't find any IDE supporting Scala for .NET.
Eclipse and Netbeans are free; to obtain a free copy of IntelliJ IDEA, one have to prove that he is an established Open Source developer, otherwise it's relatively expensive. On all three platforms you would need to install a [beta] plugin to be able to work with Scala. (Scala SDK itself is totally free.)

II. Installation.

It's easy to install Scala and to configure your machine:
1. Make sure you have a latest Java Runtime Environment or, better, Java Development Kit; see glossary for details). (I never tried to run Scala's .NET compiler, although I'm ASP.NET developer.)
2. Download and install latest Scala. Java installer works just fine. Read Getting Started with Scala and set environment variables. (If you are new to Scala, Programming in Scala book is a must.)

Here's how to install IDEs and corresponding plug-ins:
3. Eclipse.
Download and install latest stable release. I chose "Eclipse Classic".
Download and install New Scala Plugin beta (do not use "stable", it's very primitive and is not being maintained any more.)
Note, that you don't need to download plugin using browser. Instead start Eclipse, open Help Software Updates Available Software Add Site and use http://www.scala-lang.org/downloads/distrib/files/nightly/scala.update/ as a remote update site.

4. IntelliJ IDEA
Currently, to run Scala plugin you have to install a latest Diana EAP (beta) version of IntelliJ IDEA. Stable version of IntelliJ IDEA will not work with Scala plugin.
Start IntelliJ IDEA and go to File Settings IDE Settings Plugins Available. Select Scala and Sokoban, right-click and select "Download and Install". Do not select any other plugin, because they are incompatible with Diana EAP version of IntelliJ IDEA. Click OK.

5. Netbeans.
Currently, to run Scala plugin you have to install a latest nightly build of Netbeans. I installed a pack marked as All. A complete instruction of installing Netbeans and Scala beta plugin is written by plugin author.

Monday, July 14, 2008

A generic ListCollection class. Take 2.

I blogged recently about using public Collection instead of public List. The Visual Studio Code Analysis Team explained in their blog how to re-use List methods in classes derived from Collection<T> generic class. As you can see, their approach requires your class constructor to call base constructor of List<T>. To make developer's life easier, I proposed to make a generic ListCollection<T> class with such a constructor and inherit custom collection classes from it.
Then I read The Missing .NET #2: Collection<T> AddRange() article by Jason Kemp. He implemented "missing" methods of Collection<T> as extension methods. I added the same methods to my ListCollection<T> class. Because a default constructor of ListCollection<T> class guarantees that its protected Items property actually contains a List<T>, it is easier to implement "missing" methods; you just call corresponding methods of List<T>:


  /// <summary>
  /// A generic Collection class which ensures that it actually contains generic List.
  /// This provides us with an ability to re-use any public method of List&lt;T&gt; with a simple shell function.
  /// Such a shell could be implemented in a concrete implementation of this generic class,
  /// as extensions methods for ListCollection&lt;T&gt; or directly in ListColection&lt;T&gt; as it is done below.
  /// See "The Missing .NET #2: Collection&lt;T&gt; AddRange()"
  /// <see cref="http://www.ageektrapped.com/blog/the-missing-net-2-collectiont-addrange/"/> as well.
  /// </summary>
  public class ListCollection<T> : Collection<T>
    where T : class {
    public ListCollection()
      : base(new List<T>()) {
    }
 
    public void AddRange(IEnumerable<T> values) {
      ((List<T>)this.Items).AddRange(values);
    }
 
    public bool Exists(Predicate<T> match) {
      return ((List<T>)this.Items).Exists(match);
    }
 
    public T Find(Predicate<T> match) {
      return ((List<T>)Items).Find(match);
    }
 
    public ListCollection<T> FindAll(Predicate<T> match) {
      ListCollection<T> items = new ListCollection<T>();
      items.AddRange(((List<T>)Items).FindAll(match));
      //foreach (var item in ((List<T>)Items).FindAll(match)) {  //You can use this as an alternative to the above line
      //  items.Add(item);
      //}
      return items;
    }
 
    public int FindIndex(Predicate<T> match) {
      return ((List<T>)Items).FindIndex(match);
    }
 
    public int FindIndex(int startIndex, Predicate<T> match) {
      return ((List<T>)Items).FindIndex(startIndex, match);
    }
 
    public int FindIndex(int startIndex, int count, Predicate<T> match) {
      return ((List<T>)Items).FindIndex(startIndex, count, match);
    }
 
    public T FindLast(Predicate<T> match) {
      return ((List<T>)Items).FindLast(match);
    }
 
    public int FindLastIndex(Predicate<T> match) {
      return ((List<T>)Items).FindLastIndex(match);
    }
 
    public int FindLastIndex(int startIndex, Predicate<T> match) {
      return ((List<T>)Items).FindLastIndex(startIndex, match);
    }
 
    public int FindLastIndex(int startIndex, int count, Predicate<T> match) {
      return ((List<T>)Items).FindLastIndex(startIndex, count, match);
    }
 
    public void ForEach(Action<T> action) {
      ((List<T>)Items).ForEach(action);
    }
 
    public int RemoveAll(Predicate<T> match) {
      return ((List<T>)Items).RemoveAll(match);
    }
 
    public bool TrueForAll(Predicate<T> match) {
      return ((List<T>)Items).TrueForAll(match);
    }
 
  }


An update: I added a "conversion" constructor Collection<T>(IList) to my ListCollection<T> generic class. It is useful and even made one method of this class itself simpler:


 
    // A default constructor
    public ListCollection() : base(new List<T>()) { }
 
    // A "converter" constructor, which does not copy the list passed in.
    // See http://msdn.microsoft.com/en-us/library/ms132401.aspx
    public ListCollection(IList<T> list) : base(list) { }



 
    public ListCollection<T> FindAll(Predicate<T> match) {
      return new ListCollection<T>(((List<T>)Items).FindAll(match));
    }