Sunday, August 26, 2007

The difference of the LIKE SQL statements between MS Access and SQL Server

LIKE has been used widely in SQL Statements to filter or qualify certain records like this or that. The commonly used wild card characters in SQL Server are % and _, the former matches 0 or many characters; while the latter matches exactly one character. If you want to express NOT, you use ^.

If you copy and paste a SQL statement from SQL Server to MS Access with LIKE statement in it, you may not get exactly the same set of result. One of the reasons is the different symbols used in the LIKE statement.

In MS Access, * matches 0 or many characters; while ? matches extacly one. To express NOT, you use ! in MS Access.

One more note, if you want to match % or _ as is in LIKE statments in SQL Server, you will need to bracket them with a pair of square brackets [ and ]. Similarly, we need to squarely bracket * and ? to match them in the LIKE statements in MS Access.

Friday, August 24, 2007

How to search for files with specific contents on Windows XP/2003 Server

Microsoft Windows Explorer (or NT Explorer) has the search function to help us to search files with specific attributes. However, if we do not set the preference to our own likes, the default search preference may not be what everybody wants. The most significant one is whether to search files with unknown extensions, or even no extensions. The default setting is NO. That is why we can’t find files with the specific contents we are looking for, even though we know they are there. Please note that it does not have anything to do with turning on the Indexing Service or not.

To set the preference correctly, such that it will search for files with unknown extensions, we will have to (from Desktop):

Start --> Search --> Chang Preferences --> With(out) Indexing Services --> Change Indexing Service Settings (Advanced) --> (Indexing Services Console Shows) --> Right Click on the Console Window Screen --> Properties --> Check "Indexing Files with Unknown Extension" if unchecked --> OK

Please note that this preference may be "per user" not "per machine", so it is possible that whoever logged in will need to setup the preference him/herself.

Wednesday, August 22, 2007

How to use robocopy to mirror two folders

There are many cases that we need two or more folders to be synchronized, or replicated, or mirrored, for the purpose of load sharing, redundancy and backup. One obvious example is to help standalone DFS (Distributed File System) to replicate files among the redundant folders.

In Windows 2000 Resource Kit there is a command line utility called robocopy.exe. This program can synchronize the source and destination folders by deleting the deleted source files and only copying the newer files. It can also copy files recursively. Below is a simple batch file we can use to provide the simplest one-way mirroring:

net use \\host1\share1 password1 /USER:user1
net use \\host2\share2 password1 /USERS:user2
robocopy \\host1\share1 \\host2\share2 /MIR
net use \\host1\share1 /DELETE
net use \\host2\share2 /DELETE

Tuesday, August 21, 2007

Daylight Saving Time update for Linux Systems

Here is the information to manually update the timezone information for RedHat Fedora Core 4-6 and other Linux System, just in case your Fedora does not adjust the time zone information automatically (via Yum).

http://articles.techrepublic.com.com/5100-10877-6163042.html

The basic idea is to update the file /etc/localtime by the right file in tzdata package.

Daylight Saving Time Update for Windows 2000 Servers

Microsoft does not support Windows 2000 anymore and it shows this time, on the occation of daylight saving time change update - ony XP and Server 2003 were updated automatically.

If you are running Windows 2000 you will have to do a bit more work for the daylight saving time change. Microsoft has released KB article 914387 which outlines the process you must go to for the change. There are two methods by which you can change the time zone for Windows 2000 (Professional and Server). The first is to download the TZEdit tool from Microsoft. Once installed, you can run this tool (it installs by default to c:\Program Files\TZEdit\) to manually create and change your time zones. This method will require you to manually change every computer. While this is not a major task if you only have a few Windows 2000, it can be quite daunting if you have a large number of systems to update.

The second method provided by Microsoft for updating Windows 2000 is a combination of a registry edit and a VBS script. These are both available here, though you must copy the text for each of them and save them locally with the proper file extensions (.reg and .vbs respectively). You must then import the registry settings change (by double clicking the .reg file you created), then run the vbs script to perform the update. This process can easily be automated.

Microsoft provides steps to automate the process through group policy (by making a simple command file), but it can also be done using a batch file or another VB script. The only requirement again is that administrator privileges are used to run the files or the script created. This can be mitigated by using group policy to assign it as a startup or shutdown script for a computer not a user.

For further information, please checkout: http://articles.techrepublic.com.com/5100-10877_11-6161680.html

Friday, April 21, 2006

How to incorporate ZIP functions into Classic VB Applications

VB Script, or VB6, or VBA are still the dominating office automation languages. It is important to let them be able to use the ZIP utilities too. Please note that .NET Framework may not exist everywhere, so a "native" ZIP COM, not through InterOp, is needed under this condition. Fortunately there is one for VB.

InfoZIP’s Freeware ZIP32.dll and UnZIp32.dll can be wrapped with a library CGZipLibrary.dll. To be able to Zip/Unzip from VB, you will need to: Get these three libraries.

Copy zip32.dll and unzip32.dll to c:\windows\system32 directory or c:\winnt\system32.
Regsvr32 CGZipLibrary.dll

To test, get sample VB6 Project. The sample project will zip the files in current directory to c:\ziptest.dll. Be sure to add reference to CGIZipLibrary.dll before you run.

How to test AutoPlay CD

AutoPlay CD is useful, as it automatically execute the demo or installation program when you insert this CD into CD drive. It is a powerful marketing/IT tool.

The autoplay.inf file at the root folder of the CD ROM tells the System what to do when the CD is inserted.If the content of autoplay.inf is like:

[autorun] open=Filename.exe
icon=Filename.exe,1

Then the system will execute Filename.exe at the root of the CD. The iconized image of this drive will become the icon of FileName.exe too.

Below is the link of how to make Autoplay.inf file:
http://msdn.microsoft.com/library/?url=/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/autorun/autoplay_works.asp

Now, how do we test Autoplay CD ? Burn the CD time and test ? If something goes run then burn again ? That is terrible experience.

How about using USB drive to simulate the Insert action ? Well, Microsoft does not support USB Drive, as the Media Type declared by USB drive is not Removable Drive, which is supported, but is Removable Media, which is not supported.

Well, how about Network Drive ? Yes, you can create a folder called, say C:\AUTOPLAY and then share this folder to the network as, say, AUTOPLAY. When you map a drive, say K: from other machine, or even your own machine to AUTOPLAY, Autoplay.inf will be triggered. This approach saves time and money to burn CD again and again.

Please note that Windows has a registry to record what types of drives can run AutoPlay. You may need to make sure the network drive on your machihne does support AutoPlay by checking/modifying the registry:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/autorun/autoplay_reg.asp

Terminal Service IP Filtering on Windows Server 2000/2003

Unlike Internet Information Services (IIS),Windows Terminal Services does not have a place in the admin/config functions to Filter the IP’s such that it can only allow certain IP’s to login to the Services. This is a problem, because it opens the door for any hackers from the world to use TCP port 3389 to try to login. Even if they fail, they may have locked out many accounts when the legitimate users triy to login in.

As a matter of fact, starting from Windows Server 2000, Windows has a central place to accept or block IP traffic. It is under Administrative Tools -> Local Security Policy -> IP Security Policy. By default, all traffic inbound/outboard of any protocol for any ports are accepted.
To limit IPs to Terminal Service (TCP port 3389), or any other services like SQL Server Services, SNMP, SMTP, etc, we will need to create a Policy and activate it. A Policy contains pairs of (IP List + Actions). One the policy is set and activated, only IP’s not permitted will be allowed. For example, if we only allow IP Block 221.111.229.0/24 to access this Terminal Service, we should create an entry with this IP block and the action "Permit". After that, we should add another entry to "Deny" Any IP addresses. With these two entries in this policy, when it is activated, it will only allow this IP block 221.111.229.0/24 to access the Terminal Service. We can add more IP blocks if needed.

For step by step instructions for Windows 2000 Server, please refer to:
http://www.securityfocus.com/infocus/1559

Set up IP Security Policy for Windows 2003 Server is very similar.

Tuesday, March 21, 2006

How to change IIS 6.0 Configurations by editing Metabase.xml

There are many settings in IIS. Starting from version 6.0, the settings are stored in a text file called metabase.xml under %SystemRoot%\System32\Inetsrv. If you configure the IIS server such that directly editing this file is allowed, you can make changes of the behaviors of the IIS server by just changing the values in this XML file.
For example, there is a 4 MB limitation on Response Buffer. That is, is you try to use Response.BinaryWrite to download contents to the user, 4 MB is the default maximum you can reach. However, if you change the value ASPBufferingLimit in metabase.xml, you can make the value suitable for your system.
Please note this Buffering limitation is different from the file upload limitation we mentioned in one of the earlier articles, which is controlled by maxRequestLength in Web.Config.
For details, please refer to: http://www.windowsdevcenter.com/pub/a/windows/2004/07/13/iis_metabase.html

How to Debug Local VBS (VBScript) files and JS files

It is well known that VBScript (and JavaScript) can be used in ASP pages for Web Applications, and it is also known that vbs files (and js files) can run locally under WSH (Windows Script Hosting) in Microsoft Windows environment. The command line to run vbs, say foo.vbs, locally is:
WScript.exe foo.vbs
You can just doubleclick foo.vbs in Windows Explorer to run it too. WScript.exe runs foo.vbs under Windows Graphical Environment. In many IT tasks, we prefer command line (DOS) interface, so we put vbs in batch files. For command line execution, where the input and output are to and from DOS box, we type:
CScript.exe foo.vbs.
To create/edit vbs (and js), we can just use a simple editor, like Notepad, or your preferred editor. To debug, we either put the whole file into VB6 development environment, modify some lines to be suitable for VB6 syntax, and debug there. Once debugged, we change the syntax back to VBScript and use it in production. If we can’t afford to buy VB6, we can just use "MsgBox" ("printf") way. NO matter we are using VB6 or MsgBox approach, the debug process is not productive at all.
Microsoft does provide the debugging environment for vbs and js file, but the way to invoke it is a kind of tricky. To debug foo.vbs, the command line is:
WScript.exe //D //X foo.vbs
Right after you type this, the system tells you a run-time exception happened, do you want to debug ? You say Yes.
If you have Visual Studio Visual Interdev installed, the system will invoke the Visual Interdev debugger, mdm.exe, for you. This is preferred, as the function is rich, and the UI is exactly like debugging under ASP environment.
If you do not have Visual Studio Visual Interdev installed, the system will check if you have Microsoft Script Debugger installed. If yes, it will invoke this debugger MSScrDBG.exe. This debug is less convenient than the previous one, and the debug command set are different from the Visual Interdev one.
If you don’t have Microsoft Script Debugger installed, you can download it from:
http://www.microsoft.com/downloads/details.aspx?FamilyID=2f465be0-94fd-4569-b3c4-dffdf19ccd99&displaylang=en
For more information:
http://support.microsoft.com/default.aspx?scid=kb;en-us;308364

Overcome ASP.NET upload size limitation

The default size limitation in ASP.NET is 4MB. To overcome that size, you will need to add the following under System.Web section of either the Machine.Config file (to make it system wide), or Web.Config file (to make it application wide) :executionTimeout="90"maxRequestLength="4096"useFullyQualifiedRedirectUrl="false"minFreeThreads="8"minLocalRequestFreeThreads="4"appRequestQueueLimit="100" />Please note that the highlighted ones are must, in order to increase the upload file size limitation.The values in the example are default value. You should make it larger.http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/aspnet-fileupload.asp

Terminal Service IP Filtering on Windows Server 2000/2003

Unlike Internet Information Services (IIS),Windows Terminal Services does not have a place in the admin/config functions to Filter the IP’s such that it can only allow certain IP’s to login to the Services. This is a problem, because it opens the door for any hackers from the world to use TCP port 3389 to try to login. Even if they fail, they may have locked out many accounts when the legitimate users triy to login in.
As a matter of fact, starting from Windows Server 2000, Windows has a central place to accept or block IP traffic. It is under Administrative Tools -> Local Security Policy -> IP Security Policy. By default, all traffic inbound/outboard of any protocol for any ports are accepted.
To limit IPs to Terminal Service (TCP port 3389), or any other services like SQL Server Services, SNMP, SMTP, etc, we will need to create a Policy and activate it. A Policy contains pairs of (IP List + Actions). One the policy is set and activated, only IP’s not permitted will be allowed. For example, if we only allow IP Block 160.203.229.0/24 to access this Terminal Service, we should create an entry with this IP block and the action "Permit". After that, we should add another entry to "Deny" Any IP addresses. With these two entries in this policy, when it is activated, it will only allow this IP block 160.203.229.0/24 to access the Terminal Service. We can add more IP blocks if needed.
For step by step instructions for Windows 2000 Server, please refer to:
http://www.securityfocus.com/infocus/1559
Set up IP Security Policy for Windows 2003 Server is very similar.

Calling Web Services from within Notes/Domino Database

IBM Claims that Domino/Notes designers, starting from version 5.07a, can call SOAP based Web Service from within the Notes/Domino System. This is the claim. But if we look deeper into the implementation, it is messy and awkward.
The document can be found here:
http://www-128.ibm.com/developerworks/webservices/library/ws-soapcon/
In brief, the designer will need to download a connector called SoapConnect for LotusScript (Can be found in the link above) to help to connect to the SOAP service. Since the connector is written in Java, so even if you don’t use Java to develop Notes code, you still need to install a specific version of Java Run-time to get it work.
The sample LotusScript code is like:
1 %INCLUDE "SoapConnect"
2 Dim session As New NotesSession
3 Dim doc As NotesDocument
4 Dim myArgs(0) As Variant
5 Dim price As String
6 Set doc = session.DocumentContext
7 Dim bn As New SOAPClient("http://services.xmethods.com:80/soap/servlet/rpcrouter" )
8 myArgs( 0 ) = doc.BookNumber( 0 )
9 price = bn.invoke("urn:xmethods-BNPriceCheck", "getPrice", myArgs)

Writing the code may be simple, but setting up the run time environment can be tricky. Since Domino has made version 7 an easy platform to implement web service client and server, it is unlikely they will support version 5/6 much on Web Services any more. So I don’t expect it to be an easy task.

Integrate IBM Notes with Microsoft.NET

To integrate Notes and .NET, IBM, Microsoft and the 3rd party all provide solutions.
IBM’s Redbook web site (http://www.redbooks.ibm.com/redpapers/pdfs/redp3868.pdf#search=’IBM%20Notes%2FDomino%20.NET’) tells us to integrate Notes through ActiveX/COM, Web Service and .NET approach with the outside world. In most cases, we want Notes database to be accessed with Active/COM, Web Service, or .NET Assembly. In other words, we want consume Notes information from the outside world, or BizNET world.
Microsoft also has a web site, http://www.msdomino.net/, to provide links of the solutions. It looks unofficial, but it has tons of demo projects and sample codes. The approaches are clearly VS.NET oriented, instead of Notes Oriented in IBM’s web Site. It can be easier, and more familiar for us to implement.
Proposition, Inc., also provide the so called N2N solution: http://www.proposion.com/site/proposion.nsf/pages/N2N, to integrate Notes with NET. It provide middle ware to make the integration easier, but it is fee based. The Server Run-Time license starts from $1595.

Create Web Reference DLL by using .NET Framework and Command Line

It is easy to create web reference by using VS.NET, just browse the Web Service URL and give it a namespace. But if you do not VS.NET, you will have to do that manually.
First of all, you will need to run wsdl.exe to generate the proxy code in the language you want. So if you do:
wsdl http://www.mysite.com/Web%20Service%20Agent.nsf/DominoDotNetWSDL /l:vb /n /out:DomService.vb /namespace:com.mysite.www
You are generating the proxy code in vb, the file name is DOMService.vb, and the namespace is com.mysite.www.
Please note that if you write this in a batch file, you will need to double ’%’ when you need to write a single ’%’, that is because batch file always thinks a number after a single ’%’ is a parameter name supplied by the command line. But if you double ’%’ to make it ’%%’, it will believe you really mean a single ’%’.
For example, if you put the above command line in a batch file and run, it will fail because the batch file thinks the URL is actually http://www.mysite.com/Web0Service0Agent.nsf/DominoDotNetWSDL. Please note that both instances of ’%2’ disappeared, as you did not supply parameter(s) in the batch file command line.
So in order not to confuse batch file, we will need to make the command line like:
wsdl http://www.mysite.com/Web%%20Service%%20Agent.nsf/DominoDotNetWSDL /l:vb /n /out:DomService.vb /namespace:com.mysite.www
After DOMService.vb is generated, you can either put that directly into your EXE build batch file to consume this Web Service, or ’wrap’ this Web Service into a DLL for other .NET EXE to consume. Let’s say we want to do the 2nd approach:
vbc /t:library /out:MyDOMService.dll Domservice.vb /r:System.dll,System.XML.dll,System.Web.Services.dll
This will build the DLL which provides Web Services.
vbc /t:winexe Form1.vb /out:FormVB1.EXE /r:System.dll,System.XML.dll,System.Web.Services.dll,System.Drawing.dll,System.Windows.Forms.dll,MyDomService.dll /main:Form1
This will build a application FormVB1.EXE using this Web Service DLL.

How to move IIS 5.0/6.0 Web Server Configurations to another Server

There are times we will need to move/merge IISI Web Server/Services to another machine. Copying files are easy, but copying configurations are not, as they are stored in the Windows NT Metabase.
There are tools for Windows 2000 Servers and Windows 2003 Servers to Sync, Backup, and Restore Web Configurations. These tools are the vbs files stored in %SystemRoot%\system32\inetsrv subfolders, or %SystemRoot%\System32 sub-folders.
For Windows 2000 Server, or IIS 5.0, %systemroot%\system32\inetsrv\iissync.exe will do the job. The command is: iissync computername. Where computername is the computer you want to move the configurations to.
For Windows 2003 Server, or iis 6.0, You have more options to do the more complicated task like merge metabase, etc. But the simplest one is to backup the metabase from the old, , copy the backed up files to the new, and restore the metabase to the new.
To backup the configurations, go to %systemroot%\system32, then do: iisback /backup.
This will backup the metabase to a file called SampleBackup under %systemroot%\system32\inetsrv\MetaBack. The file name are called SampleBackup.md0 and SampleBackup.sc0. For more options, type iisback /backup /?
Now, before you restore, you will need to move all these SampleBackup files to the new machine, and put them into the sample place. Once they are there, you do:
iisback /restore /b SampleBackup
This should do. for more options, please use iisback /restore /?
This is the easiest and the fastest, but since it is just a complete metabase copy from the source to the destination, you’d better edit the backed up SampleBackup files, to change the machine names at least, before you restore.
There are more sophisticated ones to merge two or more metabases together. The command line is called iiscnfg.vbs. It is also located under %systemroot%\system32.

Monday, November 21, 2005

Crystal Report in a Web application fails to log on to SQL Server

When you use SQL Server 2000 to obtain live data for a Crystal Report in a Visual Studio .NET Web application, the Crystal Report fails to log on to the database.

This is because for security reasons, the SQL Server password is not persisted in the Crystal Report at run time.

To solve this problem, you must deliver the connection information to each database table individually to access the database as a whole. To deliver the connection information, add variables to the code of your Microsoft Visual C# .NET Web Form as follows:

// Add namespaces at top.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

//Crystal Report Variables
CrystalReport1 crReportDocument = new CrystalReport1();

//’CrystalReport1’ must be the name the CrystalReport
TableLogOnInfo crTableLogOnInfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();

//Crystal Report Properties
CrystalDecisions.CrystalReports.Engine.Database crDatabase;
CrystalDecisions.CrystalReports.Engine.Tables crTables;
CrystalDecisions.CrystalReports.Engine.Table crTable;

//Then, use following code sample to add the logic in the Page_Load method of your Web Form:


crConnectionInfo.ServerName = "EnterServerNameHere";
crConnectionInfo.DatabaseName = "EnterDatabaseNameHere";
crConnectionInfo.UserID = "EnterUserIDHere";
crConnectionInfo.Password = "EnterPasswordHere";
crDatabase = crReportDocument.Database;
crTables = crDatabase.Tables;

foreach(CrystalDecisions.CrystalReports.Engine.Table crTable in crTables)
{
crTableLogOnInfo = crTable.LogOnInfo;
crTableLogOnInfo.ConnectionInfo = crConnectionInfo;
crTable.ApplyLogOnInfo(crTableLogOnInfo);
}

CrystalReportViewer1.ReportSource = crReportDocument;

For detailed info, plaese go to:

http://support.microsoft.com/default.aspx?scid=kb;en;319264&sd=msdn

Monday, October 24, 2005

Use TaskKill to clean run away processes

Taskkill
Ends one or more tasks or processes. Processes can be killed by process ID or image name.

Syntax
taskkill [/s Computer [/u Domain\UserName [/p Password]]] {[/fi Filter [/fi Filter [ ... ]]] [{/pid ProcessID | /im ImageName}] | /pid ProcessID | /im ImageName} [/f] [/t]

Parameters
/s Computer

Specifies the name or IP address of a remote computer (do not use backslashes). The default is the local computer.

/u Domain\UserName

Runs the command with the account permissions of the user specified by UserName or Domain\UserName. /u can be specified only when /s is specified. The default is the permissions of the current logged on user on the computer issuing the command.

/p Password

Specifies the password of the user account that is specified in the /u parameter.

/fi Filter

Specifies the types of process(es) to include in or exclude from termination. You can specify more than one filter. Use the wildcard (*) to specify all tasks or image names. The following are valid filter names, operators, and values.


Name Operators Value
Status
eq, ne
RUNNING | NOT RESPONDING | UNKNOWN

Imagename
eq, ne
Any valid string.

PID
eg, ne, gt, lt, ge, le
Any valid positive integer.

Session
eg, ne, gt, lt, ge, le
Any valid session number.

CPUTime
eq, ne, gt, lt, ge, le
Valid time in the format of HH:MM:SS. The MM and SS parameters should be between 0 and 59 and HH can be any valid unsigned numeric value.

Memusage
eg, ne, gt, lt, ge, le
Any valid integer.

Username
eq, ne
Any valid user name ([Domain\]UserName).

Services
eq, ne
Any valid string.

Windowtitle
eq, ne
Any valid string.

Modules
eq, ne
Any valid string.


/pid ProcessID

Specifies the process ID of the process to be terminated.

/im ImageName

Specifies the image name of the process to be terminated. Use the wildcard (*) to specify all image names.

/f

Specifies that process(es) be forcefully terminated. This parameter is ignored for remote processes; all remote processes are forcefully terminated.

/t

Terminates the specified process and any child processes which that process started.

/?

Displays help at the command prompt.

Remarks
• The "WindowTitle" and "Status" filters are not supported when a remote system is specified.

• The wildcard character (*) is accepted only when specified along with the filters.

• Termination for remote processes will always be done forcefully regardless of whether the /f parameter is specified.

• Supplying a computer name to the HOSTNAME filter will cause a shutdown and all processes will be stopped.

• Use tasklist to determine the Process ID (PID) for the process to be terminated.

• Taskkill is a replacement for the kill tool.


Examples
The following examples show how you can use the taskkill command:

taskkill /pid 1230 /pid 1241 /pid 1253

taskkill /f /fi "USERNAME eq NT AUTHORITY\SYSTEM" /im notepad.exe

taskkill /s srvmain /f /im notepad.exe

taskkill /s srvmain /u maindom\hiropln /p p@ssW23 /fi "IMAGENAME eq note*" /im *

taskkill /s srvmain /u maindom\hiropln /fi "USERNAME ne NT*" /im *

taskkill /pid 2134 /t /fi "username eq administrator"

taskkill /f /fi "PID ge 1000" /im *

Saturday, October 15, 2005

MS SQL Server fixed Server Roles and Database Roles

Server Roles:

sysadmin - grants its members complete control over the SQL Server, its databases, and all of their objects. The group initially contains two logins - sa SQL login and local BUILTIN\Administrators Windows login. You can assign additional logins to it (both SQL and Windows), you can also remove Windows local BUILTIN\Administrator group from it (if you intend to separate Windows and SQL server administration), however sa login membership can not be altered (and the account can not be deleted, disabled, or renamed).

serveradmin - intended for users responsible for the configuration of SQL Server. This typically consists of modifying server-wide settings and options, such as, the amount of memory or processor time allocated to the SQL Server or query governor behavior (in essence, all operations which can be performed with sp_configure stored procedure). Members of this role can also modify table options (covered by sp_tableoption stored procedure).

setupadmin - gives its members the power to control configuration settings for linked servers and stored procedures to be executed at startup.

securityadmin - provides the ability to manage security related settings, such as changing authentication mode, creating logins or database users, and granting, denying, or revoking permissions to create databases (execute CREATE DATABASE statement).

processadmin - limited to terminating processes with the KILL command (from T-SQL) or via graphical interface in SQL Server Enterprise Manager.
dbcreator - permits its members to create, drop, and modify databases (execute CREATE DATABASE, DROP DATABASE, and ALTER DATABASE statements).

diskadmin - exists strictly for backwards compatibility purpose - allowing its members to manage disk devices created in the SQL Server 6.5.

bulkadmin - grants permissions to execute the BULK INSERT command, used to import large quantities of data into SQL Server.

Database Roles:

db_accessadmin - intended for administrators responsible for granting and revoking access to the database (which also implies the ability to create or drop users).

db_backupoperator - provides the ability to backup a database (but not restore it).

db_datareader - allows reading all database tables and views (executing SELECT statement against them).

db_datawriter - allows modifying content of all database tables and views (executing INSERT, UPDATE and DELETE statement against them). Due to the fact that functionality provided by this role includes the ability to delete all data, you should very carefully control its membership.

db_dlladmin - grants its members the ability to execute any Data Definition Language (DDL) command (which result in creation of database objects, such as tables, triggers, stored procedures, etc.). Members of this role who issue the CREATE statements automatically become their owners, which, in turn, means they have full control over them.

db_denydatareader - serving function reverse to db_datareader - denies read access to all tables and views (through DENY SELECT permissions). Since impact of the membership in this role cannot be overridden by granting permissions to individual objects, this serves as a convenient mechanism to secure them against particular users or groups of users.

db_denydatawriter - serving function reverse to db_datawriter - denies write access to all tables and views (through DENY INSERT, DENY UPDATE and DENY DELETE permissions). Just as with the db_denydatareader role, impact of the membership in this role cannot be overridden by granting permissions to individual objects, so this can also be conveniently used to secure them against particular users or groups of users.

db_owner - the most powerful role on the database level (equivalent to the sysadmin on the SQL server level) with full administrative control over all database objects and operations. The role initially contains a single user dbo, but additional user accounts can be added to it.

db_securityadmin - its members have power to grant, revoke and deny permissions on every object in the database, in addition to managing membership of fixed and custom roles.

public - contains all database users and roles (resembling Everyone Windows group) and its membership can not be altered. This is important to remember, since it means that all users who are allowed to access a particular database are automatically granted all permissions assigned to public role. In general, you should avoid granting permissions to public role.

Saturday, August 13, 2005

ARP cache poisoning / ARP spoofing

Many people think that once they use a switch for connecting their local network they're safe from network sniffing. Basically this is right because the traditional way of sniffing where a host can read all network packets just by accepting them (the so called "promiscous mode") is not possible.

However there are other means to achieve the same and because maybe some SysAdmins think they're safe from sniffing thus designing their network a bit more open it's even more dangerous.

The tool used here is called arpspoof and is distributed in the dsniff package.

What we do is the following: We constantly send the victim computer ARP answers telling him that the MAC address belonging to the IP of the gateway machine (router) is our MAC address. After some time the victim computer will believe us and makes a wrong entry in his ARP cache. Next time the victim wants to send an IP packet to the gateway he sends the ethernet frame to our MAC address so actually we get the IP packet. We do the same thing with the gateway machine just the other way round.
RFC 1027 describes the ARP protocol.

In order to tell the victim host that now we (our MAC address) are the one belonging to the IP of the gateway enter the following command:
# arpspoof -t victim gateway

In a seperate shell we start the matching command to fool gateway to belive we are victim.
# arpspoof -t gateway victim

Don't forget to enable IP forwarding on your host so that the traffic goes through your host. Otherwise victim will loose connectivity.
# echo 1 > /proc/sys/net/ipv4/ip_forward

Now watch all the traffic between the victim host and the outside network going through your machine
# tcpdump host victim and not arp

Frightening easy...

SysAdmins beware of that threat! If you have users on your network you can't trust (e.g. in universities) use tools like arpwatch to monitor the changes of the MAC / IP address tables.

Saturday, August 06, 2005

Growing pains hurt Skype

Skype CEO Niklas Zennstrom vowed to shake up the phone industry 20 months ago with his creation, the first ever peer-to-peer Internet phone service.

More than 110 million downloads and 2 billion minutes of phone conversations later, Zennstrom has shown that he wasn't kidding. But Skype's success has led to perhaps the most difficult chapter yet for the Luxemburg-based company. It now faces mounting concerns over a lack of customer service and a growing backlash by utility regulators as it hunts for new revenue opportunities. Zennstrom spoke to CNET.News.com about these and other issues earlier this week.

Q: There are a lot of customer complaints about SkypeIn, where you get inbound calls from any phone, and SkypeOut, which is used to call any phone. Is there a problem with it?

Zennstrom: One thing you have to bear in mind is that the telephone system has been around for 135 years; Skype's been around for 20 months. We are going through all kinds of improvements.

But clearly something is wrong. Customers are fuming about dropped or badly distorted calls. Any changes in the offing?

Zennstrom: There actually are people using SkypeIn that say it's better than SkypeOut. We are using a new software version for SkypeIn, which we will be gradually introducing into SkypeOut. We are continuously working on it.

Is that going to solve the problem?

Zennstrom: We're also adding more carrier partners in order to terminate more calls to traditional phones. That will help. We are also developing lots of new ways to correct errors in the traffic. I think we will continue to see improvements in quality.

These are quality of service problems Skype can address. But Skype can't control the quality of someone's broadband connection, which has a direct impact on Skype calls.
Zennstrom: We've identified a list of things we can do. But in cases where people are on a badly congested Internet network, that will have an impact on quality. But you're starting to see multi-megabit, per-second connections. In many places, Sweden for example, you can buy a 24mbps line here, and you'll start seeing that in a lot more places.

Your proprietary software has come under fire from those Net phone interests advocating open-source Session Initiation Protocol. What's Skype's SIP stance now?
Zennstrom: We've been using SIP to interconnect SkypeIn and SkypeOut calls to the (traditional) public switched telephone network (PSTN) since July. Second to Yahoo Broadband in Japan, we're probably one of largest SIP traffic generators. But doing anything beyond that? We think that SIP is not very good for end users.

But by using your own coding, don't you have trouble as a result interconnecting with the huge percentage of other Net phone operators that use SIP? Isn't Skype essentially walling in its users?

Zennstrvm: Our position is that over time, we expect to interconnect to voice over Internet Protocol (VoIP) networks directly, rather than using SIP and the PSTN.

The Federal Communications Commission recently said that Net phone operators must add 911 accompanied by a caller's location and call-back number. Will Skype comply?
Zennstrvm: We believe the FCC decision is not directly applicable to Skype. But we feel that enhanced 911 services are a serious matter, and we're working through various industry organizations to edge the industry into offering not just 911, but all kinds of IP-based emergency services.

So at some point in the future, you feel Skype needs to add 911?

Zennstrvm: Yes, but to what degree we don't know yet.

What are these new IP-based emergency services you're talking about?

Zennstrvm: If there's a burglar in my home, maybe I send an e-mail or a text message to the police instead of making a call.

But you're focusing on the future. What about now? Could Skype meet the FCC mandate?

Zennstrvm: With regards to location information? It's impossible for anyone like ourselves to supply that information. It's not technically feasible.

What's the problem?

Zennstrvm: We have no knowledge of the geographic location of anyone's IP address.

If asked to comply, how could Skype do it then?

Zennstrvm: There needs to be a database which maps IP addresses to geographical locations. There are some out there now doing geo-mapping, but the databases are not exhaustive enough.

Skype has indicated its next hardware effort involves essentially making mobile Skype phones. How's that effort going?

Zennstrvm: We're working with several manufacturers, like Motorola, on things like a Wi-Fi handset. You'll also see handsets that can get Skype calls over Wi-Fi or cellular networks.

What's the rationale for a wireless operator to sell such a handset? Doesn't it eat into their profits every time somebody uses Skype to make a call instead of their network?

Zennstrvm: The operators make money off a Skype call because Skype calls will run over their networks. They get the traffic.

Wiretap VoIP

The Federal Communications Commission* and the Justice Department are at loggerheads over a new problem in the war on terror: how to listen in on Internet phone calls. Thanks to the blistering growth of VoIP—Voice over Internet Protocol—services, which have been adopted by approximately 10 million people worldwide so far, law enforcement officials now worry that wiretapping may one day become technically obsolete. If traditional phone lines go the way of the horse and carriage, will the FBI still be able to listen in on Internet phone calls? How would it go about tapping one? Is it even possible?

I contacted three of the leading VoIP providers in the United States—Time Warner Cable, Vonage, and Skype—to ask them how they would comply with a court order to permit a wiretap. As it turns out, the Justice Department has good reason to worry. Depending on the provider, tapping a VoIP call can be either tricky or impossible.

For Jeffrey Citron, the CEO of Vonage, the critical problem is this: The 1994 law that dictates how telecoms must cooperate with the feds (it's known as CALEA) stipulates that government agents can listen in on phone calls only in real time. They are not permitted to record calls and play them back later to check for incriminating information. But as Citron explained it, on Vonage's system, it is technically impossible (for now) to listen in on a live phone call


Here's why: A VoIP call transforms your voice into digital bits, then segments them into separate packets of data that are routed through the Internet and reassembled upon arrival at the other end. From an old-fashioned perspective, there is no actual "sound" passing through the Internet at any time—the PC or other device you use to place the VoIP call digitizes your voice in your home. Of course, a huge amount of regular phone traffic is also segmented into digital packets at some point, but such calls are digitized and then reconverted into sound waves far deeper into the telephone system, at points outside private homes. Law enforcement can therefore listen in on your line within the telephone system itself; the technology to do this is already embedded in the phone company's switches.

In theory, Vonage could comply with a tap request by making a copy of the call in real time and streaming that call to a law enforcement agent. But that tack would violate CALEA, since Vonage would still be making a copy of the original call. The alternative, Citron says, is for Vonage to modify its VoIP system so that its digital routers include analog-friendly wires capable of producing a real-time sound wave. These could then be linked to a law enforcement agency, permitting simultaneous listening-in. Citron says making the shift would cost Vonage a few million dollars—before taking any action, he's awaiting further regulatory instructions from the FCC. The company has already complied with between 10 and 100 requests from various government agencies for general information (including call records and billing history), but to date, he has yet to receive a single request for a live tap into a Vonage call.

Time Warner Cable, which has announced that it will make VoIP available to all its digital cable markets by the end of the year, would have a much easier time wiretapping live phone calls. That's because Time Warner owns the underlying infrastructure its VoIP service relies on. So while Vonage could offer government agents access only to the handful of routers it uses to direct its calls over the wider Internet, Time Warner can offer them direct access to the cables, routers, and switches over which its VoIP calls travel. It could, in theory, open a live channel for law enforcement at the place where Time Warner's cable modem signals are routed onto the wider, public Internet. This switch, known as the Cable Modem Termination System, is a natural junction where a company like Cisco, which already builds CMTS hardware, could easily and cheaply add in CALEA-compliant technology.

Why, then, couldn't the feds tap any VoIP call by listening in on the line at the CMTS? Because some VoIP calls are routed, digitized, or encrypted in ways that law enforcement can't decipher. Skype, which now boasts 7 million users, specializes in such encryption. The company's system is designed to thwart potential eavesdroppers, legal and otherwise. The difference begins with how the networks are designed: Both Time Warner and Vonage offer VoIP services that run through centralized networks. For instance, when I place a call through Vonage, it starts by going to a centralized Vonage computer, which in turn looks up the phone number I am dialing and routes the call over to the traditional phone system. This is a classic instance of a "hub and spoke" network. But Skype, built by the same people who brought us Kazaa, is a totally distributed peer-to-peer network, with no centralized routing computers. (That's possible in part because Skype calls can only be sent and received by computers—you can't call a friend with an analog phone.) As a result, the company's network looks more like a tangled spider web, and the packets that make up your voice in a Skype call are sent through myriad routes to their destination. Part of the brilliance of the Skype software is that it has learned to use desktop PCs as "supernodes," each sharing some of the load needed to route Skype calls quickly to their destination. From the caller's perspective, this is all invisible: The call just works.

Since it's exceedingly difficult to follow the path that a Skype call makes through the network, law enforcement agents would be hard-pressed to figure out where to place a tap. But even if they could, the company has built in such strong encryption that it's all but mathematically impossible with today's best computer technology to decode the scrambled bits into a conversation. Here's how Skype explained it: "Skype uses AES (Advanced Encryption Standard)—also known as Rijndel—which is also used by U.S. government organizations to protect sensitive information. Skype uses 256-bit encryption, which has a total of 1.1 x 1077 possible keys, in order to actively encrypt the data in each Skype call or instant message." The point of all this mumbo-jumbo is that Skype uses an encryption algorithm* known as 256-bit AES. The National Institute of Science and Technology states that it would take a computer using present-day technology "approximately 149 thousand-billion (149 trillion) years to crack a 128-bit AES key." And that's for the 128-bit version; Skype uses the more "secure" 256-bit standard. Since computers have a way of quickly getting more powerful, the institute forecasts that "AES has the potential to remain secure well beyond twenty years."

Moreover, Skype says, the company does not keep the encryption "keys" that are used to encode each Skype transmission—each one is generated and then discarded by the computer that initiates the call. So government agents couldn't force Skype to turn over the keys needed to decrypt a call either.

Last Thursday the FCC held an open hearing on the future of VoIP telecommunications. In a 4-1 decision, FCC commissioners, supported by Chairman Michael Powell, voted that a VoIP provider called Free World Dialup should not be subject to the same regulations as traditional phone companies—including the particulars of CALEA compliance. Instead, the FCC decided to put off the issue, stating that it would initiate a proceeding "to address the technical issues associated with law-enforcement access to Internet-enabled service" and "identify the wiretapping capabilities required." One commissioner, Michael J. Copps strongly dissented, calling the postponement "reckless."

But even if the FCC had ruled differently on Thursday, mandating specific rules for Internet phone calls and CALEA compliance, it couldn't have been the definitive word on the subject.

VoIP technology is gaining ground so fast that it may be impossible for any government agency to dictate what these networks should look like. Skype, for instance, isn't even an American company. It's legally based in Luxembourg. Increased regulation on American carriers, which could lead to higher costs for consumers, is likely to push people further toward carriers like Skype, rewarding companies that seek permissive legal jurisdictions and punishing those that try to comply with domestic regulations. It's this scenario that the Justice Department legitimately fears: Even though the Patriot Act has increased its ability to eavesdrop on Americans, companies like Skype are giving everyday people unprecedented freedom from government monitoring.

Saturday, July 30, 2005

Session Cookies blocked when Server Name is NOT DNS compliant

While I was trying to tackle the problem of blocked session cookies in our Web_Test server, I found something very important and very few people know so far:

According to Microsoft, after the latest patch of the Servers (or the Browsers):

Cookies on ASP pages are blocked if the server name contains characters that are not supported by Domain Name System (DNS). For example, you cannot use underscore characters (_) in the server name. This behavior is by design.

This fact happens to match our case on Web_Test, because we have ’_’ in server name! So no matter where you are, as long as you use http://Web_Test, or http://Web_Test.MyDomain.com, you will NOT be able to send the session cookies to the client to maintain the session (You still have other way to maintain session in ASP.NET, described later.) But if you use, say, http://192.168.1.77, or, if you are at the server. http://localhost, http://127.0.0.1, you will be OK.

This is NEW to me. I believe also new to many people who get confused why suddenly the session is not working any more!

Why do we have this rule, and when did this start to happen ? Microsoft just mentioned it is security related, and it is already happening.

So how do we solve our own problem with Web_Test ?

Well, the straightforward way is to rename it to, say, WebTest, or Web-Test. Actually, I added the following entry:

192.168.1.77 WebTest

to the hosts file of the machine where browser is at (I did that on MyServer.MyDomain-test.com), then browsed the web server by doing http://WebTest. it worked.

Another way, which is only available to ASP.NET, is to set cookieless = "true" in the following section of the web.config file:

<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="true"
timeout="20"
/>

This is ASP.NET’s way to maintain session without cookies. It is quite useful, as more and more people turning off cookies because of security concern.

So, in the future, what kind of server name should we use, to comply with DNS naming convention ?

According to DNS, the characters should supports RFC 1123, which permits "A" to "Z", "a" to "z", "0" to "9", and the hyphen (-). The fully qualified domain name length should be no more than 63 bytes per label and 255 bytes total for an FQDN (Fully Qualified Domain Name)

For details, please refer to:

http://support.microsoft.com/default.aspx?scid=kb;en-us;325192

and

http://www.microsoft.com/resources/documentation/Windows/2000/server/reskit/en-us/cnet/cncf_imp_xvxz.asp

Friday, July 22, 2005

Simulate the Excel Freeze Pane Effect on Web Pages

There are times when people need to enter a long row of information on the web. When scrolling to the right to keep on entering, the user will lose sight of the content of the left. It is needed to overcome this kind of problem for the user by using Javascript/DHTML.

Attached please find the solution with one ASP page and one Javascript. Since most of the work is done at the client side, it works on both ASP and ASP.NET environment with little or no modifications.

Here is the demo:

http://gate.ebizts.com/demo/hscroll2.asp

How to expose COM objects to .NET Framework

To expose COM to NET, we will make a "Wrapper", or "Proxy Assembly", which plays the role of the bridge between the COM object and the .NET applications. This assembly will be put into the /bin sub folder once generated.

To generate this Wrapper Assembly, we will need to run a program called tlbimp.exe, which comes with the .NET Framework. The command line takes a Type Library as the parameter and optionally a output assembly name as another parameter:

tlbimp foo.tbl /out:myfoo.dll

Once the assembly myfoo.dll is generated, it will be placed in the /bin sub folder.
After this, using COM is just like using any other assembly. For example, in VB.NET, the code is like:

Import myfoo

Dim foo as new myfooClass

foo.method1.....
foo.method2....
foo.method3....

The next issue is how to get the type library. Type Library can be a standalone file with the extension of .tlb, or is embedded in the COM dll files, or in ocx, or olb files. If it is embedded into a dll, then the tlbimp command line will be like:

tlbimp foo.dll /out:myfoo.dll (please be careful not to override the original dll, by specifying a different sub folder in /out:, if you want to use the same name as the output.)

If you are using VS.NET, then creating the COM wrapper is as easy as adding an reference. No TlbImp command needed:

To add a reference to a type library

Install the COM DLL or EXE file on your computer, unless a Windows Setup.exe performs the installation for you.
From the Project menu, select References.
Select the COM tab.
Select the type library from the Available References list, or browse for the TLB file.
Click OK.

How to upload file(s) bigger than 4 MB in ASP.NET

The maximum file size you can upload by default is 4 MB. This can be increased in the web.config file by adding the following configuration setting:

<httpRuntime maxRequestLength="4096" />

1,024 Kiliobytes = 1 Megabyte
4096 is the default in Kilobytes. Hence; 4,096 KB is equal to 4 MB. If you want to allow files bigger than 4 MB simply add the above setting so your web.config file looks like this.


<configuration>
<system.web>
<httpRuntime maxRequestLength="4096" />
</system.web>
</configuration>

Converting Java Applications to C#

It is easy to convert a Java project to C# by using VS.NET. Below is the procedure:
Java-Language Projects
To convert a Java-language project

Start Visual Studio .NET
On the File menu, point to Open, and click Convert.
Select Java Language Conversion Assistant, and click OK.
On the Source Files page, click A directory containing the project's files.
On the Select source directory page, click Browse.
Browse to the correct project, and select it.
Note You will not see the files in the directory you select, but all .jav and .java files in it will be converted. All other files in the directory are ignored.
On the Configure your new project page, specify the following:
Name of the project to be created.
Directory in which the any additional files for your project are located.
Note You will not see the files in the directory you select, but all .jav and .java files in it will be converted. All other files in the directory are ignored.
Output type of the project.
On the Specify a directory for your new project page, specify the name and directory of the new project to be created.
On the Begin your conversion page, click Next.
Fix code that could not be converted automatically. For more information, see Manually Upgrading Unconverted Code.

Package Java into COM Object for ASP/ASP.NET

We have discussed how to convert the Java Source code to C# in order to run under the .NET Framework. If we just want to use the Java Classes under ASP/ASP.NET, then there is an alternative. The alternative is to package the Java Class(es) into the ActiveX/COM object by using the Visual J++ development environment.

Please note that Visual J++ is not a language. It is a development environment for Java Developer to develop applications for Microsoft Windows easily. With Visual J++ development environment, it is relatively easy to package Java Classes into COM/ActiveX to be used by ASP/ASP.NET and other languages.

If you already have the Java Class source code, you can follow the steps described below to make it a COM/ActiveX. But before you do this, there are issues to consider:

1. The Windows platform needs to have Windows JVM installed to run this COM/ActiveX. (It is supposed to be the case. But today's Windows Server 2003 does not seem to have it natively)

2. The speed of this ActiveX/COM is some what slower than the native COM/ActiveX developed by C++.

Below is the link to demonstrate the step by step procedures.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnjpp/html/msdn_vjfaq.asp

How to create multiple Virtual Sites in Windows XP Professional

Windows XP Professional does allow you to host web applications, but it only officially allows one web site. That is, no virtual sites allowed like we can do with Windows 2000/2003 Server. This problem can be overcame by editing the metabase, but there are still limitations: you can have only one web site active at a time, other sites have to be stopped.

The procedure(s) to add the 2nd Web Site:

1. Open a command prompt, C:\windows>.

2. cd \inetpub\adminscripts

3. run adsutil.vbs create_vserv w3svc/2 (this command creates the 2nd instance of the web site).

4. run adsutil.vbs copy w3svc/1 w3svc/2 (this command copies the data from virtual site 1 to virtual site 2).

5. Open IIS by using ISM(Internet Services Manager), you will see the 2nd Web Site with the identical name as the first one, because you just copied it. Just change name and other settings to the one you want.

6. Re-register ASP.NET to all the sites:

cd c:\windows\Microsoft.net\Framework\v1.1.4322

aspnet_regiis /i

How to implement Tables in ASP.NET

When it comes to the repetitive items, Microsoft’s ASP.NET encourages you to use one of the followings controls: DataGrids, DataLists, or Repeaters. While DataGrid and DataList Controls are the easiest for displaying/editing database tables, the Repeater Controls provide the best flexibility among the three. All three of them needs to use Data Binding to bind with the database or the data source. They are all powerful, but they are not as flexible as it used to be when we were using tables in ASP.

What if we want to use the good old ASP ways to present a table under ASP.NET. The good old way is to use a While Loop to draw one cell, and then one row at a time, until the whole table is drawn. Yes, ASP.NET does include a server control called Table to allow us to add one cell, then one row at a time in a while loop.

Below is the code segment to show you how to add one row of data to the ASP.NET Table control with the ID of Table1:

private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

TableRow r = new TableRow();

// build the title row

TableCell c = new TableCell();

c.CssClass = "ItemSubHead";

c.BackColor = Color.BurlyWood;

c.Text="League";

c.Width = 225;

r.Cells.Add(c);

c = new TableCell();

c.CssClass = "ItemSubHead";

c.BackColor = Color.BurlyWood;

c.Text="Date";

c.Width = 180;

r.Cells.Add(c);

c = new TableCell();

c.CssClass = "ItemSubHead";

c.BackColor = Color.BurlyWood;

c.Text="Time";

c.Width = 180;

r.Cells.Add(c);

Table1.Rows.Add(r);

}

Make use of URL Rewriting in ASP.NET

URL rewriting is used to allow the Web users to access many URL’s which does not really exist in the Web Server’s file system. The benefit of that are at least the followings:

1. Use part of URL’s as the parameter (query string) to the application. For example, a Canadian web site which supports both French and English language can use the URL’s to decide what kind of messages the Web Application should show:

http://www.domain.com/en-CA/login.aspx will show an English Login Screen

http://www.domain.com/fr-CA/login.aspx will show a French Login Screen

Inside the server, there is only one URL: http://www.domain.com/login.aspx

2. Hide the aspx extension, and the actual file system structure from Web Site, such that people may not know this is a ASP.NET site,a nd the hacker may not be able to hack the site by playing around the URL’s.

Before ASP.NET, it is hard to achieve this, other than writing a custom ISAPI dll, which is hard. With ASP.NET, we can easily intercept the requester’s URL, parse and rearrange to the real internal URL with the parameters.

To implement URL rewrite, we will need to develop a HTTPModule and include that Module into the web.config file. Like:

<system.web>
<httpModules>

<add name="Localization" type="Localization.LocalizationHttpModule, Localization" />

</httpModules>

</system.web>

The Module itself we intercept each URL request, parse and redirect to the real URL. Please note this Redirect is not the HTTP browser redirect, so it does not take additional round trip between the browser and the server. It redirect internally. It is faster and secure.

Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init

AddHandler context.BeginRequest, AddressOf context_BeginRequest

End Sub

Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)

Dim request As HttpRequest = CType(sender, HttpApplication).Request

Dim context As HttpContext = CType(sender, HttpApplication).Context

Dim applicationPath As String = request.ApplicationPath

If applicationPath = "/" Then

applicationPath = String.Empty

End If

Dim requestPath As String = request.Url.AbsolutePath.Substring(applicationPath.Length)

LoadCulture(requestPath)

context.RewritePath(applicationPath + requestPath)

End Sub

For detals, please refer to the following URL:


http://www.codeproject.com/aspnet/LocalizedSamplePart2.asp

SQL Server Database Maintenance: File Size

To Shrink the size of the database data file or the transaction Log by using Query Analyzer. Let’s say The database name is called BNET.

Use BNET

DBCC ShrinkFile (BNET_Data)

DBCC ShrinkFile(BNET_Log, 2)

The parameter 2 means you hope you can shrink the Translation Log to 2 MB.

The transaction log can grow very big, and the DBCC ShrinkFile will not be able to Shrink, if the system thinks there are incomplete Transactions in the Transactions Log. If you don’t not care about the pending transactions, or if you think all the transactions you need is already in BNET_Data, you can use the following command:

Backup LOG BNET with Truncate_Only

After this is done, run:

DBCC ShrinkFile(BNET_Log, 2)

again to make sure the size shrinks to 2 MB.

SQL Server maintenance: Indexes Tuning

Microsoft SQL Server has the capability to help you decide which index(es) to add after monitoring your "typical" database access activities for long enough time. To do this, Start Profiler in Microsoft SQL Server, then New a Trace and Run. After you have collected enough "Typical" database activities, you can stop and save the trace, then use the Tools -> Index Tuning Wizard to let the wizard analyze your trace and made suggestions on you. If the suggestions make senses to you, you can just accept it and the wizard will automatically add/modify the indexes for you.

MS SQL Server DBCC CheckDB command

DBCC CheckDB (’dbname’) is used to check and optionally repair the Database Allocation Consistency and the Index Pointer Correctness of the Database. It is the combination of DBCC CheckAlloc and DBCC CheckTable commands.

DBCC CheckDB can run when the system is running, but it is not recommended to run when Intensive Transactions are in progress, or when the database backup is running. DBCC CheckDB is using tempdb to sort and store working data, so it is recommended to make tempdb big enough to speed up the Check/Repair Process.

If the database only reports allocation error, we can just run DBCC CheckAlloc to check and repair, save time and resources. If we just want to check/repair the data, index, and field type text, ntext, and image fields of certain table, we can just run DBCC CheckTable (’tablename’).

Below are the command syntax and the examples of DBCC CheckDB:

Syntax
DBCC CHECKDB
( ’database_name’
[ , NOINDEX
| { REPAIR_ALLOW_DATA_LOSS
| REPAIR_FAST
| REPAIR_REBUILD
} ]
) [ WITH { [ ALL_ERRORMSGS ]
[ , [ NO_INFOMSGS ] ]
[ , [ TABLOCK ] ]
[ , [ ESTIMATEONLY ] ]
[ , [ PHYSICAL_ONLY ] ]
}
]

Examples
A. Check both the current and the pubs database
This example executes DBCC CHECKDB for the current database and for the pubs database.

-- Check the current database. DBCC CHECKDB GO -- Check the pubs database without nonclustered indexes. DBCC CHECKDB (’pubs’, NOINDEX) GO
B. Check the current database, suppressing informational messages
This example checks the current database and suppresses all informational messages.

DBCC CHECKDB WITH NO_INFOMSGS GO

MS SQL Database Backup and Restore

We can make MS SQL server backup a scheduled activity or a one-time manual process. The simplest way to do the backup is going to the Enterprise Manager, right click on that database, pick All Tasks, and pick Backup Database. Over there you can choose the devices or files you want to backup your Data and/or Log file of the database to. You can also decide whether this is going to be a scheduled task to one-time task. The backuped files can be appended to the backup media, or overwrote to the backup media.

To Restore the database(s), go to the same place to restore from your backup device(s). At some point we will need to overwrite the data and the log when needed, if we really want to restore. To make it 100% safe just in case restoration fails, you can backup data and log files to some other place first. To know where the data and the log files are, right click on the database in enterprise manager, click properties, the click on Data Files for the location and the Transaction Log for the location.

If the Master Database is damaged, then it is a different story: The SQL server will not run at all!

Let’s assume we already have a backup master, then all we need to do are the following steps:

1. Build The Master Database from scratch by a command line utility rebuildm.exe.

2. Start the SQL server in single user mode (sqlserver.exe -c -m)

3. Restore Master database from the backup device.

4. Restore msdb database from the backup device.

5. Restore other databases, if applicable.

For details, please go to:

http://www.dbarecovery.com/restoremasterdb.html#T-SQL

Commonly used SQL Server 2000 Performance Monitors

The following items are common used "Health Meter" for SQL Server 2000:

SQL Server/NT Server Performance Monitor. (Displaying a wide range of system parameters. Activated by: Start->Run->PerfMon)
Current Activity Window. (Showing SQL Server Current Processes and Locks. Activated by: Start -> Programs -> MS SQL Server -> Enterprise Manager->Select a server->Management->Current Activity)
SQL Server Profiler. (Trace and Fine Tuning SQL Server Activities and Indexing. Activated by: Start -> Programs -> MS SQL Server -> Profiler.)
sp_monitor (Show how busy the SQL server has been. Activated by Start -> Programs -> MS SQL Server -> Query Analyzer -> sp_monitor)
sp_spaceused (Show how much disk space the table or database has used. Activated by Start -> Programs -> MS SQL Server -> Query Analyzer -> sp_spaceused)
sp_who (Show current users and status. Activated by Start -> Programs -> MS SQL Server -> Query Analyzer -> sp_who)
sp_lock (Show current lock and block information. Activated by Start -> Programs -> MS SQL Server -> Query Analyzer -> sp_lock)
DBCC commands (Database consistency checker. Activated by Start -> Programs -> MS SQL Server -> Query Analyzer -> DBCC .......)

Web Programming Security: SQL Injection

SQL Injection is a way the web hackers taking advantages of the programming habit of the common web developers to gain access to the protected system. It will allow the hackers break into the Login/Password screen without even knowing the login name and/or the password.

In many web login pages, the typical user interface has a field called, say Login, and a fields called, say Password. When the users enter the login and the password, the program will check if this user is authenticated by running the SQL like:

Select * from Users Where Login = ’" & Login & "’ and Password = ’" & Password & """

If the record exists (not EOF), this person is authenticated. If not (EOF), not authenticated.

It looks correct, but from hacker’s eye, it is not. The hackers will be able to enter the system by filling the Login box with:

’ or 1 = 1 --

and leave blank to the Password.

It will effectively make the SQL statement become:

Select * from Users where Login = ’’ or 1 = 1 --’ and Password = ’’

This is effectively equal to

Select * from User Login = ’’ or 1 = 1

Since -- makes the statement after it irrelevant.

At this point, this hacker is authenticated. It is scary.

How to prevent this from happening ? First of all, check the input box to see if there is anything unusual, like symbol ’ or =. Secondly, make SQL statement harder to guess. For example, if you make a SQL statement check the User Name first. If the user exist then check the Password of that record against the password entered.

SQL1: Select * from Users where Login = ’" & Login & "’"

if SQL1 is not EOF then compare the Password from that record to the Password Entered.

SQL Injection can be applied to many places, not just Login Screen. The Hackers can alter the path of your program by predicting how you write the code and the SQL and "HiJack" your code to do the things they want to do. Please be careful.

Additional Network Troublshooting Methods

To verify or check TCP/IP routing table, you can use route print command. To add a route until next reboot, use route add command. To add a route permanently, use route add -p command.

To check local computer’s IP related settings, type ipconfig /all. This will show all related IP information including IP address for each interface, Mac(LAN card) address, default Gateway, Subnet Mask, DHCP server IP address, and DNS server names.

To release an DHCP assigned IP address, do ipconfig /release. To renew an DHCP assigned IP address do ipconfig /renew. For many Wireless Bridges/Routers, they will need you to enter Mac address into the bridge/router to enforce the security. ipconfig /all is the command to find out Mac address.

Just as DNS maps from DNS name to IP address, ARP, or Address Resolution Protocol, maps from IP address to Mac address. To check the current ARP table of this host, use arp -a, to add an ARP entry, do arp -s. we will need to use ARP to make sure the IP we are pinging is the host we intend to ping.

Common Network Troubleshooting Methods

There are DOS prompt commands helping you to conduct the TCP/IP network troubleshoot: ping, tracert, nslookup, route, telnet.

Ping is used to test point to point connection. If ping an IP is successful, it means the TCP/IP network between them is OK, but not sure abut DNS; if ping an DNS name is successful, that means DNS is OK too.

If ping an IP is not OK (time out, or unreachable), we can use tracert to know which routing segment of the whole path has problem.

If ping an DNS name is not OK, then we can use nslookup to test if your DNS is in good condition. You can either host DNS yourself, or ask your ISP to host your DNS.

There is a web site called http://www.dnsstuff.com. This site has lots of tools to help you to make sure you DNS and SMTP e-mail server are correct.

If you can ping the other site by DNS name, but still can not access that site via HTTP or FTP or SMTP or POP3, then you can use telnet thatsite portnumber to diagnose the problem. For example, telnet bnet.thesite.com 80 will be able to communicate that site using HTTP. You will need to be familiar with HTTP to continue the test. For example, the first command after this line can be:

get /

to get then home page displayed.

TCP/IP Network Settings and Terms

If a host is NOT using DHCP, then there are at least the following settings need to be filled by yourself manually:

IP Address: 192.168.1.101

Subnet Mask: 255.255.255.0

Default Gateway: 192.168.1.1

DNS Server IP: 206.13.28.12

(The numbers above are just examples.)

IP Address, or IPv4, is a 32-bit representation of a unique ID in the TCP/IP network. It has to be unique, such that the world will reach you when sending information to this IP address. Since most of the corporate TCP/IP networks are behind the firewalls, so the corporates can define their own TCP/IP addresses. Most commonly used ones are 192.168.1.x for Class C network, and 10.10.x.x for Class B network. In general, there is no way to reach the host behind the firewall with the IP address like 192.168.1.101, since there is no public host assigned to this kind of non-routable IP addresses.

When the web browser of this host 192.168.1.101 tries to send an http request to, say, www.yahoo.com, it will do the followings:

1. The browser tries to contact the DNS server, in this case 206.13.28.12, to know what the IP of www.yahoo.com is. (But how does 192.168.1.101 know how to reach 206.13.28.12 in the first place ?)

2. The host will apply the "Mask" operation, which actually is the bit-by-bit AND operation, between the destination, which is 206.13.28.12, and the subnet mask, which is 255.255.255.0. The result is not zero. So the host knows there is no direct link between itself and the DNS Server.

3. The host will have to go to the routing table to find the best route. Eventually it finds the default route, the default gateway. The IP of the default is 192.168.1.1. Please note that the "Mask" result between the Host and the default route has to be zero.

4. The host sends a DNS query regarding "what is the IP address of www.yahoo.com" to the default gateway.

5. The default gateway eventually send the DNS query to the DNS server and get back the answer to the host. The answer is: 66.94.230.36.

6. Finally, the browser goes through step 2, 3, and 4 again to send the http Get request to www.yahoo.com, and gets the response back.

The whole process takes two round trips to the Internet just to get one home page of www.yahoo.com. In the subsequent requests to www.yahoo.com, the first round trip can be saved as the browser may use the cache value 66.94.230.36 to try first.

If you are using DHCP, you still need to have IP address, Subnet mask, Default Gateway and DNS server on the host. The difference is you don’t need to manually setup them yourself, you get them automatically when your system boots up and requests them from the DHCP Server.

Tuesday, July 19, 2005

How to convert the Numeric Unicde to Real Unicode

Below is the VB code segment to convert the numeric unicode &#.....; to Real Unicode in KnownAs field of a table X:

Private Sub Command1_Click()
Dim Conn As New ADODB.Connection
Dim RS01 As New ADODB.Recordset
Dim ConnStr As String

'Set Conn = Server.CreateObject("ADODB.Connection")
ConnStr = "Provider=SQLOLEDB;Server=someserver;Database=somedb;Uid=someuser;Password=password;"
Conn.Open ConnStr

SSQL = "select * from userlistcsv_unicode2"
RS01.Open SSQL, Conn, adOpenDynamic, adLockPessimistic

Do While Not RS01.EOF
KAStr = RS01("KnownAs")
RS01("KnownAs") = UniConvert(KAStr)
RS01.Update
DoEvents
RS01.MoveNext
Loop
RS01.Close
Set RS01 = Nothing
End Sub
Function UniConvert(Str)
' 陈舵蛻
parts = Split(Str, ";")
xx = ""
For Each part In parts
pos = InStr(1, part, "#")
If pos > 0 Then
xx = xx & Left(part, pos - 2) & ChrW(CLng(Mid(part, pos + 1)))
Else
xx = xx & part
End If
Next
UniConvert = xx
End Function

How to convert big-5 tables to Unicode tables

If a Table X in a database contains the following codes (other than ASCII):
1. Big-5
2. Encoded Unicode. Like 陈
Our goal is to convert the Big-5 ones to Unicode and leave the Encoded Unicode alone. As long as we can achieve this, we will be able to display Unicode from any country correctly from the Web Browser. As to how to convert the Encoded Unicode into "Internal" Unicode, we can use a one-shot VB program to convert, and we can discuss this later.
Step 1: Export X table to ANSI CSV Text file on a English Windows Platform.
Use DTS Import/Export Wizard.
Source is X table
Destination is a CSV Text file. ANSI encoding. First Row contains Field Name.
Step 2: Convert this Text file to Unicode.
Copy this file to a Big-5 Win2000 platform.
Open this file by NotePad.
Save As Unicode.
Copy this file back to the place ready to import to SQL server.
Step 3: Import this Unicode Text file to X table.
Use DTS Import/Export Wizard.
Source is this Text File
Destination is X Table (I suggest we backup the old first just in case).
Choose Delimited, Unicode, First Row contains Field Name.
Once imported. You can use the attached asp code to verify the correctness of the code. This simple unicode ASP file only display one field: KnownAs.
Database Application Test: Simplified + Traditional Chinese + Japanese + Korean
©P¤pµX
¥Ó¯À±ö
³¢­ì§Á
ªL±ê¶Ô
¤ý¦æ°·
±d»ï¤å
马畅
¤ýܦ­d
¤ý½U
©s¥çÚ|
­S¬üªÚ
°ª®Ú伟
刘华
§õµq
¸â¦i®p

How to use COM object in .Net Code

There has been a lot of investment in COM/MTS/COM+/Win32 DLLs, and it will not be feasible to migrate that entire code base to .NET. But you don't have to worry about it because you can access your legacy code from .NET code and vice versa.

The steps:

1. Create a "Wrapper DLL" by doing: tlbimp OriginalCOM.dll OriginalCOM_net_wrapper.dll

2. Compile your code which uses this COMObject (sample below) by using the following switch:
csc /reference:OriginalCOM_net_wrapper.dll /out:ManagedClient.exe ManagedClient.cs
3. Sample Source code of ManagedClient.cs:


1 using System;
2 using OriginalCOM;
3
4 class ManagedClient
5 {
6 public static void Main()
7 {
8 CTest objTest ;
9 objTest = new CTest() ;
10 string strMessage = "15Seconds reader" ;
11 strMessage = objTest.SayHello(strMessage) ;
12 Console.WriteLine(strMessage) ;
13 Console.WriteLine("\nPress any key to exit") ;
14 Console.Read() ;
15 }
16 }


For complete details, please go to:

http://www.15seconds.com/Issue/010129.htm

Null value in Database

Null can be inserted, updated, and searched in SQL:

If you have a table T1(F1, F2, F3, F4) where F1 is Text, F2 is Date/Time, F3 is Long Integer and F4 is Currency, then you can insert Null:

Insert Into T1(F1, F2, F3, F4) values(null, null, 100, 101)

You can Select based on Null

Select * from T1 Where F1 is Null

You can update a field to Null:

Update T1 set F4 = Null where F1 = Null

You can Insert part of all the Fields and leave all the other Fields Null

Insert Into T1 (F2, F3) Values (#2/3/03#, 100)

(F1 and F4 will be Null)

I have tested all of them on MS Access 2000 database.

How to prevent too frequent refreshes from Web Broswers

No matter we are using ASP or ASP.NET, each time we post back, we refresh the whole screen, or whole frame. The reason is that the client almost always use the "submit" way (ASP way), or click buttons running at Server (ASP.NET way) to communicate with Server. These will eventually trigger the "Post Back" effect to refresh the whole screen. ASP.NET is handling it better with the View State, but still not prefect. There are still too many unnecessary refreshes. Below is a method, which uses Client Side Script with XMLHTTP, and the DIV tags to reduce the number of refreshes.This idea can be applied to both ASP and ASP.NET.

We know by making DIV display or not display, we can change the content of the client without refresh. We also know that using XMLHTTP object from client, we can send and receive XML data to and from server without postback. Combining these two, below is an example for your reference. (doubleclick the orders for the order details without refresh.)

http://gate.ebizts.com/orders/stores.asp

The source code is attached. for further information, you can go to:

http://www.aspalliance.com/das/xmlhttp.aspx

RTE control for ASP

The RTE we have so far is a framework which consists of a bunch of Javascript files scattered around a web page. The major disadvantages of this RTE are:

Not easy to use. The programmers have to know where to put which files at the right sequence.
Not possible to have more than one RTE in a page.
No undo, redo, save to file functions.
To overcome these drawbacks, I developed a new version of RTE, which is based on the RTE for ASP.NET I mentioned before, to make it work for ASP. It is not as flexible as The Custom Server Control in ASP.NET (ASP does not have the concept of Server Control), but it is a COM object fairly easy to use. Please take a look at the demo at:

http://gate.ebiztscom/RTFBox/asp/RTETest.asp

The RTETest.asp is attached:

RTETest

A ready to use SepllChecker with RTFBox for .NET

I just integrated the NetSpell Open Source Spell Checker with our RTFBox. Please take a look at:

http://gate.ebizts.com/netspell/sample1.aspx

The sample RTF code which includes Spell Checker code is here.

An Open Source Spell Checker Written in C# for Dot Net

NetSpell is a open source spelling checker written in C# under Dot Net environment. It uses the dictionary from OpenOffice.Org. The English version has 162,573 words. It has sophisticated Words Suggestion Algorithm and Near Miss Strategy, Phonetic Strategy. To gain the performance, the word list, or dictionary are compressed using Affix Compression.

I have already installed and did some evaluation. To see the demo, go to:

http://gate.ebizts.com/netspell

The user interface is not as slick as other commercial product, but that is something we can improve. It is pretty easy to plug into our Dot Net based Web server.

The NetSpell open source URL:

http://sourceforge.net/project/showfiles.php?group_id=76171

Use MSMQ to communicate between COM and NET

There are times when two processes will need to talk to each other. Besides the simplest ShellExec way, there are many other Process Synchronization and Synchronization methods provided by the specific language. But to make two or more loosely coupled processes written in different languages to communicate, MSMQ (Microsoft Message Queue) is one of the best methods: you create a queue and others join the queue. You put whatever messages into the queue, and others consume the elements in the queue. It provides both Process Communication and Process Synchronization between EXE/DLL written in, say, VB, and EXE/DLL written in, say, C#. Below is an example from MSDN:

http://msdn.microsoft.com/msdnmag/issues/03/12/MSMQandNET/

How to use Win2000 Server CDOSYS Event Sink to Process e-Mails

It is possible to register a DLL or VBScript to the Windows 2000 SMTP Event Sink, such that when E-mails arrives, or posted, will trigger the DLL or the VBScript to do certain process like Spam Block or E-Mail Redirect.

To accomplish this, we will need to download a vbscript called smtpreg.vbs from the Windows 2003 Platform 2003. The purpose of this this smtpreg.vbs is to register and to unregister the DLL’s and the VBScripts on certain events like "onarrival", "onpost" etc.

For example, if you have a DLL used to log the incoming e-mail. The registered PROGID of this DLL is called CDOTest.Class1. Now, to register this DLL to the Windows 2000 CDOSYS, type the command line:

cscript smtpreg /add 1 onarrival CDOTest.Class1 "mail from=*"

This means, on all the incoming e-mails (mail from=*), please call the class in a DLL who is registered to the registry as CDOTest.Class1.

The VB source code of this DLL is like:

Implements CDO.ISMTPOnArrival
Implements IEventIsCacheable

Private Sub IEventIsCacheable_IsCacheable()
’ just returns S_OK
End Sub

Private Sub ISMTPOnArrival_OnArrival(ByVal Msg As CDO.Message, EventStatus As CDO.CdoEventStatus)

Dim fs As New Scripting.FileSystemObject
Dim file As Scripting.TextStream
Set file = fs.OpenTextFile("c:\yamabay\test.log", ForAppending, True)
file.Write "From: " & Msg.From & vbCrLf
file.Write "To: " & Msg.To & vbCrLf
file.Write "Subject: " & Msg.Subject & vbCrLf & vbCrLf
file.Write Msg.TextBody & vbCrLf & vbCrLf
file.Close
EventStatus = cdoRunNextSink
End Sub


After you have made the DLL, registered it, and type the smtpreg.vbs command, the incoming mails will be recorded in c:\yamabay\test.log.

Click here to find the VB Project and smtpreg.vbs

Monday, July 18, 2005

How to use Perl/PHP in .NET Environment

Perl is a popular scripting language on Unix/Linux based system, and PHP is a Web computing platform using Perl as the programming language. To convert Perl/PHP based code/components to Microsoft ASP/ASP.NET platform, there are at least two approaches:

1. Package the Perl code into an ActiveX component and used it by various languages. For details, please see:

http://www.extropia.com/tutorials/misc/perl_com.html

2. Manually convert PHP code to VB.NET. For details, please read:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/aspnet-migratingphp-aspnet.asp

Approach 1 is easier, but you have to have someone who knows perl for future maintenance.

Approach 2 may take more efforts, but once converted to VB.NET, it is native .NET language. No Perl/PHP expertise needed any more.

Upload File in ASP environment without using Post Acceptor

Using Post Acceptor has always be a problem, because of the following drawbacks:

1. Session will be disconnected. That is, session variable will not be available.
2. Need to install CPSHOST.DLL on the IIS server and change the Registry entry. This is not portable and not easy to deploy the Web applications.
3. Not Reliable.

Click here to get the FilePost.htm and FilePost.asp which does the File Post job by the ASP code itself, so the above problems are automatically resolved.

The way to use FilePost.asp is very similar to the way we use PostAcceptor. It takes TargetURL as the file upload URL (default is the current virtual dir). Multiple files uploads are allowed.

How to Pass Client Time (and time zone) to Server with different locale id

As we know, different locale has different way of describing Date, Time, Currency, etc. For example, French (Belgium) can describe their date in dd.mm.yyyy format. If you need to pass the client timezone information and date time information to server for logging or performance measurement purpose. You will need to use client site script(s) to accomplish these.

Here is the javascript code to get the client time zone information:

function TimezoneOffset() {

var ldNow = new Date();

var lnOffset = ldNow.getTimezoneOffset()/60; // time zone in hour

lnOffset = -lnOffset; // make it Negative. For example, PST is -8, EST is -5.

FRMLGN.tz.value = lnOffset; // assume the form name is FRMLGN and the control name is tz

}

Here is the vbscript (Javascript similar) to pass the date/time information to server in U.S. ("en-us") locale.

Original = SetLocale("en-us")

FRMLGN.ltime.value = FormatDateTime(Now()) ’the form name is FRMLGN and the control name is ltime

Something = SetLocale(Original)

The once the server receives ltime value in Request("ltime"), it is easy to process by using CDate() or other functions suitable for the current locale, which I assume is "en-us".

Using Visio to generate .NET Code Skeleton, etc.

There is a version of Visio, Visio for Enterprise Architect, sold with Visual Studio.net 2003 System Architect. This version of Visio can help to generate the class skeleton once the UML is drawn, or to reverse engineer a Visual Studio project from code to the class diagram components of the UML.

To reverse engineer from code to UML, in VS.NET do Project --> Visio UML --> Reverse Engineer.

To do code gen, from Visio for Enterprise Architect, open the UML vsd, then do UML --> Code --> Generate.

Events and Delegates in .NET environment

Events and Delegates are a pair of terms Microsoft used to deal with the event handlers (function pointers) and events in .NET environment. It is very important to learn Events and Delegates if a develop wants to move beyond just the application development into system/component development.

In short, Delegate is just a function pointer. Any function which has the same signature as the delegate can be passed into the constructor of this delegate and becomes a registered function.

An Event a just a variable with the type of a specific delegate. Once declared as a Event, this event can add these registered function(s) (can be more than one) to become the event handlers.

For example, OnClick is a event for a Button. If we have added some functions (through the Delegate mechanism) to this event, then when this Button gets clicked, ALL the registered functions will be called.

Please note that there is no such concept called Delegate in Java, even though Java does support event handlers. For the complete explanation, please refer to:

http://www.codeproject.com/csharp/events.asp

Call WebServices from ASP using Classes

Calling Web Service from ASP.NET is quite easy. To call Web Services from ASP, we sued to use SOAP SDK. But that is not necessary.

Actually, we can develop a class called, say, WebService, in a ASP page, and use that class to call Web Services. Inside this class, we use:

Set xmlhttp = CreateObject("Microsoft.XMLHTTP")

to communicate between the Web Service and the ASP,a nd then use

Set mCol = CreateObject("Scripting.Dictionary")

to manage the web service parameters in a form.

Once we have the class ready, the caller code is as simple as below (assuming you have already included the webservice class in your page:

dim ws

set ws = new webservice
ws.url = "http://localhost/yourwebservice.asmx"
ws.method = "MethodName"
ws.parameters.Add "ParamName1",1
ws.parameters.Add "ParamName2",300
ws.parameters.Add "ParamNameN",500

ws.execute
response.Write ws.response

set ws = nothing

For details, you can go to: http://www.codeproject.com/asp/aspcallwebservice.asp

The source code of the WebService Page can be downloaded here:

http://www.codeproject.com/asp/aspcallwebservice/aspcallwebservice_src.zip

How to make HTML E-Mail with embedded images

Many HTML based e-mails have images linked to the world wide web. While the size is compact, but there are the following drawbacks:

1. The linked object/image may be deleted in the future, such that the the content of the e-mail will not be archived.
2. The E-Mail reader may not have Internet access at the time reading the e-mail (off-line reading case.)

If we can make the images embedded into this HTML file and make this HTML file self-contained, then we will not need to worry about the availability of the image and the availability of the Internet. This is particular important if you want to keep a news story happened two years ago with pictures .

You can implement this by using CDONTS (NT/2000) or CDOSYS(2000/2003 Server).

In CDONTS:
If we have a image source = logo.gif, then we will need to use the following code to include this Logo to our e-mail:
Set eMailObj = Server.CreateObject("CDONTS.NewMail")
eMailObj.BodyFormat = 0
eMailObj.MailFormat = 0
eMailObj.Body = ......... 'html code with Img Src of Logo.gif
eMailObj.AttachURL MapPath("Logo.Gif"), "Logo.gif"
eMail.Obj.Send

In CDOSYS:

Set iMsg = Server.CreateObject("CDOSYS.Message")
'prepare strHTML and make Img Src Login.gif
iMsg.HTMLBody = strHTML

iMsg.AddRelatedBodyPart MapPath("Logo.gif"), "Logo.gif", cdoRefTypeId 'cdoRefTypeID = 0

iMsg.Send

Disable AutoComplete for Login Forms

The AutoComplete feature of the Internet Explorer is convenient, but it is insecure if you use a shared computer to login, or some people comes to your computer to login as you. They even don't need the user name and the password. The browser will autocomplete for them.

There is a way to turn off AutoComplete from the IE browser (Tools->Inter Options->Content->Auto Complete), but in many cases you either forgot to turn off or your are using shared computers which has the settings you can't change. Even you turn off to make it safe, you still want to turn it on for some Web applications.

Autocomplete=off is an attribute you can add in the login form tag to disable the autocomplete for that form, regardless of the IE settings. I suggest we add that for all the Web Login applications. After the implementation, please test it comprehensively too.

How to Integrate CHAP Login Autehntication with the encrypted passwords in database

We have talked about the Yahoo Mail Compatible CHAP login in my last message, we also have talked about MD5 encrypted password in the database back the while ago. Now, how do we integrate them to make the passwords secure for both Internet Users and the Database Users.

When the users create/assign the password on the password creation/modification screen, at the Javascript/client side, we send back the followings to the Server:

X = MD5(password)

When server receive this MD5(password), it just save it to the password database field, so the database users will not be able to view the clear text password.

When this user logs in, the server sends the Challenge, and he/she types user and and password. The client side Javascript will do:
X = MD5(password)
Y = X + Challenge
Z = MD5(Y)
and send back Z and Challenge to the Server. (This is the standard client side CHAP we discussed last time)

Now, the server will use W= MD5(password) from the database. Then do a
V = W + Challenge
U = MD5(V)

If U and Z are equal, then password is correct. Otherwise not correct.

Please note that:
1. Password never travels across the Internet.
2. Dataset does not store the clear text password.

This concludes the integration of CHAP Login and encrypted password in database.

CHAP Login Security Implementation

"How secure is your system ?" is always the question any potential customers will ask. If we only have password protection for our sites, it is not enough and people may reluctant to use this product.

I recently developed a "CHAP Login" mechanism which will make our Web Server more secure. The term "more secure" here means harder to intercept the password, and/or harder to break in without the password.

First of all, CHAP is one of the industry recognized authentication protocol, it stands for "Challenge/Handshake Authentication Protocol". The benefits of this protocol are:

1. Password never travel across the Internet, only the generated Digest, or Hash, does.

2. The Server Challenges the Browser with a random number, called Challenge, each time when it presents the Login Screen. The Challenge will be used, together with the password, to generate the Hash/Digest. The will prevent from the so called "Replay Attack", which intercepts a successful login session and break in.

I have implemented it on one of my Web system and test it successfully. It is located at:

http://www.yamabay.com/NTPortal/webMail/inbox/loginy.asp

You can use the user test and password test to try it out.

It takes a Server Site COM Object and the Client Site JavaScript to accomplish this. Source code are attached.

By the way, Yahoo! Mail is using exactly the same login mechanism as I mentioned here.