Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Asynchronous method calls in c# [part 3] — using parameters in calls

without comments

Sorry for the delay in part 3. Without wasting time, lets get strated. Till part 2, we were using asynchronous calls with out any parameters. Now in this one, we will try to pass some parameters to the GetMessage method. Here also we are gonne consider the same example. If you haven’t read the part 2 of this article, go thru’ it before beginning this one.

Modifications to be done in GetMessage method

In the RemoteObject.cs file, modify the signature of the GetMessage class by making it accepting a string parameter. Consider that the GetMessage method now looks some thing like this,

public void GetMessage(string theName)
{
  MessageBox.Show(theName);
}

Modifications to be done in the Form1.cs file

In the Form1.cs file, there are a couple of modofications to be done. First, we need to change the delegate’s signature.

private delegate void AsyncCaller(string  theName);  //Now the delegate acceps a parameter

Also in the button’s click event, the way we invoke the delegate method needs to be modified.

Instead of just calling aAsyncCaller.BeginInvoke(null, null); this time, we will call it using

aAsyncCaller.BeginInvoke("foo", null, null);  //"foo" is the parameter to the GetMessage() method

Thats it. you have made an async call passing some arguments. Try to run it. Clicking the button should give you a message box with the string “foo“.

Next up, Callbacks.

Still confused with null, null in the BeginInvoke() method call??

You will get the answer in my next post.

Written by sudarsanyes

October 3rd, 2008 at 9:04 am

Posted in C#, Tips 'n' Tricks, UI

Tagged with , , ,

Asynchronous method calls in c# [part 2]

with 2 comments

Hmm. Lets get stared with the async call implementation in c#. The concept can be better understood using window based application (GUI application). Let us first create a new window project in c#. Follow me,

Note: I have attached the project with this, if you are not comfortable with that, then create a new one by following these steps.

  • Click File > New > Project and select WindowApplication. Give it some name (say AsyncCalls)
  • Now our idea is to have another class with some method that takes a long time for execution. For that, add a new class (Right click on the Project from solution explorer > Add > Class. Give it some name, like RemoteObject.cs)
  • Implement a public method in this class. Lets name it GetTheMessage() with no params, no return type (for simplicity) and just add a MessageBox.Show(”foobarbaz”) statement with some string to show. As we have mentioned earlier, this method should take some time for execution. So lets add a Thread.Sleep(10000); statement before the MessageBox.Show() statement. Thread.Sleep(10000); will just give a delay of 10 seconds during the runtime.
  • Coming back to the main application (your form), create an object of the RemoteObject class (say myRemoteObject).
  • Add two buttons to the form. One for synchronous call and the other for the asynchgronous call.
  • In the synchronous call button clicked event, call the GetTheMessage() method the traditional way, myRemoteObject.GetTheMessage();
  • In the asynchronous call button clicked event, we will call the GetTheMessage() method asynchronous way. For this, we need a new delegate. So lets do it.
  • Create a new delegate in the Form1.cs file. Lets name it AsyncCaller.


public delegate void AsyncCaller();  //Delegate for the async calling

  • In the button clicked event create an object of the delegate class for the GetTheMessage() target.

AsyncCaller aAsyncCaller = new AsyncCaller(myRemoteObject.GetTheMessage());  //Ususal way of initialising a delegate method

  • Lets invoke this delegate (not using .Invoke() method) using .BeginInvoke(null, null).

aAsyncCaller.BeginInvoke(null, null);  //Don't care about the null and null. We will come back to that later

  • Thats it. You have made an asynchronous call to the GetTheMessage() method.

Now, to test the asynchronous calls, lets run the application. After running click on the sync call button and try to drag the form using the title bar. It won’t move. The UI will be frozen until the execution of the GetTheMethod is completed. Now after seeing the message, click on the async call button and try to move the form. It will move, because the method call has been spawned to another thread. Cool, isn’t it. Lets understand the code snippet for the async calls.

  • First async calls needs to be made through a delegate object. Thats why we created a delegate called AsyncCaller and a delegate method called aAsyncCaller.
  • The delegate’s signature must be similar to the target’s signature (usual thingy)
  • The invocation of the delegate method should be done using the BeginInvoke(); method, as it calls the method asynchronously. It automatyically creates threads and handles it. You are free from those activities.
  • The BeginInvoke() method takes two parameters. CallBack and AsyncResult. Over here. WE are not concerned about the return values or the parameters of the GetTheMessage(); function. So we have null, null over there.

Note: Try to replace the MessageBox.Show(); with some other UI related statements. You should be getting an exception. We will deal about that later. In my next post, I will explain the ways to pass arguments to these asynchronous method calls.

Written by sudarsanyes

September 21st, 2008 at 11:04 am

Posted in C#, Tips 'n' Tricks, UI

Tagged with , , ,

Explain recursion to your kids

with 2 comments

Today saw this explanation of recursion on proggit (direct link). This is the best way to teach recursion for kids (3 to 5 years).

A child couldn't sleep, so her mother told her a story about a little frog,
  who couldn't sleep, so the frog's mother told her a story about a little bear,
    who couldn't sleep, so the bear's mother told her a story about a little weasel...
      who fell asleep.
    ...and the little bear fell asleep;
  ...and the little frog fell asleep;
...and the child fell asleep.

One thing I like best about reddit is the comments.

Written by cnu

September 19th, 2008 at 10:30 am

Asynchronous method calls in c# [part 1]

with 2 comments

Planning to write something interesting, yet very useful, I thought of writing about asynchronous calls. Before that, first we need to know the two categories of method calls.

Note:This post will be partioned in to two. This one will be just an introduction to the asynchronous calls.

There are two methods of method calls (crappy sentence nah ??)

Synchronous method call

This is the traditional method call, calling the method directly from another method. What happens in here is the control, as soon as it sees a method call, will jump to the target and start to execute that one. Only after finishing that one will come bak to the originator (or the caller). For example,

ln: 100 private void Foo()
ln: 101 {
ln: 102   //some crappy logics
ln: 103   Bar();
ln: 104 }
ln: 105  private void Bar()
ln: 106 {
ln: 107   //again some logics are done in here
ln: 108 }

In the above snippet, when the control sees the call Bar(); (ln: 103), will directly jump to the Bar() function (ln: 105) and start to execute the method. After the completion of this will return to the caller (ln: 104).

This is the normal method call. Suppose if the Bar() method (ln: 105) has too many logics in it and if it takes a long time to execute, then the control will come to the caller (ln. 104) only after successfully finishing all those logics. This may sound obvious, but not soo good when it comes to the GUI programming.

Considering that the Foo() method (ln: 100) is called on a button clicked event, then the UI will remain frozen until the control finishes executing Foo() method (there by executing the Bar() function). This freezing of the UI can be (rather should be) avoided by using asynchronous calls.

Asynchronous calls

Asynchronous calls are like event. They are of “fire and forget” type you can say. Considering the above quoted example, the Foo() method (ln: 100) now will make an asynchronous call to the Bar() method (ln: 105). Programatical explanation will be given in the next post. The charm for such a method call is that, as soon as the Foo() method calls Bar() method, asynchronously, the control still remains in Foo() and the Bar() method will be running in another thread. So in the GUI applications there won’t be any freezing of UI if such calls are made. Yeah, its a great feature.

Also I should talk about call backs while explaining asynchronous calls. Suppose that you wanna update some information in the UI when a button is clicked and for which, it may take a long time, now what you do is, make an asynchronous call. But the question is “How will you know when the asynchronous call has been completed ??” The processing of making the application to notify you on finishing an asynchronous call is called callback. All these will be explained more clearly in the next post.

Written by sudarsanyes

September 16th, 2008 at 6:07 pm

Password Encryption Using SHA1 (MD5) - JAVA

without comments

Here’s is a program where the password stored in the code is encoded by SHA1, It accepts the input from user computes the SHA1 digest and check if it is the same as the set Password. I have set the Password to - password


import java.io.Console;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1Pwd {

public static void main(String[] args) {

char[] passwordChar = null;
Console console = System.console();
MessageDigest md = null;
String encodedSetPwdInHexString = “5:BA:A6:1E:4C:9B:93:F3:F0:68:22:50:B6:CF:83:31:B7:EE:68:FD:8″;

//digest value of the string - password. change it to your required password digest.

try {

md = MessageDigest.getInstance(”SHA1″); // can be replaced with MD5
// SHA1 has fewer collisions in comparison with MD5.

Read the rest of this entry »

Written by danish

September 13th, 2008 at 9:53 am

Posted in Java

Tagged with , , ,

Simple Password Encryption Technique - Java

without comments

Here’s a simple Password Encryption technique using hashCode(), It is just a basic style that does not expose your password in the source code. The Password I have set is - password

import java.io.Console;

public class pwd {

public static void main(String[] args) {

char[] passwordChar = null;

Console console = System.console();

int hashInt = 1216985755;                     // value of the string “password”

try {

passwordChar = console.readPassword(”Enter Password : “);

} catch (NullPointerException e) {

System.out.println(”You Might Be Running The Program From An IDE , Try In Terminal”);

System.exit(1);

}

String passwordString = new String(passwordChar);

System.out.println(”The Hash value of the Entered String : ”

+ passwordString.hashCode());

System.out.println(”The Hash Value Required : ” + hashInt);

if (passwordString.hashCode() != hashInt)   {                     // hash coded check

System.out.println(”Wrong password”);

System.exit(2);

}

System.out.println(”Correct Password”);

}

}

There are better ways to do it than hashcode() method which is fragile, md5 or sha1 would be better techniques. The ONE TIME PADDING or encrypting the password using a secret key and storing it, but just for the program access I dont think it is that necessary, but the latter techniques will be useful while transmitting messages.

Written by danish

September 13th, 2008 at 8:55 am

Posted in Java

Tagged with , ,

Custom shaped controls in C# — using GraphicsPath

with 2 comments

Have you ever thought of having a circular button, triangular form, amoebic labels ?? Doing all these in C# is really simple and cool. All you need to do is, use the Region property of the control to change the shape. Lets try to change the shape of a button to ellipse.

  • Create a new button the usual way.

System.Windows.Forms.Button myButton = new System.Windows.Forms.Button();

  • Change the color of the button to distinguish it from the form’s background.

myButton.BackColor = Color.Blue; //Lets change the color

  • Increase the size of the button.

myButton.Size = new Size(100, 100);

  • Create a GraphicsPath object to define a custom path which will be associated with the button’s region in the next step. There are loads of methods like AddEllipse(). Try AddPloygon() which takes a set of points.

System.Drawing.Drawing2D.GraphicsPath aGraphicsPath = new System.Drawing.Drawing2D.GraphicsPath(); //The GraphicsPath class allows us to define custom paths

myGraphicsPath.AddEllipse(5, 5, 90, 90); //A big circle

  • Associate the GraphicsPath with the button’s Region property.

myButton.Region = new Region(aGraphicsPath); //Associating the path made by us to the button's region

Run the application and see for your self, a rounded button. Cool, isn’t it ? Play with GraphicsPath to create custom shaped controls.

Written by sudarsanyes

September 6th, 2008 at 10:19 am

Posted in C#, Controls, UI

Tagged with , ,

Visual studio shortcuts

without comments

Its always time consuming to use all the features provided by an editor while coding (if you don;t know the hotkeys). For example, Visual Studio. When you are using a big editor like Visual Studio, you will have soo many functionalities to use while you code. Most of the time, these features goes unnoticed when you can’t find the shortcuts for those. Also the shortcuts will be too big to remember. Below mentioned ones are really handy. I will be talking from the C# point of view. So I really don’t know whether all these will work for all the languages. Read the rest of this entry »

Written by sudarsanyes

September 6th, 2008 at 9:38 am

virtualenv - Sandboxed python environments

without comments

This problem has haunted me many times when I want to work on two frameworks (Turbogears and Pylons) and there are some packages which interfere with each other. Having both installed in /usr/lib/python-2.5/site-packages is a nightmare. You won’t know what causes your nosetests to fail, you will have to comment out the other dirty package and try again. Also some packages may be upgraded which will cause some problem in some place in your application.

All this can be easily solved by using the virtualenv package in python. What it does is - create isolated python working environments. So that packages you install in one environment doesn’t interfere with the other. Also if you can’t install packages in the global site-packages, this will be really helpful.

You just have to easy_install virtualenv and it gets installed as a executable. If you can’t easy_install, there is a single python script (virtualenv.py) which can be used instead.

You can create your sandbox with the command $ virtualenv --no-site-packages env. The –no-site-packages option make sure that the global site-packages doesn’t inherit any packages from the global site-packages.

It will create a directory ‘env’ in your current directory. The bin folder inside this has its own python executable and a seperate site-packages in the lib directory. It also has easy_install installed in the bin.

Now you can install whatever package you want by typing $ env/bin/easy_install packagename

All your commands need to be prefixed with the env/bin/ path else it will use the wrong python version. But you can avoid typing the long commands by using the activate script bundled with the bin folder.

On *nix systems, you have to $ source bin/activate and on a windows machine > \path\to\env\bin\activate.bat. After you are finished with it, you just have to type deactivate and you get back to the old shell.

Most of the times, it would work perfectly, but sometimes the shell will cache the path of the commands. So, it is always advisable to check whether the path is set correctly by typing which python.

Now this solves my problem of mismatched and wrong packages and can start working in Pylons.

Written by cnu

August 28th, 2008 at 6:25 pm

Posted in Python

Tagged with ,

Password Masking in CLI using Java

with one comment

Java CLI password masking was appended to Java 6. Wonder why it took them so long to add it. It comes with the Console Class. This class has several features for the ones developing CLI programs. I always hated the method to mask the letters with another thread.

Here is a sample,

import java.io.Console;

class pass {

public static void main (String[] args) {

    char passwd[];
    Console cons = System.console();
    passwd = cons.readPassword(" Enter Your Password : ");
    System.out.println("The Password is : " +passwd);
}
}

Here is the Documentation Link http://java.sun.com/javase/6/docs/api/java/io/Console.html.

In my next post I’ll describe a simple Encryption and Decryption of this password.

Written by danish

August 26th, 2008 at 4:17 pm

Posted in Java

Tagged with , ,