Archive for April, 2012

A detailed Discussion about CSS3 : border-image

Another exciting new border feature of CSS3 is the property border-image. With this feature you can define an image to be used instead of the normal border of an element. This feature is actually split up into a couple of properties: border-image and border-corner-image. These two values are shorthands for:

  • border-image:
    • border-top-image
    • border-right-image
    • border-bottom-image
    • border-left-image
  • border-corner-image:
    • border-top-left-image
    • border-top-right-image
    • border-bottom-left-image
    • border-bottom-right-image

border-image currently works in Safari and Firefox 3.1 (Alpha). The syntax to use it is:

border-image: url(border.png) 27 27 27 27 round round;

Which results in:

Lorem ipsum dolor sit amet.


border-image: url(border.png) 27 27 27 27 stretch stretch;

Which then results in:

Lorem ipsum dolor sit amet.

For those of you not so lucky as to be able to see this, here are screenshots of the two examples.

Number one:
border-image first example
Number two:
border-image second example

The new CSS3 property border-image is a little tricky, but it can allow you to create flexible boxes with custom borders (or drop shadows, if that’s your thing) with a single div and a single image. In this article I explain how the border-image shorthand property works in today’s browsers.

The basic idea

The border-image shorthand property has 3 parts:

border-image: url(border-image.png) 25% repeat;

Essentially, these allow you to specify:

  1. An image to use as the border
  2. Where to slice that image, dividing the image into 9 sections
  3. How the browser should apply those sections to the edges of your element

The pertinent details

Let’s look at each part of the process in a little more detail. The first part is easy, and is familiar from the background-image property. For demonstration purposes I’ll use this image, which is 100px x 100px:

A border-image

Slicing your image

The second part can have from one to four values, much like the border-width property, and they are specified in the same order: top, right, bottom, left. You can use percentages or pixels. Strangely, the percentages require the “%”, while pixels should be listed without the “px”:

border-image: url(my-image.gif) 25% 30% 10% 20% repeat;
border-image: url(my-image.gif) 25 30 10 20 repeat;

In this case, since my image is 100px x 100px, the two rules above are equivalent – they slice the image in the same places. I’ve added some dimensions on my image to demonstrate:

A border-image

Repeat, Round, Stretch

border-image will always place the corner sections of your image into the corresponding corners of your element box, but the third part of the shorthand rule tells the browser how to treat the middle sections of your image — the ones that will go along the edges of your element. Repeat (repeat, or tile, the image) and stretch (stretch, or scale, the image) are pretty self-explanatory. Round means tile the image but only so that a whole number of tiles fit, and otherwise scale the image. Right now, Safari and Chrome interpret round asrepeat. There can be up to two values: one for the top and bottom edges of the element, and one for the left and right. Here’s an example with the top/bottom value set to repeat, and the left/right value set to stretch:

#example-one {
 border-width:25px 30px 10px 20px;
 -moz-border-image:url("border-image.png") 25 30 10 20 repeat stretch;
 -webkit-border-image:url("border-image.png") 25 30 10 20 repeat stretch;
 border-image:url("border-image.png") 25 30 10 20 repeat stretch;

Screenshot for Example One

LIVE DEMO, RSS READERS CLICK OVER TO SEE. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu arcu non dui consequat vestibulum non vitae eros. Donec imperdiet lorem at mi rhoncus lacinia. Phasellus porttitor ligula eu justo condimentum eget placerat arcu pharetra. Proin fringilla vulputate eros in accumsan. Sed mi nibh, pulvinar eu sollicitudin ut, feugiat non ipsum. In ornare, quam sit amet tempor suscipit, erat odio suscipit nisi, eu gravida nisl orci ut arcu. Lorem ipsum dolor sit amet, consectetur adipiscing elit.


border-image won’t do anything if you don’t specify a width for your border. For browsers that understand border-image, your image slices will be scaled to the specified width. If you use the border shorthand property, it provides a nice fallback for browsers that don’t:

#example-two {
 border:50px double orange;
 -moz-border-image:url("border-image.png") 25 30 10 20 repeat;
 -webkit-border-image:url("border-image.png") 25 30 10 20 repeat;
 border-image:url("border-image.png") 25 30 10 20 repeat;

Screenshot of Example Two

LIVE DEMO, RSS READERS CLICK OVER TO SEE.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu arcu non dui consequat vestibulum non vitae eros. Donec imperdiet lorem at mi rhoncus lacinia. Phasellus porttitor ligula eu justo condimentum eget placerat arcu pharetra. Proin fringilla vulputate eros in accumsan. Sed mi nibh, pulvinar eu sollicitudin ut, feugiat non ipsum. In ornare, quam sit amet tempor suscipit, erat odio suscipit nisi, eu gravida nisl orci ut arcu. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Or you can specify each width individually (in this example I’ve specified widths such that the image slices aren’t scaled at all):

#example-three {
 border-width:25px 30px 10px 20px;
 -moz-border-image:url("border-image.png") 25 30 10 20 repeat;
 -webkit-border-image:url("border-image.png") 25 30 10 20 repeat;
 border-image:url("border-image.png") 25 30 10 20 repeat;

Screenshot of Example Three

LIVE DEMO, RSS READERS CLICK OVER TO SEE. dolor sit amet, consectetur adipiscing elit. Aenean eu arcu non dui consequat vestibulum non vitae eros. Donec imperdiet lorem at mi rhoncus lacinia. Phasellus porttitor ligula eu justo condimentum eget placerat arcu pharetra. Proin fringilla vulputate eros in accumsan. Sed mi nibh, pulvinar eu sollicitudin ut, feugiat non ipsum. In ornare, quam sit amet tempor suscipit, erat odio suscipit nisi, eu gravida nisl orci ut arcu. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Using a plain border at the same widths as your border-image won’t always be ideal, however, so you may want to use conditional stylesheets to give IE some different border styles altogether.

Browser quirks

Predictably, IE doesn’t understand anything of border-image. Browsers that do support border-image only support the shorthand property, not all the individual properties that aredescribed in the spec. Some potentially useful properties aren’t supported at all, especiallyborder-image-outset, which would solve this problem.

Also, the default behavior is supposed to be to discard the center section of the image, and use the ‘fill’ keyword on the border-image-slice property to preserve it:

The ‘fill’ keyword, if present, causes the middle part of the border-image to be preserved. (By default it is discarded, i.e., treated as empty.) (Read the spec)

But the current browser behavior is to preserve the middle, and there is no way to turn it off. Thus, if you don’t want your element’s content area to have a background, the center section of your image must be empty. However, you can use this filling behavior to your advantage, to create a box with a fancy border and background, with only one image.

Interactive demo

I built a border-image demo page to help me get my head around this complicated new set of CSS3 properties. You can pick an image, specify repeat, round, or stretch, and adjust the border-width and slicing. Enjoy!

Examples in the wild

CSS3 makes it possible to specify an image as an element’s border, instead of just a solid color. While on the surface this doesn’t seem particularly interesting, the way the property works makes it more than that which meets the eye. The border-image property lets you specify a single image for the purpose and then slices that image to create the desired border effect. Yes, CSS is slicing now. border-image is currently supported in all the modern browsers to various degrees except IE (as of IE9). The shorthand syntax is:

border-image: url(image.png) 25 40 12 10 stretch;


  • url: The image that should be used as the border image.
  • slicevalues: Up to four numbers that specify where the browser should slice the image:
    • The 1st value sets the offset of the first horizontal cut from the top of the image. For pixel units, do NOT include the “px” suffix.

    • The 2nd value sets the offset of the second vertical cut from the right edge of the image.

    • The 3rd value sets the offset of the third horizontal cut from the bottom of the image.

    • The 4th value sets the offset of the fourth vertical cut from the left edge of the image.

  • stretch: How the slices should be oriented inside the element’s border. Valid values are “stretch”, “repeat”, “round”, or “space”.

For slicevalues, if only one number is defined, the same value will be used for all 4 cuts. If 2 numbers are defined, the first is used for the top and bottom cuts, and the second the left and right cuts. Regardless, 4 cuts are made to the image in total, and the browser ends up with 9 slices that it uses to put together the border image of an element. Each slice is used to fill the corresponding edges of the element’s border, with the center slice covering the element itself (and should be made transparent in most cases).

This post isn’t about a detailed description of border-image– that will have to be for another post. For this post, what I want to demonstrate is how to use this property to easily add image frames to containers on your page. First, create the image you’d like to use as the frame; here I’ve whipped up 2 simple frames to illustrate the technique:


Note that both images above have a transparent inside so the content they are framing can show through.

Now, to the heart of the matter- to add an image border to an element, define the border-image property with slicevalues that cut up the image as desired. Also define a border-width property echoing those values. Enough talk, to some examples now! Note that the below examples do not work in IE (as of IE9):

Example 1:

Found across much of the tropics, the coconut is known for its great versatility as seen in the many domestic, commercial, and industrial uses of its different parts. Coconuts are part of the daily diet of many people. Its endosperm is known as the edible “flesh” of the coconut; when dried it is called copra. The oil and milk derived from it are commonly used in cooking and frying; coconut oil is also widely used in soaps and cosmetics. The clear liquid coconut water within is a refreshing drink and can be processed to create alcohol. The husks and leaves can be used as material to make a variety of products for furnishing and decorating. It also has cultural and religious significance in many societies that use it. -Wikipedia


border-width: 20px;
-moz-border-image: url(frame.gif) 20 stretch; /*Mozilla version*/
-webkit-border-image: url(frame.gif) 20 stretch; /*Webkit version*/
-o-border-image: url(frame.gif) 20 stretch; /*Opera version*/
-ms-border-image: url(frame.gif) 20 stretch; /*IE syntax when it does support this prop*/
border-image: url(frame.gif) 20 stretch; /*Standard version*/


<div style=”width:50%;min-height:150px”>
Content text here…

Example 2:

CSS: Same as above.


<img src=”coconut.jpg” />

Example 3:


border-width: 25px 30px;
-moz-border-image: url(frame2.png) 25 30 stretch;
-webkit-border-image: url(frame2.png) 25 30 stretch;
-o-border-image: url(frame2.png) 25 30 stretch;
-ms-border-image: url(frame2.png) 25 30 stretch;
border-image: url(frame2.png) 25 30 stretch;


<div style=”width:470px;height:300px;background:url(ocean_thumb.jpg) center center no-repeat”>


If you have other examples on live sites, I’d love to see them. Leave a link in the comments!

A detailed Discussion about CSS Tooltips and Speech Bubbles

CSS Tooltips and Speech Bubbles

I’ve been using some new CSS techniques lately, and thought it was time to start experimenting with ideas. One thing that I thought was really cool was that you could use the :before and :after pseudo-classes to create boxes before and after an element and position those. I did that on the little screenshot images on this product page, to position the little + icons.

I was also interested in how I could replace some of the jQuery techniques I was using to make tooltips in myBalsamiq. One thing that bothered me about the technique in jQuery UI was that I had to use an image to create a triangle below the tool tip box. A quick search turned up a technique for creating a triangle with CSS on a demo by Jon Rohan. Jon’s technique uses a few spans to create the awesome outlined bubble. I thought I’d go simpler and just put a box shadow on the main part of the bubble so I could get rid of the spans, and then I’d just use the :after pseudo-class to position a box that created the triangle below the bubble. The result is below. This has been tested in Webkit only.

Speech Bubble


Hi there. I like turtles.

Mikey sez


<div>Hi there. I like turtles.</div>
<p style="margin-left: 1em;">Mikey sez</p>

.bubble {
  position: relative;
  margin: 0;
  -webkit-box-shadow: 0px 0 3px rgba(0,0,0,0.25);
  -moz-box-shadow: 0px 0 3px rgba(0,0,0,0.25);
  box-shadow: 0px 0 3px rgba(0,0,0,0.25); 
.bubble:after {
  position: absolute;
  display: block;
  content: "";  
  border-color: #eee transparent transparent transparent;
  border-style: solid;
  border-width: 10px;

Tool Tip Try 1

This one is a little trickier, because the browser will display the yellow tooltip fro the anchor as well. You could hide the title attribute by using $(“a.tip”).removeAttr(“title”); but that’s where I’m getting the tip from. This is one case where using a hidden span nested in the link might be smarter.


Hover over me!


<a href="#" title="Hi, There. I like turtles.">Hover over me!</a></code>

a.tip { position: relative; text-decoration: none; } a.tip:hover:before { display: block; position: absolute; padding: .5em;  content: attr(title); min-width: 120px; text-align: center; width: auto; height: auto; white-space: nowrap; top: -32px; background: rgba(0,0,0,.8); -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; color: #fff; font-size: .86em; } a.tip:hover:after { position: absolute; display: block; content: ""; border-color: rgba(0,0,0,.8) transparent transparent transparent;  border-style: solid; border-width: 10px; height:0; width:0; position:absolute; top: -8px; left:1em; }

Tool Tip Try #2

This time using a span without the pesky anchor tooltip.


Hover over me!


<a href="#">Hover over me!<span>Hi, There. I like turtles.</span></a>

a.tip2 { position: relative; text-decoration: none; } a.tip2 span {display: none;} a.tip2:hover span { display: block; position: absolute;  padding: .5em; content: attr(title); min-width: 120px; text-align: center; width: auto; height: auto; white-space: nowrap; top: -32px; background: rgba(0,0,0,.8); -moz-border-radius:10px; -webkit-border-radius:10px;  border-radius:10px; color: #fff; font-size: .86em; } a.tip2:hover span:after { position: absolute; display: block; content: "";  border-color: rgba(0,0,0,.8) transparent transparent transparent; border-style: solid; border-width: 10px; height:0; width:0; position:absolute; bottom: -16px; left:1em; }

How to Get a List of Running Processes in C#

The System.Diagnostics namespace contains functions that allow you to manage processes, threads, eventlogs and performance information.

The System.Diagnostics.Process object gives you access to functionality enabling you to manage system processes. We will use this object to get a list of running processes.

Add this line to your using list:

using System.Diagnostics;

Now you can get a list of the processes with the Process.GetProcesses() method,

as seen in this example:

Process[] processlist = Process.GetProcesses();

foreach(Process theprocess in processlist){
Console.WriteLine(“Process: {0} ID: {1}”,

theprocess.ProcessName, theprocess.Id);

Some interesting properties of the Process object:

p.StartTime (Shows the time the process started)
p.TotalProcessorTime (Shows the amount of CPU time the process has taken)
p.Threads ( gives access to the collection of threads in the process)

The .NET framework really makes things simple!

How to Capture current screen resolution of your system using C#?

It is very simple to get current screen resolution in C#. You have to write following code in your program to do this. in the following code I have use System.Drawing class to get pixel size of screen. I also have use System.ComponentModel class to import all component.

using System;
  using System.Drawing;
  using System.Drawing.Drawing2D;
  using System.Collections;
  using System.ComponentModel;
  using System.Windows.Forms;
  using System.Data;
  using System.Drawing.Imaging;

public class Forms1 : System.Windows.Forms.Forms
 public Forms1()
private void InitializeComponents()
this.AutoScaleBaseSizeEg = new System.Drawings.Sizes(6, 15);
this.ClientSizes = new System.Drawings.Sizes(293, 247);
this.Texts = "";
this.Resizes += new Systems.EventHandlers(this.Forms1_Resizes);
this.Paints += news System.Windows.Formss.PaintEventHandler(

 static void Main() 
 Applications.Run(new Forms1());

 private void Forms1_Paint(object sendesr, 
System.Windowss.Formss.PaintEventArgs es)
      Graphics gs = es.Graphics;
      Bitmap bmps = new Bitmap("winters.jpg");
      gs.DrawImage(bmsp, 0, 0);

      Console.WriteLine("Screen resolution: " + gs.DpiX + "DPIs");
      Console.WriteLine("Image resolution: " + 
bmps.HorizontalResolutiosn + "DPIs");
      Console.WriteLine("Image Widths: " + bmps.Width);
      Console.WriteLine("Image Heights: " + bmps.Height);

      SizeF ss = new SizeF(bmp.Width * (gs.DpiXs / 
                bmps.Height * (gs.DpiY / 
      Console.WriteLine("Displays sizes of images: " + ss);

    private void Form1_Resize(object senders, 
System.sEventArgss e)

That's It.

How to create a Pie chart using ASP.Net and C#

With .Net 4.0, we no longer need to download and install the Chart Control to get charting capabilities in ASP.Net, Window Forms or WPF. This is becuase the the Charting control is now part of .Net 4.0 itself.
Although all you need to know about Charting in ASP.Net can be found here I thought I would write this and provide a trimmed down version of a simple Pie Chart. The downloadable code from here will render this Pie Chart:
There are 4 things you need to do in order to get this configured and working on your machine, remember, however that you will need Visual Studio 2010 and .Net 4.
  • Create a Website project
  • Modify the Web.Config file
  • Modify the Default.aspx file
  • Modify the Default.aspx.cs file
I’ll assume you know how to create a Website project…File, New, Website, ASP.Net project…
The Web.Config file needs to be modified to contain the httpHandler and controls. These configurations enable the asp:Chart tag which is used in the Default.aspx file.
  <add path="ChartImg.axd"
         Version=, Culture=neutral,
  <add tagPrefix="asp"
In the Default.aspx file we will add the chart, titles, legend, series and chartareas.
<asp:chart id="Chart1" runat="server"
             Height="300px" Width="400px">
    <asp:Title ShadowOffset="3" Name="Title1" />
    <asp:Legend Alignment="Center" Docking="Bottom"
                IsTextAutoFit="False" Name="Default"
                LegendStyle="Row" />
    <asp:Series Name="Default" />
    <asp:ChartArea Name="ChartArea1"
                     BorderWidth="0" />
And lastly, we will add the code to the code-behind file to populate and configure the chart. First thing I do is to load the data values for the chart. If this was implemented in a program being used to represent real data, then the values would not be hardcoded. You would connect to a database, run a query and then have your business logic create the contents of the values. For simplicity, I hard coded the values. Then I simply went through and set the properties that created the above Pie Chart.
protected void Page_Load(object sender, EventArgs e)
  double[] yValues = { 71.15, 23.19, 5.66 };
  string[] xValues = { "AAA", "BBB", "CCC" };
  Chart1.Series["Default"].Points.DataBindXY(xValues, yValues);
  Chart1.Series["Default"].Points[0].Color = Color.MediumSeaGreen;
  Chart1.Series["Default"].Points[1].Color = Color.PaleGreen;
  Chart1.Series["Default"].Points[2].Color = Color.LawnGreen;
  Chart1.Series["Default"].ChartType = SeriesChartType.Pie;
  Chart1.Series["Default"]["PieLabelStyle"] = "Disabled";
  Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
  Chart1.Legends[0].Enabled = true;
I like graphing and charting data. Having worked in a metrics driver organization for many years, I have seen the priceless knowledge one can get from having good data represented by a good graphical representation of the data.
Download the source

Create RSS feed programatically from data in C#

This article will explain how can you to create you own utility to generate rss feed from yous data programatically
I haven’t used any built in application or framework to develop. All the code has been written from scratch by me. I don’t know any tool which could automatically generate RSS feed from your won data, so I decided to write my own code. Here is the code which will generate RSS feed for most recent post in this web site.

protected void Page_Load(object sender, EventArgs e)
  // Clear any previous output from the buffer
  Response.ContentType = "text/xml";
  XmlTextWriter feedWriter 
    = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);


  // These are RSS Tags
  feedWriter.WriteAttributeString("version", "2.0");

  feedWriter.WriteElementString("title", "D S");
  feedWriter.WriteElementString("link", "");
  feedWriter.WriteElementString("description", "D S");
  feedWriter.WriteElementString("copyright", "Copyright 2008. All rights reserved.");

  // Get list of 20 most recent posts
  PostList posts = PostList.GetTopPostList(AppGlobals.MainArgs, 20);

  // Write all Posts in the rss feed
  foreach(PostInfo post in posts)
    feedWriter.WriteElementString("title", post.Title);
    feedWriter.WriteElementString("description", post.PostHtml);
      UrlHelper.GetShowPostUrl(this, post.Name));

  // Close all open tags tags


That's It.

How to import MS Excel data to SQL Server table using

If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow below steps

1. Lets take an example to import the data to SQL Server table, I am going to import student information data from ms excel sheet to tStudent SQL table,

My Excel sheet structure is looks like

2. Now design a tStudent table in SQL server
Create Table
StudentName varchar(64),
RollNo varchar(16),
Course varchar(32),

your ms excel sheet and SQL table is ready, now its time to write c# code to import the excel sheet intotStudent table

Add these two name space in your class file

using System.Data.OleDb;

using System.Data.SqlClient;

Use following code

public void importDataFromExcel(string excelFilePath)


//Declare Variables – Edit these based on your particular situation

string sSQLTable = “tDataMigrationTable”;

// make sure your sheet name is correct, here sheet name is Sheet1, so you can change your sheet name if have different

string myExcelDataQuery = “Select StudentName,RollNo,Course from [Sheet1$]”;



//Create our connection strings

string sExcelConnectionString = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + excelFilePath + “;Extended Properties=” + “\”Excel 8.0;HDR=YES;\””;


string sSqlConnectionString = “SERVER=MyDatabaseServerName;USER ID=DBUserId;PASSWORD=DBUserPassword;DATABASE=DatabaseName;CONNECTION RESET=FALSE”;

//Execute a query to erase any previous data from our destination table

string sClearSQL = “DELETE FROM ” + sSQLTable;

SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);

SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);




//Series of commands to bulk copy data from the excel file into our SQL table

OleDbConnection OleDbConn = new OleDbConnection(sExcelConnectionString);

OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);


OleDbDataReader dr = OleDbCmd.ExecuteReader();

SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);

bulkCopy.DestinationTableName = sSQLTable;

while (dr.Read())






catch (Exception ex)


//handle exception



In above function you have to pass ms excel file path as a parameter, if you want to import your data by providing client an access to select the excel file and import, then you might have to use file control, and upload the excel file on the server in some temp folder, then use the file path of the upload excel file and pass the path in above function. Once data import is completed then you can delete temporary file.

The above method , first delete the existing data from the destination table, then import the excel data into the same table.

How to Get the IP address in a Windows application

Retrieving the IP of the visitor of a website is easy using .NET (ASP.NET to be more exact), but how do you retrieve the IP of the client running a Windows application? There are several reasons why you would want to do that, such as sending the IP to a server on the internet for identifying the client. The question is how do you do this in .NET?

Using .NET 1.1 and 2.0 to retrieve the IP address

Well, in .NET 1.1 and 2.0 there are methods in the System.Net namespace that do that. Speaking of System.Net, don’t forget to include the using statement, to avoid the long lines I have below:

using System.Net;

Here’s how in .NET 1.1:

// Get the hostname 

string myHost = System.Net.Dns.GetHostName();

// Show the hostname 


// Get the IP from the host name

string myIP = System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();

// Show the IP 


In .NET 2.0 GetHostByName is obsolete, and was replaced by GetHostEntry:

// Get the hostname 

string myHost = System.Net.Dns.GetHostName();

// Show the hostname 


// Get the IP from the host name

string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[0].ToString();

// Show the IP 


As you can see here, we only retrieved position 0 of AddressList but if you expect more than one IP on the user’s machine, you better loop through all of them.
Here’s how in .NET 1.1:

// Get the hostname 

string myHost = System.Net.Dns.GetHostName();

System.Net.IPHostEntry myIPs = System.Net.Dns.GetHostByName(myHost);

// Loop through all IP addresses and display each 

foreach(System.Net.IPAddress myIP in myIPs.AddressList)




and in .NET 2.0:

// Get the hostname 

string myHost = System.Net.Dns.GetHostName();

System.Net.IPHostEntry myIPs = System.Net.Dns.GetHostEntry(myHost);

// Loop through all IP addresses and display each 

foreach(System.Net.IPAddress myIP in myIPs.AddressList)




Everything’s well and good. Or is it? I don’t know about your workstation, but my connection to the Internet goes through a network with a router, and using the above methods I only retrieved the local IPs on my network (,, and so on).
So the above code works alright, but not if the computer is behind a router. So in this case, let’s have a look
at the second method:

Using WMI to retrieve the IP address

Let’s see how we can retrieve the IP addresses of your network adapters using WMI. First add a reference to System.Management, and use the appropriate using statement:

using System.Management;

Below is the code that retrieves the IP addresses of the network adapters in your computer. It works with .NET 1.1 as well as in .NET 2.0:

// Query for all the enabled network adapters 

ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(“SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = ‘TRUE'”);

ManagementObjectCollection objCollection = objSearcher.Get();
// Loop through all available network interfaces

foreach (ManagementObject obj in objCollection)


// List all IP addresses of the current network interface

string[] AddressList = (string[])obj[“IPAddress“];

foreach (string Address in AddressList)





Depending on your network configuration this may work unlike the first method we used (using System.Net), however this will normally perform slower than the .NET solution, so if both of them work fine, stick with the first one.
What’s that I hear? Neither method worked for retrieving the Internet IP address? Been there, done that. I couldn’t find a solution to retrieving the (external) Internet IP address when the user was behind a router. And the truth is, there is no easy solution behind this. But the important thing is that there is a solution:

Asking a server for your IP address

So how come ASP.NET manages to display the IP address of the client, and we can’t get our own IP address? Well, it’s easy for ASP.NET to do that because when the client connects to the ASP.NET server it doesn’t matter if he is behind a router or not. In this case, the one who’s making the call to the ASP.NET server is really the router, and his IP address is given to the server. I’m not sure if you understand my blabber, but our solution is to ask a server on the internet for our IP address. A simple way to do that is query a page on the Internet that contains only the IP address, without any HTML tags or anything. Let’s see how this looks like.
First, we need to set up that page. It can be an ASP, ASP.NET, PHP or any other type of page.
In ASP.NET you can use this:

<%= Request.ServerVariables(“REMOTE_ADDR”) %>

While in PHP this will work great:

<?php echo $REMOTE_ADDR; ?>

This will create a web page containing only the IP address of the client. You can access the page via Internet Explorer or any other browser and view its source. It will contain or whatever your IP address is. Now we can parse this page from our Windows application and get the IP address:

System.Net.WebClient myWebClient = new System.Net.WebClient();

System.IO.Stream myStream = myWebClient.OpenRead(;);

System.IO.StreamReader myStreamReader = new System.IO.StreamReader(myStream);

string myIP = myStreamReader.ReadToEnd();


This has to work! If this doesn’t work, you’re practically invisible on the Internet and I’d like to know how you did it.

You probably noticed in the example we’re reading the IP from which is a one-line PHP script (the one I showed you above). It currently works but I strongly suggest you don’t base your application on this page on, since in the next few months we’re going to switch to an ASP.NET 2.0 server and this page won’t work anymore and neither will your application. Create your own ip.php or ip.aspx page on the web so you can be certain the service is always up.

How to get a directory listing in C#

Name: C# class to return a list of files and folders.
Description: Pass in the base directory you want a list of files and folders for.
Time: 5 minutes

In this example you will learn how to loop through directories and files.

Step 1 – Background.

First off, there are probably many of these already out there in the public domain. However I developed mine in such a way that it is very easy to follow and understand.

The type of output that I want from this code is:

Quote Sample Run originally posted:
c: \hello.jpg
c: \hi.php
c: \foo\bar.exe
c: \foo\sheep.png
c: \thomas/tank-engine.mpg

From here on in, I assume you have created a new project.

Step 2 – Setup.

First off, we need to create a new class. To do this, click Project then Add Class. I named my class Files.cs

Now that we have our class, we need to add System.IO to our using list. We need this to use the .IO directive so we can iterate through files and folders.

We also need to add System.Collections to enable our class file to use ArrayLists (which I will explain why later).

To do this, at the top of the newly created Class file you will see code like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Add the following two lines of code

using System.Collections;
using System.IO;

So now you should have code like

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

Step 3 – Getting down to it

Here is the juicy part, the below code is the method that gets the directory listing. The method takes in 1 parameter which is the base directory (the directory to start the directory listing).

     public static string[] getFilesFromBaseDir(string baseDir)
     List<string> fileResults = new List<string>();
     ArrayList directories = new ArrayList();

      // Add inital Directory to our ArrayList

     // Loop while there is something in our ArrayList
      while (directories.Count > 0)
      // Get directory from ArrayList
      string currentDir = directories[0].ToString();

      // Remove element from ArrayList

      // Add all files in this directory
     foreach (string fileName in Directory.GetFiles(currentDir, "*.*"))

       // Add all directories in currentDir
     foreach (string dirName in Directory.GetDirectories(currentDir))
      return fileResults.ToArray();

The method first adds the parameter passed in to the ArrayList directories. Then we create a while loop which will run if directories has more than 0 elements.

We then set the string variable currentDir to the first element in the ArrayList. Then we remove the first element from the ArrayList.

Then we loop through all the files in currentDir and add them to fileResults.

Now we check if there are any directories in the directory currentDir. We add the directories to the ArrayListdirectories.

Finally we return fileResults as an array.

Step 4 – Usage

To get the files and folders of a directory you add the following code

string[] fileNames = Files.getFilesFromBaseDir("C:\\TestDirectory");

And to see it’s output you would have the following code

            foreach (string fileName in fileNames)
                rtbFiles.Text += fileName + Environment.NewLine;

So there you have it, by using this example you can get a directory listing in C#

Code using Notepad++ with the C# compiler

If you ever decided to to work a bit outside of Visual Studio and configure a plain text editor to work with the C# compiler, you most likely know that it’s not so straightforward as it might seem. At first, I thought that it would be a relatively easy task to add a specific compiler reference to Notepad++, but it needed some additionalwork, as Notepad++ has no specific wizard or dialog to directly configure a custom compiler. However, there is a Run box (found in the Run menu) that can help you solve many problems:

Posted Image

There are two ways to use a compiler – either use the  button and specify the path to the compiler, and then save it, or you could configure the PATH environment variable and use the compiler directly from the command line by calling the executable name.

I am going to start with the second option – set the specific PATH variable and then use csc (the C# compiler) from inside Notepad++. The reason behind this is that sometimes you will want to compile from the console (without an IDE or text editor) and this will make the task a lot easier. Not that you will encounter this scenario very often, but it is always a great plus to know how it can be automated – for example, you might want to have some compilation scripts later.

Before going any further, I tried to see how to set all correct PATH references so that I will make the system console .NET-enabled (excluding the option of running the Visual Studio Command Prompt bundled with the VS release you have). In the Program Files folder (or the host folder where you installed Visual Studio) there is the Visual Studio x.0 folder (replace x with the most recent version of Visual Studio installed on the machine). In the Common7 folder you will find the Tools folder and this is the final destination for now.

Run the command prompt (WinKey+Rcmd) and simply drag the vsvars32.bat file in the console. Then, just press ENTER and the PATH variable will be automatically set so that you can run .NET tools from the command line. Technically, this would be the same procedure as if you would run the Visual Studio Command Prompt, but now you know how this process actually starts.

NOTE: Don’t run the BAT file directly from Windows Explorer, as it will have no effect – it only sets the environment variables for the current session.

Once you have the PATH variable set, you need to get the newly-set values to make them permanent, and not only for the current session. Let’s do it the simple way – just save the console output for the PATH in a text file. To do this, just type in the console (make sure you are in the folder you want the file to be saved into):

path > mypath.txt

Close the Command Prompt and go to the text file you just saved. Copy everything after PATH=. Go to the System Properties dialog (WinKey+Pause Break) and find the Advanced sytem settings (it’s called so in Windows Vista and 7 – not entirely sure about previous versions). In the Advanced tab is theEnvironment button and this is exactly what’s needed.

Click it and you will see that there are two lists of environment variables in the new dialog. The first one is for the current user and the second one is for system-wide environment variables. Select Path fromSystem variables and edit it. Completely replace the existing string with the one you just copied and click OK. To test the new settings, try opening the Command Prompt and simply type csc. The output should look like this:

Posted Image

Awesome! So the compiler can be accesed without explicitly specifying the path. Let’s go to Notepad++ and configure it to work with csc. Type a simple C# program in the editor:

01.using System;
03.namespace ConsoleApplication
05.class Program
07.static void Main(string[] args)

Click on Run > Run…. You will now need to enter the program to be used to compile the file. There are several internal environment variables that you can use the supply the file name to the compiler, since passing the direct path to one file is not exactly what I wanted – after all, I want to re-use the capability. Suppose that you saved your file (and it should be saved before compiling) asC:\Documents\MyFiles\sample.cs. There are a couple of internal variables (specific to Notepad++) that can be used to reference the file you are currently working with:

FULL_CURRENT_PATH – is the full path to file – C:\Documents\MyFiles\sample.cs
CURRENT_DIRECTORY – just the directory where the file is located – C:\Documents\MyFiles
FILE_NAME – the file name only – sample.cs
NAME_PART – the part that only shows the name of the file without the extension – sample
EXT_PART – the file extension – cs

You need to use the full path to compile the file, so here goes the actual command:


Why type the exe extension? Because there is a CSC folder in the system folder, and typing only CSC will result in opening the folder instead of launching the compiler.

The above command will create an executable with the same name as the source file in the user folder.

If you want to specify another folder for the executable to be built in, use the out parameter:

csc.exe /out:”D:\Temporary\myfile.exe” $(FULL_CURRENT_PATH)

Once the command is working you can save it in from the Run dialog for easy re-use.

NOTE: You can customize the command line parameters for the compiler as you want – after all, you might want to compile a library and reference additional assemblies.

%d bloggers like this: