Codelog

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

Archive for the ‘C#’ tag

System Events in C#

without comments

Recently I was trying to develop a caneldar application in C#. I had a very big problem dealing with it. How do I change my calendar’s date when the user goes to control panel and changes the date manually ?? This was the problem and it can be delt very easily in C#. While googling, I got multiple solutions. Some of them are really cool, while some other are damn easy. One such way is to handle System Events.

SystemEvents are the events raised by our operating system (Win in my case — not tested in Linux using Mono, will update once it is tested in mono) when something happens to its configurations, like a change in DateTime, change in DisplaySettings, SwitchUser, etc. You can subscribe to these events and then write the handlers that will take care of the business process you wanna perform when such events are raised. To use a SystemEvents in your application, follow the steps. Its simple,

  • Subscribe for the event that you are interested in, example, TimeChanged. The SystemEvents are under the namespace, Microsoft.Win32  

    SystemEvents.TimeChanged += new EventHandler(TimeChangedHandler); 

  • Write your logic in this handler (define the handler)

    private void TimeChangedHandler(object theSender, EventArgs theArgs)
    {
      MessageBox.Show("time has been altered manually by the user");
      //Check the current date/time and update accordingly
  • Thats it. You have successfully handled a system event

 There are loads of system events like,

  • PowerModeChanged — When the power mode (suspend / resume) happens
  • SessionSwitch — When the user switches loggs (in to / out of) the system
  • DisplaySettingChanged — When the display properties (resolution) changes
  • Try to play with the event args to get more information about these events.
     

Written by sudarsanyes

November 21st, 2008 at 8:35 am

DeskToDo - ToDo application in C#

with one comment

Recently one of my friend, praseodeveloper(AKA Pradeep) asked me to get him my todo manager. But it was kinda messy. So I thought of making a very small todo manager for him - DeskToDo. The first version of this application was developed in 2 hours since I didn’t have time, with absolutely no (rather some) design patterns in mind. After months I thought of revisiting that application. So now we have the second version of it. Kind of stable, I thought of sharing it with you. The application (source) can be modified by anyone and you can use it for free ;-) if you really find it useful.

Download DeskToDo Source

Features

  • Add a new task
  • Delete a task
  • Prioritise a task
  • Give it some dead line
  • Handy UI (I don’t know what you think about it)
  • Color coded tasks so that you get to know about the priorities easily

So whats the big deal. It still dosen’t have,

  • EDITING A TASK
  • YOU CAN’T SORT TASKS ON ANY BASIS

I know that you are really a great programmer. Its really easy. If you are a developer try to do it, if not, send me an email. I shall help you.

Notes, Assumptions, blah blah about the application

Let me give you a brief note on how things are done internally. the application has got three main classes.

  • Task.cs. Represents the task that you wanna do.
  • TaskManager.cs. This guy actually manages the tasks. He holds loads of taks with him. You can add or delete any tasks from him at any time
  • Form1.cs (sorry about that name. I told you rite ?? There was no time). He actually represents the presentation part of the application
  • All your tasks are serialised in to a file. So as long as the file exists, you can see your tasks

Comming back to assumptions, there are not much of it. But ofcourse there is one. The order of tasks in the TaskManager and the order of tasks in the Presentation Control should be the same.

If you wanna develop

  • Download the application’s source from here
  • Open visual studio
  • Click on File -> New -> Project from existing codes
  • Select C# language and Window Application
  • Click on Finish
  • Thats it

If you wanna use it, you need to build it first. To build it,

  • Open your Visual Studio Command Prompt
  • Navigate to the source (downloaded folder)
  • Type csc /recurse:*.cs /out:DeskToDo.exe
  • There won’t be any errors. On second thought, you can refer building a C# application to troubleshoot

Thats it. As simple as that. Throw in your feedbacks about the application, we are ready considering those.

Written by sudarsanyes

November 7th, 2008 at 4:37 pm

Posted in C#, Tips 'n' Tricks

Tagged with , ,

Tracing in C#

with one comment

Recently I went thru’ a article that talks about Conditional Debugging in C#. Eager to try it out, I was researching it. I was really surprised to see the out comes. So I thought of sharing all those things with you. As the above has link already talked about conditional debugging, lets start with tracing.

In C#, there are loads of ways to trace the execution. All of them can be acheived using the object Trace. You can trace the execution and the errors that are thrown by the application in to a,

Console

Here what ever you trace will be written to the Console (command prompt), if you run the application from a command prompt. To accomplish this we need to do the following,

  • Create an object of the ConsoleTraceListener ConsoleTraceListener aConsoleTraceListener = new ConsoleTraceListener();  //Creating an object for tracing
  • In the place where you wanna trace something, add the following statementaConsoleTraceListener.WriteLine("<the message you wish to trace on executing the current method>");  //Will write a trace line in to the console

This will work only if you are running a console application or a window application from the console (You can also change the properties of a window application to console application and then run it so that it automatically runs from the console even if you press F5 from Visual Studio).

EventViewer

There is a utility called EventViewer that comes with windows. Try typing eventvwr in Run applications. You will get a dialog that has loads of events and their logs. You can create an object of EventLogTraceListener to log the events out there. Lets see how we do it.

  • Create an object of the EventLogTraceListenerEventLogTraceListener aEventLogTraceListener = new EventLogTraceListener("Foo");  //Creating an object of the trace viewer with the source name as Foo
  • In the place where you wanna trace something, add the following statementaEventLogTraceListener.WriteLine("<the message you wish to trace on executing the current method>");  //Will write a trace line in to the event viewer

 

Additional options

The above methods allows you to trace some messages. In addition if you need to trace the ThreadID, ProcessID, TimeStamp or even CallStack, you can use the TraceEventCache. This class allows one to get the above mentioned properties of a event. Try adding the following snippet to your code.

TraceEventCache aTraceEventCache = new TraceEventCahce();  //New trace cache object that will hold additional info about the event

aConsoleTraceListener.TraceOutputOptions = TraceOptions.TimeStamp | TraceOptions.ProcessId;  //Will add these details to the log

The TraceEvent method will log additional details like TimeStamp, ProcessID, etc., to the message that is being logged. These are some of the methods to trace the flow or execution of a program. These are some of the easy ways to find the bugs(if any) in our application even if it has been released to the customers irrespective of the nature of the build (debug or release).

 

aConsoleTraceListener.TraceEvent(aTraceEventCache, “Foo”, TraceEventtype.Information, 0, “Method __name___ has been executed”);  //Will log the trace message in to the console window

 

Update

To log to a text stream you can use the TextWriterTraceListener object. You can also use the static class EventLog to trace messages to the EventViewer.

Written by sudarsanyes

November 4th, 2008 at 2:14 pm

Yield statements in C#

with 2 comments

Yield statements are new to C# 2.0. It largely resembles python’s yield.

Its used to iterate through a set of results returned by a method, but the biggest difference being that the yield statements can maintain the state of that method.

 

It may be a bit confusing, yet pretty simple. Take a look at the following snippet.

Say, if you wanna print numbers between 0 and 50. What will you do ??

for(int i = 1; i < 50 ; i++)
{
  Console.Write(i);  //Just prints i in the screen
}

Really a child’s play. Now if you wanna return the intermediary values to the caller, then ??

Yield assists you in this scenario. Here is how you can do it.

private IEnumerable<int> GetNumbersBetween(int theStart, int theEnd)  //Returns an IEnumerable<int> object that allows iteration using foreach
{
  theStart++;
  while(theStart < theEnd)
  {
    yield return theStart;  //statement that returns the intermediary values
  }


In the main method, you can use,

foreach(integer aNumber in GetNumbersBetween(0, 50))  //iteration is possible because GetNumbersBetween returns IEnumerable<int>
{
  Console.Write(aNumber);  //prints the number
}

You might wonder how the above snippet works. Lets dive in to it. 

First iteration – Here GetNumbersBetween(1,50) will be executed. Unlike the ordinary methods, the GetNumbersBetween() won’t execute / exhaust the entire while loop. As there is a yield statement, it returns 1

Second iteration – Again the GetNumbersBetween(1, 50) will be called. Now since the method returns a yield value, it remembers the previous state. Now internally the value of theStart will be 2. So it returns 2 this time

Third iteration – Again the same method will be called, as usual, the value of theStart will be 3. So it returns 3 this time. This goes until theStart+1 = theEnd

This is how it works. Another confusing snippet for you. If you feel really bad, skip it.

while(true)
{
  yield return 1;  //Not an infinite loop
}

The above is not an infinite loop as this loop is totally controlled by the caller’s loop.

Things that you need to take care while using yield statements

  • Yield can appear only inside a loop (obvious !!) — Check the comments to know more on this 
  • Parameters cannot be ref or out
  • Don’t use yield inside catch or finally blocks (can’t think of a sample problem that covers this scenario)

Written by sudarsanyes

November 3rd, 2008 at 10:12 am

Rubber band selection rectangle in C#

without comments

Rubber band selection rectangle -- This is how it looks like finally

You might have selected a couple of icons from your desktop by dragging the left mouse button and my drawing a rectangle over the icons. Such rectangles are called Rubber band selection rectangles. A rubber band selection is a selection rectangle that will track down the mouse pointer when the left mouse button is held.

In this artilce, we will try to draw those kina rectangles in C#. The article covers only the drawing part.

Lets get started.

Here are the terms used in the explanation,
I will be helping you draw the rectangle using four connected lines.

  • Origin point (O) to denote the place from which the user has started to draw the rectangle
  • Intermediate point (I) to refer to the incremental points over which the user has moved his mouse pointer
  • Nearer – close to the mouse pointer
  • Farther – distant from the mouse pointer
  • Ox, Oy referes to the Origin’s X and Origin’s Y

Read the rest of this entry »

Written by sudarsanyes

October 31st, 2008 at 2:03 pm

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

Tagged with , , ,

TreeView Control in C#

without comments

ListViewControl

ListViewControl

The folder list pane that you see in a Windows Explorer is called TreeViewControl. In C#, its really easy to use these controls. There are loads of facilities provided by this control. Some of them are really great. In this post, I will try to explain some of the basics of this control.

Adding a TreeViewControl

To add a TreeView control, just double click on the TreeView control from the Tools window or add the snippet,

TreeView myTreeView = new TreeView();
this.Controls.Add(myTreeView);  //adding the control to the presentation form

Adding a Node

Nodes are the items that you can find in a tree view control. This is the tricky part. You can have a node, that has another node, that has one more node, and so on. Just like the files and folders inside another folder. To add a node, the control has got, Nodes.Add() method. This is a overloaded method and it has loads of overloaded parameters. For example, you can have a string as a parameter to this method to add a node.

myTreeView.Nodes.Add("foo");  //will add a new node with the text foo in it
Read the rest of this entry »

Written by sudarsanyes

October 29th, 2008 at 8:37 am

Posted in C#, Controls, UI

Tagged with , ,

Glossy buttons in c#

without comments

Is there any way to create glossy, eye candy buttons in c# ?? Before starting off, we need to know what makes a thing glossy. There are two factors,

  • Color selection
  • Linear gradient fill over the control

Ok. Now lets see the implementation. For colors, we have Color class, but for Lineargradient ?? Yeah, we do have a LinearGradientBrush in c#.

Note: The task of making a button glossy will be acheived in the following order,

  • Drawing the border
  • Filling the lower rectangle with a solid color
  • Filling the upper rectangle with a linear gradient
  1. Include a button to the project (myGlossyButton)
  2. Change the FlatStyle of the myGlossyButton to Flat

    myGlossyButton.FlatStyle = FlatStyle.Flat;
  3. Handle the paint event of this button. Lets name the handler method as GlossyPainter
  4. In the GlossyPainter, first we need to give our button a border [task:1]. Say White border.

    e.Graphics.DrawRectangle(Pens.White, new Rectangle(0, 0, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1));  //1 is subtracted from the size to make the border completely visible
  5. Next up, we need to fill the rectangle with some base color [task:2]. This time, we will fill the bottom half with some solid color and the upper half with some gradient color.

    SolidBrush aBaseSolidbrush = new SolidBrush(Color.FromArgb(150, Color.YellowGreen));  //FromArgb allows you to even specify the opacity of the colore.Graphics.FillRectangle(aBaseSolidBrush,  new Rectangle(2, (e.ClipRectangle.Height - 4) / 2, e.ClipRectangle.Width - 4, e.ClipRectangle.Height - 4));  //4 is subtracted just to leave a blank space between the border and the button     

  6. Filling the upper part of the button with the linear gradient color [task:3]

    LinearGradientBrush aLineargradientBrush = new LinearGradientBrush(new Rectangle(2, 2, e.ClipRectangle.Width - 4, (e.ClipRectangle.Height - 4) / 2), Color.FromArgb(255, Color.White), Color.FromArgb(100, aColor), 90);  //Specifying how big the linear gradient should be and in what direction the gradient should appear

    e.Graphics.FillRectangle(aLinearGradientBrush, new Rectangle(2, 2, e.ClipRectangle.Width - 4, (e.ClipRectangle.Height - 4) / 2));  //Filling the upperpart of the button
  7. Run the application, you should be seeing a glossy button

This is one of the ways to make a control look glossy. There are many ways to acheive this. If you know a really simple way share it with us.

Written by sudarsanyes

October 15th, 2008 at 9:34 am

Asynchronous method calls in c# [part 4] — Call back

without comments

Atlast, callback. Now, whats call back?? Remember part 1 of this post??

Callback is the techinique of executing a method automatically, when the asynchronous call has been finished.

Lets see how we can do this.

For this tutorial, we need to change the functionalities a bit. The following changes needs to be done.

RemoteObject.cs file

The signature of the method, GetMessage() should be changed in such a way that it takes a argument and gives out an out parameter.

public void GetMessage(string theName, out string theMesssage)  //The method returns an out parameter instead of a message box.
//
 MessageBox will be shown in the form1.cs file
{
  Thread.Sleep(10000);
  theMessage = "Hello " + thename;
}


Form1.cs file

The signature of the AsyncCaller delegated should be changed to,

private delegate void AsyncCaller(string theName, out string theMessage);  //Now the method returns an out parameter

The way the BeginInvoke() is called needs to be altered,

aAsyncCaller.BeginInvoke("foo", myMessage, new AsyncCallback(ShowMessage), null);  //"foo" is the parameter, myMessage is a class level field variable for out parameter and AsyncCallback(...) is the way in which the csc will be notified with the method that it should call once the asynchronous method has completed its execution

Addition of a new method, ShowMessage that takes an IAsyncResult as its parameter

private void ShowMessage(IAsyncResult theAsyncResult)  //This is the callback method and will show the message box with the out parameter's value
{
  AsyncResult aAsyncResult = theAsyncResult as AsyncResult;  //Creating a AsyncResult object from the interface parameter. This paramater actually holds out intended result
  AsyncCaller aAsyncCaller = aAsyncRsult.AsyncDelegate;  //Getting the delegate that was used to call the method asynchronously
  aAsyncCaller.EndInvoke(out myMessage, aAsyncResult);  //Getting the callback message from the delegate
  MessageBox.Show(myMessage);  //Shows the message box to the user with the message that he has got from the RemoteObject.cs file
}

Insight of BeginInvoke() and ShowMessage()

  • As you have noticed the BeginInvoke() method has a big change. the first parameter, “foo” is the parameter for the GetMessage() method, the second parameter is the out parameter, while the third parameter new AsyncCallback(ShowMessage) is the way by which you are telling the csc (c# compiler) that ShowMessage is the method that will be called after the execution of GetMessage.  The constructor  of the AsyncCallback class takes the callback method name.
  • ShowMessage(IAsyncResult) is a new method. It takes an IAsyncResult parameter. IAsyncResult is an interface. The object that it receives as parameter will hold all the details about the asychronous call. It has the result of the call, the delegate that was used to make the call and many more.
  • We actually get the result of the call using the delegate that was used to make the call. So the first statement in this method would be the typecasting of the interface object to AsyncResult object.
  • Secondly, we need to get the delegate that was used to make the asynchronous call (it will be AsyncCaller). Thats what we have done in the second statement.
  • Third statement ends the call by calling the EndInvoke() to get the result of the GetMessage().

This is a simple method of implementing callbacks in c#. Hope you understood. There are loads of other ways in whihc you can accomplish this. I will try to post the alternative ways very soon.

Written by sudarsanyes

October 3rd, 2008 at 9:58 am

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

Tagged with , , ,

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 , , ,