Archive

Posts Tagged ‘.NET’

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

Microsoft Win32 to Microsoft .NET Framework API Map

February 20th, 2008 Sarath Comments

I just would like to share Microsoft Win32 to Microsoft .NET Framework API Map from MSDN. May be useful for you. .NET is almost like MFC, a thin layer over Win32 but having much more libraries and functionalities

I saw this while reading Jeff’s  blog. Thanks for put this information on light

Categories: C++, Code, Tips Tags: , ,