Selasa, 13 Mei 2008

Deploy SQL Databases Easily with the Installer Class

Introduction
If you made an application that uses an SQL database that needs to be located on the client server, VS.NET Setup Project doesn't help too much. You could go for InstallShield or another product that will make things easy, but the costs will get higher. So, while searching for a free solution, I found an article on MSDN about using the Installer class and custom actions to make this happen. The code is in VB .NET, so this article ports it to C# with some new features that I've found useful, such as storing the connection string to the database more safely, restoring the initial state of the server if something fails, and an uninstall feature. All you need to do is to make a class derived from System.Configuration.Install and add two Embedded Resources named install.txt & uninstall.txt to the solution. The install.txt will contain the SQL script for your database and uninstall.txt the drop script. For the database script, I am using the ASPstate script made by the Microsoft team for the ASP.NET InSQL session state:< sessionState
mode ="SQLServer"
stateConnectionString ="tcpip=127.0.0.1:42424"
sqlConnectionString = "data source=aleph;
User ID=ASPsession;Password=ASPsession;"
cookieless = "false"
timeout = "60"
/>
For my Web application to work on a client server, I need to make a MSI with my app and the SQL script. To run the script at install time, I've made a .dll named ScriptInstall; the code for it will follow.
Installer Class Code
First, you declare a string that will have a default value and can be overridden by the Install method:[RunInstaller(true)]
public class ScriptInstall : Installer
{
//default value, it will be overwritten by the installer
string conStr= "packet size=4096;integrated security=SSPI;" +
"data source=\"(local)\";
persist security info=False;" +
"initial catalog=master";
I use two static functions that will return the script content and the connection string to the SQL server:private static string GetScript(string name)
{
Assembly asm = Assembly.GetExecutingAssembly();
Stream str = asm.GetManifestResourceStream(asm.GetName().Name +
"." + name);
StreamReader reader = new StreamReader(str);
return reader.ReadToEnd();
}
private static string GetLogin(string databaseServer,string userName,
string userPass,string database)
{
return "server=" + databaseServer + ";database="+database+
";User ID=" + userName + ";Password=" + userPass;
}
Then, process two functions that will run install.txt and uninstall.txt onto the SQL server. The ExecuteSQL has a regex that splits the script after GO so I can execute them one by one with SQLCommand. I am doing this because ADO.NET will throw an exception if the SQL script contains "GO".private static void ExecuteSql(SqlConnection sqlCon)
{
string[] SqlLine;
Regex regex = new Regex("^GO",RegexOptions.IgnoreCase
RegexOptions.Multiline);
string txtSQL = GetScript("install.txt");
SqlLine = regex.Split(txtSQL);
SqlCommand cmd = sqlCon.CreateCommand();
cmd.Connection = sqlCon;
foreach(string line in SqlLine)
{
if(line.Length>0)
{
cmd.CommandText = line;
cmd.CommandType = CommandType.Text;
try
{
cmd.ExecuteNonQuery();
}
catch(SqlException)
{
//rollback
ExecuteDrop(sqlCon);
break;
}
}
}
}
private static void ExecuteDrop(SqlConnection sqlCon)
{
if(sqlCon.State!=ConnectionState.Closed)sqlCon.Close();
sqlCon.Open();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.Connection = sqlCon;
cmd.CommandText = GetScript("uninstall.txt");
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
sqlCon.Close();
}
Having the functions, now you can override Install(IDictionary stateSaver) and Uninstall(IDictionary savedState). In the Install method, besides running the SQL script on to the server, I save the connection data submitted by the user. It's dangerous to save connection strings, so I use RijndaelManaged to encrypt it. You can find the class in the source as well. I am saving the connection string because I need it at uninstall to drop the database ASP state.public override void Install(IDictionary stateSaver)
{
base.Install (stateSaver);
if(Context.Parameters["databaseServer"].Length>0 &&
Context.Parameters["userName"].Length>0 &&
Context.Parameters["userPass"].Length>0)
{
conStr = GetLogin(
Context.Parameters["databaseServer"],
Context.Parameters["userName"],
Context.Parameters["userPass"],
"master");
RijndaelCryptography rijndael = new RijndaelCryptography();
rijndael.GenKey();
rijndael.Encrypt(conStr);
//save information in the state-saver IDictionary
//to be used in the Uninstall method
stateSaver.Add("key",rijndael.Key);
stateSaver.Add("IV",rijndael.IV);
stateSaver.Add("conStr",rijndael.Encrypted);
}
SqlConnection sqlCon = new SqlConnection(conStr);
sqlCon.Open();
ExecuteSql(sqlCon);
if(sqlCon.State!=ConnectionState.Closed)sqlCon.Close();
}
public override void Uninstall(IDictionary savedState)
{
base.Uninstall (savedState);
if(savedState.Contains("conStr"))
{
RijndaelCryptography rijndael = new RijndaelCryptography();
rijndael.Key = (byte[])savedState["key"];
rijndael.IV = (byte[])savedState["IV"];
conStr = rijndael.Decrypt((byte[])savedState["conStr"]);
}
SqlConnection sqlCon = new SqlConnection(conStr);
ExecuteDrop(sqlCon);
}
About the AuthorI am a software analist & C# developer working for a software company in East Europe.
Go to page: 1 2 Next
Downloads
sqlscriptinstall_demo.zip - Demo MSI file
sqlscriptinstall_src.zip - Source files

ASP.NET 2.0 Moves User Authentication One Step Forward

Authentication is a critical aspect of Web development. Developers are always on the lookout for easier ways to implement an effective authentication system on their Web pages. With ASP.NET 1.1, developers have to write lengthy code to authenticate users from a database. They also can validate user credentials using an XML file, but that is not a secure solution. Moreover, Visual Studio .NET 2003 doesn't provide any built-in controls for performing authentication functionalities.

SP.NET 2.0 moves authentication one step forward. It provides new classes, methods, and controls for implementing authentication in an easy manner. This article demonstrates how to apply the functionalities of the Membership class into ASP.NET applications. This class provides several methods that you can use to create, delete, and validate users. Moreover, you can combine its methods with the built-in ASP.NET security controls that ship with Visual Studio 2005 (aka Whidbey). This article briefly examines these controls as well.
Create New Users
You can create new users easily by using the CreateUser() method (See Table 1).
Syntax
Description
CreateUser(Username, Password)
Creates a new user with the specified username and password.
CreateUser(Username, Password, Email)
Creates a new user with the specified username, password, and e-mail.
Table 1. Creating a New User with the CreateUser() Method
When you create a new user in an ASP.NET project using Visual Studio 2005, it creates an MS Access database called ASPNETDB.mdb by default and stores the relevant user data (username, password, and e-mail address) in it. Listing 1 shows how to create a new user using the Membership class. (Before working with the code, you should place two textboxes, one button, and the required label controls on the form.)
Listing 1. Create a new user using the Membership class

Try
Membership.CreateUser(txtUsername.Text, txtPassword.Text)
lblStatus.Text = "User " & txtUsername.Text &
" Successfully Created"
Catch ex As MembershipCreateUserException
lblStatus.Text = ex.ToString()
End Try

If you attempt to add the same user again, ASP.NET automatically throws an exception and displays the relevant message on the label control. In older versions of ASP.NET, you have to write lengthy code to do this task.
Authenticate Users
You easily can verify the status of a user by using the ValidateUser() method of the Membership class. After you have verified the user, you can redirect him or her to another Web page or elsewhere, depending upon your requirements. Listing 2 shows the code for authenticating users using Visual Studio 2005.
Listing 2. Authenticating users using Visual Studio 2005If (Membership.ValidateUser(txtUsername.Text, txtPassword.Text)) Then
lblMessage.Text = "You are now authorized by the system"
Else
lblMessage.Text = "You are not an authorized user"
End If

As you can see, you need only a minimal amount of code to achieve various authentication tasks in Visual Studio 2005. You can also modify the above code to redirect users to some other Web page upon successful authorization.
Display Current User
You also can display a stamp on the top of every page with the name of the logged user after every successful login. You can easily achieve this functionality by using the GetUser() method (See Listing 3).
Listing 3. Display stamp of logged user's name on every pageDim usrUser As MembershipUser
usrUser = Membership.GetUser(True)
lblUserstatus.Text = usrUser.Username

Display All Users
With ASP.NET 2.0, you can produce a list of all registered users for your internal use on the fly. Just use the GetAllUsers() method of the Membership class (See Listing 4 and Figure 1).
Listing 4. Produce list of all registered users'Users is the ID for the GridView control
Users.DataSource = Membership.GetAllUsers()
Users.DataBind()


Figure 1. List of all users in GridView
Delete Users
You can delete a user from the database by using the DeleteUser() method of the Membership class. First, you should verify whether that particular user exists on the database (See Listing 5).
Listing 5. Verify whether user existsIf (Membership.DeleteUser(txtDelete.Text)) Then
lblStatus.Text = "Username " & txtDelete.Text &
" successfully deleted from the database"
Else
lblStatus.Text = "Username does not exist or wrong username"
End If

E-Commerce Tip: Programmatically Validate Credit Card Numbers

Before I accept any credit card number into my application, I run a simple numerical validation against it. All major credit cards (American Express, Discover, MasterCard, and Visa) use the Luhn algorithm to validate the numbers—why not you? Although this function doesn't go the extra step of actually running the card to see if the transaction will work, it will give you a simple true/false result regarding the card number's validity. The function also ignores all non-digit characters, so your users can enter the number however they wish.

This is the function to run the algorithm on a given string of numbers:///
/// Validates a credit card number using the standard Luhn/mod10
/// validation algorithm.
///

/// Card number, with or without
/// punctuation
/// True if card number appears valid, false if not
///
public bool IsCreditCardValid(string cardNumber)
{
const string allowed = "0123456789";
int i;
StringBuilder cleanNumber = new StringBuilder();
for (i = 0; i < cardNumber.Length; i++)
{
if (allowed.IndexOf(cardNumber.Substring(i, 1)) >= 0)
cleanNumber.Append(cardNumber.Substring(i, 1));
}
if (cleanNumber.Length <> 16)
return false;
for (i = cleanNumber.Length + 1; i <= 16; i++)
cleanNumber.Insert(0, "0");
int multiplier, digit, sum, total = 0;
string number = cleanNumber.ToString();
for (i = 1; i <= 16; i++)
{
multiplier = 1 + (i % 2);
digit = int.Parse(number.Substring(i - 1, 1));
sum = digit * multiplier;
if (sum > 9)
sum -= 9;
total += sum;
}
return (total % 10 == 0);
}

Voice Chat Using Client/Server Architecture

When the client application starts recording and playing threads created in OnInitDialog() of the Display class.// Create and Start Recorder Thread
record=new RecordSound(this);
record->CreateThread();
//Create and Start Player Thread
play=new PlaySound1(this);
play->CreateThread();

Thread functions are based on the code by the great person Paul Cheffers (from the CodeGuru site). I am grateful to him for making my dream project become a reality.
PreCreateHeader() of the Display class (from the constructor) creates some buffers for playing wavedata. (This prevents the creation of buffers during runtime...) When the client presses the connect button OnConnect() of the Display class, it connects client to server and displays the userlist and start button. On pressing the start button. recording and playing are started by sending a message to the recording and playing thread (OnStart function).record->PostThreadMessage(WM_RECORDSOUND_STARTRECORDING,0,0);
play->PostThreadMessage(WM_PLAYSOUND_STARTPLAYING,0,0);

These messages will activate corresponding functions defined in the message map of the respective thread class.
On pressing the stop button, recording and playing are stopped by in the same way as above (OnStop Function). It also contains other functions that will be activated on pressing the buttons....and some functions are activated from other classes (mysocket and RecordSound classes).
In mysocket class
OnReceive: When data arrives at the client, it will call the Display class's receive function, which plays the sound by sending message to the PlaySound thread.play->PostThreadMessage(WM_PLAYSOUND_PLAYBLOCK,0,(LPARAM)lpHdr);
Message Format:Total length : 2020 bytes
15 : header (destination username or special status)
5 : Length of actual data
2000 : Reserved for actual data.

RecordSound class
The PreCreateHeader() function creates buffers for recording data. These are added using the waveInPrepareHeader() and waveInAddBuffer() functions in the OnStartRecording function. (It is called when the start button is clicked, as explained earlier.)
Playsound1 class
Contains the functions for starting, playing, and stopping wavedata. Buffers are created initially in the Display class itself.
MicMute, MicPhone, and Mixer are the special classes to add several extra features to the Voice Chat function. Some of the concepts are collected from various developers at the CodeGuru site. I am grateful to those developers!!!
Running the Application
First, start the server application (with port number xxx). Then, start a minimum of two clients on any hosts (same or different). I should mention that the server hosts address and port xxx with username xyz. Then, click the connect button. The userlist will be displayed. Select the user and click the start button to start the chat...
Note: Any client can chat with any other client; hence, a client can receive data from any number of clients. Performance depends upon the situation. Developers are free to use their own ideas. (Please let me know if you see some new mechanism.)
I am eagerly waiting for your doubts and suggestions at nsry2002@yahoo.co.in.
I am grateful to the CodeGuru site for connecting developers....and helping us realise their dreams!!!
Downloads
Download demo project - 165 Kb

HTML Editor for VC++ 6.0

Introduction
Today, applications often need a rich user interface. One of them is ability to compose or edit HTML documents in an easy, effective, and reliable way. This article and source code attached give you a nice control to perform this task. And now, the best part: This control works fine with Microsoft VC++ 6.0!
Background
I'm author of the Tray Helper application. For a long time, I wanted to add a feature to send colorful HTML mail. After some research, I found that Microsoft did a nice thing implementing IHTMLDocument2 interface (and a few others related to it), but working with raw COM interfaces is not very easy, effective, or programmer-friendly. I think someone from Microsoft also realized that and in MFC 7.0 there is a very nice wrapper for COM: CHtmlEditCtrlBase class. After examining code from this class, I decided to port it to MFC 4.0 and VC++ 6.0.
Using the Code
The CHtmlEditCtrl2 class I want to introduce there is not only ported from CHtmlEditCtrlBase—I did some other improvements and changes to the orginal code—so it not only compiles under VC++ 6.0 but also has some new features and is even easier to use in existing projects. The main change was that CHtmlEditCtrl2 class derives from CWebBrowser2. It means that if your projects already use a standard Web browser control to display a HTML documents, adding editing capabilities would be trivial (read below for full instructions).
Adding HTML Editor to Your Projects
Step 1: Adding an ordinary Web browser control to your project
If you already use a Web browser control in your project, skip this paragraph and start reading from "Step 2."
Let's assume that you want add a HTML edit control to your dialog-based application. First, you need to add a Web browser control that will contain your HTML documents.
Go to the dialog template editor of Visual Studio and click on "Project / Add to project / Components and controls". From the resulting pop-up dialog, select "Registered active X controls" and finally find a select "Web Browser control" (the name of the control depends on language of your PC; for example, on my Polish version of Windows it is "Przegladarka Przeglądarka sieci Web firmy Microsoft"). To be sure that you're selecting a correct control, check the description below the file list; it should be "WebBrowser control".
After selecting a control, a dialog box with the CWebBrowser2 class to be created should appear. Click "OK" without any modifications.
Note that the new position should be added to the toolbar with a list of controls available to insert into the dialog. So, select it and just add a Web browser!
Finally, use a class wizard (Ctrl+W) to add a member variable of type CWebBrowser2 to the newly addeded item.
Next, you can add an OnInitdialog method to your dialog and request a browser to load a HTML document using the Navigate method of the CWebBrowser2 class.
Step 2: Adding edit capabilities to the Web browser
It's VERY easy. Just follow those few steps:
Copy the HtmlEditCtrl2.H and HtmlEditCtrl2.cpp directories with your source files and add them to your project.
Modify the header file where you have a member variable of CWebBrowser2 declared and change it to CHtmlEditCtrl2.
Change #include "WebBrowser2.H" to #include "HtmlEditCtrl2.H".
After loading an HTML document (using, for example, the Navigate method) call the SetDesignMode(TRUE) method to enable edit mode.
If, after editing is complete, you want to get a source of the HTML document, call the GetDocumentHTML function.

more

Offline Capable (Internet Explorer) AJAX Client

Why Is There a Need for an Offline Capable Client?
A Web application serving a large number of clients can suffer bandwidth and server performance bottlenecks. From a business perspective, it makes sense to single out the pages that hit the server the most, and bring the server requests from these pages to a minimum.


An offline AJAX client accomplishes exactly that; it all but eliminates server roundtrips so that a single server can handle many more clients. In addition, an offline AJAX client improves reliability by allowing the client to continue using the application even if the server or the Internet connection is disrupted. Moreover, an offline AJAX client supports untethered users, allowing users who are on-the-go to continue working while away from an internet connection.
Ultimately, by addressing these issues, you can eliminate the two most prevalent problems with Web applications from a user's perspective: speed and reliability.
How Is the Proposed Application Different than Standard Web Applications and other AJAX Applications?
The evolution of web applications...
In a Standard web application:
Client
Server
Reads user input

Posts data
Receives and stores data
Waits
Renders HTML (possibly by use of XSLT)
Displays HTML

In other AJAX applications:

more ->

Parsing HTML without Using the Browser Control

Click here for larger image
Environment: VB6 SP5, XPPro, IE6
The main goal of this article is to provide a way to use the HTML parser inside Microsoft Internet Explorer within your program.
This is something usually easy if you use the browser control. There are plenty of examples on the Internet, but when it comes to using it in a UI-less way, there is nothing done in Visual Basic. All examples I've seen are in Visual C++ using interfaces that are not available in Visual Basic.
After days of trying to find a way, trying the .NET platform to be able to use an HTML parser in a Windows NT service, I finally found a way. I don't claim this is the nicest way to do it, but it works like a charm, and you have access to the DOM of the HTML document you want, which can be very useful if you're looking to parse a HTML document.
Your code must have a reference to the Microsoft HTML Object Library. Internet Explorer 5 or more is required to do this. Simply copy this code in any function.Dim objLink As HTMLLinkElement
Dim objMSHTML As New MSHTML.HTMLDocument
Dim objDocument As MSHTML.HTMLDocument
' This function is only available with Internet Explorer 5
Set objDocument = objMSHTML.createDocumentFromUrl(txtURL.Text, _
vbNullString)
' Tricky, to make the function wait for the document to
' complete, usually the transfer is asynchronous. Note
' that this string might be different if you have another
' language than English for Internet Explorer on the
' machine where the code is executed.
While objDocument.readyState <> "complete"
DoEvents
Wend
' Source Code
Debug.Print = objDocument.documentElement.outerHTML
' Title
Debug.Print "Title : " & objDocument.Title
' Link Collection
For Each objLink In objDocument.links
lstLinks.AddItem objLink
Debug.Print "Link: " & objLink
Next
DownloadsDownload demo project - 3 Kb

This page is powered by Blogger. Isn't yours?

Berlangganan Postingan [Atom]