LEARNING MONO
Experiments for
Url fileReading,
MySql dbquery
and
Cryptography
R.S.Ramaswamy
(rs.ramaswamy@gmail.com)
( published in DeveloperIQ…Jan-2006)
The C# language
has been made available for Linux/Unix platforms through Mono , an open-source/free project,
initiated by Miguel de Icaza and promoted by Novell Netware
& IBM.In fact, the Common Language Runtime, the special feature of
DotNet platform , originally available for Windows platform only , is now being
ported to Linux/Unix environments. The C# compiler in Mono is only the first
step in this direction. Just as DotNet framework can be used with VB.net, Java
script, J# and Managed C++, the Mono project also hopes to provide these
features, ultimately. Thereby, it is claimed that all the platform-independent
advantages of Java will be combined with the language-independent
common-language-runtime of DotNet and the result will be better than either. That
is for the future however.
Right now, only C# is available in Mono. And
unlike Java, which can be run in any platform, ( for which a Java interpreter
is available) , Mono is available only for Linux/Unix).As it is, it may be a bit premature to abandon j2ee and
jump into the Mono bandwagon too hastily.! Enterprise container is not yet
available in Mono and so it will not be suitable for projects which require
enterprise-services.
Even DotNet , has not provided independent
Enterprise container and gives only a
wrapper for COM+ of legacy fame. It is a tacit admission and may be the reason
for Microsoft vigorously promoting XML webservice, because it enables DotNet to
make use of EJB!
No harm in
experimenting and learning C# through Mono, however, to get ready for the
promised day of deliverance from 'non-open' software like Java!, (as if Java source is being kept secret !Actually,
it is as open as it can be. It is like an open-access public library where you
can access, borrow and use the books without mutilating the books! There are
many voices questioning the very rationale of the Mono project and suspecting
Corporate shadow-boxing behind the scenes.)
JDK was introduced in Jan 1996 , and C#
came in
2000 & Mono about 2 years back in
2003. No wonder then that C# has taken a number of advanced features from JDK
and hence Mono's C# also is very much like JDK.
It will be
instructive to study C# and Java side-by-side. Sometimes, it would seem that
the class naming and API of Java is much more elegant than C#. For learners who would like to study C# in
comparison to Java, the following two books are very useful.
1)Professional DotNet
for Java Developers with C#
-by
Jack Lunn & others
( WROX PRESS)
2) C# Programming
-Burton Harvey
(WROX PRESS)
We can use Java both in Windows and Linux.
Similarly, Mono allows C# to be developed and run in Windows and Linux
platforms. Mono for Windows has been
given in DeveloperIQ cd's a number of times. It is a compact zip file compared
to the DotNet Framework SDK and installtion is very easy. After installing it ,
we can get at the Mono console through
the 'start' menu.
We can then
edit our C# source code in any
folder of our choice and compile and run the programs.
To compile , the command is:
>mcs demo.cs
and to run the program,
>mono demo.exe
------------------------------------------
Let us now begin with a simple example to
read an URL file and print the contents in console. We will first see the Java
version and then the C# version.
--------------------------------------------
import
java.io.*;
import
java.net.*;
class
urlfile
{
public static void main(String args[])
{
try
{
URL url = new URL ( args[0]);
DataInputStream dis =
new
DataInputStream( url.openStream());
String s = dis.readLine();
while(s
!= null)
{
System.out.println(s);
s = dis.readLine();
}
} catch(Exception e1)
(System.out.println(""+e1);}
}
}
===========================================
As usual ,
we give path:
g:\sam>
set
PATH=c:\windows\command;d:\jdk1.3\bin
compile and run the program .Let us assume
that Apache server has been installed in our system (using PHP-Triad software).
We start apache from 'start' menu. Let us place a simple file names.txt in
the root folder of Apache. ( c:\apache\htdocs).
To test our program, we run the java
program with the argument:
>java urlfile
"http://localhost/names.txt"
This will show the names.txt file in the
console.
-------------------------------------------
Let us now write a similar program in C# ,
compile and test it using MONO.
------------------------------------------
EXPERIMENT-2
------------
Reading an URL file
----------------------
using System;
using System.Net;
using System.IO;
using System.Text; //
Encode.ASCII
class urlfile
{
public static void Main(String[]
args)
{
HttpWebRequest webreq =
(HttpWebRequest)
WebRequest.Create (args[0]);
HttpWebResponse webresp =
(HttpWebResponse)webreq.GetResponse();
StreamReader ins =
new StreamReader
( webresp.GetResponseStream(),
Encoding.ASCII);
//-----------------------------------
String
s = ins.ReadLine();
while(s
!= null)
{
Console.WriteLine(s);
s=ins.ReadLine();
}
}
}
===========================================
The code is almost the same as in Java .
We can create this file in g:\monodemos folder.
Navigate to g:\monodemos folder(through the Mono
console obtained from start menu...this is important.If we access this file from outside the mono
console, we won't get the required classpaths).
We can compile and run the program by the
procedure mentioned already and we get expected result without any problem.
======================================
EXPERIMENT-2
============
Accessing MySql
Database
------------------------
We now see an
example of accessing a MySql Database, through Mono.But before that we
see a simple sample for Database access in DotNet Framework SDK.
( let us create a
folder 'g:\dnf'.
dnf for DotNet
FrameWork Sdk)
=======================================
//
g:\dnf\accessreader.cs
using System;
using System.Data.OleDb;
using System.Data;
class
accessreader
{
public static void Main(String[] args)
{
String s1=
"Provider=Microsoft.JET.OLEDB.4.0;
data source=e:\\dbdemo.mdb";
//( to be typed
in a single line)
// ( leave space
between 'data' & 'source')
OleDbConnection con=
new OleDbConnection(s1);
con.Open();
String
sql= args[0];
OleDbCommand command=
new OleDbCommand(sql,con);
OleDbDataReader reader=
command.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
reader.Close();
con.Close();
}
}
-------------------------------------------
The above code is
meant for DotNet FrameWork SDK.
We can create
this file in g:\csharp
and compile by
the command:
g:\csharp>csc dbdemo.cs
and run the
program by
g:\csharp>dbdemo
------------------------------------------
The important
part of the code is the String for Provider. In Mono, also the operative
part of the code is the same except for the string denoting the Provider for
MySql database.
=========================================
// g:\monodemos\monomysql.cs
using System;
using System.Data;
using ByteFX.Data.MySqlClient;
class
monomysql
{
public static void Main(String[] args)
{
String s1 = "Server=localhost;Database=addressbook;";
MySqlConnection conn=null;
try
{
conn=new MySqlConnection(s1);
String
sql = args[0];
MySqlCommand command=
new MySqlCommand(sql,conn);
conn.Open();
MySqlDataReader reader=
command.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
reader.Close();
conn.Close();
}catch(Exception e1) { }
}
}
===========================================
It is assumed that readers are quite
familiar with ADO.net in DotNet Framework SDK.
Mono installation provides ready-made
Data-providers for IBM DB2, MySql,ODBC,Oracle,OLE DB, PostgreSQL,Micrsoft
SqlServer and Sybase.
But we must
import the required libraries.
In the above
case, we have used
ByteFX.Data.MySqlClient;
Except that we
have changed the provider string and name of the classes, there is very little
difference in DotNet Framework code and Mono code!
=======================================
However, the following points are very
important.
While compiling,
we should give reference to ByteFX.Data
We have created
the file in :
g:\monodemos\monomysql.cs
>mcs -r:ByteFX.Data -r:System.Data monomysql.cs
We get the message ,
compilation
succeeeded.
After this, we
can run the program as:
>mono
monomysql.exe "select * from
table1"
It is assumed
that we have already created the mysql database 'address book' and table1.
The
mysql database is started from the start menu of php triad.
We get correct
result.
=======================================
EXPERIMENT-3
Cryptography in
C#
------------------
Finally, we will
see an example for Encryption and Decryption in C# . Readers can refer to the
tutorial on Java Cryptography API's in the December 2005 issue of DeveloperIQ.
The concept of Secret key and the various types of algorithms has been
covered there. One such algorithm is TripleDES.In this example, we will
use that algorithm. The code creates the secret key by TripleDES, and then gets
the key and the Initialisation Vector(IV). Using this secret key, it encrypts
the given string.
After this, the
encrypted message is decrypted and displayed. Readers may compare the code with
that of the similar lesson in Java , published in December 2005 issue. The
similarity would be striking!
Now for the
code..
-------------------------------------------//
g:\monodemos\keyer.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public
class keyer
{
public static void Main(String[] args)
{
TripleDESCryptoServiceProvider provider=
new
TripleDESCryptoServiceProvider();
provider.GenerateKey();
provider.GenerateIV();
String a = args[0];
//--------------------------------------
MemoryStream ms1 = new MemoryStream();
CryptoStream cs1 = new CryptoStream (ms1,
provider.CreateEncryptor(),
CryptoStreamMode.Write);
cs1.Write
(Encoding.ASCII.GetBytes(a),0,a.Length);
cs1.FlushFinalBlock();
byte[]
secret = ms1.ToArray();
//----encrypted data ready!--------
Console.WriteLine("encrypted
data ready!");
MemoryStream ms2 = new MemoryStream();
CryptoStream cs2 = new CryptoStream
(ms2,provider.CreateDecryptor(),
CryptoStreamMode.Write);
cs2.Write(secret,0,secret.Length);
cs2.FlushFinalBlock();
ms2.Seek(0,SeekOrigin.Begin);
StreamReader reader =
new StreamReader(ms2);
String original = reader.ReadToEnd();
Console.WriteLine("original
got back!");
Console.WriteLine(original);
}
}
=========================================
After creating the file, we can compile this
through the Mono console and run it .
g:\monodemos>mcs keyer.cs
g:\monodemos>mono
keyer.exe "this is secret!"
We will get the
console display:
encrypted data
ready
oroginal got back
this is secret!
--
In actual practice, we can store the key ,
vector and encrypted data in files. We then read these from the files and use
the same key and vector to decrypt.
=========================================
Suggested
Reference book:
MONO
-A
Developer's notebook
-by
Ed Dumbill
-OReilly
publication
-------------------------------------------