Consuming URL Shortening Services – is.gd

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Read more about URL Shortening Services here.

Source- Elsheimy.Samples.ShortenSvcs.zip

Contents

Contents of this article:

  • Contents
  • Overview
  • Introduction
  • API
  • What’s next

Overview

Another article of our series that talks about accessing URL shortening services programmatically.

This article is talking about is.gd shortening service, how you can use it, and how to access it via your C#/VB.NET application.

Introduction

is.gd is one of the most popular shortening services ever in the web because of its simple interface and its easy-to-use API.

When you visit service website, http://is.gd, you can see that nothing easier from is.gd, just push your long URL into the text box and click the shortening button.

API

is.gd provides you a very simple easy-to-use API. This API contains only one function that’s used for shortening URLs. Another good thing is that this function doesn’t require any kind of authentication for users. Therefore, you need just to spam it with your long URL (as you did with the website.)

This glorious function is called http://is.gd/api.php, it accepts only a single argument, longurl, which can be set to the long URL you need to shorten. When you call the function, it simply returns the shortened URL as plain text (no more overhead.)

Now, let’s try this function. We’ll try to shorten the URL http://JustLikeAMagic.com with our function. First, connect the arguments, http://is.gd/api.php?longurl=http://JustLikeAMagic.com. Now copy this address and paste it into your favorite browser. If everything was OK, you should see the short URL after clicking €˜Go’ in the browser toolbar.

Now, let’s do it in C# and VB.NET. Check the following function that tries to shorten long URLs via the id.gd API:

// C#

string Shorten(string url)
{
    url = Uri.EscapeUriString(url);
    string reqUri = String.Format(@"http://is.gd/api.php?longurl={0}", url);

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(reqUri);
    req.Timeout = 5000;

    try
    {
        using (System.IO.StreamReader reader =
            new System.IO.StreamReader(req.GetResponse().GetResponseStream()))
        {
            return reader.ReadLine();
        }
    }
    catch (WebException ex)
    {
        return ex.Message;
    }
}
' VB.NET

Function Shorten(ByVal url As String) As String

    url = Uri.EscapeUriString(url)
    Dim reqUri As String = _
        String.Format("http://is.gd/api.php?longurl={0}", url)
    Dim req As WebRequest = WebRequest.Create(reqUri)
    req.Timeout = 5000

    Try
        Dim reader As System.IO.StreamReader = _
            New System.IO.StreamReader(req.GetResponse().GetResponseStream())

        Dim retValue As String = reader.ReadLine()
        reader.Dispose()

        Return retValue
    Catch ex As WebException
        Return ex.Message
    End Try

End Function

Notice that we have used the function System.Net.Uri.EscapeUriString() to eliminate unacceptable characters from the URL by encoding them.

Notice too that we have included our code in a Try-Catch block so we can catch exceptions before they blow up our application.

What’s next

Consider reading other articles in this series here.

Consuming URL Shortening Services – Introduction

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Read more about URL shortening services here.

Source- Elsheimy.Samples.ShortenSvcs.zip

Contents

Contents of this article:

  • Contents
  • Overview
  • Introduction
  • Accessing the API
  • Authentication
  • .NET Support
  • Encoding
  • Sample
  • Where to Go Next
  • Poll: What are your favorite URL shortening services?

Overview

This is the first article of our series that talks about accessing URL shortening services programmatically.

Here we introduce new concepts like the REST API. We also have a brief discussion of URL shortening services APIs and how you can access them.

In addition, we are going to talk about .NET support for the REST API and tools and techniques available that would help us during our journey through the API.

A working example built using C# and WinForms is available at the end of this article.

This article is the base for all other articles. Articles other than this discuss specific services and their APIs. We will make use of code and techniques discussed here throughout the rest of articles.

Let’s go!

Introduction

URL shortening services are very popular these days since web addresses tend to be very long and very difficult to be exchanged via email or other micro-blogging services like Twitter.

Today, there’re tenths of URL shortening services spread out all over the web. Most of them are listed in the following articles:

In this series, we are going to talk about how to consume URL shortening services in your .NET application. In other words, we will discuss how to program URL shortening services; we mean how to access them programmatically. In addition, we will have a brief discussion of each service and its unique features.

How we will go through this discussion? This is going to be a series of articles published regularly. Each article discusses a given shortening service from the following list (updated regularly, expect new services to be added):

The preceding list may not be comprehensive, many other popular services exist. However, not all shortening services have APIs! The preceding list contains the shortening services we know that allow developers to consume their functionalities via an exposed API.

Before we start with a specific service, let’s have a brief discussion of features of the API and how we can access them.

Accessing the API

Most APIs in the web are just REST (Representational State Transfer) web services. A REST web service is simply a collection of functions (HTTP endpoints) that can be used to retrieve data in a variety of formats (optional.)

Given an endpoint (function) like http://ab.c/api/shrink, we could supply the required input arguments as query strings in the URL. For example, we could shorten the URL www.google.com using a call to the HTTP endpoint http://ab.c/api/shrink?url=www.google.com supplied with the required information. It is worth mentioning that every service has its own API functions and arguments. Although they all do the same thing (shortening the URL,) they differ in function and argument names.

When you call a web function, you just end up with the results in the format used in that function (XML, Atom, JSON, etc.) The function could also return plain text! It’s all about the function documentation that you should check carefully before calling the function. In addition, the returned value from a function may also contain error details if the function didn’t success.

Keep in mind that API calls are limited and you can’t just leave the shortening code in an end-less loop! Other limitations of specific APIs should be discussed later.

Authentication

Most URL shortening services allow users to consume the service without being registered, some of allow users to register, and others not. Many other services require users to be registered in order to use the service.

Likewise, service APIs may or may not require user authentication. Some services give the user an API key that can be used in the authentication process. Other services require user to enter his login details in the API calls. Most use the API key approach.

.NET Support

Does .NET support the REST API? Sure! As long as REST web services are just collections of HTTP endpoints, we do not need to worry about accessing them from .NET since that the BCL offers us a bunch of classes (available in System.dll) that can help with HTTP requests and responses.

In addition, we will rely heavily on classes of System.Xml.dll to handle the data returned from functions (we will make use of functions that support XML.)

If we could write something in C# that calls our fake web function http://ab.c/api/shrink, we could end up with some code like this:

// C#

public void string Shorten(string url)
{
    string reqUri = @"http://ab.c/api/shrink?url=" + url;

    WebRequest req = WebRequest.Create(reqUri);
    req.Timeout = 5000;

    XmlDocument doc = new XmlDocument();
    doc.Load(req.GetResponse().GetResponseStream());

    return HandleXml(doc);
}
' VB.NET

Function Shorten(ByVal url As String) As String

    Dim reqUri As String = "http://ab.c/api/shrink?url=" & url

    Dim req As WebRequest = WebRequest.Create(reqUri)
    req.Timeout = 5000

    Dim doc As new XmlDocument()
    doc.Load(req.GetResponse().GetResponseStream())

    Return HandleXml(doc)

End Function

Encoding

If the URL to shorten have special characters like ‘&’, ‘?’, ‘#’, or ‘ ‘, those characters should be handled first before the URL is sent to the shortening function.

This special handling for URLs is usually called Percent-encoding or URL Encoding. This encoding replaces unsafe characters with their hexadecimal values preceded by percentage (‘%’) signs.

There are many unsafe characters that should be percent-encoded including ‘$’, ‘+’, ‘&’, ‘:’, and ‘=’. A nice discussion of URL Encoding can be found in the article URL Encoding by Brian Wilson.

Why unsafe characters are problematic? Consider the following example: we need to shorten the URL http://justlikeamagic.com/?s=twitter with our fake shortening service http://ab.c, we end up with a call to the function using the following address http://ab.c/api/shrink?url=http://justlikeamagic.com/?s=twitter. Now we have two ‘?’s!!!

So how can we encode URLs? Simply use the EscapeUriString() function of System.Net.Uri class it would work well for us here. If you need a full-featured encoder; a procedure that would work for all and every situation, you will need to consider creating one yourself, or you can use this:

// C#

char[] _chars = new char[]
{
     '%',
     '$' ,
     '&',
     '+',
     ',',
     '/',
     ':',
     ';',
     '=',
     '?',
     '@',
     ' ',
     '"',
     '',
     '#',
     '{',
     '}',
     '|',
     '\',
     '^',
     '~',
     '[',
     ']',
     ''', };

string EncodeUrl(string url)
{
    for (int i = 0; i < _chars.GetUpperBound(0); i++)
        url = url.Replace(
            _chars[i].ToString(),
            string.Format("{0:X}", (int)_chars[i]));

    return url;
}

string DecodeUrl(string url)
{
    for (int i = 0; i < _chars.GetUpperBound(0); i++)
        url = url.Replace(
            string.Format("{0:X}", (int)_chars[i]),
            _chars[i].ToString());

    return url;
}

' VB.NET

Private _chars() As String = _
{ _
"%", _
"$", _
"&amp;", _
"+", _
",", _
"/", _
":", _
";", _
"=", _
"?", _
"@", _
" ", _
"", _
"”, _
“#”, _
“{“, _
“}”, _
“|”, _
“”, _
“^”, _
“~”, _
“[“, _
“]”, _
“‘”}

Public Function EncodeUrl(ByVal url As String) As String
For i As Integer = 0 To _chars.GetUpperBound(0) – 1
url = url.Replace( _
_chars(i).ToString(), _
String.Format(“{0:X}”, CInt(_chars(i))))
Next

Return url
End Function

Public Function DecodeUrl(ByVal url As String) As String
For i As Integer = 0 To _chars.GetUpperBound(0) – 1
url = url.Replace( _
String.Format(“{0:X}”, CInt(_chars(i))), _
_chars(i))
Next

Return url
End Function

Sample

Download the sample from here.

Where to Go Next

Now start with any shortening service you like (links are update regularly, new services will be available too):

Or else, check our URL Shortening Services tag.

Poll

Creating a Simple Twitter Client Application

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Code: Geming.twitoo.msi

Contents

Contents of this writing:

  • Contents
  • Overview
  • Introduction
  • Twitter API
    • What Twitter API is
    • API Documentation
    • Things to be Kept into mind
  • API Methods
    • Method Address
    • Methods with Arguments
    • Methods Require Authentication
  • Twitter and .NET
    • Accessing the API
    • Authentication
    • Encoding URIs
    • Business Objects
    • Retrieving Data
  • twittoo; Sample Application
    • Snapshots
    • Description
    • Interface
    • URL Shortening
    • Download

Overview

This writing discusses the Twitter API and how you can utilize it in your managed application. It begins by a brief discussion of the API and the methods used. After that, it digs into the discussion of how you can utilize the API into your application with help of code samples and examples. At the end of this writing, there’s a nice open-source Twitter client application available for download. Worth mentioning that this article focuses on the REST API set of Twitter, specifically XML endpoints.)

Introduction

Today, we are talking about Twitter as it is one of the most famous social networking services. This article discusses how you can create Twitter clients using .NET Framework. Oh, before we start, I’d like to introduce you my twitter account first; it’s @elsheimy.

Twitter API

What Twitter API is

Before we dig into the discussion of Twitter API we need to know first what the Twitter API is.

Twitter API is a set of endpoints (or methods) that allow applications to work with Twitter data.

Twitter API consists of three parts:

  • Two REST APIs:
    • REST API:
      This is the core API set; it allows developers to access core Twitter data, it contains most (if not all) of the methods and functions you would use to utilize Twitter data in your application, and it supports (mostly) three formats (or endpoints) for each method: XML, Atom, and JSON formats.
    • Search API:
      Fully integrating search methods allows you to search for tweets based on specific criteria and to search for daily/weekly hot trends. It supports only the JSON format. This set of API was originally developed by Summize, Inc. and integrated into the Twitter API. (Twitter is looking forward to unify the REST API.)
  • Streaming API:
    A set of API methods that allow near-realtime access to various subsets of Twitter public statuses. All methods are in JSON format, no XML or ATOM endpoints available.

Actually, the REST API would be very sufficient for you unless you find it easier to handle the JSON format.

It is worth mentioning that the REST API provides very handful and sufficient search methods that your application can use. If you need more searching capabilities (like searching for tweets that confirm to a set of criteria,) you can dig into the REST Search API.

You are not required to stick to a specific set of API methods. You can mix the methods you like from the three APIs.

Wikipedia: REST (Representational State Transfer) is a style of software architecture for distributed hypermedia systems such as the World Wide Web.

Wikipedia: JSON (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange based on the JavaScript programming language.

Wikipedia: Atom Publishing Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and updating web resources.

This writing focuses on the XML endpoints of the REST API.

API Documentation

Twitter has with a very nice API documentation that documents each and all methods and endpoints of the three parts of the API. This documentation can be found here: http://apiwiki.twitter.com.

To avoid duplication, we are not going to discuss the Twitter API again in this writing; it is already documented and available for all users. Instead, we will take a brief look at the API and discuss how we can utilize it in our .NET application. For simplicity, we will focus on XML endpoints. Therefore, all of our code would rely on the XML features of .NET Framework 2.0 (i.e. System.Xml.dll library.) Oh, you are free to write the code the way you like (e.g. integrating LINQ for XML into the code.)

Now, we are going to look inside the Twitter API.

Things to be Kept into Mind

There are some basics of the Twitter API that a developer should keep into his mind.

  • Calls to the Twitter API are limited:
    Don’t expect to post unlimited updates or to follow thousands of users in just an hour! Many methods have a call limit (hourly/daily.) For example, at the time of this writing, you have only 150 API requests per hour, further requests would return an exception. In addition, you can send only 1,000 updates and 250 direct messages per day (can we remove this word ‘only€?) You can check Twitter limits here.
  • Every endpoint has its HTTP methods that need to be set (e.g. GET, POST, and DELETE) in the request. The documentation of each endpoint lists the HTTP methods required for that endpoint. For more information about HTTP and HTTP methods check the RFC 2616 Section 9 document.
  • Some methods (like methods send updates) require user authentication and others not. Authentication is discussed soon.

API Methods

The following is a discussion about Twitter API methods and how you can call them.

Method Address

Every method has an address (i.e. URI). The address of a method is something like that: http://api.twitter.com/1/statuses/public_timeline.format (for the statuses/public timeline method.) We replace the format field with the format we like to work with (e.g. xml, atom, json.)

Now, try to copy the method address http://api.twitter.com/1/statuses/public_timeline.xml and paste it into your browser. You should get something like that:


    
        Wed Apr 14 19:32:07 +0000 2010
        12179999634
        35 Ingenious Examples of Footwear - http://su.pr/1JxMAr
        <a href="http://apiwiki.twitter.com/" rel="nofollow">API</a>
        false
        
        
        false
        
        
            15736190
            Smashing Magazine
            smashingmag
            Freiburg, Germany
            Vitaly Friedman, editor-in-chief of SmashingMagazine.com ...
            http://a3.twimg.com/profile_images/572829723/...
            http://www.smashingmagazine.com
            false
            166019
            B2DFDA
            333333
            f51616
            ffffff
            eeeeee
            394
            Tue Aug 05 14:00:40 +0000 2008
            4
            -10800
            <time>Greenland</time>
            http://s.twimg.com/a/...
            true
            false
            true
            false
            false
            8703
            en
            false
        
        
        
        
        
    
    . . .

This method returns the 20 most recent statuses from arbitrarily-selected non-protected Twitter users; this list is called the Public Timeline. Because we have selected the XML format (or endpoint) we end up with XML data.

From the data returned we can extract the structure of statuses and users. Twitter API is good enough; it uses the same structure for all data returned. In other words, all methods (in the REST API, remember?) use the same structure (i.e. schema) to represent status and user objects. Those structures are covered soon.

Methods with Arguments

Most of methods accept arguments, some are optional and others are required. An example of a function requires a single argument is the users/show method that returns profile information about a specific user.

This function accepts one of three arguments:

  • id:
    The ID or screen name of the user.
  • user_id:
    The ID of the user.
  • screen_name:
    The screen name of the user.

We set arguments the same way we set web pages query strings. Considering my twitter account @elsheimy as an example, we could query user profile using one of four ways:

All of the four calls return the same results that should be like this:


    19645411
    Mohammad Elsheimy
    Elsheimy
    KB, Egypt
    Technology evangelist from Egypt born in 1991
    http://a1.twimg.com/profile_images/833061500/...
    http://justlikeamagic.com
    false
    278
    DBE9ED
    333333
    CC3366
    E6F6F9
    DBE9ED
    179
    Wed Jan 28 10:47:36 +0000 2009
    7
    7200
    <time>Cairo</time>
    http://s.twimg.com/a/1271811071/...if
    false
    
    true
    false
    
    1877
    en
    false
    
        Wed Apr 21 16:21:46 +0000 2010
        12585240751
        I'm reading this, it's really hot: #RFC 2616 - Hypertext Transfer Protocol ...
        <a href="http://bit.ly" rel="nofollow">bit.ly</a>
        false
        
        
        false
        
        
        
        
        
    

As you can see, it returns user information and the last update of that user. Notice that the structure of the data is the same in all methods.

Methods Require Authentication

Some methods require user authentication. Examples are functions update status, send direct messages, retrieve friends’ timeline, etc.

Let’s take an example. Bring up your browser and browse to the address of statuses/friends timeline method that returns user’s friends’ timeline, http://api.twitter.com/1/statuses/friends_timeline.xml. A small window like this should appear that asks you your Twitter username and password.

Figure 1. IE Authentication

Provide your Twitter username and password to pass to the results. If authentication was OK, you should receive the most recent 20 statuses of your friend timeline in the same structure (schema) as the Public Timeline method. On the other hand, if the authentication process failed, you should receive an error:


    /1/statuses/friends_timeline.xml
    Could not authenticate you.

Let’s consider another example, the direct_messages/new method. This function sends a new direct message to a specific user from the current user authenticated.

This function accepts two required arguments:

  • user:
    The ID or screen name of the recipient user. You can use one of two arguments in place of this argument:

    • screen_name:
      Screen name of the user.
    • user_id:
      The ID of the user.
  • text:
    Message body, not longer than 140 UTF-8-encoded characters.

The following two calls send the same message (‘hi, how is it going€) to the same user:

Notice that we need to encode arguments before we pass them to the server.

Because this function updates data, it requires HTTP POST method. Therefore, you won’t be able to try it from your browser unless your browser allows you to set HTTP methods in the request.

If the function succeeded, it should return the message object that has been sent, and it should be like this:


    88619848
    1401881
    all your bases are belong to us.
    7004322
    Wed Apr 08 20:30:04 +0000 2009
    dougw
    igudo
    
        1401881
        Doug Williams
        dougw
        San Francisco, CA
        Twitter API Support. Internet, greed, users, dougw ...
        http://s3.amazonaws.com/twitter_production/...
        http://www.igudo.com
        false
        1036
        9ae4e8
        000000
        0000ff
        e0ff92
        87bc44
        290
        Sun Mar 18 06:42:26 +0000 2007
        0
        -18000
        <time>Eastern Time (US &amp; Canada)</time>
        http://s3.amazonaws.com/...
        false
        3394
        false
        false
        true
    
    
        7004322
        Doug Williams
        igudo
        North Carolina
        A character.
        http://s3.amazonaws.com/...
        http://www.igudo.com
        false
        19
        69A1AA
        000000
        F00
        ACBEC1
        8A8F85
        3
        Thu Jun 21 21:16:21 +0000 2007
        0
        -18000
        <time>Eastern Time (US &amp; Canada)</time>
        http://static.twitter.com/...
        false
        382
        false
        true
        true
    

Notice that the sender and recipient are just user objects. It is worth mentioning that the direct_messages function return a list of direct_message objects (like the timeline functions that return list of status objects.)

Twitter and .NET

Now, you have a solid understanding of the Twitter API and how you can access it. Now, let’s utilize this API into our .NET applications.

Accessing the API

To access the API from your .NET application you need to create a HTTP request and send it to the server and wait for server response. Let’s consider an example. The following code snippet connects to the server and retrieves a System.Xml.XmlDocument that contains the returned data.

// C# Code

public static Main()
{
    GetResponse("http://api.twitter.com/1/statuses/public_timeline.xml");
}

public static XmlDocument GetResponse(string uri)
{
    WebRequest req = WebRequest.Create(new Uri(uri));

    XmlDocument doc = new XmlDocument();
    doc.Load(req.GetResponse().GetResponseStream());
    return doc;
}
' VB.NET Code

Sub Main()
    GetResponse("http://api.twitter.com/1/statuses/public_timeline.xml")
End Sub

Public Function GetResponse(ByVal uri As String) As XmlDocument

    Dim req As WebRequest = WebRequest.Create(New Uri(uri))

    Dim doc As New XmlDocument()
    doc.Load(req.GetResponse().GetResponseStream())

    Return doc
End Function

We have used the System.Xml.WebRequest class to create the request and to get the response (as an instance of System.Xml.WebResponse class) from the server. Once we get the XmlDocument, we can walk through the data and retrieve it.

Authentication

You can take one of two approaches to authenticate Twitter users:

  • OAuth Authentication:
    An authentication protocol that allows users to approve application to act on their behalf without sharing their password. As this function requires more overhead and requires your application to be registered in the Twitter clients’ directory, we would better use the second approach in our examples.
  • Basic Authentication:
    To provide authentication information in each request you make to the server. Unfortunately, Twitter announced that this method will not be available later.

Considering a method like statuses/update method that updates the status information of the user (i.e. sends a tweet) we would develop our previous code to be like this:

// C# Code

public static void Main()
{
    GetResponse("http://api.twitter.com/1/statuses/update.xml?status=hello%20from%20the%20API",
        "elsheimy", "b@zzword", true);
}

public static XmlDocument GetResponse(string uri, string username, string password, bool post)
{
    WebRequest req = WebRequest.Create(new Uri(uri));
    if (post)
        req.Method = "POST";
    if ((username != null) && (username.Trim() != String.Empty) && (!String.IsNullOrEmpty(password)))
        req.Credentials = new NetworkCredential(username.Trim(), password);

    XmlDocument doc = new XmlDocument();
    doc.Load(req.GetResponse().GetResponseStream());
    return doc;
}
' VB.NET Code

Sub Main()
    GetResponse("http://api.twitter.com/1/statuses/update.xml?status=hello%20from%20the%20API", "elsheimy", "b@zzword", True)
End Sub

Public Function GetResponse(ByVal uri As String, ByVal username As String, ByVal password As String, ByVal post As Boolean) As XmlDocument
    Dim req As WebRequest = WebRequest.Create(New Uri(uri))
    If (post) Then
        req.Method = "POST"
    End If
    If ((username  Nothing) And (username.Trim()  String.Empty) And (Not String.IsNullOrEmpty(password))) Then
        req.Credentials = New NetworkCredential(username.Trim(), password)
    End If

    Dim doc As XmlDocument = New XmlDocument()
    doc.Load(req.GetResponse().GetResponseStream())

    Return doc
End Function

Notice how we set the HTTP method based on the function requirements. It is worth mentioning that a status should not exceed 140 UTF-8-encoded characters.

Encoding URIs

Have you noticed the previous code? It tries to post the update ‘hello from the API€. Because the text is included with the URI, special handling to the text should be carried. This special handling for text included in URIs is usually called Percent-encoding or URL Encoding. This encoding replaces unsafe characters with their hexadecimal values preceded by percentage (%) signs. Unsafe characters are those somewhat conflicted with URI special characters. For example, if we would encode the text ‘hello from the API€ we would end up with ‘hello%20from%20the%20API€.

There are many unsafe characters that should be percent-encoded including $, +, &, :, and =. A nice discussion of URL Encoding can be found in the article URL Encoding by Brian Wilson.

Once we get the idea, we can create our percent-encoding class that encodes/decodes strings:

// C# Code

private static string[,] _chars = new string[,]
        {
        { "%", "%25" },     // this is the first one
        { "$" , "%24" },
        { "&", "%26" },
        { "+", "%2B" },
        { ",", "%2C" },
        { "/", "%2F" },
        { ":", "%3A" },
        { ";", "%3B" },
        { "=", "%3D" },
        { "?", "%3F" },
        { "@", "%40" },
        { " ", "%20" },
        { """ , "%22" },
        { "", "%3E" },
        { "#", "%23" },
        { "{", "%7B" },
        { "}", "%7D" },
        { "|", "%7C" },
        { "\", "%5C" },
        { "^", "%5E" },
        { "~", "%7E" },
        { "[", "%5B" },
        { "]", "%5D" },
        { "`", "%60" } };

public static string EncodeUrl(string url)
{
    for (int i = 0; i < _chars.GetUpperBound(0); i++)
        url = url.Replace(_chars[i, 0], _chars[i, 1]);

    return url;
}

public static string DecodeUrl(string url)
{
    for (int i = 0; i < _chars.GetUpperBound(0); i++)
        url = url.Replace(_chars[i, 1], _chars[i, 0]);

    return url;
}

' VB.NET Code
Public Module UrlEncoder

Private _chars(,) As String = _
{ _
{"%", "%25"}, _
{"$", "%24"}, _
{"&", "%26"}, _
{"+", "%2B"}, _
{",", "%2C"}, _
{"/", "%2F"}, _
{":", "%3A"}, _
{";", "%3B"}, _
{"=", "%3D"}, _
{"?", "%3F"}, _
{"@", "%40"}, _
{" ", "%20"}, _
{"", "%22"}, _
{"”, “%3E”}, _
{“#”, “%23”}, _
{“{“, “%7B”}, _
{“}”, “%7D”}, _
{“|”, “%7C”}, _
{“”, “%5C”}, _
{“^”, “%5E”}, _
{“~”, “%7E”}, _
{“[“, “%5B”}, _
{“]”, “%5D”}, _
{“‘”, “%60”}}

Public Function EncodeUrl(ByVal url As String) As String
For i As Integer = 0 To _chars.GetUpperBound(0) – 1
url = url.Replace(_chars(i, 0), _chars(i, 1))
Next

Return url
End Function

Public Function DecodeUrl(ByVal url As String) As String
For i As Integer = 0 To _chars.GetUpperBound(0) – 1
url = url.Replace(_chars(i, 1), _chars(i, 0))
Next

Return url
End Function

End Module

For clearness, we have included the encoded string of each character along with the character itself. You don’t have to do this. You can convert the character to a number and just output the number in hex format.

Now we could change the code that updates the status to the following:

// C# Code

public static void Main()
{
    string uri;
    string text = UrlEncoder.EncodeUrl("hello from the API");
    uri = "http://api.twitter.com/1/statuses/update.xml?status=" + text;
    GetResponse(uri, "elsheimy", "b@zzwrd", true);
}
' VB.NET Code

Public Sub Main()

    Dim uri As String
    Dim text As String = UrlEncoder.EncodeUrl("hello from the API")
    uri = "http://api.twitter.com/1/statuses/update.xml?status=" & text
    GetResponse(uri, "elsheimy", "b@zzwrd", True)
End Sub

.NET includes a nice function that escapes (encodes) a URI, System.Uri.EscapeUriString() function. However, this function does not encode all unsafe characters.

Business Objects

Once you know the structure of the XML data returned, you can create your business objects that would encapsulate this data. The following are the three classes that would represent our three core objects, the user, the status, and the message.

// C# Code

public structure TwitterUser
{
    public long ID;
    public string Name;
    public string ScreenName;
    public string Location;
    public string Description;
    public string ProfileImage;
    public string Url;
    public bool IsProtected;
    public long FollowersCount;
    public long FriendsCount;
    public string CreatedAt;
    public long FavoritesCount;
    public bool Verified;
    public bool Following;
    public long StatusCount;
}

public structure TwitterStatus
{
    public string CreatedAt;
    public long ID;
    public string Text;
    public string Source;
    public bool Truncated;
    public long InReplyToStatusID;
    public long InReplyToUserID;
    public bool Favorited;
    public string InReplyToScreenName;
    public TwitterUser User;
}

public structure TwitterMessage
{
    public long ID;
    public long SenderID;
    public long SenderScreenName;
    public long RecipientID;
    public long RecipientScreenName;
    public string Text;
    public string CreatedAt;
    public TwitterUser Sender;
    public TwitterUser Recipient;
}
' VB.NET Code

Public Structure TwitterUser
    Public ID As Long
    Public Name As String
    Public ScreenName As String
    Public Location As String
    Public Description As String
    Public ProfileImage As String
    Public Url As String
    Public IsProtected As Boolean
    Public FollowersCount As Long
    Public FriendsCount As Long
    Public CreatedAt As String
    Public FavoritesCount As Long
    Public Verified As Boolean
    Public Following As Boolean
    Public StatusCount As Long
End Structure

Public Structure TwitterStatus
    Public CreatedAt As String
    Public ID As Long
    Public Text As String
    Public Source As String
    Public Truncated As Boolean
    Public InReplyToStatusID As Long
    Public InReplyToUserID As Long
    Public Favorited As Boolean
    Public InReplyToScreenName As String
    Public User As TwitterUser
End Structure

Public Structure TwitterMessage

    Public ID As Long
    Public SenderID As Long
    Public SenderScreenName As Long
    Public RecipientID As Long
    Public RecipientScreenName As Long
    Public Text As String
    Public CreatedAt As String
    Public Sender As TwitterUser
    Public Recipient As TwitterUser
End Structure

Retrieving Data

Now you can walk through the XML data and get that data inside your objects. The following code returns a list of statuses from your friends’ timeline.

// C# Code

public static void Main()
{
    GetStatuses("elsheimy", "b@zzword");
}
public static List GetStatuses(string username, string password)
{
    XmlNode node = GetResponse("http://api.twitter.com/1/statuses/friends_timeline.xml",
        username, password, true);

    List lst = new List(node.ChildNodes.Count);

    foreach (XmlNode nd in node.ChildNodes)   // for each status
        lst.Add(HandleStatus(nd));

    return lst;
}

public static TwitterStatus HandleStatus(XmlNode nd)
{
    // HandleNumber, FormatText, HandleBool
    // are just functions that converts strings
    // to numbers, decoded strings, and bool
    TwitterStatus status = new TwitterStatus(
        nd["created_at"].InnerText,
        HandleNumber(nd["id"]),
        FormatText(nd["text"]),
        FormatText(nd["source"]),
        HandleBool(nd["truncated"]),
        HandleNumber(nd["in_reply_to_status_id"]),
        HandleNumber(nd["in_reply_to_user_id"]),
        HandleBool(nd["favorited"]),
        FormatText(nd["in_reply_to_screen_name"]),
        HandleUser(nd["user"]));
    return status;
}

public static TwitterUser HandleUser(XmlNode nd)
{
    // HandleNumber, FormatText, HandleBool
    // are just functions that converts strings
    // to numbers, decoded strings, and bool
    long id = HandleNumber(nd["id"]);
    TwitterUser user;

    user = new TwitterUser(
        id,
        FormatText(nd["name"]),
        FormatText(nd["screen_name"]),
        FormatText(nd["location"]),
        FormatText(nd["description"]),
        nd["profile_image_url"].InnerText,
        nd["url"].InnerText,
        HandleBool(nd["protected"]),
        HandleNumber(nd["followers_count"]),
        HandleNumber(nd["friends_count"]),
        nd["created_at"].InnerText,
        HandleNumber(nd["favourites_count"]),
        HandleBool(nd["verified"]),
        HandleBool(nd["following"]),
        HandleNumber(nd["statuses_count"]));

    return user;
}
' VB.NET Code

Sub Main()
    GetStatuses("elsheimy", "b@zzword")
End Sub

Public Function GetStatuses(ByVal username As String, ByVal password As String) As List(Of TwitterStatus)
    Dim node As XmlNode = GetResponse("http://api.twitter.com/1/statuses/friends_timeline.xml", username, password, True)

    Dim lst As New List(Of TwitterStatus)(node.ChildNodes.Count)

    For Each nd As XmlNode In node.ChildNodes
        lst.Add(HandleStatus(nd))
    Next

    Return lst
End Function

Public Function HandleStatus(ByVal nd As XmlNode) As TwitterStatus
    ' HandleNumber, FormatText, HandleBool
    ' are just functions that converts strings
    ' to numbers, decoded strings, and bool

    Dim status As New TwitterStatus( _
            nd("created_at").InnerText, _
            HandleNumber(nd("id")), _
            FormatText(nd("text")), _
            FormatText(nd("source")), _
            HandleBool(nd("truncated")), _
            HandleNumber(nd("in_reply_to_status_id")), _
            HandleNumber(nd("in_reply_to_user_id")), _
            HandleBool(nd("favorited")), _
            FormatText(nd("in_reply_to_screen_name")), _
            HandleUser(nd("user")))

    Return status
End Function

Public Function HandleUser(ByVal nd As XmlNode) As TwitterUser
    ' HandleNumber, FormatText, HandleBool
    ' are just functions that converts strings
    ' to numbers, decoded strings, and bool
    Dim id As Long = HandleNumber(nd("id"))

    Dim user As New TwitterUser( _
        id, _
        FormatText(nd("name")), _
        FormatText(nd("screen_name")), _
        FormatText(nd("location")), _
        FormatText(nd("description")), _
        nd("profile_image_url").InnerText, _
        nd("url").InnerText, _
        HandleBool(nd("protected")), _
        HandleNumber(nd("followers_count")), _
        HandleNumber(nd("friends_count")), _
        nd("created_at").InnerText, _
        HandleNumber(nd("favourites_count")), _
        HandleBool(nd("verified")), _
        HandleBool(nd("following")), _
        HandleNumber(nd("statuses_count")))
    Return user
End Function

twittoo; Sample Application

twitto, is our WinForms sample application that utilizes the Twitter API. This is just a very simple application with basic functionalities.

Snapshots

The following are snapshots of the application:

Figure 2 - twitto 0

Figure 3 - twitto 1

Figure 4 - twitto 2

Figure 5 - twitto 3

Figure 6 - twitto 4

Figure 7 - twitto 5

Description

This application was created using C# and WinForms 2.0 technology; it allows the user to navigate through his friends’ timeline, mentions, direct messages, retweets, and friends, and to update his status, reply to tweets, retweets, and to direct messages. Data is not refreshed automatically, the user have to click the ‘refresh€ button. (You can create your own routine that creates a timer that updates the data automatically.)

Interface

As you see, the application uses just the Windows Common Controls all around the application; no 3rd party controls were used.

To represent a status, message, or a user, the application overuses the System.Windows.Forms.TableLayoutPanel control to represent each status, message, or user. It consists of four columns and two rows. The following figure shows how the control is laid-out.

Figure 8 - TableLayoutPanel Status Template

URL Shortening

twittoo, has a very nice feature, it allows the user to insert a shortened URL into his tweets. For this to work, the application makes use of http://is.gd URL shortening service. The following is the function that utilizes the http://is.gd API:

// C# Code

public static string Shorten(string url)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch
        (url, @"(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&:/~+#]*[w-@?^=%&/~+#])?"))
        throw new FormatException("The URL you specificed is not in the current format.");

    url = Uri.EscapeUriString(url);
    string reqUri = String.Format(@"http://is.gd/api.php?longurl={0}", url);

    WebRequest req = WebRequest.Create(reqUri);
    req.Timeout = 5000;
    using (System.IO.StreamReader reader =
        new System.IO.StreamReader(req.GetResponse().GetResponseStream()))
    {
        return reader.ReadLine();
    }
}
' VB.NET

Public Function Shorten(ByVal url As String) As String
    If (Not System.Text.RegularExpressions.Regex.IsMatch _
        (url, "(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&;:/~+#]*[w-@?^=%&;/~+#])?")) Then
        Throw New FormatException("The URL you specificed is not in the current format.")
    End If

    url = Uri.EscapeUriString(url)
    Dim reqUri As String = String.Format("http://is.gd/api.php?longurl={0}", url)

    Dim req As WebRequest = WebRequest.Create(reqUri)
    req.Timeout = 5000

    Dim reader As New System.IO.StreamReader(req.GetResponse().GetResponseStream())
    url = reader.ReadLine()
    reader.Close()

    Return url
End Function

Download

Download twittoo; our sample application

Introducing RSS; Developing a Simple RSS Reader

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Code: Geming.WinForms.RssBars.zip

Contents

Contents of this writing:

  • Contents
  • Overview
  • Definition
  • Feeds
  • Aggregators/Readers
  • Version History
  • Schema
  • Sample; RSS Bars Library
  • Download
  • Further Readings

Overview

This writing does not include a full discussion or even the full details of RSS or XML. Rather, it includes a nice introduction to RSS and its XML schema. In addition, it incorporates what you get in a sample application that is easy-to-code, understand, and to extend.

Definition

RSS (commonly expanded as Really Simple Syndication or, sometimes, Rich Site Summary) is a XML content with specific schema used to deliver frequently changing web content (like news headlines, blogs, etc.).

RSS content is also known as a feed, web feed, syndication feed, web syndication, and a channel. It is widely known and distinguished by its icon €œ€.

RSS feeds are usually files that reside in a specific location. Those files usually (not extensively) has the extension rss or xml.

Feeds

Today, most -if not all – of the blogs and sites that have frequently changing web content incorporate RSS.

For instance, The New York Times has more than one hundred of RSS feeds available for subscription (listed here.) Every feed delivers the latest headlines for a specific category (Technology, Sports, etc.)

Aggregators/Readers

How can you benefits from RSS feeds? Surely, XML data is not the flexible and readable content that can be used. Thus, users usually access feeds via applications (or web clients) that are known as Feed Readers, RSS Readers, and Aggregators. Those applications read the RSS XML content, parse it, and display feed items (e.g. news headlines) to the user in a friendly interface.

Version History

RSS undergoes several changes that result in different versions and two major branches:

  1. RDF (Resource Description Framework) or RSS 1.* in other words.
  2. RSS 2.*

We will assume RSS 2.* is our discussion.

Schema

As any other XML format, RSS has a specific schema that RSS contents (i.e. feeds) should comply with; they required to implement obligatory elements, and they had the choice to implement other optional elements.

As a matter of discussion, we will take the CodeProject latest articles RSS feed (available here) as an example and extract the RSS schema from it.

The following is a sample from the CodeProject RSS feed content (at the time of this writing):


    
        The Code Project Latest Articles
        http://www.codeproject.com
        Latest Articles from The Code Project
        en-us
        
            The Code Project
            
            http://www.codeproject.com
            100
            30
            The Code Project
        
        Copyright &copy; CodeProject, 1999-2010
        webmaster@codeproject.com
        Sun, 04 Apr 2010 12:27:00 GMT
        20
        C# Hand-coded goodness
        
            Comparison of Architecture presentation patterns MVP(SC),MVP(PV), ...
            This article will compare four important architecture ...
            http://www.codeproject.com/KB/aspnet/ArchitectureComparison.aspx
            Shivprasad koirala
            Sun, 04 Apr 2010 12:27:00 GMT
            ASP.NET
            http://www.codeproject.com/KB/aspnet/ArchitectureComparison.aspx
        
        
            Arcade Button in Expression Blend & Silverlight
            Discover the power of the Grid object, & how it controls ...
            http://www.codeproject.com/KB/expression/ArcadeButton.aspx
            Alan Beasley
            Sun, 04 Apr 2010 11:42:00 GMT
            Expression
            http://www.codeproject.com/KB/expression/ArcadeButton.aspx
        
        
            How to translate your forms application
            Translate your forms application to multiple languages ...
            http://www.codeproject.com/KB/dotnet/forms-translator.aspx
            Davide Vitelaru
            Sun, 04 Apr 2010 07:19:00 GMT
            .NET Framework
            http://www.codeproject.com/KB/dotnet/forms-translator.aspx
        
    

If we have a look at the file in XML Notepad we can see the following results:

To gain more understanding of the schema, let’s have a look at this diagram:

Required elements surrounded by the red border. Many other optional elements are available.

Most elements are self-explanatory from their names. However, the following maybe need more explanation:

  • rsschannellanguage:
    Content language (e.g. en-us for English for United States.)
  • rsschannellastBuildDate:
    The date of the last change of the content.
  • rsschannelttl:
    Time to Live. The number of minutes that indicate how long a channel can be cached before refreshing from the source. You would ignore this element, in many cases.
  • rsschannelgenerator:
    The name of the program used to generate this feed.
  • rsschannelitemguid:
    A Globally Unique Identifier used to identify this feed item.

Sample; RSS Bars Library

Our sample project is not an application in itself. Actually it is a WinForms control library that is called Geming.WinForms.RssBars. This library includes bars that read RSS content from a specific feeds and display it to the user.

This is an extensible library you can extend it to read from any RSS feed you like. The following are snapshots of the RssBars controls (reading CodeProject, Just Like a Magic, BBC, and the Nile News channels.)




The following figure shows library class diagram:

As you see, we have only one business object, RssItem structure. It encapsulates fields related to a feed item.

The RssBar is the base MustInherit (abstract in C#) class. It defines the base functionality of a RSS bar. All other classes are just children of the base class. They incorporate the functionality of RssBar by just setting its RSS feed path.

The RssBar requires two parameters for instantiation, the RSS path, and the banner image. For the sake of performance, we have required the developer to pass a banner image of the feed instead of automatically loading it from the image element of the feed content.

To avoid duplication, members of the RssBar are documented in the code.

The core function of the RssBar is the ReadRss() function. This function accesses the RSS feed and populates the list of feed items and display them to the user.

Since RSS is a XML format, we will need to reference the System.Xml.dll library as it is the core library for accessing XML via .NET. (Do not forget to import the System.Xml namespace.)

The following is a sample from the function code. Code abbreviated for clarity.

Public Sub ReadRss()
    ' Checking design mode, exit if True

    ' Preparing the screen

    ' The XML Document
    Dim xmlDoc As New Xml.XmlDocument
    ' Loading the RSS feed, should fail if network is not available
    xmlDoc.Load(m_rss)

    ' Accessing the €œchannel€ element
    Dim ndChannel As Xml.XmlNode = xmlDoc.Item("rss").Item("channel")

    ' Comparing publication date to one we have
    ' continue if something new

    ' Item cocollection
    Dim collItems As New Collections.Generic.List(Of RssItem)
    Dim ndItem As Xml.XmlNode

    ' Enumerating through the items
    ' and populating the collection
    For i As Integer = 0 To ndChannel.ChildNodes.Count - 1
        ndItem = ndChannel.ChildNodes(i)
        If (ndItem.Name = "item") Then
            collItems.Add( _
            NewRssItem(ndItem.Item("title").ChildNodes(0).InnerText, _
            ndItem.Item("link").ChildNodes(0).InnerText, _
            ndItem.Item("description").ChildNodes(0).InnerText))
        End If
    Next

    ' Checking if items cound

    ' Clear existing items

    Do While enumerator.MoveNext

        ' Item

        lbl = New Label
        ' Creating a Label for the item
        ' and filling its fields
        Me.CtrlsPanel.Controls.Add(lbl)

        ' Adding handlers, so we could fire events
        AddHandler lbl.Click, AddressOf Me.RssItem_Click
        AddHandler lbl.MouseMove, AddressOf Me.RssItem_MouseMove

        ' Image
        image = New PictureBox
        ' Adding the banner image between items
        Me.CtrlsPanel.Controls.Add(image)

        ' Adding event handlers, so we could fire events
        AddHandler image.Click, AddressOf Image_Click
        AddHandler image.MouseMove, AddressOf Image_MouseMove
    Loop

    ' Finalization
End Sub

Child classes simply do not contain any code, just the line that instantiates the base RssBar and sets the RSS feed path and image. For instance,

    Public Sub New()
MyBase.New("http://www.codeproject.com/webservices/articlerss.aspx?cat=1", m_image)
Me.RightToLeft = Windows.Forms.RightToLeft.No
End Sub

Download

Download Geming.WinForms.RssBars Sample Code

Further Readings

Need more about RSS? Here are a few good references:

Assembly Spy; a Reflection Sample

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Code: Assembly Spy + Source Code.msi

Introduction

Assembly Spy is a very nice simple application written in VB.NET that uses reflection to dynamically inspect assemblies and list the containing types and members of the selected type.

The following figure shows application’s only window loading .NET 2.0 mscorlib.dll and lists members of System.String.

Background

Here are some things that should be kept in your mind:

  • All types (classes, structures, enumerations, etc.) inherit -directly or indirectly- from System.Type, and System.Type, in turn, inherits from System.Object. Therefore, System.Type can represent any other type.
  • Reflection, as described in MSDN, is a CLR feature allows you to obtain information about assemblies and types defined within them dynamically (on the fly.)
  • All types related to reflection are grouped together inside the namespace System.Reflection in the core COR (Common Object Runtime) assembly, mscorlib.dll.
  • Reflection represents type members as objects inherit from System.Reflection.MemberInfo class. We will see how soon.
  • Visual Studio’s Object Browser and Class Viewer (WinCV) are the most illustrative examples of tools that use reflection to obtain information about types in a given assembly.

Sample Code

It allows you to select an assembly, and it lists types defined within that assembly it in the left pane. When you select a type, it automatically lists type members in the right pane of the window.

After loading the assembly using the shared method System.Reflection.LoadFrom(), the application retrieves an array of all types defined inside this assembly (accurately, module) and calls our core function ListModuleTypes() to list the types into the List Box:

Private Sub ListModuleTypes(ByRef tTypes() As System.Type)
    Dim tType As System.Type

    For Each tType In tTypes
        If (tType.IsPublic) Then
            lbNamespaces.Items.Add(tType.FullName)
        End If
    Next
End Sub

When a user selects a type, the code clears out members tree view and adds the members of the newly selected type. Those members are categorized into those categories:

  1. Static Fields:
    Shared fields. Retrieved using System.Type.GetFields() function.
  2. Static Properties:
    Shared properties. Retrieved using System.Type.GetProperties() function.
  3. Static Events:
    Shared events. Retrieved using System.Type.GetEvents() function.
  4. Static Methods:
    Shared methods. Retrieved using System.Type.GetMethods() function.
  5. Static Constructors:
    Shared constructors. Retrieved using System.Type.GetContructors() function.
  6. Instance Fields:
    Retrieved using System.Type.GetFields() function with BindingFlags.Instance flag set.
  7. Instance Properties:
    Retrieved using System.Type.GetProperties() function with BindingFlags.Instance flag set.
  8. Instance Events:
    Retrieved using System.Type.GetEvents() function with BindingFlags.Instance flag set.
  9. Instance Methods:
    Retrieved using System.Type.GetMethods() function with BindingFlags.Instance flag set.
  10. Instance Constructors:
    Retrieved using System.Type.GetContructors() function with BindingFlags.Instance flag set.

Every one of our System.Type.GetXXX() functions returns an array of types inherit from System.Reflection.MemberInfo class. This allows us to polymorphically enumerate the array and work with all class members the same way. The following illustration should give you a basic understanding of how types are related to each other.

The code uses the following function add members to the members tree view:

Private Sub ListMembers(ByVal miElements() As System.Reflection.MemberInfo)
    Dim miElement As System.Reflection.MemberInfo

    For Each miElement In miElements
        tnNode = New TreeNode
        tnNode.Text = System.Convert.ToString(miElement)
        tvMembers.SelectedNode.Nodes.Add(tnNode)
    Next
End Sub

Download

Code sample and application are attached with the article. The setup file installs both the application and its source code.

Code: Assembly Spy + Source Code.msi

I created this application since several years ago when I was discovering .NET for the first time. Honestly, the UI of this sample originated from a VB.NET book.  I really know neither the name of that book nor the name of its author. However, a big €œThank You€ to the author and the book.

Sending Mails in .NET Framework

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

فيديو AR002: إرسال رسائل البريد الإلكتروني في ASP.NET

App: Mail+.msi
Code: Mail+ Source-Code.msi

Contents

Contents of this article:

  • Overview
  • Introduction
  • Type Overview
    • System.Net.Mail Types
    • System.Web.Mail Types
  • SMTP Servers
  • Implementation
  • Changing Mail Delivery Method
    • Configuring IIS Default Pickup Directory
    • Programmatically Changing Delivery Method
  • A Sample Application
  • Summary

Overview

This lesson focuses on how to send mail messages in .NET Framework via a SMTP server. It firstly discusses the techniques which .NET Framework provides you to send mail messages. After that, it discusses types available for you when working with SMTP servers. Next, it discusses how to implement these techniques and to send mails from a .NET client.

At the end of this lesson, there is a sample application, Geming Mail+, which is used to send mails from a various SMTP servers. This application is open-source, so you can download its code freely.

Introduction

Simple Mail Transport Protocol or simply SMTP provides a way for applications to connect to the mail server and send mail messages via server’s exposed SMTP service.

Before .NET 2.0, you were to access SMTP via classes in System.Web.Mail namespace which resides in System.Web.dll library. With the release of .NET 2.0, System.Web.Mail classes became deprecated and replaced with classes in System.Net.Mail namespace which exists in System.dll library. That means that you still can use classes of System.Web.Mail, however, you will receive warnings indicate that those classes are deprecated and you should use classes from System.Net.Mail namespace.

Type Overview

System.Net.Mail Types

System.Net.Mail namespace includes many types each of which provides a special feature. In fact, the most time you will not need to use all of them or to know them at all. However, being aware of what .NET provides to you for accessing SMTP is better to help you evolving your SMTP client application in many sides and in various degrees. Here are the most common classes of System.Net.Mail:

  • SmtpClient:
    One of the essential classes provides you with means of connecting to the SMTP server and sending mail messages. Before starting using this class and send a message, you must initialize server properties like Host, Port, and EnableSsl to allow communicating with the SMTP server. SmtpClient also provides you with some methods like the Send method that sends a specific message synchronously, and SendAsync to send it asynchronously.
  • MailMessage:
    The message to be sent using the SmtpClient class. This class exposes many properties specific to the message like To, CC, Bcc, Subject, and Body properties that corresponds to the message fields.
  • MailAddress:
    Encapsulates a mail address. Provides the DisplayName and Address properties.
  • MailAddressCollection:
    A collection of MailAddress objects. This collection is used inside the MailMessage object in the properties To, CC, and Bcc.
  • Attachment:
    Encapsulates an attached file.
  • AttachmentCollection:
    A collection of Attachment objects. Used in the MailMessage class in its Attachments property.
  • SmtpException:
    Represents an exception thrown from the SmtpClient if it failed to send a message. Use SmtpException’s StatusCode property to determine the error occurred. In addition, see the inner exception for more details.
  • SmtpFailedRecipientException and SmtpFailedRecipientsException:
    Represent exceptions thrown when the SmtpClient fails to send a message to a specific recipient or a group of recipients. Both classes are derived from SmtpException.
  • SmtpPermission and SmtpPermissionAttribute:
    If you are aware of your code running from various locations or from an unsecure environment, you can use these classes to control how your application should access SMTP servers. You use SmtpPermission to control application permissions imperatively. SmtpPermissionAttribute is used to control the permissions declaratively. Consult MSDN documentation for more information about these types and how to use them.

In addition, System.Net.Mail includes various enumerations each represents a set of options for a specific feature. For example, MailPriority enumeration is exposed via the Priority property of a MailMessage object; it can take one of three values, Low, Normal, and High, and it is used to mark your message with a specific priority flag.

System.Web.Mail Types

Besides types in System.Net.Mail, for whose interested in .NET 1.0 and descendent before .NET 2.0, we will cover types of System.Web.Mail briefly. In fact, they are very few types, actually, they are only three classes and three enumerations, and they serve the same as types in System.Net.Mail.

Classes in System.Web.Mail:

  • SmtpMail:
    Serves the same as System.Net.Mail.SmtpClient. However, it exposes only a single property SmtpServer. Plus, it exposes methods for sending mail messages.
  • MailMessage:
    Encapsulates message related information and data like To, CC, BCC, Subject, and Body fields.
  • MailAttachment:
    Encapsulates an attachment. MailMessage exposes a list of MailAttachment objects via its Attachments property.

Besides those only three classes, System.Web.Mail also includes three enumerations, MailEncoding, MailFormat, and MailPriority. I think that those enumerations have expressive names enough and do not need to be explained. If you need some explanation consult MSDN documentation or continue reading this article. Although, this article concentrates on types from System.Net.Mail, they are very similar to the types in System.Web.Mail.

SMTP Servers

In order to connect to a SMTP server you need to be aware of four things:

  • Server address:
    Like smtp.example.com.
  • Port number:
    Usually 25, and sometimes 465. Depends on server’s configuration.
  • SSL:
    You need to know if the server requires a SSL (Secure Socket Layer) connection or not. To be honest, most servers require SSL connections.
  • Credentials:
    You need to know if the server accepts default credentials of the user or requires specific credentials. Credentials are simply the username and password of the user. All e-mail service providers require specific credentials. For example, to connect to your Gmail’s account and send mails via Gmail’s SMTP server, you will need to provide your mail address and password.

The following is a list of some of the major e-mail service providers who provide SMTP services for their clients:

Name Server Address Port SSL Required?
Live smtp.live.com 25 Yes
Gmail smtp.gmail.com 465, 25, or 587 Yes
Yahoo! plus.smtp.mail.yahoo.com 465, 25, or 587 Yes
Only for Plus! accounts. Consult Yahoo! documentation for more help about selecting the right port number.
GMX mail.gmx.com 25 No

Implementation

The following is a simple code segment uses classes from System.Net.Mail namespace to send mail messages via Gmail’s SMTP server.

Do not forget to add a using statement (Imports in VB.NET) for the System.Net.Mail namespace.

// C# Code

MailMessage msg = new MailMessage();

// Your mail address and display name.
// This what will appear on the From field.
// If you used another credentials to access
// the SMTP server, the mail message would be
// sent from the mail specified in the From
// field on behalf of the real sender.
msg.From = new MailAddress("example@gmail.com", "Example");

// To addresses
msg.To.Add("friend_a@example.com");
msg.To.Add(new MailAddress("friend_b@example.com", "Friend B"));

// You can specify CC and BCC addresses also

// Set to high priority
msg.Priority = MailPriority.High;

msg.Subject = "Hey, a fabulous site!";

// You can specify a plain text or HTML contents
msg.Body =
    "Hello everybody,<br /><br />" +
    "I found an interesting site called " +
    "<a href="http://JustLikeAMagic.com">" +
    "Just Like a Magic</a>. Be sure to visit it soon.";
// In order for the mail client to interpret message
// body correctly, we mark the body as HTML
// because we set the body to HTML contents.
msg.IsBodyHtml = true;

// Attaching some data
msg.Attachments.Add(new Attachment("C:\Site.lnk"));

// Connecting to the server and configuring it
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 578;
client.EnableSsl = true;
// The server requires user's credentials
// not the default credentials
client.UseDefaultCredentials = false;
// Provide your credentials
client.Credentials =
    new System.Net.NetworkCredential("example@gmail.com", "buzzwrd");
client.DeliveryMethod = SmtpDeliveryMethod.Network;

// Use SendAsync to send the message asynchronously
client.Send(msg);
' VB.NET Code

Dim msg As New MailMessage()

' Your mail address and display name.
' This what will appear on the From field.
' If you used another credentials to access
' the SMTP server, the mail message would be
' sent from the mail specified in the From
' field on behalf of the real sender.
msg.From = New MailAddress("example@gmail.com", "Example")

' To addresses
msg.To.Add("friend_a@example.com")
msg.To.Add(New MailAddress("friend_b@example.com", "Friend B"))

' You can specify CC and BCC addresses also

' Set to high priority
msg.Priority = MailPriority.High

msg.Subject = "Hey, a fabulous site!"

' You can specify a plain text or HTML contents
msg.Body = _
    "Hello everybody,<br /><br />" &amp; _
    "I found an interesting site called " &amp; _
    "<a>" &amp; _
    "Just Like a Magic</a>. Be sure to visit it soon."
' In order for the mail client to interpret message
' body correctly, we mark the body as HTML
' because we set the body to HTML contents.
msg.IsBodyHtml = True

' Attaching some data
msg.Attachments.Add(New Attachment("D:Site.lnk"))

' Connecting to the server and configuring it
Dim client As New SmtpClient()
client.Host = "smtp.gmail.com"
client.Port = 578
client.EnableSsl = True
' The server requires user's credentials
' not the default credentials
client.UseDefaultCredentials = True
' Provide your credentials
client.Credentials = _
    New System.Net.NetworkCredential("example@gmail.com", "buzzwrd")
client.DelieryMethod = SmtpDeliveryMethod.Network

' Use SendAsync to send the message asynchronously
client.Send(msg)

Changing Mail Delivery Method

You can specify that messages sent do not go to the SMTP server. Instead, it is sent to a directory in your computer that you specify. Actually, it is a good idea when it comes to testing your application. Thus, decreases the testing time.

SmtpClient supports two properties for changing mail delivery location; they are DeliveryMethod and PickupDirectoryLocation properties. DeliveryMethod specifies the delivery method that would be taken when sending the message. This property is of type SmtpDeliveryMethod enumeration; therefore, it can be set to one of three values:

  • Network: (default)
    The message is sent via the network to the SMTP server.
  • PickupDirectoryFromIis:
    The message is copied to the mail default directory of the Internet Information Services (IIS).
  • SpecifiedPickupDirectory:
    The message is copied to the directory specified by the property PickupDirectoryLocation.

Configuring IIS Default Pickup Directory

To change the IIS default pickup directory in IIS 7 follow the following steps:

  1. Start Internet Information Services (IIS) 7 Manager.
  2. From the Home view, select SMTP E-mail item. Figure 1 shows the SMTP E-mail item in the IIS 7 MMC snap-in.

    Figure 1 - Selecting SMTP E-mail Item in IIS 7

    Figure 1 - Selecting SMTP E-mail Item in IIS 7

  3. From the SMTP E-mail configuration view, change the default pickup directory by choosing the option €œStore e-mail in pickup directory€ and selecting your desired directory using the Browse button. Figure 2 shows the SMTP E-mail view while changing pickup directory options.

    Figure 2 - Configuring SMTP E-mail Pickup Directory

    Figure 2 - Configuring SMTP E-mail Pickup Directory

  4. From the right pane, click Apply to save your current settings.

Programmatically Changing Delivery Method

The following lines change the delivery location to a specific location in the drive C. You can add the following lines before the line that calls Send() method of the SmtpClient.

In order for the example to run correctly, the specified directory must be existed or you will receive an exception when executing the Send() method.

    // C# Code
    client.DeliveryMethod =
        SmtpDeliveryMethod.SpecifiedPickupDirectory;
    client.PickupDirectoryLocation = "C:\mails";
    ' VB.NET Code
    client.DeliveryMethod =
        SmtpDeliveryMethod.SpecifiedPickupDirectory
    client.PickupDirectoryLocation = "C:mails"

A Sample Application

Geming Mail+ is an application that is used to send mails via extendable variety of SMTP servers. This application created using .NET 2.0 and Visual Studio 2008. The following are snapshots of the application:

Geming Mail+ Splash Geming Mail+

Download the application here

Download the source code Here

Summary

This lesson was a great introduction to e-mail programming in .NET Framework. You learned how to send mails via a SMTP server. Soon we will cover how to receive mails in .NET Framework.

Have a nice day…

Moving a Form without the Title Bar

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Sample: Geming.Samples.FormDragging.zip

What is that?

Today, we are talking about how to move a form without its title bar.

You might have noticed that some applications with fancy UIs do not allow the user to move the window from its title bar. Honestly, some hide the overall title bar from the user. An example of these applications is Microsoft Windows Media Player -when in skin mode,- and Microsoft Windows Live Messenger. Both applications allow you to drag their windows using the client area not the title bar.

In this lesson, you will learn how to do this trick to move the form without its title bar.

At the end of this lesson, a sample application is available for download. It is a simple application with an outstanding UI illustrates how to move the form using its client area.

How?

Theoretically, you cannot drag any form without its title bar. However, we can simulate the dragging process which implies clicking with the left mouse button on the title bar and moving the cursor without releasing the left mouse button.

You can simulate this process using the SendMessage() function. This function is used to send a specific message (you can say command/order) to a specific object -specified by its handle.- This specific message can be attached with another messages (commands) to produce a new command. For example, in our lesson we will attach the message WM_NCLBUTTONDOWN with the message HTCAPTION to simulate the left mouse button clicking on the caption (title bar) of a window (form.)

Honestly, every object is a window. Every button -even the Close button- is a window, the menu item is a window, the status bar is a window, and the tooltip is another window!

The definition of SendMessage() is as following:

LRESULT SendMessage(
    HWND hWnd,
    UINT Msg,
    WPARAM wParam,
    LPARAM lParam
    );

This function takes four arguments:

  • hWnd:
    The handle of the object (window.) to send the message to. Can be set to a window handle, HWND_DESKTOP (to send the message to the desktop,) HWND_BROADCAST (to send the message to all windows.)
  • Msg:
    The primary message that will be sent.
  • wParam:
    A secondary message to be attached to the primary message. Set to 0 to indicate NULL.
  • lParam:
    Another message that can be attached to the primary message. Set to 0 to indicate NULL. If wParam was not set, you cannot set lParam.

The return value of this function depends on the message sent. In our example, the function may return 0 if succeeded, or non-zero if failed.

It is worth mentioning that, in our example, another function must be called before SendMessage(); it is the ReleaseCapture() function. This function releases the mouse capture from a window (object) and restores the normal mouse processing. A window (object) that has captured the mouse receives all mouse input. Therefore, calling the ReleaseCapture() allows our form to release this mouse input (left-clicking) simulated.

The ReleaseCapture() function is very simple; its definition is as following:

BOOL ReleaseCapture(VOID);

This function returns TRUE if succeeded, or FALSE otherwise.

Let’s Code!

Now, we are going to put things together and mix them up.

The first step is to hide the title bar of the form. This can be done through the FormBorderStyle property of the form. You can set this property to FormBorderStyle.None to hide the toolbar and borders of the form.

The next step to take is to create the PInvoke methods for the functions. Here is the full code:

    // C# Code

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.I4)]
static extern int SendMessage(
    IntPtr hWnd,
    [param: MarshalAs(UnmanagedType.U4)]
    uint Msg,
    [param: MarshalAs(UnmanagedType.U4)]
    uint wParam,
    [param: MarshalAs(UnmanagedType.I4)]
    int lParam);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ReleaseCapture();

const uint WM_NCLBUTTONDOWN = 0xA1; // 161
const uint HTCAPTION = 2;
' VB.NET
Declare Function SendMessage Lib "user32.dll" ( _
    ByVal hWnd As IntPtr, _
    ByVal Msg As Integer, _
    ByVal wParam As Integer, _
    ByVal lParam As Integer) As Integer

Declare Auto Function ReleaseCapture _
    Lib "user32.dll" () As Boolean

Const WM_NCLBUTTONDOWN As Integer = 161
Const HTCAPTION As Integer = 2

Again and again, PInvoke stands for Platform Invocation; it is the CLR service allows .NET to call unmanaged code. This service requires special changes to the PInvoke method. Also, specific rules applied when PInvoking an unmanaged function.

The last code demonstrates the PInvoke methods for the functions, and the constants required.

The last step is to add the implementation code required to the MouseDown event of any control that you wish to allow the user to drag the form from. For instance, you can add the code to the MouseDown event of a PictureBox control that will act as the new and fancy title bar. In addition, you can add the code to the form’s MouseDown event to allow the user to drag the form from any point of its client area.

The following code demonstrates how to allow the user to drag the form from its client area:

    // Code

private void MainForm_MouseDown
    (object sender, MouseEventArgs e)
{
    // Releasing the mouse capture
    // to allow the form to receive
    // the order
    ReleaseCapture();
    // Ordering the form
    // Simulating left mouse button clicking
    // on the title bar
    SendMessage(this.Handle, // Form handle
        WM_NCLBUTTONDOWN, // Simulating the click
        HTCAPTION, // Attaching it to the title bar
        0); // No further options required
}
' VB.NET
Private Sub Form1_Load(ByVal sender As Object,ByVal e As EventArgs) _
    Handles MyBase.Load
    ReleaseCapture()
    SendMessage(Me.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0)
End Sub

It is better to check the return value of every call to determine whether the operation succeeded or failed.

A problem occurred!

It is wonderful to allow the user to drag the form from its client area. But, what if the user tried to drag the form from a label on the client area? It will not be dragged.

To overcome this situation, you can add the same code to the MouseDown event of the label. In this case, for better code maintenance and to avoid code repetition, you can define a method that contains the code, and call it from the MouseDown event of every control that you need to allow the user to drag the form from such as a label or a PictureBox. Another solution is to create a single MouseDown event handler for all controls that you are interested in.

Well! What’s next?

You can use this technique when creating applications with hot skins to allow the user to drag the form from its client area or from a specific control like a PictureBox that acts as the new hot title bar.

It is worth mentioning that you would better follow the guidelines when interoperating with unmanaged code. For example, PInvoke methods and constants should be declared inside an internal class called -in our example- SafeNativeMethods. In addition, it is better creating a wrapper method for the PInvoke methods. For example, instead of calling many functions to drag the form, you can create a single function named -for instance- MoveForm() that acts as a wrapper for the PInvoke methods. And that results in code that is more readable and easier to maintain. Plus, it prevents code repetition.

For more information about the functions, consult the MSDN documentation:

WOW! A code sample!

This is a very simple application that illustrates moving a form using its client area.

This sample created using Microsoft Visual Studio 2008 and .NET Framework 2.0.

The following is a snapshot from the application:

Moving Form without Title Bar Sample Snapshot

Download Here

Changing Screen Resolution Programmatically via DirectX

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Overview

This lesson focuses on how to change the screen resolution and color system programmatically via DirectX. It starts by an overview about how the Windows satisfies user’s need through the Display Settings window. Then, it digs into discussing how to retrieve these settings and to change these programmatically in the .NET environment.

Introduction

It is common to change the screen resolution when working with some applications. In addition, games automatically change the screen resolution (bounds) and color system (bit count) to accommodate performance issues.

Background

In Windows, you can change display settings from Display Settings window where you can change screen resolution and color system. Figure 1 shows the Display Settings window.

Display Settings
Figure 1. Display Settings Dialog

However, your screen might support more than these settings. For instance, it could support 8 bit color system which you cannot see in the colors list.

To list all modes that are supported by your screen, you can click Advanced Settings then List All Modes button to display all modes supported and change to the desired mode. Figure 2 shows the List All Modes dialog.

Display List All Modes
Figure 2. Listing All Display Modes Supported

What is a mode? A mode is a combination of four settings, resolution (width and height,) orientation (rotation,) bit count (color system,) and frequency (refresh rate.)

Accessing the DirectX Library

DirectX is the technology of choice when working with multimedia of any type. Here in this lesson, we will focus on how to use DirectX to retrieve screen settings and to change them in the .NET environment.

DirectX consists of many libraries of which every library is specialized in some processing. The library we are interested in is dx3j.dll (Direct 1.0 Type Library) which resides in the System32 folder. You can reference this library in your project by adding it from the Add Reference dialog from the COM tab. Because it is a COM component, you end up creating an interop assembly (DIRECTLIB.dll) for accessing the library. Figure 3 shows the Add Reference dialog.

Figure 3. Adding Direct 1.0 Type Library to References
Figure 3. Adding Direct 1.0 Type Library to References

Because there is no such compatibility between .NET and unmanaged code, you cannot call COM components directly. Instead, you may create a RCW (Runtime Callable Wrapper) assembly that acts as a proxy to the COM component. RCWs also called Interop Assemblies are created automatically when you try to reference a COM component in Visual Studio .NET. However, if you want to have more control over the creation process, you can create your RCW via the tool tlbimp.exe. This tool allows you to control the RCW at a granular level. For instance it allows you to sign the RCW, change its name and version, and to control the marshalling process of the unmanaged types. It is worth mentioning that ActiveX COM components are created with the tool aximp.exe not tlbimp.exe.

Retrieving Current Display Settings

After referencing the required DirectX library, you can now dig into the details of programmatically retrieving and changing display settings.

You can access display settings from the _dxj_DirectDrawClass that resides in our RCW assembly.

The getDisplayMode() function is used to retrieve current display mode information; it accepts a single output parameter that is of type DDSurfaceDesc which encapsulates the retrieved data.

Like other DirectX structures, DDSurfaceDesc is fairly big. However, here, we are interested in four members:

  • width and height:
    Represent the screen bounds (resolution.)
  • rgbBitCount:
    Represents the bit count (color system) of the screen.
  • refreshRate:
    Represents the screen refresh rate (monitor flicker.)

Now, it is the time for the code retrieves current display mode information:

// C# Code

static void Main()
{
    DIRECTLib._dxj_DirectDrawClass ddraw =
        new DIRECTLib._dxj_DirectDrawClass();

    DIRECTLib.DDSurfaceDesc desc;

    ddraw.getDisplayMode(out desc);

    Console.WriteLine("{0} by {1}, {2} bit, {3} Hertz",
        desc.width, desc.height,
        desc.rgbBitCount, desc.refreshRate);
}
' VB.NET Code

Sub Main()
    Dim ddraw As _
        New DIRECTLib._dxj_DirectDrawClass()

    Dim desc As DIRECTLib.DDSurfaceDesc

    ddraw.getDisplayMode(desc)

    Console.WriteLine("{0} by {1}, {2} bit, {3} Hertz", _
        desc.width, desc.height, _
        desc.rgbBitCount, desc.refreshRate)
End Sub

Changing Current Display Settings

Changing the current display settings is very easy. All you need is to provide the new settings to the setDisplayMode() function.

The setDisplayMode() function takes five parameters. However, we are interested in the first three parameters:

  • w:
    The screen width.
  • h:
    The screen height:
  • bpp:
    The bit count (color system.)

The following code sets the display bounds to 640 by 480, and sets the bit count to only 8. I think that feeling reminds you of the ancients Windows ME and its ascendants specially before installing the video driver.

    // C# Code

static void Main()
{
    DIRECTLib._dxj_DirectDrawClass ddraw =
        new DIRECTLib._dxj_DirectDrawClass();

    DIRECTLib.DDSurfaceDesc desc =
        new DIRECTLib.DDSurfaceDesc();

    ModeCallback callback = new ModeCallback();
    const uint DDEDM_REFRESHRATES = 3;
    string format = "{0} by {1}, {2} bit, {3} Hertz";
    ddraw.enumDisplayModes
        (DDEDM_REFRESHRATES, ref desc, format, callback);
}

class ModeCallback : DIRECTLib.IEnumModesCallback
{
    public void callbackEnumModes
        (ref DIRECTLib.DDSurfaceDesc surfDesc, object ctxt)
    {
        Console.WriteLine(ctxt.ToString(),
            surfDesc.width, surfDesc.height,
            surfDesc.rgbBitCount, surfDesc.refreshRate);
    }
}
    ' VB.NET Code

Sub Main()

    Dim ddraw As New DIRECTLib._dxj_DirectDrawClass()

    Dim desc As New DIRECTLib.DDSurfaceDesc()

    Dim callback As New ModeCallback()
    Const DDEDM_REFRESHRATES As UInt32 = 3
    Dim format As String = "{0} by {1}, {2} bit, {3} Hertz"
        ddraw.enumDisplayModes _
        (DDEDM_REFRESHRATES, desc, format, callback)
End Sub

Class ModeCallback
    Implements DIRECTLib.IEnumModesCallback

    Public Sub callbackEnumModes _
        (ByRef surfDesc As DIRECTLib.DDSurfaceDesc, _
        ByVal ctxt As Object) _
        Implements DIRECTLib.IEnumModesCallback.callbackEnumModes
        Console.WriteLine(ctxt.ToString(), _
        surfDesc.width, surfDesc.height, _
        surfDesc.rgbBitCount, surfDesc.refreshRate)
    End Sub
End Class

Notice that closing your application rolls everything back to its original state.
It is worth mentioning that, trying to change the display settings to a mode that is not supported by the display throws NotImplementedException. Despite this, you can enumerate all display modes by the enumDisplayModes() function.

The Last Word

You can use this technique to change the display settings at the beginning of the application and let the runtime returns it back for you when closing the application. For instance, you could add the code to the Main() function and everything will be returned back after the last line of Main() completes.

Programmatically Turning on the Screen Saver

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Overview

This lesson focuses on how to programmatically turn on the screen saver.

Background

In Windows, you can turn it on automatically by leaving the machine inactive for a specific period. You can control this period from the Screen Saver options from the desktop properties dialog. The following figure shows the Screen Saver Settings dialog.

Screen Saver Settings

Programmatically turning on the screen saver

In this section we will learn how to turn on the screen saver in .NET and C#. Of course you can write the code in any language you prefer, but here we will write it in C#.

You can turn on the screen saver by sending the WM_SYSCOMMAND message with the parameter SC_SCREENSAVE.

Sending a message can be done using the SendMessage() function that resides in the User32.dll library.

The definition of this function is as follows:

LRESULT SendMessage(
    HWND hWnd,
    UINT Msg
    WPARAM wParam,
    LPARAM lParam
    );

This function takes four arguments:

  • hWnd:
    Handle to the window to send the message to. You can set this argument to a window handle, the desktop handle (HWND_DESKTOP), or the handle for all top-level windows (HWND_BROADCAST).
  • Msg:
    The message to send.
  • wParam:
    Additional message-specific options.
  • lParam:
    Additional message-specific options.

This function returns a value specific to the message sent. Usually, it returns non-zero if it succeed or zero otherwise.

Here is the full code:

// C# Code

[DllImport("User32.dll")]
static extern int SendMessage
    (IntPtr hWnd,
    uint Msg,
    uint wParam,
    uint lParam);

const uint WM_SYSCOMMAND = 0x112;
const uint SC_SCREENSAVE = 0xF140;
const uint HWND_BROADCAST = 0xFFFF;

static void Main()
{
    SendMessage(
    new IntPtr((int)HWND_BROADCAST),
    WM_SYSCOMMAND,
    SC_SCREENSAVE,
    0);
}
' VB.NET Code

Declare Auto Function SendMessage Lib "user32.dll" _
    (ByVal hWnd As IntPtr, _
    ByVal Msg As UInt32, _
    ByVal wParam As UInt32, _
    ByVal lParam As UInt32) As Int32

Const WM_SYSCOMMAND As UInt32 = &amp;h212
Const SC_SCREENSAVE As UInt32 = &amp;HF140
Const HWND_BROADCAST As UInt32 = &amp;HFFFF

Sub Main()
    SendMessage( _
        New IntPtr(CInt(HWND_BROADCAST)), _
        WM_SYSCOMMAND, _
        SC_SCREENSAVE, _
        0)
End Sub

Code explanation

First, we created our PInvoke method. This method is decorated by the DllImportAttribute attribute specifying the library which the method resides in. Also PInvoke methods must be declared as “static” and “extern”.

Because LRESULT defined as a signed 32-bit integer, it is marshaled as System.Int32 in .NET. Also, because of System.IntPtr is the best type for marshaling any Win32 raw handle, we have used it for the first argument. UINT, WPARAM, AND LPARAM are all defined as an unsigned 32-bit integer, so we have marshaled them as System.UInt32. HWND_BROADCAST represents the handle for all top-level windows, so we have sent them the order to turn on the screen saver.

PInvoke stands for Platform Invocation, it is the process of creating a wrapper for the .NET to interact with unmanaged functions.

Marshaling is the process of creating a bridge between .NET types and unmanaged types.

You can use PostMessage() in place of SendMessage() if you want to send the message asynchronously and don’t want to wait for a response.

Read more about PInvoking and Marshaling in other API lessons.

Programmatically Taking a Screen Snapshot

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Honestly, this lesson is not primarily focusing on how to take a screen snapshot! Instead, it is focusing on how to simulate keyboard strokes and send them to the active application.

In .NET, this is done using the System.Windows.Forms.Forms.SendKeys class. As you might guess it is located in System.Windows.Forms.dll.

Using the SendKeys class you can call static methods like SendWait() to send the keystrokes and wait for them to be processed, or you can send them via the Send() method if you do not care about whether they processed or not.

Both Send() and SendKeys() requires a single argument keys. This argument represents the keys to send it.  Each key is represented by one or more characters. To get list of all values supported for this argument visit the documentation for the SendKeys class, visit this page.

For our example we will try to combine two keys Alt + Print Screen. Alt represented by a percent (%) sign. Print Screen key is represented by the value PrtSc enclosed in curly brackets.

// C#

public static Image TakeScreenSnapshot(bool activeWindowOnly)
{
    // PrtSc = Print Screen Key
    string keys = "{PrtSc}";

    if (activeWindowOnly)
        keys = "%" + keys; // % = Alt

    SendKeys.SendWait(keys);

    return Clipboard.GetImage();
}
' VB.NET

Public Shared Function TakeScreenSnapshot(activeWindowOnly As Boolean) As Image
    ' PrtSc = Print Screen key
    Dim keys As String = "{PrtSc}"

    If (activeWindowOnly) Then
        keys = "%" &amp; keys
    End If

    SendKeys.SendWait(keys)

    Return Clipboard.GetImage()
End Function