Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Tuesday, March 17, 2009

.NET Parallel Computation Made Easy : System.Threading.Parallel

I had conduct a simple experiment for some time ago. It's about the performance of .NET program running on a multi-core processor versus the same program running on the single-core one. The result from my experiment shows that if you have a normal .NET program implemented without multi-threading, there will be no significant performance difference between running it on multi-core and single-core system.

I found it hard to create a multi-thread version of my classic old "Prime Generator" program. The hardest part is I don't know the appropiate number of thread to create since I had no information about the system the program is runnning on. And the threading code just looks ugly .. developers with no multi-threading background will find it hard to understand and maintain. Take my old code for example.


The Rescue
This is where Microsoft Parallel Extensions to .NET Framework 3.5 comes in handy. It simplify the process of constructing the multithread code yourself. There are many useful stuffs under System.Threading.Parallel. But I find System.Threading.Parallel.For is the easiest to understand and utilize :)


Here is the plotting between the data set size and time used in millisecond on my machine with Intel(R) Core(TM)2 Duo CPU E6750 @ 2.66GHz. The System.Thread.Parallel.For actually takes extra computation time on the first call which makes me wonder why an ordinary for-loop outperforms parallel version at very first version of my benchmark. However, after the first call, the parallel version outperforms ordinary for-loop as expected.

I believe the results will be different on a quad core machine too :)


Hope this helps.

Tuesday, February 10, 2009

C# Lambda Expression on MonoDevelop and Ubuntu

I always wanted to try out coding C# application on Ubuntu Linux. The most popular IDE of choices for this would be MonoDevelop by Mono Project. I installed MonoDevelop through Synaptic the same way I did with other applications.

It was a surprise to me to found out that Mono even supports some new features from of C# such as Lambda Expression and Object Initializer!


The only problem is their IDE, MonoDevelop, still not support autocompletion (a.k.a. Intellisense) of Lambda Expressions and Object Initializers. Moreover, it marks the code as error by underlining them in red.

In conclusion, Mono looks promising. And I just can't wait to see more Linux people coding new apps in C#!

Sunday, November 30, 2008

LINQ with MySQL

LINQ to SQL from Microsoft supports only their SQL Server. How about other popular DBMS such as MySQL ?

I investigate the first result returned from Google using "LINQ with MySQL" query: DbLinq. It's an opensource project which provides "LINQ to SQL" for other databases include MySQL, PostgreSQL, Oracle and SQLite.

However, the project is still at its very beginning stage and I think it will take some time before we can use it in production environment, IMHO.

Here is my setup of DbLinq with MySQL

  • Visual Studio 2008 Professional
  • MySQL 5
  • DbLinq 0.18
  • Windows Vista
1. I first have my database prepared, its name is "Items".

2. Run DbMetal which is a tool comes with DbLinq in "build" folder. I use the following command for my MySQL server. I have user root with no password.

C:\Downloads\DbLinq-0.18\DbLinq-0.18\build>DbMetal /server:127.0.0.1 /database:items /provider:MySQL /user:root /code:Items.cs
DbLinq Database mapping generator 2008 version 0.18.0.0
for Microsoft (R) .NET Framework version 3.5
Distributed under the MIT licence (http://linq.to/db/license)

>>> Reading schema from MySQL database
<<<>


3. You will have a C# code file, Items.cs in my case, automatically generated. This file contains C# classes generated from database schema and the mapping attributes.

4. You may want to compile the project now. I found some errors in my cases:
  • There is no type specified for fields of MySQL's Enum type. You can fix this easily by insert C#'s "string" type. In my case: private _gender; to private string _gender;
  • EntitySet cannot be resolved. Change every occurances to System.Data.Linq.EntitySet instead.

If you can compile your project, you can proceed to the next step.

5. Here is my code for querying from MySQL database. From my setup, it's an ASP.NET web application with a single GridView on the Default.aspx page.



6. Run and see the result : )

Saturday, September 27, 2008

Syntax Highlight/Format C#, Java, PHP Code in Blogger

The method I used to put syntax highlighted code in my blog is to use the "Code Format" tool provided by Manoli.net. It works fine but I am just lazy to convert my code every time I post a new entry.

I then try to find another solution. One option is to use SyntaxHighlighter, a Java Script library that does all the syntax highlight jobs for you.

After installation, one problem I faced is that all the "new line" I wrote in "Edit Html" of Compose Page in Blogger are converted to "
". That's not very nice : (

Like everytime, I performed a search and found a good solution here, Using SyntaxHighlighter on BLOGGER. The purpose of additional script is to convert all the "
" found in the code to "new line" chracter. It works fine and here is my sample of highlighted Java code.

(Of course, I will not use silly program like Hello World for this :D )

And here is the result:



Simple, isn't it ?

Friday, May 11, 2007

Programming MSMQ (Microsoft Message Queue) - Sample code

Yesterday, I went to "MSDN Connection Training Sneak Peak Preview" seminar at Microsoft Thailand. The topic is "Distributed Application Development with Visual Studio 2005". It is actually a shortened version of Iverson training course : if you want to take a full course, you will have to pay at least ten thousand baht for 3 days training o__O!

I really learned many things from this session. One of them is MSMQ or Microsoft Message Queue.

Message queuing is a communication tool that allows applications to reliably interconnect in a distributed environment where one of the applications may or may not be available at any given time. The queue acts as a holding container for messages as they are sent between applications. The applications send messages to and read messages from queues to communicate back and forth. An application writes a message to a queue, which will then be received and processed by another application at some point determined by the receiving application. This type of communication is designed for asynchronous use where the applications involved are not waiting for an immediate response from the other end. - http://www.codeguru.com/Csharp/.NET/net_general/netframeworkclasses/article.php/c4241/


This really fits into my project's need for a queue which can serve clients over the internet.

To program the MSMQ you need to install Messaging Queuing first. Insert your Windows Setup CD and choose "Install optional Windows components". Then, tick the checkbox in front of "Message Queuing" and go on.



Now, create a new Visual C# Console project. Add reference to System.Messaging and add the following code.




using System;
using System.Collections.Generic;
using System.Text;
using System.Messaging;
using System.Threading;

namespace MSMQSample
{
class Program
{
static void Main(string[] args)
{
// Check if queue alreasy exists.
string queuePath = @".\private$\SampleQueue";
MessageQueue queue;
if (!MessageQueue.Exists(queuePath))
// If not, create one.
queue = MessageQueue.Create(queuePath);
else
queue = new MessageQueue(queuePath);

// Send something to queue.
DateTime dt = DateTime.Now;
Console.WriteLine("Message to send: " + dt.ToString());
Message sendMsg = new Message(dt, new XmlMessageFormatter());
queue.Send(sendMsg, "My DateTime");

// Wait for five seconds.
Thread.Sleep(5000);

// Get sent message from queue.
Message receiveMsg = queue.Receive();
receiveMsg.Formatter = new XmlMessageFormatter(
new Type[] { typeof(DateTime) });
DateTime ret = (DateTime)receiveMsg.Body;

Console.WriteLine("Message Received: " + ret);
Console.Read();


}
}
}


And this is what our message looks like. You can open this window in Computer Managment/Services and Applications/Message Queuing/samplequeue



Here are some great resources on the basics of MSMQ:
And for those who want to attend next MSDN Connection Training Sneak Peak Preview you have to register for an account at http://www.msdnconnection.com/thailand and monitor this page [MSDN Connection Training Sneak Peak Preview]



Tuesday, April 17, 2007

Polymorphism example in Java, C# and C++

It has been a while since I coded my first C program. Now, because many of my friends at the department began to interest themselves in C++ programming. So I think I should learn some of the basics of it too :P

C++ is a powerful programming language with tons of language features and hard-to-understand syntaxes. However, I am only interested in its object oriented features such as Class, Inheritance, Composition, Polymorphism, blah blah. Thanks to my background knowledge in OO, it did not take me long to understand all these.

I tried to create a very simple Polymorphism example in C++ using the famous open-source IDE, Dev-C++. Unfortunately, I experienced some problems about building C++ project with multiple files. The IDE kept telling me that there is multiple definition of functions in my code. So, I went googling and found this page, Organizing Code Files in C and C++. It provided me the basic understandings of compiling and linking process.

After finished coding the C++ example, I thought I should create the Java and C# version to compare with it too. I noticed that C# is more like C++ in that the functions (or methods) to be overriden must declared to be virtual while there is no such modifier in Java.


Here are my output and codes.



C++

main.cpp
#include 
#include "shape.h"
#include "circle.h"

using namespace
std;

int
main(int argc, char *argv[])
{

Shape *shape = new Shape();
shape->calculateArea();
shape->test();

Shape *circle = new Circle(10);
circle->calculateArea();
circle->test();

system("PAUSE");
return
EXIT_SUCCESS;
}

shape.h
#ifndef _SHAPE_CLASS
#define _SHAPE_CLASS

class
Shape{
public
:
virtual
void showName();
virtual
double calculateArea();
void
test(){
showName();
}
};


#endif

shape.cpp
#include "shape.h"
#include

using namespace
std;

void
Shape::showName(){
cout << "Shape: I am a shape!" << endl;
}


double
Shape::calculateArea(){
cout << "Shape: Dunno how to calc my area ..." << endl;
return
0.0;
}

circle.h
#ifndef _CIRCLE_CLASS
#define _CIRCLE_CLASS

#include "shape.h"

class
Circle : public Shape{
public
:
Circle(double radius) : radius_(radius){}
virtual
void showName();
virtual
double calculateArea();
protected
:
double
radius_;

};


#endif

circle.cpp
#include "circle.h"
#include
#include

using namespace
std;

void
Circle::showName(){
cout << "Circle: I am a circle!" << endl;
}


double
Circle::calculateArea(){
cout << "Circle : My area = " << M_PI*radius_*radius_ << endl;
return
M_PI*radius_*radius_;
}


C#
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace CSharpPolymorphism
{
class Program
{
static void Main(string[] args)
{
Shape shape = new Shape();
shape.showName();
shape.calculateArea();

Circle circle = new Circle(10.0);
circle.showName();
circle.calculateArea();

Console.Read();
}
}
}

Shape.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace CSharpPolymorphism
{
class Shape
{
public virtual void showName()
{
Console.WriteLine("Shape: I am a shape!");
}

public virtual double calculateArea()
{
Console.WriteLine("Shape: Dunno how to calc my area ...");
return 0.0;
}
}
}

Circle.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace CSharpPolymorphism
{
class Circle : Shape
{
protected double radius;

public Circle(double radius)
{
this.radius = radius;
}
public override void showName()
{
Console.WriteLine("Circle: I am a circle!");
}

public override double calculateArea()
{
Console.WriteLine("Circle : My area = " +
Math.PI * radius * radius);
return Math.PI * radius * radius;
}
}
}

Java
Main.java
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Shape shape = new Shape();
shape.showName();
shape.calculateArea();

Circle circle = new Circle(10.0);
circle.showName();
circle.calculateArea();

}

}

Shape.java
public class Shape {

/** Creates a new instance of Shape */
public Shape() {
}

public void showName(){
System.out.println("Shape: I am a shape!");
}

public double calculateArea(){
System.out.println("Shape: Dunno how to calc my area ...");
return 0.0;
}
}

Circle.java
public class Circle extends Shape{

protected double radius;
/** Creates a new instance of Circle */
public Circle(double radius) {
this.radius = radius;
}

public void showName() {
System.out.println("Circle: I am a circle!");
}

public double calculateArea() {
System.out.println("Circle : My area = " + Math.PI*radius*radius);
return Math.PI*radius*radius;
}

}

Wednesday, January 10, 2007

.NET Remoting Object in Action!

About .NET Remoting Object

I have started learning .NET nearly two years ago. One of the topics which is hard to understand and confused many newbies is .NET Remoting Object.

.NET Remoting Object is often compared to ASP.NET Web Service as an alternative for building distributed system. There are many tutorials on the internet that show how to consume web service or how to create a web service. So we can see clearly how and where web service would plug into our applications. But for .NET Remoting Object, there are less tutorial. And I really don't know how can I make use of it in my application.

The Situation
Here at my university, My friends and I (as a group of Microsoft Student Ambassadors) conduct a competition on AI programming. Competitors have to code his/her robot in C#. The robot can move in 4 directions and can place a bomb just like in the "Bomberman" game. 4 of these will be placed in the same map in each round and the last stand wins.

So what's the problem ?

The competitors have to code his/her robot as a derived class from "BaseAIBot" which is a class derived from "Thread". Then they have to compile their projects into DLLs. And have these DLLs run in our host application.

This is COMPLETE BLIND DEBUGGING !!

So the competitors must find someway debugging their programs. One approach is to have information dump into text file. This solution is OK but I really hate switching back and forth between the host application and the text file. So I decided to write a program which acts as a text terminal to receive text message from robot.

The root of problem

The problem is how can I send information across application domain or process ?

Yes, the answer is to use .NET Remoting Object.

I will have one object setup at my "Terminal" application and let the robot get this object and call "PushMessage(string)" method to add a message. After a message is pushed, the MessageReceived will be raised. And the UI will be updated.

This results as a program in the screen shot in the left.

Useful links

I studied how to implement .NET Remoting from the two web pages below :

http://www.developer.com/net/net/article.php/2201701 - This covers the basics of .NET Remoting Object. What is it ? And when to use it.

http://www.codeproject.com/csharp/RemotingChatSample.asp - This is the working sample for application using .NET Remoting Object.