Wednesday, December 31, 2003

Last post of the year ...

Hi Readers, its just 15 days since I started this blog and as of now there are 300+ visitors from 10+ different countries (India, USA, Kuwait, Italy, Singapore, Canada, Russia, Sweden, Yugoslavia, United kingdom and Malaysia.). I am really impressed by the response :)

I would like to take this opportunity to wish you ALL a very HAPPY NEW YEAR. May all your dreams come true in the near future.

Preventing simultaneous logons to a website

Long time I was dreaming of my article being published in Microsoft site. That dream has come true now. Check my article on "Preventing simultaneous logons to a website" in Microsoft's site :) As usual feedback are most welcome.

Monday, December 29, 2003

Query to display Null values at the bottom ...

Let us assume that a table has following records in it:

Sno, FirstName
1, NULL
2, 'Vadivel'
3, 'Sachin'
4, NULL

If we write a select statement as follows

Select * from sampleTable
Order by FirstName


The result would be:

Sno, FirstName
1, NULL
4, NULL
3, 'Sachin'
2, 'Vadivel'

If you want to push all the NULL values to the bottom of the result then use the below the query.

Select * from sampleTable
Order by
 Case
   When FirstName Is Null Then 1
 Else 0
 End,
FirstName

Verbatim ...

C# supports 2 forms of string literals. They are, regular string literals and Verbatim string literals. Verbatim string literals begin with @" and end with the matching quote.

For instance,

strSample = @"F:\sample.xls"; is equivalent to strSample = "F:\\sample.xls";

Sunday, December 28, 2003

Researchers find serious vulnerability in Linux Kernel ...

Security professionals took note of a critical new vulnerability in the Linux kernel that could enable an attacker to gain root access to a vulnerable machine and take complete control of it. An unknown cracker recently used this weakness to compromise several of the Debian Project's servers, which led to the discovery of the new vulnerability. Find more about that interesting :) article here

Alternate rows ...

Sometime back in a user group a guy enquired "how to fetch alternate rows from a SQL Server table"?

As all of us know there isn't any direct method of doing it in SQL Server. So let me explain couple of work arounds for this.

Using Table Variables

Declare @tmpTable table
(
 [RowNum] int identity,
 [au_id] varchar(50) NOT NULL ,
 [au_lname] [varchar] (40),
 [au_fname] [varchar] (20),
 [phone] [char] (12)
)

-- Filling the row number column of the table variable
Insert into @tmpTable select au_id,au_lname, au_fname, phone from authors

-- Fetching the alternate records from the table.
Select * from @tmpTable where RowNum % 2 <> 0

Using Temp Tables

-- Filling the row number column of the temp table
Select IDENTITY(int, 1,1) RowNum, au_id,au_lname, au_fname, phone INTO #tmpTable from authors

-- Fetching the alternate records from the table.
Select * from #tmpTable where RowNum % 2 <> 0

Obviously we could solve this using many other methods like using cursors, using user defined functions etc., Just think about performance hit before choosing a method.

HTTP compression utility

If your sites uses large amounts of bandwidth consider enabling HTTP compression in your IIS. This feature is available from IIS 5.0 onwards. It compresses web pages and content that is downloaded to a browser running on an end users computer and decompresses it on the fly.

The server first determines if the end user has a compatible browser (IE 4+, Netscape 4+ etc.,). If the browser is compatible, it then pushes down a compressed version of the page to the client. The customers browser then decompresses the file and displays it.

I need to admit that I haven't tried it yet but have read that the feature provided by IIS itself called gzip isn't that stable :( Many say that pipeboost gives us better and reliable functionality.

BTW, do you know that google encodes its content and their pages are tiny?

Metabase ...

Are you one among the guys who think Apache is powerful because it is configurable using a config file? then I suggest you to learn about IIS "MetaBase". For your information we can do almost anything we want with IIS by editing the MetaBase!!

For instance, we can create virtual directories, stop/ start / pause websites etc.,

Microsoft provides a GUI utility called MetaEdit, which is somewhat similar to RegEdit, to help you read from and write to the MetaBase.

To take full advantage of the MetaBase try out the command-line tool, called the IIS Administration Script Utility (adsutil.vbs) which can be found @ C:\inetpub\adminscripts, or system32\inetsrv\adminsamples. This folder would have lots of other useful administrative scripts as well.

That said, the MetaBase is crucial for the functioning of IIS server, so ALWAYS take a backup first before fiddling with it :)

Saturday, December 27, 2003

Friday, December 26, 2003

Logging tool ...

Log4net is a good open source logging tool for .NET. Its framework has been implemented in C# and has been developed to run in the .NET Runtime. I suggest everyone to have a look at it here.

Some good tools for .NET !!!

I got this link from Lutz Roeder's blog. This link lists some of the Tools and source codes for .NET, C# and Visual Basic. Its worth having a look at it.

language comparison of C# with Java/C++ ...

A good feature-wise language comparison of C# with Java/C++ is here.

Navigation ...

Some of us are still using Response.Redirect in wrong places!! In order to get a good idea about different navigation techniques!! in ASP.NET do check this article.

Wednesday, December 24, 2003

Merry Christmas ...

One shining star to make the world bright,
one infant child of that wonderful night,
one little prayer for those we hold dear,
to bless you @ Christmas
and may the peace and joy of the
holiday season be with you all
throughout the coming year.....


(its December 24, 10:35 PM here in India)

C# Refactory ...

C# Refactory is a new tool which enhances VS.NET IDE. Full integration with the IDE allows for quick-access to important refactorings such as Extract Method - simply highlight the code you want to move, then invoke the Refactoring interface to quickly and reliably re-shape your code.

1. Provides useful refactorings.
2. Reliably improves code design.
3. Increases individual and team productivity.
4. Improves the quality of the application development process.
5. Removes the time-consuming and error-prone task of rewriting or refactoring by hand.

Download the evaluation copy here and test it for yourself :)

Running number !!

This is one of the question a senior DBA asked me in an interview. Let me explain the question which is really interesting (at least for me :) )

Sample table: Table1
ID, Name
1, aaa
2, aaa
3, aaa

Sample table: Table2
ID, Name
Null, bbb
Null, bbb
Null, bbb

Required result
ID, Name
1, aaa
2, aaa
3, aaa
4, bbb
5, bbb
6, bbb

Hmm actually as I was then a Project leader I have lost touch with code :) so it took some time before I answered him properly. At last the query which I wrote is as follows:

Select a.[ID], a.[Name] from Table1 a
  Union
   select distinct a.[ID] + (Select max(ID) from Table1), b.[Name] from Table1 a, Table2 b
order by a.[ID]

Microsoft thinks green ...

Check this eweek article about Microsoft's next generation of business applications, code-named Project Green

Converting a project from VS.NET 2003 to VS.NET 2002

Couple of months back I wrote an visual studio .Net tip in techtarget.com. If you want to know the easiest way for converting a VS.NET 2003 application to VS.NET 2002 then check that here.

Doing case sensitive searches

As we know, by default SQL Server installation (6.5/7/0/2K) is case insensitive. What does that mean? The DB would consider the string "VADIVEL" & "vadivel" as same. Perfect! But what if we want to do a case sensitive search in a database. i.e., we want to search for a string "SMART" (Note all characters should be capitals/upper case).

If we do a normal select query as shown below it won't work because as said earlier SQL Server installation by default is case insensitive

Select *
from testTable
where testField = 'SMART'


In order to overcome this situation, we need to select binary sort order (or) collation while installing SQL Server. After that one way is we need to convert the strings into binary and then compare. Since, 'S' and 's' have different ASCII values, when you convert them to binary, the binary representations wouldn't match and you could get case sensitive results.

For example,

Select *
from testTable
where cast ( testField as varbinary(25)) = cast('SMART' as varbinary(25))


Though the above query solves our purpose as far as performance (!) is concerned it wouldn't make use of Index (if we have one on the field testField) as our column name is within a function "CAST". Here I have added redundant :-) testField column so the optimizer would check for indexed values for testField before entering the Cast function

Select * from testTable
where testField = 'SMART'
and
cast(testField as varbinary(25)) = cast('SMART' as varbinary(25))

Another way of searching for case-sensitive data is by using Binary_Sum() function. For example,

Select * from testTable
where testField = 'SMART' and
binary_checksum(testField) = binary_checksum('SMART')

Tuesday, December 23, 2003

Easiest way to add comments to your SQL 2k code ...

If you are using SQL Server (2K) Query Analyzer to create your Stored procedure / Function / View / Trigger etc., then probably the below tip (!!!) might be of use to you. This would be particularly useful to maintain uniformity in commenting the code when more than one developer is working on a project.

Step 1: Create a comment template something like the one I have shown below:

/**********************************************************************************************
Name             : Name of the SP/Function/View/etc., comes here
Parameters    : Details about the parameters should come here.

Description     : Give a detailed description about the procedure here

Developer      : M. Vadivel (Put your name here :) )
Created Date : Date on which the procedure is created comes here

Change History:-

Modified By:     Modified Date:

Test Script  : Sample execution script would come here. For example, Execute GetDataFromEmployee '10'
**********************************************************************************************/


Step 2: Save it as a file with an extension .tql @ ....\Microsoft sql server\80\tools\templates\SQL Query Analyzer

Step 3: So from now on you just need to press "CTRL" + "SHIFT" + "INSERT" and select the .tql file which you have created.

Easy isn't it?

MSDN presentations archive ....

"ALL" MSDN Yatra and technical session presentations starting from September 2000 to till date can be downloaded here. The best part is from this month they are hosting the demo's as well :)

Code conversion tool ...

Want to convert C# code to VB.NET?
Want to convert VB.NET code to C#?
Want to have a stored proc builder?

Just click here :)

Monday, December 22, 2003

Code Correctness with FxCop

Check out the video wherein, Michael Murray and Jeffrey Van Gogh from the CLR Team describe FxCop, the freely-available code analysis tool from Microsoft, and talk about what the tool is for and how it works. They also show how FxCop is applied to a typical code example.

Controlling the display of page numbers in a DataGrid ...

The DataGrid control contains built-in functionality to display its contents in pages. The number of items on the page is determined by the PageSize property. If no value is specified for the PageSize property, the DataGrid control displays 10 items on the page by default.

As the DataGrid would be dynamically populated, there is always the possibility of the number of records fetched to be less than the PageSize value. The DataGrid would then display the page number "1" by itself below the DataGrid. How would we avoid that is the question? Check out my article regarding this (which I wrote sometime in 2002) for further details.

A Small HTML file using Microsoft Agent

<Html>
<Head>
 <Title>X-Mas Greetings ...Designed and Developed by M. Vadivel </Title>
</Head>
<Body bgcolor=black>
<!--
Sets or retrieves the URL of the component. If the value for version is set as -1 the component is downloaded from the server if the release date is later than the installation date on the client computer. If the compnent is installed on the client computer and the release date is the same or earlier than the installation date only an HTTP header transaction occurs.

The below line would take care of installing the agent control and the TTS engine if it is not already present in the end
user PC
-->

<OBJECT ID="AgentControl" width=0 height=0 CLASSID="CLSID:D45FD31B-5C6E-11D1-9EC1-00C04FD7081F" CODEBASE="#VERSION=2,0,0,0">
</OBJECT>

<OBJECT ID="TruVoice" width=0 height=0 CLASSID="CLSID:B8F2846E-CE36-11D0-AC83-00C04FD97575" CODEBASE="#VERSION=6,0,0,0">
</OBJECT>

<Script language=VBScript>
Dim Genie
Sub window_OnLoad
  AgentControl.Connected = True ' needed for IE3
  AgentControl.Characters.Load "Genie", "http://agent.microsoft.com/agent2/chars/genie/genie.acf"
  Set Genie = AgentControl.Characters("Genie")
  Genie.LanguageID = &H0409 ' needed under some conditions (English)
  Genie.Get "state", "Showing, Speaking"
  Genie.Get "animation", "DoMagic2, DoMagic2Return"
  Genie.Show
  Genie.Get "state", "Hiding"

  Genie.Play "DoMagic2"
  Genie.Speak "Dear friends Merry Chrismas."
End Sub
</Script>

</Body>
</Html>

Till the above line save it as a HTML file. On firing that HTML you could see the Genie in action :)

There are lots of animation effects which comes along with Genie (BTW there are lots of other character as well like Merlin, Robbie, Peddy etc., You know what? we can create our own Character as well). Some of the other animations which I used while preparing a diwali greetings are as follows:

1. "Announce, AnnounceReturn"
2. "Explain, ExplainReturn"
3. "Pleased, PleasedReturn"
4. "Suggest, SuggestReturn"
5. "Think, ThinkReturn"
6. "Process, ProcessReturn"
7. "DoMagic1, DoMagic1Return"
8. "Wave, WaveReturn"

The complete list of possible animations of Genie is here. For creating your own character check this.

But when I was developing the application I wasn't aware about these links, so I downloaded the Character (Genie) and referenced it in a Visual Basic application and from it I got all the animation effects :) If anyone needs that diwali greetings which I developed using this Agent control do get in touch with me.

Sunday, December 21, 2003

Purpose of Idispatch interface ...

In yesterday's post (About IUNKnown interface ...), I discussed about Adodb.Recordset object creation, in which I invoked 2 methods namely Open and Close correct? when I call these 2 functions what is the background process going on is what I am going to address now.

When a function or a property of an object is called, the background execution is been carried out by an interface called Idispatch interface. It consists of 4 functions names:

1. GetTypeInfoCount: This determines whether the function or property is having any parameter or not.

2. GetTypeInfo: This not only determines the function names but a detailed collection of what are the parameters passed and what are its datatype and what is its return value, whether it is an IN parameter or OUT parameter etc.,

3. GetIDSofName: This determines the unique id given for each function or property of an object. The ID associated with each and every function or property of an object is called Idispatch ID.

4. Invoke: This is the one which does the job. This collects all the information acquired namely the number of parameters, its datatype and then identifies the function based on its ID and execute the function to return the result.

Let me now switch to the example discussed in the yesterday's post. I was calling OPEN method in that, now what happens is

A. First GetIdsofName will fire accepting the OPEN keyword as its parameter and it retreives the corresponding ID of OPEN method.

B. Then, GetTypeInfoCount will determine whether there are any parameters for this OPEN method.

C. Then, GetTypeInfo will collect all the parameters required for the OPEN method, namely the Query, Connection string, Lock, cursor type etc.,

D. Now the invoke method will execute the functionality with all its relevant collected values.

Thats it :) This is what happening internally when we call a method or a function.

Exe Vs Dll ...

"First we need to be clear that both "exe" and "dll" are fundamentally the same but the difference lies in how windows interacts with them. "

When windows loads a dll, it runs the initialization code and then leaves it alone. Functions in the dll are called if they are explicitly referenced by an application. Another thing, when dll gets crashed it not only crashes itself but also the application as the dll runs in the memory of the parent application.

When windows load an exe, the exe's initialization code is responsible for creating what is called as "message pump", nothing but a program loop which runs as long as the application is running. The message pump request messages from the operating system. Windows keep track of the application as a separate task. It allocates separate memory for both the exe and the application using that exe. The memory area in which each exe runs is called "Process Space".

Saturday, December 20, 2003

An Interview with Jerry Weissman

An interview with Jerry Weissman founder of Power Presentations, Ltd. by Geetesh Bajaj (a MVP in PowerPoint) can be read here. FYI, Mr. Weissman is the author of the bestselling book, 'Presenting to Win: the Art of Telling Your Story' (Financial Times/ Prentice Hall 2003)


About IUNKnown interface ...

I think this is one of the very common questions in many UG's and interviews. Thought I would share my knowledge about this topic here.

The data present inside the COM objects are manipulated by means of functions or properties called Interfaces. For example, a Textbox is a COM object and its values is been accessed by an interface called "Text" property. Got it ...

Every object when declared, will internally call one interface called, IUNKnown interface. This is applicable for all COM objects. Don't worry lemme simulate this with an example.

As I told interfaces means it will have some functions or properties this IUNKnown interface also contains some 3 important functions. They are:

A. AddRef: A counter is maintained internally of how many times we are declaring or instancising one object. This AddRef method would increment the counter by one.

B. Release: This is a method which will reduce the counter by one. This will normally get fired when we set the object as nothing.

C. Query Interface: Most important one. This only will determine what are the functions or properties available for the object. i.e., when we type "text1" in VB program we are listed with all the properties and methods of a text box control, correct, this query interface only is responsible for getting all those properties and functions for that text box control.

Code snippet:

1. Set mail = createobject("adodb.recordset")
2. mail.open "select * from table",cnproject,1,3,1
3. mail.close
4. Set mail = nothing


This is a very simple example of declaring our ADO recordset. Here when we declare the record, i.e., Point 1, the AddRef will get fired, incrementing the counter to one. When we execute the Point 4, the Release function will get fired making the counter to get decremented by one. When we type "mail" as in Point 2 and 3, we are listed with functions namely Open and Close. These methods are identified and isplayed to the user by means of Query interface.

Hope I haven't confused anybody with this explanation :)

Friday, December 19, 2003

Windows Service in .NET

IMO this is a good on-line tutorial about Windows services.

Extract from that tutorial:

Windows Services, formerly NT Services, were introduced as a part of the Windows NT operating system. They are not available on Windows 9x and Windows Me. You need to use one of the operating systems in the NT generation such as Windows NT, Windows 2000 Professional, or Windows 2000 Server to run a Windows Service. Examples of Windows Services are server products such as Microsoft Exchange, SQL Server, and other applications such as Windows Time that sets the computer clock.

Session timeout

Check this tip (which i wrote) on session timeout limit which we can set in a web.config file.

Size limit while uploading files ...

Couple of weeks back, one of my friend who was working on a file upload page told me that his page throws an exception when a *huge* file is uploaded. Hope many of us would have faced similar situation previously!!!

The default limit in the size of file upload is 4 MB. This default setting can be overridden by making some minor changes to our Machine.config. In the configuration file we need to change the value for the attribute "MaxRequestLength" in the section "httpRuntime".

By default httpRuntime section in machine.config would look as follows:


<httpRuntime
  executionTimeout="90"
  maxRequestLength="4096"
  useFullyQualifiedRedirectUrl="false"
  minFreeThreads="8"
  minLocalRequestFreeThreads="4"
  appRequestQueueLimit="100"
  enableVersionHeader="true"
/>


Here, change the value of "maxRequestLength" as per your requirement. Beware from now on machine wide the new value would be the default limit for all ASP.NET application.

On the flip side, if you want the size limit to be changed for a particular project then copying that section from machine.config and pasting it in web.config would do the trick.

Listing records from 10 to 15 (for ex) without using where clause

The below query lists the records from 10 to 15 from a table. The logic is we need to fetch the first 15 records from the table then take the first 6 records within it in the DESCending order. Hope the logic is pretty straight forward!!

Select * From
    (
    Select TOP 6 * From -- (A1)
        (
            Select TOP 15 * from employeeTable order by Sno --- (A2)
        )
        as D1 ORDER BY Sno DESC
    )
    as D2 ORDER BY Sno


Let us assume that the field sno has values from 1,2,3,4..... 20. Part "A2" in the above sample would fetch 1,2,3,4....15. Now check part "A1" it fetches the first 6 records from this result in DESCending order. So the result would be 10,11,12,13,14,15.

Thursday, December 18, 2003

Is sorting possible in Views?

As we all know, for sorting the values while fetching records we need to make use of ORDER BY clause.

That said, would the below code snippet work?


CREATE VIEW SampleView 
AS 
SELECT Sno, Firstname 
FROM employeeTable 
ORDER BY Firstname
GO


Nope it won't!!!

The work around is, we need to use "TOP 100 PERCENT" in our query if we want to use ORDER BY clause in a View (or) a Subquery (or) a derived table. (BTW this is possible in SQL Server 7.0 and SQL Server 2000).

See below the modified code snippet:


CREATE VIEW SampleView 
AS 
SELECT 
TOP 100 PERCENT Sno, 
Firstname
FROM
employeeTable 
ORDER BY Firstname
Pals, I am M. Vadivel (from India) a MVP in ASP/ASP.NET. I am into IT field since '97 and have a decent experience in client server and web technologies. I am actually thrilled to receive couple of awards from Microsoft this year (Microsoft India Community Star and MVP).

Offlate I wanna create a blog and share the little knowledge which I have on Microsoft technologies. This is the first step towards that.

Other than computers I love cricket very much and am a great fan of Master blaster Sachin Tendulkar :)