You are creating an ASP.NET page that contains a Label control named specialsLabel. A text file named Specials.txt contains a list of products. Specials.txt is located in the application directory. Each product name listed in Specials.txt is followed by a carriage return.You need to display a list of featured products in specialsLabel. You need to retrieve the lost of products from Specials.txt.Which code segment should you use?
A. System.IO.StreamReader reader =
System.IO.File.OpenText(
Server.MapPath(“Specials.txt”));
string inout = “”;
while (input !=null)
{
specialsLabel.Text =
string.Format(“{0} <br> {1} “,
specialsLabel.Text, input);
input = reader.BaseStream.ToString();
}
reader.Close();
B. System.IO.StreamReader reader =
System.IO.File.OpenText(
Server.MapPath(“Specials.txt”));
string inout = “”;
input = reader.ReadLine();
while (input != null)
{
specialsLabel.Text =
string.Format(“{0} <br> {1} “,
specialsLabel.Text, input);
input = reader.ReadLine();
}
reader.Close()
C. System.IO.Stream strm = System.IO.File.OpenRead(
Server.MapPath(“Specials.txt”));
byte[] b 0 new byte[1024];
string input;
input = strm.Read(b, 0, b.Length).ToString();
specialsLabel.Text = input
strm.Close();
D. System.IO.Stream strm = System.IO.File.OpenRead(
Server.MapPath(“Specials.txt”));
string input;
input = strm.ToString();
specialsLabel.Text = input;
strm.Close();
Answer: B
You create a Web custom control named TKToggle that users can turn on and off. The TKToggle 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 TKToggle class so that when toggleButton is clicked, pages that contain instances of TKToggle can process custom event handling code. You add the following code to the TKToggle 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
TKToggle 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)
A. ChangedValue(this, EventArgs.Empty);
B. s.Click += new System.EventHandler(this.OnChangedValue);
C. OnChangedValue(EventArgs.Empty);
D. OnChangedValue(this, EventArgs.Empty);
Answer: B, C
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 BMWDB. 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?
A. 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.
B. 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
You are creating an ASP.NET application for BMW. 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 TestKPolicyLibrary.dll contains the logic for calculating the renewal premium.TestKPolicyLibrary.dll is written in Visual Basic 6.0. 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 TestKPolicyLibrary.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 TestKPolicyLibrary.DLL
/out:TestKPolicyLibrary.NET.DLL
Copy the original TestKPolicyLibrary.dll to the /bin directory of your ASP.NET application.
B. Run the following command in a command window:
TLBEXP.EXE TestKPolicyLibrary.DLL
/out:TestKPolicyLibrary.NET.DLL
Copy the original TestKPolicyLibrary.dll to the /bin directory of your ASP.NET application.
C. Select Add Existing Item from the Project menu in Visual Studio .NET and browse to
TestKPolicyLibrary.dll.
D. Select Add Reference from the Project menu in Visual Studio .NET, select the COM tab, and
browse to TestKPolicyLibrary.dll.
Answer: D
You are creating a Web site for BMW. You receive product lists in the form of XML documents. You are creating a procedure to extract information from these XML documents according to criteria that your users will select.When a user makes a request, you want the results of these requests to be returned as quickly
as possible.What should you do?
A. Create an XmlDataDocument object and load it with the XML data.
Use the DataSet property of the object to create a DataSet object.
Use a SQL SELECT statement to extract the requested data.
B. Create an XmlDataDocument object and load it with the XML data.
Use the SelectNodes method of the object to extract the requested data.
C. Create an XPathDocument object and load it with the XML data.
Call the CreateNavigator method to create an XPathNavigator object.
Call the Select method of the XPathNavigator object to run an XPath query that extracts the
requested data.
D. Create an XmlReader object.
Use the Read method of the object to stream through the XML data and to apply an XPath
expression to extract the requested data.
Answer: C
You company BMW 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?
A. Modify all ASP.NET pages in the application so that the view state is enabled.
B. Modify all ASP.NET pages in the application to add custom logic that conveys the demographic information in either textual or graphical format.
C. Modify all images in the application so that the ToolTip property conveys the same demographic information as the image.
D. Modify all images in the application so that the AlternateText property conveys the same demographic information as the image.
Answer: D
You are developing an ASP.NET application for BMW’s intranet. Employees will use the application to administer their employee benefits. The benefits information is stored in a Microsoft SQL Server database named Benefits.An employee can select benefits options from 10 different drop-down list boxes. The values for each list are stored in separate tables in the Benefits database. The values that are available for employees to choose can change once each year during the benefits enrollment period.You want to minimize the number of times your application must access the Benefits database
to obtain the values for the drop-down list box.Which two courses of action should you take? (Each correct answer presents part of the
solution. Choose two)
A. Create one stored procedure that returns the result for all 10 drop-down list boxes.
Create one DataTable object for each of the 10 drop-down list boxes.
Use a SqlDataReader object to populate 10 DataTable objects by calling the NextResult()
method.
Bind the drop-down list boxes to the DataTable objects.
B. Create a stored procedure that returns the result set for all 10 drop-down list boxes.
Bind the drop-down list boxes to the DataReader object.
C. Create one DataTable object for each of the 10 drop-down list boxes.
Create a stored procedure for each of the 10 tables.
Use a SqlDataReader object to populate the 10 DataTable objects.
Bind the drop-down list boxes to the DataTable objects.
D. Store the result sets for the 10 drop-down list boxes in a DataSet object.
Add the DataSet objects to the Cache object for the application.
E. Store the result sets for the 10 drop-down list bikes in a file on the user’s computer by using
the DataSet.WriteXml() method.
Answer: A, D
You are creating an ASP.NET application that uses role-based security to allow users to access only those pages that they are authorized to access. You use a Microsoft SQL Server database to manage the list of users and roles for the ASP.NET application. A table named Roles contains a column named RoleID and a column named RoleName. A table named Users contains a column named UserID, a column named UserName, and a column named Password.A table named UserRoles contains a column named UserID and a column named RoleID.You need to create a stored procedure that returns all users who belong to a specific role. You
write the following Transact-SQL code to define the stored procedure:
CREATE PROCEDURE GetRoleMembers
@RoleID int
AS
Which code segment should you use to complete the stored procedure?
A. SELECT UserRoles.UserID, Users.UserName
FROM Users
INNER JOIN
Roles UserRoles On UserRoles.RoleID = Users.UserID
WHERE UserRoles.RoleID = @RoleID
B. SELECT UserRoles.UserID, Users.UserName
FROM UserRoles
INNER JOIN
Roles On UserRoles.RoleID = Roles.RoleID, Users
WHERE UserRoles.RoleID = @RoleID
C. SELECT UserRoles.UserID, Users.UserName
FROM UserRoles
INNER JOIN
Users On Users.UserID = UserRoles.UserID
WHERE UserRoles.RoleID = @RoleID
D. SELECT Users.UserID. Users.UserName
FROM Users, UserRoles
INNER JOIN
Roles On UserRoles.RoleID = Roles.RoleID
WHERE UserRoles.RoleID = @RoleID
Answer: C
You are a Web developer for BMW. 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?
A. private string TKGetDisplayValue(double value,string
inputRegion)
{
string display:
RegionInfo region;
region = new RegionInfo(inputRegion);
display = value.ToString(“C”);
display += region.CurrencySymbol;
return display;
}
B. private string TKGetDisplayValue(double value,string
inputCulture)
{
string display;
NumberFormatInfo LocalFormat = (NumberFormatInfo)
NumberFormatInfo.CurrentInfo.Clone();
display = value.ToString(“C”, LocalFormat);
return display;
}
C. private string TKGetDisplayValue(double value,string
inputRegion)
{
string display;
RegionInfo region;
region = new RegionInfo(inputRegion);
display = value.ToString(“C”);
display += region.ISOCurrencySymbol;
return display;
}
D. private string TKGetDisplayValue(double value, string
inputCulture)
{
string display;
CultureInfo culture;
culture = new CultureInfo(inputCulture);
display = value.ToString(“C”, culture);
return display;
}
Answer: D
You are creating an ASP.NET page for the sales department at BMW. 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
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?
A. OnHand = reader.GetInt16(0);
B. OnHand = reader.GetInt16(1);
C. OnHand = reader.GetInt32(0);
D. OnHand = reader.GetInt32(1);
Answer: C
You create an ASP.NET application for an online shopping site. The application uses a Microsoft SQL Server 2000 database named BMWSales. The database contains a stored procedure named getProductsByCategory that returns all products that match a specified category code. The category code is supplied as a parameter named @ProdCode.The application includes a page named ShowProducts.aspx. You are using Visual Studio .NET to debug ShowProducts.aspx.
ShowProducts.aspx uses the getProductsByCategory stored procedure to populate a DataSet object. You set a breakpoint within getProductsByCategory so that you can step through the stored procedure within the debugger.Which you are debugging getProductsByCategory, you need to view the current value of @ProdCode.
What should you do?
A. Open the Locals debugging window.
B. Open the Modules debugging window.
C. Add the following line of code to getProductsByCategory:
Print @ProdCode
Open the Output debugging window and select Debug as the source from the drop-.down list
box.
D. Add the following line of code to getProductsByCategory:
SELECT @ProdCode As DebugOutput
Open the Output debugging window and select Database Output as the source from the dropdown
list box.
Answer: A
You are creating an ASP.NET application for BMW’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)
1 private void WorkDays_Render(object source,
DayRenderEventArgs e)
2 {
3
4 }
Which code should you add at line 3 of the event handler?
A. 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;
}
B. if ((e.Day.Date.Day == 6) && e.DayIsOtherMonth)
{
e.Cell.Controls.Add(new
LiteralControl(“Staff Meeting”));
e.Cell.BackColor = System.Drawing.Color.Yellow;
}
C. if (e.Day.Date.Day == 6)
{
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
You are creating an ASP.NET page for BMW. The company wants to use this page to allow customers to enter their addresses. You create a user control named CustomerAddress. You define this control in a file named CustomerAddress.ascx. You place this file in a folder named AddressControls.You create a page in the same folder to test your control. You add the following directive to the top of your test page:
<%@ Register Tagprefix=”TK” Tagname=”CustomerAddress”
Namespace=”CustomerAddress.ascx” %>
You add the following tag to your test page:
<TK:CustomerAddress runat=”server”/>
When you open the test page, you receive the following error message: “Parser Error –Description: An error occurred during the parsing of a resource required to service this request.”
You need to change the directive to correct this error.Which directive should you use?
A. <%@ Register Tagprefix=”TK” Tagname=”CustomerAddress”
Namespace=”.\AddressControls\CustomerAddress.ascx” %>
B. <%@ Register Tagprefix=”TK” Tagname=”CustomerAddress”
Src=”CustomerAddress.ascx” %>
C. <%@ Register Tagprefix=”TK” Tagname=”CustomerAddress”
Assembly=”CustomerAddress” %>
D. <%@ Reference control=”CustomerAddress.ascx” %>
Answer: B
You create an ASP .NET page for BMW’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=”30”
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?
A. purchaseOrder = e.Item.Cells[1].Text;
B. purchaseOrder = (TextBox)e.Item.Cells[1].Controls[“PONumber”].Text;
C. purchaseOrder = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
D. purchaseOrder = PONumber.Text;
Answer: C
You create an ASP.NET application for online sales site for the BMW Corporation. A page named OrderTKVerify.aspx displays a detailed listing of the items ordered, their quantity, and their unit price. OrderTKVerify.aspx then displays the final order total at the end of the page.The Web Form within OrderTKVerify.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?
A. Modify the HTML element as follows:
<asp:button id=”submitOrderButton” runat=”server”
Text=”Submit Order”
onClick=”verifyBeforeSubmit();”></asp:button>
B. Modify the HTML elements as follows:
<asp:button id=”submitOrderButton” runat=”server”
Text=”Submit Order”
ServerClick=”verifyBeforeSubmit();”></asp:button>
C. Add the following code to the Page.Load event handler for OrderTKVerify.aspx:
submitOrderButton.Attribute.Add(“onclick”,
“verifyBeforeSubmit();”;
D. Add the following code to the Page.Load event handler for OrderTKVerify.aspx:
submitOrderButton.Attribute.Add(“ServerClick”,
“verifyBeforeSubmit();”;
Answer: C
You create an ASP.NET application for BMW. You create an exception class named DataCollisionEx. The exception class is defined in TkNamespace. 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(“TkNamespace.DataCollisionEx”);
ex = Server.GetLastError();
if (ex.GetType().Equals(argExType))
{
Response.Redirect(“DataCollision.aspx”);
}
else
{
Server.ClearError();
}
B. Type argExType;
Exception ex;
argExType = Type.GetType(“TkNamespace.DataCollisionEx”);
ex = Server.GetLastError();
if (ex.GetType().Equals(argExType))
{
Response.Redirect(“DataCollision.aspx”);
}
C. Type argExType;
Exception ex;
argExType = Type.GetType(“TkNamespace.DataCollisionEx”);
ex = Server.GetLastError().InnerException;
if (ex.GetType().Equals(argExType))
{
Response.Redirect(“DataCollision.aspx”);
}
D. Type argExType;
Exception ex;
argExType = Type.GetType(“TkNamespace.DataCollisionEx”);
ex = Server.GetLastError().InnerException;
if (ex.GetType().Equals(argExType))
{
Response.Redirect(“DataCollision.aspx”);
}
else
{
Server.ClearError();
}
Answer: C
You are creating an ASP.NET page for recording contact information for BMW 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?
A. 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.”
B. 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.”
C. 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.”
D. 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
You create an ASP.NET application for BMW 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 encapsulate 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: <h2>BMW</h2> You need to write code in the CompanyName class to display the company header.Which code should you use?
A. protected override void Render(
HtmlTextWriter output)
{
output.Write(“<h2>BMW</h2>”);
}
B. protected override void OnPreRender(
EventArgs e)
{
this.Controls.Add(new
LiteralControl(“<h2>BMW</h2>”));
}
C. protected override void RenderChildren(
HtmlTextWriter output)
{
output.Write(“<h2>BMW</h2>”);
}
D. protected override void OnInit(EventArgs e)
{
this.Controls.Add(new
LiteralControl(“<h2>BMW</h2>”);
}
Answer: A
You create an ASP.NET application for BMW. Your application contains a method named nextBusinessDay. This method uses a date parameter and returns the next date that is not a holiday or weekend day.You are debugging a page named ProjectTimeLine.aspx. You need the execution to break on the following line of code when the value of the dStartDate variable changes:dStartDate = nextBusinessDay(dStartDate);What should you do?
A. Set a breakpoint on the line of code and open the BreakPoint Properties dialog box.
Specify the following breakpoint condition:
dStartDate !=dStartDate
Select the is true option.
B. Set a breakpoint on the line of code and open the BreakPoint Properties dialog box.
Specify the following breakpoint condition:
dStartDate
Select the has changed option.
C. Add the following statement immediately after the call to nextBusinessDay:
System.Diagnostics.Debug.Assert(
dStartDate !=dStartDate, “dStartDate has changed.”;
D. Add the following statement immediately after the call to nextBusinessDay:
System.Diagnostics.Trace.Assert(
dStartDate !=dStartDate, “dStartDate has changed.”;
Answer: B
You create an ASP.NET page that retrieves product information from a Microsoft SQL Server database named TestKiDB. 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?
A. repeaterProducts.DataSource = dt;
repeaterProducts.DataBind();
da.Fill(dt);
B. da.Fill(dt);
repeaterProducts.DataBind();
repeaterProducts.DataSource = dt;
C. repeaterProducts.DataBind();
da.Fill(dt);
repeaterProducts.DataSource = dt;
D. da.Fill(dt);
repeaterProducts.DataSource = dt;
repeaterProducts.DataBind();
Answer: D
You are a Web developer for a BMW bookstore. You create a Web user control named TkBookTopics that is defined in a file named TkBookTopics.ascx. TkBookTopics 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 TkBookTopics named AuthorProfile.You create an ASP.NET page named AuthorPage.aspx that contains an instance of the TkBookTopics 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 TkBookTopics 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?
A. Add the following element to the OutputCache directive for AuthorPage.aspx:
VaryByParam=”TkBookTopics.AuthorProfile”
B. Add the following element to the OutputCache directive for AuthorPage.aspx:
VaryByControl=”TkBookTopics.AuthorProfile”
C. Add the following element to the OutputCache directive for TkBookTopics.ascx:
VaryByParam=”none”
D. Add the following element to the OutputCache directive for TkBookTopics.ascx:
VaryByControl=”authorProfileID”
Answer: D
You create an ASP.NET application to keep track of BMW’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 TestKiEmployeeStatus 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 TestKiEmployeeStatus is as follows:
<asp:repeater id=”TestKiEmployeeStatus” 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 TestKiEmployeeStatus. 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)
A. Add the following HTML code to the ItemTemplate element of TestKiEmployeeStatus:
<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”]);
}
B. Add the following HTML code to the Item Template element of TestKiEmployeeStatus:
<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”]));
}
C. Add the following HTML code to the ItemTemplate element of TestKiEmployeeStatus:
<asp:Button id=”changeStatusButton” Runat=”Server”
Text=”Change Status”
CommandArgument=<%# Container.DataItem[“EmployeeID”]%>
/>
Add the following code to the ItemCommand event of TestKiEmployeeStatus:
if (source.id == “changeStatusButton”)
{
ChangeInOutStatus(
(int)e.CommandSource.CommandArgument);
}
D. Add the following HTML code to the ItemTemplate element of TestKiEmployeeStatus:
<asp:Button id=”changeStatusButton” Runat=”server”
Text=”Change Status”
CommandArgument=<%# Container.DataItem[“EmployeeID”]%>
/>
Add the following code to the ItemCommand event of TestKiEmployeeStatus:
if (e.CommandSource.id == “changeStatusButton”)
{
ChangeInOutStatus((int)e.CommandArgument);
}
Answer: B, D
You are creating an ASP.NET application that performs updates to a database named BMWDB. The application performs the updates by running a series of SQL statements.You write a procedure to run the SQL statements. The procedure accepts a connection string and an array of SQL statement as parameters.You use structured exception handling in your procedure to handle any errors that occur while the statements are running. You want the procedure to terminate after handling an exception and to return the SQL statement that caused the exception. You also want to ensure that the database connection is closed before the procedure terminates, whether or not an error occurs.You begin writing the procedure by using the following code:
public static void ExecuteStatements(
string connectionString, string[] sql)
{
OleDbConnection cnn =
new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
int i;
cmd.Connection = cnn;
cnn.Open();
try
{
for (i=0; i <= sql.Length – 1; i++)
{
cmd.CommandText = sql[i];
cmd.ExecuteNonQuery();
}
}
Which code segment should you use to complete the procedure?
A. catch(OleDbException ex)
{
throw(ex);
}
finally
{
cnn.Close();
}
}
B. catch(OleDbException ex)
{
throw(new Exception(sql[i], ex));
}
finally
{
cnn.Close();
}
}
C. catch(OleDbException ex)
{
throw(ex);
}
}
cnn.Close();
D. catch(OleDbException ex)
{
throw(new Exception(sql[i], ex));
}
}
cnn.Close();
Answer: B
You create an ASP.NET page that contains a DataGrid control. The control displays data that is retrieved from a database named BMWDB. 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
You 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 ValidateTKRole that has three arguments. The argument named User is the user name, the argument named Role1 is the first role to verify, and the argument named Role2 is the second role to verify. You want ValidateTKRole to return a value of true if the specified user has membership in either of the specified roles.You write the following code:
PrincipalPermission principalPerm1 =new PrincipalPermission(“User”, “Role1”);
PrincipalPermission principalPerm2 =new PrincipalPermission(“User”, “Role”);
Which code segment should you use to complete the function?
A. return principalPerm1.IsUnrestricted() && principalPerm2.IsUnrestricted();
B. return principalPerm1.IsSubsetOf(principalPerm2);
C. return principalPerm1.Intersect(principalPerm2).Demand();
D. return principalPerm1.Union(principalPerm2).Demand();
Answer: D
You create a class named TKFormat that has two public properties. One of the properties is named Size, and the other property is named Color. You want to use the TKFormat 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 TKFormat _formatter = new TKFormat();
public TKFormat 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=”testkctl” 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 10
and the color property is set to red.
Which code should you use?
A. <testkctl:MessageRepater Format-Color=”red”
Format-Size=”10” />
B. <testkctl:MessageRepater Format-Color=”red”
Format-Size=”10” runat=”server” />
C. <testkctl:MessageRepater Color=”red”
Size=”10” runat=”server” />
D. <testkctl:MessageRepater Format=”Color:red;size:10” />
Answer: B
You Create an ASP.NET application for a bank. The application provides account management functionality.A page named AccountWithdrawal.aspx contains a method named WithdrawFunds. The WithdrawFunds method is defined in the following code segment. (Line numbers are included for reference only)
1 private double WithdrawFunds(double Amount)
2 {
3
4 m_dAccountBalance -= Amount;
5 return m_dAccountBalance;
6 }
The callers of this method need to verify that sufficient funds exist in the account before
attempting the withdrawal. During unit testing, you want to receive notification when a call is
made requesting a withdrawal amount for which the account does not have sufficient funds
available.
You plan to build the production version of your application by using the Release Build
Configuration in Visual Studio .NET. You need the testing instrumentation to be included but
not enabled in the application when the application is deployed to production. You need to
have the ability to enable the instrumentation after deploying it to production without
requiring the application to be rebuilt.
Which code should you insert at line 3 of the code segment?
A. Debug.Assert(m_dAccountBalance – Amount >=0,
“Insufficient funds for withdrawal.”);
B. Trace.Assert(m_dAccountBalance – Amount >=0,
“Insufficient funds for withdrawal.”);
C. Debug.WriteLine(m_dAccountBalance – Amount >=0,
“Insufficient funds for withdrawal.”);
D. Trace.WriteLineIf(m_dAccountBalance – Amount >=0,
“Insufficient funds for withdrawal.”);
Answer: B
You are creating an ASP.NET application for BMW’s Travel. BMW’s Travel uses a Microsoft SQL Server 2000 database to store information about vacation packages. Your application will allow a user to request information about vacation packages for a specific destination.You want to display this data to the user in a DataGrid. You want the data to be displayed in read-only form. The user’s travel destination is contained in a form level string variable named
destinationCode. In your Page.Load event handler, you create a SqlConnection object named SqlConnection1, initialize it, and call its Open() method. When your code runs the query, you want the data to be returned as quickly as possible. You define the following local variable to hold the destination code:
string dest = destinationCode; What should you do?
A. Create a stored procedure named GetDestinations and then use the following code to retrieve
the data:
SqlCommand cmd =
new SqlCommand(“GetDestinations”,
sqlConnection1);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm =
new SqlParameter(“@DestinationCode”, dest);
cmd.Parameters.Add(parm);
SqlDataReader sqlDataReader1 = cmd.ExecuteReader();
B. Create a stored procedure named GetDestinations and then use the following code to retrieve
the data:
string qry =
“EXEC GetDestinations WHERE DestID = “ + dest + “”;
SqlDataAdapter da =
new SqlDataAdapter(qry, sqlConnection1);
DataSet ds = new DataSet();
da.Fill(ds);
C. Use the following code to retrieve the data:
string qry =
“SELECT * FROM Destination WHERE DestID =
“ + dest + “”;
SqlCommand cmd = new SqlCommand(qry,
sqlConnection1);
cmd.CommandType = CommandType.Text;
SqlDataReader sqlDataReader1 = cmd.ExecuteReader();
D. Use the following code to retrieve the data:
string qry =
“SELECT * FROM Products WHERE DestID = @DestID”;
SqlCommand cmd = new SqlCommand(qry;
sqlConnection1);
cmd.CommandType = CommandType.Text;
SqlParameter parm = new SqlParameter(“@DestID”,
dest);
cmd.Parameters.Add(parm);
SqlDataReader sqlDataReader1 = cmd.ExecuteReader();
Answer: A
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 TkNewsItems, 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 TkNewsItems in HTML format. You write the following code segment:
XmlDataDocument doc = new XmlDataDocument(TkNewsItems);
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?
A. tran.Transform(doc, null, Response.OutputStream);
B. tran.Transform(doc, null, Request.InputStream);
C. TkNewsItems.WriteXml(Response.OutputStream);
D. TkNewsItems.WriteXml(tran.ToString());
Answer: A
You are a Web developer for a travel company called BMW 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);
}
B. 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;
}
C. 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
}
D. 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
You create an ASP.NET application for BMW 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)
A. Add the following code to the vehicleIDNumber.TextChanged event handler for InsuredAuto.aspx:
vehicleIDNumber.Text = vehicleIDNumber.Text.ToUpper();
B. Add the following code to the submitButton.Click event handler for InsuredAuto.aspx:
vehcicleIDNumber.Text = vehicleIDNumber.Text.ToUpper();
C. 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
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 timeTKLabel. The timeTKLabel 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 predefines styles are created in the following function:
public Style GetStyle(int styleType)
{
Style myStyle = new Style();
switch (styleType)
{
case 1:
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?
A. public void PickStyle(int styleType)
{
Style myStyle = GetStyle(styleType);
timeTKLabel.ApplyStyle(myStyle);
}
B. public void PickStyle(int styleType)
{
Style myStyle = GetStyle(styleType);
timeTKLabel.MergeStyle(myStyle);
}
C. public void PickStyle(int styleType)
{
Style myStyle = GetStyle(styleType);
timeTKLabel.ForeColor = myStyle.ForeColor;
timeTKLabel.BackColor = myStyle.BackColor:
}
D. public void PickStyle(int styleType)
{
Style myStyle = GetStyle(styleType);
timeTKLabel.CssClass = myStyle.CssClass;
}
Answer: B
You create an ASP.NET application for a consulting company BMW Insurance. BMW uses the application to perform time tracking and to generate billing invoices. The accounts receivable department uses a page named PrepareInvoices.aspx to issue invoices to clients at the end of each month.During testing of the application, you discover that some invoices are being generated with negative values for the total amount due. The total amount due is calculated within a function named CalculateTotalDue, which is defined in the PrepareInvoices.aspx page. The call to CalculateDue is contained in the following code segment from PrepareInvoices.aspx. (Line numbers are included for reference only)
1 double TotalAmountDue;
2 totalAmountDue = CalculateTotalDue();
3 totalAmountDue -= totalAmountDue * discountRate;
You need to stop execution of the code within PrepareInvoices.aspx and enter the interactive debugger when CalculateTotalDue returns a negative value.What should you do?
A. Modify the code segment as follows:
double totalAmountDue;
totalAmountDue = CalculateTotalDue();
System.Diagnostics.Debug.Assert(totalAmountDue >= 0);
totalAmountDue -= totalAmountDue * discountRate;
B. Modify the code segment as follows:
double totalAmountDue;
totalAmountDue = CalculateTotalDue();
totalAmountDue -= totalAmountDue * discountRate;
System.Diagnostics.Debug.Assert(totalAmountDue >= 0);
C. In the Watch window, add a watch expression of totalAmountDue < 0, and select the Break
When Value Is True option.
D. Set a breakpoint on line 3 of the code segment.
Define a condition for the breakpoint to break when totalAmountDue < 0 is true.
E. Set a breakpoint on line 2 of the code segment.
Define a condition for the breakpoint to break when totalAmountDue < 0 is true.
Answer: D
You create an ASP.NET application for tracking student examinations at the local BMW Certification school. You use Microsoft Windows authentication. Students are members of a group named Students, and teachers are members of a group named Teachers.The root folder for your application is named Exams. The Exams folder displays information about pending examinations. The Exams folder has a subfolder named Grades. Both Students and teachers can access pages in Exams. Only teachers can access page in Grades. You create the following entries in the Web.config file in Exams. (Line numbers are included for reference only)
1 <authentication mode=”Windows” />
2 <authorization>
3 <allow roles=”Students, Teachers” />
4 <deny users=”*” />
5 </authorization>
You crate the following entries in the Web.config file in Grades. (Line numbers are included for reference only.)
1 <authentication mode=”Windows” />
2 <authorization>
3 <allow roles=”Teachers” />
4 <deny users=”*” />
5 </authorization>
When teachers try to access pages in the Grades folder, they receive an error message that reads in part: “An error occurred during the processing of a configuration file required to service this request.” You need to ensure that teachers can access pages in the Grades folder.What should you do?
A. Remove line 1 in the Web.config file in Grades.
B. Modify line 4 in the Web.config file in Grades as follows:
<allow users=”*” />
C. Add the following line between line 1 and line 2 in the Web.config file in Exams:
<identity impersonate=”true” />
D. Add the following line between line 1 and line 2 in the Web.config file in Grades:
<identity impersonate=”true” />
E. Add the following line between line 1 and line 2 in the Web.config file in Grades:
<identity impersonate=”false” />
Answer: A
You are a Web developer for a museum. The museum has a Microsoft SQL Server database that contains information about science experiments. The database currently contains information on 5,000 experiments. The information is updated monthly.You are creating an ASP.NET application for users to find information about specific experiments. The application will run on a server that is connected to the database by a lowbandwidth leases line.You want to accomplish the following two goals:
• Minimize the number of times the application accesses the database.
• Minimize the time required for each page of the application to load.
What should you do?
A. Initialize the DataSet object in the Page.Load event handler when the IsPostBack property is false.Store the DataSet object in an XML file on the user’s computer.
B. Create a Cache object for the application and add the DataSet object to the cache.
C. Use the view state to maintain the DataSet object during postback events to the server.
D. Create a Cache object for the session and add the DataSet object to the cache.
Answer: B
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 BMWSQL1. 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 tkDataView 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:
tkDataView:
dataGridCurrentYear.DataSource = tkDataView;
tkDataView.RowFilter = “OrderDate >= #01/01/”+Now.Year + “#”
dataGridCurrentYear.DataBind();
dataGridPreviousYears.DataSource = tkDataView;
tkDataView.RowFilter = “OrderDate < #01/01/”+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?
A. Remove the Page.DataBind() statement.
B. Remove the dataGridPreviousYears.DataBind() statement.
C. Add a Response.Flush() statement immediately before the Page.DataBind() statement.
D. Add a Response.Flush() statement immediately before the dataGridPreviousYears.DataBind() statement.
Answer: A
You create an ASP.NET application for BMW. This application will display information about products that the company sells. The application uses a Microsoft SQL Server database.You add two DropDownList controls to your .aspx page. One drop-down list box will display product information. The control for this drop-down list box is named Products. The other drop-down list box will display category information. The control for this drop-down lost box is named Category. You have an open SqlConnection object named con.The Page.Load event handler uses the following code segment to populate the drop-down list boxes by binding the SqlDataReader. (Line numbers are included for reference only)
01 SqlCommand cmd1 = new SqlCommand(“SELECT * FROM
Products”,con);
02 SqlDataReader dr1 = cmd1.ExecuteReader();
03 Products.DataTextField = “ProductName”;
04 Products.DataValueField = “ProductID”;
05 Products.DataSource = dr1;
06 Products.DataBind();
07 cmd1.CommandText = “SELECT * FROM Category”;
08 SqlDataReader dr2 = cmd1.ExecuteReader();
09 Category.DataTextField = “CategoryName”;
10 Category.DataValueField = “CategoryID”
11 Category.DataSource = dr2;
12 Category.DataBind();
During testing, the page raises an invalid operation exception. You need to ensure that the page displays correctly without raising an exception.What should you do?
A. Replace the code for line 02 of the code segment with the following code:
dr1.ExecuteReader(CommandBehavior.CloseConnection;
B. Add the following code between line 06 and line 07 of the code segment:
dr1.Close();
C. Replace the code for line 07 and line 08 of the code segment with the following code:
SqlCommand cmd2 = new SqlCommand(“SELECT * FROM Category”,con);
SqlDataReader dr2 = cmd2.ExecuteReader();
D. Remove the code for line 06 of the code segment.
Replace the code for line 12 of the code segment with the following code:
Page.DataBind();
Answer: B
You are creating an ASP.NET application for an online banking site. You need to allow customers to transfer funds between accounts. You write a component in Visual C# .NET to handle transfer of funds. This component is used by the page named FundsTransfer.aspx. For unit testing, you add the following code segment to the TransferFunds method of your component. (Line numbers are included for reference only)
1 HttpContext ctx;
2 ctx = HttpContext.Current;
3 ctx.Trace.Write(“Funds transfer requested.”;
You want to be able to view the trace output on the FundsTransfer.aspx page.What should you do?
A. Add code to the FundsTransfer.aspx page that instantiate a Trace listener.
B. Enable tracing in the Page directive for the FundsTransfer.aspx page.
C. Add the following attribute to the Machine.config file:
<trace enabled=”true”>
D. Modify line 3 of the code segment as follows:
System.Diagnostics.Trace.WriteIf(
ctx.IsDebuggingEnabled, “Funds transfer requested.”);
Answer: B
You develop an application that generates random numbers to test statistical data. The application uses the following code:
Random rnd = new Random();
short num1 = Convert.ToInt16(rnd.Next(35000));
short num2 = Convert.ToInt16(rnd.Next(35000));
short num3 = Convert.ToInt16(num1 / num2);
When you test the application, you discover that certain exceptions are sometimes raised by this code. You need to write additional code that will handle all such exceptions. You want to accomplish this goal by writing the minimum amount of code.Which code segment should you use?
A. try { // Existing code goes here. }
catch(DivideByZeroException e) { // Insert error-handling code. }
catch (OverflowException e) { // Insert error-handling code. }
catch (NotFiniteNumberException e) { // Insert error-handling
code. }
B. try { // Existing code here goes. }
catch (ArithmeticException e){ // Insert error-handling code. }
C. try { // Existing code goes here. }
catch (DivideByZeroException e)
{ // Insert error-handling code. }
catch (OverflowException e) { // Insert error-handling code. }
D. try { // Existing code goes here. }
catch (OverflowException e) { // Insert error-handling code. }
Answer: B
You are maintaining an ASP.NET application. Another developer at BMW wrote the following code for the WebForm1.aspx file:
<%@ Page language=”c#” Codebehind=”WebForm1.aspx.cs”
Inherits=”WebForm1”%>
<HTML>
<body MS_POSITIONING=”GridLayout”>
<form id=”Form1” method=”post” runat=”server”>
<asp:Button id=”Button1” style=”Z-INDEX: 101;
LEFT: 203px; POSITION: absolute; TOP: 206px”
runat=”server” Text=”Submit” Width=”132pk”
Height=”25px”></asp:Button>
</form>
</body>
</HTML>
You are debugging the application and set a breakpoint in the Page.Load event handler. You notice that when you click the Submit button, the application stops at your breakpoint twice for each time that you click the button.You need to ensure that you stop at the breakpoint only once for each time that you click the Submit button.What should you do?
A. Add the following attribute to WebForm1.aspx: smartNavigation=”true”
B. Add the following attribute to WebForm1.aspx: smartNavigation=”false”
C. Add the following attribute to the Page directive: AutoEventWireup=”true”
D. Add the following attribute to the Page directive: AutoEventWireup=”false”
Answer: D
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)
A. Add the following statement to the declaration section of ListSubscribe.ascx:
public TextBox listNameText:
B. Add the following statement to the declaration section of Subscribe.aspx:
public TextBox listNameText:
C. Add the following statement to the Page.Load event handler for Subscribe.aspx:
if (!Page.IsPostBack)
{
listNameLabel.Text = ctlSubscribe.listNameText.Text;
}
D. Add the following statement to the Page.Load event handler for Subscribe.aspx:
if (Page.IsPostBack)
{
listNameLabel.Text = ctlSubscribe.listNameText.Text;
}
E. Add the following statement to the Page.Load event handler for ListSubscribe.ascx:
if (!Page.IsPostBack)
{
listNameLabel.Text = listNameText.Text;
}
F. Add the following statement to the Page.Load event handler for ListSubscribe.ascx:
if (Page.IsPostBack)
{
listNameLabel.Text = listNameText.Text;
}
Answer: A, D
You are creating an ASP.NET page that presents data to users in an updatable DataGrid control. Users update data in the grid. Your code uses the System.Data namespace and the System.Data.OleDb namespace.Data changes are saved in an ADO.NET DataTable object. You want a user’s changes to be saved to a database when the user finishes making changes. You write the following procedure to accomplish this task:
string sql, string connectionString, DataTable dataTable)
{
OleDbDataAdapter da = new OleDbDataAdapter();
OleDbConnection cnn =
new OleDbConnection(connectionString);
dataTable.AcceptChanges();
da.UpdateCommand.CommandText = sql;
da.UpdateCommand.Connection = cnn;
da.Update(dataTable);
da.Dispose();
}
This code runs to completion, but no data changes appear in the database. You test the update query and the connection string that you are passing to the procedure, and they both work correctly.You need to alter the code to ensure that data changes appear in the database.What should you do?
A. Add the following two lines of code before calling the Update method:
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
cb.GetUpdateCommand();
B. Add the following line of code before calling the Update method:
da.UpdateCommand.Connection.Open();
C. Delete thus line of code:
dataTable.AcceptChanges();
D. Delete this line of code:
da.Dispose();
Answer: C
You are creating a DataGrid control named TKGrid 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)
1 private void TKGrid_EditCommand(object s,
DataGridCommandEventArgs e)
}
2
3 }
Which code should you add at line 2 of the event handler?
A. TKGrid.EditItemIndex = e.Item.ItemIndex;
B. TKGrid.DataKeyField = e.Item.AccessKey;
C. TKGrid.SelectedIndex = e.Item.ItemIndex;
D. TKGrid.CurrentPageIndex = e.Item.ItemIndex;
Answer: A
You are creating an ASP.NET Web Form that displays employee data from a DataSet object.You want to fill the DataSet object and then you want to retrieve a reference to the employee whose primary key has the value of 1.You write the following code. (Line numbers are included for reference only)
01 SqlConnection(ConnectionString);
02 conn.Open();
03 SqlCommand cmd = new SqlCommand
(“SELECT * FROM Employees”, conn);
04 SqlDataAdapter da = new
SqlDataAdapter(cmd);
05 DataSet ds = new DataSet();
06
07 da.Fill(ds, “Employees”);
08
09 DataRow dr;
10 dr = ds.Tables[“Employees”].Rows.Find(1);
11 nameLabel.Text = dr[“Name”].ToString();
When you run the code, you receive the following error message at line 10: “Table doesn’t have a primary key.” You ensure that a primary key is defined on the Employees table in the database. You want to alleviate the error to allow the code to run correctly. You also want to catch the exception that would occur if the employee whose primary key has the value if 1 is deleted from the database.Which two actions should you take? (Each correct answer presents part of the solution. Choose
two)
A. Add the following code at line 06:
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
B. Add the following code at line 06:
da.MissingSchemaAction = MissingSchemaAction.Add;
C. Add the following code at line 06:
da.MissingSchemaAction = MissingSchemaAction.Ignore;
D. Add the following code at line 06:
da.MissingSchemaAction = MissingSchemaAction.Error;
E. Place line 07 in a structured exception handling block.
F. Place lines 10 and 11 in a structured exception handling block.
Answer: A, F
You are creating an ASP.NET page to enroll new members in a health care program for BMW employees. One of the requirements for membership is that a participant must be at least 65 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
A. System.IO.StreamReader reader =
System.IO.File.OpenText(
Server.MapPath(“Specials.txt”));
string inout = “”;
while (input !=null)
{
specialsLabel.Text =
string.Format(“{0} <br> {1} “,
specialsLabel.Text, input);
input = reader.BaseStream.ToString();
}
reader.Close();
B. System.IO.StreamReader reader =
System.IO.File.OpenText(
Server.MapPath(“Specials.txt”));
string inout = “”;
input = reader.ReadLine();
while (input != null)
{
specialsLabel.Text =
string.Format(“{0} <br> {1} “,
specialsLabel.Text, input);
input = reader.ReadLine();
}
reader.Close()
C. System.IO.Stream strm = System.IO.File.OpenRead(
Server.MapPath(“Specials.txt”));
byte[] b 0 new byte[1024];
string input;
input = strm.Read(b, 0, b.Length).ToString();
specialsLabel.Text = input
strm.Close();
D. System.IO.Stream strm = System.IO.File.OpenRead(
Server.MapPath(“Specials.txt”));
string input;
input = strm.ToString();
specialsLabel.Text = input;
strm.Close();
Answer: B
You create a Web custom control named TKToggle that users can turn on and off. The TKToggle 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 TKToggle class so that when toggleButton is clicked, pages that contain instances of TKToggle can process custom event handling code. You add the following code to the TKToggle 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
TKToggle 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)
A. ChangedValue(this, EventArgs.Empty);
B. s.Click += new System.EventHandler(this.OnChangedValue);
C. OnChangedValue(EventArgs.Empty);
D. OnChangedValue(this, EventArgs.Empty);
Answer: B, C
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 BMWDB. 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?
A. 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.
B. 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
You are creating an ASP.NET application for BMW. 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 TestKPolicyLibrary.dll contains the logic for calculating the renewal premium.TestKPolicyLibrary.dll is written in Visual Basic 6.0. 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 TestKPolicyLibrary.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 TestKPolicyLibrary.DLL
/out:TestKPolicyLibrary.NET.DLL
Copy the original TestKPolicyLibrary.dll to the /bin directory of your ASP.NET application.
B. Run the following command in a command window:
TLBEXP.EXE TestKPolicyLibrary.DLL
/out:TestKPolicyLibrary.NET.DLL
Copy the original TestKPolicyLibrary.dll to the /bin directory of your ASP.NET application.
C. Select Add Existing Item from the Project menu in Visual Studio .NET and browse to
TestKPolicyLibrary.dll.
D. Select Add Reference from the Project menu in Visual Studio .NET, select the COM tab, and
browse to TestKPolicyLibrary.dll.
Answer: D
You are creating a Web site for BMW. You receive product lists in the form of XML documents. You are creating a procedure to extract information from these XML documents according to criteria that your users will select.When a user makes a request, you want the results of these requests to be returned as quickly
as possible.What should you do?
A. Create an XmlDataDocument object and load it with the XML data.
Use the DataSet property of the object to create a DataSet object.
Use a SQL SELECT statement to extract the requested data.
B. Create an XmlDataDocument object and load it with the XML data.
Use the SelectNodes method of the object to extract the requested data.
C. Create an XPathDocument object and load it with the XML data.
Call the CreateNavigator method to create an XPathNavigator object.
Call the Select method of the XPathNavigator object to run an XPath query that extracts the
requested data.
D. Create an XmlReader object.
Use the Read method of the object to stream through the XML data and to apply an XPath
expression to extract the requested data.
Answer: C
You company BMW 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?
A. Modify all ASP.NET pages in the application so that the view state is enabled.
B. Modify all ASP.NET pages in the application to add custom logic that conveys the demographic information in either textual or graphical format.
C. Modify all images in the application so that the ToolTip property conveys the same demographic information as the image.
D. Modify all images in the application so that the AlternateText property conveys the same demographic information as the image.
Answer: D
You are developing an ASP.NET application for BMW’s intranet. Employees will use the application to administer their employee benefits. The benefits information is stored in a Microsoft SQL Server database named Benefits.An employee can select benefits options from 10 different drop-down list boxes. The values for each list are stored in separate tables in the Benefits database. The values that are available for employees to choose can change once each year during the benefits enrollment period.You want to minimize the number of times your application must access the Benefits database
to obtain the values for the drop-down list box.Which two courses of action should you take? (Each correct answer presents part of the
solution. Choose two)
A. Create one stored procedure that returns the result for all 10 drop-down list boxes.
Create one DataTable object for each of the 10 drop-down list boxes.
Use a SqlDataReader object to populate 10 DataTable objects by calling the NextResult()
method.
Bind the drop-down list boxes to the DataTable objects.
B. Create a stored procedure that returns the result set for all 10 drop-down list boxes.
Bind the drop-down list boxes to the DataReader object.
C. Create one DataTable object for each of the 10 drop-down list boxes.
Create a stored procedure for each of the 10 tables.
Use a SqlDataReader object to populate the 10 DataTable objects.
Bind the drop-down list boxes to the DataTable objects.
D. Store the result sets for the 10 drop-down list boxes in a DataSet object.
Add the DataSet objects to the Cache object for the application.
E. Store the result sets for the 10 drop-down list bikes in a file on the user’s computer by using
the DataSet.WriteXml() method.
Answer: A, D
You are creating an ASP.NET application that uses role-based security to allow users to access only those pages that they are authorized to access. You use a Microsoft SQL Server database to manage the list of users and roles for the ASP.NET application. A table named Roles contains a column named RoleID and a column named RoleName. A table named Users contains a column named UserID, a column named UserName, and a column named Password.A table named UserRoles contains a column named UserID and a column named RoleID.You need to create a stored procedure that returns all users who belong to a specific role. You
write the following Transact-SQL code to define the stored procedure:
CREATE PROCEDURE GetRoleMembers
@RoleID int
AS
Which code segment should you use to complete the stored procedure?
A. SELECT UserRoles.UserID, Users.UserName
FROM Users
INNER JOIN
Roles UserRoles On UserRoles.RoleID = Users.UserID
WHERE UserRoles.RoleID = @RoleID
B. SELECT UserRoles.UserID, Users.UserName
FROM UserRoles
INNER JOIN
Roles On UserRoles.RoleID = Roles.RoleID, Users
WHERE UserRoles.RoleID = @RoleID
C. SELECT UserRoles.UserID, Users.UserName
FROM UserRoles
INNER JOIN
Users On Users.UserID = UserRoles.UserID
WHERE UserRoles.RoleID = @RoleID
D. SELECT Users.UserID. Users.UserName
FROM Users, UserRoles
INNER JOIN
Roles On UserRoles.RoleID = Roles.RoleID
WHERE UserRoles.RoleID = @RoleID
Answer: C
You are a Web developer for BMW. 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?
A. private string TKGetDisplayValue(double value,string
inputRegion)
{
string display:
RegionInfo region;
region = new RegionInfo(inputRegion);
display = value.ToString(“C”);
display += region.CurrencySymbol;
return display;
}
B. private string TKGetDisplayValue(double value,string
inputCulture)
{
string display;
NumberFormatInfo LocalFormat = (NumberFormatInfo)
NumberFormatInfo.CurrentInfo.Clone();
display = value.ToString(“C”, LocalFormat);
return display;
}
C. private string TKGetDisplayValue(double value,string
inputRegion)
{
string display;
RegionInfo region;
region = new RegionInfo(inputRegion);
display = value.ToString(“C”);
display += region.ISOCurrencySymbol;
return display;
}
D. private string TKGetDisplayValue(double value, string
inputCulture)
{
string display;
CultureInfo culture;
culture = new CultureInfo(inputCulture);
display = value.ToString(“C”, culture);
return display;
}
Answer: D
You are creating an ASP.NET page for the sales department at BMW. 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
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?
A. OnHand = reader.GetInt16(0);
B. OnHand = reader.GetInt16(1);
C. OnHand = reader.GetInt32(0);
D. OnHand = reader.GetInt32(1);
Answer: C
You create an ASP.NET application for an online shopping site. The application uses a Microsoft SQL Server 2000 database named BMWSales. The database contains a stored procedure named getProductsByCategory that returns all products that match a specified category code. The category code is supplied as a parameter named @ProdCode.The application includes a page named ShowProducts.aspx. You are using Visual Studio .NET to debug ShowProducts.aspx.
ShowProducts.aspx uses the getProductsByCategory stored procedure to populate a DataSet object. You set a breakpoint within getProductsByCategory so that you can step through the stored procedure within the debugger.Which you are debugging getProductsByCategory, you need to view the current value of @ProdCode.
What should you do?
A. Open the Locals debugging window.
B. Open the Modules debugging window.
C. Add the following line of code to getProductsByCategory:
Print @ProdCode
Open the Output debugging window and select Debug as the source from the drop-.down list
box.
D. Add the following line of code to getProductsByCategory:
SELECT @ProdCode As DebugOutput
Open the Output debugging window and select Database Output as the source from the dropdown
list box.
Answer: A
You are creating an ASP.NET application for BMW’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)
1 private void WorkDays_Render(object source,
DayRenderEventArgs e)
2 {
3
4 }
Which code should you add at line 3 of the event handler?
A. 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;
}
B. if ((e.Day.Date.Day == 6) && e.DayIsOtherMonth)
{
e.Cell.Controls.Add(new
LiteralControl(“Staff Meeting”));
e.Cell.BackColor = System.Drawing.Color.Yellow;
}
C. if (e.Day.Date.Day == 6)
{
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
You are creating an ASP.NET page for BMW. The company wants to use this page to allow customers to enter their addresses. You create a user control named CustomerAddress. You define this control in a file named CustomerAddress.ascx. You place this file in a folder named AddressControls.You create a page in the same folder to test your control. You add the following directive to the top of your test page:
<%@ Register Tagprefix=”TK” Tagname=”CustomerAddress”
Namespace=”CustomerAddress.ascx” %>
You add the following tag to your test page:
<TK:CustomerAddress runat=”server”/>
When you open the test page, you receive the following error message: “Parser Error –Description: An error occurred during the parsing of a resource required to service this request.”
You need to change the directive to correct this error.Which directive should you use?
A. <%@ Register Tagprefix=”TK” Tagname=”CustomerAddress”
Namespace=”.\AddressControls\CustomerAddress.ascx” %>
B. <%@ Register Tagprefix=”TK” Tagname=”CustomerAddress”
Src=”CustomerAddress.ascx” %>
C. <%@ Register Tagprefix=”TK” Tagname=”CustomerAddress”
Assembly=”CustomerAddress” %>
D. <%@ Reference control=”CustomerAddress.ascx” %>
Answer: B
You create an ASP .NET page for BMW’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=”30”
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?
A. purchaseOrder = e.Item.Cells[1].Text;
B. purchaseOrder = (TextBox)e.Item.Cells[1].Controls[“PONumber”].Text;
C. purchaseOrder = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
D. purchaseOrder = PONumber.Text;
Answer: C
You create an ASP.NET application for online sales site for the BMW Corporation. A page named OrderTKVerify.aspx displays a detailed listing of the items ordered, their quantity, and their unit price. OrderTKVerify.aspx then displays the final order total at the end of the page.The Web Form within OrderTKVerify.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?
A. Modify the HTML element as follows:
<asp:button id=”submitOrderButton” runat=”server”
Text=”Submit Order”
onClick=”verifyBeforeSubmit();”></asp:button>
B. Modify the HTML elements as follows:
<asp:button id=”submitOrderButton” runat=”server”
Text=”Submit Order”
ServerClick=”verifyBeforeSubmit();”></asp:button>
C. Add the following code to the Page.Load event handler for OrderTKVerify.aspx:
submitOrderButton.Attribute.Add(“onclick”,
“verifyBeforeSubmit();”;
D. Add the following code to the Page.Load event handler for OrderTKVerify.aspx:
submitOrderButton.Attribute.Add(“ServerClick”,
“verifyBeforeSubmit();”;
Answer: C
You create an ASP.NET application for BMW. You create an exception class named DataCollisionEx. The exception class is defined in TkNamespace. 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(“TkNamespace.DataCollisionEx”);
ex = Server.GetLastError();
if (ex.GetType().Equals(argExType))
{
Response.Redirect(“DataCollision.aspx”);
}
else
{
Server.ClearError();
}
B. Type argExType;
Exception ex;
argExType = Type.GetType(“TkNamespace.DataCollisionEx”);
ex = Server.GetLastError();
if (ex.GetType().Equals(argExType))
{
Response.Redirect(“DataCollision.aspx”);
}
C. Type argExType;
Exception ex;
argExType = Type.GetType(“TkNamespace.DataCollisionEx”);
ex = Server.GetLastError().InnerException;
if (ex.GetType().Equals(argExType))
{
Response.Redirect(“DataCollision.aspx”);
}
D. Type argExType;
Exception ex;
argExType = Type.GetType(“TkNamespace.DataCollisionEx”);
ex = Server.GetLastError().InnerException;
if (ex.GetType().Equals(argExType))
{
Response.Redirect(“DataCollision.aspx”);
}
else
{
Server.ClearError();
}
Answer: C
You are creating an ASP.NET page for recording contact information for BMW 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?
A. 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.”
B. 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.”
C. 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.”
D. 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
You create an ASP.NET application for BMW 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 encapsulate 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: <h2>BMW</h2> You need to write code in the CompanyName class to display the company header.Which code should you use?
A. protected override void Render(
HtmlTextWriter output)
{
output.Write(“<h2>BMW</h2>”);
}
B. protected override void OnPreRender(
EventArgs e)
{
this.Controls.Add(new
LiteralControl(“<h2>BMW</h2>”));
}
C. protected override void RenderChildren(
HtmlTextWriter output)
{
output.Write(“<h2>BMW</h2>”);
}
D. protected override void OnInit(EventArgs e)
{
this.Controls.Add(new
LiteralControl(“<h2>BMW</h2>”);
}
Answer: A
You create an ASP.NET application for BMW. Your application contains a method named nextBusinessDay. This method uses a date parameter and returns the next date that is not a holiday or weekend day.You are debugging a page named ProjectTimeLine.aspx. You need the execution to break on the following line of code when the value of the dStartDate variable changes:dStartDate = nextBusinessDay(dStartDate);What should you do?
A. Set a breakpoint on the line of code and open the BreakPoint Properties dialog box.
Specify the following breakpoint condition:
dStartDate !=dStartDate
Select the is true option.
B. Set a breakpoint on the line of code and open the BreakPoint Properties dialog box.
Specify the following breakpoint condition:
dStartDate
Select the has changed option.
C. Add the following statement immediately after the call to nextBusinessDay:
System.Diagnostics.Debug.Assert(
dStartDate !=dStartDate, “dStartDate has changed.”;
D. Add the following statement immediately after the call to nextBusinessDay:
System.Diagnostics.Trace.Assert(
dStartDate !=dStartDate, “dStartDate has changed.”;
Answer: B
You create an ASP.NET page that retrieves product information from a Microsoft SQL Server database named TestKiDB. 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?
A. repeaterProducts.DataSource = dt;
repeaterProducts.DataBind();
da.Fill(dt);
B. da.Fill(dt);
repeaterProducts.DataBind();
repeaterProducts.DataSource = dt;
C. repeaterProducts.DataBind();
da.Fill(dt);
repeaterProducts.DataSource = dt;
D. da.Fill(dt);
repeaterProducts.DataSource = dt;
repeaterProducts.DataBind();
Answer: D
You are a Web developer for a BMW bookstore. You create a Web user control named TkBookTopics that is defined in a file named TkBookTopics.ascx. TkBookTopics 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 TkBookTopics named AuthorProfile.You create an ASP.NET page named AuthorPage.aspx that contains an instance of the TkBookTopics 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 TkBookTopics 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?
A. Add the following element to the OutputCache directive for AuthorPage.aspx:
VaryByParam=”TkBookTopics.AuthorProfile”
B. Add the following element to the OutputCache directive for AuthorPage.aspx:
VaryByControl=”TkBookTopics.AuthorProfile”
C. Add the following element to the OutputCache directive for TkBookTopics.ascx:
VaryByParam=”none”
D. Add the following element to the OutputCache directive for TkBookTopics.ascx:
VaryByControl=”authorProfileID”
Answer: D
You create an ASP.NET application to keep track of BMW’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 TestKiEmployeeStatus 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 TestKiEmployeeStatus is as follows:
<asp:repeater id=”TestKiEmployeeStatus” 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 TestKiEmployeeStatus. 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)
A. Add the following HTML code to the ItemTemplate element of TestKiEmployeeStatus:
<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”]);
}
B. Add the following HTML code to the Item Template element of TestKiEmployeeStatus:
<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”]));
}
C. Add the following HTML code to the ItemTemplate element of TestKiEmployeeStatus:
<asp:Button id=”changeStatusButton” Runat=”Server”
Text=”Change Status”
CommandArgument=<%# Container.DataItem[“EmployeeID”]%>
/>
Add the following code to the ItemCommand event of TestKiEmployeeStatus:
if (source.id == “changeStatusButton”)
{
ChangeInOutStatus(
(int)e.CommandSource.CommandArgument);
}
D. Add the following HTML code to the ItemTemplate element of TestKiEmployeeStatus:
<asp:Button id=”changeStatusButton” Runat=”server”
Text=”Change Status”
CommandArgument=<%# Container.DataItem[“EmployeeID”]%>
/>
Add the following code to the ItemCommand event of TestKiEmployeeStatus:
if (e.CommandSource.id == “changeStatusButton”)
{
ChangeInOutStatus((int)e.CommandArgument);
}
Answer: B, D
You are creating an ASP.NET application that performs updates to a database named BMWDB. The application performs the updates by running a series of SQL statements.You write a procedure to run the SQL statements. The procedure accepts a connection string and an array of SQL statement as parameters.You use structured exception handling in your procedure to handle any errors that occur while the statements are running. You want the procedure to terminate after handling an exception and to return the SQL statement that caused the exception. You also want to ensure that the database connection is closed before the procedure terminates, whether or not an error occurs.You begin writing the procedure by using the following code:
public static void ExecuteStatements(
string connectionString, string[] sql)
{
OleDbConnection cnn =
new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
int i;
cmd.Connection = cnn;
cnn.Open();
try
{
for (i=0; i <= sql.Length – 1; i++)
{
cmd.CommandText = sql[i];
cmd.ExecuteNonQuery();
}
}
Which code segment should you use to complete the procedure?
A. catch(OleDbException ex)
{
throw(ex);
}
finally
{
cnn.Close();
}
}
B. catch(OleDbException ex)
{
throw(new Exception(sql[i], ex));
}
finally
{
cnn.Close();
}
}
C. catch(OleDbException ex)
{
throw(ex);
}
}
cnn.Close();
D. catch(OleDbException ex)
{
throw(new Exception(sql[i], ex));
}
}
cnn.Close();
Answer: B
You create an ASP.NET page that contains a DataGrid control. The control displays data that is retrieved from a database named BMWDB. 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
You 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 ValidateTKRole that has three arguments. The argument named User is the user name, the argument named Role1 is the first role to verify, and the argument named Role2 is the second role to verify. You want ValidateTKRole to return a value of true if the specified user has membership in either of the specified roles.You write the following code:
PrincipalPermission principalPerm1 =new PrincipalPermission(“User”, “Role1”);
PrincipalPermission principalPerm2 =new PrincipalPermission(“User”, “Role”);
Which code segment should you use to complete the function?
A. return principalPerm1.IsUnrestricted() && principalPerm2.IsUnrestricted();
B. return principalPerm1.IsSubsetOf(principalPerm2);
C. return principalPerm1.Intersect(principalPerm2).Demand();
D. return principalPerm1.Union(principalPerm2).Demand();
Answer: D
You create a class named TKFormat that has two public properties. One of the properties is named Size, and the other property is named Color. You want to use the TKFormat 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 TKFormat _formatter = new TKFormat();
public TKFormat 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=”testkctl” 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 10
and the color property is set to red.
Which code should you use?
A. <testkctl:MessageRepater Format-Color=”red”
Format-Size=”10” />
B. <testkctl:MessageRepater Format-Color=”red”
Format-Size=”10” runat=”server” />
C. <testkctl:MessageRepater Color=”red”
Size=”10” runat=”server” />
D. <testkctl:MessageRepater Format=”Color:red;size:10” />
Answer: B
You Create an ASP.NET application for a bank. The application provides account management functionality.A page named AccountWithdrawal.aspx contains a method named WithdrawFunds. The WithdrawFunds method is defined in the following code segment. (Line numbers are included for reference only)
1 private double WithdrawFunds(double Amount)
2 {
3
4 m_dAccountBalance -= Amount;
5 return m_dAccountBalance;
6 }
The callers of this method need to verify that sufficient funds exist in the account before
attempting the withdrawal. During unit testing, you want to receive notification when a call is
made requesting a withdrawal amount for which the account does not have sufficient funds
available.
You plan to build the production version of your application by using the Release Build
Configuration in Visual Studio .NET. You need the testing instrumentation to be included but
not enabled in the application when the application is deployed to production. You need to
have the ability to enable the instrumentation after deploying it to production without
requiring the application to be rebuilt.
Which code should you insert at line 3 of the code segment?
A. Debug.Assert(m_dAccountBalance – Amount >=0,
“Insufficient funds for withdrawal.”);
B. Trace.Assert(m_dAccountBalance – Amount >=0,
“Insufficient funds for withdrawal.”);
C. Debug.WriteLine(m_dAccountBalance – Amount >=0,
“Insufficient funds for withdrawal.”);
D. Trace.WriteLineIf(m_dAccountBalance – Amount >=0,
“Insufficient funds for withdrawal.”);
Answer: B
You are creating an ASP.NET application for BMW’s Travel. BMW’s Travel uses a Microsoft SQL Server 2000 database to store information about vacation packages. Your application will allow a user to request information about vacation packages for a specific destination.You want to display this data to the user in a DataGrid. You want the data to be displayed in read-only form. The user’s travel destination is contained in a form level string variable named
destinationCode. In your Page.Load event handler, you create a SqlConnection object named SqlConnection1, initialize it, and call its Open() method. When your code runs the query, you want the data to be returned as quickly as possible. You define the following local variable to hold the destination code:
string dest = destinationCode; What should you do?
A. Create a stored procedure named GetDestinations and then use the following code to retrieve
the data:
SqlCommand cmd =
new SqlCommand(“GetDestinations”,
sqlConnection1);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm =
new SqlParameter(“@DestinationCode”, dest);
cmd.Parameters.Add(parm);
SqlDataReader sqlDataReader1 = cmd.ExecuteReader();
B. Create a stored procedure named GetDestinations and then use the following code to retrieve
the data:
string qry =
“EXEC GetDestinations WHERE DestID = “ + dest + “”;
SqlDataAdapter da =
new SqlDataAdapter(qry, sqlConnection1);
DataSet ds = new DataSet();
da.Fill(ds);
C. Use the following code to retrieve the data:
string qry =
“SELECT * FROM Destination WHERE DestID =
“ + dest + “”;
SqlCommand cmd = new SqlCommand(qry,
sqlConnection1);
cmd.CommandType = CommandType.Text;
SqlDataReader sqlDataReader1 = cmd.ExecuteReader();
D. Use the following code to retrieve the data:
string qry =
“SELECT * FROM Products WHERE DestID = @DestID”;
SqlCommand cmd = new SqlCommand(qry;
sqlConnection1);
cmd.CommandType = CommandType.Text;
SqlParameter parm = new SqlParameter(“@DestID”,
dest);
cmd.Parameters.Add(parm);
SqlDataReader sqlDataReader1 = cmd.ExecuteReader();
Answer: A
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 TkNewsItems, 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 TkNewsItems in HTML format. You write the following code segment:
XmlDataDocument doc = new XmlDataDocument(TkNewsItems);
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?
A. tran.Transform(doc, null, Response.OutputStream);
B. tran.Transform(doc, null, Request.InputStream);
C. TkNewsItems.WriteXml(Response.OutputStream);
D. TkNewsItems.WriteXml(tran.ToString());
Answer: A
You are a Web developer for a travel company called BMW 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);
}
B. 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;
}
C. 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
}
D. 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
You create an ASP.NET application for BMW 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)
A. Add the following code to the vehicleIDNumber.TextChanged event handler for InsuredAuto.aspx:
vehicleIDNumber.Text = vehicleIDNumber.Text.ToUpper();
B. Add the following code to the submitButton.Click event handler for InsuredAuto.aspx:
vehcicleIDNumber.Text = vehicleIDNumber.Text.ToUpper();
C. 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
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 timeTKLabel. The timeTKLabel 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 predefines styles are created in the following function:
public Style GetStyle(int styleType)
{
Style myStyle = new Style();
switch (styleType)
{
case 1:
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?
A. public void PickStyle(int styleType)
{
Style myStyle = GetStyle(styleType);
timeTKLabel.ApplyStyle(myStyle);
}
B. public void PickStyle(int styleType)
{
Style myStyle = GetStyle(styleType);
timeTKLabel.MergeStyle(myStyle);
}
C. public void PickStyle(int styleType)
{
Style myStyle = GetStyle(styleType);
timeTKLabel.ForeColor = myStyle.ForeColor;
timeTKLabel.BackColor = myStyle.BackColor:
}
D. public void PickStyle(int styleType)
{
Style myStyle = GetStyle(styleType);
timeTKLabel.CssClass = myStyle.CssClass;
}
Answer: B
You create an ASP.NET application for a consulting company BMW Insurance. BMW uses the application to perform time tracking and to generate billing invoices. The accounts receivable department uses a page named PrepareInvoices.aspx to issue invoices to clients at the end of each month.During testing of the application, you discover that some invoices are being generated with negative values for the total amount due. The total amount due is calculated within a function named CalculateTotalDue, which is defined in the PrepareInvoices.aspx page. The call to CalculateDue is contained in the following code segment from PrepareInvoices.aspx. (Line numbers are included for reference only)
1 double TotalAmountDue;
2 totalAmountDue = CalculateTotalDue();
3 totalAmountDue -= totalAmountDue * discountRate;
You need to stop execution of the code within PrepareInvoices.aspx and enter the interactive debugger when CalculateTotalDue returns a negative value.What should you do?
A. Modify the code segment as follows:
double totalAmountDue;
totalAmountDue = CalculateTotalDue();
System.Diagnostics.Debug.Assert(totalAmountDue >= 0);
totalAmountDue -= totalAmountDue * discountRate;
B. Modify the code segment as follows:
double totalAmountDue;
totalAmountDue = CalculateTotalDue();
totalAmountDue -= totalAmountDue * discountRate;
System.Diagnostics.Debug.Assert(totalAmountDue >= 0);
C. In the Watch window, add a watch expression of totalAmountDue < 0, and select the Break
When Value Is True option.
D. Set a breakpoint on line 3 of the code segment.
Define a condition for the breakpoint to break when totalAmountDue < 0 is true.
E. Set a breakpoint on line 2 of the code segment.
Define a condition for the breakpoint to break when totalAmountDue < 0 is true.
Answer: D
You create an ASP.NET application for tracking student examinations at the local BMW Certification school. You use Microsoft Windows authentication. Students are members of a group named Students, and teachers are members of a group named Teachers.The root folder for your application is named Exams. The Exams folder displays information about pending examinations. The Exams folder has a subfolder named Grades. Both Students and teachers can access pages in Exams. Only teachers can access page in Grades. You create the following entries in the Web.config file in Exams. (Line numbers are included for reference only)
1 <authentication mode=”Windows” />
2 <authorization>
3 <allow roles=”Students, Teachers” />
4 <deny users=”*” />
5 </authorization>
You crate the following entries in the Web.config file in Grades. (Line numbers are included for reference only.)
1 <authentication mode=”Windows” />
2 <authorization>
3 <allow roles=”Teachers” />
4 <deny users=”*” />
5 </authorization>
When teachers try to access pages in the Grades folder, they receive an error message that reads in part: “An error occurred during the processing of a configuration file required to service this request.” You need to ensure that teachers can access pages in the Grades folder.What should you do?
A. Remove line 1 in the Web.config file in Grades.
B. Modify line 4 in the Web.config file in Grades as follows:
<allow users=”*” />
C. Add the following line between line 1 and line 2 in the Web.config file in Exams:
<identity impersonate=”true” />
D. Add the following line between line 1 and line 2 in the Web.config file in Grades:
<identity impersonate=”true” />
E. Add the following line between line 1 and line 2 in the Web.config file in Grades:
<identity impersonate=”false” />
Answer: A
You are a Web developer for a museum. The museum has a Microsoft SQL Server database that contains information about science experiments. The database currently contains information on 5,000 experiments. The information is updated monthly.You are creating an ASP.NET application for users to find information about specific experiments. The application will run on a server that is connected to the database by a lowbandwidth leases line.You want to accomplish the following two goals:
• Minimize the number of times the application accesses the database.
• Minimize the time required for each page of the application to load.
What should you do?
A. Initialize the DataSet object in the Page.Load event handler when the IsPostBack property is false.Store the DataSet object in an XML file on the user’s computer.
B. Create a Cache object for the application and add the DataSet object to the cache.
C. Use the view state to maintain the DataSet object during postback events to the server.
D. Create a Cache object for the session and add the DataSet object to the cache.
Answer: B
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 BMWSQL1. 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 tkDataView 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:
tkDataView:
dataGridCurrentYear.DataSource = tkDataView;
tkDataView.RowFilter = “OrderDate >= #01/01/”+Now.Year + “#”
dataGridCurrentYear.DataBind();
dataGridPreviousYears.DataSource = tkDataView;
tkDataView.RowFilter = “OrderDate < #01/01/”+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?
A. Remove the Page.DataBind() statement.
B. Remove the dataGridPreviousYears.DataBind() statement.
C. Add a Response.Flush() statement immediately before the Page.DataBind() statement.
D. Add a Response.Flush() statement immediately before the dataGridPreviousYears.DataBind() statement.
Answer: A
You create an ASP.NET application for BMW. This application will display information about products that the company sells. The application uses a Microsoft SQL Server database.You add two DropDownList controls to your .aspx page. One drop-down list box will display product information. The control for this drop-down list box is named Products. The other drop-down list box will display category information. The control for this drop-down lost box is named Category. You have an open SqlConnection object named con.The Page.Load event handler uses the following code segment to populate the drop-down list boxes by binding the SqlDataReader. (Line numbers are included for reference only)
01 SqlCommand cmd1 = new SqlCommand(“SELECT * FROM
Products”,con);
02 SqlDataReader dr1 = cmd1.ExecuteReader();
03 Products.DataTextField = “ProductName”;
04 Products.DataValueField = “ProductID”;
05 Products.DataSource = dr1;
06 Products.DataBind();
07 cmd1.CommandText = “SELECT * FROM Category”;
08 SqlDataReader dr2 = cmd1.ExecuteReader();
09 Category.DataTextField = “CategoryName”;
10 Category.DataValueField = “CategoryID”
11 Category.DataSource = dr2;
12 Category.DataBind();
During testing, the page raises an invalid operation exception. You need to ensure that the page displays correctly without raising an exception.What should you do?
A. Replace the code for line 02 of the code segment with the following code:
dr1.ExecuteReader(CommandBehavior.CloseConnection;
B. Add the following code between line 06 and line 07 of the code segment:
dr1.Close();
C. Replace the code for line 07 and line 08 of the code segment with the following code:
SqlCommand cmd2 = new SqlCommand(“SELECT * FROM Category”,con);
SqlDataReader dr2 = cmd2.ExecuteReader();
D. Remove the code for line 06 of the code segment.
Replace the code for line 12 of the code segment with the following code:
Page.DataBind();
Answer: B
You are creating an ASP.NET application for an online banking site. You need to allow customers to transfer funds between accounts. You write a component in Visual C# .NET to handle transfer of funds. This component is used by the page named FundsTransfer.aspx. For unit testing, you add the following code segment to the TransferFunds method of your component. (Line numbers are included for reference only)
1 HttpContext ctx;
2 ctx = HttpContext.Current;
3 ctx.Trace.Write(“Funds transfer requested.”;
You want to be able to view the trace output on the FundsTransfer.aspx page.What should you do?
A. Add code to the FundsTransfer.aspx page that instantiate a Trace listener.
B. Enable tracing in the Page directive for the FundsTransfer.aspx page.
C. Add the following attribute to the Machine.config file:
<trace enabled=”true”>
D. Modify line 3 of the code segment as follows:
System.Diagnostics.Trace.WriteIf(
ctx.IsDebuggingEnabled, “Funds transfer requested.”);
Answer: B
You develop an application that generates random numbers to test statistical data. The application uses the following code:
Random rnd = new Random();
short num1 = Convert.ToInt16(rnd.Next(35000));
short num2 = Convert.ToInt16(rnd.Next(35000));
short num3 = Convert.ToInt16(num1 / num2);
When you test the application, you discover that certain exceptions are sometimes raised by this code. You need to write additional code that will handle all such exceptions. You want to accomplish this goal by writing the minimum amount of code.Which code segment should you use?
A. try { // Existing code goes here. }
catch(DivideByZeroException e) { // Insert error-handling code. }
catch (OverflowException e) { // Insert error-handling code. }
catch (NotFiniteNumberException e) { // Insert error-handling
code. }
B. try { // Existing code here goes. }
catch (ArithmeticException e){ // Insert error-handling code. }
C. try { // Existing code goes here. }
catch (DivideByZeroException e)
{ // Insert error-handling code. }
catch (OverflowException e) { // Insert error-handling code. }
D. try { // Existing code goes here. }
catch (OverflowException e) { // Insert error-handling code. }
Answer: B
You are maintaining an ASP.NET application. Another developer at BMW wrote the following code for the WebForm1.aspx file:
<%@ Page language=”c#” Codebehind=”WebForm1.aspx.cs”
Inherits=”WebForm1”%>
<HTML>
<body MS_POSITIONING=”GridLayout”>
<form id=”Form1” method=”post” runat=”server”>
<asp:Button id=”Button1” style=”Z-INDEX: 101;
LEFT: 203px; POSITION: absolute; TOP: 206px”
runat=”server” Text=”Submit” Width=”132pk”
Height=”25px”></asp:Button>
</form>
</body>
</HTML>
You are debugging the application and set a breakpoint in the Page.Load event handler. You notice that when you click the Submit button, the application stops at your breakpoint twice for each time that you click the button.You need to ensure that you stop at the breakpoint only once for each time that you click the Submit button.What should you do?
A. Add the following attribute to WebForm1.aspx: smartNavigation=”true”
B. Add the following attribute to WebForm1.aspx: smartNavigation=”false”
C. Add the following attribute to the Page directive: AutoEventWireup=”true”
D. Add the following attribute to the Page directive: AutoEventWireup=”false”
Answer: D
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)
A. Add the following statement to the declaration section of ListSubscribe.ascx:
public TextBox listNameText:
B. Add the following statement to the declaration section of Subscribe.aspx:
public TextBox listNameText:
C. Add the following statement to the Page.Load event handler for Subscribe.aspx:
if (!Page.IsPostBack)
{
listNameLabel.Text = ctlSubscribe.listNameText.Text;
}
D. Add the following statement to the Page.Load event handler for Subscribe.aspx:
if (Page.IsPostBack)
{
listNameLabel.Text = ctlSubscribe.listNameText.Text;
}
E. Add the following statement to the Page.Load event handler for ListSubscribe.ascx:
if (!Page.IsPostBack)
{
listNameLabel.Text = listNameText.Text;
}
F. Add the following statement to the Page.Load event handler for ListSubscribe.ascx:
if (Page.IsPostBack)
{
listNameLabel.Text = listNameText.Text;
}
Answer: A, D
You are creating an ASP.NET page that presents data to users in an updatable DataGrid control. Users update data in the grid. Your code uses the System.Data namespace and the System.Data.OleDb namespace.Data changes are saved in an ADO.NET DataTable object. You want a user’s changes to be saved to a database when the user finishes making changes. You write the following procedure to accomplish this task:
string sql, string connectionString, DataTable dataTable)
{
OleDbDataAdapter da = new OleDbDataAdapter();
OleDbConnection cnn =
new OleDbConnection(connectionString);
dataTable.AcceptChanges();
da.UpdateCommand.CommandText = sql;
da.UpdateCommand.Connection = cnn;
da.Update(dataTable);
da.Dispose();
}
This code runs to completion, but no data changes appear in the database. You test the update query and the connection string that you are passing to the procedure, and they both work correctly.You need to alter the code to ensure that data changes appear in the database.What should you do?
A. Add the following two lines of code before calling the Update method:
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
cb.GetUpdateCommand();
B. Add the following line of code before calling the Update method:
da.UpdateCommand.Connection.Open();
C. Delete thus line of code:
dataTable.AcceptChanges();
D. Delete this line of code:
da.Dispose();
Answer: C
You are creating a DataGrid control named TKGrid 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)
1 private void TKGrid_EditCommand(object s,
DataGridCommandEventArgs e)
}
2
3 }
Which code should you add at line 2 of the event handler?
A. TKGrid.EditItemIndex = e.Item.ItemIndex;
B. TKGrid.DataKeyField = e.Item.AccessKey;
C. TKGrid.SelectedIndex = e.Item.ItemIndex;
D. TKGrid.CurrentPageIndex = e.Item.ItemIndex;
Answer: A
You are creating an ASP.NET Web Form that displays employee data from a DataSet object.You want to fill the DataSet object and then you want to retrieve a reference to the employee whose primary key has the value of 1.You write the following code. (Line numbers are included for reference only)
01 SqlConnection(ConnectionString);
02 conn.Open();
03 SqlCommand cmd = new SqlCommand
(“SELECT * FROM Employees”, conn);
04 SqlDataAdapter da = new
SqlDataAdapter(cmd);
05 DataSet ds = new DataSet();
06
07 da.Fill(ds, “Employees”);
08
09 DataRow dr;
10 dr = ds.Tables[“Employees”].Rows.Find(1);
11 nameLabel.Text = dr[“Name”].ToString();
When you run the code, you receive the following error message at line 10: “Table doesn’t have a primary key.” You ensure that a primary key is defined on the Employees table in the database. You want to alleviate the error to allow the code to run correctly. You also want to catch the exception that would occur if the employee whose primary key has the value if 1 is deleted from the database.Which two actions should you take? (Each correct answer presents part of the solution. Choose
two)
A. Add the following code at line 06:
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
B. Add the following code at line 06:
da.MissingSchemaAction = MissingSchemaAction.Add;
C. Add the following code at line 06:
da.MissingSchemaAction = MissingSchemaAction.Ignore;
D. Add the following code at line 06:
da.MissingSchemaAction = MissingSchemaAction.Error;
E. Place line 07 in a structured exception handling block.
F. Place lines 10 and 11 in a structured exception handling block.
Answer: A, F
You are creating an ASP.NET page to enroll new members in a health care program for BMW employees. One of the requirements for membership is that a participant must be at least 65 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
No comments:
Post a Comment