Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Programming for the Microsoft SQL Server Database

Similar presentations


Presentation on theme: "C# Programming for the Microsoft SQL Server Database"— Presentation transcript:

1 C# Programming for the Microsoft SQL Server Database
Dave Henson

2 Logistics Class Hours Notes/Handouts Demos Class website

3 Recommended Reading Beginning C# Databases, APress, ISBN

4 Course Setup Software required to complete course labs:
Windows xp, 2000 or 2003 .Net Framework 1.1 MSDE Recommended Software: Visual Studio 2003 SQL Server Standard Version

5 Course Topics Quick C# Primer Tools Creating/Using Class Libraries
ADO.Net Exception handling Stored Procedures Avoiding SQL Injection Com Interop SQL Server Best Practices and Techniques

6 Chapter 1 - Tools Visual Studio Command Line Tools Other Tools

7 Visual Studio Fully integrated IDE Intellisense
Automatic Code Generation Drag/Drop Database and Control Interface Database and Other Design Wizards

8 Command Line Tools Subdirectory: Csc.exe (vbc.exe, jsc.exe)
C:\WINDOWS\Microsoft.NET\Framework\V Csc.exe (vbc.exe, jsc.exe) Compiler GACUtil.exe Global Assembly Cache tool Ngen.exe Native windows exe converter RegAsm.exe Register a .Net assembly with COM SN.exe Strong Name Generator

9 Csc.exe – C# Compiler Typical Syntax Examples: C:>Csc Simple.cs
Produces Simple.exe in current directory C:>Csc /target:library DBUtil.cs Produces DBUtil.dll in the current directory C:>Csc /r:DBUtil.dll DBClient.cs Products DBClient.exe which uses the dll Visual C# .NET Compiler Options(Abbreviated) - OUTPUT FILES - /out:<file> Output file name (default: base name of file with main class or first file) /target:exe Build a console executable (default) (Short form: /t:exe) /target:winexe Build a Windows executable (Short form: /t:winexe) /target:library Build a library (Short form: /t:library) /target:module Build a module that can be added to another assembly (Short form: /t:module) /doc:<file> XML Documentation file to generate - INPUT FILES - /recurse:<wildcard> Include all files in the current directory and subdirs according to the wildcard specifications /reference:<file list> Reference metadata from the specified assembly files (Short form: /r) /addmodule:<file list> Link the specified modules into this assembly - CODE GENERATION - /debug[+|-] Emit debugging information /debug:{full|pdbonly} Specify debugging type ('full' is default, and enables attaching a debugger to a running program) /optimize[+|-] Enable optimizations (Short form: /o) /incremental[+|-] Enable incremental compilation (Short form: /incr) - ERRORS AND WARNINGS - /warnaserror[+|-] Treat warnings as errors /warn:<n> Set warning level (0-4) (Short form: /w) /nowarn:<warning list> Disable specific warning messages - LANGUAGE - /checked[+|-] Generate overflow checks /unsafe[+|-] Allow 'unsafe' code - MISCELLANEOUS - /main:<type> Specifies the type that contains the entry point (ignore all other possible entry points) (Short form: /m) /lib:<file list> Specify additional directories to search in for references

10 Other Tools IDE Automated Code Generation: Codecharge studio
SQL Queries that dynamically c# C# that dynamically builds c# C# that dynamically builds SQL

11 Chapter 2 – C# Review Program Structure Case sensitivity
if/while/foreach try/catch Creating objects

12 Program Structure using System; class App{ public static void Main() {
Console.WriteLine("hey"); Console.ReadLine(); }

13 Case Sensitivity Most .Net classes are Mixed Case
Many C# keywords are lower case Valid Code: String greeting = “hello”; String Greeting = “goodbye”;

14 if Statement if (loop != 20) { string errorMessage = “Oops”; }

15 while statement while(dr.Read()) { Console.WriteLine(dr[“FirstName”]);
}

16 foreach statement DirectoryInfo dir = new DirectoryInfo(@“c:\\temp”);
try { foreach(FileInfo f in dir.GetFiles()) Console.WriteLine(f.Name); } catch(Exception e) Console.WriteLine(e.Message); Finally

17 Creating Objects An object is an instance of a class Examples:
String stuff = “hello”; MyClass class = new MyClass(1); SqlDataSet ds = CreateDataSet(query);

18 Chapter 3 - Class Libraries

19 Definitions Class library – body of functions and properties usable by other code Examples: ActiveX control/COM object .Net Assembly Web Service Win32 dll Implementation: Often in a .dll file

20 Purpose Supply re-usable code to developer Maintain consistency
Ease of maintenance – Separation of front end from back end Reduce development costs

21 Methods Class biz{ //Static – member of the type
static public string SayHi(){ return “hi”; } //Non static – member of the instance public string SayBye(){ string message = _message; return message;

22 Properties Properties are methods! Get Set
“value” keyword has special meaning Example: Class Address{ protected string ; //field public string //property { get {return ;} set //pull from database = value; }

23 Application Layers Presentation Business Logic Data Access
Potential ease of use and potential disaster

24 Chapter 4 – ADO.Net

25 ADO.NET Components SqlConnection SqlDataAdapter DataSet DataTable
DataRow, DataColumn collections SqlDataReader SqlCommand These are the main components that are available to use for data access from ASP.NET DataAdapter – Moves data back and forth from the data source and the DataSet Object. Completely abstracts the data DataSet – Represents a collection of DataTables, and programmatic referential integrity between them DataTable – Represents a single in-memory table DataReader – Used to retrieve a forward only “firehose” cursor. The namespaces needed to reference these objects are: System.Data – for System.SQLClient – for See Example 1 for use of SqlConnection, SQLCommand and DataGrid

26 Required Namespaces System.Data System.Data.SqlClient
The classes, enums, structs and types associated with each provider are defined in the namespace. The allows objects of the same name defined in different namespaces not to collide

27 Providers Providers Available: SQL Server .NET Provider
OleDB .NET Provider Example-AllRecordsBasicOleDB.aspx ODBC .NET Provider SQL XML .NET Provider

28 Connections Connection Defined Where to Store the Connection String
Connection Syntax Examples Connection Pooling Security Close Your Connections! Monitoring Connections A Connection defines the options needed to gain access to a database and related tables. It is generally defined by a string which varies depending upon the type of database you will access and the options required. Other options include transaction and pooling behavior.

29 Where to Store the Connection String
Options Available: Configuration Class Front End App (.aspx file) Web.Config UDL File (OleDB Only) Registry Custom File COM+ Catalog Using Connection Strings Evaluation Terms: Security, Convenience, Performance You can use “Persist Security Info = false” in your connection string to prevent programmatic access to login/password information from the ConnectionString property of SQLConnection or OleDBConnection Objects

30 Two Connection String Syntax Examples
In the .aspx file: ConnString = “server= ;UID=sa;PWD=;” Dim Conn As New SqlConnection(ConnString) In Web.Config XML file: <configuration> <appSettings> <add key=“ConnString” value=“server= ;UID=sa;PWD=;”/> </appSettings> </configuration>

31 Connection Pooling Defined
Controlling Min/Max-Example6ShowConnectionStatePoolControl.aspx Importance of “Exact String Match” Pooling for SqlClient vs. OleDBClient Effects of pooling on SQL security Close Your Connections! Deployed through “Exact Match” Reduce default max (100) during development to detect errors during development Pools are transaction specific, unless you are not in a transaction OleDB resource pooling is discourages in favor of COM+ object pooling because of configuration options and performance. Monitor pooling through Profiler or through System Monitor Windows authentication is slightly slower for pooled connections than standard authentication

32 Performance Issues Choose Providers Wisely DataReader vs. DataAdapter
Repeater Control vs. DataGrid Control Connection Pooling Embedding SQL vs. Stored Procedures Controlling The HTML Typed Accessor Methods-Example7AdapterVsReaderUsingTypedAccessorMethods.asp

33 DataReader Vs. DataAdapter
Forward Only Only One Record At A Time In Memory “Firehose” Functionality Typed Accessor Methods Avoid Conversions One datareader open per connection DataAdapter More Overhead More Flexible Note that while the DataReader is open, the connection used is exclusive to that DataReader and cannot be used for anything else If the command contains output params or return values, these will not be available until the Reader is closed

34 Repeater Control vs. DataGrid(or DataList) Control
Repeat Control Simply Repeats Low overhead You Have To Do Everything You Can Do It Better Than Microsoft Did! DataGrid Default HTML Behaviour Higher Overhead, Most Functionality

35 Embedding SQL vs. Stored Procedures
Stored Proc Advantages: Procedure Cache Separate Security Model Potentially Less Network Traffic Output Params, Error Code & Result Set Can Do Anything Server Side Abstracts the Front End from Changes – Possible Disadvantage with Xcopy Deployment

36 Controlling the Presentation
HTML-Use Stylesheets if Possible! Make Sure The Page Fails Gracefully If Needed With DataGrids, Use TemplateColumns

37 Final Recommendations
Use DataGrids Only When Updates Are Needed Embed Connection In Web.Config through Config class Only “Select” What You Need Call StoredProcs For Ultimate Performance When “Paging”


Download ppt "C# Programming for the Microsoft SQL Server Database"

Similar presentations


Ads by Google