Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать
☆

n Chapter 8, you created an MFC application with database connectivity. You

Iwill now learn to implement database connectivity in Managed C++ using

ADO.NET. As you discovered in Chapter 13, ADO.NET is the established data

 

 

 

 

Y

access technology for .NET applications. So, read on to find out how to imple-

ment ADO.NET in Managed C++.

L

 

 

F

To begin with, I will present the scenario for the project, and then proceed to dis-

 

M

 

cuss the implementation details.

 

 

 

A

 

 

E

 

 

 

Project Overview

 

 

 

T

 

 

 

 

In Chapter 8, you encountered the SaveMyMoney Bank, which had a banking application created to handle the day-to-day activities of the bank. The banking application was created using MFC, and used ODBC for data access. The banking application has been successfully implemented across the many branches of the bank. However, now the management is thinking of re-creating the application as a .NET application, since they see many advantages in completely moving onto the .NET platform. But before migrating to .NET, they intend to create a pilot application that implements only some of the features of the original banking application and verify its performance.

As part of the pilot, they want to implement the login feature and the accounthandling feature of the existing MFC’s Banking application in Managed C++.

Database Schema

In the pilot project, the database for the SaveMyMoneyBankApplication bank comprises two tables:

The AccountDetail table stores details of bank accounts of customers.

The BankLogin table stores the username and passwords of users who are authorized to access the banking application.

Team-Fly®

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 471

In this section, I include the steps to create the Banking1 database, which stores the tables for the application, and add tables to the database.

Creating the Database

After connecting to the SQL Server by using Query Analyzer, run the following code to create the Banking1 database:

create database Banking1

Go

use Banking1

Go

Creating the Account_Detail Table

The Account_Detail table is used for storing the account number, first name, last name, data of birth, permanent address, mailing address, phone number, e-mail address, account type, and balance details of customers. To create the Account_Detail table and add sample data to it, run the following code in Query Analyzer:

print ‘Creating table Account_Detail’ create table Account_Detail

(

Account_Number int IDENTITY (10000,1) not null primary key,

First_Name varchar(30) not null,

Last_Name varchar(30) not null, date_birth varchar(10) not null, Permanent_Addr varchar(50) not null, Mailing_Addr varchar(50) not null, Phone_Number varchar(15) not null, eMailID varchar(30) null, Type_account char(1) not null, Balance float not null,

Valid_Acc char(2) not null,

Ref_Acc_No int not null

)

go

insert Account_Detail

Bank-

472 Project 3 ADO.NET IN MANAGED C++

values(‘Masine’,’Philip’,’09/09/72’,’Street V Opp. Great Circle’,’Bldg-11, Avenue

2’,’91-20392012’,’mph@pinc.com’,’S’,800,’VA’,0)

go

Creating the BankLogin Table

The BankLogin table is used for storing the username and password of users who are authorized to access the application. The following query creates the Login table and adds a sample value to it:

print ‘Creating table BankLogin’ create table BankLogin

(

UserNm varchar(5) not null,

Pwd varchar(15) not null

)

go

insert BankLogin values(‘S103’,’password’) go

Having created the database structure for the application, you will now create the Windows application for the bank, by using Managed C++.

Creating the Banking Application

To create the banking application using Managed C++, you need to follow these steps:

1.Create a new project by using the Managed C++ Application project template.

2.Design the Login form and implement its business logic.

3.Design the form to manage account details and implement its business logic.

In this section, I examine the steps to accomplish each of the preceding tasks.

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 473

Creating a Project in Managed Extensions

To create a project in Managed Extensions, you use the Managed C++ Application project template provided in Visual Studio .NET. In this section, you create the MCppBankOperations project by using this template.

Follow these steps to create the banking application by using the Managed C++ Application template:

1.Open Visual Studio .NET.

2.Click on the File menu, click on New, and then click on Project. The New Project dialog box will appear.

3.In the New Project dialog box, click on Visual C++ Projects in the Project Types list. The templates available for creating Visual C++ projects will appear in the Templates list.

4.In the Templates list, click on Managed C++ Application and specify the name of the project as MCppBankOperations in the Name text box. The completed New Project dialog box is shown in Figure 14-1.

5.Click on OK.

FIGURE 14-1 The New Project dialog box

474 Project 3 ADO.NET IN MANAGED C++

When you complete the preceding steps, Visual Studio .NET creates an application in Managed Extensions. In the next two sections, you will learn how to customize this application as per the requirements stated earlier.

Creating the Login Form

Before you create the Login form for the application, delete the existing code of the application generated by the Application Wizard. The existing code creates a sample Hello World application, which is not required for your application.

You will design the Login form shown in Figure 14-2.

FIGURE 14-2 The Login form

NOTE

Starting with the following code snippet, I have added comment entries explaining the use of the corresponding lines of code. It will help you to easily understand what is happening. I will follow the same approach in explaining the complete application.

Next, to begin coding the Login form, first include all the necessary DLL (dynamic linked library) files and namespaces into your application by writing the following code in the MCppBankOperations.cpp file:

#include “stdafx.h”

#using <mscorlib.dll>

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 475

#using “System.Data.dll” #using “System.Xml.dll” #include <tchar.h>

using namespace System;

using namespace System::ComponentModel; using namespace System::Windows::Forms; using namespace System::Drawing;

using namespace System::Data;

using namespace System::Data::SqlClient; using namespace System::Xml;

Next, you need to write the code for creating the LoginForm class, which is derived from the Form class, and renders the login form for the user. The code snippet given below creates the LoginForm class and declares variables with private scope, which will be later used for rendering controls on the form:

__gc class LoginForm: public Form

{

private:

//Variables to store the caption, width, height of the form

String *caption; int width;

int height;

//Variables to render the controls of the form

TextBox *loginid;

TextBox *pwd;

Label *lglabel;

Label *pwdlabel;

Button *submitbutton; Button *cancelbutton; ErrorProvider *error; int totallogincount;

public:

//Constructor

LoginForm()

476 Project 3 ADO.NET IN MANAGED C++

{

caption = “Login form”;

width = 280;

height = 180;

LoginControls();

totallogincount= 0;

}

In the preceding code, note the use of the LoginControls function. This function is used for rendering controls on the form. The following is the code for the

LoginControls function:

void LoginControls()

{

Text = caption;

Size = Drawing::Size(width, height);

// Set up the Login edit box loginid = new TextBox();

loginid->Name=”loginid”;

loginid->Size = Drawing::Size(120, 40); loginid->TabIndex = 0;

loginid->Location = Drawing::Point(width/2-5, height - 160); Controls->Add(loginid);

// Set up the password edit box pwd = new TextBox(); pwd->Name=”pwd”; pwd->PasswordChar = ‘*’;

pwd->Size = Drawing::Size(120, 40); pwd->TabIndex = 1;

pwd->Location = Drawing::Point(width/2-5, height - 120); Controls->Add(pwd);

// To add the labels lglabel = new Label(); lglabel->Text=”Login id”;

lglabel->Size = Drawing::Size(90, 20);

lglabel->Location = Drawing::Point(width/2-90, height - 160);

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 477

Controls->Add(lglabel);

// To add the labels pwdlabel = new Label(); pwdlabel->Text=”Password”;

pwdlabel->Size = Drawing::Size(90, 20);

pwdlabel->Location = Drawing::Point(width/2-90, height - 120); Controls->Add(pwdlabel);

// Code to create the Submit button submitbutton = new Button(); submitbutton->Text = “&Submit”; submitbutton->Size = Drawing::Size(90, 30); submitbutton->TabIndex = 2;

submitbutton->Location = Drawing::Point(width/2-100, height - 70); submitbutton->Click += (new EventHandler(this, &LoginForm::OnSubmitButtonClick));

Controls->Add(submitbutton);

// Code to create the Cancel button cancelbutton = new Button(); cancelbutton->Text = “&Cancel”; cancelbutton->Size = Drawing::Size(90, 30); cancelbutton->TabIndex = 3;

cancelbutton->Location = Drawing::Point(width/2+10, height - 70); cancelbutton->Click += (new EventHandler(this, &LoginForm::OnCancelButtonClick));

Controls->Add(cancelbutton);

//Create the error provider control error=new ErrorProvider(); error->BlinkRate=250;

error->BlinkStyle=ErrorBlinkStyle::BlinkIfDifferentError;

}

After the Login form is displayed, the user will enter his or her login ID and password. This data is validated against the entries in the database. If the login ID or the password does not match, an error is displayed. If the login attempt fails

478 Project 3 ADO.NET IN MANAGED C++

thrice, the form is closed. Here is the code for the event handler of the Submit button of the Login form:

void OnSubmitButtonClick(Object *sender, EventArgs *e)

{

//If the login id is not entered then display an error message if (loginid->Text->get_Length()==0)

{

error->SetError(loginid,”Invalid login name”); return;

}

else

error->SetError(loginid,””); if (pwd->Text->get_Length()==0)

{

error->SetError(pwd,”Invalid password”); return;

}

else

error->SetError(pwd,””);

// user id and password

String *userId = “sa”;

String *password = “”;

// Code to connect to the SQL Database and issue a SELECT command

//The string variable,’query’ stores the query to be passed to the database //The value from the loginid and pwd edit boxes are retrieved into variables, //usernm and pwd and passed as the criteria for record selection.

//This query will retrieve the record corresponding to the login id and password //passed as parameters.

String *query = String::Format(S”SELECT * FROM BankLogin where usernm = ‘{0}’ and pwd=’{1}’”,loginid->Text, pwd->Text);

// Build the connect string with the user ID and password

String *connectString = String::Format(S”Data Source=localhost;Database=Banking;UID={0};Password={1};”, userId, password);

IMPLEMENTING ADO.NET IN A MANAGED C++ APP. Chapter 14 479

//Establishing Connection

//You can use this format if you are connecting with a known user name and //password; however, it is not recommended to store these in the source for //security reasons

// Create the SQL Connection object and pass it the connection string

SqlConnection* sqlconn = new SqlConnection(connectString);

//Open the connection sqlconn->Open();

//Create the SQL Command to store the select query

SqlCommand *sqlCommand = new SqlCommand(query, sqlconn);

//Create a SqlDataReader to enumerate the result of executing the command

//against the database.

SqlDataReader *dataReader = sqlCommand->ExecuteReader();

//Find out if there was a record existing with the given user name and password

//if yes, then increase the count in the variable numrows.

int numrows = 0;

while (dataReader->Read()) // Always call Read before accessing data.

{

numrows = numrows + 1;

}

//This part checks if any rows were selected –validating the user name and

//password entered

if(numrows == 0) //the record doesn’t exist

{

MessageBox::Show(“Invalid login name or password. Please try again.”); loginid->Text=””;

pwd->Text=””; loginid->Focus();

//To check the number of login attempts made totallogincount = totallogincount + 1;