Top Posters
Since Sunday
5
a
5
k
5
c
5
B
5
l
5
C
4
s
4
a
4
t
4
i
4
r
4
A free membership is required to access uploaded content. Login or Register.

Web Applications with Visual C#.docx

Uploaded: 6 years ago
Contributor: redsmile
Category: Operating Systems
Type: Other
Rating: N/A
Helpful
Unhelpful
Filename:   Web Applications with Visual C#.docx (323.07 kB)
Page Count: 247
Credit Cost: 1
Views: 882
Last Download: N/A
Transcript
Developing and Implementing Web Applications with Microsoft Visual C NET QUESTION You create an ASP NET application for Certkiller 's intranet All employee on the intranet use Internet Explorer A page named UserAccount aspx contains several controls that require postback to the server for event processing The event handlers for these controls require access to a database in order to complete their processing Each time UserAccount aspx performs a postback there is a brief period of time in which the browser window is blank while the page is refreshed The control that had the focus prior to the postback does not have the focus after the page is re-rendered This factor results in confusion and invalid data entry by some of the users You need to modify UserAccount aspx to prevent the browser window from going blank after a postback and to maintain the correct control focus after events are processed You need to accomplish this task with the minimum amount of development effort What should you do Add the following attribute to the HTML code for the controls that cause the postbacks RunAt client Add the following attribute to the HTML code for the controls that cause the postbacks EnableViewState True Add the following attribute to the Page directive for UserAccount aspx SmartNavigation True Add the following attribute to the OutputCache directive for UserAccount aspx Location client Answer C Explanation When a page is requested by an Internet Explorer browser or later smart navigation enhances the user's experience of the page by performing the following eliminating the flash caused by navigation persisting the scroll position when moving from page to page persisting element focus between navigations retaining only the last page state in the browser's history Smart navigation is best used with ASP NET pages that require frequent postbacks but with visual content that does not change dramatically on return Reference NET Framework Class Library Page SmartNavigation Property C QUESTION You are a Web developer for a Certkiller bookstore You create a Web user control named CKBookTopics that is defined in a file named CKBookTopics ascx CKBookTopics displays a list of book topics based on an author's profile identification number The profile identification number is stored in a public property of CKBookTopics named AuthorProfile You create an ASP NET page named AuthorPage aspx that contains an instance of the CKBookTopics Web user control AuthorPage aspx is opened by an HTTP-GET request that has two parameters The parameters are named publisherID and authorProfileID The value of authorProfileID is a profile identification number You want to enable output caching for the CKBookTopics Web user control You need to ensure that the cached control is varied only by an author's profile identification number What should you do Add the following element to the OutputCache directive for AuthorPage aspx VaryByParam CKBookTopics AuthorProfile Add the following element to the OutputCache directive for AuthorPage aspx VaryByControl CKBookTopics AuthorProfile Add the following element to the OutputCache directive for CKBookTopics ascx VaryByParam none Add the following element to the OutputCache directive for CKBookTopics ascx VaryByControl authorProfileID Answer D Explanation You can vary user control output to the cache in two ways With the user control name and the parameter The VaryByParam attribute of the OutputCache directive must be used A and C are inadequate since both the control name and the parameter must be specified With the VaryByControl attribute just the parameter should be supplied This is the case in D but not in B Reference NET Framework Developer's Guide Caching Multiple Versions of a User Control Based on Parameters C QUESTION You are maintaining an ASP NET application named Certkiller SalesForecast The application is written in Visual C NET The application includes a page named FirstQuarter aspx that resides within the Sales namespace The page class is named FirstQuarter You discover that another developer inadvertently deleted the Page directive for FirstQuarter aspx You want to create a new Page directive to allow FirstQuarter aspx to work properly Which directive should you use Page Language c Codebehind FirstQuarter aspx cs Inherits FirstQuarter Page Language c Codebehind FirstQuarter aspx cs ClassName Sales FirstQuarter Page Language c Codebehind FirstQuarter aspx cs Inherits Sales FirstQuarter Page Language c Codebehind FirstQuarter aspx cs ClassName Sales FirstQuarter Inherits FirstQuarter Answer C Explanation The Inherits attribute in the Page directive defines a code-behind class for the page to inherit As FirstQuarter aspx resides within the Sales namespace we should use Inherits Sales FirstQuarter Note The Page directive defines page-specific aspx file attributes used by the ASP NET page parser and compiler Reference NET Framework General Reference Page Incorrect Answers A As FirstQuarter aspx resides within the Sales namespace we should use Inherits Sales FirstQuarter B D The ClassName attribute specifies the class name for the page that will be automatically compiled dynamically when the page is requested We should not use ClassName here QUESTION You are creating and ASP NET application for the mortgage services department of Certkiller Inc The application will be used for generating documents required during the closing process of a home purchase Certkiller already has a component written in Visual C NET that identifies which forms are required to be printed based on a set of criteria specified by the closing agent The name of the component namespace is Certkiller Mortgage The name of the class is Closing You create an ASP NET page named Purchase aspx You add a reference to the assembly that contains the Certkiller Mortgage namespace The code behind file for Purchase aspx includes the following code using Certkiller Mortgage You add a method to the code-behind file to instantiate the Closing class Which code segment should you include in the method to instantiate the class Closing CKClosing new Closing Closing CKClosing Server CreateObject Certkiller Mortgage Closing object CKClosing Server CreateObject closing Type CKType Type GetTypeFromProgID Certkiller Mortgage Closing localhost true Answer A Explanation We simply instantiate an object with the class with the New constructor Note Web Forms pages have code -behind files associated with them These files are created automatically when you create a new Web form They have the same base name as the Web form with the vb or cs filename extension added Incorrect Answers B C The CreateObject function creates and returns a reference to a COM object CreateObject cannot be used to create instances of classes in Visual Basic unless those classes are explicitly exposed as COM components D The Type GetTypeFromProgID method is provided for COM support Program IDs are not used in Microsoft NET Framework because they have been superceded by the concept of namespace QUESTION You create a class named CKFormat that has two public properties One of the properties is named Size and the other property is named Color You want to use the CKFormat class in custom server controls to expose format properties to container pages You add the following statements to a custom server control named MessageRepeater private CKFormat formatter new CKFormat public CKFormat Format get return formatter You create a container page named MessageContainer aspx to test your custom control You register the control as follows Register Tagprefix CertK ctl Namespace MessageControls Assembly MessageControls You want to add an instance of the control to a test page so that the size property is set to and the color property is set to red Which code should you use CertK ctl MessageRepater Format-Color red Format-Size CertK ctl MessageRepater Format-Color red Format-Size runat server CertK ctl MessageRepater Color red Size runat server CertK ctl MessageRepater Format Color red size Answer B Explanation ASP NET has a special syntax for setting subproperties The - syntax denotes a subproperty The Format Color and Format Size properties are denoted by Format-Color and Format-Size respectively We should also specify that the control should run at the server Incorrect Answers A As this is a custom server control we should specify that it should run at the server C D We must use the - syntax denotes a subproperties QUESTION You create an ASP NET page named Location aspx Location aspx contains a Web user control that displays a drop-down list box of counties The Web user control is named CountyList and is defined in a file named CountyList ascx The name of the DropDownList control in CountyList ascx is CKCounty You try to add code to the Page Load event handler for Location aspx but you discover that you cannot access CKCounty from mode in Location aspx You want to ensure that code within Location aspx can access properties of CKCounty What should you do In the code-behind file for CountyList ascx add the following line of code protected DropDownList CKCounty In the code-behind file for CountyList ascx add the following line of code public DropDownList CKCounty In the code-behind file for Location aspx add the following line of code protected DropDownList CKCounty In the code-behind file for Location aspx add the following line of code public DropDownList CKCounty Answer B Explanation We must declare the CKCounty as public in the file in which it is defined CountyList ascx Note The Public keyword in the Dim statement declares elements to be accessible from anywhere within the same project from other projects that reference the project and from an assembly built from the project Reference Visual Basic Language Concepts Accessibility Incorrect Answers A C The Protected keyword in the Dim statement declares elements to be accessible only from within the same class or from a class derived from this class However do not want to protect MyCount at the contrary we must make it public D We must declare it public in the files in which it is defined not Location aspx where it is only used QUESTION You create an ASP NET page that uses images to identify areas where a user can click to initiate actions The users of the application use Internet Explorer You want to provide a pop-up window when the user moves the mouse pointer over an image You want the pop-up window to display text that identifies the action that will be taken if the user clicks the image What should you do For each image set the AlternateText property to specify the text you want to display and set the ToolTip property to True For each image set the ToolTip property to specify the text you want to display In the onmouseover event handler for each image add code that calls the RaiseBubbleEvent method of the System Web UI WebControls Image class In the onmouseover event handler for each image add code that calls the ToString method of the System Web UI WebControls Image class Answer B Explanation WebControl ToolTip property gets or sets the text displayed when the mouse pointer hovers over the Web server control The use of the ToolTip property meets the requirement of this scenario Reference NET Framework Class Library WebControl ToolTip Property C Incorrect Answers A The AlternateText property is used to specify the text to display if the image is not available C The RaiseBubbleEvent is not useful here Note ASP NET server controls such as the Repeater DataList and DataGrid Web controls can contain child controls that raise events Rather than each button raising an event individually events from the nested controls are bubbled -that is they are sent to the control's parent D The ToStringMethod would not by itself provide the functionality required QUESTION You create a user control named Address that is defined in a file named Address ascx Address displays address fields in an HTML table Some container pages might contain more than one instance of the Address user control For example a page might contain a shipping address and a billing address You add a public property named CKCaption to the Address user control The caption property will be used to distinguish the different instances You want the caption to be displayed in the first td element of the table of address fields You need to add code to the td element of the table to display the caption Which code should you use td CKCaption td td script runat server CKCaption script td td script document write CKCaption scripts td td CKCaption td Answer A Explanation CKCaption is a public property contained on the Web server We reference it with the CKCaption element Incorrect Answers B C Scrips are not called for We just want to display a property D To access the public property we must use an element QUESTION You create an ASP NET page named Subscribe aspx for users to subscribe to e -mail lists You include an existing user control named ListSubscribe in your page ListSubscribe has two constituent controls One control is a TextBox control named listNameText and the other control is a Button control named subscribeButton ListSubscribe is defined in the ListSubscribe ascx file To add ListSubscribe to Subscribe aspx you add the following tag email ListSubscribe id ctlSubscribe runat server You add a Label control named listNameLabel to the container page When a user subscribes to a list by entering a list name in listNameText and clicking the subscribeButton button you want the page to display the list name in listNameLabel Which two actions should you take Each correct answer presents part of the solution Choose two Add the following statement to the declaration section of ListSubscribe ascx public TextBox listNameText Add the following statement to the declaration section of Subscribe aspx public TextBox listNameText Add the following statement to the Page Load event handler for Subscribe aspx if Page IsPostBack listNameLabel Text ctlSubscribe listNameText Text Add the following statement to the Page Load event handler for Subscribe aspx if Page IsPostBack listNameLabel Text ctlSubscribe listNameText Text Add the following statement to the Page Load event handler for ListSubscribe ascx if Page IsPostBack listNameLabel Text listNameText Text Add the following statement to the Page Load event handler for ListSubscribe ascx if Page IsPostBack listNameLabel Text listNameText Text Answer A D Explanation We must expose the listNameText control by declaring it as public The ListSubscribe ascx file contains the listNameText control so we expose it in this file Note The controls that make up a user control are called constituent controls These controls are normally declared private and thus cannot be accessed by the developer If you want to make properties of these controls available to future users you must expose them to the user If the control is reloaded in the Subscribe aspx file due to a response to a client postback we should set the listNameLabel Text property Note The UserControl IsPostBack property gets a value indicating whether the user control is being loaded in response to a client postback or if it is being loaded and accessed for the first time Reference Visual Basic and Visual C Concepts Exposing Properties of Constituent Controls NET Framework Class Library UserControl IsPostBack Property Incorrect Answers The listNameText control is defined in ListSubscribe aspx not in Subscribe aspx C This would only copy the text when the page is initially loaded E F We should use the Page Load event of Subscribe aspx not for ListSubscribe aspx QUESTION You create an ASP NET server control to display date and time information You want to enable other programmers who use your control to customize the style properties of a Label control named timeCKLabel The timeCKLabel control displays the date and time You create two custom property procedures to accomplish this goal One procedure modified the BackColor property of the constituent controls The other procedure modifies the ForeColor property of the constituent controls In addition to these two custom property procedures you want to allow users to apply one of two predefined styles The predefined styles are created in the following function public Style GetStyle int styleType Style myStyle new Style switch styleType case myStyle ForeColor System Drawing Color White myStyle BackColor System Drawing Color Black break return myStyle You want to write a public method that will apply these styles You do not want to overwrite the ForeColor property and BackColor property if the Label control of these properties are already set by using the custom property procedures Which code segment should you use for this method public void PickStyle int styleType Style myStyle GetStyle styleType timeCKLabel ApplyStyle myStyle public void PickStyle int styleType Style myStyle GetStyle styleType timeCKLabel MergeStyle myStyle public void PickStyle int styleType Style myStyle GetStyle styleType timeCKLabel ForeColor myStyle ForeColor timeCKLabel BackColor myStyle BackColor D public void PickStyle int styleType Style myStyle GetStyle styleType timeCKLabel CssClass myStyle CssClass Answer B Explanation The WebControl MergeStyle method copies any nonblank elements of the specified style to the Web control but will not overwrite any existing style elements of the control This method is used primarily by control developers Reference NET Framework Class Library WebControl MergeStyle Method C Incorrect Answers A WebControl ApplyStyle Method copies any nonblank elements of the specified style to the Web control overwriting any existing style elements of the control We don't want to overwrite any existing style elements however We don't want to overwrite any existing style elements - The WebControl CssClass Property gets or sets the Cascading Style Sheet CSS class rendered by the Web server control on the client It not useful in this scenario though QUESTION You are a Web developer for a travel company called Certkiller travels You are developing a Web site for customers who participate in the company's frequent flyer program The frequent flyer program includes three levels of award for customers The levels are named Emerald Ruby and Diamond For each award level the page contains content specific to that award level The page contents are contained in three user controls which are named Emerald ascx Ruby ascx and Diamond ascx You want to dynamically load and display the proper page header based on the value contained in a variable named awardLevel The awardLevel variable is a property of the page In addition you want to minimize the mount of memory resources each page uses Which code should you use in the Page Load event handler A UserControl headerUserControl switch awardLevel case Emerald headerUserControl UserControl LoadControl Emerald ascx break case Ruby headerUserControl UserControl LoadControl Ruby ascx break case Diamond headerUserControl UserControl LoadControl Diamond ascx break Controls Add headerUserControl UserControl headerUserControl switch awardLevel case Emerald headerUserControl UserControl LoadControl Emerald ascx break case Ruby headerUserControl UserControl LoadControl Ruby ascx break case Diamond headerUserControl UserControl LoadControl Diamond ascx break emeraldheaderUserControl Visible false rubyheaderUserControl Visible false diamondheaderUserControl Visible false switch awardLevel case Emerald emeraldHeaderControl Visible true break case Ruby rubyHeaderControl Visible true break case Diamond diamondHeaderControl Visible true break UserControl emeraldHeaderControl UserControl rubyHeaderControl UserControl diamondHeaderControl emeraldHeaderControl UserControl LoadControl Emerald aspx rubyHeaderControl UserControl LoadControl Ruby aspx diamondHeaderControl UserControl LoadControl Diamond aspx switch awardLevel case Emerald Controls Add emeraldHeaderControl break case Ruby Controls Add rubyHeaderControl break case Diamond Controls Add diamondHeaderControl break Answer A Explanation The TemplateControl LoadControl method obtains a UserControl object from a user control file Reference NET Framework Class Library TemplateControl LoadControl Method C Incorrect Answers We must add the control in order to display it We must load the user controls Loading all three controls increase the demand on the system resource QUESTION You are creating an ASP NET application for Certkiller 's Internet Web site You want to create a toolbar that will be displayed at the top of each page in the Web site The toolbar will contain only static HTML code The toolbar will be used in only your application Your plan to create the toolbar as a reusable component for your application You need to create the toolbar as quickly as possible What should you do Create a new Web Control Library project Create the toolbar within a Web custom control Add a new Web user control to your ASP NET project Create the toolbar within the Web user control Add a new Web Form to your ASP NET project Use HTML server controls to design the toolbar within the Web Form and save the Web Form with an ascx extension D Add a new component class to your ASP NET project Use HTML server controls to design the toolbar within the designer of the component class Answer B Explanation Web user controls enable you to easily define controls as you need them for your applications using the same programming techniques that you use to write Web Forms pages Reference Visual Basic and Visual C Concepts Introduction to Web User Controls Incorrect Answers A You can use the Web Control Library project template to author custom Web server controls However since the toolbar is only going to be used in this application there is no need of the complexity of a Web customer control An HTML server control would be inadequate The Component class provides the base implementation for the IComponent interface and enables object-sharing between applications It does not fit in this scenario QUESTION You create an ASP NET page that displays customer order information This information is displayed in two separate DataGrid controls on the page The first DataGrid control displays the current year orders and the second DataGrid control displays all orders from previous years The page uses both the System Data SqlClient namespace and the System Data namespace The information is stored in a Microsoft SQL Server database named Certkiller SQL A customer's complete order history information is obtained from the database by calling a stored procedure named GetOrders and passing the customer's identification number as a parameter The Page Load event handler populates a DataView object named ckDataView with the result of calling the GetOrders stored procedure The following code segment in the Page Load event handler is then used to bind the two DataGrid controls to myData view ckDataView dataGridCurrentYear DataSource ckDataView ckDataView RowFilter OrderDate Now Year dataGridCurrentYear DataBind dataGridPreviousYears DataSource ckDataView ckDataView RowFilter OrderDate Now Year DataGridPreviousYears DataBind Page DataBind During testing you discover that both DataGrid controls are displaying order information for the previous years only What should you do to correct this problem Remove the Page DataBind statement Remove the dataGridPreviousYears DataBind statement Add a Response Flush statement immediately before the Page DataBind statement Add a Response Flush statement immediately before the dataGridPreviousYears DataBind statement Answer A Explanation Both datagrids use the same DataView The Page Databind method binds a data source to the invoked server control and all its child controls We should remove this statement Reference NET Framework Class Library Control DataBind Method C Incorrect Answers B We must bind each data grid control to its data source C D The HttpResponse Flush method sends all currently buffered output to the client It is not useful in this scenario QUESTION You are creating an e-commerce site for Certkiller Your site is distributed across multiple servers in a Web farm Users will be able to navigate through the pages of the site and select products for purchase You want to use a DataSet object to save their selections Users will be able to view their selections at any time by clicking a Shopping Cart link You want to ensure that each user's shopping cart DataSet object is saved between requests when the user is making purchases on the site What should you do A Create a StateBag object Use the StateBag object to store the DataSet object in the page's ViewState property Use the HttpSessionState object returned by the Session property of the page to store the DataSet object Use the Web config file to configure an out-of-process session route Use the Cache object returned by the page's Cache property to store a DataSet object for each user Use an HttpCachePolicy object to set a timeout period for the cached data D Use the Session Start event to create an Application variable of type DataSet for each session Store the DataSet object in the Application variable Answer B Explanation An HttpSessionState object provides access to session-state values as well as session- level settings and lifetime management methods We should use an out-of-process session to ensure that each user's shopping cart DataSet object is saved between requests Note ASP NET provides three distinct ways to store session data for your application in-process session state out-of-process session state as a Windows service and out-of-process session state in a SQL Server database The out-of-process solutions are primarily useful if you scale your application across multiple processors or multiple computers or where data cannot be lost if a server or process is restarted Reference NET Framework Class Library HttpSessionState Class C NET Framework Developer's Guide Developing High-Performance ASP NET Applications C Incorrect Answers A A StateBag object manages the view state of ASP NET server controls including pages This object implements a dictionary It would not be useful in this scenario however A cache is not a secure storage location As multiple servers are going to be used an Application variable is not the best solution QUESTION You are creating a new ASP NET page named ItemList that displays item and price information for many different items When a user logs on to the Web site the page retrieves the current list of prices from a database ItemList will be accessed by several thousand registered users When a price list is retrieved for a user the prices remain valid for as long as the user continues to access the page Users are allowed to keep the same price list for several days When ItemList is posted back to the server you want to ensure that the price list was not altered on the user's computer You also want to minimize the memory resources consumed on the Web server Which three parameters should you add to the Page directive in ItemList Each correct answer presents part of the solution Choose three EnableSessionState True EnableSessionState False EnableSessionState ReadOnly EnableViewState True EnableViewState False EnableViewStateMac True EnableViewStateMac False Answer B D F Explanation To minimize the memory resources consumed on the Web server we need to use view state instead of session state Setting EnableViewState to true will only cost us bandwidth not memory resources Disable session state Enable view state A view state MAC is an encrypted version the hidden variable that a page's view state is persisted to when sent to the browser When you set this attribute to true the encrypted view state is checked to verify that it has not been tampered with on the client Reference NET Framework Developer's Guide Developing High-Performance ASP NET Applications NET Framework General Reference Page NET Framework Developer's Guide Session State Incorrect Answers An enabled Session state would require additional server resources A readonly Session state would still require additional server resources E We need view state to be eanbled G To ensure that client has not changed the data we set EnableViewStateMac QUESTION You create an ASP NET page named Certkiller Calendar aspx that shows scheduling information for projects in your company The page is accessed from various other ASP and ASP NET pages hosted throughout the company's intranet All employees on the intranet use Internet Explorer Certkiller Calendar aspx has a Calendar control at the top of the page Listed below the Calendar control is detailed information about project schedules on the data selected When a user selects a date in the calendar the page is refreshed to show the project schedule details for the newly selected date Users report that after viewing two or more dates on Certkiller Calendar aspx they need to click the browser's Back button several times in order to return to the page they were viewing prior to accessing Certkiller Calendar aspx You need to modify Certkiller Calendar aspx so that the users need to click the Back button only once What should you do Add the following statement to the Page Load event handler for Certkiller Calendar aspx Response Expires Add the following statement to the Page Load event handler for Certkiller Calendar aspx Response Cache SetExpires DateTime Now Add the following attribute to the Page directive for Certkiller Calendar aspx EnableViewState True Add the following attribute to the Page directive for Certkiller Calendar aspx SmartNavigation True Answer D Explanation the user's experience of the page by performing the following retaining only the last page state in the browser's history This is what is required in this scenario eliminating the flash caused by navigation persisting the scroll position when moving from page to page persisting element focus between navigations Reference NET Framework Class Library Page SmartNavigation Property C Incorrect Answers This is not a page expiration problem This is not a caching problem The Page EnableViewState property Gets or sets a value indicating whether the page maintains its view state and the view state of any server controls it contains when the current page request ends QUESTION You are creating an ASP NET application for Certkiller Customers will use the application to file claim forms online You plan to deploy the application over multiple servers You want to save session state information to optimize performance What are two possible ways to achieve this goal Each correct answer presents a complete solution Choose two Modify the Web config file to support StateServer mode Modify the Web config file to support SQLServer mode Modify the Web config file to support InProc mode In the Session Start procedure in the Global asax file set the EnableSession property of the WebMethod attribute to true In the Session Start procedure in the Global asax file set the Description property of the WebMethod attribute to sessionState Answer A B Explanation A With StateServer mode session state is using an out-of-process Windows NT Server to store state information This mode is best used when performance is important but you can't guarantee which server a user will request an application from With out-of-process mode you get the performance of reading from memory and the reliability of a separate process that manages the state for all servers As this scenario requires that we should optimize performance not reliability StateServer mode is the preferred solution Indicates that session state is stored on the SQL Server In SQL mode session states are stored in a SQL Server database and the worker process talks directly to SQL The ASP NET worker processes are then able to take advantage of this simple storage service by serializing and saving using NET serialization services all objects within a client's Session collection at the end of each Web request Note HTTP is a stateless protocol which means that it does not automatically indicate whether a sequence of requests is all from the same client or even whether a single browser instance is still actively viewing a page or site As a result building Web applications that need to maintain some cross-request state information shopping carts data scrolling and so on can be extremely challenging without additional infrastructure help ASP NET provides the following support for sessions A session-state facility that is easy to use familiar to ASP developers and consistent with other NET Framework APIs A reliable session-state facility that can survive Internet Information Services IIS restarts and workerprocess restarts without losing session data A scalable session-state facility that can be used in both Web farm multicomputer and Web garden multiprocess scenarios and that enables administrators to allocate more processors to a Web application to improve its scalability A session-state facility that works with browsers that do not support HTTP cookies A throughput equivalent to that of ASP or better for core session-state scenarios read write when putting items into shopping carts modifying last page visited validating credit card details and so on Reference NET Framework Developer's Guide Session State Incorrect Answers With InProc mode session state is in process with an ASP NET worker process InProc is the default However since we are using multiple servers we cannot use InProc mode This will not allow session information to be stored over multiple servers The Description property of the WebMethod attribute supplies a description for an XML Web service method that will appear on the Service help page QUESTION You are creating an ASP NET page to enroll new members in a health care program for Certkiller employees One of the requirements for membership is that a participant must be at least years old You need to ensure that each prospective member enters a name in a TextBox control named nameTextBox and a date of birth in a TextBox control named birthdayTextBox In addition you need to verify that prospective members meet the age requirement What should you do A Add a CustomValidator to the page In the Properties window set the ControlToValidate property to birthdayTextBox Write code to validate the date of birth Add a RegularExpressionValidator control to the page In the Properties window set the ControlToValidate property to nameTextBox and create a regular expression to validate the name B Add a CompareValidator control to the page In the Properties window set the ControlToValidate property to birthdayTextBox Write code that sets the Operator and ValueToCompare properties to validate the date of birth Add a RequiredFieldValidator control to the page In the Properties window set the ControlToValidate property to nameTextBox C Add a RangeValidator control to the page In the Properties window set the ControlToValidate property to birthdayTextBox Write code that sets the MinimumValue and MaximumValue properties to validate the date of birth Add a CompareValidator control to the page In the Properties window set the ControlToValidate property to nameTextBox Add a second CompareValidator control to the page In the Properties window set the ControlToValidate property to birthdayTextBox Write code that sets the Operator and ValueToCompare properties of the two CompareValidator controls to validate the name and date of birth D Add a CustomValidator control to the page In the Properties window set the ControlToValidate property to birthdayTextBox and write code to validate the date of birth Add a RequiredFieldValidator control to the page In the Properties window set the ControlToValidate property to nameTextBox Add a second RequiredFieldValidator control to the page In the Properties window set the ControlToValidate property to birthdayTextBox Answer D Explanation To check the data of the birthdayTextBox we can use a CustomValidator control page and add appropriate program code to validate that the birth date is in the correct range We use two RequiredFieldValidators to ensure that both textboxes are non-empty Note The CustomValidator Control evaluates the value of an input control to determine whether it passes customized validation logic The RequiredFieldValidator Control evaluates the value of an input control to ensure that the user enters a value Reference NET Framework General Reference RequiredFieldValidator Control Incorrect Answers The RegularExpressionValidator control evaluates the value of an input control to determine whether it matches a pattern defined by a regular expression It is not useful in this scenario We should use two RequiredFieldValidtor one for each textbox It would be hard to use a RangeValidator for the birthday Textbox It is better to use a CustomerValidator control QUESTION You are creating an ASP NET page for recording contact information for Certkiller Inc The page contains a TextBox control named emailTextBox and a TextBox control named phone TextBox Your application requires users to enter data in both of these text boxes You add two RequiredFieldValidator controls to the page One control is named emailRequired and the other control is named phoneRequired You set the ControlToValidate property of emailRequired to emailTextBox You set the ControlToValidate property of phoneRequired to phoneTextBox In addition you add a ValidationSummary control at the bottom of the page If the user attempts to submit the page after leaving emailTextBox blank you want the word 'Required to appear next to the text box If the user leaves phoneTextBox blank you also want to the Required to appear next to the text box If the user attempts to submit the page after leaving emailTextBox or phoneTextBox blank you also want to display a message at the bottom of the page You want to display a bulleted list showing which required entries are missing If emailTextBox is blank you want the bulleted list to include the following phrase E-mail is a required entry If phoneTextBox is blank you want the bulleted list to include the following phrase Telephone number is a required entry What should you do Set the InitialValue property of each RequiredFieldValidator control to Required Set the ErrorMessage property of emailRequired to E-mail is a required entry Set the ErrorMessage property of phoneRequired to Telephone number is a required entry Set the Display property of each RequiredFieldValidator control to Dynamic Set the ErrorMessage property of emailRequired and phoneRequired to Dynamic Set the Text property of emailRequired to E-mail is a required entry Set the Text property of phoneRequired to Telephone number is a required entry Set the InitialValue property of each RequiredFieldValidator control to Required Set the Text property of emailRequired to E-mail is a required entry Set the Text property of phoneRequired to Telephone number is a required entry Set the Text property of each RequiredFieldValidator control to Required Set the ErrorMessage property of emailRequired to E-mail is a required entry Set the ErrorMessage property of phoneRequired to Telephone number is a required entry Answer D Explanation The Text property of the RequiredFieldValidator is used to specify the text to display in the validation control We want to display Required The ErrorMessage property is used to specify the text to display in the validation control when validation fails Reference Visual Basic and Visual C Concepts Validating Required Entries for ASP NET Server Controls NET Framework Class Library RequiredFieldValidator Members Incorrect Answers We should use the Text property not the InitialValue property to specify the text to display in the validation control The ErrorMessage property should be set to the text to display in the validation control not to dynamic We must use the ErrorMessage property QUESTION You create an ASP NET page that allows a user to enter a requested delivery date in a TextBox control named requestCKDate The date must be no earlier than two business days after the order date and no later that business days after the order date You add a CustomValidator control to your page In the Properties window you set the ControlToValidate property to requestCKDate You need to ensure that the date entered in the requestDate TextBox control falls within the acceptable range of values In addition you need to minimize the number of round trips to the server What should you do A Set the AutoPostBack property of requestDate to False Write code in the ServerValidate event handler to validate the date B Set the AutoPostBack property of requestDate to True Write code in the ServerValidate event handler to validate the date C Set the AutoPostBack property of requestDate to False Set the ClientValidationFunction property to the name of a script function contained in the HTML page that is sent to the browser D Set the AutoPostBack property of requestDate to True Set the ClientValidationFunction property to the name of a script function contained in the HTML page that is sent to the browser Answer C Explanation Set CustomValidator ClientValidationFunction property to the name of the function that performs the client-side validation Because the client validation function runs on the target browser the function must be written using a scripting language supported by the browser such as JScript or VBScript The AutoPostBack property gets or sets a value indicating whether an automatic postback to the server will occur whenever the user changes the content of the text box We should set it to false as we want to avoid server round trips Reference NET Framework Class Library CustomValidator ClientValidationFunction Property C NET Framework Class Library TextBox AutoPostBack Property C Incorrect Answers A B We want to validate the control with client side script to save a server round-trip D If the AutoPastBack is set to true an automatic postback to the server will occur whenever the user changes the text in the text box This is what we want to avoid QUESTION You deploy and ASP NET application When an error occurs the user is redirected to a custom error page that is specified in the Web config file Users report that one particular page is repeatedly generating errors You need to gather detailed error information for the page You need to ensure that users of the application continue to see the custom error page if they request pages that generate errors What should you do A In the Web config file set the mode attribute of the customErrors element to RemoteOnly and access the page from a browser on your client computer In the Web config file set the mode attribute of the customErrors element to RemoteOnly and access the page from a browser on the server Modify the Page directive so that the Trace attribute is set to True and the LocalOnly attributes is set to true and then access the page from a browser on the server Modify the Web config file to include the following element trace enabled true LocalOnly false PageOutput true Access the application from a browser on your client computer Answer B Explanation The RemoteOnly option specifies that custom errors are shown only to remote clients and ASP NET errors are shown to the local host This meets the requirements since you will be able to see the ASP NET errors while the users still will see the custom error page Reference NET Framework General Reference customErrors Element Incorrect Answers A If you use the RemoteOnly option and access the page from a client computer you would only see the custom error page not see the detailed error information The LocalOnly Trace attribute indicates that the trace viewer trace axd is available only on the host Web server This is not relevant in this scenario The LocalOnly attribute only affects the availability of the Trace vxd tool QUESTION You create an ASP NET application for Certkiller You create an exception class named DataCollisionEx The exception class is defined in CKNamespace You want the exception to be thrown from any page in which a user attempts to edit data that has been changed by another user during the edit You want to use centralized error handling You need to write code for the Application Error event handler of your application You want the event handler to direct the user to a page named DataCollision aspx when DataCollisionEx exception is thrown You want the DataCollision aspx page to retrieve error information from the server object and format the message for the user You want other exceptions to direct the user to the default error page that is enabled by the Web config file Which code should you include in the Application Error event handler A Type argExType Exception ex argExType Type GetType CKNamespace DataCollisionEx ex Server GetLastError if ex GetType Equals argExType Response Redirect DataCollision aspx Else Server ClearError Type argExType Exception ex argExType Type GetType CKNamespace DataCollisionEx ex Server GetLastError if ex GetType Equals argExType Response Redirect DataCollision aspx Type argExType Exception ex argExType Type GetType CKNamespace DataCollisionEx ex Server GetLastError InnerException if ex GetType Equals argExType Response Redirect DataCollision aspx D Type argExType Exception ex argExType Type GetType CKNamespace DataCollisionEx ex Server GetLastError InnerException if ex GetType Equals argExType Response Redirect DataCollision aspx Else Server ClearError Answer C Explanation We use the GetLastError method to retrieve the last error We use the InnerException property to catch the earlier exception Note When an exception X is thrown as a direct result of a previous exception Y the InnerException property of X should contain a reference to Y The HttpServerUtility ClearError method clears the previous exception Reference NET Framework Class Library Exception InnerException Property C NET Framework Class Library HttpServerUtility ClearError Method C Incorrect Answers We should retrieve the previous error with the InnerException property Furthermore we should not clear the previous exception We should retrieve the previous error with the InnerException property D We should not clear the previous exception QUESTION You create an ASP NET application that will run on Certkiller 's Internet Web site Your application contains Web pages You want to configure your application so that it will display customized error messages to users when an HTTP code error occurs You want to log the error when an ASP NET exception occurs You want to accomplish these goals with the minimum amount of development effort Which two actions should you take Each correct answer presents part of the solution Choose two Create an Application Error procedure in the Global asax file for your application to handle ASP NET code errors Create an applicationError section in the Web config file for your application to handle ASP NET code errors Create a CustomErrors event in the Global asax file for your application to handle HTTP errors Create a CustomErrors section in the Web config file for your application to handle HTTP errors Add the Page directive to each page in the application to handle ASP NET code errors Add the Page directive to each page in the application to handle HTTP errors Answer A D Explanation A Any public event raised by the HttpApplication class is supported using the syntax Application EventName For example a handler for the Error event can be declared protected void Application Error Object sender EventArgs e D The customErrors element which is used in the Web config file provides information about custom error messages for an ASP NET application Reference NET Framework Developer's Guide Handling Public Events NET Framework General Reference customErrors Element Incorrect Answers There is no such thing as an applicationError section in the Web config file There is no such thing as CustomErros event in the Global asax file E F It is not necessary to add a Page Directive to each page QUESTION You are creating an ASP NET application for Certkiller An earlier version of the application uses ActiveX components that are written in Visual Basic The new ASP NET application will continue to use the ActiveX components You want the marshaling of data between your ASP NET application and the ActiveX components to occur as quickly as possible Which two actions should you take Each correct answer presents part of the solution Choose two Use ODBC binding Use late binding Use early binding Set the AspCompat attribute of the Page directive to true Set the AspCompat attribute of the Page directive to false Answer C D Explanation Early binding is a better choice for performance reasons When using single-threaded STA COM components such as components developed using Visual Basic from an ASP NET page you must include the compatibility attribute aspcompat true in an Page tag on the ASP NET page Reference NET Framework Developer's Guide COM Component Compatibility Incorrect Answers ODBC is set of legacy database drivers OleDB and SQL should be used Furthermore database drivers are irrelevant in this scenario While late binding to components is still supported early binding is a better choice for performance reasons The aspcompat attribute must be set to true QUESTION You are creating an ASP NET application that delivers customized news content over the Internet Users make selections from an ASP NET page Your code creates a DataSet object named CKNewsItems which contains the news items that meet the criteria selected by the user You create a style sheet named NewsStyle xsl that renders the data in CKNewsItems in HTML format You write the following code segment XmlDataDocument doc new XmlDataDocument CKNewsItems XslTransform tran new XslTransform tran Load NewsStyle xsl You want to display the transformed data as HTML text Which line of code should you add to the end of the code segment tran Transform doc null Response OutputStream tran Transform doc null Request InputStream CKNewsItems WriteXml Response OutputStream CKNewsItems WriteXml tran ToString Answer A Explanation The XslTransform Transform method transforms the XML data in the XPathNavigator using the specified args and outputs the result to a Stream We should use the Response OutputStream to enable output of text to the outgoing HTTP response stream Reference NET Framework Class Library XslTransform Transform Method XPathNavigator XsltArgumentList Stream C Incorrect Answers B We want to display data not read data so we must use Response OutputStream not Request InputStream C D We want to generate HTML not XML data We should use the XslTransform Transform method not the DataSet WriteXml method QUESTION You create an ASP NET application to display a sorted list of products in a DataGrid control The product data is stored in a Microsoft SQL Server database named Certkiller DB Each product is identified by a numerical value named ProductID and each product has an alphabetic description named ProductName You write ADO NET code that uses a SqlDataAdapter object and a SqlCommand object to retrieve the product data from the database by calling a stored procedure You set the CommandType property of the SqlCommand object to CommandType StoredProcedure You set the CommandText property of the object to procProductList Your code successfully files a DataTable object with a list of products that is sorted by ProductID in descending order You want to data to be displayed in reverse alphabetic order by ProductName What should you do Change the CommandType property setting of the SqlCommand object to CommandType Text Change the CommandText property setting of the SqlCommand object to the following SELECT FROM procProductList ORDER BY ProductName DESC Bind the DataGrid control to the DataTable object Create a new DataView object based on the DataTable object Set the Sort Property of the DataView object to ProductName DESC Bind the DataGrid control to the DataView object C Set the AllowSorting property of the DataGrid control to True Set the SortExpression property of the DataGridColumn that displays ProductName to ProductName DESC Bind the DataGrid control to the DataTable object D Set the DisplayExpression property of the DataTable object to ORDER BY ProductName DESC Bind the DataGrid control to the DataTable object Answer B Explanation We can create a DataView object set the appropriate Sort Property and bind the DataGrid control to the DataView and not the DataTable object Reference NET Framework Developer's Guide Sorting and Filtering Data Using a DataView C Incorrect Answers A procProductList is a stored procedure It cannot be used in the FROM clause of a SELECT statement The DataGrid AllowSorting property gets or sets a value that indicates whether sorting is enabled The DataGridColumn SortExpression property gets or sets the name of the field or expression to pass to the OnSortCommand method when a column is selected for sorting However the sorting only occurs when a user clicks the column header The DataTable DisplayExpression gets or sets the expression that will return a value used to represent this table in the user interface This is only a display string We cannot use it to sort the DataTable QUESTION You are a Web developer for an online research service Certkiller Research Inc You are creating an ASP NET application that will display research results to users of the Certkiller Web site You use a DataGrid control to display a list of research questions and the number of responses received for each question You want to modify the control so that the total number of responses received is displayed in the footer of the grid You want to perform this task with the minimum amount of development effort What should you do Override the OnPreRender event and display the total when the footer row is created Override the OnItemCreated event and display the total when the footer row is created Override the OnItemDataBound event and display the total when the footer row is bound Override the OnLayout event and display the total in the footer row Answer C Explanation The ItemDataBound event is raised after an item is data bound to the DataGrid control This event provides you with the last opportunity to access the data item before it is displayed on the client After this event is raised the data item is nulled out and no longer available Reference NET Framework Class Library DataGrid ItemDataBound Event C Incorrect Answers The OnPreRender method notifies the server control to perform any necessary prerendering steps prior to saving view state and rendering content The ItemCreated event is raised when an item in the DataGrid control is created both during round-trips and at the time data is bound to the control The OnLayout Method raises the Layout event that repositions controls and updates scroll bars QUESTION You are a Web developer for Certkiller You create an ASP NET application that accesses sales and marketing data The data is stored in a Microsoft SQL Server database on a server named CertK The company purchases a factory automation software application The application is installed on CertK where it creates a second instance of SQL Server named Factory and a database named FactoryDB You connect to FactoryDB by using Windows Integrated authentication You want to add a page to your ASP NET application to display inventory data from FactoryDB You use a SqlConnection object to connect to the database You need to create a connection string to FactoryDB in the instance of SQL Server named Factory on CertK Which string should you use A Server CertK Data Source Factory Initial Catalog FactoryDB Integrated Security SSPI Server CertK Data Source Factory Database FactoryDB Integrated Security SSP Data Source CertK Factory Initial Category Factory Integrated Security SSP Data Source CertK Factory Database FactoryDB Integrated Security SSP Answer D Explanation The Data Source attribute of the connection string contains the name instance or network address of the instance of SQL Server to which to connect In this scenario we are to connect to the Factory Instance on CertK so we use CertK Factory as data source To specify the database we should either use the Database or the Initial Catalog attribute Here we use Database FactoryDB Note The SQL Server NET Data Provider provides connectivity to Microsoft SQL Server version or later using the SqlConnection object The connection string includes the source database name and other parameters needed to establish the initial connection Reference NET Framework Class Library SqlConnection ConnectionString Property C Incorrect Answers A B There is no Server attribute in the connection string Instead we should use the Data Source attribute to specify the server and the instance C There is no Initial Category attribute in the connection string We can use Database or the Initial Catalog attribute to specify the database QUESTION You create an ASP NET page that contains a DataGrid control The control displays data that is retrieved from a database named Certkiller DB You want your users to be able to sort the data in either ascending or descending order You write code to sort the data in the DataGrid control by using the SortOrder property when a user clicks in a column The values stored for the SortOrder property are ASC for ascending order and DESC for descending order You want to preserver the value during postbacks A user selects descending order Which code should you use to save and retrieve the value A Save Application SortOrder DESC Retrieve string val string Application SortOrder B Save Cache SortOrder DESC Retrieve string val string Cache SortOrder C Save ViewState SortOrder DESC Retrieve string SortOrder string ViewState SortOrder D Save Cache SortOrder SortOrder Retrieve string val string Cache DESC Answer C Explanation An ASP NET server control inherits a property named ViewState from Control that enables it to participate easily in state management ViewState is persisted to a string variable by the ASP NET page framework and sent to the client and back as a hidden variable Upon postback the page framework parses the input string from the hidden variable and populates the ViewState property of each control Reference NET Framework Developer's Guide Maintaining State in a Control C Incorrect Answers A The application state is not adequate here since only a single application would apply to all users B D A cache would not be a secure place to save this information Caching is used for performance reasons QUESTION You are creating an ASP NET page for a travel service The page contains a CheckBoxList control that contains travel destinations Customer can select favorite destinations to receive weekly e-mail updates of travel packages The CheckBoxList control is bound to a database table of possible destinations Each destination is ranked according to its popularity You modify the page to sort the destination list by rank from the most popular to the least popular The list has three columns You want the most popular destination to be on the top row of the check box list at run time Which property setting should you use for the CheckBoxList control Set the RepeatDirection property to Vertical Set the RepeatDirection property to Horizontal Set the RepeatLayout property to Flow Set the RepeatLayout property to Table Answer B Explanation The DataList RepeatDirection property is used to get or select whether the DataList control displays vertically or horizontally If this property is set to RepeatDirection Horizontal the items in the list are displayed in rows loaded from left to right then top to bottom until all items are rendered Reference NET Framework Class Library DataList RepeatDirection Property C NET Framework Class Library DataList RepeatLayout Property C Incorrect Answers A If the DataList RepeatDirection property is set to RepeatDirection Vertical the items in the list are displayed in columns loaded from top to bottom then left to right until all items are rendered C D DataList RepeatLayout Property gets or sets whether the control is displayed in a table or flow layout It does not affect the order in which the items are displayed QUESTION You are creating an ASP NET application to track Certkiller sales orders The application uses an ADO NET DataSet object that contains two DataTable objects One table is named Orders and the other table is named OrderDetails The application displays data from the Orders table in a list box You want the order details for an order to be displayed in a grid when a user selects the order in the list box You want to modify these objects to enable your code to find all the order details for the selected order What should you do Add a DataRelation object to the Relations collection of the DataSet object Use the DataSet Merge method to connect the Orders table and the OrderDetails table to each other Add a ForeignKeyConstraint to the OrderDetails table Add a keyref constraint to the DataSet schema Answer A Explanation In order to enable the DataGrid to display from multiple tables we need to relate the tables with DataRelation Reference Visual Basic and Visual C Concepts Introduction to the Windows Forms DataGrid Control Incorrect Answers We don't want to merge the two datasets into a single dataset A foreignKeyConstraint represents an action restriction enforced on a set of columns in a primary key foreign key relationship when a value or row is either deleted or updated However a foreign key constraint does not create a relation between the tables We need to define a relation not a constraint QUESTION You are creating an ASP NET application for Certkiller The company deploys an XML Web service that returns a list of encyclopedia articles that contain requested keywords You want to create a class that calls the XML Web service What should you do Select Add Web Service from the Project menu in Visual Studio NET and browse to the XML Web service Select Add Reference from the Project menu in Visual Studio NET and browse to the XML Web service Select Add Web Reference from the Project menu in Visual Studio NET and browse to the XML Web service Run the Type Library Importer Tlbimp exe and provide it with the URL for the XML Web service Run the Web Services Discover tool Disco exe and provide it with the URL for the XML Web service Answer C Explanation You can add a Web reference to projects that use XML Web services that are published on the Internet or on your local Web servers To add a Web reference to a project In Solution Explorer select a project that supports adding Web references On the Project menu choose Add Web Reference In the Add Web Reference dialog box type the URL for the XML Web service in the Address text box and then choose the Arrow Icon Verify that the items in the Available References box are the items you want to reference in your project and then choose Add Reference In Solution Explorer expand the Web References folder to note the namespace for the Web reference classes that are available to the items in your project Reference Visual Studio Adding and Removing Web References Incorrect Answers A B We should use the Add Web reference command not Add Web Service or Add Reference D The Type Library Importer converts the type definitions found within a COM type library into equivalent definitions in a common language runtime assembly E The Web Services Discovery tool discovers the URLs of XML Web services located on a Web server and saves documents related to each XML Web service on a local disk QUESTION You are creating an ASP NET application for an online payment service The service allows users to pay their bills electronically by using a credit card The application includes a payment page named Payment aspx This page contains a form for entering payee payment amount and credit card information When a user needs to submit a new billing address to a payee the page form allows the user to provide the new address information If the user indicates a change of address the application needs to provide the information to the ProcessAddressChange aspx page for processing as soon as the user submits the payment page information The ProcessAddressChange aspx page processes the request for a change of address but does not provide any display information for the user When the requested processing is complete Payment aspx displays status results to the user You need to add a line of code to Payment aspx to perform the functionality in ProcessAddressChange aspx Which line of code should you use Response Redirect ProcessAddressChange aspx Response WriteFile ProcessAddressChange aspx Server Transfer ProcessAddressChange aspx True Server Execute ProcessAddressChange aspx Answer D Explanation The HttpServerUtility Execute method executes a request to another page using the specified URL path to the page The Execute method continues execution of the original page after execution of the new page is completed Reference NET Framework Class Library HttpServerUtility Execute Method String C Incorrect Answers The HttpResponse Redirect method Redirects a client to a new URL and specifies the new URL The HttpResponse WriteFile method writes the specified file directly to an HTTP content output stream The HttpServerUtility Transfer method Terminates execution of the current page and begins execution of a new page using the specified URL path to the page QUESTION You are creating an ASP NET application for Certkiller Your application will call an XML Web service run by Wide World Importers The XML Web service will return an ADO NET DataSet object containing a list of companies that purchase wine You need to make the XML Web service available to your application What should you do On the NET tab of the Reference dialog box select System Web Services dll In the Web References dialog box type the address of the XML Web service Add a using statement to your Global asax cs file and specify the address of the XML Web service Write an event handler in the Global asax cs file to import the wsdl and disco files associated with the XML Web service Answer B Explanation Web references differ from traditional references and components in that they refer to XML Web services published on either a local intranet or the Internet Procedure to add a Web reference to a project In Solution Explorer select a project that supports adding Web references On the Project menu choose Add Web Reference In the Add Web Reference dialog box type the URL for the XML Web service in the Address text box Verify that the items in the Available References box are the items you want to reference in your project and then choose Add Reference In Solution Explorer expand the Web References folder to note the namespace for the Web reference classes that are available to the items in your project Reference Visual Studio Adding and Removing Web References QUESTION You are a Web developer for Certkiller Publishing You are performing a migration of your company's ASP-based Web page named Booklist asp to ASP NET You want to deploy the ASP NET version of your Web page with the minimum amount of development effort You also want the migration to be accomplished as quickly as possible The page contains a COM component named Certkiller BookList The component is written in Microsoft Visual Basic When you open the new page you receive the following error message Server error - The component ' Certkiller BookList' cannot be created You need to ensure that you can open the Web page successfully What should you do Write a manage component to perform the tasks that the Lucerne BookList component currently performs Set the AspCompat attribute of the Page directive to true Add the following line of code to the Page Load event handler RegisterRequiresPostBack Certkiller BookList D Add the following attribute to the processModel element of the Web config file comImpersonationLevel Delegate Answer B Explanation If the older file contains calls to COM components - for example ADO code then we must add the AspCompat attribute to the page directive in HTML view The aspcompat attribute forces the page to execute in single-threaded STA mode Note You can work with and run existing ASP pages asp files as-is in Visual Studio You can use ASP pages and ASP NET pages in the same project It is useful to convert ASP pages to ASP NET Web Forms pages so that you can take advantage of the enhanced features of the newer architecture Reference Visual Basic and Visual C Concepts Migrating ASP Pages to Web Forms Pages QUESTION You are creating an ASP NET application for Certkiller Customers will use this application to manage their own insurance policies For example a customer can use the application to renew policies An existing COM component named CertK PolicyLibrary dll contains the logic for calculating the renewal premium CertK PolicyLibrary dll is written in Visual Basic The class that performs the calculations is named cPolicyActions The CalculateRenewal function of cPolicyActions accepts a policy identification number and returns a premium as a Double You need to use CertK PolicyLibrary dll in your ASP NET application You also need to enable the application to use the cPolicyActions class What should you do A Run the following command in a command window TLBIMP EXE CertK PolicyLibrary DLL out CertK PolicyLibrary NET DLL Copy the original CertK PolicyLibrary dll to the bin directory of your ASP NET application B Run the following command in a command window TLBEXP EXE CertK PolicyLibrary DLL out CertK PolicyLibrary NET DLL Copy the original CertK PolicyLibrary dll to the bin directory of your ASP NET application Select Add Existing Item from the Project menu in Visual Studio NET and browse to CertK PolicyLibrary dll Select Add Reference from the Project menu in Visual Studio NET select the COM tab and browse to CertK PolicyLibrary dll Answer D Explanation To add a reference to a COM object from a NET application Open a new or existing Microsoft Visual C NET project in Visual Studio NET Click the Project menu and select Add Reference In the Add Reference window click the COM tab Scroll down the list of components and select the one you want to reference such as Microsoft CDO For Exchange Library Click Select After the component name appears in the Selected Components window click OK Note The COM component must have been previously registered on the server for this to succeed Reference Using COM Interoperability in Visual Basic NET Incorrect Answers TBLIMP is required if Visual Studio NET macros must reference COM components TLBIMP wraps the component enabling Visual Studio NET macros to reference it However TLBIMP is not required if we are going to reference a COM object from a Visual Studio NET application Tlbexp exe generates a type library that contains definitions of the types defined in the assembly Applications such as Visual Basic can use the generated type library to bind to the NET types defined in the assembly However the requirements of this scenario are the opposite we want to reference a COM object from a Visual Studio NET application We must specify that we are referencing a COM object QUESTION As a software developer at Certkiller you are creating an ASP NET application that will display facts about the solar system This application will support localization for users from France Germany Japan and the United States To see information about a particular planet the user will select the planet from a drop-down list box on SolarSystem aspx You want to display the planet names in the drop-down list box in the language appropriate to the individual who is using the application What should you do A Create a database table named Planets Create three column named PlanetID LocaleID and Description Use SqlCommand ExecuteReader to query the table for the locale specified in the request Using the locale specified in the request translate the values by using the TextInfo OEMCodePage property Populate the drop-down list box with the translated text B Create a DataTable object named Planets Populate the Planets DataTable object by using string constants Using the locale specified in the request translate the values by using a UnicodeEncoding object Bind the DataSource property of the drop-down list box to the DataTable object C Create a database table named Planets Create two columns named PlanetID and Description Use a SqlDataAdapter to load the planet information into a DataSet object Using the locale specified in the request use the String format provider to translate the values Bind the DataSource property of the drop -down list box to the DataSet DefaultView object D Create string resources assemblies for each locale Using the locale specified in the request use a ResourceManager to load the appropriate assembly Populate an array with the string values from the assembly Bind the DataSource property of the drop-down list box to the array Answer D Explanation The ResourceManager class provides convenient access to culture-correct resources at run time Reference NET Framework Tutorials ResourceManager QUESTION You are creating an ASP NET page that enables users to select a country and view information on tourist attractions in that country Users select a country from a list box named countryList The list box displays country names The list box also contains hidden country codes Your code retrieves a cached DataTable object that contains tourist attraction descriptions and a numeric country code named CountryID The DataTable object is named attractionsTable You want to extract an array of DataRow objects from the DataTable object You want to include tourist attractions for only the selected country Which code segment should you use DataRow result attractionsTable Select CountryID countryList SelectedItem Text DataRow result attractionsTable Select CountryID countryList SelectedItem Value DataRow result attractionsTable Rows Find CountryID countryList SelectedItem Value D DataRow result attractionsTable Rows Find countryList SelectedItem Value Answer B Explanation The DataTable Select method gets an array of all DataRow objects that match the filter criteria in order of primary key or lacking one order of addition The filter will compare CountryID values We should use Country codes and not country names We should therefore use the Value of the selected item not the Text Reference NET Framework Class Library DataTable Select Method String C NET Framework Class Library ListControl SelectedItem Property C Incorrect Answers A The ListBox TextBox property gets or searches for the text of the currently selected item in the ListBox However this would retrieve names of countries but the filter use comparison to a CountryID column We must use the country code not the country name C D The DataRowCollection Find method is not appropriate in this scenario It retrieves only a single row not an array of rows QUESTION You create an ASP NET application to provide corporate news and information to Certkiller 's employees The application is used by employees in New Zealand Default aspx has a Web Form label control named currentDateLabel The Page Load event handler for Default aspx included the following line of code currentDateLabel Text DateTime Now ToString D You need to ensure that the data is displayed correctly for employees in New Zealand What should you do In the Web config file for the application set the culture attribute of the globalization element to en-NZ In the Web config file for the application set the uiCulture attribute of the globalization element to en-NZ In Visual Studio NET set the responseEncoding attribute in the page directive for Default aspx to UTF- In Visual Studio NET save the Default aspx page for both versions of the application by selecting Advanced Save Options from the File menu and selecting UTF- Answer A Explanation The culture attribute of the globalization element specifies the default culture for processing incoming Web requests Reference NET Framework General Reference globalization Element Incorrect Answers B The uiculture attribute of the globalization specifies the default culture for processing locale-dependent resource searches It does not apply in this scenario C D The UTF Encoding Class encodes Unicode characters using UCS Transformation Format -bit form UTF- This encoding supports all Unicode character values and surrogates However it does not help in displaying data in New Zealand format QUESTION You are a Web developer for Certkiller You are creating an online inventory Web site to be used by employees in Germany and the United States When a user selects a specific item from the inventory the site needs to display the cost of the item in both United States currency and German currency The cost must be displayed appropriately for each locale You want to create a function to perform this task Which code should you use private string CKGetDisplayValue double value string inputRegion string display RegionInfo region region new RegionInfo inputRegion display value ToString C display region CurrencySymbol return display private string CKGetDisplayValue double value string inputCulture string display NumberFormatInfo LocalFormat NumberFormatInfo NumberFormatInfo CurrentInfo Clone display value ToString C LocalFormat return display private string CKGetDisplayValue double value string inputRegion string display RegionInfo region region new RegionInfo inputRegion display value ToString C display region ISOCurrencySymbol return display private string CKGetDisplayValue double value string inputCulture string display CultureInfo culture culture new CultureInfo inputCulture display value ToString C culture return display Answer D Explanation We create a new CultureInfo object based on the inputCulture parameter We then produce the result with C constant representing the current culture and the new CultureInfo object display value ToString C culture Note The CultureInfo Class contains culture-specific information such as the language country region calendar and cultural conventions associated with a specific culture This class also provides the information required for performing culture-specific operations such as casing formatting dates and numbers and comparing strings Reference NET Framework Developer's Guide Formatting Numeric Data for a Specific Culture C Incorrect Answers B The NumberFormatInfo class defines how currency decimal separators and other numeric symbols are formatted and displayed based on culture However we should create a CultureInfo object not a NumberFormatInfo object A C We should use the CultureInfo class not the RegionInfo class Note In contrast to CultureInfo RegionInfo does not represent preferences of the user and does not depend on the user's language or culture QUESTION You are creating a DataGrid control named CKGrid for a travel service Each row in myGrid contains a travel reservation and an Edit command button In each row the fields that contain travel reservation information are read-only labels You want all the fields to change to text boxes when a user clicks the Edit command button in the row You are writing the following event handler for the EditCommand event Line numbers are included for reference only private void CKGrid EditCommand object s DataGridCommandEventArgs e Which code should you add at line of the event handler CKGrid EditItemIndex e Item ItemIndex CKGrid DataKeyField e Item AccessKey CKGrid SelectedIndex e Item ItemIndex CKGrid CurrentPageIndex e Item ItemIndex Answer A Explanation The EditItemIndex property is used to programmatically control which item is being edited Setting this property to an index of an item in the DataGrid control will enable editing controls for that item in the EditCommandColumn Reference NET Framework Class Library DataGrid EditItemIndex Property C Incorrect Answers The DataKeyfield is used to get or set the key field in the data source specified by the DataSource property The SelectedIndex property is used to determine the index of the item selected by the user in the DataGrid control The CurrentPageIndex property is used to determine the currently displayed page in the DataGrid control when paging is enabled This property is also used to programmatically control which page is displayed QUESTION You create an ASP NET application for an online insurance site Certkiller Insurance A page named VehicleInformation aspx has the following Page directive Page Language c CodeBehind VehicleInformation aspx cs AutoEventWireup false inherits InsApp VehicleInfo VehicleInformation aspx had a TextBox control named vehicleIDNumber in which the user can enter a vehicle identification number VIN The HTML code for this control is as follows asp TextBox ID vehicleIDNumber Columns Runat server You need to implement a TextChanged event handler for vehicleIDNumber You want this event handler to retrieve information about a vehicle by using an XML Web service that charges for each access The page will then be redisplayed with additional information about the vehicle obtained from the XML Web service You are implementing the TextChanged event handler Which two courses of action should you take Each correct answer presents part of the solution Choose two In the Page directive for VehicleInformation aspx ensure that the AutoEventWireup attributes is set to true In the Page directive for VehicleInformation aspx ensure that the EnableViewState attribute is set to true In the vehicleIDNumber HTML element ensure that the AutoPostback attribute is set to false Include code for the client-side onserverchange event to submit the Web Form for processing by the server In the vehicleIDNumber HTML element ensure that the AutoPostback attribute is set to true Include code in the TextChanged event handler to query the XML Web service Answer B D Explanation The Page EnableViewState property value indicates whether the page maintains its view state and the view state of any server controls it contains when the current page request ends The AutoPostBack property is used to specify whether an automatic postback to the server will occur whenever the user changes the content of the text box As we want we want to use an XML Web service we must set the attribute to true Reference NET Framework Class Library Control EnableViewState Property C NET Framework Class Library TextBox AutoPostBack Property C Incorrect Answers AutoEventWireup is used to automatically associate page events and methods It does not provide a solution for this scenario We are required to use a XML Web service The AutoPostback attribute must be set to false QUESTION You are creating a Web Form for Certkiller 's human resources department You create a Web user control named Employee that allows the user to edit employee information Each instance of the control on your Web Form will contains information about a different employee You place the Employee control on the Web Form and name the control CK You also add the Employee control to the ItemTemplate of a Repeater control named repeaterEmployees Each Employee control in repeaterEmployees contains several TextBox controls You want your Web Form to handle TextChanged events that are raised by these TextBox controls Which event handler should you use private void CK TextChanged object source EventArgs e private void repeaterEmployees ItemDataBound object source RepeaterItemEventArgs e private void repeaterEmployees DataBinding object source RepeaterItemEventArgs e D private void repeaterEmployees ItemCommand object source RepeaterCommandEventArgs e Answer B Explanation The ItemDataBound event occurs after an item in the Repeater is data-bound but before it is rendered on the page Note The Repeater Web server control is a basic container control that allows you to create custom lists out of any data available to the page Reference Visual Basic and Visual C Concepts Introduction to the Repeater Web Server Control NET Framework Class Library Repeater Events Incorrect Answers A The Repeater class does not have any TextChanged event The DataBinding event occurs when the server control binds to a data source The Repeater ItemCommand event is raised in response to button clicks in individual items in a Repeater control QUESTION You create an ASP NET application for online sales site for the Certkiller Corporation A page named OrderCKVerify aspx displays a detailed listing of the items ordered their quantity and their unit price OrderCKVerify aspx then displays the final order total at the end of the page The Web Form within OrderCKVerify aspx includes a Web server control button for order submission The control includes the following HTML element generate by Visual Studio NET asp button id submitOrderButton runat server Text Submit Order asp button The primary event handler for submitOrderButton is named submitOrderButton Click and runs on the server A client-side function named verifyBeforeSubmit displays a dialog box that asks the user to verify the intent to submit the order You need to ensure that verifyBeforeSubmit runs before submitOrderButton Click What should you do Modify the HTML element as follows asp button id submitOrderButton runat server Text Submit Order onClick verifyBeforeSubmit asp button Modify the HTML elements as follows asp button id submitOrderButton runat server Text Submit Order ServerClick verifyBeforeSubmit asp button Add the following code to the Page Load event handler for OrderCKVerify aspx submitOrderButton Attribute Add onclick verifyBeforeSubmit Add the following code to the Page Load event handler for OrderCKVerify aspx submitOrderButton Attribute Add ServerClick verifyBeforeSubmit Answer C Explanation The proposed solution demonstrates how to specify and code an event handler for the Click event in order to display a simple message on the Web page Reference NET Framework Class Library Button OnClick Method C Incorrect Answers The OnClick property of the button control is for server side procedures not client side ones not A QUESTION You create an ASP NET page for Certkiller 's sales department Employees in the sales department will use the page to review and modify customer purchase orders that are associated with sales invoices The page contains a DataGrid control named OrderHeader that displays the customer company name the purchase order PO number and the related sales invoice order number You define OrderHeader by using the following HTML element asp DataGrid id OrderHeader runat server AutoGenerateColumns False DataKeyField OrderID In addition you define the following HTML element for the EditItemTemplate for the PONumber field EditItemTemplate asp TextBox ID PONumber width Text ' Container DataItem PONumber ' Runat server EditItemTemplate You define the UpdateCommand event handler for OrderHeader as follows private void OrderHeader UpdateCommand object source System Web UI WebControls DataGridCommandEventArgs e In the UpdateCommand event handler you define a variable named PurchaseOrder This variable is a string You need to set this variable equal to the new value of the item being updates Which statement should you include in the UpdateCommand event handler purchaseOrder e Item Cells Text purchaseOrder TextBox e Item Cells Controls PONumber Text purchaseOrder TextBox e Item Cells Controls Text purchaseOrder PONumber Text Answer C Explanation The proposed solution works but a more practical answer that works also would be TextBox e Item Cells FindControl PONumber Text QUESTION You are creating an ASP NET application for Certkiller 's intranet Employees will use this application to schedule conference rooms for meetings The scheduling page includes a Calendar control that employees can use to choose a date to reserve a room The Calendar control is defined as follows asp calendar id WorkDays runat server OnDayRender WorkDays DayRender You want to display a message that reads Staff Meeting below every Friday displayed in the calendar You also want to find all the weekdays for the current month displayed in the calendar and show them with a yellow highlight You are writing code for the WorkDays DayRender event handler to perform these tasks You write the following code Line numbers are included for reference only private void WorkDays Render object source DayRenderEventArgs e Which code should you add at line of the event handler if e Day Date DayOfWeek DayOfWeek Friday e Cell Controls Add new LiteralControl Staff Meeting if e Day IsWeekend e Cell BackColor System Drawing Color Yellow if e Day Date Day e DayIsOtherMonth e Cell Controls Add new LiteralControl Staff Meeting e Cell BackColor System Drawing Color Yellow if e Day Date Day e Cell Controls Add new LiteralControl Staff Meeting if e Day IsWeekend e Day IsOtherMonth e Cell BackColor System Drawing Color Yellow D if e Day Date DayOfWeek DayOfWeek Friday e Cell Controls Add new LiteralControl Staff Meeting if e Day IsWeekend e Day IsOtherMonth e Cell BackColor System Drawing Color Yellow Answer D Explanation The statement e Day Date DayOfWeek DayOfWeek Friday checks if the Date is a Friday If this is the case we add the appropriate text We then use another if-statement to check that the date is not a weekend and that the date is not a weekend If both the conditions are true we change the background color to yellow Note The CalendarDay IsOtherMonth property gets a value that indicates whether the date represented by an instance of this class is in a month other than the month displayed in the Calendar control Reference NET Framework Class Library CalendarDay IsOtherMonth Property C Incorrect Answers We should check if the date is in the month that is displayed by the calendar We need two separate if-statements to specify both conditions The e Day Date Day comparison checks if the day is the th day in the month This is not appropriate for this scenario QUESTION You are creating an ASP NET application called CertK App that will be used by companies to quickly create information portals customized to their business CertK App stored commonly used text strings in application variables for use by the page in your application You need your application to initialize these text strings only when the first user accesses the application What should you do Add code to the Application OnStart event handler in the Global asax file to set the values of the text strings Add code to the Application BeginRequest event handler in the Global asax file to set the values of the text strings Add code to the Session OnStart event handler in the Global asax file to set the values of the text strings Include code in the Page Load event handler for the default application page that sets the values if the text strings when the IsPostback property of the Page object is False Include code in the Page Load event handler for the default application page that sets the values of the text strings when the IsNewSession property of the Session object is set to True Answer A Explanation The OnStart event only occurs when the first user starts the application Reference NET Framework Class Library ServiceBase Class C Incorrect Answers B The HttpApplication BeginRequest event occurs as the first event in the HTTP pipeline chain of execution when ASP NET responds to a request C This would set the values every time a new session is started D E We should use the OnStart event handler of the application not the Page Load event handler QUESTION You create an ASP NET application to keep track of Certkiller 's employees Employees will use the application to indicate whether they are currently in the office or out of the office The main page of the application is named ShowBoard aspx This page contains a Repeater control named CertK iEmployeeStatus that is bound to the results of a stored procedure if the back-end database The stored procedure provides all employee identification numbers IDs all employee names and each employee's current status of either In of the employee is in the office or Out if the employee is out of the office The HTML code for CertK iEmployeeStatus is as follows asp repeater id CertK iEmployeeStatus runat server ItemTemplate Container DataItem EmployeeName Container DataItem Status br ItemTemplate asp repeater The code-behind file for ShowBoard aspx contains a private procedure named ChangeInStatus that toggles the status for an employee by using the employee's ID You need to add a button for each employee listed by CertK iEmployeeStatus When an employee clicks the button you want the button to call ChangeInOutStatus and pass the employee ID to toggles the status of the employee What are two possible ways to achieve this goal Each correct answer presents a complete solution Choose two Add the following HTML code to the ItemTemplate element of CertK iEmployeeStatus input type button id changeStatusButton alt Container DataItem EmployeeID OnClick changeStatusButton Runat server Value Change Status Add the following subroutine to the code-behind file for ShowBoard aspx public void changeStatusButton System Object sender System EventArgs e ChangeInOutStatus int sender Attributes alt Add the following HTML code to the Item Template element of CertK iEmployeeStatus input type button id changeStatusButton alt Container DataItem EmployeeID OnServerClick changeStatusButton Runat server Value Change Status Add the following subroutine to the code-behind file for ShowBoard aspx Public void changeStatusButton System Object sender System EventArgs e ChangeInOutStatus int sender Attributes alt Add the following HTML code to the ItemTemplate element of CertK iEmployeeStatus asp Button id changeStatusButton Runat Server Text Change Status CommandArgument Container DataItem EmployeeID Add the following code to the ItemCommand event of CertK iEmployeeStatus if source id changeStatusButton ChangeInOutStatus int e CommandSource CommandArgument Add the following HTML code to the ItemTemplate element of CertK iEmployeeStatus asp Button id changeStatusButton Runat server Text Change Status CommandArgument Container DataItem EmployeeID Add the following code to the ItemCommand event of CertK iEmployeeStatus if e CommandSource id changeStatusButton ChangeInOutStatus int e CommandArgument Answer B D Explanation B The ServerClick event is raised when the HtmlButton control is clicked This event causes a roundtrip to occur from the client to the server and back It is deliberately different from the client-side OnClick event In the event that a conflict exists between code run with a ServerClick event and code run by a client-side OnClick event the server-side event instructions will override the client-side code D The CommandSource property is used to determine the source of the command Reference NET Framework Class Library HtmlButton OnServerClick Method C QUESTION You create a Web custom control named CKToggle that users can turn on and off The CKToggle control includes a Button control named toggleButton You write an event handler named toggleButton Click for the toggleButton Click event This event adjusts the BorderStyle property to signify whether the Button is toggled on or off You want to add code to the CKToggle class so that when toggleButton is clicked pages that contain instances of CKToggle can process custom event handling code You add the following code to the CKToggle class public event EventHandler ChangedValue protected void OnChangedValue EventArgs e ChangedValue this e You need to add code to the toggleButton Click so that pages that contain instances of CKToggle can handle the ChangedValue event and process custom event handling code Which lines of code are two possible ways to achieve this goal Each correct answer presents a complete solution Choose two ChangedValue this EventArgs Empty s Click new System EventHandler this OnChangedValue OnChangedValue EventArgs Empty OnChangedValue this EventArgs Empty Answer B C Explanation To wire your event handler to the instance you must create an instance of EventHandler that takes a reference to OnChangedValue in its argument and add this delegate instance to the Click event We can invoke the OnChangedValue event We must use only the EventArgs parameter Note To consume an event in an application you must provide an event handler an event- handling method that executes program logic in response to the event and register the event handler with the event source This process is referred to as event wiring Reference C Programmer's Reference Events Tutorial NET Framework Developer's Guide Consuming Events C Incorrect Answers A We must use the OnChangedValue event D We should specify only the EventArgs parameter QUESTION You company Certkiller Inc hosts an ASP NET application that provides customer demographic information Some of the demographics data is presented by using images The target audience for the application includes a significant number of users who have low vision These individuals use various browsers that vocalize the textual content of Web pages These users need to receive the content of the images in vocalized form You need to modify the application to make it accessible for your target audience You need to accomplish this task with the minimum amount of development effort How should you modify the application Modify all ASP NET pages in the application so that the view state is enabled Modify all ASP NET pages in the application to add custom logic that conveys the demographic information in either textual or graphical format Modify all images in the application so that the ToolTip property conveys the same demographic information as the image Modify all images in the application so that the AlternateText property conveys the same demographic information as the image Answer D Explanation The AlternateText property is used by accessibility utilities such as the Windows XP narrator in order to present graphics as speech QUESTION Your ASP NET application uses the Microsoft NET Framework security classes to implement role-based security You need to authorize a user based on membership in two different roles You create a function named ValidateCKRole that has three arguments The argument named User is the user name the argument named Role is the first role to verify and the argument named Role is the second role to verify You want ValidateCKRole to return a value of true if the specified user has membership in either of the specified roles You write the following code PrincipalPermission principalPerm new PrincipalPermission User Role PrincipalPermission principalPerm new PrincipalPermission User Role Which code segment should you use to complete the function return principalPerm IsUnrestricted principalPerm IsUnrestricted return principalPerm IsSubsetOf principalPerm return principalPerm Intersect principalPerm Demand return principalPerm Union principalPerm Demand Answer D Explanation The SecurityPermission Union method creates a permission that is the union of the current permission and the specified permission This ensures that ValidateRole returns a value of true if either permissions is true Reference NET Framework Class Library SecurityPermission Union Method C Incorrect Answers The SecurityPermission IsUnrestricted method returns a value indicating whether the current permission is unrestricted The SecurityPermission IsSubsetOf method determines whether the current permission is a subset of the specified permission Intersect would require that both conditions were true in order to return true QUESTION You are creating an ASP NET page for Certkiller 's Web site Customers will use the ASP NET page to enter payment information You add a DropDownList control named cardTypeList that enables customers to select a type of credit card You need to ensure that customers select a credit card type You want a default value of Select to be displayed in the cardTypeList control You want the page validation to fail if a customer does not select a credit card type from the list What should you do Add a RequiredFieldValidator control and set its ControlToValidate property to cardTypeList Set the InitialValue property of the RequiredFieldValidator control to Select Add a RequiredFieldValidator control and set its ControlToValidate property to cardTypeList Set the DataTextField property of the cardTypeList control to Select Add a CustomValidator control and set its ControlToValidate property to cardTypeList Set the DataTextField property of the cardTypeList control to Select D Add a RegularExpressionValidator control and set its ControlToValidate property to cardTypeList Set the ValidateExpression property of the RegularExpressionValidator control to Select Answer A Explanation We use a RequiredFieldValidator control to ensure that users enter a cardTypeList We use the InitialValue property of the RequiredFieldValidator control to specify the default or initial value of the cardTypeList control Note The RequiredFieldValidator Control evaluates the value of an input control to ensure that the user enters a value RequiredFieldValidator InitialValue property gets or sets the initial value of the associated input control QUESTION You create an ASP NET application for Certkiller Motors The application allows users to purchase automobile insurance policies online A page named InsuredAuto aspx is used to gather information about the vehicle being insured InsuredAuto aspx contains a TextBox control named vehicleIDNumber The user enters the vehicle identification number VIN of the vehicle into vehicleIDNumber and then clicks a button to submit the page The Button control is named submitButton Upon submission of the page additional vehicle information is obtained for the VIN and the page is redisplayed for showing the vehicle information You define vehicleIDNumber by using the following HTML tag asp TextBox id vehicleIDNumber runat server EnableViewState True Valid VINs are composed of numbers and uppercase letters You need to include code that converts any lowercase letters to uppercase letters so that the properly formatted VIN is displayed after the page is submitted and redisplayed What are two possible ways to achieve this goal Each correct answer presents a complete solution Choose two Add the following code to the vehicleIDNumber TextChanged event handler for InsuredAuto aspx vehicleIDNumber Text vehicleIDNumber Text ToUpper Add the following code to the submitButton Click event handler for InsuredAuto aspx vehcicleIDNumber Text vehicleIDNumber Text ToUpper Add the following code to the Page Init event handler for InsuredAuto aspx vehicleIDNumber Text vehicleIDNumber Text ToUpper D Add the following code to the Page Render event handler for InsuredAuto aspx vehicleIDNumber Text vehicleIDNumber Text ToUpper Answer A B Explanation The TextBox TextChanged event occurs when the content of the text box is changed upon server postback When the user hits the submit button additional information is obtained for the VIN We must therefore convert the text to upper case Reference NET Framework Class Library Page Members Incorrect Answers The Page Init event only occurs when the server control is initialized which is the first step in its lifecycle This occurs only when the page is loaded The Page class does have a rerender event but it does not have a render event QUESTION You create an ASP NET application for Certkiller 's purchasing department A page in the application displays a list of products based on the supplier the product category or the price The URL of the page includes this information as parameters You want to store multiple versions of your ASP NET page in the cache based in the parameter values You want each version of the page to be cached for seconds You need to add code to the page to accomplish this goal Which code segment should you use Response Cache SetExpires DateTime Now AddSeconds Response Cache VaryByParams true Response Cache SetExpires DateTime Now AddSeconds Response Cache VaryByParams All true Response Cache SetCacheability HttpCacheability Public Response Cache SetLastModified DateTime Parse Response Cache VaryByParams All true Response Cache SetCacheability HttpCacheability Public Response Cache SetExpires DateTime Now AddSeconds Response Cache VaryByParams true Answer D Explanation Cachability corresponds to the Location attribute The Public value corresponds to any location We use the SetExpires to set the cache duration Finally we use the string to specify that all parameter values are cached Reference NET Framework Developer's Guide Caching Versions of a Page Based on Parameters C NET Framework Developer's Guide Setting Expirations for Page Caching C Incorrect Answers A B Cachability has to be set C We should use not all when specify VaryByParams QUESTION You create an ASP NET application to display sales analysis information for Certkiller A page named CKSalesSummary aspx displays three separate sections of information For each section you write code that calls a stored procedure in a database The code for each section calls a different stored procedure After the stored procedure runs the results are immediately written in HTML format to the Response object for the application You do not want users to wait until the results are returned from all three stored procedures before they begin to receive content rendered in their browser What are two possible ways to achieve this goal Each correct answer presents a complete solution Choose two Set the SuppressContent property of the Response object to False Set the BufferOutput property of the Response object to False Set the CacheControl property of the Response object to Public Insert the following statement after each section is written to the Response object for the application Response Clear Insert the following statement after each section is written to the Response object for the application Response ClearContent Insert the following statement after each section is written to the Response object for the application Response Flush Answer B F Explanation The HttpResponse BufferOutput property gets or sets a value indicating whether to buffer output and send it after the entire page is finished processing The flush method forces all currently buffered output to be sent to the client Reference NET Framework Class Library HttpResponse BufferOutput Property C NET Framework Class Library HttpResponse Flush Method C Incorrect Answers The HttpResponse SuppressContent property gets or sets a value indicating whether to send HTTP content to the client Caching would not meet the requirements of this scenario D E The HttpResponse Clear and HttpResponse ClearContent methods just clear all content output from the buffer stream QUESTION You create an ASP NET application named CKApp You create an assembly named CKApp dll in a directory named CKDir The assembly includes a default resource file named strings resources that adequately supports English-speaking users of the application You create an additional resource file named strings ja resources to enable support for Japanese-speaking users The resource file is located in the CKDir ja subdirectory You want to create a satellite assembly for CKApp dll that will use the new resource file What should you do Run the Assembly Linker Al exe to embed strings ja resources in the output assembly Place the output assembly in CKDir Run the Assembly Linker Al exe to embed strings ja resources in the output assembly Place the output assembly in CKDir ja Run the Assembly Linker Al exe to link strings ja resources to the output assembly Place the output assembly in CKDir Run the Assembly Linker Al exe to link strings ja resources to the output assembly Place the output assembly in CKDir ja Answer B Explanation Assemblies contain resources We embed the strings ja resources in the assembly After you have compiled your satellite assemblies they all have the same name The runtime differentiates between them based upon the culture specified at compile time with Al exe's culture option and by each assembly's directory location Reference NET Framework Developer's Guide Creating Satellite Assemblies Incorrect Answers A We must put the Japanese assembly into a separate folder C D We must embed the resource file within the assembly not link it QUESTION You are creating an ASP NET application that will be published in several languages You develop a satellite assembly that will include the localized resources for one of the other languages The satellite assembly will also contain code that accesses Enterprise Services Certkiller has a build team that is responsible for compiling and publishing all software applications created by your group The build team is also responsible for digitally signing the software with a public private key pair The build team permits you to have access to Certkiller 's public key but not the private key In order to test your localized satellite assembly you need to digitally sign the assembly What are two possible ways to achieve this goal Each correct answer presents a complete solution Choose two Create a test certificate for your satellite assembly by using the Software Publisher Certificate Test tool Cert spc exe Compile the satellite assembly by using the Resource File Generator Resgen exe with the compile switch Compile the satellite assembly by using the Assembly Linker Al exe with the delay switch Use the Global Assembly Cache tool Gacutil exe to install the assembly in the global assembly cache Generate a new public private key pair by using the Strong Name tool Sn exe Use the new key pair to sign the assembly temporarily for testing purposes Answer C E Explanation The delay switch specifies whether the assembly will be fully or partially signed When an assembly is delay signed Al exe does not compute and store the signature but just reserves space in the file so the signature can be added later The Strong Name tool helps sign assemblies with strong names Sn exe provides options for key management signature generation and signature verification The -R and -Rc options are useful with assemblies that have been delay signed In this scenario only the public key has been set at compile time and signing is performed later when the private key is known Reference NET Framework Tools Strong Name Tool Sn exe NET Framework Tools Assembly Linker Al exe NET Framework Tools Software Publisher Certificate Test Tool Cert spc exe Incorrect Answers The Software Publisher Certificate Test tool creates a Software Publisher's Certificate SPC from one or more X certificates Cert spc exe is for test purposes only However there is no need of a SPC since we already have access to the company's public key Resgen is not useful for signing assemblies Note The Resource File Generator converts txt files and resx XML-based resource format files to common language runtime binary resources files that can be embedded in a runtime binary executable or compiled into satellite assemblies The Global Assembly Cache tool allows you to view and manipulate the contents of the global assembly cache and download cache However it cannot be used to digitally sign an assembly QUESTION You create English French and German versions of a test engine ASP NET application you are developing for Certkiller Inc You have separate resource files for each language version You need to deploy the appropriate resource file based on the language settings of the server What should you do Create an installer and set the Installer Context property for each version of your application Create an installer that has a launch condition to verify the locale settings Create an installer that has a custom action to install only location-specific files Create an installer that has an MsiConfigureProduct function to install the appropriate version Answer C Explanation Custom actions are a Windows Installer feature that allows you to run code at the end of an installation to perform actions that cannot be handled during installation This is an appropriate solution for this scenario as we only want to deploy the resource files on the server Note Resources can be composed of a wide range of elements including interface elements that provide information to the user for example a bitmap icon or cursor custom resources that contain data an application needs version resources that are used by setup APIs and menu and dialog box resources Reference Visual Studio Working with Resource Files Visual Studio Custom Actions Incorrect Answers We just want to deploy the resource files We do not need to set the Context property in the application We don't need any launch conditions We just want to deploy the resource files D We just want to deploy the resource files QUESTION You create an ASP NET application named CKProject You write code to specify the namespace structure of CKProject by including all class declarations within a namespace named CKNamespace You want to compile CKProject so that the fully qualifies namespace of each class is CKNamespace You want to prevent the fully qualifies namespace of each class from being CKProject CKNamespace You need to make changes in the Common Properties folder of the Property Pages dialog box for CKProject What should you do Change the value of the AssemblyName property to CKNamespace Clear the value of the AssemblyName property and leave it blank Change the value of the RootNamespace property to CKNamespace Clear the value of the RootNamespace property and leave it blank Answer D Explanation Returns or sets the namespace for items added through the Add New Item Dialog Box This property provides the same functionality as the DefaultNamespace Property and using the DefaultNamespace property is preferred for setting the namespace of new project items We should clear this property as we want to prevent the fully qualifies namespace of each class from being CKProject CKNamespace Reference Visual Basic and Visual C Project Extensibility RootNamespace Property C Incorrect Answers A B The AssemblyName property is not directly related to the fully qualified namespace class C We should clear the RootNamespace property as we want to prevent the fully qualifies namespace of each class from being CKProject CKNamespace QUESTION You create an ASP NET application for Certkiller to sell Study Guides online One of the requirements is that every page must display the company name at the top You create a Web custom control that encapsulates the company name in a heading element Your control class named CompanyName inherits from the Control class The following HTML code displays the company name h Certkiller h You need to write code in the CompanyName class to display the company header Which code should you use protected override void Render HtmlTextWriter output output Write h Certkiller h protected override void OnPreRender EventArgs e this Controls Add new LiteralControl h Certkiller h protected override void RenderChildren HtmlTextWriter output output Write h Certkiller h protected override void OnInit EventArgs e this Controls Add new LiteralControl h Certkiller h Answer A Explanation You create a rendered custom control's appearance by overriding the base class' s Render method and writing to the method' s output argument using the HtmlTextWriter utility methods The most direct approach is to use the Write methods to add the HTML directly to the HtmlTextWriter The Control RenderChildren method outputs the content of a server control's children to a provided HtmlTextWriter object which writes the content to be rendered on the client This method notifies ASP NET to render any Active Server Pages ASP code on the page If no ASP code exists on the page this method renders any child controls for the server control Reference - - Training kit Creating the Rendered Control's Appearance pages - NET Framework Class Library Control RenderChildren Method C Incorrect Answers B D We should not add controls to the web page just a header C We should override the render method not the RenderChildren method as we want to add content to the page itself not the controls of the page QUESTION Your ASP NET application enables customers to create new sales orders The sales orders are stored in a Microsoft SQL Server database table named Certkiller Sales The table has an IDENTITY column named OrderID Your code uses a DataTable object to manage the order data The DataTable object contains a column named OrderNumber You use the Update method of a SqlDataAdapter object to call a stored procedure that inserts each new order into the database The stored procedure uses a parameter to return the new OrderID value for each order You assign a SqlCommand object to the InsertCommand property of the SqlDataAdapter object You add a SqlParameter object to the Parameters collection of the SqlDataAdapter object specifying the name and data type of the parameter You need to set properties of the SqlParameter object to retrieve new OrderID values from the database into the OrderNumber column of your DataTable object What should you do Set the Direction property to ParameterDirection ReturnValue Set the SourceColumn property to OrderID Set the Direction property to ParameterDirection ReturnValue Set the SourceColumn property to OrderNumber Set the Direction property to ParameterDirection Output Set the SourceColumn property to OrderID D Set the Direction property to ParameterDirection Output Set the SourceColumn property to OrderNumber Answer D Explanation As the stored procedure uses a parameter to return the new OrderID value we need to use an output paramater This is accomplished by setting the Direction property to ParameterDirection Output The SqlParameter SourceColumn property gets or sets the name of the source column that is mapped to the DataSet and used for loading or returning the Value The source column where the value will be stored is the OrderNumber column Note SqlParameter Direction property gets or sets a value indicating whether the parameter is input-only output-only bidirectional or a stored procedure return value parameter Reference NET Framework Class Library SqlParameter Direction Property C NET Framework Class Library ParameterDirection Enumeration NET Framework Class Library SqlParameter SourceColumn Property Incorrect Answers A B The scenario clearly states that the stored procedure uses a parameter not a return value to return the new OrderID value We should not set the Direction property to ParameterDirection ReturnValue C The output parameter should be stored in the OrderNumber column We must set the SourceColumn property to the OrderNumber column QUESTION You create an ASP NET page that retrieves product information from a Microsoft SQL Server database named CertK iDB You want to display the list of products in a Repeater control named repeaterProducts Your code uses the System Data namespace and the System Data SqlClient namespace You write the following procedure to retrieve the data private void RepeaterBind string ConnectionString string SQL SqlDataAdapter da DataTable dt da new SqlDataAdapter SQL ConnectionString dt new DataTable You need to add code that will fill repeaterProducts with data retrieved from the database Which code segment should you use repeaterProducts DataSource dt repeaterProducts DataBind da Fill dt da Fill dt repeaterProducts DataBind repeaterProducts DataSource dt repeaterProducts DataBind da Fill dt repeaterProducts DataSource dt da Fill dt repeaterProducts DataSource dt repeaterProducts DataBind Answer D Explanation First we must fill the data set Then we specify the data source and finally we bind the data to the control Note Using data-access objects in code follows the sequence Create the data connection object Create a data adapter object Create a data set object Invoke methods on the adapter object to fill or update the data set This scenario da Fill dt Use data binding or another technique to display the data from the data set This scenario repeaterProducts DataSource dt repeaterProducts DataBind Reference - - Training kit Creating a Database Connection at Run Time pages - Incorrect Answers A We must start by filling the data set B We must specify the data source before we bind the control to the data C We must start by filling the data set QUESTION You are creating an ASP NET page that displays inventory figures for selected items Your code creates ad hoc SQL queries and retrieves data from a Microsoft SQL Server database The identification number of an item is stored in a string variable named ItemID and the SQL statement for your query is stored in a variable named SQL You use the following line of code to construct the SQL query SQL SELECT UnitsOnHand UnitsOnOrder FROM Inventory WHERE ProductID ItemID The ProductID UnitsOnHand and UnitsOnOrder columns in the database are all of type int You use a SqlDataReader object named reader to retrieve the data You want to assign the UnitsOnHand quantity to a variable named OnHand Which line of code should you use OnHand reader GetInt OnHand reader GetInt OnHand reader GetInt OnHand reader GetInt Answer C Explanation The SQL Server datatype int corresponds to -bit Visual Basic NET integers We must therefore use the GetInt method which gets the value of the specified column as a -bit signed integer We must specify the st column as we want to retrieve the value of the UnitsOnHand column which is listed first in the SQL SELECT statement The GetInt parameter which specifies the ordinal of the column is based We should use value of the parameter to retrieve the appropriate column Note The SQL Server datatype int Integer whole number represents data from - - through - Storage size is bytes The SQL- synonym for int is integer Reference SQL Server Books Online Transact-SQL Reference int bigint smallint and tinyint NET Framework Class Library SqlDataReader GetInt Method C Incorrect Answers A SqlDataReader GetInt method gets the value of the specified column as a -bit signed integer D GetInt would retrieve the second column named UnitsOrder QUESTION You are creating an ASP NET page for the sales department at Certkiller The page enables users to access data for individual customers by selecting a customer's name After a customer's name is selected the page displays a list of that customer's unshipped orders and the total year-to-date YTD sales to that customer Your company's sales data is stored in a Microsoft SQL Server database You write a stored procedure to return the data that you need to display on the ASP NET page The stored procedure returns a result set containing the list of unshipped orders and it returns the YTD sales in a parameter named YTD You write code that uses a SqlCommand object named cmd and a SqlDataReader object named reader to run the stored procedure and return the data You bind reader to a DataGrid control on your page to display the list of unshipped orders You want to display the YTD sales in a Label control named ytdLabel Which code segment should you use A reader NextResult ytdLabel Text cmd Parameters YTD Value ToString reader Close B reader Close ytdLabel Text reader NextResult ToString C reader Close ytdLabel Text cmd Parameters YTD Value ToString D ytdLabel Text cmd Parameters RETURN VALUE Value ToString reader Close Answer C Explanation The YTD parameter is an output parameter that contains the information we want to display in the Label control We fetch this value from the parameters collection convert it to a string and save it the label control Reference NET Framework Developer's Guide Input and Output Parameters and Return Values C Incorrect Answers A B The SqlDataReader NextResult method advances the data reader to the next result when reading the results of batch Transact-SQL statements However in this scenario the reader only provides a single result set D The YTD sales is returned in a parameter named YTD It is not returned as a return value of the stored procedure QUESTION You are creating an ASP NET page that displays a list of products The product information is stored in a Microsoft SQL Server database You use SqlConnection object to connect to the database Your SQL Server computer is named Certkiller The database that contains the product information is named SalesDB The table that contains the product information is named Products To connect to SalesDB you use a SQL Server user account named WebApp that has the password CertK i You need to set the ConnectionString property of the SqlConnection object Which string should you use Provider SQLOLEDB File Name Data MyFile udl Provider MSDASQL Data Source Certkiller Initial Catalog SalesDB User ID WebApp Password CertK i Data Source Certkiller Initial Catalog SalesDB User ID WebApp Password CertK i Data Source Certkiller Database SalesDB Initial File Name Products User ID WebApp Pwd CertK i Answer C Explanation We specify the name of the SQL Server computer with the Data Source attribute The database is specified with the Initial Catalog attribute Reference NET Framework Class Library SqlConnection ConnectionString Property C Incorrect Answers A B The SqlConnection ConnectionString has no Provider attribute The provider is implicitly SQL Server or later D There is no Initial

Related Downloads
Explore
Post your homework questions and get free online help from our incredible volunteers
  1220 People Browsing