1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning Visual Basic 2005 Databases phần 8 ppsx

75 259 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

.Spacer { HEIGHT: 5px; } .General { FONT-FAMILY: Verdana; FONT-SIZE: 10pt; } The FlatButton style is used to define the style of the Button controls on your Web form. Instead of having plain gray buttons, you use this style to give them the same look as the buttons on the TimeSheet form in the Time Tracker application. The BORDER-RIGHT, BORDER-TOP, BORDER-LEFT, and BORDER- BOTTOM style attributes are used to set the borders of the Button control. These style attributes accept three parameters: the color of the border, the size of the border, and the line style of the border. This style also defines the font to be used and the size of the font. The BACKGROUND-COLOR style attribute defines the background color of the Button control and the COLOR style attribute defines the color of the text on the Button control. .FlatButton { BORDER-RIGHT: black 1px solid; BORDER-TOP: black 1px solid; FONT-SIZE: 10pt; BORDER-LEFT: black 1px solid; BORDER-BOTTOM: black 1px solid; FONT-FAMILY: Verdana; BACKGROUND-COLOR: #F5F5F5; COLOR: #000066; } The CellOutline style is used in the table cell where the timesheet was built. This style defines the bor- ders of the cell and specifies the padding to be used in the cell. The PADDING-LEFT, PADDING-RIGHT, PADDING-TOP, and PADDING-BOTTOM style attributes define the amount of space to leave between the borders of the cell and the content of the cell. Here you specify the padding space to be 10 pixels: .CellOutline { BORDER-LEFT: 1.5px solid #4682B4; BORDER-RIGHT: 1.5px solid #4682B4; BORDER-TOP: 1.5px solid #4682B4; BORDER-BOTTOM: 1.5px solid #4682B4; PADDING-LEFT: 10px; PADDING-RIGHT: 10px; PADDING-TOP: 10px; PADDING-BOTTOM: 10px; } The TimeSheetTable style is used in the table that contains the timesheet and defines the borders of the table. The BORDER-WIDTH style attribute defines the width of the borders in the table and has been set to use a border width of 1 pixel. The BORDER-STYLE attribute defines the styles of the borders of the table 513 Accessing Data in ASP.NET 17_58894x ch14.qxd 10/13/05 5:56 PM Page 513 and is set to a value of solid to define a solid border line. The BORDER-COLLAPSE style attribute indi- cates whether the row and cell borders of a table are joined in a single border or detached. A value of collapse, as defined here, indicates that the borders of the cells and rows are collapsed to form a solid border around each cell and row. The TimeSheetTableHeader style is used to define the header row of the timesheet. This is where the column labels are defined, and this style sets the background color of the cells, the color of the text, and the font weight. .TimeSheetTable { BACKGROUND-COLOR: White; BORDER-COLOR: Black; BORDER-WIDTH: 1px; BORDER-STYLE: solid; BORDER-COLLAPSE: collapse; FONT-FAMILY: Verdana; FONT-SIZE: 10pt; } .TimeSheetTableHeader { COLOR: White; BACKGROUND-COLOR: #006699; FONT-WEIGHT: bold; } The alternating style of the DataGrid control provides a means to have every other row a different color. To emulate this behavior, you define an EvenRow and OddRow style, which is used in the rows of your timesheet. The EvenRow style defines the background color to use in each cell and the color to be used for the text in the cells. The OddRow style simply defines the color to be used on the text in the cells. Finally, the TransparentTextBox style is used to make the TextBox controls in the total row of the timesheet look like regular text. You need the TextBox controls in the total row to be able to calculate and display the total for each column in your JavaScript. This style sets the width of the TextBox control and sets the border styles to none, meaning that no bor- ders will be visible in the TextBox control. Also, the BACKGROUND-COLOR style attribute is set to a value of transparent, indicating that the background color of the text box will inherit the background color of the cell in which it is placed. .EvenRow { COLOR: #000066; BACKGROUND-COLOR: #F5F5F5; } .OddRow { COLOR: #000066; } 514 Chapter 14 17_58894x ch14.qxd 10/13/05 5:56 PM Page 514 .TransparentTextBox { WIDTH: 30px; BORDER-TOP-STYLE: none; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BORDER-BOTTOM-STYLE: none; BACKGROUND-COLOR: transparent; } You continue by adding two client-side JavaScript functions that are used to validate input and recalcu- late the total row in your timesheet. The IsNumeric JavaScript function is lengthy but really quite simple. This function validates the key that has been pressed and determines whether it is a numeric key, a backspace key, or a Tab key. Any other key is invalid and this function will cause the invalid key to be canceled. The text boxes on your form that contain the hours for the various projects call this function when the onkeydown event is fired for that text box. The onkeydown event is a cancelable event, meaning that your code can cancel the key being pressed. The Event object is an object of the Window object (the browser window) and represents the state of an event. HTML elements have different events and the text box element raises the onkeydown event when the user presses a key. This function evaluates the event keyCode of the key being pressed in the switch statement. This is the equivalent to the Case statement in VB. If the keyCode of the key is equal to the backspace key, Tab key, or any of the numeric keys across the top of your keyword or any of the numeric keys in the keypad of your keyboard, the case statements will set the returnValue property of the event object to a value of true, meaning that the event may be processed. The break statement is required in each Case state- ment to exit the processing of the switch statement. function IsNumeric() { switch (event.keyCode) { case 8: //Backspace event.returnValue = true; break; case 9: //Tab event.returnValue = true; break; case 48: //0 event.returnValue = true; break; case 96: //0 event.returnValue = true; break; case 49: //1 515 Accessing Data in ASP.NET 17_58894x ch14.qxd 10/13/05 5:56 PM Page 515 event.returnValue = true; break; case 97: //1 event.returnValue = true; break; case 50: //2 event.returnValue = true; break; case 98: //2 event.returnValue = true; break; case 51: //3 event.returnValue = true; break; case 99: //3 event.returnValue = true; break; case 52: //4 event.returnValue = true; break; case 100: //4 event.returnValue = true; break; case 53: //5 event.returnValue = true; break; case 101: //5 event.returnValue = true; break; case 54: //6 event.returnValue = true; break; case 102: //6 event.returnValue = true; break; case 55: //7 event.returnValue = true; break; case 103: //7 event.returnValue = true; break; 516 Chapter 14 17_58894x ch14.qxd 10/13/05 5:56 PM Page 516 case 56: //8 event.returnValue = true; break; case 104: //8 event.returnValue = true; break; case 57: //9 event.returnValue = true; break; case 105: //9 event.returnValue = true; break; The code in the default statement will execute when none of the previous case statements are matched, and here you set the returnValue property to a value of false. This causes the onkeydown event to be canceled, meaning that the key pressed by the user will not be processed. default: //All others event.returnValue = false; break; } } The Recalculate function recalculates the total for a given day of the week. This function has been designed to accept the day of the week as an input parameter so it knows which day of the week it should recalculate the totals for. This function will be called when the user tabs out of a text box in the timesheet. The text boxes for a given day of the week for the various projects have the same name. For example, the text box for Monday has a name of txtMondayHours for each project listed. This effectively creates an array of TextBox controls named txtMondayHours. Therefore, the first thing that this function does is to declare a variable named intCount and get the number of elements in the array. This is accomplished using the length property of the TextBox element txtMondayHours. The length property returns the actual number of elements in the array. You access this property by first specifying the document object, which represents the HTML document in the browser window. Then you access the all collection in the document object, and then access the text box by specifying the text box name. You may have noticed that the text box for the Monday hours is always specified. Each column for each day of the week has the same number of TextBox controls, so this is a reliable method for determining how many elements are in the array of text boxes. After getting the number of elements in the array, you use a switch statement to determine which day of the week you should recalculate the totals for. The value passed in the dayofweek input parameter is the actual day of the week. 517 Accessing Data in ASP.NET 17_58894x ch14.qxd 10/13/05 5:56 PM Page 517 After you determine which day of the week you should be processing, the first thing that you do is clear the total in the text box in the total row for that day of the week. Then you set up a for loop and process each element in the array. The for statement accepts three parameters: the initialization parameter, the test parameter, and the increment parameter. The variable named i is declared and set to an initial value of 0 for the initialization parameter. This will represent the first item in the array, as the items in the array use a zero-based index. The test parameter is specified as i<intCount, meaning that this for statement should process as long as the value in the i parameter is less than the value in the intCount parameter. The increment parameter is specified as i++, meaning that for each iteration of the loop, the value of the i parameter is incremented by a value of 1. Inside of the for loop, you set the value property of the total text box to the value that is already there plus the value of the text box in the array for the day of the week that you are processing. For example, if you are processing the totals for Monday, you set the value of the txtMondayTotal text box to equal the current value of the txtMondayTotal text box plus the value of the txtMondayHours text box in the array that you are processing. The parseInt function returns an Integer value converted from a string, as all values in the value property of a text box are strings. Using this function just helps speed up the calculation of the totals, as the JavaScript engine does not have to go through the process of determining that this is a string value and then converting the string to an Integer data type. function Recalculate(dayofweek) { //Get the number of rows var intCount = document.all.txtMondayHours.length; //Find the day of the week that you are working with switch (dayofweek) { case “Monday”: //Set the current total to 0 as it will be recalculated document.all.txtMondayTotal.value = 0; //Process each row of data adding it to the total for (i=0;i<intCount;i++) { document.all.txtMondayTotal.value = parseInt(document.all.txtMondayTotal.value) + parseInt(document.all.txtMondayHours[i].value); } break; case “Tuesday”: //Set the current total to 0 as it will be recalculated document.all.txtTuesdayTotal.value = 0; //Process each row of data adding it to the total for (i=0;i<intCount;i++) { document.all.txtTuesdayTotal.value = parseInt(document.all.txtTuesdayTotal.value) + parseInt(document.all.txtTuesdayHours[i].value); } 518 Chapter 14 17_58894x ch14.qxd 10/13/05 5:56 PM Page 518 break; case “Wednesday”: //Set the current total to 0 as it will be recalculated document.all.txtWednesdayTotal.value = 0; //Process each row of data adding it to the total for (i=0;i<intCount;i++) { document.all.txtWednesdayTotal.value = parseInt(document.all.txtWednesdayTotal.value) + parseInt(document.all.txtWednesdayHours[i].value); } break; case “Thursday”: //Set the current total to 0 as it will be recalculated document.all.txtThursdayTotal.value = 0; //Process each row of data adding it to the total for (i=0;i<intCount;i++) { document.all.txtThursdayTotal.value = parseInt(document.all.txtThursdayTotal.value) + parseInt(document.all.txtThursdayHours[i].value); } break; case “Friday”: //Set the current total to 0 as it will be recalculated document.all.txtFridayTotal.value = 0; //Process each row of data adding it to the total for (i=0;i<intCount;i++) { document.all.txtFridayTotal.value = parseInt(document.all.txtFridayTotal.value) + parseInt(document.all.txtFridayHours[i].value); } break; } } The next step is to create a table that will hold the controls and the actual timesheet. The first row in this table is just a filler row to create a space between the last row of data in the previous table and the first row of data in this table. If none of the columns in a row contain data, the row will not take up space in the resulting output that is displayed. To have this row create the space that you are looking for, you specify that a blank space should be created in the column using the text &nbsp;. This creates a place- holder for a space in the column, thus giving you the effect that you want. The next row in this table contains the username and contains the Save and Submit buttons as well as the DropDownList control for the week ending dates. The third row in this table is an alternative way to create a spacer row instead of using the HTML characters, &nbsp;, used to create the first row in this table. Here you are using a user-defined style in your style sheet to specify the height of the row, which causes this row to take up space in the HTML output regardless of whether the row contains any data. The final row in this table contains some server-side code to call the DisplayTimeSheet function. This function builds a timesheet table and writes it in the column of this row: 519 Accessing Data in ASP.NET 17_58894x ch14.qxd 10/13/05 5:56 PM Page 519 <table border=”0” cellpadding=”0” cellspacing=”0” width=”100%”> <tr> <td colspan=”4”>&nbsp;</td> </tr> <tr> <td class=”General” nowrap>TimeSheet for <b><%=Request.QueryString(“UserName”)%></b> </td> <td></td> <td></td> <td class=”General”>Week Ending Date</td> </tr> <tr> <td colspan=”4” class=”Spacer”></td> </tr> <tr> <td colspan=”4” class=”CellOutline”> <%Call DisplayTimeSheet()%> </td> </tr> </table> The next steps add the actual controls to the Web form and set their properties. You add the Dates class next and add two functions to this class. The GetCurrentWeekEndingDate and GetPreviousWeekEndingDate functions are the same functions that you created in your TimeSheet form in the Time Tracker application. Placing these functions in this class makes them accessible to all Web forms in your application. You’ll not only use these functions in your TimeSheet Web form, but also in another Web form that you create in Chapter 16. Public Function GetCurrentWeekEndingDate() As String GetCurrentWeekEndingDate = DateSerial( _ Year(Now), Month(Now), DateAndTime.Day(Now) - _ DatePart(“w”, Now, Microsoft.VisualBasic.FirstDayOfWeek.Sunday) + 6) End Function Public Function GetPreviousWeekEndingDate() As String GetPreviousWeekEndingDate = DateSerial( _ Year(Now), Month(Now), DateAndTime.Day(Now) - _ DatePart(“w”, Now, Microsoft.VisualBasic.FirstDayOfWeek.Sunday) - 1) End Function The first thing you do when you start adding code to the code-behind file for your TimeSheet Web form is to import the System.Data namespace, for which the code is not shown here. Then you declare some variables. These variables are used throughout your code for the various tasks that you perform and all of these variables should look familiar from your TimeSheet form in the Time Tracker application. ‘Private variables and objects Private intIndex As Integer Private intTotal As Integer Private blnEvenRow As Boolean = True 520 Chapter 14 17_58894x ch14.qxd 10/13/05 5:56 PM Page 520 Private strCompany As String = “Wrox” Private strApplication As String = “Time Tracker” Private dteWeekEndingDate As Date Private objTimeSheets As WroxBusinessLogic.WBLTimeSheets Private objDates As New Dates Private objTimeSheetDS As DataSet Remember that the Page_Load procedure is always executed first, before any HTML in your Web form is rendered. Here you have some tasks that need to be performed before a post back occurs and after a post back occurs. Starting at the top, you want to check the IsPostBack property and if this Web form is being posted back to the server, you want to get the data that you stored in ViewState. ViewState is a field in a Web page inserted by ASP.NET in encrypted format and persists changes to the state of a Web form between post backs. You can add your data to the ViewState of a Web form on the server when building the Web page and then retrieve those values when the page is posted back to the server for processing. The first value that you want to retrieve from ViewState is the initial week ending date that was stored there with a name of WeekEndingDate. You explicitly convert the value you retrieve from ViewState to a Date data type and set this value in your dteWeekEndingDate variable. Then you retrieve the DataSet containing the timesheet data from ViewState and explicitly convert this object to a DataSet data type and set it in your objTimeSheetDS object. Finally, you call the UpdateTimeSheetDS function to update the timesheet DataSet with any changes that the user may have made. Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If IsPostBack Then ‘Get the week ending date dteWeekEndingDate = CType(ViewState(“WeekEndingDate”), Date) ‘Get the timesheet DataSet objTimeSheetDS = CType(ViewState(“TimeSheetDS”), DataSet) ‘Update the timesheet DataSet Call UpdateTimeSheetDS() If the page is not being posted back then the code in the Else statement is executed and sets some initial values, loads the controls on the Web form, gets the timesheet data, and saves the data in ViewState. First, you set the default week ending date in the dteWeekEndingDate variable using the week ending date for the current week, which is retrieved from the GetCurrentWeekEndingDate function in the Dates class. Then you add the previous and current week ending dates to the Items collection in the cboWeekEndingDate combo box on your Web form and set the SelectedIndex property to display the current week ending date. Next, you call the GetTimeSheet procedure to get the timesheet for the specified week ending date that has been set in the dteWeekEndingDate variable. Finally, you save the timesheet DataSet and current 521 Accessing Data in ASP.NET 17_58894x ch14.qxd 10/13/05 5:56 PM Page 521 week ending date in ViewState so that they will be available when the user posts the Web form back to the server for processing. Else ‘Set the default week ending date dteWeekEndingDate = CType(objDates.GetCurrentWeekEndingDate, Date) ‘Load the week ending dates in the form cboWeekEndingDate.Items.Add(objDates.GetPreviousWeekEndingDate) cboWeekEndingDate.Items.Add(objDates.GetCurrentWeekEndingDate) cboWeekEndingDate.SelectedIndex = 1 ‘Get the timesheet Call GetTimeSheet() ‘Save the data between requests ViewState(“TimeSheetDS”) = objTimeSheetDS ViewState(“WeekEndingDate”) = dteWeekEndingDate End If End Sub The GetTimeSheet procedure does not need much explanation as it pretty much mirrors the code in the LoadTimeSheet procedure in the TimeSheet form in the Time Tracker application. In the LoadTimeSheet procedure, you worked with a DataView object to build and calculate the total row. In this procedure you are working directly with the DataSet object to build and calculate the total row. Also, this proce- dure does not do any data binding to any controls, so you’ll notice that it is much smaller than the LoadTimeSheet procedure in the TimeSheet form in the Time Tracker application. Private Sub GetTimeSheet() ‘Initialize a new instance of the business logic component Using objTimeSheets As New WroxBusinessLogic.WBLTimeSheets( _ strCompany, strApplication) ‘Get the timesheet for the user objTimeSheetDS = objTimeSheets.GetTimeSheet( _ New Guid(Request.QueryString(“UserID”)), dteWeekEndingDate) ‘Initialize a new DataRow object Dim objDataRow As DataRow = objTimeSheetDS.Tables(“TimeSheet”).NewRow ‘Set the values in the columns objDataRow.Item(“ProjectName”) = “Total Hours” ‘Calculate and set the total hours for Monday intTotal = 0 For intIndex = 0 To objTimeSheetDS.Tables(“TimeSheet”).Rows.Count - 1 intTotal += CType(objTimeSheetDS.Tables( _ “TimeSheet”).Rows(intIndex).Item(“MondayHours”), Integer) Next objDataRow.Item(“MondayHours”) = intTotal ‘Calculate and set the total hours for Tuesday intTotal = 0 522 Chapter 14 17_58894x ch14.qxd 10/13/05 5:56 PM Page 522 [...]... Web Service to produce report data ❑ Leverage your business logic component by using it in your Web Service I recommend that you read the chapter on Web Services in Beginning VB 2005 for a basic understanding of how Web Services work and the basic terminology used in this chapter Design Goal The design goal behind your Web Service is to generate report data for your Time Tracker application and to expose... to produce the report data for the reports that will be generated from your Web Service Try It Out Report Stored Procedures To complete this exercise: 1 2 Open your Time Tracker application in Visual Studio 2005 3 The first stored procedure that you want to create is the stored procedure to select a specific manager’s name The manager’s name will be displayed in the heading of all reports Readers using... executes, it returns the Friday date for the current week SELECT DATEADD(WK, DATEDIFF(WK,0,GETDATE()), 4) The Oracle version of calculating the current week ending date relies on the TO_CHAR function and some basic math The TO_CHAR function converts a date to a string format and accepts two parameters: the date to be converted and the date format to which the date should be converted In the following example,... DATEADD(QQ, DATEDIFF(QQ,0,GETDATE()), 0) 536 Creating a Web Service The code for Oracle takes a different approach to calculating the first day of the quarter The TRUNC function will round down dates to the beginning of the format mask provided This function accepts two parameters: a date value and the format mask A format mask is typically a one- or two-character abbreviation for the format that you want... objTimeSheetDS.Tables(“TimeSheet”).Rows(intIndex).Item( _ “ThursdayHours”) = CType(Request.Form(“txtThursdayTotal”), Byte) objTimeSheetDS.Tables(“TimeSheet”).Rows(intIndex).Item( _ “FridayHours”) = CType(Request.Form(“txtFridayTotal”), Byte) End Sub 5 28 Accessing Data in ASP NET The next order of business is to add code for the combo box on your Web form When a user selects a new week ending date in the combo box, it will automatically call this procedure... TimeSheetItems.TimeSheetID LEFT OUTER JOIN Users ON TimeSheets.UserID = Users.UserID WHERE Users.ManagerID = @ManagerID AND WeekEndingDate = @WeekEndingDate AND Submitted = 0 GROUP BY FirstName, LastName, Email 5 38 Creating a Web Service Click the Save icon on the toolbar to have the stored procedure created in your database Oracle CREATE OR REPLACE PACKAGE TimeSheetsDuePackage AS TYPE CURSOR_TYPE IS REF CURSOR;... varFirstDayOfQuarter AND varWeekEndingDate AND Submitted = 1 GROUP BY WeekEndingDate, FirstName, LastName, ApprovalDate; END; END; Click the Execute button to have the package body created in your database 8 The last stored procedure to create is one to select the timesheets for the year-to-date report Again, Oracle readers need to create a package, as this stored procedure returns data SQL Server users... MyBase.InitializeCommand() ‘Add the Parameters to the Parameters collection MyBase.AddParameter(“@ManagerID”, _ SqlDbType.UniqueIdentifier, 16, ManagerID) MyBase.AddParameter(“@WeekEndingDate”, _ SqlDbType.DateTime, 8, WeekEndingDate) ‘Fill the DataSet MyBase.FillDataSet(TimeSheetsDue, “TimeSheets”) Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) End... Parameters to the Parameters collection MyBase.AddParameter(“inManagerID”, _ OracleClient.OracleType.Char, 36, ManagerID.ToString) MyBase.AddParameter(“inWeekEndingDate”, _ OracleClient.OracleType.DateTime, 8, WeekEndingDate) MyBase.AddParameter(“results_cursor”, _ OracleClient.OracleType.Cursor, ParameterDirection.Output) ‘Fill the DataSet MyBase.FillDataSet(TimeSheetsDue, “TimeSheets”) Catch ExceptionErr... Parameters to the Parameters collection MyBase.AddParameter(“@ManagerID”, _ SqlDbType.UniqueIdentifier, 16, ManagerID) 546 Creating a Web Service MyBase.AddParameter(“@WeekEndingDate”, _ SqlDbType.DateTime, 8, WeekEndingDate) ‘Fill the DataSet MyBase.FillDataSet(TimeSheetsSubmitted, “TimeSheets”) Catch ExceptionErr As Exception Throw New System.Exception(ExceptionErr.Message, _ ExceptionErr.InnerException) . pixels: .CellOutline { BORDER-LEFT: 1.5px solid #4 682 B4; BORDER-RIGHT: 1.5px solid #4 682 B4; BORDER-TOP: 1.5px solid #4 682 B4; BORDER-BOTTOM: 1.5px solid #4 682 B4; PADDING-LEFT: 10px; PADDING-RIGHT: 10px; PADDING-TOP:. 103: //7 event.returnValue = true; break; 516 Chapter 14 17_ 588 94x ch14.qxd 10/13/05 5:56 PM Page 516 case 56: / /8 event.returnValue = true; break; case 104: / /8 event.returnValue = true; break; case 57: //9 event.returnValue. parseInt(document.all.txtTuesdayTotal.value) + parseInt(document.all.txtTuesdayHours[i].value); } 5 18 Chapter 14 17_ 588 94x ch14.qxd 10/13/05 5:56 PM Page 5 18 break; case “Wednesday”: //Set the current total to 0 as it will be

Ngày đăng: 12/08/2014, 10:21

TỪ KHÓA LIÊN QUAN