Presentation is loading. Please wait.

Presentation is loading. Please wait.

BIT 285: ( Web) Application Programming Lecture 14: Thursday, February 19, 2015 SQL Database and LINQ Instructor: Craig Duckett.

Similar presentations


Presentation on theme: "BIT 285: ( Web) Application Programming Lecture 14: Thursday, February 19, 2015 SQL Database and LINQ Instructor: Craig Duckett."— Presentation transcript:

1 BIT 285: ( Web) Application Programming Lecture 14: Thursday, February 19, 2015 SQL Database and LINQ Instructor: Craig Duckett

2 2 Assignment 2: Database is due in ONE WEEK on Thursday, February 26 th (zipped and uploaded to StudentTracker by midnight) Assignment 3: REST Framework is due on Tuesday, March 17 th Final Exam is on Tuesday, March 17 th

3 Creating an ASP.NET SQL Database in Visual Studio 3

4 Databases and SQL Almost every ASP.NET web site has a database of some kind. For example, online shops have databases filled with products, customer details, orders, payment info, etc. Being able to interact with a database is almost always required when writing interactive web sites or applications.. SQL (Structured Query Language) is a query language that allows computer applications to add, edit and delete data from a database. Whenever your application interacts with a database it does so by constructing an SQL query. While you do not need to know SQL to access data in your projects—ASP.NET provides classes which generate SQL code for you—if you are planning to make a career as an application developer it is one of the recommended languages to add to your skillset and programming box of tricks. 4

5 Creating an SQL Database in ASP.NET (C#) WALK-THROUGH 1.Download the lec14_demoform.zip web site and unzip. 2.Open the lec14_demoform web site with Visual Studio. 3.Examine, experiment, and test the lec14_demoform web site. This contains a simple form and form validation controls. 4.Right-click on the lec14_demoform project in the Solution Explorer, and select Add > Add New Item > then scroll down and select SQL Server Database. Change database name to Registration, and then click OK button 5.At the "You are attempting to add a special file type (database)…" message window, select Yes. 5

6 Creating an SQL Database in ASP.NET (C#) 6.After a brief pause the App_Data folder and Registration database is added to the project (Registration.mdf) on the right and Server Explorer is opened on the left 6 If you are unable to see Server Explorer, from the menu bar select View > Server Explorer to display the Registration.mdf database.

7 Creating an SQL Database in ASP.NET (C#) 7.In the Server Explorer, right-click on the Table folder and select Add New Table. 8.Add the data columns with corresponding names and data types, making sure to uncheck all Allow Nulls. You can use either nvarchar (with Unicode) or varchar (non-Unicode) for the string data type. The number in the parentheses (50) represents the number of characters in the string.Unicode 9.In the SQL code window, change the table name from Table to UserData, then click the Update arrow button. Unclick Include transactional scripts. Click Update database. 10.In Server Explorer, select the Refresh button, then open the Tables folder to see the UserData table and its fields. 7

8 Creating an SQL Database in ASP.NET (C#) 11.In the Solution Explorer, right-click on the project and add a new web form, and name it Grid. 12.Open the Grid.aspx page in Design view, and from the Toolbox drag-and-drop a GridView control from the Data section (you may have to close the Server Explorer to access the Toolbox). 13.Now from the Toolbox drag-and-drop a SqlDataSource control from the Data section to the form. 14.Click the the SqlDataSource control and rename its ID to sdsRegistration. 15.Click the edit arrow button on the SqlDataSource control and select Configure Data Source… 16.In the Configure Data Source window, select the Registration.mdf data source, and Next button. 8

9 Creating an SQL Database in ASP.NET (C#) 17.Save the Connection String as RegistrationConnectionString, then click Next. 18.In the Configure Select Statement window, keep the default settings, and click Next. 9

10 Creating an SQL Database in ASP.NET (C#) 19.In the Test Query window, click the Test Query button. 20.If your database is connected successfully, after a slight pause you should see the column heads you provided, then click Finish. 10

11 Creating an SQL Database in ASP.NET (C#) 21.Now you need to connect the data source to the GridView data table. 22.Select the edit arrow button on the GridView table, and select Choose Data Source… 23.Select sdsRegistration from the Choose Data Source drop down list to populate the GridView table 11

12 Creating an SQL Database in ASP.NET (C#) 24.You can optionally change the features of the table by selecting Enable Paging, Enable Sorting, or Enable Selection 12

13 Creating an SQL Database in ASP.NET (C#) 25.You can optionally change the properties and look of the table by selecting Auto Format and selecting a table scheme (I selected the Rainy Day scheme, as shown below). 13

14 Creating an SQL Database in ASP.NET (C#) 26.It would be nice to add some initial data to see the table in action. To do so, click on the Registration.mdf database in the Solution Explorer to bring up the Server Explorer again. 27.In the Server Explorer, open the Tables folder, right-click on the UserData table, and select Show Table Data. Because the table contains no data at this point, there is only one row showing NULL values. 28.Add an ID, UserName, Email, Password, and Country. If you see red warning dots, just click down in the next row to remove them. 14

15 Creating an SQL Database in ASP.NET (C#) 29.Test the Grid page in a browsers to confirm that everything works as planned. 15 NOTE: At this point I usually save this project folder and make a second copy of it to create a second project to work with going forward. For example, you might name this second project folder lec14_demoform2 to differentiate it from the original folder. I usually do this as I work through a project so won't have to start from scratch if I mess something up. By the time I am finished I might have three or four project folders each saved at different points of construction.

16 Binding an ASP.NET SQL Database in Visual Studio 16

17 Binding a Database to an ASP.NET Page 17 WALK-THROUGH 1.Open the Default.aspx page in Design view. 2.Double-click on the Submit button to bring up the "code behind" page. You'll see there is already a line of code in the btnSend_Click() method from when the page was initially created. Go ahead an delete.

18 Binding a Database to an ASP.NET Page 18 3.Add the following name spaces along with those already there to the top of the code: using System.Data.SqlClient; using System.Configuration; 4.In the btnSend_Click() method add the beginnings of the SQL connection code: In the next step we will need to add the name we gave our connection string, which is missing in the string in the braces in the above code. Note: There is a tricky bit of business here dependent upon what you named your ConnectionString previously, so I'll show you how to find this name again in case you don't remember what it is. Programming Tip: It is always a good idea to document the steps of your project so you can easily look up previous information later on. This can be a real timesaver in the long run, even though right now it may appear as if it is taking up time.

19 Binding a Database to an ASP.NET Page 19 To find the name of your connection string do the following: Open your Grid page in Design view Click once on the SqlDataSource control In the Properties window, under the Data category find (Expressions) and click in the column to bring up the button with the three ellipses Click on the button and under Bindable properites: scroll to find ConnectionString and click on it In Expression properties: is the Connection Name (here it is called RegistrationConnectionString) Highlight and copy the ConnectionName Click OK and return to the Default "code behind" page

20 Binding a Database to an ASP.NET Page 20 5.Enter the ConnectionName in the missing string in the braces 6.Make sure that.ConnectionString (with no 's' after String) follows the square braces. FYI – Copy-and-paste code is available for this on Slide 23 below

21 Binding a Database to an ASP.NET Page 21 7.In the lines following SqlConnection add the following code: FYI – Copy-and-paste code is available for this on Slide 23 below

22 Binding a Database to an ASP.NET Page 22 8.In the lines below the if statement, add the following else lines of code: FYI – Copy-and-paste code is available for this on Slide 23 below

23 23 protected void btnSend_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString); conn.Open(); string checkuser = "SELECT count(*) FROM UserData WHERE UserName= @username"; int temp = 0; SqlCommand com = new SqlCommand(checkuser, conn); com.Parameters.Add(new SqlParameter("@username", txtUsername.Text.Trim())); temp = Convert.ToInt32(com.ExecuteScalar()); if (temp > 0) { lblSuccess.Visible = true; lblSuccess.Text = "User Already Exists! Try different name."; } else { try { string insertQuery = "INSERT INTO UserData (Username, Email, Password, Country) VALUES (@username, @email, @password, @country)"; SqlCommand com1 = new SqlCommand(insertQuery, conn); com1.Parameters.Add(new SqlParameter("@username", txtUsername.Text)); com1.Parameters.Add(new SqlParameter("@email", txtEmail.Text)); com1.Parameters.Add(new SqlParameter("@password", txtPassword.Text)); com1.Parameters.Add(new SqlParameter("@country", DropDownList1.SelectedItem.Text)); com1.ExecuteNonQuery(); // Used for Insert, Update, Delete SQL Statements Response.Redirect("Grid.aspx"); } catch (Exception ex) { lblSuccess.Text = "Error: " + ex.ToString(); }

24 Binding a Database to an ASP.NET Page 24 9.In the Server Explorer, open the UserData table in Design view, select the Id, and in the Properties window change the Identity Specification from False to True in order to auto-increment the ID, then Update > Update the datatabase. Also: at this point I go into the database and delete my row of test data from the previous section.

25 Binding a Database to an ASP.NET Page 25 10.Open the Default page in a browser and test your program. Fix any errors, wash/rinse/repeat. NOTE: If you have been adding users while developing and testing the database and want to return it back to its original state, then just run a query with the following: truncate table table_name In Server Explorer, just right-click on the table, select New Query, enter the above query with the correct table name, the click the Execute button

26 Adding a Login Page 26

27 Adding a Login Page 27 1.Right-click on the project and select Add > Add New Item > Web Form and name it Login.aspx. 2.Open the Login page in Design view. 3.Add a Login Page Label to the page, and adjust the font size and color as you see fit. 4.Add a Table to the page containing 4 rows and 3 columns. 5.Set up the table with labels, text boxes, required field validators, and button as shown below

28 Adding a Login Page 28 6.Double-click on the Login button to bring up the "code behind" file, and add the following to the top: using System.Data.SqlClient; using System.Configuration; 7.In the Login button Click method, add the code as written on the next slide:

29 protected void btnLogin_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString); conn.Open(); string checkuser = "SELECT count(*) FROM UserData WHERE UserName=@username AND Password=@password"; SqlCommand com = new SqlCommand(checkuser, conn); com.Parameters.AddWithValue("@username", txtLoginUser.Text); com.Parameters.AddWithValue("@password", txtLoginPassword.Text); int temp = Convert.ToInt32(com.ExecuteScalar()); conn.Close(); if (temp == 1) { Session["New"] = txtLoginUser.Text; lblPasswordStatus.Visible = true; lblPasswordStatus.Text = "User credentials are validated!"; Response.Redirect("Grid.aspx"); } else { lblPasswordStatus.Visible = true; lblPasswordStatus.Text = "Invalid user credentials! Try again."; }

30 LINQ 30

31 What is LINQ ? LINQ, which stands for Language Integrated Query, is a relatively new addition to.NET which makes working with databases much easier. Before LINQ, programmers would usually create their own set of classes to generate the SQL code that is needed to interact with a database. This took a lot of time and effort. ASP.NET’s LINQ classes automatically create the SQL code needed to interact with your data, making it unnecessary to learn SQL. LINQ also streamlines the development process by removing the need to create your own data access classes. 31

32 Add LINQ Data Classes to Project 1.Create a new ASP.NET Empty Web Site project called lec14_linq 2.Right-click on the project and select Add > Add New Item > Web Form 3.Right-click on the project and select Add > Add New Item > SQL Server Database and name it Students.mdf 4.At the message box select Yes to create the database in an App_Data folder 5.In the Server Explorer, right-click on the Tables folder and select Add > Add New Table 6.Define the columns as follows, making sure to rename Id to StudentID and to set its Identity Specification and (Is Identity) to True to set up auto-increment by 1 SEE NEXT SLIDE  32

33 Add LINQ Data Classes to Project 33

34 Add LINQ Data Classes to Project 7.Update the Table by invoking the Update arrow then Update the Database 8.Right-click on the Students table and select Show Table Data, then add two or three fictitious students 9.Now we can add the LINQ to XML class. In the Solution Explorer, right-click on the project and select Add > Add New Item > LINQ to SQL Classes, naming it LinqToStudents.dbml, then Add button 10.At the message window, select Yes to create the.dbml file in an App_Code folder 11.After the App_Code folder and.dmbl file is generated, this will bring up the Object Relational Designer in the center column. 34

35 Add LINQ Data Classes to Project 35

36 Add LINQ Data Classes to Project 12.From Server Explorer, drag and the Students table that you just created into the left pane of the Object Relational Designer. It should appear as follows: 36

37 Add LINQ Data Classes to Project 13.Back to the Default.aspx page, in Design drag-and-drop a DataGrid server control from the Toolbox on to Designer View (you may have to close the Server Explorer to see the Toolbox). Auto format it if you want, but do not configure any data sources at this time. 37

38 Add LINQ Data Classes to Project 14.Right-click anywhere on the Default.aspx page and select “View Code”, this should open the Default.aspx.cs class file. Go ahead and keep the default name of GridView1. 15.Add the following code to the Page_Load event: LinqToStudentsDataContext linqStud = new LinqToStudentsDataContext(); var allstudents = from stud in linqStud.Students where stud.StudentID != null select stud; GridView1.DataSource = allstudents; GridView1.DataBind(); 16. Now run and test the program in a browser. It should look something like this: 38

39 Add LINQ Data Classes to Project Now that we've done it the "hard way" (not really), let's take a look at an even easier way to link the GridView control to an SQL table. 1.Using the same project and Default.aspx page from the previous example, let’s first DELETE all the code you just added to the Page_Load event of the Default.aspx.cs class file and then Save that file. 2.From the Toolbox, drag-and-drop the LinqDataSource server control (under Data) anywhere onto the Designer view of the Default.aspx page. Go ahead an keep the default name of LinqDataSource1. 39

40 Add LINQ Data Classes to Project 3.You can now select “Configure Data Source” from the LinqDataSource you just added, as follows 40

41 Add LINQ Data Classes to Project 4.Once the “Configure Data Source” window opens, the LinqToStudentsDataContext option is already selected from the DropDown (since it is the only one available), so select Next. 41

42 Add LINQ Data Classes to Project 5.On the Configure Data Selection screen, just accept the defaults and click Finish 42

43 Add LINQ Data Classes to Project 6.Back to the Default.aspx and Design view where we can now bind the GridView to our newly created LinqDataSource. 7.Select “LinqDataSource1” from the Chose Data Source dropdown list of your GridView control as follows: 43

44 Add LINQ Data Classes to Project 8.Run and test the program in a browser. It might look something like this: 44

45 Add LINQ Data Classes to Project 9.Optionally, you can Enable Delete, Enable Insert, Enable Update to the LinqDataSource, although you would have to add additional controls (like textboxes and buttons) and events in the 'code behind" to make this functional. 10.Optionally, you can Enable Paging, Enable Sorting, Enable Editing, Enable Deleting, Enable Selection to the GridView. 45

46 ASP Helps Links Data Modeling in the.NET Framework (Microsoft) Data Modeling in the.NET Framework XML Documents and Data LINQ Portal ADO. Net Accessing Data with ASP.Net (Microsoft) Accessing Data with ASP.Net LINQ (Microsoft, Visual Studio 2013) LINQ 101 LINQ Examples (Microsoft) 101 LINQ Examples Gallery of Developer Code Examples (Microsoft) Gallery of Developer Code Examples C# SQL Server Connection (C-Sharp.net) C# SQL Server Connection How to Connect to SQL Server Using ASP.Net and C# (Overpie) How to Connect to SQL Server Using ASP.Net and C# Visual Studio 2013: Insert Data to SQL Database with TextBox and ASP.NET, C# (YouTube) Visual Studio 2013: Insert Data to SQL Database with TextBox and ASP.NET, C# Creating Model Classes with LINQ to SQL C# (ASP.NET MVC, Microsoft) Creating Model Classes with LINQ to SQL C# The Connection String Reference (connectionstrings.com) The Connection String Reference 46

47 ASP Helps Links (asphelps.com) How to Bind GridView in ASP.NET How to Bind GridView in ASP.NET How to Bind GridView by using Linq How to Bind GridView by using Linq Insert, Update and Delete in GridView using Linq Insert, Update and Delete in GridView using Linq Linq Tutorial Linq Tutorial Linq to Sql Tutorial Linq to Sql Tutorial Linq to Xml - Create Xml Linq to Xml - Create Xml Linq to Xml - Insert Xml in C# Linq to Xml - Insert Xml in C# Linq to Xml - Read Xml in C# Linq to Xml - Read Xml in C# Linq to Xml - Update Xml in C# Linq to Xml - Update Xml in C# Linq to Xml - Delete Xml in C# Linq to Xml - Delete Xml in C# 47

48 Lecture 14: In-Class Exercise NO ICE TODAY. YOU WILL BE WORKING ON THE "WALK THROUGHS" OF THE LECTURE POWERPOINT IN LIEU OF THE ICE. 48


Download ppt "BIT 285: ( Web) Application Programming Lecture 14: Thursday, February 19, 2015 SQL Database and LINQ Instructor: Craig Duckett."

Similar presentations


Ads by Google