Creating the Product Catalog Part I (continued) Instructor: Wei Ding The lecture notes are written based on the book Beginning ASP.NET 2.0 E-Commerce in C# 2005 From Novice to Profession by Cristian Darie and Karli Waston, www.apress.com, US $44.99, ISBN 1-59059- 468-1, Chapter 2 and Chapter 3. Source Code: http://www.apress.com/book/view/1590594681 1
Configure the connectionstrings Web.config and connectionstrings <configuration xmlns="http://schemas.microsoft.com/.netconfiguration/v2.0"> <connectionstrings> <add name="balloonshopconnection" connectionstring="server=(local)\sqlexpress;integrated Security=True;Database=BalloonShop" providername="system.data.sqlclient"/> </connectionstrings> <system.web> </system.web> </configuration> Notice that you should type the <add> element on a single line, not split in multiple lines as shown in the slide.
Implementing Generic Data Access Code using System.Data.Common; provide generic data access functionality (they weren t available in ADO.NET 1.0 or 1.1), such as DBConnection, DbCommand. The first step in implementing database-agnostic data access is to use the DbProviderFactory class to create a new database provider factory object. // Create a new data provider factory DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName); So where do we obtain the data provider name?
Discussion In practice, the System.Data.SqlClient string parameter is kept in a configuration file, allowing you to have C# code that really doesn t know what kind of database it s dealing with.
Connection object The database provider factory class is capable of creating a database-specific connection object through its CreateConnection object. However, you will keep the reference to the connection object stored using the generic DbConnection reference. // Obtain a database specific connection object DbConnection conn = factory.createconnection(); // Set the connection string conn.connectionstring = connectionstring; Where do you obtain the connection string?
Sql command The connection object has a method named creatcommand that returns a database command object, but you ll keep the reference stored using a database-neutral object: DbCommand. // Create a database specific command object DbCommand comm = conn.createcommand(); // Set the command type to stored procedure comm.commandtype = CommandType.StoredProcedure; // Return the initialized command object
Static class members Static properties and static methods can be called by external classes without creating an instance of the class first; Instead, they can be called directly using the class various operations, such as Math.Cos, and so on. Under the hood, the static class members are called on a global instance of that class, which is not destroyed by the Garbage Collector after execution. So the values of any static members are persisted. A static class member can call or access another static class member directly.
CatalogAccess.cs public static class CatalogAccess. The class to use static members mainly to improve performance. Static classes and static members are initialized only once, they don t need to be reinstantiated each time a new visitor makes a new requewst; instead, a global instances are used.
CatalogAccess.cs uses GenericDataAccess.cs public static class CatalogAccess // Retrieve the list of departments public static DataTable GetDepartments() // get a configured DbCommand object DbCommand comm = GenericDataAccess.CreateCommand(); // set the stored procedure name comm.commandtext = "GetDepartments"; // execute the stored procedure and return the results return GenericDataAccess.ExecuteSelectCommand(comm);
Data provider connection string command GenericDataAccess.cs uses BalloonShopConfiguration.cs Class: GenericDataAccess.cs public static DbCommand CreateCommand() // Obtain the database provider name string dataprovidername = BalloonShopConfiguration.DbProviderName; // Obtain the database connection string string connectionstring = BalloonShopConfiguration.DbConnectionString; // Create a new data provider factory DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName); // Obtain a database specific connection object DbConnection conn = factory.createconnection(); // Set the connection string conn.connectionstring = connectionstring; // Create a database specific command object DbCommand comm = conn.createcommand(); // Set the command type to stored procedure comm.commandtype = CommandType.StoredProcedure; // Return the initialized command object return comm;
Class: GenericDataAccess.cs // execute a command and returns the results as a DataTable object public static DataTable ExecuteSelectCommand(DbCommand command) // The DataTable to be returned DataTable table; // Execute the command making sure the connection gets closed in the end try // Open the data connection command.connection.open(); // Execute the command and save the results in a DataTable DbDataReader reader = command.executereader(); table = new DataTable(); table.load(reader); // Close the reader reader.close(); catch (Exception ex) Utilities.SendErrorLogEmail(ex); throw ex; finally // Close the connection command.connection.close(); return table; GenericDataAccess.cs uses Utilities.cs Send an email to the administrator and move on The finally block is always executed whether an exception occurs or not
BalloonShopConfiguration.cs The BalloonShopConfiguration class is simply a collection of static properties that return data from web.config. Using this class instead of needing to read web.config all the time is better. Because the class can cache the values read from web.config instead of reading them on every request.
Sending Emails Add necessary configuration data under the <appsettings> node in web.config. <configuration xmlns="http://schemas.microsoft.com/.netconfiguration/v2.0"> <appsettings> <add key="mailserver" value="localhost" /> <add key="enableerrorlogemail" value="true" /> <add key="errorlogemail" value="errors@yourballoonshopxyz.com" /> </appsettings> </configuration>
Utilities.cs using System.Net.Mail; the namespace includes SmtpClient and MailMessage classes to help you send emails. // Generic method for sending emails public static void SendMail(string from, string to, string subject, string body) // Configure mail client (may need additional // code for authenticated SMTP servers) SmtpClient mailclient = new SmtpClient(BalloonShopConfiguration.MailServer); // Create the mail message MailMessage mailmessage = new MailMessage(from, to, subject, body); // Send mail mailclient.send(mailmessage);
SMTP Server To work with your local SMTP server, you need ensure that the server is started using the IIS Configuration console (check the handouts distributed by the instructor in class). You also need to enable replaying for the local machine. IIS configuration console expand your computer s node right-click Default SMTP Virtual Server select properties go to the Access tab click the Relay button add 127.0.0.1 to the list finally restart the SMTP server. http://www.systemwebmail.com/default.aspx for help.
DepartmentsList.ascx // Load department details into the DataList protected void Page_Load(object sender, EventArgs e) // CatalogAccess.GetDepartments returns a DataTable object containing // department data, which is read in the ItemTemplate of the DataList list.datasource = CatalogAccess.GetDepartments(); // Needed to bind the data bound controls to the data source list.databind();