Archive

Archive for the ‘.NET’ Category

How to Programmatically Set Thread Name in Debugger Window(native) ?

March 9th, 2009 Sarath Comments

Most of windows Debuggers supports thread names. This is really helpful to identify the purpose of threads especially when you’re having multiple threads in your application. In Visual Studio  you can see the details of threads including it’s name in the “Threads” window. [updated types 9.15 AM 11-03-2008 IST]

image

There are no direction functions to set the thread names for a thread. But it’s possible to implement by exploiting exception handling mechanism of a debugger. The debugger will get the first chance to handle the exception when an application is being debugged. Using this concept we will be explicitly raising an exception with parameters which specifies the thread name and other information. The particular exception will be specially handled by debugger and thus it will update the name of corresponding thread.

When application running without debugger, raising exceptions lead to application crash. So we’ve to enclose the RaiseException code inside a try-except block.

Here’s the sample snippet. This has been specified in MSDN directly.

[sourcecode language='cpp']
#define MS_VC_EXCEPTION 0×406D1388

#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0×1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)

void SetThreadName( DWORD dwThreadID, char* threadName)
{
THREADNAME_INFO info;
info.dwType = 0×1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;

__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
// printf(”Not under debugger. Swallowing exception”);
}
}
[/sourcecode]

The function can be used either by specifying the thread ID of the particular thread to be named or passing -1 as thread ID will set the name for the current thread which is calling the function. The demonstration of inside and external calling is demonstrated below. If same thread function is used to create multiple threads, then setting name from external thread or by getting current thread ID is better than passing -1 as thread ID.

[sourcecode language='cpp']
DWORD WINAPI Thread2(LPVOID)
{
// Setting for current thread
SetThreadName( -1, “DisplayThread” );
return 0;
}

DWORD WINAPI Thread1(LPVOID)
{
SetThreadName( -1, “Worker” );
return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
DWORD dwID;
CreateThread( 0,0,Thread1, 0,0,&dwID);
// Setting using thread ID.
SetThreadName(dwID,”External1″);
CreateThread( 0,0,Thread2, 0,0,&dwID);
// Setting using thread ID.
SetThreadName(dwID,”External2″);
// Creating new thread using Thread2 function again
HANDLE h = CreateThread( 0,0,Thread2, 0,0,&dwID);
// Setting using thread ID.
SetThreadName(dwID,”External3″);

WaitForSingleObject( h, INFINITE );
return 0;
}
[/sourcecode]

MSDN has also specified how to set thread name in Managed code

Categories: .NET, C++, Debugging, Tips, Visual Studio Tags:

How to programmatically create your tiny URL?

March 2nd, 2009 Sarath Comments

If you’re active in social networks especially twitter and newsgroups, you might have seen lot of short URLs which encapsulates and redirect to actual long and cumbersome URLs. There are many websites which provides URL Redirection services like tinyurl.com , bit.ly and is.gd etc. Yeap, in programmer’s word, I will take courage to compare TinyURs as C/C++ macros as a simple single name replaces a bunch of statements.

Consider, twitter, each “tweet” is limited to 140 characters (length of single SMS) and if the user enables device updates, then he/she can read the updates through phone. Often the link you supposed to share either too length or takes more letters which can be used for your message.

http://sarathc.wordpress.com/2007/01/31/how-to-trim-leading-or-trailing-spaces-of-string-in-c/

The above URL is a link to my most active blog post. If this got converted using tinyurl.com, it may appear as http://tinyurl.com/bg487k

So you saved lot of spaces by putting this short url. Now let’s see how to write a simple C# function to shorten url. Each provides having different kind formats to specify actual URL and get the converted URL back. Most of the sites will be listed this as their API. Here I listed 3 of the most famous provider’s format.

Is.gd http://is.gd/api.php?longurl={your_url}
Bit.ly http://bit.ly/api?url={your_url}
Tinyurl http://tinyurl.com/api-create.php?url={your_url}

.NET framework provides HttpWebRequest class to connect to make a web request to the desired website. So our responsibility is to send a formatted URL to desired website.

See the code below for coversion. I’ve done only primary error handling and supposed to deal with http:// and https:// urls

[sourcecode language='csharp']
using System;
using System.IO;
using System.Net;
using System.Text;

namespace ShortURL
{
enum ShortURLProvider
{
Bitly,
Isgd,
Tinyurl,
}

class ConvertURL
{
public static string ShortenURL(string strUrl, ShortURLProvider eService)
{
// return empty strings if not valid
if( !IsValidURL( strUrl ))
{
return “”;
}

string requestUrl = string.Format(GetRequestTemplate(eService), strUrl);
WebRequest request = HttpWebRequest.Create(requestUrl);
request.Proxy = null;
string strResult = null;
try
{
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.ASCII);
strResult = reader.ReadToEnd();
if( !IsValidURL(strResult))
{
WebException w = new WebException(strResult);

throw w;
}
}
}
catch( Exception )
{
return strUrl; // eat it and return original url
}

// if converted is longer than original, return original
if ( strResult.Length > strUrl.Length)
strResult = strUrl;

return strResult;
}

/* Validate URL */
public static bool IsValidURL(string strurl)
{
// Validate the URL
if (true == strurl.ToLower().StartsWith(”http://”) || true == strurl.StartsWith(”https://”))
{
return true;
}
return false;
}

/* Request template for URL */
private static string GetRequestTemplate(ShortURLProvider eService)
{
string strRequest = null;
switch (eService)
{
case ShortURLProvider.Isgd:
strRequest = “http://is.gd/api.php?longurl={0}”;
break;
case ShortURLProvider.Bitly:
strRequest = “http://bit.ly/api?url={0}”; ;
break;
case ShortURLProvider.Tinyurl:
strRequest = “http://tinyurl.com/api-create.php?url={0}”;
break;
default:
break;
}
return strRequest;
}
}
}
[/sourcecode]

Here’s how client use the class.

[sourcecode language='csharp']
string strShortURL = ConvertURL.ShortenURL(textBoxOrgURL.Text, eProvider);
[/sourcecode]

Categories: .NET, C Sharp, Code, Tips Tags: , ,

Jagged Array in C#

June 4th, 2008 Sarath Comments

Jagged array represents array of arrays where each array can have arbitrary number of elements. It’s the similar concept of double pointers in C.

Jagged array provides flexible services for manipulating and controlling data. In the case of C pointers will have to do the manual book keeping for better control over the bounds of data. We can have the same implementation by using dequeue/vector container classes in C++. But still we can’t say they’re representing array. Rather than they’re containers and provides common “container” interfaces.

You can check the number of facilities available for jagged arrays and arrays from MSDN. Also you will get some other good examples

How to use Jagged Arrays – Listing 1

// constructing jagged array

int[][] myJaggedArray = new int[5][];

for (int i = 0; i < myJaggedArray.Length; i++)

{

myJaggedArray[i] = new int[i + 1];

}

// iterating each arrays

for (int i = 0; i < myJaggedArray.Length; i++)

{

// iterating each elements in an array

for (int j = 0; j < myJaggedArray[i].Length; j++)

{

Console.Write( “{0} “, myJaggedArray[i][j]);

}

Console.WriteLine(” – {0} elements”, myJaggedArray[i].Length);

}

How to use Jagged Arrays – Listing 1

int[][,] jaggedArray4 = new int[3][,]

{

new int[,] { {1,3}, {5,7} },

new int[,] { {0,2}, {4,6}, {8,10} },

new int[,] { {11,22}, {99,88}, {0,9} }};

Categories: .NET, C Sharp, Code Tags: , ,

Parameter Modifiers in C#

May 19th, 2008 Sarath Comments

In C++, we can pass by value, reference (pointers are also there) when we need to pass some data to a C++ function.

In the case of C# also we’ve the same facilities.(Pointers are still there). They’re named as ref, out and params.

Let’s take a look at ref keyword. As the name indicates, “ref” stands for reference. If the formal parameter (ref variable) modified inside the function, it will be also get reflected in the actually parameter. (Same as C++ reference). In C#, the object must be initialized before passing as a reference. The sytanx is clean in C# because we’re specifying the parameter modifier at both function definition and at the time of usage.

[sourcecode language='C#']
static void Foo(ref int nData)
{
nData++;
}
static void Main(string[] args)
{
int x = 10;
Foo(ref x);
int y;
Foo(ref y); // ERROR: Uninitialized variables
}
[/sourcecode]
Let’s take a look at out keyword. Out behaves similar to ref keyword but there’s no need to initialize the object passing to function. Even the object is initialized, inside the function, we’ve to re-initialize object. We can’t exclude this step.

In C++, there’s no constraint to use the reference variable inside the function. We can omit with/ without conditional statements. But in C# if you use out keyword, you will have to initialize the object inside the calling function. If you want the same behavior of C++ reference, it’s better to use ref keyword.

Ref and out keywords are same at the compilation time but behaves different at run time. So that you can’t overload “ref” and “out” with similar function signature.

[sourcecode language='C#']
static void Foo(ref Math m){}
static void Foo(out Math m){} // ERROR: can’t overload with ref and out keyword
[/sourcecode]

params are allows to pass pass arbitrary number of parameters to this function. Params keyword has the following constraints. There should be only one params argument as function parameter and it should be appeared as the last parameter of a function(or no other parameters can be passed after a param variable)
See the same sample from MSDN

[sourcecode language='c#']
using System;
public class MyClass
{
public static void UseParams(paramsparams int[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}

public static void UseParams2(params object[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}

static void Main()
{
UseParams(1, 2, 3);
UseParams2(1, ‘a’, “test”);

// An array of objects can also be passed, as long as
// the array type matches the method being called.
int[] myarray = new int[3] {10,11,12};
UseParams(myarray);
}
}
[/sourcecode]

Categories: .NET, 1, C Sharp, Code Tags: ,

Learning .NET with C#

May 15th, 2008 Sarath Comments

Learning .NET becomes an important in my professional life. I’m basically a native programmer and really comfortable with C++/MFC/Win32 World. But seems it’s really necessary to learn the booming technologies and languages because I’m basically a Software Engineer.
I believe choosing a programming language is the end side of Software engineering. We can architect a new concept/idea and design it well. Choosing the programming languages is consists of many factors. It depends upon the domain we’re representing, availability of resources, cost for the compilers and other related development product, support & maintenance factor etc… Still the programming language has some impact on particular domains.
I could not say that I can program only with C/C++. Rather I’m comfortable with C/C++.even the domain switching is not so easy, I believe we’ve to keep the pace with the industry. Many of my friends shared their story, if they get a U.S Project, they will be asking for either Java or C# platform. I don’t know whether this is a global trend or not.
One of our Program Manager Anil, came forward to take up the task to teach the basic C# with his short trainings.  Being a Program Manager he’s much interested in the new technologies always keeping his technical skills up-to-date with current trends.
Anyway I started learning this managed things (I really hate that I don’t have any control over the memory). Hope to see some upcoming beginners posts on C# and .NET.
There are lots of tutorials available to learn C#. Many excellent books like CLR via C#, Pro C# 2008 and .NET 3.5 Platform. So I’m not gonna some in-depth posts on C# but still I try to provide some information comparing C++

Categories: .NET, C Sharp Tags: