Tuesday 28 December 2010

Fixed - One or more ActiveX controls could not be displayed because either:...– When opening windows services screen


Sometimes when opening windows services screen (or by running ‘services.msc’ from the command prompt) you might receive the following error screen:


And gives you an empty service screen.


This can be caused due to many reasons. But most of the time it can be fixed by simply editing a registry entry.

Open the registry editor (or run ‘regedit’ from the command prompt) and browse to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones

And if you see a pseudo-graphic number before zone 0 like shown below, it could be the issue.


Delete this. How ever if that doesn’t fix the issue, or if the entry does not exist, select zone ‘0’. And change the value of ‘1200’ to ‘0’ or to ‘1’ (Usually the value will be ‘3’). The values 0,1 and 3 are associated with the following behavior:

  • 0 = Enabled, or the action is permitted
  • 1 = Prompt
  • 3 = Disabled, or the action is not permitted


And if this doesn’t work try to reset the Internet Explorer. To do that follow these steps:

  1. Click on Start & Run.
  2. Type ‘inetcpl.cpl’ & click ok
  3. Click on Advance Tab & click on Reset (Make sure to put the check mark on the delete the personal setting for IE8) then again reset.
  4. Click close.

Thursday 9 December 2010

Constructor Chaining in C#


What’s ‘Constructor Chaining’ ?

Constructor Chaining is an approach where a constructor calls another constructor in the same or base class.

This is very handy when we have a class that defines multiple constructors. Assume we are developing a class call ‘Student’. And this class consist of 3 constructors. On each constructer we have to validate the students id and categorize him/her. So if we do not use the constructor chaining approach, it would be something similar to the one shown below:


Even the above approach solve our problem, it duplicate our code. (We are assigning a value to ‘_id’ in all constructors). This where constructor chaining is very useful. It will eliminate this problem. This time we only assign values only in the constructor which consist most number of parameters. And we call that constructor, when other two constructers are called.

class Student {
string _studentType = "";
string _id = "";
string _fName = "";
string _lName = "";

public Student(string id)
: this(id, "", "") {


public Student(string id, string fName)
: this(id, fName, "") {


public Student(string id, string fName, string lName) {
//Validate logic.....
_studentType = "<student_type>";

_id = id;
_fName = fName;
_lName = lName;

**Please note: If you do not specify anything [In this example we used ‘this’), it will be consider that we are calling the constructor on the base class. And it’s similar to using ‘: base(…)’]

Friday 3 December 2010

Show properties of a class on Property Grid

When developing user controls, usually we use Booleans, Integers, Strings, etc.. as data types of the attributes of the control. But sometimes, we have to use structures or other classes as attributes. So when we use those, we should be able to change or browse the attributes of those structures or classes.

Open visual studio IDE and create a new Windows Forms Application type project.

Add a new class and name it as ‘MyCustomClass’. And define two properties. One integer and a string type.

public class MyCustomClass {

public int MyIntProperty { get; set; }
public string MyStringProperty { get; set; }

public override string ToString() {
return "...";

**Please note that I have overridden the ‘ToString’ method. Because this what will be shown on the property grid when the properties are collapsed.

Now add a new user control to the project and name it as ‘MyCutomUsercontrol’. And create three properties. One integer, string and MyCustomClass. And use ‘[TypeConverter(typeof(ExpandableObjectConverter))]’ attribute on the third property. The syntax should be:

public partial class MyCutomUsercontrol : UserControl {
public MyCutomUsercontrol() {

private MyCustomClass _MyCustomClass = new MyCustomClass();

public int Property1 { get; set; }
public string Property2 { get; set; }

public MyCustomClass Property3 {
get {
return _MyCustomClass;
set {
_MyCustomClass = value;



Now build the solution. And add it a windows form. And on the property grid you can see your custom controls properties.


Wednesday 1 December 2010

Calling Methods using Named Parameters using C# 4.0

Another new feature added to .Net 4.0 is to call methods using named parameters. This is very handy when calling a method which has optional arguments (You can use this to call other methods which consist of non optional parameters too). We’ll consider the following method.

static void SampleMethod(string ar1, 
string ar2 = "",
string ar3 = "",
string ar4 = "",
string ar5 = "",
string ar6 = "") {

//Some logic..

And assume that we only need to pass a value only to the last parameter. If the named parameter method was not there, the way to call the method would be something like this:

SampleMethod("message", "", "", "", "", "Hello World!");

But instead we can call the method using the following syntax.

ar1: "message",
ar6: "Hello World!");

And you will get the following output:


Defining Optional Parameters for Methods using C# 4.0

The ability to create methods or functions with optional parameters/arguments was there in VB 6.0. How ever it was taken away when .Net came into action. And it was not there in earlier versions. But now it's available again in framework version 4.0.

Assume you have a method called "Greeting" which defines a single optional parameter:

static void Greeting(string message, string user = "Guest") {
Console.WriteLine(message + ", {0}",user);


So when the method is called by passing a value only to the first parameter, the default value of "Guest" will be assigned to the second argument. And you will get the following output.




And when the method is called passing parameters to both arguments, you will get the following output.



Thursday 25 November 2010

Disabling tab pages on a Tab Control

Sometimes there can be a requirement, which we have to prevent users from accessing certain tab pages on a tab control. But there’s no straight forward method provided on the Visual Studio IDE (2005,2008 or 2010). But we can do that easily.

Add a tab control to your windows application. (tabControl1)

Add few tabs and few controls to each tab.


Now we’ll disable one tab using the following code on the form’s load event:

tabControl1.TabPages[2].Enabled = false;

** Please note : Though it does not list the ‘Enabled’ property on intellisense, it’s available.

Now if you run the application you can see, that all the controls in tab page 3 are dissabled.


But if we want to prevent from users accessing that tab, we can use this coding on tab controls selecting event (Not the page, but the control’s)

private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
if (!e.TabPage.Enabled)
e.Cancel = true;

Now if you run the application and try to select that tab page, you will not be able to do so..

Thursday 18 November 2010

Show an image saved in a SQL Table on an ASP.Net Image Control

In a previous entry I have shown, how to store images to a database table. Now I will show you how to retrieve it and show it on a ASP.Net Image control. There is no straight forward method showing it like “ImageControl.Image = ImageStream….” How ever it can be achieved using a Generic Handler.

Add a ‘Generic Handler’ to your ASP.Net web application. And in this example I will name it as ‘getImageFromDB.ashx’. By default IHttpHandler will be implemented. (ProcessRequest and IsReusable methods will be implemented). And I will add another method called ‘GetImage’ and alter the ‘ProcessRequest’ method. And the finished handler should similar to this:

   1: using System;
   2: using System.Drawing;
   3: using System.Drawing.Imaging;
   4: using System.IO;
   5: using System.Web;
   6: using System.Data;
   7: using System.Data.SqlClient;
   9: namespace MyWebApplication
  10: {
  12:     public class getImageFromDB : IHttpHandler
  13:     {
  14:         public void ProcessRequest(HttpContext context)
  15:         {
  16:             context.Response.Clear();
  18:             if (!String.IsNullOrEmpty(context.Request.QueryString["empID"]))
  19:             {
  20:                 int id = Int32.Parse(context.Request.QueryString["empID"]);
  22:                 Image image = GetImage(id);
  24:                 context.Response.ContentType = "image/jpeg";
  25:                 image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
  26:             }
  27:             else
  28:             {
  29:                 context.Response.ContentType = "text/html";
  30:                 context.Response.Write("<p>Need a valid id</p>");
  31:             }
  32:         }
  34:         public bool IsReusable
  35:         {
  36:             get
  37:             {
  38:                 return false;
  39:             }
  40:         }
  42:         private Image GetImage(int empID)
  43:         {
  45:             MemoryStream memoryStream = new MemoryStream();
  46:             //Retrieve image from Database to a memeory stream. If you are using a different method, use it and assign the data to the 'memoryStream' variable.
  48:             string connectionString = "Password=PWD;Persist Security Info=True;User ID=USER;Initial Catalog=SampleDatabase;Data Source=SQLSERVER";
  49:             using (SqlConnection sqlConnection = new SqlConnection(connectionString))
  50:             {
  51:                 using (SqlCommand sqlCommand = new SqlCommand("SELECT emp_id, emp_name, emp_image FROM Employee where emp_id = " + empID.ToString(), sqlConnection))
  52:                 {
  53:                     sqlConnection.Open();
  54:                     SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
  56:                     if (sqlDataReader.HasRows)
  57:                     {
  58:                         sqlDataReader.Read();
  59:                         byte[] btImage = (byte[])sqlDataReader["emp_image"];
  61:                         memoryStream = new MemoryStream(btImage, false);
  62:                     }
  63:                 }
  64:                 sqlConnection.Close();
  65:             }
  66:             return Image.FromStream(memoryStream);
  67:         }
  68:     }
  69: }

And you can call the handler and display the image, using the following syntax :

   1: private void GetImageFromDatabase(int empID)
   2: {
   3:     imageControl.ImageUrl = "getImageFromDB.ashx?empID=" + empID.ToString();
   4: }

Saving an image to a SQL Database Table

Sometimes it’s not the best of method, to store images in to the database, since it’ll take lot of database space. But there are times, that it’s the only option on your list.
To this sample I will be using the following SQL Table.
   1: CREATE TABLE [dbo].[Employee](
   2:     [emp_id] [int] NOT NULL,
   3:     [emp_name] [varchar](50) NOT NULL,
   4:     [emp_image] [image] NULL

When inserting data use the following syntax:

   1: string fileName = @"D:\MyImage.jpg";
   2: string connectionString = "Password=PWD;Persist Security Info=True;User ID=USER;Initial Catalog=DATABASE;Data Source=SQLSERVER";
   3: using (SqlConnection sqlConnection = new SqlConnection(connectionString))
   4: {
   6:     FileInfo finfo = new FileInfo(fileName);
   8:     byte[] btImage = new byte[finfo.Length];
   9:     FileStream fStream = finfo.OpenRead();
  11:     fStream.Read(btImage, 0, btImage.Length);
  12:     fStream.Close();
  15:     using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO Employee (emp_id, emp_name, emp_image) VALUES(@emp_id, @emp_name, @emp_image)", sqlConnection))
  16:     {
  18:         sqlCommand.Parameters.AddWithValue("@emp_id", 2);
  19:         sqlCommand.Parameters.AddWithValue("@emp_name", "Employee Name");
  20:         SqlParameter imageParameter = new SqlParameter("@emp_image", SqlDbType.Image);
  21:         imageParameter.Value = btImage;
  23:         sqlCommand.Parameters.Add(imageParameter);
  26:         sqlConnection.Open();
  27:         sqlCommand.ExecuteNonQuery();
  28:         sqlConnection.Close();
  29:     }
  31: }

Wednesday 17 November 2010

Changing App.config contents at runtime

Sometimes it is required to change the contents of ‘App.config’ file. Assume if we are allowing user to override things like taxrates, which we keep on the ‘App.config’.
On the App.config, we have a key ‘TaxRate’ which has the value ‘15’.
   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:     <appSettings>
   4:         <add key="TaxRate" value="15"/>
   5:     </appSettings>
   6: </configuration>

And we have to change it to ‘20’. We can use the following syntax:

   1: Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
   2: AppSettingsSection appSection = config.AppSettings;
   4: appSection.Settings["TaxRate"].Value = "20";
   5: config.Save(ConfigurationSaveMode.Modified,false);
   7: ConfigurationManager.RefreshSection("appSettings");
   8: string zVal = ConfigurationManager.AppSettings["TaxRate"];
**Please note : The changes are temporary, when running on debug mode. But will be permanent when run using the built application (Executable)

Monday 15 November 2010

Using FileSystemWatcher to monitor multiple directories

In a previous example I have showed how to use ‘FileSystemWatcher’ class to monitor a directory. But there are times that we need to monitor multiple directories and if any changes are available, invoke a given method.

We can do that by using this method. First create a class. We’ll call this class ‘Watcher’

   1: public class Watcher
   2:     {
   4:         public string Directory { get; set; }
   5:         public string  Filter { get; set; }
   8:         private Delegate _changeMethod;
  10:         public Delegate ChangeMethod
  11:         {
  12:             get { return _changeMethod; }
  13:             set { _changeMethod = value; }
  14:         }
  16:         FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
  18:         public Watcher(string directory, string filter, Delegate invokeMethod)
  19:         {
  20:             this._changeMethod = invokeMethod;
  21:             this.Directory = directory;
  22:             this.Filter = Filter;
  23:         }
  26:         public void StartWatch()
  27:         {
  30:             fileSystemWatcher.Filter = this.Filter;
  31:             fileSystemWatcher.Path = this.Directory;
  32:             fileSystemWatcher.EnableRaisingEvents = true;
  34:             fileSystemWatcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed);
  35:         }
  37:         void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
  38:         {
  39:             if (_changeMethod != null)
  40:             {
  41:                 _changeMethod.DynamicInvoke(sender, e);
  42:             }
  43:         }
  44:     }

And we can use it to monitor multiple directories as shown below (for this example I have used a console application and I am only considering the change event):

   1: class Program
   2:     {
   3:         delegate void invokeMethodDelegate(object sender, FileSystemEventArgs e);
   5:         static void Main(string[] args)
   6:         {
   8:             invokeMethodDelegate mymethod = new invokeMethodDelegate(InvokeMethod);
   9:             Watcher w1 = new Watcher(@"C:\Directory1", "*.*", mymethod);
  10:             w1.StartWatch();
  12:             Watcher w2 = new Watcher(@"D:\Directory2", "*.*", mymethod);
  13:             w2.StartWatch();
  15:             string zRetVal = Console.ReadLine();
  18:         }
  20:         static  void InvokeMethod(object sender, FileSystemEventArgs e)
  21:         {
  22:             Console.WriteLine("Change in file {0}", e.FullPath);
  23:         }
  24:     }