Structs….. A light-weight Class

In C# Structs are a lot like classes. Both expose variables, properties and constructors. Both are used to organize data or a common type that organizes your code. There are some differences between the two. For one, Structs are value types while Classes are reference types. What does this mean? Well value types hold their value in memory where they are declared while reference types store an object in memory and then holds a reference to that object. So it’s like a reference pointer. Unfortunately this is less efficient.

If you copy a Struct, a new Struct instance is created while if you copy a class, C# creates a new copy of the reference to the object and assigns the copy of the reference to the separate class instance.

Structs are not as robust as classes however. For example, they do not support inheritance and they do not support destructors. Having said that though, they should be used whenever possible as they are an efficient alternative.

Here is a very simple Struct:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            employee emp = new employee();
            emp.Age = 45;
            emp.Lastname = "Gaut";
            emp.Firstname = "Samuel";
            Console.WriteLine("Employee: ");
            Console.WriteLine("Age: " + emp.Age);
            Console.WriteLine("LastName: " + emp.Lastname);
            Console.WriteLine("Firstname: " + emp.Firstname);
            Console.WriteLine("-------------------------------");
            Console.ReadLine();
        }
    }

//HERE IS THE STRUCT

    struct employee
    {
        private int _age;
        private string _lastname;
        private string _firstname;

        public int Age
        {  get { return _age; } set { _age = value; } }

        public string Lastname
        { get { return _lastname; } set { _lastname = value; } }

        public string Firstname
        { get { return _firstname; } set { _firstname = value; } }

    }
}

Structs also support overloaded Constructors where you can pass in values and initialize struct members.

Here is an overloaded constructor defined for the Struct:

public employee(int age, string ln, string fn)
{
    _age = age;
    _lastname = ln;
    _firstname = fn;
}

  • Share/Bookmark

Using ADO.NET DataTable.Load() method

The ADO.NET DataTable supports a Load() method that will fill a datatable from a datasource using the IDataReader.The good thing about this is that if your datatable already contains data, the new data can be merged with the existing tables datarows.

The Load option supports the following 3 enumerations:

PreserveChanges is the default and states that it will update the existing value of the row with the new data being loaded (if it already exists).

OverwriteChanges – Updates the current and original versions of the row with the value of the incoming row.

Upsert – Updates the current and original versions of the row with the value of the incoming row.

I have a method within a .aspx page that checks the Cache for a datatable. If the table is not in the Cache, it will be loaded and put into the Cache.. In it’s simplest terms, the Load() method looks as follows:

private DataTable CheckCacheForCustomers()
{
DataTable _customers = null;
_customers = (DataTable)Cache["Customers"];

if (_customers != null)
return _customers;

using(SqlConnection conn = new SqlConnection(connectstring))
{
try
{
conn.Open();
string _sql = “Select * from Customers”;
using (SqlCommand command = new SqlCommand(_sql, conn))
{
IDataReader reader = command.ExecuteReader();
_customers = new DataTable();
_customers.Load(reader);
Cache["Customers"] = _customers;
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
return _customers;
}

Notice the code:
IDataReader reader = command.ExecuteReader();
_customers = new DataTable();
_customers.Load(reader);

  • Share/Bookmark

LINQ Queries against Cached ADO.NET DataTable

LINQ (Language-Integrated Query) is newly added to VS 2008 .NET 3.5 that extends the query capabilities while letting developers write queries using C# (or VB.NET) syntax. It utilizes standardized easy to learn for querying and updating data. Linq is great for ORM and basically supports the coupling of objects and data. Linq makes a query a first class language construct in C# or VB.

A typical Linq query will consist of 3 parts: Obtaining the datasource, Creating the query and executing the query.

I’m going to define a string array with 10 names. I’ll build a very simple query against this string array.

string[] _names = new string[10]
{“John”, “Jason”, “Jimmy”, “Tony”, “Thomas”,
“Timmy”, “Larry”, “Lee”, “Livingston”, “Lucas”};

Here is the Linq Query

var _nameQuery = from _name in _names
select _name;

foreach (var _name in _nameQuery)
{
Response.Write(_name.ToString());
}

This should output all 10 names to the screen.

This query could be changed to filter the output results fairly easily as follows:

var _nameQuery = from _name in _names
where _name.StartsWith(“J”)
select _name;

This query should output “John”, “Jason”, and “Jimmy” because we only want names that start with ‘J’.

Here is another query in a method that is written against a Cached Datatable, the Customers from Northwind.

Customers customers = (Customers)Cache["customers"];                                                   

var importQuery = from emp in customers.AsEnumerable()
select new
{
    CustomerID = emp.Field("CustomerID")
};

foreach (var emp in importQuery)
{
    Response.Write(emp.CustomerID.ToString());
}


Here is another query against the same Cached datatable that will be bound to a dropdownlist control.

private void BindDropdownList()
{
  Customers customers = (Customers)Cache["customers"];
  try
  {
      this.DropDownList1.DataSource = (from emp in customers.AsEnumerable()
      where emp.Field("CustomerID").StartsWith("A")
      select new
      {
           CustomerID   = emp.Field("CustomerID"),
           CompanyName  = emp.Field("CompanyName")

      });
      this.DropDownList1.DataTextField  = "CompanyName";
      this.DropDownList1.DataValueField = "CustomerID";

      this.DropDownList1.DataBind();
 }
 catch (Exception ex)
 {
     Response.Write(ex.Message.ToString());
  }
}

  • Share/Bookmark

How To Implement IDisposable Interface

The IDisposable Interface exposes the Dispose method which must be implemented by any class that inherits this Interface. It should be used to release any un-managed resources of an object that have been initialized, like Database connections, handles, streams and files. You should also call GC.SuppressFinalize. This will keep your object from landing on the .NET finalization queue. When you land on this queue, you really do not know when your resources will be released by the Garbage Collection.

Here is a sample class that inherits IDisposable:

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

using System.IO;
using System.Globalization;
using System.Diagnostics;

namespace CallIdisposable
{
   class clsDisposable : IDisposable
   {
       StreamReader reader = null;

       public clsDisposable() { }

       public void ReadFileStream(string _path)
       {
           if (!File.Exists(_path))
               throw new Exception("file not found");
           reader = new StreamReader(_path);
           string _record = string.Empty;
           while (_record != null)
           {
               _record = reader.ReadLine();
               if(_record != null)
                   Console.WriteLine(_record.ToString());
           }
       }
       public void Dispose()
       {
           reader.Dispose();
           //remove from the finalize queue.
           GC.SuppressFinalize(reader);
       }
   }
}

Call the class

string path = @”C:\Users\sam\Documents\SQL\employees.dat”;
clsDisposable cd = new clsDisposable();
cd.ReadFileStream(path);
cd.Dispose();

  • Share/Bookmark

How To Use FindControl with Master Pages

How to modify a property of a control located in a Master Page from a content page by exposing a property from the Master Page. You have an alternative here. If you need to modify a control in a Master Page, you can use the FindControl() method in a content page.

ASPXMasterPage.master

<%@ Master Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<style type=”text/css”>
html
{
background-color:silver;
}
.content
{
margin:auto;
width:700px;
background-color:white;
padding:10px;
}
h1
{
border-bottom:solid 1px blue;
}
</style>
<title>Find Master</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div class=”content”>
<h1><asp:Literal ID=”ltlPageTitle” runat=”server” /></h1>
<asp:contentplaceholder id=”ContentPlaceHolder1” runat=”server” />
</div>
</form>
</body>
</html>

The content page modifies the Text property of the Literal control located in the Master Page. The content page uses the FindControl() method to retrieve the Literal control from the Master Page.

ASPXContent.aspx

<%@ Page Language=”C#” MasterPageFile=”~/ASPXMasterPage.master” %>
<script runat=”server”>
void Page_Load()
{
if (!Page.IsPostBack)
{
Literal ltlPageTitle = (Literal)Master.FindControl(“ltlPageTitle”);
ltlPageTitle.Text = “The Web Page Title”;
}
}
</script>
<asp:Content ID=”Content1” ContentPlaceHolderID=”ContentPlaceHolder1” Runat=”Server”> </asp:Content>

The FindControl() method enables you to search a naming container for a control with a particular ID. The method returns a reference to the control.

  • Share/Bookmark

How To Load Master Pages Dynamically in ASP.Net

Associate different Master Pages dynamically with a content page.

In your website you can enable the users to customize the appearance of the website by loading different Master Pages and allow your users to pick their favorite layout.

You can maintain this illusion by dynamically loading different Master Pages based on a query string passed from a partner website.
A Master Page is merged with a content page very early in the page execution life-cycle. This means that you cannot dynamically load a Master Page during the Page Load event.
The only event during which you can load a Master Page is during the Page PreInit event. This is the first event that is raised during the page execution life cycle.

<%@ Page Language=”C#” MasterPageFile=”~/LoadDynamicFirst.master” %>
<script runat=”server”>
protected void Page_PreInit(object sender, EventArgs e)
{
if (Request[“master”] != null)
{
switch (Request[“master”])
{

case “LoadDynamicFirst”:
Profile.MasterPageFile = “LoadDynamicFirst.master”;
break;
case “LoadDynamicSecond”:
Profile.MasterPageFile = “LoadDynamicSecond.master”;
break;
}
}
MasterPageFile = Profile.MasterPageFile;
}
</script>
<asp:Content
ID=”Content1” ContentPlaceHolderID=”ContentPlaceHolder1” Runat=”Server”>
Select a Master Page:
<ul class=”selectMaster”>
<li><a href=”DynamicContent.aspx?master=LoadDynamicFirst”>Load LoadDynamicFirst</a></li>
<li><a href=”DynamicContent.aspx?master=LoadDynamicSecond”>Load LoadDynamicSecond</a></li>
</ul>
</asp:Content>

Both links include a query string parameter named master, which represents the name of a Master Page. When you click the first link, the LoadDynamicFirst.master Master Page is loaded and when you click the second link, the LoadDynamicSecond.master Master Page is loaded.
The page includes a Page_PreInit() event handler. This handler grabs the value of the master query string parameter and assigns the value of this parameter to a Profile property.

Web.Config

<configuration>
<system.web>
<profile>
<properties>
<add name=”MasterPageFile” defaultValue=”LoadDynamicFirst.master” />
</properties>
</profile>
</system.web>
</configuration>

  • Share/Bookmark

How to Disable flash plugin in Firefox

Firefox makes it very easy to disable any browser plugin. Simply go to Tools->Add-ons->Plugins. Select “Shockwave Flash” from the list of plugins and click the disable button.

  • Share/Bookmark

How to clear dropdown items using JQuery

We can use the following method to remove dropdown items using query

$("select[id$=ddlPeople] > option").remove();

  • Share/Bookmark

How To Create a Windows Service using VB.NET

Introduction

Microsoft introduced long running background application called Services along with Windows NT Operating System. These services are multithreaded. Writing a windows NT Service using VB 6 was a tedious job. However, VB.NET masks the task much easy. In this article I will show you how to create a simple Windows Service using VB.NET

Overview of Services

Windows service is a background process that performs certain task. You can start, stop, pause or resume services on remote and local computers. Windows also provide option to enable or disable a service. Objective of Windows service is to run application in the background in certain period even though machine is busy with other process or work. You can also set a user account that a service will use to log on.

Is Windows NT Service having an advantage over application running under Windows Scheduler?

As mentioned earlier, windows services are used to do certain task on regular intervals. Is this can be achieved by other way? Actually Yes. You can create an application for performing your task. Using windows scheduler you can call this application at regular intervals. What is the advantage of implementing Windows Service then? Normally windows services will not have a user interface. Windows services runs efficiently because of its own process. To start windows Scheduler, one of the user has to log on to system. Whereas Windows service can automatically started when system boots.

Creating a simple windows service

Before we start developing windows service one thing you have to remember. You can deploy the service only on OS that has NT based architecture. If you are working in Visual Studio .Net, you can see a windows service template on new project dialog. You have to code very less to test this simple windows service if you are using VS.NET. In this article we are going to create a simple windows service which will monitor a specific folder on the disk. If any file is renamed, created, modified or deleted, service will keep its track in the system log.

Open your VS.NET and select windows service project and enter the name folderSPY and click ok. Double click the design form or Press Shift + F7. On the top section of code window, enter the following:

Imports System.IO
Public folderToWatch as fileSystemWatcher

On the OnStart procedure type the following

Dim strSysDir As String
folderToWatch = new fileSystemWatcher()

To watch system directory

strSysDir = System.Enviroment.SystemDirectory()

Set the path of the folder which you want to watch. Here our service is watching WINNT folder.

folderToWatch.path = strSysDir

To monitor above mentioned folder, you have to set certain filters.

With folderToWatch
	.notifyFilter = .notifyFilter
				OR notifyFilters.FileName
	.notifyFilter = .notifyFilter
				OR notifyFilters.Attributes
	'To watch sub directories....
	 .includeSubDirectories = True
End With

How to know whether any user changed the file name or file attributes?

To know this you need handlers. Following code will explain this.

AddHandler folderToWatch.Created, Addressof newLog
AddHandler folderToWatch.Deleted, Addressof newLog
folderToWatch.enableRaisingEvent = True

Next, write a sub procedure called newLog.

Private Sub newLog(byVal Source as Object,
byVal evt as FileSystemEventArgs)
	If evt.ChangeType = WatcherChangeTypes.Created Then
		writeToLog(evt.fullPath,"Created")
	else if evt.ChangeType = WatcherChangeTypes.Deleted
  		writeToLog(evt.fullPath,"Deleted")
	End if
End Sub

Private Sub writeToLog(byVal filePath as String,
byVal fileManip as String)
	Dim evtLog as new EventLog()
	If not evtLog.sourceExists("folderSPY") then
		evtLog.createEventSource
		("folderSPY", "Log of folderSPY")
	End if
	evtLog.source = "folderSPY"
	evtLog.writeEntry
	("Folder spy Log", "File "  & filePath & " has "
	& fileManip &  " by " & Environment.UserName.ToString,
	EventLogEntryType.Information)
End Sub

Installing the folderSPY windows service

The application that we have created is ready to test. Since it is not a traditional windows executable, you need to install it on your machine by special way. .NET Framework ships with InstallUtil.exe command line tool that installs the windows service on your machine. Before using this tool, however, we have to add an installer toy your project. This can done by right clicking your design screen and select add installer option from the menu. After you do that, you can see two more controls called ServiceProcessInstaller1 and ServiceInstaller1 added to your screen. To Change the display name of the service, open the ServiceInstaller1 control’s property window and change the ServiceName property and Display name property to folderSPY (This is the service name we have given).

Since we are going to run our application on the local machine, set the account property of the ServiceProcessInstaller1 to LocalSystem. To make your service pause and continue, set the CanPauseandContinue property of your service to true. Now, compile the folderSPY application and run following command from Command Prompt:

InstallUtil <Project Path>\BIN\folderSPY.exe

If you want to uninstall the service use:

InstallUtil /U \BIN\folderSPY.exe

Running the Service

If Startup property of the service is not set to Automatic, you have to start the service manually or through some other program. To start the service open Services snap-in from the Control panel. Right click on the folderSPY service and click start.

  • Share/Bookmark

“My” Objects of VB.NET

Introduction

The VB.NET Version 2.0 as well as C# version 2.0 contains many new enhancements to the core language. One of the new cool feature added to VB.NET is “My” objects. My objects is a set of objects that are implicitly available to your application which provide short cut to many tasks otherwise seem tedious. For example, to know details about the computer on which the application is running such as name, memory, clock and network  you have My.Computer object. No need to look anywhere else. All the necessary information is available at a single place! In all there are seven My objects and this article is going to give you peek into some of them.

“My” Namespace

VB.NET 2.0 provides a namespace called “My” (Me, MyBase, MyClass and now My…hmm…what next?). This namespacfe provides seven implecit objects to your application. The following table lists all of them:

Object Purpose
My.Computer Gives information about your computer such as its name, memory, clock, network details and so on.
My.Application Gives information about the current application such as path, assembly information (name, version etc.) and environmental variables
My.User Gives information about the current Windows user such as user name. Also, allows to check if user belongs to a specific role.
My.Forms Gives reference to all the forms from a project. (I am sure VB6 developers are going to like this feature a lot)
My.WebServices Gives access to proxy classes of the web services being used
My.Settings Allows to read or store application configuration settings
My.Resources Allows to read resources used by the application.

Example

As an example we are going to develop a Windows Forms application as shown in the following figure:

Here, we are displaying information about the computer, application and the user. We are also using an embedded resource. Displaying information about computer, application and user is straightforward. In order to retrieve embedded resource you must first add one to your application. In order to do so, double click on the Resources folder in the Solution Explorer. The interface of the resulting dialog is simple and you can easily embed image files using Add Resource toolbar option. Once you add required image file, rename the embedded resource as DotNetLogo. Finally, add the following lines of code to the Form_Load event:

Label2.Text = My.Computer.Name
Label4.Text = My.Computer.Network.IsAvailable
Label6.Text = My.Computer.Screen.DeviceName
Label8.Text = My.Computer.Clock.LocalTime
Label10.Text = My.Computer.Screen.Bounds.Width &
" X " & My.Computer.Screen.Bounds.Height

Label15.Text = My.Application.Info.DirectoryPath
Label16.Text = My.Application.IsNetworkDeployed
Label17.Text = My.Application.Info.AssemblyName
Label18.Text = My.Application.Info.Version.Major & "."
& My.Application.Info.Version.Minor & "."
& My.Application.Info.Version.Build & "."
& My.Application.Info.Version.Revision
Label19.Text = "Welcome " & My.User.Name & "!"
PictureBox1.Image = My.Resources.DotNetLogo

The code simply uses My.Computer, My.Application, My.User and My.Resources objects. That’s it! Run the application and see the power of “My” objects in action.

  • Share/Bookmark