:FM

Ni`k\jkXe[Xi[j$Zfdgc`Xek:gif^iXdj`e`elon`k_;fk>EL J@E>@E>J?8IG

Write C# programs in with the free and vendor-neutral DotGNU. DotGNU, the emphasis is on standards compliance and staying free of license BY MAYANK SHARMA restrictions, rather than on being com- patible with the latest from the ike many, I grew up programming programming language are codified as camp. As DotGNU developer Klaus Tre- in C and C++ before moving ECMA (a non-profit standards body) and ichel points out, it is unfair to compare Cinto LAMP-land and Python, Perl, ISO international standards, which cre- DotGNU with because Mono has and PHP. But like that first car, first date, ates the possibility for independent im- full-time developers paid by a large com- and first paycheck, everyone has a spe- plementations. The DotGNU project was pany. DotGNU has always been a volun- cial memory of the first time they com- started with huge fanfare to bring stan- tary project supported with donations. piled gibberish into executable machine dards-compliant C# to Linux. Over the One such donation was from Trumpf code. years, DotGNU has received less atten- Group, which has a pulsed laser cutting Thanks to GCC, open source develop- tion than the other .NET for Linux: the tool that uses DotGNU. The touch screen ers have never had any issues writing C Novell-sponsored Mono project. Never- user interface of the laser tool was built or C++ code on a Linux platform. theless, the project is still chugging through the use of DotGNU. However, when Microsoft announced along, and it is even finding some use in Although some parts of the Mono en- their .NET initiative and the intention to commercial applications. vironment (including the C# compiler) focus their efforts around C#, few people Although DotGNU has lost some of its are released under the GPL, other parts expected Microsoft to release a Linux cli- steam in recent years, it is still in active are subject to license and patent con- ent for their “platform-independent” de- development. Certainly one cannot com- cerns that reflect the complex business velopment tool. pare the pace of development with that relationships between Novell and Micro- Fortunately, .NET’s Common Lan- of Mono – or even with its own initial soft. Fortunately for us, then, the Dot- guage Infrastructure (CLI) and the C# activity – but that’s mainly because, at GNU project offers a vendor-indepen-

22 ISSUE 102 MAY 2009 DotGNU :FM

For writing web services, DotGNU re- brary, which is used to build GUIs. Sys- lies on the DotGNU Execution Environ- tem.Windows.Forms simplifies develop- ment, or DGEE, and phpGroupWare. ment by reducing dependence on other DGEE is a web-service server that can toolkits. accept and process XML-RPC requests from web services, and it can generate >\kk`e^k_\Kffcj browsable documentation for these ser- Some distro repositories carry DotGNU vices in HTML or XML. phpGroupWare binaries, but it’s a good idea to compile is a groupware suite that also provides them from source. The tarballs are avail- a host of web-service components. able on the DotGNU website [1], and The DotGNU C# compiler also com- you can also fetch them via CVS. piles programs written in C, thanks to To get the compiler and libraries, in- the libc implementation of the C com- stall treecc, pnet, and the pnetlib pack- piler, pnetC. Because DotGNU’s objective ages. Optionally, the ml-pnet package is to follow the standards, rather than lets you work with Mono’s libraries, and follow Microsoft, the implementation the pnetC package enables the DotGNU lacks a few assemblies. To help develop- compiler to compile C programs. ers use the missing bits, the DotGNU The command: folks distribute some of the libraries from the Mono project. This distribution cvs -z3 -d:pserver:anonymous5 of the Mono libraries is achieved via the @cvs.sv..org:/sources/5 build scripts in the ml-pnet package. dotgnu-pnet co .

N_pGif^iXdn`k_ downloads the latest source of all Dot- ;fk>EL6 GNU packages inside the directory it is One of the main reasons for writing C# issued from, so make sure it is under code in DotGNU is that it is compatible something like /opt/dotgnu. Now change with the EMCA standards for C# and the to each directory and run ./auto_gen.sh CLI. Furthermore, DotGNU also is com- for all the packages to generate the con- patible with Microsoft’s own CLI imple- figuration and make files. Once that’s mentation of the .NET framework. completed, or if you just grabbed the tar- Thanks to the modular design of Por- ball instead of checking out via CVS, the table.Net, the DotGNU C# compiler can usual ./configure, make, make install run on multiple platforms. Portable.Net’s (the last one, as usual, as root) will in- run-time engine and the C# class stall the DotGNU compiler and libraries. have extensive support for embedded dent alternative for open source pro- system profiles and can be built with dif- Nfib`e^n`k_k_\:fdg`c\i grammers who want to try their luck ferent ECMA profiles. Each profile en- For those who speak binary, DotGNU with C# and .NET. ables or disables features in the system. works by transforming bytecode into a As a testament to its portability, one of simple instruction set that is passed on 9i\Xb`e^;fne;fk>EL the founding develop- DotGNU is more than just a C# compiler, ers, Gopal Vijayaragha- Listing 1: Hello.cs but I’ll start off with that. Portable.Net is van, was able to get 01 using System; the free implementation of .NET, and it Portable.Net running 02 public class HelloWorld contains a run-time engine, a C# com- on the Indian hand-held 03 { piler, and a host of other tools that make computer, the Encore 04 public static void Main (string [ ] args) Portable.Net easy to port to other plat- Simputer, during the 05 { forms. All these components are written three days of FOSS.IN 06 if (args.Length != 1) in C. The aim of the project is to make in Bangalore. 07 { the development of .NET apps easy on also non-Microsoft platforms. will appreciate the self- 08 Console.Error.WriteLine("You must tell me your name."); In the early days of development, the contained nature of 09 Environment.Exit(-1); C# system library was split from the DotGNU and that it 10 } main Portable.Net distribution. The li- doesn’t depend on ex- braries are now available as part of the ternal libraries. A much- 11 string name = args[0]; pnetlib package. Another important discussed feature of 12 Console.WriteLine ("Hello, {0}!", name); component is treecc, an aspect-oriented DotGNU is its imple- programming tool that assists in devel- mentation of the Sys- 13 } opment with the DotGNU C# compiler. tem.Windows.Forms li- 14 }

MAY 2009 ISSUE 102 23 Anzeige wird separat angeliefert Anzeige wird separat angeliefert :FM

Listing 2: Hello-Advanced.cs 01 using System; 11 {

02 using System.Collections; 12 Console.WriteLine("Hello,

03 {0}!", value);

04 public class HelloWorld 13 }

05 { 14 else

06 public static void Main() 15 {

07 { 16 Console.WriteLine("Sorry, you

08 String value; apparently don't have a name!");

09 value = Environment. 17 } GetEnvironmentVariable("USER"); 18 }

10 if(value != null) 19 } to a virtual machine to be executed via libraries required to process a Win- Listing 1 greets the user with a name an interpreter. This design makes Dot- Forms-dependent program. Sometimes slipped in as input. But why enter a GNU easily portable and explains the you’ll have to create your own DLL li- name for the user when a name is prob- number of supported platforms. braries. The -shared switch will produce ably already defined on the system? The components you’ll use are the these DLLs instead of a .exe. Using the System.Collections library, you ilrun run-time engine, which executes In addition to C#, the DotGNU com- can, among other things, display the the binaries doled out via the cscc com- piler can also compile to Java Virtual contents of all the environment vari- piler, and cscc some-program.cs, which Machine bytecode with the -mjvm ables. If you modify the hello.cs program produces a file called a.out. This file can switch. Remember to use the .jar file to use the System.Collections library then be executed with: extension instead of .exe or .dll. (Listing 2), you can read the username of the user executing the program with ilrun a.out ;`m\@e value = Environment.Get En viron ment- After that brief introduction to the com- Variable("USER"), wherein value is a With the -o switch, you can specify a file piler and common options, I’ll honor String type variable. name when compiling your program the long tradition of coding tutorials by with cscc – for instance: writing a “Hello, World” program in C# >\kJ\k>L@ (Listing 1) and compiling it with cscc -o One of the best bits about DotGNU is an cscc -o some-program.exe 5 hello.exe hello.cs. implementation of the System.Windows. some-program.cs The simple program contains only one Forms library that doesn’t require trans- method: Main(). Command-line argu- lation via other popular toolkits such as To print debugging information, use the ments are passed to this method as an Gtk. Much like the Java Swing library, -v switch while compiling. array of string objects by way of the Sys- DotGNU’s System.Windows.Forms draws If you have to link against a particular tem library and its various classes and its own controls. library, say System.Drawing, you’ll need methods. System.Environment.Exit() To compile the code in Listing 3, use: to point this out to the compiler with the exits the program and sends a return -lLIBRARY switch, which will search for code to the shell. The System.Console cscc -o form.exe form.cs 5 the libraries DLL along the library search class interfaces the command line to -winforms. path. If you are compiling a GUI program the program. The Console.Writeline() that uses the System.Windows.Forms method writes the greeting to standard The code displays a simple re-sizable library, you can also use the -winforms output, and Console.Error.Writeline() window with the usual minimize, maxi- switch, which automatically links all the writes to standard error. mize, and close controls.

Listing 3: Using System.Windows.Forms 01 using System; 11 }

02 using System.Windows.Forms; 12 }

03 13

04 public class MyForm : Form 14

05 { 15 public class MyApp

06 public MyForm () 16 {

07 { 17 public static void Main(string[] args)

08 this.Text = "The beginnings of a multi-tab 18 {

text editor"; 19 App.Run(new MyForm());

09 this.Height = 600; 20 }

10 this.Width = 800; 21 }

26 ISSUE 102 MAY 2009 DotGNU :FM

Listing 4: Advanced Form Controls 01 public class MyMenu : System.Windows.Forms.MainMenu 12

02 { 13 mFileNew = new MenuItem("&New");

03 public System.Windows.Forms.MenuItem mFile; 14 mFileSave = new MenuItem("&Save");

04 public System.Windows.Forms.MenuItem mFileNew; 15 mFileExit = new MenuItem("E&xit");

05 public System.Windows.Forms.MenuItem mFileSave; 16

06 public System.Windows.Forms.MenuItem mFileExit; 17 mFile.MenuItems.Add(mFileNew);

07 18 mFile.MenuItems.Add(mFileSave);

08 public MyMenu() 19 mFile.MenuItems.Add(mFileExit);

09 { 20 }

10 mFile = new MenuItem("&File"); 21 }

11 this.MenuItems.Add(mFile);

The next step is to add a menu to this For the first-time GUI , this with the use of buttons to save the file window. The complete listing is avail- procedure might be a little overwhelm- and do other tasks. able on the magazine website [2], but ing, but really it couldn’t be simpler. The the most important bits are in Listing 4. various System.Windows.Forms methods :feZclj`fe A custom class called MyMenu inherits take care of adding GUI functionality to Several books and tutorials on C# can be from the System.Windows.Forms.Main- the menu and the items, so that when found on the Internet. The advantage of Menu class and is used to create the you compile and run the code, the File DotGNU is that it is completely stan- menu items. The menu item variables menu will function as it does in any GUI dards compliant; therefore, you can use are of the MenuItem type, which is spe- application: First you click to display the documentation from Microsoft’s C# li- cifically used to create items within a items, and then you click to fold them brary. To get things done faster, you can menu or a context menu. back in. use front ends, such as Microsoft’s Vi- The MyMenu() constructor creates the Of course, you still have to associate sual Studio and Mono’s MonoDevelop File menu item with the new keyword. your menu with your original form code IDE [3]. But if you want to write truly Similarly, Listing 4 creates an instance of and program event handlers for the vari- portable code with DotGNU, you’ll have the three menu items and specifies how ous items to get them to work. Also, to be extra careful with these tools and they’ll appear in the menu. Because I al- you’ll have to tie these event handlers to make sure you stay away from features ready have the File menu ready, I use the the particular menu item’s click event. unique to a particular platform. p Add() method to add the three menu Further on, you have to create dialog items to the main menu. boxes and add functionality to them INFO

[1] DotGNU website: Languages and Libraries http://www. gnu. org/ software/ C# borrows a bit from several popular lan- for reading and writing streams and files, dotgnu/ guages, including C, C++, and Java. If System.Net for network programming, [2] Listings for this article: you’ve programmed in Java, you’ll find System.Security for making your pro- http:// www. linux-magazine. com/ that, in C#, you can have a class name grams respect permissions, and, of resources/ article_code with a name that’s not the same as the course, System.Windows.Forms for creat- [3] MonoDevelop: source file. Similar to Java, and unlike the ing GUIs. http:// . com/ C languages, C# doesn’t have header files. However, some libraries are not directly [4] DotGNU library definitions: Plus, you have the flexibility of either im- available, such as System.Data, which http://www. gnu. org/ software/ porting a namespace or specifying it fully provides classes to implement the ActiveX dotgnu/ pnetlib-doc/ when using a function like System.Con- Data Object, or ADO for reading and writ- sole.Writeline. Again, this has the Java ing data from various data stores such as [5] Library status: footprint all over it. databases. But you can use the ADO li- http://www. gnu. org/ software/ dotgnu/ pnetlib-status/ Also note that the C++ :: operator isn’t re- brary via the ml-pnet package. quired in C#. The task of referencing class DotGNU-specific definitions for the pack- members is accomplished with the dot (.) aged libraries are available online [4], al- Mayank Sharma has written for vari- operator. though they are not complete, and it is ous Linux publications, including All the most important C# libraries are im- possible that a function might not be de- Linux.com, IBMdeveloperWorks, and plemented in DotGNU. The library lineup fined there but available nonetheless. Linux Format, and he has published includes the core System library that Some of the libraries do have missing two books through Packt on adminis- (among other things) contains classes for constructs and methods, and you can also tering Elgg and Openfire. Occasion- handling data types, the System.Collec- learn more about these elements online ally he teaches FLOSS technologies. tions library that helps define and traverse [5]. However, this information might not

THE AUTHOR THE You can reach him at: objects such as lists and arrays, System.IO be up to date. http://www. geekybodhi. net.

MAY 2009 ISSUE 102 27