Thursday, March 25, 2010

.NET 4 ASP.NET Web Dev 70-515 exam prep ‘real world exam questions’ Catto Crackin Code #8

Hey Now Everybody,

In this 8th post of the Catto Code Crackin series we’ll continue with the section ‘real world exam question concepts’. In the .NET 3.5  * the .NET 4 exam there are questions. Let’s inspect some concepts & properties that will be the skills measured.

        Microsoft announced the .NET 4.0 Beta Exams on St. Patrick’s Day which are a free exam & if passed you get certified. Much of the study & prep materials are not available yet, therefore I’ve been studying for a similar exam 70-562 which is the .NET 3.5 ASP.NET Application Development. I hope by posting this content it will help myself along with other people in the community learn & get excited about .NET 4. If you are serious about studying for a MS Exam 2 must have resources: the Self Paced training books are a great books to buy along with practice exams from eBay.

Here are some real world exam concepts I’d like to think about. In the future I was thinking a CodePlex project(*s) of all these examples would be killer so someday maybe that would be great.

 

QUESTION 1  OnItemDataBound LineTotal Condition

A Web page that contains the following two XML fragments.
01 <script runat="server">
02
03 </script>
04 <asp:ListView ID="ListView1" runat="server"
05 DataSourceID="SqlDataSource1"
06
07 >
08 <ItemTemplate>
09 <td>
10 <asp:Label ID="LineTotalLabel" runat="server"
11 Text='<%# Eval("LineTotal") %>' />
12 </td>
13 </ItemTemplate>

The database table has a column named LineTotal. 
ensure that when the size of the LineTotal column value is greater than seven characters,
the column is displayed in red color.

A. Insert the following code segment at line 06.
OnItemDataBound="FmtClr"

Insert the following code segment at line 02.
protected void FmtClr (object sender, ListViewItemEventArgs e) {
Label LineTotal = (Label)
e.Item.FindControl("LineTotalLabel");
if ( LineTotal.Text.Length > 7)
{ LineTotal.ForeColor = Color.Red; }
else
{ LineTotal.ForeColor = Color.Black; }

QUESTION 2 - Repeater Item FindControl
A Web form code:
<asp:Repeater ID="rptData" runat="server" DataSourceID="SqlDataSource1"ItemDataBound="rptData_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("QuantityOnHand") %>' />
</ItemTemplate>
</asp:Repeater>
The SqlDataSource retrieves the Quantity column values
from a table named Products.
The rptData_ItemDataBound event handler:

01 protected void rptData_ItemDataBound(object sender,
02 RepeaterItemEventArgs e)
03 {
04
05 if(lbl != null)
06 if(int.Parse(lbl.Text) < 10)
07 lbl.ForeColor = Color.Red;
08 }
You need to retrieve a reference to the lblQuantity Label control into a variable named lbl.
The code segment you insert at line 04 is

B. Label lbl = e.Item.FindControl("lblQuantity") as Label;

QUESTION 3 - Dynamically add usercontrol
Uuser control named UserCtrl.ascx. page named Default.aspx.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html> ...
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblHeader" runat="server"></asp:Label>
<asp:Label ID="lbFooter" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
dynamically add the UserCtrl.ascx control between the lblHeader and lblFooter Label controls.

D. Add a PlaceHolder control named PlHldr between the lblHeader and lblFooter label controls.
Write the following code segment in the Init event of the Default.aspx Web page.
Control ctrl = LoadControl("UserCtrl.ascx"); PlHldr.Controls.Add(ctrl);

QUESTION 4 - LoadViewState
You create two user controls named UserCtrlA.ascx and UserCtrlB.ascx.
The user controls postback to the server.
aspx code:
<asp:CheckBox ID="Chk" runat="server" oncheckedchanged="Chk_CheckedChanged" AutoPostBack="true" />
<asp:PlaceHolder ID="PlHolder" runat="server"></asp:PlaceHolder>
To dynamically create the user controls, you write the following code segment for the Web page.
public void LoadControls() {
if (ViewState["CtrlA"] != null) {
Control c; if ((bool)ViewState["CtrlA"] == true) {
c = LoadControl("UserCtrlA.ascx");
} else
{
c = LoadControl("UserCtrlB.ascx");
}
c.ID = "Ctrl"; PlHolder.Controls.Add(c); }
}
protected void Chk_CheckedChanged(object sender, EventArgs e)
{
ViewState["CtrlA"] = Chk.Checked; PlHolder.Controls.Clear(); LoadControls();
}
ensure that the user control that is displayed meets the following requirements:
It is recreated during postback It retains its state.
you should add the following method

D. protected override void LoadViewState(object savedState) {
base.LoadViewState(savedState); LoadControls(); }
Answer: D

QUESTION 5 - OrderFormData
You create the following controls:

A composite custom control named MyControl.
A templated custom control named OrderFormData.
The following code segment to override the method named CreateChildControls() in the MyControl class.
01 protected override void
02 CreateChildControls() {
03 Controls.Clear();
04 OrderFormData oFData = new
05 OrderFormData("OrderForm");
06
07 }
Add the OrderFormData control to the MyControl control.
code segment inserted at line 6

B. Template.InstantiateIn(oFData); Controls.Add(oFData);

QUESTION 6  Custom Control

OrderFormData
A composite custom control named MyControl.
add an instance of the OrderFormData control to the MyControl control.
use the code segment:

A. protected override void CreateChildControls() {
Controls.Clear();
OrderFormData oFData = new OrderFormData("OrderForm");
Controls.Add(oFData);
}

QUESTION 7     method to raise CheckOrderForm event
created a custom control named OrderForm.
Code:
public delegate void CheckOrderFormEventHandler(EventArgs e); private static readonly object CheckOrderFormKey = new object();
public event CheckOrderFormEventHandler CheckOrderForm
{
add { Events.AddHandler(CheckOrderFormKey, value); }
remove { Events.RemoveHandler(CheckOrderFormKey, value); }
}
You need to provide a method that enables the OrderForm control to raise the CheckOrderForm event.
USe the following code segment:

B. protected virtual void OnCheckOrderForm(EventArgs e) {
CheckOrderFormEventHandler checkOrderForm = Events[CheckOrderFormKey] as CheckOrderFormEventHandler;
if (checkOrderForm != null) checkOrderForm(e); }

QUESTION 8.    Validation customValidator, CompareValidator ValueToCompare property
Add a TextBox control named TextBox1.
code  for validation.
protected void CustomValidator1_ServerValidate( object source, ServerValidateEventArgs args) {
DateTime dt = String.IsNullOrEmpty(args.Value)
DateTime.Now : Convert.ToDateTime(args.Value);
args.IsValid = (DateTime.Now - dt).Days < 10;
}
validate the value of TextBox1.
The following code should be added to the page:
A. <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1" ValidateEmptyText="True"
onservervalidate="CustomValidator1_ServerValidate"> </asp:CustomValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" Type="Date" EnableClientScript="true" ControlToValidate="TextBox1"
Operator="DataTypeCheck" >
</asp:CompareValidator>

QUESTION 9      -  Override Method Validates
Derive a new validation control from the BaseValidator class.
The validation logic for the control is implemented in the Validate method
.
protected static bool Validate(string value) { ...
}
Override the method that validates the value of the related control by the following :

C. protected override bool EvaluateIsValid()
    { string value = GetControlValidationValue(this.ControlToValidate); bool isValid = Validate(value); return isValid; }

QUESTION 10     Bulleted List  DataSourceID property
XmlDataSource control named XmlDataSource1
XmlDataSource1 is bound to an XML document with the following structure.
<?xml version="1.0" encoding="utf-8" ?>
<clients>
<client ID="1" Name="John Evans" />
<client ID="2" Name="Mike Miller"/> ...
</clients>
page.cs
protected void BulletedList1_Click( ?object sender, BulletedListEventArgs e) { //...
}
add a BulletedList control named BulletedList1 to the Web page that is bound to XmlDataSource1.
Use the following code:

C. <asp:BulletedList ID="BulletedList1" runat="server" DisplayMode="LinkButton" DataSourceID="XmlDataSource1" DataTextField="Name" DataValueField="ID"
onclick="BulletedList1_Click"> </asp:BulletedList>

q11
11
QUESTION 11 Selected List moved from ListboxA to Listbox B
<asp:ListBox SelectionMode="Multiple" ID="ListBox1" runat="server"> </asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server"> </asp:ListBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Ensure that when you click the Button1 control, a selected list of items move from the ListBox1 control to the ListBox2 control.

C. foreach (ListItem li in ListBox1.Items) { if (li.Selected) { li.Selected = false; ListBox2.Items.Add(li); }
}
D. foreach (ListItem li in ListBox2.Items) { if (ListBox1.Items.Contains(li)) ListBox1.Items.Remove(li); }

12
QUESTION 12 DDL Multiview ActiveViewIndex property

<asp:DropDownList AutoPostBack="true" ID="DropDownList1" runat="server" onselectedindexchanged= "DropDownList1_SelectedIndexChanged">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
A MultiView control named MultiView1 to the Web page. MultiView1 has three child View controls.
Ensure that you can select the View controls by using the DropDownList1 DropDownList control.

A. int idx = DropDownList1.SelectedIndex; MultiView1.ActiveViewIndex = idx;

13 Calendar contorl Non Weekday is selectable false

<asp:Calendar SelectionMode="DayWeek" ID="Calendar1" runat="server"> </asp:Calendar>

Disable the non-week days in the Calendar control.

A. Add the following code segment to the Calendar1 DayRender event handler.

if (e.Day.IsWeekend) {
Day.IsSelectable = false;
}

14

QUESTION 14 XML Serializer

Define the following class.
public class Product {
public decimal Price { get; set; }
}
Application contains a Web form, a Label control named lblPrice.
You use a StringReader variable named xmlStream to access the following XML fragment.
<Product>
<Price>35</Price>
</Product>
Display the price of the product from the XML fragment in the lblPrice Label control.

C. XmlSerializer xs = new XmlSerializer(typeof(Product));
Product boughtProduct = xs.Deserialize(xmlStream) as Product;
lblPrice.Text = boughtProduct.Price.ToString();

15
QUESTION 15 Sorting Gridview SqlDataAdapter

<asp:GridView ID="gvProducts" runat="server" AllowSorting="True" DataSourceID="Products"> </asp:GridView>
<asp:ObjectDataSource ID="Products" runat="server" SelectMethod="GetData" TypeName="DAL" /> </asp:ObjectDataSource>

Code segment for the GetData method of the DAL class:
01 public object GetData() {
02 SqlConnection cnn = new SqlConnection( )
03 string strQuery = "SELECT * FROM Products";
04
05 }
Ensure that the user can use the sorting functionality of the gvProducts GridView control.
insert at line 04?

C. SqlDataAdapter da = new SqlDataAdapter(strQuery, cnn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;

16 Fill DataSet - List always avaiablve from Cashe Object
You create a class
01 public object GetCachedProducts(sqlConnection conn) {
02
03 if (Cache["products"] == null) {
04 SqlCommand cmd = new SqlCommand(
05 "SELECT * FROM Products", conn);
07 conn.Open();
08 Cache.Insert("products", GetData(cmd));
09 conn.Close();
10 }
11 return Cache["products"];
12 }
13
14 public object GetData(SqlCommand prodCmd) {
15
16 }

Each time a Web form has to access a list of products, the GetCachedProducts method is called to provide this list from the Cache object.
Ensure that the list of products is always available in the Cache object.
You insert at line 15 the following code:

D. SqlDataAdapter da = new SqlDataAdapter(prodCmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;

17 SQLDataReader.NextResult() & DataBindings
01 string strQuery = "select * from Products;"
02 + "select * from Categories";
03 SqlCommand cmd = new SqlCommand(strQuery, cnn);
04 cnn.Open();
05 SqlDataReader rdr = cmd.ExecuteReader();
06
07 rdr.Close();
08 cnn.Close();

Ensure that the gvProducts and gvCategories GridView controls display the data that is contained in the following two database tables:
The Products database tabl
The Categories database tabl

You insert at line 06 the following code:
D. gvProducts.DataSource = rdr;
gvCategories.DataSource = rdr;
gvProducts.DataBind();
rdr.NextResult();
gvCategories.DataBind();

18. Sorting Grid from Session
page.aspx:
<asp:TextBox runat="server" ID="txtSearch" />
<asp:Button runat="server" ID="btnSearch" Text="Search" OnClick="btnSearch_Click" />
<asp:GridView runat="server" ID="gridCities" />

page.cs:
01 protected void Page_Load(object sender, EventArgs e)
02 {
03 DataSet objDS = new DataSet();
04 SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
05 objDA.Fill(objDS);
06 gridCities.DataSource = objDs;
07 gridCities.DataBind();
08 Session["ds"] = objDS;
09 }
10 protected void btnSearch_Click(object sender, EventArgs e)
11 {
12
13 }
Ensure that when the btnSearch Button control is clicked,
the records in the gridCities GridView control are filtered by
using the value of the txtSearch TextBox.
You should insert at line 12 the folloing code:

B. DataSet ds = Session["ds"] as DataSet;
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = "CityName LIKE '" + txtSearch.Text + "%'";
gridCities.DataSource = dv;
gridCities.DataBind();

19 WCF WebChannelFactory
The application consumes a WCF service.
The WCF service exposes the following method:

[WebInvoke] string UpdateCustomerDetails(string custID);
The application hosts the WCF service by using the following code segment.
WebServiceHost host = new WebServiceHost(typeof(CService), new Uri("http://win/"));
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(ICService), new WebHttpBinding(), "");
Invoke the UpdateCustomerDetails method with the following code:

A. WebChannelFactory<ICService> wcf = new WebChannelFactory<ICService>(new Uri("http: //win")) ;
ICService channel = wcf.CreateChannel();
string s = channel.UpdateCustomerDetails("CustID12");

20 WCF Service Contract BlogService
WCF service that exposes the following service contract:
01 [ServiceContract]
02 public interface IBlogService
03 {
04 [OperationContract]
05 [WebGet(ResponseFormat=WebMessageFormat.Xml)]
06 Rss20FeedFormatter GetBlog();
07 }
configure the WCF service to use the WebHttpBinding class,
& exposed at the following URL:
http://www.contoso.com/BlogService

Store the result of the GetBlog operation in an XmlDocument variable named xmlBlog in a Web form:

A. string url = @"http: //www.contoso.com/BlogService/GetBlog";
XmlReader blogReader = XmlReader.Create(url);
xmlBlog.Load(blogReader);

21
QUESTION 21 SQLDataSource Custom Parameter object Evaluate

Plan to add a custom parameter in the SqlDataSource control.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" InsertCommand="INSERT INTO [Employee] ([Field1], [Field2], [PostedDate]) VALUES (@Field1,
@Field2, @PostedDate)"> <InsertParameters>
<asp:Parameter Name="Field1" />
<asp:Parameter Name="Field2" />
<custom:DayParameter?Name="PostedDate" />
</InsertParameters>
</asp:SqlDataSource>

Create a custom parameter class:
public class DayParameter : Parameter { }

Ensure that the custom parameter returns
the current date and time.
add to the DayParameter class the following code:

C. protected override object Evaluate(HttpContext context, Control control) { return DateTime.Now; }

22. CustomErrors & logging exceptions
QUESTION 22
The application has an ASPX page named ErrorPage.aspx.
Planning to manage the unhandled application exceptions.
Perform the following tasks:
Display the ErrorPage.aspx page
Write the exceptioninformation in the Event log file.

The two actions you perform are:
A. Add the following code fragment to the Web.config file.
<customErrors mode="On" defaultRedirect="ErrorPage.aspx" />
D. Add the following code segment to the ErrorPage.aspx file.
void Page_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
//Write Exception details to event log
Server.ClearError();
}

23 CustomErrors Mode="On" & Unhandled Errors / Error Page
QUESTION 23

Two Web pages named OrderDetails.aspx & OrderError.htm.
If the application throws unhandled errors in the OrderDetails.aspx Web page,
a stack trace is displayed to remote users.
Ensure that the OrderError.htm Web page is displayed
for unhandled errors only in the OrderDetails.aspx Web page.

C. Set the Page attribute for the OrderDetails.aspx Web page in the following manner.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OrderDetails.aspx.cs" Inherits="OrderDetails" ErrorPage="~/OrderError.htm" Debug="false" %>
Add the following section to the Web.config file.
<customErrors mode="On"> </customErrors>

24
QUESTION 24 Asynchronosly Update - AJAX RegisterDataItem

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="updateLabels" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" />
<asp:Label ID="Label2" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label id="Label3" runat="server" />
Ensure that when you click the btnSubmit Button control,
each Label control value is asynchronously updatable.

Which code segment should you use?

B. protected void btnSubmit_Click(object sender, EventArgs e) {
Label1.Text = "Label1 updated value";
Label2.Text = "Label2 updated value";
ScriptManager1.RegisterDataItem(Label3, "Label3 updated value");
}

25 AJAX args.set_cancel(true); Suppress event while request in process

01 <script runat="server">
02 protected void Button_Handler(object sender, EventArgs e)
03 {
04 // some long-processing operation.
05 }
06 </script>
07 <div>
08 <asp:ScriptManager ID="defaultScriptManager"
09 runat="server" />
10
11 <asp:UpdatePanel ID="defaultPanel"
12 UpdateMode="Conditional" runat="server">
13 <ContentTemplate>
14 <!-- more content here -->
15 <asp:Button ID="btnSubmit" runat="server"
16 Text="Submit" OnClick="Button_Handler" />
17 </ContentTemplate>
18 </asp:UpdatePanel>
19 </div>
Plan to create a client-side script code by using ASP.NET AJAX.
Ensure that while a request is being processed,
any subsequent Click events on the btnSubmit Button control are suppressed.
You insert at line 10 the following code:
C. <script type="text/javascript" language="javascript">
var rm = Sys.WebForms.PageRequestManager.getInstance();
rm.add_initializeRequest(checkPostback);
function checkPostback(sender, args) {
if (rm.get_isInAsyncPostBack() && args.get_postBackElement().id == 'btnSubmit') {
args.set_cancel(true);
alert('A previous request is still in progress.');
}
}
</script>

 

that is all, htere will be more,

 

Catto

No comments: