Oct 30, 2007

Get Physical File Path, Virtual Directory

oFSO = Server.CreateObject("Scripting.FileSystemObject")
sPath = Server.MapPath("Moozik\")
fRoot = oFSO.GetFolder(sPath)


(web paths, not full physical)

My file: /Test/Myfile.aspx
Virtual directory: /Test/VirtualDir/
Code: Server.MapPath("VirtualDir/")

or if you are in a higher directory:

MyFile: /Test/Something/MyFile.aspx
Virutal: /VirtualDir/
Code: Server.MapPath("../../VirtualDir/")

You are probably just getting the virtual path (the one that gets sent into
MapPath) wrong.

How To Change Vista Desktop Icon Size

Just start using Windows Vista and found the desktop icon is too large which to allow me to put more items on desktops.

so... any of you face the same ?


Solution:

Right-click the desktop, choose View, and choose between "Classic icons", "Medium icons" and "Large icons" (the default is medium).

=)

Crystal Report VS Microsoft Report

Now I develop under Visual Studio 2005 and I use only Microsoft report system.

Those are the benefits I found:

- xml structure, so you can programmatically modify report structure;

- built in support for DataSets as data source;

- good parameters system;

- much faster than CR in rendering (i have reports > 1.000 pages).


Microsoft report system have some never fixed bug, as visual studio 2005, but for my experience is much better than Cr.


Win App Local Application Path

LocalReport.ReportPath = _

My.Application.Info.DirectoryPath & "\Reports\" & "myReport.rdlc"



Where myReport.rdlc is located under Reports folder in my win app program.



Oct 29, 2007

Using Microsoft Report Viewer

Create a Microsoft report:

1. add in a list.
2. add in table
3. drag data from data source to table

Dim voucher As New Voucher
DataGridView1.DataSource = voucher.FillVoucherHeader
DataGridView1.AutoResizeColumns()

DataGridView2.DataSource = voucher.FillVoucherItems
DataGridView2.AutoResizeColumns()

DataGridView3.DataSource = voucher.FillVoucherTotal
DataGridView3.AutoResizeColumns()

Me.VoucherTotalTableAdapter.Fill(Me.cpvdbDataSet.VoucherTotal)
Me.VoucherItemTableAdapter.Fill(Me.dsCheque.VoucherItem)
Me.VoucherHeaderTableAdapter.Fill(Me.dsCheque.VoucherHeader)

Me.ReportViewer1.RefreshReport()

Using VBC Command Line Compiler

Do you ever compile with command line ?

Just recall back Java Learning during university lab.

Let's try:
  1. From the Start menu, click on the Accessories folder, and then open the Windows Command Prompt.

  2. At the command line, type vbc.exe /imports:Microsoft.VisualBasic,System sourceFileName and then press ENTER.

    For example, if you stored your source code in a directory called SourceFiles, you would open the Command Prompt and type cd SourceFiles to change to that directory. If the directory contained a source file named Source.vb, you could compile it by typing vbc.exe /imports:Microsoft.VisualBasic,System Source.vb.

  3. To compile with reference file:
    vbc /reference:metad1.dll,metad2.dll /out:out.exe input.

Oct 28, 2007

Enable Windows Vista Administrator Account

Introduction

If for whatever reason you must login Windows Vista with the Administrator account this guide will show you how it’s done.

Warning: Running as Administrator in Windows Vista bypasses all security (UAC) and is NOT recommended. If you decide to use the Administrator account don’t complain when you start having problems.

Enable the Administrator Account

  1. Open the command prompt with Administrative privileges by opening the Start Menu, type cmd in the search box, and then press Ctrl+Shift+Enter to open cmd with admin rights.
  2. Type the following in the command prompt and press Enter after:

    net user administrator /active:yes

  3. Restart your computer and logon as Administrator.

Note: You might want to set a password for the administrator’s account for at least a little protection.

Disable the Administrative Account

To disable the Administrative account run the Net User command demonstrated above while logged on an account with administrative privileges but not as the Administrator account and replace yes with no.

or

Disable the User Account
To disable the user account run the Net User command demonstrated above while logged on an account with user privileges but not as the Administrator account and replace yes with no.

-------------------------------------------------------------------------------------------

Here is another way!

Remember that cute "Administrator" account you see when you login to safe mode in XP? That's the built-in administrator account that's installed by default, and disabled by default too, after a little digging-in I made this tutorial that'll let you enable and use this account in normal mode, and with a little other tweak, enjoying an XP-like administrator experience, while UAC is left ON (or off, it doesn't matter), but with no prompts or right clicks.


For Windows Vista Ultimate/Business/Enterprise:
1- Click Start, and type "secpol.msc" in the search area and click Enter.
(You may receive a prompt from UAC, approve/login and proceed)

2- In the left list, choose "Local Policies", then "Security Options"

3- Set "Accounts: Administrator account status" to Enabled.

4- Set "User Account Control: Admin Approval Mode for the Built-in Administrator account" to Disabled.


For Windows Vista Home Basic/Home Premium:
1- Click Start, and type "cmd" in the search area, right click on "Command Prompt" and select 'Run as Administrator".

2- In the command prompt type "net users Administrator /active:yes" (Note the capital "A" in Administrator) and press Enter, you will get a confirmation as "The command completed successfully".

3- Click Start, and type "regedit" in the search area and click Enter, navigate to: [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]Double click on "FilterAdministratorToken" and set it to "0"

*************************************

Now log-off, and you'll see new account named "Administrator" is available, click on it to login.
Now you are the master of your domain! I recommend if you're going to use this method is to apply it as soon as you do a fresh install of Windows, so you can simply delete whatever administrator you've created in the setup process, and make this one the "real" administrator for your PC, also you can rename this new admin account or change its password like any other account from "User Accounts" in the Control Panel.

A last note/disclaimer:
Please note that disabling UAC and using the built in Adminstrator account will also disable IE7 "Protected Mode", fore more information and a work around please see this post.
Please apply this procedures only if you know what you're doing. Disabling security features in the operating system is not something recommended to the average Joe, and for sure I won't be held accountable for any damaging happens to your system or files resulting from running a full administrator account all the time.


Special thanks to:

- Farstrider for providing the location of the relevant register keys that made applying this method to the home versions of Vista possible!.

- bradavon for his comment/solution of IE7 protected mode.

Oct 19, 2007

Connection Strings

Connection Strings

SQL Server 2005
SQL Native Client ODBC Driver

1. Standard security


Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

Are you using SQL Server 2005 Express? Don't miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.

2. Attach a database file on connect to a local SQL Server Express instance


Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

3. Attach a database file, located in the data directory, on connect to a local SQL Server Express instance


Driver={SQL Native Client};Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.


-----------------------------------------------------------------------------------------------

SQL Native Client OLE DB Provider

1. Standard security


Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

Are you using SQL Server 2005 Express? Don't miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.

2. Trusted connection


Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;

Equivalent key-value pair: "Integrated Security=SSPI" equals "Trusted_Connection=yes"


3. Encrypt data sent over network


Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;Encrypt=yes;

4. Attach a database file on connect to a local SQL Server Express instance


Provider=SQLNCLI;Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.


5. Attach a database file, located in the data directory, on connect to a local SQL Server Express instance


Provider=SQLNCLI;Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

------------------------------------------------------------------------------------------------

SqlConnection (.NET)

1. Standard Security


Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Use serverName\instanceName as Data Source to connect to a specific SQL Server instance.
Are you using SQL Server 2005 Express? Don't miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.

2. Standard Security alternative syntax

This connection string produce the same result as the previous one. The reason to include it is to point out that some connection string keywords have many equivalents.

Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;



3. Trusted Connection


Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

4. Trusted Connection from a CE device

Often a Windows CE device is not authenticated and logged in to a domain. To use SSPI or trusted connection / authentication from a CE device, use this connection string.


Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword;

Note that this will only work on a CE device.

5. Connect via an IP address


Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;

DBMSSOCN=TCP/IP. This is how to use TCP/IP instead of Named Pipes. At the end of the Data Source is the port to use. 1433 is the default port for SQL Server.

6. Attach a database file on connect to a local SQL Server Express instance

Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;




Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.


7.Attach a database file, located in the data directory, on connect to a local SQL Server Express instance


Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

8.Using an User Instance on a local SQL Server Express instance

The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server 2005 instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL Server instance to a user with limited administrative rights on the computer.


Data Source=.\SQLExpress;Integrated Security=true;AttachDbFilename=|DataDirectory|\mydb.mdf;User Instance=true;

To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure 'user instances enabled', '1'. To disable the functionality execute sp_configure 'user instances enabled', '0'.

Using CDO Email Encoding

public sub SendEmail(_
astrRecipientEmailAddress, _
astrCCEmailAddress, _
astrBCCEmailAddress, _
astrSenderEmailAddress, _
astrEmailSubject, _
astrEmailText)

'Dimension local variables
Dim objCDOMail


'Create Server Object
Set objCDOMail = Server.CreateObject("CDO.Message")

objCDOMail.From = astrSenderEmailAddress
objCDOMail.To = astrRecipientEmailAddress
objCDOMail.Subject = astrEmailSubject
objCDOMail.TextBody = astrEmailText

'this is the encoding part if you are using text as mail content
objCDOMail.BodyPart.Charset = "utf-8"
objCDOMail.TextBodyPart.Charset = "utf-8"

'this is the encoding part if you are using html as mail content
'create a proper html tag
'with Content-Type: text/html; charset=utf-8
objCDOMail.BodyPart.Charset = "utf-8"
objCDOMail.HtmlBodyPart.Charset = "utf-8"


'check whether to Copy or BCC this email
if len(astrCCEmailAddress) > 0 then
objCDOMail.CC = astrCCEmailAddress
end if
if len(astrBCCEmailAddress) > 0 then
objCDOMail.BCC = astrBCCEmailAddress
end if

objCDOMail.Send


end sub

MSSQL 2005 Backup and Restore SQL Syntax

RESTORE DB
---------------
RESTORE DATABASE myNewDb
FROM DISK = 'C:\Documents and Settings\Administrator\Desktop\family_backup.bak'
WITH MOVE 'myOldDb_Data' TO 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\myNewDb.mdf',
MOVE 'myOldDb_Log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\myNewDb.ldf',
REPLACE

**Note:
If you are about to restore the old version sql2000 DB,
you can create a sql2005 db with the same name first,
change the DB Properties > Options > Capability Level > SQL2000 (80),
then you proceed with the above sql syntax


BACKUP DB
--------------
use [myNewDb]
BACKUP DATABASE [myNewDb] TO DISK = N'D:\Database Backup\myNewDb.bak'
WITH NOFORMAT, NOINIT, NAME = N'myNewDb-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO

Oct 18, 2007

Runtime Web.config / App.config Editing




Web.config configuration files and app.config project item files, which get converted to "ExecutableName.exe.config" at build time, both support the convenient appSettings section with its own read method in the System.Configuration.ConfigurationSettngs class. The appSettings section stores element name / value pairs in the format:

You can store as many of these elements as you want, read them out at runtime, and use the values in the application. If you have an item that contains multiple values and you would like to keep them together, you can store them as a single string, delimited with a pipe | or other symbol, read them out at runtime, and call the String.Split() method to parse them into a useable string array.

I often read out my appSetting values into a NameValueCollection at runtime, which provides one-shot acess to the entire collection in memory:

NameValueCollection mySettings = System.Configuration.ConfigurationSettings.AppSettings;
string connStr = mySettings["connString"];

But what about being able to change, add, and save appSettings items while that app is running in response to user input or other actions, instead of just reading them out? Nada, Zippo, Efes! You have to open the config file manually and add them by "hand". Well that kinda stinks, don't you think? So here's my take on a convenient little class that allows you to either modify, add or delete any appSettings element, in either your Executable, Console or ASP.NET web application at runtime, on the fly. Bear in mind of course, that if you modify a web.config on a running ASP.NET app, the ASP.NET worker process will recycle. Users currently using your app aren't exactly guaranteed to have a fun experience when this happens...

Original Source: http://www.eggheadcafe.com/articles/20030907.asp
By Peter A. Bromberg, Ph.D.

Oct 17, 2007

Failed to enable constraints













Did any one face this issue before ?

I had created odbc connection to mysql in .net 2.0 dataset.
Having issue on "fillby" transaction after i create a new select query.











In the front end page, having constraint issue too.
I had try to enable the dataset and set auto increment in the dataset to solve these issue on my local, but when upload to the server, the error happen again. :S

Any one have any idea ?




Oct 16, 2007

CAL3D Modeling Exportation

CAL3D Exportation

During FYP 3D Game , Novice Odyssey , I am lack of time to research Cal3D ,
thus, I am using MD2 to repalce Cal3D, Cal3D had been listed in my future list.
Who is interesting, may refer it:

1. create a box, modifier > editable mesh.
2. name your box head[0].
2. create bones for charactor and name your bones.
3. click your head[0], modifier > skin.
4. in skin modifier, add bones where the mesh covered.
5. click envelop, adjust the skin size.
6. click your box, utitlies > more > body paint.
7. send your box to body for uv map and texture.
8. in body paint, click your map and create a color of mapping.
8. adjust your uvmap vertex, paint your texture.
9. set your texture saiz as 128 x 128.
10. save your texture as tga file.
11. send back to 3d max
12. click m, material, beside your (standard) button, name your material.
13. material name should b head[0], body[1], leg[2]...
14. create your animation.
15. export your skeleton first.
16. click your mesh,export yuur mesh and choose your skeleton file as reference.
17. export your material, you wil see ur head[0] material.
18. export your animation.
19. create cfg files as below :

#
# cal3d model configuration file
#
# model: 2
#

scale=0.5

skeleton=m4.csf

animation=1.caf

mesh=m4_head.cmf
mesh=m4_body.cmf


material=1.crf
material=2.crf

20. create your batch file.
21. done.

How To Create MD2 ( Animated Model )

MD2 was my fyp game project 's modeling technique.
Today refresh all my notes in my Yahoo! notes and dig out some stuff to share over here.

How to create md2

1) in 3d max create the snow man, save snowman.max
2) convert into mesh or patch
3) in photoshop create texture 128 x 128
4) image> index color save as snowman.bmp
5) in 3dmax, press m, set only one material map
6) use body paint to paint it
7) in body paint,click ur object
8) click the mapping, scale down to seperate each mapping in diff place
9) paint it
10) in body paint save texture as bmp as 128x 128 (mus change later)
11) send back to 3dmax
12) qtip exporter, rename tris.pcx to snowman.pcx
13) use photoshop to change texture snowman.bmp put same name snowman.md2
14) check for the saiz 128x128 and the 8 bit color
15) u are done!!

Oct 12, 2007

SVN Server Setup

Source Control Subversion Server Setup Under Windows

Get SVN Server Tools
http://subversion.tigris.org/ ( original subversion )
http://www.collab.net/products/subversion/ ( CollabNet Subversion)

Get SVN Client Tools
http://tortoisesvn.net/

Get Visual Studio Intergration Add-On
http://www.VisualSvn.com/
http://ankhsvn.tigris.org/


A) Download Subversion

You'll need the latest version of..

B) Install Subversion

  1. Unzip the Windows binaries to a folder of your choice. I chose c:\program files\subversion\ as my path.
  2. Now, add the subversion binaries to the path environment variable for the machine. I used %programfiles%\subversion\bin\

  3. You'll also need another environment variable, SVN_EDITOR, set to the text editor of your choice. I used c:\windows\notepad.exe

C) Create a Repository

  1. Open a command prompt and type
    svnadmin create "c:\Documents and Settings\Subversion Repository"
  2. Navigate to the folder we just created. Within that folder, uncomment the following lines in the /conf/svnserve.conf file:
    [general]
    anon-access = read
    auth-access = write
    password-db = passwd

    Next, uncomment these lines in the /conf/passwd file:

    [users]
    harry = harryssecret
    sally = sallyssecret

D) Verify that everything is working

  1. Start the subversion server by issuing this command in the command window:
    svnserve --daemon --root "C:\Documents and Settings\Subversion Repository"

    You can create shortcut and set the target
    "C:\Program Files\CollabNet Subversion Server\svnserve.exe" -d -r
    C:\Documents and Settings\Subversion Repository
  2. Create a project by opening a second command window and entering this command:

    svn mkdir svn://localhost/myproject

    It's a standard Subversion convention to have three folders at the root of a project:

    /trunk
    /branches
    /tags

  3. At this point, Notepad should launch:

    Enter any comment you want at the top of the file, then save and exit.
  4. You'll now be prompted for credentials. In my case I was prompted for the administrator credentials as well:

    Authentication realm:  0f1a8b11-d50b-344d-9dc7-0d9ba12e22df
    Password for 'Administrator': *********

    Authentication realm: 0f1a8b11-d50b-344d-9dc7-0d9ba12e22df
    Username: sally
    Password for 'sally': ************

    Committed revision 1.

    Congratulations! You just checked a change into Subversion!

E) Start the server as a service

  1. Stop the existing command window that's running svnserve by pressing CTRL+C.
  2. Copy the file SVNService.exe from the zip file of the same name to the subversion\bin folder.
  3. Install the service by issuing the following commands:
    svnservice -install --daemon --root "C:\Documents and Settings\Subversion Repository"
    sc config svnservice start= auto
    net start svnservice
  4. Test the new service by listing all the files in the repository:
    svn ls svn://localhost/

    You should see the single project we created earlier, myproject/

F) Set up the shell extension

  1. Run the TortoiseSVN installer. It will tell you to restart, but you don't need to.
  2. Create a project folder somewhere on your hard drive. Right click in that folder and select "SVN Checkout..."



    type svn://localhost/myproject/ for the repository URL and click OK.


  3. Create a new file in that directory. Right click the file and select "TortoiseSVN, Add"


  4. The file hasn't actually been checked in yet. Subversion batches any changes and commits them as one atomic operation. To send all your changes to the server, right click and select "SVN Commit":



And we're done! You now have a networked Subversion server and client set up on your machine. Note that the default port for svnserve is 3690.


Extra Command:
SVN Client Command: svn
-----------------------
add
blame (praise, annotate, ann)
cat
changelist (cl)
checkout (co)
cleanup
commit (ci) -m "my log message"
copy (cp)
delete (del, remove, rm)
diff (di)
export
help (?, h)
import
info
list (ls) -v
lock
log -v
merges
mergeinfo
mkdir
move (mv, rename, ren)
propdel (pdel, pd)
propedit (pedit, pe)
propget (pget, pg)
proplist (plist, pl)
propset (pset, ps)
resolved
revert
status (stat, st) -u -v
switch (sw)
unlock
update (up)


SVN Admin Command: svnadmin
-----------------------------
crashtest
create
deltify
dump
help (?, h)
hotcopy
list-dblogs
list-unused-dblogs
load
lslocks
lstxns
recover
rmlocks
rmtxns
setlog
setrevprop
verify



SVN Look Command: svnlook
--------------------------
author
cat
changed
date
diff
dirs-changed
help (?, h)
history
info
lock
log
propget (pget, pg)
proplist (plist, pl)
tree
uuid
youngest


SVN Dump Fileter Command: svndumpfilter
----------------------------------------
exclude
include
help (?, h)


SVNServe Daemon: svnserve
---------------------------
svnserve -d -r /path/to/repo

SVN Windows Service
---------------------------
sc create svn
binpath= "C:\svn\bin\svnserve.exe --service -r C:\repos"
displayname= "Subversion Server"
depend= Tcpip
start= auto

C:\> sc create svn
binpath= "\"C:\program files\svn\bin\svnserve.exe\" --service -r C:\repo
displayname= "Subversion Server"
depend= Tcpip
start= auto


C:\> net stop svn
C:\> net start svn







error C4430: missing type specifier - int assumed. Note: C++ does not

Compile error with Visual C++ 2005 / Orcas : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Solution:
Compiler expect (const int) not (const).

Oct 11, 2007

ASCII/Multibyte to Unicode conversion

 
ASP.NET, All Topics, C# , .NET >> C# Database >> Unedited Reader Contributions
http://www.codeproject.com/useritems/ASCIIMB2UnicodeTSQL.asp

ASCII/Multibyte to Unicode conversion
By carlop().

An article about converting ASCII/Multibyte to unicode using C# and SQL/CLR Integration
C# (C# 2.0), SQL
Windows (WinXP), .NET (.NET 2.0)
Win32, SQL (SQL 2005), VS
DB, Dev
Posted: 8 Feb 2007
Updated: 16 Feb 2007
Views: 15,212
Note: This is an unedited reader contribution  

7 votes for this article.
Popularity: 2.62. Rating: 3.1 out of 5.

Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report this article.

Sample image

Introduction

A common problem when converting legacy database applications is that our customers have a lot of data and they don't want to loose it. Probably data strings are encoded in ASCII / Multibyte but our new system uses NVARCHAR fields. So the problem is that we have to convert old data into Unicode. This is exactly what we'll do.

I have to highlight that the approach I will present is 'oversized' for most cases: in a common scenario you will deal with a single codepage, in that case SQL Server built-in tools are enough. But there are situations that requires a more advanced approach, such as when you have a legacy database that stores strings with different codepages.

As a complete example to show you capabilities of SQL-CLR integration I've also decided to use a Win32 API to perform the conversion, so that you can also see how use P/Invoke from SQL. This can be useful if you have an old DLL and want to use it... but *beware* that it can be really dangerous... if you don't have full knowledge of what you're doing you can keep down the entire SQL Server process !!!

Just a note: I do not provide a test project since the code I will show here is really simple, you can use copy & paste, it's faster !

Solution

The solution I want to show is simple and powerful at the same time. It is made of two logical parts: First we'll build the conversion routine as a standard C# function. Secondly we'll integrate it into SQL Server as a function, so you can use with T-SQL.

Clearly, depending on you application scenario, this may not be the best approach, so once you have the conversion routine you may choose to follow my approach or you may prefer to use it in an external application that performs a batch conversion or you may think of something else.

Part #1: create the conversion routine.

I've used the following well known Win32 API:

int MultiByteToWideChar(
UINT CodePage,
DWORD dwFlags,
LPCSTR lpMultiByteStr,
int cbMultiByte,
LPWSTR lpWideCharStr,
int cchWideChar
);

Here there's the C# signature that can be used for P/Invoking:

  [DllImport("kernel32.dll")]
private static extern int MultiByteToWideChar(
uint CodePage,
uint dwFlags,
[MarshalAs(UnmanagedType.LPArray)] Byte[] lpMultiByteStr,
int cbMultiByte,
[Out, MarshalAs(UnmanagedType.LPArray)] Byte[] lpWideCharStr,
int cchWideChar);

Now it's quite easy to write a class that performs a conversion:

namespace ConvUtils {

public static class Unicode {

public static SqlString ConvToUnicode(SqlInt32 codepage , SqlString multibyteString) {
byte[] b = (byte[])iConvToMultibyteArray(multibyteString);
return (SqlString)ToUnicode((uint)(int)codepage, b);
}

private static string ToUnicode(uint codepage, Byte[] lpMultiByteStr) {
Byte[] lpWideCharStr = new Byte[2*lpMultiByteStr.Length];
MultiByteToWideChar(codepage, 0, lpMultiByteStr, lpMultiByteStr.Length, lpWideCharStr, 2*lpMultiByteStr.Length);
return System.Text.Encoding.Unicode.GetString(lpWideCharStr);
}


private static SqlBinary iConvToMultibyteArray(SqlString multibyteString) {
byte[] result = multibyteString.GetUnicodeBytes();
return (SqlBinary)result;
}
}
}

The example is quite easy and does not require any other explanation. The SqlTypes has been used because I will integrate it into SqlServer, but if you don't need it you may replace them with strings and Byte arrays.

I've also decided to let the codepage be a parameter since the codepage on your PC or on SQL Server can be different from the one needed for the conversion.

Part #2: SQL Server code

Ok, now we have a C# code that converts ASCII/Multibyte into Unicode. The next step is to integrate it into SQL Server so that any database user can have access to this conversion routine:

First create a DLL that can be hosted by SQL Server: all we have to do is to add the [SQLFunction] attribute to the ConvToUnicode :

    [SQLFunction] 
public static SqlString ConvToUnicode( …

Finally build the DLL and integrate it into SQL with a script that is like the following one:

use TESTDB 
go
exec sp_configure "clr enabled", '1'
go
reconfigure
go
-- for test purpouses only, not recommended in production environments
ALTER DATABASE TESTDB SET TRUSTWORTHY ON
go

begin try
CREATE ASSEMBLY [asmUni] FROM 'c:\project_output_dir\uniconv.dll' with permission_set=UNSAFE
end try
begin catch
alter assembly [asmUni] FROM 'c:\project_output_dir\uniconv.dll' WITH UNCHECKED DATA
end catch
go

if exists(select name from sys.objects where name = 'csConvToUnicode') drop function [dbo].[csConvToUnicode]
go
CREATE FUNCTION [dbo].[csConvToUnicode] (
@codepage int,
@multibytestr nvarchar(max)
) returns nvarchar(max)
AS EXTERNAL name [asmUni].[ConvUtils.Unicode].[ConvToUnicode]
go

That's all !

Now you can use this function like any other, for example in a classic select statement, to create a view or to create a trigger that automatically keeps your data updated.

Just a final example on how we can use this function in a T-SQL statement (950 is the codepage for traditional chinese):

select 
description,
dbo.csConvToUnicode(950, description) as converted
from testtable

description converted
----------------------- -------------------
¨àµ£ºô¸ô¦w¥þ 兒童網路安全
°ê»Ú¸ê°T °T°T°T°T°T 國際資訊 訊訊訊訊訊
°ê»Ú¸ê°T °T°T°T°T°T 國際資訊 訊訊訊訊訊
a a
Áô¨pÅv¬Fµ¦ 隱私權政策
test c test c

Conclusion

I have shown a really simple but powerful way to leverage the CLR integration provided by SqlServer to convert old ASCII/Multibyte data into Unicode. I Hope that this is a good starting point for your personal solution.

History

February 16th, 2007 - Added more comments on introduction
February 8th, 2007 - First Version

About carlop()


10 years of hard coding... and it's going on !

Click here to view carlop()'s online profile.



Add this article to:

Discussions and Feedback

14 comments have been posted for this article. Visit http://www.codeproject.com/useritems/ASCIIMB2UnicodeTSQL.asp to post and view comments on this article.
Updated: 16 Feb 2007 Article content copyright carlop(), 2007
everything else Copyright © CodeProject, 1999-2007.

Useful Chinese Links

Chinese links

Chinese script, Free Chinese fonts, Writing Chinese, Chinese computing, Chinese radio, Chinese newspapers, Chinese dictionaries, Chinese translation, Chinese courses, Chinese names, Chinese calligraphy, Chinese computing, Chinese philosophy, Chinese forums, Miscellaneous


Chinese script

中国文字研究与应用中心 (Center for the Study of Chinese Characters and Their Applications)
http://www.ideograms.org

A history of written Chinese
http://www.pinyin.info/readings/texts/visible/

Information about and articles on Chinese characters and the Chinese script
http://en.wikipedia.org/wiki/Chinese_character
http://www.chinaorbit.com/china-culture/chinese-characters.html
http://www.chinaknowledge.de/Literature/script.html

Pinyin/Zhuyin Converter - converts Chinese characters to pinyin or zhuyin
http://www.pin1yin1.com

Free Chinese fonts

http://www.sino.uni-heidelberg.de/edv/sinopc/chinese_fonts.htm
http://www.indeed.com.tw/download.html
http://www.yale.edu/chinesemac/pages/fonts.html
http://www.twinbridge.com

Chinese Translation
Chinese Translation
Our Price:$10.00

Writing Chinese

Writing Chinese Characters - and how to count the strokes
http://www.sungwh.freeserve.co.uk/methods/bihua.htm

Animated Chinese characters - shows you how to write individual characters
http://ocrat.com/ocrat/chargif/

Videos showing you how to write Chinese characters stroke by stroke
http://www.chineselearner.com/writing/symbol/

Online Chinese radio

China Radio International - in Mandarin and many other languages
http://www.cri.com.cn

Beijing Music Radio (北京音乐台) - in Mandarin
http://fm974.tom.com

Radio Shanghai (上海人民广播电台) - in Mandarin
http://www.radioshanghai.com

Radio Taiwan International (中央廣播電台) - in Mandarin, Taiwanese, Hakka, Cantonese and various other languages): http://www.cbs.org.tw

BCC (中國廣播電台) - in Mandarin, Taiwanese and Hakka
http://www.bcc.com.tw

Voice of Taipei (台北之聲) - in Mandarin and Taiwanese
http://www.vot.com.tw

RTHK (香港電台) - in Cantonese
http://www.rthk.org.hk

BBC World Service - in Mandarin and Cantonese
http://www.bbc.co.uk/chinese/

Radio Free Asia - in Mandarin and Cantonese
http://www.rfa.org/english/

Melody Studio - Chinese, Taiwanese and Cantonese music
http://www.melodystudio.com/

Online Chinese newspapers

China

People's Daily (人民日报)
http://www.peopledaily.com.cn

Taiwan

China Times (中時電子報)
http://news.chinatimes.com

Hong Kong

Ming Pao News (明報新聞網)
http://www.mingpaonews.com

Apple Daily (蘋果日報)
http://www.appledaily.com

Singapore

Lianhe Zaobao (联合早报)
http://www.zaobao.com

Online Chinese dictionaries

http://www.chinalanguage.com/dictionaries/ccdict/
http://www.yourdictionary.com/languages/sinotibe.html
http://www.mdbg.net/chindict/chindict.php
http://www.mandarintools.com/chardict.html
http://www.pristine.com.tw/resources/lexicon.php
http://zhongwen.com
http://www.tigernt.com/dict.shtml
http://www.chinese-tools.com/tools/dictionary.html
http://www.chinesedic.com
http://www.chinese-dictionary.org
http://www.kanjinetworks.com
http://www.clearchinese.com/chinese-english-dictionary.htm
http://chdw.de
http://app.chinesesavvy.com/services/dictionary/DictionarySearchPO.ot
http://www.ilearnchinesehere.com

Picture-based Chinese character/word dictionary
http://www.vertical-sun.com/hanzi

Speaking Chinese English Dictionaries
http://moosenose.com/speakingpinyin.htm
http://app.chinesesavvy.com/services/dictionary/sentence/DictionarySentencePO.ot

Chinese Electronic talking dictionaries
http://www.ectaco.com

Chinese language resources - information, dictionaries, etc
http://www.chinalanguage.com
http://www.easechinese.com

Online Cantonese dictionary
http://www.cantonese.sheik.co.uk/scripts/wordsearch.php

Online Shanghainese/Wu dictionaries
http://dict.zanhe.com
http://www.glossika.com/en/dict/wudict.php

Online Taiwanese dictionary
http://daiwanway.dynip.com/cgi/tdict.acgi

Photo dictionary of rare Chinese characters (with explanations in Japanese)
http://homepage2.nifty.com/Gat_Tin/kanji/kaindex.htm


Online Chinese translation

Online translation from English into Chinese (Simplified & Traditional) of websites and text: http://www.readworld.com/tran

Online Chinese courses/lessons

Cantonese
http://www.khuang.com/chinese/cantonese.asp
http://www.chinawestexchange.com/Cantonese/

Mandarin
http://www.csulb.edu/~txie/ccol/content.htm
http://www.chineseon.net
http://www.csulb.edu/~txie/online.htm
http://www.languageguide.org/mandarin/
http://www.chinese-lessons.com
http://www.chinese-outpost.com/language/
http://www.chinese-tools.com/learn/chinese
http://www.zapchinese.com
http://www.sinoling.com
http://learnchinese.elanguageschool.net
http://www.clearchinese.com/learn-chinese/
http://www.effectivelanguage.com/mandarin.html
http://www.chinesepod.com
http://www.clearchinese.com
http://www.activechinese.com
http://www.china-8.com/cms/sites/china-8/section.cfm?id=12
http://parlezchinois.free.fr
http://www.loquella.com/learn-chinese
http://www.echineselearning.com
http://www.chinese-course.com

Mandarin phrases (some with audio)
http://www.bbc.co.uk/languages/chinese/
http://www.wku.edu/~yuanh/AudioChinese/
http://www.chinaadviser.com/useful_chinese_phrases.html
http://www.languageguide.org/mandarin/
http://www.slanguage.com/fun_chinese_mand.html

Shanghainese
http://www.linguasinica.com/Shanghai/
http://www.zanhe.com
http://www.shanghai.or.jp/zw/shanghai/

Taiwanese
http://www.glossika.com/en/dict/
http://www.tacpa.org/wdcts/mtl/intro.html
http://edu.ocac.gov.tw/lang/taiwanese/

Basic lessons in Mandarin, Taiwanese, Shanghainese and Hakka
http://www.hqpin.com/eindex.html

China Online - inlcudes articles, phrases and information about Chinese languages
http://www.chinaonline.cn.com/chinese_language.html

Online resources for learning Mandarin
http://www.chinesetools.eu

HyperChina - an interactive Mandarin Chinese course on CD-ROM http://www.sinologic.com/HyperChina.html

Chinese Phrases for Travellers (with audio)
http://chinese.travel-way.net

Chinese Writing Master - software that helps you learn how to write Chinese characters
http://www.cchar.com

Early Learning - Chinese: Free printable bilingual (English- Mandarin Chinese) materials and tips for parents, homeschoolers, caregivers, daycare/child-care providers, babysitters, or anyone who works with young children who are learning chinese/english
http://www.earlylearning-chinese.com


Chinese names

Your name in Chinese
http://www.mandarintools.com/chinesename.html
http://www.qualitylanguage.com/name_translator.htm
http://www.transname.com
http://www.chinese-tools.com/names
http://www.chinesenames.org
http://www.chine-informations.com/mods/prenoms/
http://definingcharacters.com

Chinese Seals

A guide to the hundred most common Chinese surnames
http://www.geocities.com/Tokyo/3919/hundred.html

An introduction to Chinese names and other interesting facts about Chinese language and culture: http://www.wlu.edu/~hhill/btl.html

Chinese calligraphy, translation and design - get your name in beautiful Chinese calligraphy: http://www.transname.com


Chinese calligraphy

http://www.chinapage.com/callig1.html
http://www.asiawind.com/art/callig/calligal.htm
http://www.tongram.com/gallery/default.asp
http://home.flash.net/~cameron/calligraphy/collection.htm
http://www.rice-paper.com/uses/calligraphy.html

Chinese computing

The Complete Guide to Chinese Computing
http://www.chinesecomputing.com/

An introduction to Chinese Input Methods http://zsigri.tripod.com/fontboard/cjk/input.html#chinese
http://www.nationmaster.com/encyclopedia/Chinese-input-methods-for-computer

The Cangjie Input Method
http://www.sungwh.freeserve.co.uk/methods/cangjie.htm

InputKing - a program for inputting Chinese text online
http://www.inputking.com

Guide to reading Chinese on the internet
http://www.cathay.net/help/read-chn.shtml

Beautiful Chinese wallpaper for your computer
http://www.desktopchina.com/desktopchina/

SIMO - enables you to input Chinese through browsers
http://www.simo.us

Chinese philosophy

The Daodejing (Tao-te-ching) by Laozi (Lao-tzu) in Chinese and English
http://www.chinapage.com/laotze.html

Chinese Text Project - texts of ancient Chinese philosophy online
http://chinese.dsturgeon.net

Chinese forums

http://www.chinese-forums.com
http://www.omnitalk.com
http://www.chinesesavvy.com/savvy/

Miscellaneous

Chinese Tools - online tools to learn chinese or build chinese websites. Includes annotation tools, dictionaries, and converters for pinyin, unicode, traditional and simplified chinese: http://www.chinese-tools.com

Chinesesavvy - a variety of resources for students of Chinese, including an online dictionary, articles on Chinese culture and history, forums, etc/
http://www.chinesesavvy.com/savvy/

Interesting Chinese - information about Chinese language, history and culture
http://www.interestingchinese.com

Free Chinese New Year E-cards
http://www.chinesenewyearecards.com
http://www.123greetings.com/events/chinese_new_year/


Convert Chinese characters to Unicode

This tool will convert Chinese characters (and just about everything else, including Japanese hiragana, katakana, and kanji; tonal Hanyu Pinyin; and Cyrillic script) into the decimal (not hex) form of Unicode numerical character references (NCRs). These NCRs can then be used in Web pages, with greater ease than the Chinese characters themselves for those whose operating systems or other software don't handle double-byte text well.

For example, 台北, the characters for "Taipei" (Táiběi), can also be written as 台北. For this to work, the "charset" of the Web page should be set to Unicode:
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

It's generally better, however, to use the characters themselves rather than their Unicode NCRs in cases where a Web page has a lot of Chinese text, because Chinese characters take up less file space than their NCRs.

http://www.pinyin.info/tools/converter/chars2uninumbers.html


Convert Chinese Charactor To Pin Yin

http://www.purpleculture.net/pinyin_old.asp




Information about written and spoken Chinese on this site

Recommended books

Books about Chinese characters and calligraphy
Classical Chinese, Mandarin, Shanghainese, Hokkien, Taiwanese and Cantonese language courses, dictionaries, etc.