70-516

TS: Accessing Data with Microsoft .NET Framework 4


Note: The answer is for reference only, you need to understand all question.
QUESTION 1
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. You define a Category class by writing the following code segment. (Line numbers are included for reference only.)
01 public class Category 02 { 03 public int CategoryID { get; set; } 04 public string CategoryName { get; set; } 05 public string Description { get; set; } 06 public byte[] Picture { get; set; } 07 ... 08 }
You need to add a collection named Products to the Category class. You also need to ensure that the collection supports deferred loading. Which code segment should you insert at line 07?
A. public static List Products { get; set; }
B. public virtual List Products { get; set; }
C. public abstract List Products { get; set; }
D. protected List Products { get; set; }

Answer: B
Question 2
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Forms application. You plan to deploy the application to several shared client computers. You write the following code segment. (Line numbers are included for reference only.)
01 Configuration config = ConfigurationManager.OpenExeConfiguration(exeConfigName); 02 ... 03 config.Save(); 04 ...
You need to encrypt the connection string stored in the .config file. Which code segment should you insert at line 02?

A. ConnectionStringsSection section = config.GetSection("connectionString") as ConnectionStringsSection; section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
B. ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection; section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
C. ConnectionStringsSection section = config.GetSection("connectionString") as ConnectionStringsSection; section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
D. ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection; section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");

Answer: D
Question 3
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses the ADO.NET Entity Framework to model entities. The database includes objects based on the exhibit. The application includes the following code segment. (Line numbers are included for reference only.)
01 using (AdventureWorksEntities context = new AdventureWorksEntities()){ 02 ... 03 foreach (SalesOrderHeader order in customer.SalesOrderHeader){ 04 Console.WriteLine(String.Format("Order: {0} ", order.SalesOrderNumber)); 05 foreach (SalesOrderDetail item in order.SalesOrderDetail){ 06 Console.WriteLine(String.Format("Quantity: {0} ", item.Quantity)); 07 Console.WriteLine(String.Format("Product: {0} ", item.Product.Name)); 08 } 09 } 10 }
You want to list all the orders for a specified customer. You need to ensure that the list contains the following
fields: Order number Quantity of products Product name Which code segment should you insert at line 02?

A. Contact customer = context.Contact.Where("it.ContactID = @customerId", new

ObjectParameter("@customerId", customerId)).First();
B. Contact customer = context.Contact.Where("it.ContactID = @customerId", new ObjectParameter("customerId", customerId)).First();
C. context.ContextOptions.LazyLoadingEnabled = true;
Contact customer = (from contact in context.Contact include("SalesOrderHeader.SalesOrderDetail") select conatct).FirstOrDefault();
D. Contact customer = (from contact in context.Contact include("SalesOrderHeader") select conatct).FirstOrDefault();

Answer: B
Question 4
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use the ADO.NET Entity Framework to model entities. You write the following code segment. (Line numbers are included for reference only.)
01 AdventureWorksEntities context = new AdventureWorksEntities("http://localhost:1234/AdventureWorks.svc"); 02 ... 03 var q = from c in context.Customers 04 where c.City == "London" 05 orderby c.CompanyName 06 select c;
You need to ensure that the application meets the following requirements: Compares the current values of unmodified properties with values returned from the data source. Marks the property as modified when the properties are not the same. Which code segment should you insert at line 02?

A. context.MergeOption = MergeOption.AppendOnly;
B. context.MergeOption = MergeOption.PreserveChanges;
C. context.MergeOption = MergeOption.OverwriteChanges;
D. context.MergeOption = MergeOption.NoTracking;

Answer: B
Question 5
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use the ADO.NET Entity Framework to model entities. You write the following code segment.

(Line numbers are included for reference only.)
01 public partial class SalesOrderDetail : EntityObject 02 { 03 partial void OnOrderQtyChanging(short value) 04 { 05 ... 06 { 07 ... 08 } 09 } 10 }
You need to find out whether the object has a valid ObjectStateEntry instance. Which code segment should you insert at line 05?
A. if (this.EntityState != EntityState.Detached)
B. if (this.EntityState != EntityState.Unchanged)
C. if (this.EntityState != EntityState.Modified)
D. if (this.EntityState != EntityState.Added)

Answer: D
Question 6
You use Microsoft Visual Studio 2010, Microsoft Sync Framework, and Microsoft .NET Framework 4.0 to create an application. You have a ServerSyncProvider connected to a Microsoft SQL Server database. The database is hosted on a Web server. Users will use the Internet to access the Customer database through the ServerSyncProvider. You write the following code segment. (Line numbers are included for reference only.)
01 SyncTable customerSyncTable = new SyncTable("Customer"); 02 customerSyncTable.CreationOption = TableCreationOption.UploadExistingOrCreateNewTable; 03 ... 04 customerSyncTable.SyncGroup = customerSyncGroup; 05 this.Configuration.SyncTables.Add(customerSyncTable);
You need to ensure that the application meets the following requirements: Users can modify data locally and receive changes from the server. Only changed rows are transferred during synchronization. Which code segment should you insert at line 03?


A. customerSyncTable.SyncDirection = SyncDirection.DownloadOnly;
B. customerSyncTable.SyncDirection = SyncDirection.Snapshot;
C. customerSyncTable.SyncDirection = SyncDirection.Bidirectional;
D. customerSyncTable.SyncDirection = SyncDirection.UploadOnly;

Answer: C
Question 7
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Communication Foundation (WCF) Data Services service. The service connects to a Microsoft SQL Server 2008 database. The service is hosted by an Internet Information Services (IIS) 6.0 Web server.
The application works correctly in the development environment. However, when you connect to the service on the production server, attempting to update or delete an entity results in an error. You need to ensure that you can update and delete entities on the production server. What should you do?
A. Add the following line of code to the InitializeService method of the service: config.SetEntitySetAccessRule ("*", EntitySetRights.WriteDelete | EntitySetRights.WriteInsert);
B. Add the following line of code to the InitializeService method of the service: config.SetEntitySetAccessRule ("*", EntitySetRights.WriteDelete | EntitySetRights.WriteMerge);
C. Configure IIS to allow the PUT and DELETE verbs for the .svc Application Extension.
D. Configure IIS to allow the POST and DELETE verbs for the .svc Application Extension.

Answer: C
Question 8
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. The database includes a table named dbo.Documents that contains a column with large binary data. You are creating the Data Access Layer (DAL). You add the following code segment to query the dbo.Documents table. (Line numbers are included for reference only.)
01 public void LoadDocuments(DbConnection cnx) 02 { 03 var cmd = cnx.CreateCommand(); 04 cmd.CommandText = "SELECT * FROM dbo.Documents"; 05 ... 06 cnx.Open();

07 ... 08 ReadDocument(reader); 09 }
You need to ensure that data can be read as a stream. Which code segment should you insert at line 07?
A. var reader = cmd.ExecuteReader(CommandBehavior.Default);
B. var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly);
C. var reader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
D. var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

Answer: D
Question 9
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You create a DataSet object in the application. You add two DataTable objects named App_Products and App_Categories to the DataSet. You add the following code segment to populate the DataSet object. (Line numbers are included for reference only.)
01 public void Fill(SqlConnection cnx, DataSet ds) 02 { 03 var cmd = cnx.CreateCommand(); 04 cmd.CommandText="SELECT*FROMdbo.Products;"+"SELECT *FROMdbo.Categories"; 05 var adapter = new SqlDataAdapter(cmd); 06 ... 07 }
You need to ensure that App_Products and App_Categories are populated from the dbo.Products and dbo.Categories database tables. Which code segment should you insert at line 06?
A. adapter.Fill(ds, "Products"); adapter.Fill(ds, "Categories");
B. adapter.Fill(ds.Tables["App_Products"]); adapter.Fill(ds.Tables["App_Categories"]);
C. adapter.TableMappings.Add("Table", "App_Products"); adapter.TableMappings.Add("Table1", "App_Categories"); adapter.Fill(ds);

D. adapter.TableMappings.Add("Products", "App_Products"); adapter.TableMappings.Add("Categories", "App_Categories"); adapter.Fill(ds);

Answer: D
Question 10
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Communication Foundation (WCF) Data Services service. You deploy the data service to the following URL: http://contoso.com/Northwind.svc. You add the following code segment. (Line numbers are included for reference only.)
01 var uri = new Uri(@"http://contoso.com/Northwind.svc/"); 02 var ctx = new NorthwindEntities(uri); 03 var categories = from c in ctx.Categories select c; 04 foreach (var category in categories) { 05 PrintCategory(category); 06 ... 07 foreach (var product in category.Products) { 08 ... 09 PrintProduct(product); 10 } 11 }
You need to ensure that the Product data for each Category object is lazy-loaded. What should you do?
A. Add the following code segment at line 06:
ctx.LoadProperty(category, "Products");
B. Add the following code segment at line 08:
ctx.LoadProperty(product, "*");
C. Add the following code segment at line 06:
var strPrdUri = string.Format("Categories({0})?$expand=Products", category.CategoryID); var productUri = new Uri(strPrdUri, UriKind.Relative); ctx.Execute(productUri);
D. Add the following code segment at line 08:
var strprdUri= string.format("Products?$filter=CategoryID eq {0}",
category.CategoryID);

var prodcutUri = new Uri(strPrd, UriKind.Relative); ctx.Execute(productUri);

Answer: A
Question 11
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You load records from the Customers table into a DataSet object named dataset. You need to retrieve the value of the City field from the first and last records in the Customers table. Which code segment should you use?
A. DataTable dt = dataset.Tables["Customers"]; string first = dt.Rows[0]["City"].ToString(); string last = dt.Rows[dt.Rows.Count -1]["City"].ToString();
B. DataTable dt = dataset.Tables["Customers"]; string first = dt.Rows[0]["City"].ToString(); string last = dt.Rows[dt.Rows.Count]["City"].ToString();
C. DataRelation relationFirst = dataset.Relations[0]; DataRelation relationLast = dataset.Relations[dataset.Relations.Count -1]; string first = relationFirst.childTable.Columns["City"].ToString(); string last = relationLast.childTable.Columns["City"].ToString();
D. DataRelation relationFirst = dataset.Relations[0]; DataRelation relationLast = dataset.Relations[dataset.Relations.Count]; string first = relationFirst.childTable.Columns["City"].ToString(); string last = relationLast.childTable.Columns["City"].ToString();

Answer: A
Question 12
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application has two DataTable objects that reference the Customers and Orders tables in the database. The application contains the following code segment. (Line numbers are included for reference only.)
01 DataSet customerOrders = new DataSet(); 02 customerOrders.EnforceConstraints = true;

03 ForeignKeyConstraint ordersFK = new ForeignKeyConstraint("ordersFK", 04 customerOrders.Tables["Customers"].Columns["CustomerID"], 05 customerOrders.Tables["Orders"].Columns["CustomerID"]); 06 ... 07 customerOrders.Tables["Orders"].Constraints.Add(ordersFK);
You need to ensure that an exception is thrown when you attempt to delete Customer records that have related Order records. Which code segment should you insert at line 06?
A. ordersFK.DeleteRule = Rule.SetDefault;
B. ordersFK.DeleteRule = Rule.None;
C. ordersFK.DeleteRule = Rule.SetNull;
D. ordersFK.DeleteRule = Rule.Cascade;

Answer: B
Question 13
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses a DataTable named OrderDetailTable that has the following columns:

ID OrderID ProductID Quantity LineTotal
Some records contain a null value in the LineTotal field and 0 in the Quantity field. You write the following code segment. (Line numbers are included for reference only.)
01 DataColumn column = new DataColumn("UnitPrice", typeof(double)); 02 ... 03 OrderDetailTable.Columns.Add(column);
You need to add a calculated DataColumn named UnitPrice to the OrderDetailTable object. You also need to ensure that UnitPrice is set to 0 when it cannot be calculated. Which code segment should you insert at line 02?
A. column.Expression = "LineTotal/Quantity";
B. column.Expression = "LineTotal/ISNULL(Quantity, 1)";

C. column.Expression = "if(Quantity > 0, LineTotal/Quantity, 0)";
D. column.Expression = "iif(Quantity > 0, LineTotal/Quantity, 0)";

Answer: D
Question 14
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database and contains a LINQ to SQL data model. The data model contains a function named createCustomer that calls a stored procedure. The stored procedure is also named createCustomer. The createCustomer function has the following signature.
createCustomer (Guid customerID, String customerName, String address1)
The application contains the following code segment. (Line numbers are included for reference only.)
01 CustomDataContext context = new CustomDataContext(); 02 Guid userID = Guid.NewGuid(); 03 String address1 = "1 Main Steet"; 04 String name = "Marc"; 05 ...
You need to use the createCustomer stored procedure to add a customer to the database. Which code segment should you insert at line 05?
A. context.createCustomer(userID, customer1, address1);
B. context.ExecuteCommand("createCustomer", userID, customer1, address1); Customer customer = new Customer() { ID = userID, Address1 = address1, Name = customer1, };
C. context.ExecuteCommand("createCustomer", customer); Customer customer = new Customer() { ID = userID, Address1 = address1, Name = customer1, };
D. context.ExecuteQuery(typeof(Customer), "createCustomer", customer);

Answer: A
Question 15
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database.

You use the ADO.NET Entity Framework to manage persistence-ignorant entities. You create an ObjectContext instance named context. Then, you directly modify properties on several entities. You need to save the modified entity values to the database. Which code segment should you use?
A. context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
B. context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
C. context.SaveChanges(SaveOptions.None);
D. context.SaveChanges();

Answer: B
Question 16
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use the ADO.NET Entity Data Model (EDM) to define a Customer entity. You need to add a new Customer to the data store without setting all the customer's properties. What should you do?
A. Call the Create method of the Customer object.
B. Call the CreateObject method of the Customer object.
C. Override the Create method for the Customer object.
D. Override the SaveChanges method for the Customer object.

Answer: B
Question 17
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. You use the ADO.NET Entity Framework to model your entities. You use ADO.NET self-tracking entities. You need to ensure that the change-tracking information for the self-tracking entities can be used to update the database. Which ObjectContext method should you call after changes are made to the entities?
A. Attach
B. Refresh
C. SaveChanges
D. ApplyChanges
Answer: D Question 18


You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application.
The application uses the ADO.NET Entity Framework to manage Plain Old CLR Objects (POCO) entities.
You create a new POCO class. You need to ensure that the class meets the following requirements: It can be used by an ObjectContext. It is enabled for change-tracking proxies. Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)

A. Modify each mapped property to contain sealed and protected accessors.
B. Modify each mapped property to contain non-sealed, public, and virtual accessors.
C. Configure the navigation property to return a type that implements the ICollection interface.
D. Configure the navigation property to return a type that implements the IQueryable interface.
E. Configure the navigation property to return a type that implements the IEntityWithRelationships interface.

Answer: BC
Question 19
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. The application allows users to make changes while disconnected from the data store. Changes are submitted to the data store by using the SubmitChanges method of the DataContext object. You receive an exception when you call the SubmitChanges method to submit entities that a user has changed in offline mode. You need to ensure that entities changed in offline mode can be successfully updated in the data store. What should you do?
A. Set the ObjectTrackingEnabled property of DataContext to true.
B. Set the DeferredLoadingEnabled property of DataContext to true.
C. Call the SaveChanges method of DataContext with a value of false.
D. Call the SubmitChanges method of DataContext with a value of System.Data.Linq.ConflictMode.ContinueOnConflict.

Answer: A
Question 20
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses the ADO.NET LINQ to SQL model to retrieve data from the database.

The application will not modify retrieved data. You need to ensure that all the requested data is retrieved. You want to achieve this goal using the minimum amount of resources. What should you do?
A. Set ObjectTrackingEnabled to true on the DataContext class.
B. Set ObjectTrackingEnabled to false on the DataContext class.
C. Set DeferredLoadingEnabled to true on the DataContext class.
D. Set DeferredLoadingEnabled to false on the DataContext class.

Answer: B
Question 21
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use the ADO.NET Entity Framework to model your entities. You use Plain Old CLR Objects (POCO) entities along with snapshot-based change tracking. The code accesses the POCO entities directly. You need to ensure that the state manager synchronizes when changes are made to the object graph. Which ObjectContext method should you call?
A. Refresh
B. SaveChanges
C. DetectChanges
D. ApplyPropertyChanges

Answer: C
Question 22
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. The application includes a Customer entity along with a CustomerKey property of the Guid type as shown in the following exhibit:


You discover that when the application adds a new instance of a Customer, calling the SaveChanges method results in the following error message: "Server generated keys are only supported for identity columns." You need to ensure that the application can add new Customer entities. What should you do?
A. Add a handler for the ObjectContext.SavingChanges event. In the event handler, set the CustomerKey value.
B. Add a handler for the ObjectContext.ObjectMaterialized event. In the event handler, set the CustomerKey value.
C. Call the ObjectContext.Attach method before saving a Customer entity.
D. Call the ObjectContext.CreateEntityKey method before saving a Customer entity.

Answer: A
Question 23
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use the ADO.NET Entity Framework to model entities. The application connects to a Microsoft SQL Server database named AdventureWorks. The application includes the following code segment. (Line numbers are included for reference only.)
01 using (AdventureWorksEntities context = new AdventureWorksEntities()) 02 { 03 ObjectQuery orders = context.SalesOrderHeader.
Where("it.CreditCardApprovalCode IS NULL").Top("100"); 04 foreach (SalesOrderHeader order in orders){ 05 order.Status = 4; 06 } 07 try{ 08 context.SaveChanges();

09 } 10 catch (OptimisticConcurrencyException){ 11 ... 12 } 13 }
You need to resolve any concurrency conflict that can occur. You also need to ensure that local changes are persisted to the database. Which code segment should you insert at line 11?
A. context.Refresh(RefreshMode.ClientWins, orders); context.AcceptAllChanges();
B. context.Refresh(RefreshMode.ClientWins, orders); context.SaveChanges();
C. context.Refresh(RefreshMode.StoreWins, orders); context.AcceptAllChanges();
D. context.Refresh(RefreshMode.StoreWins, orders); context.SaveChanges();

Answer: B
Question 24
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses the following object query to load a product from the database. (Line numbers are included for reference only.)
01 using (AdventureWorksEntities advWorksContext = new AdventureWorksEntities()) 02 { 03 ObjectQuery productQuery = advWorksContext.Product.Where("it.ProductID = 900"); 04 ... 05 }
You need to log the command that the query executes against the data source. Which code segment should you insert at line 04?
A. Trace.WriteLine(productQuery.ToString());

B. Trace.WriteLine(productQuery.ToTraceString());
C. Trace.WriteLine(productQuery.CommandText);
D. Trace.WriteLine(((IQueryable)productQuery).Expression);

Answer: B
Question 25
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Forms application. The application connects to a Microsoft SQL Server database. You need to find out whether the application is explicitly closing or disposing SQL connections. Which code segment should you use?
A. string instanceName = Assembly.GetEntryAssembly().FullName; PerformanceCounter perf = new PerformanceCounter( ".NET Data Provider for SqlServer",
"NumberOfReclaimedConnections", instanceName, true);
int leakedConnections = (int)perf.NextValue();
B. string instanceName = Assembly.GetEntryAssembly().GetName().Name; PerformanceCounter perf = new PerformanceCounter( ".NET Data Provider for SqlServer",
"NumberOfReclaimedConnections", instanceName, true);
int leakedConnections = (int)perf.NextValue();
C. string instanceName = Assembly.GetEntryAssembly().FullName; PerformanceCounter perf = new PerformanceCounter( ".NET Data Provider for SqlServer",
"NumberOfNonPooledConnections", instanceName, true);
int leakedConnections = (int)perf.NextValue();
D. string instanceName = Assembly.GetEntryAssembly().GetName().Name; PerformanceCounter perf = new PerformanceCounter( ".NET Data Provider for SqlServer",
"NumberOfNonPooledConnections", instanceName, true); int leakedConnections = (int)perf.NextValue();
Answer: A
Question 26

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You write the following code segment that executes two commands against the database within a transaction. (Line numbers are included for reference only.)
01 using(SqlConnection connection = new SqlConnection(cnnStr)) { 02 connnection.Open(); 03 SqlTransaction sqlTran = connection.BeginTransaction(); 04 SqlCommand command = connection.CreateCommand(); 05 command.Transaction = sqlTran; 06 try{ 07 command.CommandText = ��INSERT INTO Production.ScrapReason(Name) VALUES(��Wrong size��)��; 08 command.ExecuteNonQuery(); 09 command.CommandText = ��INSERT INTO Production.ScrapReason(Name) VALUES(��Wrong color��)��;
10 command.ExecuteNonQuery();
11 ...
l2 }

You need to log error information if the transaction fails to commit or roll back. Which code segment should you insert at line 11?
A. sqlTran.Commit(); } catch (Exception ex) {
sqlTran.Rollback(); Trace.WriteLine(ex.Message); }
B. sqlTran.Commit(); } catch (Exception ex) {
Trace.WriteLine(ex.Message); try {
sqlTran.Rollback(); } catch (Exception exRollback) {
Trace.WriteLine(exRollback.Message); } }
C. catch (Exception ex){

Trace.WriteLine(ex.Message); try{
sqlTran.Rollback(); } catch (Exception exRollback){
Trace.WriteLine(exRollback.Message);
} } finaly {
sqltran.commit( ); }
D. catch (Exception ex) { sqlTran.Rollback(); Trace.WriteLine(ex.Message);
} finaly { try {
sqltran.commit( ); } catch (Exception exRollback) {
Trace.WriteLine(excommit.Message); } }

Answer: B
Question 27
You use Microsoft Visual Studio 2010 and Microsoft.NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You use the ADO.NET LINQ to Entity model to retrieve data from the database. You need to call a function that is defined in the conceptual model from within the LINQ to Entities queries. You create a common language runtime (CLR) method that maps to the function. What should you do next?
A. Declare the method as static.
B. Declare the method as abstract.
C. Apply the EdmFunctionAttribute attribute to the method.
D. Apply the EdmComplexTypeAttribute attribute to the method.
Answer: C Question 28

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use Microsoft ADO.NET Entity Data Model (EDM) to model entities. You create an entity named Person with a schema defined by the following XML fragment.



You need to ensure that entities within the application are able to add properties related to the city, region, and country of Person's address. What should you do?
A. Create a new complex type named CAddress that contains the properties for city, region, and country. Change the Type of the Address property in CPerson to "Self.CAddress".
B. Create a SubEntity named Address. Map the SubEntity to a stored procedure that retrieves city, region, and country.
C. Create a new entity named Address. Add a person ID property to filter the results to display only the City, Region, and Country properties for a specific Person entity.
D. Create a view named Name that returns city, region, and country along with person IDs. Add a WHERE clause to filter the results to display only the City, Region and Country properties for a specific Person entity.

Answer: A
Question 29
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You use the ADO.NET Entity Framework to

model entities. You need to add a new type to your model that organizes scalar values within an entity. You also need to map stored procedures for managing instances of the type. What should you do?
A. 1. Add the stored procedures in the SSDL file along with a Function attribute.
2.
Define a complex type in the CSDL file.

3.
Map the stored procedure in the MSL file with a ModificationFunctionElement.


B. 1. Add the stored procedures in the SSDL file along with a Function attribute.
2.
Define a complex type in the CSDL file.

3.
Map the stored procedure in the MSL file with an AssociationEnd element.


C. 1. Use the edmx designer to import the stored procedures.
2.
Derive an entity class from the existing entity as a complex type.

3.
Map the stored procedure in the MSL file with an AssociationEnd element.


D. 1. Add the stored procedures in the SSDL file along with a Function attribute.
2.
Derive an entity class from the existing entity as a complex type.

3.
Map the stored procedure in the MSL file with a ModificationFunctionElement.



Answer: A
Question 30
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. The database includes a table that contains information about all the employees. The database table has a field named EmployeeType that identifies whether an employee is a Contractor or a Permanent employee. You declare the Employee entity base type. You create a new Association entity named Contractor that inherits the Employee base type. You need to ensure that all Contractors are bound to the Contractor class. What should you do?
A. Modify the .edmx file to include the following line of code:
B. Modify the .edmx file to include the following line of code:
C. Use the Entity Data Model Designer to set up an association between the Contractor class and EmployeeType.
D. Use the Entity Data Model Designer to set up a referential constraint between the primary key of the Contractor class and EmployeeType.


Answer: B
Question 31
You use Microsoft Visual Studio 2010 and Microsoft ADO.NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. You use the ADO.NET LINQ to SQL model to retrieve data from the database. You use stored procedures to return multiple result sets. You need to ensure that the result sets are returned as strongly typed values. What should you do?
A. Apply the FunctionAttribute and ResultTypeAttribute to the stored procedure function. Use the GetResult method to obtain an enumerator of the correct type.
B. Apply the FunctionAttribute and ParameterAttribute to the stored procedure function and directly access the strongly typed object from the results collection.
C. Apply the ResultTypeAttribute to the stored procedure function and directly access the strongly typed object from the results collection.
D. Apply the ParameterAttribute to the stored procedure function. Use the GetResult method to obtain an enumerator of the correct type.

Answer: A
Question 32
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You create stored procedures by using the following signatures:
CREATE procedure [dbo].[Product_Insert](@name varchar(50),@price float) CREATE procedure [dbo].[Product_Update](@id int, @name varchar(50), @price float) CREATE procedure [dbo].[Product_Delete](@id int) CREATE procedure [dbo].[Order_Insert](@productId int, @quantity int) CREATE procedure [dbo].[Order_Update](@id int, @quantity int,@originalTimestamp timestamp) CREATE procedure [dbo].[Order_Delete](@id int)
You create a Microsoft ADO.NET Entity Data Model (EDM) by using the Product and Order entities as shown in the exhibit:


You need to map the Product and Order entities to the stored procedures. To which two procedures should you add the @productId parameter? (Each correct answer presents part of the solution. Choose two.)
A. Product_Delete
B. Product_Update
C. Order_Delete
D. Order_Update

Answer: CD
Question 33
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use Plain Old CLR objects (POCO) to model your entities. The application communicates with a Windows Communication Foundation (WCF) Data Services service. You need to ensure that entities can be sent to the service as XML. What should you do?
A. Apply the virtual keyword to the entity properties.
B. Apply the [Serializable] attribute to the entities.
C. Apply the [DataContract(IsReference = true)] attribute to the entities.
D. Apply the [DataContract(IsReference = false)] attribute to the entities.

Answer: C
Question 34
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. You need to create a database from your model. What should you do?
A. Run the edmgen.exe tool in FullGeneration mode.
B. Run the edmgen.exe tool in FromSSDLGeneration mode.

C. Use the Update Model Wizard in Visual Studio.
D. Use the Generate Database Wizard in Visual Studio. Run the resulting script against a Microsoft SQL Server database.

Answer: D
Question 35
You use Microsoft Visual Studio 2010 and Microsoft. NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You use Entity SQL of the ADO.NET Entity Framework to retrieve data from the database. You need to define a custom function in the conceptual model. You also need to ensure that the function calculates a value based on properties of the object. Which two XML element types should you use? (Each correct answer presents part of the solution. Choose two.)
A. Function
B. FunctionImport
C. Dependent
D. Association
E. DefiningExpression

Answer: AE
Question 36
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You deploy a Windows Communication Foundation (WCF) Data Service to a production server. The application is hosted by Internet Information Services (IIS). After deployment, applications that connect to the service receive the following error message: "The server encountered an error processing the request. See server logs for more details."
You need to ensure that the actual exception data is provided to client computers. What should you do?
A. Modify the application's Web.config file. Set the value for the customErrors element to Off.
B. Modify the application's Web.config file. Set the value for the customErrors element to RemoteOnly.
C. Add the FaultContract attribute to the class that implements the data service.
D. Add the ServiceBehavior attribute to the class that implements the data service.
Answer: D
Question 37

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Microsoft ASP.NET
application. You want to connect the application to a Microsoft SQL Server Express 2008 database named MyDatabase. The primary database file is named MyDatabase.mdf and it is stored in the App_Data folder. You need to define the connection string. Which connection string should you add to the Web.config file?
A. Data Source=localhost; Initial Catalog=MyDataBase; Integrated Security=SSPI; User Instance=True
B. Data Source=.\SQLEXPRESS; Initial Catalog=MyDataBase; Integrated Security=True; User Instance=True
C. Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\MyDatabase.mdf; Integrated Security=True; User Instance=True
D. Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\App_Data\MyDatabase.mdf; Integrated Security=SSPI; User Instance=True

Answer: C
Question 38
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. The application uses a Microsoft ADO.NET SQL Server managed provider. When a connection fails, the application logs connection information, including the full connection string. The information is stored as plain text in a .config file. You need to ensure that the database credentials are secure. Which connection string should you add to the .config file?
A. Data Source=myServerAddress; Initial Catalog=myDataBase; Integrated Security=SSPI; Persist Security Info=false;
B. Data Source=myServerAddress; Initial Catalog=myDataBase; Integrated Security=SSPI; Persist Security Info=true;
C. Data Source=myServerAddress; Initial Catalog=myDataBase; User Id=myUsername; Password=myPassword; Persist Security Info=false;
D. Data Source=myServerAddress; Initial Catalog=myDataBase; User Id=myUsername; Password=myPassword; Persist Security Info=true;

Answer: A
Question 39
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses the ADO.NET Entity

Framework to manage order data. The application makes a Web service call to obtain orders from an order-tracking system. You need to ensure that the orders are added to the local data store. Which method should you call on the ObjectContext?
A. Attach
B. AttachTo
C. AddObject
D. ApplyCurrentValues

Answer: C
Question 40
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You manually create your own Context class named AdventureWorksDB that inherits from ObjectContext. You need to use AdventureWorksDB to invoke a stored procedure that is defined in the data source. Which method should you call?
A. Translate
B. ExecuteFunction
C. ExecuteStoreQuery
D. ExecuteStoreCommand

Answer: B
Question 41
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. You create an entity as shown in the following code fragment.

...

You need to provide two entity-tracking fields:


rowguid that is automatically generated when the entity is created ModifiedDate that is automatically set whenever the entity is updated. Which code fragment should you add to the .edmx file?
A.
B.
C.
D.

Answer: C
Question 42
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Communication Foundation (WCF) Data Services service. The service connects to a Microsoft SQL Server 2008 database. The service is hosted by an Internet Information Services (IIS) 6.0 server. You need to ensure that applications authenticate against user information stored in the database before the application is allowed to use the service. Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)
A. Configure IIS to require basic authentication.
B. Configure IIS to allow anonymous access.
C. Configure IIS to require Windows authentication.
D. Enable the WCF Authentication Service.
E. Modify the Data Services service to use a Microsoft ASP.NET membership provider.


Answer: BE
Question 43
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Communication Foundation (WCF) Data Services service. You discover that when an application submits a PUT or DELETE request to the Data Services service, it receives an error. You need to ensure that the application can access the service. Which header and request type should you use in the application?
A. an X-HTTP-Method header as part of a POST request
B. an X-HTTP-Method header as part of a GET request
C. an HTTP ContentType header as part of a POST request
D. an HTTP ContentType header as part of a GET request

Answer: A
Question 44
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. You create classes by using LINQ to SQL based on the records shown in the exhibit:

You need to create a LINQ query to retrieve a list of objects that contains the OrderID and CustomerID properties. You need to retrieve the total price amount of each Order record. What are two possible ways to achieve this goal? (Each correct answer presents a complete solution. Choose two.)
A. from details in dataContext.Order_Detail group details by details.OrderID into g join order in dataContext.Orders on g.Key equals order.OrderID

select new
{
OrderID = order.OrderID,
CustomerID = order.CustomerID,
TotalAmount = g.Sum(od => od.UnitPrice * od.Quantity)
}
B. dataContext.Order_Detail.GroupJoin(dataContext.Orders, d => d.OrderID,
o => o.OrderID,
(dts, ord) => new { OrderID = dts.OrderID, CustomerID = dts.Order.CustomerID, TotalAmount = dts.UnitPrice * dts.Quantity
})
C. from order in dataContext.Orders group order by order.OrderID into g join details in dataContext.Order_Detail on g.Key equals
details.OrderID select new
{
OrderID = details.OrderID,
CustomerID = details.Order.CustomerID,
TotalAmount = details.UnitPrice * details.Quantity
}
D. dataContext.Orders.GroupJoin(dataContext.Order_Detail, o => o.OrderID, d => d.OrderID,
(ord, dts) => new { OrderID = ord.OrderID, CustomerID = ord.CustomerID, TotalAmount = dts.Sum(od => od.UnitPrice *
od.Quantity) })

Answer: AD
Question 45
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You use the following SQL statement to retrieve an instance of a DataSet object named ds:

SELECT CustomerID, CompanyName, ContactName, Address, City FROM dbo.Customers
You need to query the DataSet object to retrieve only the rows where the ContactName field is not NULL. Which code segment should you use?
A. from row in ds.Tables[0].AsEnumerable() where (string)row["ContactName"] != null select row;
B. from row in ds.Tables[0].AsEnumerable() where row.Field("ContactName") != null select row;
C. from row in ds.Tables[0].AsEnumerable() where !row.IsNull((string)row["ContactName"]) select row;
D. from row in ds.Tables[0].AsEnumerable() where !Convert.IsDBNull(row.Field("ContactName")) select row;

Answer: B
Question 46
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You use Entity SQL to retrieve data from the database. You need to find out whether a collection is empty. Which entity set operator should you use?
A. ANYELEMENT
B. EXCEPT
C. EXISTS
D. IN
Answer: C
Question 47
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application.

The application connects to a Microsoft SQL Server database. You use Entity SQL to retrieve data from the database. You need to enable query plan caching. Which object should you use?
A. EntityCommand
B. EntityConnection
C. EntityTransaction
D. EntityDataReader

Answer: A
Question 48
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. You need to ensure that the application calls a stored procedure that accepts a table-valued parameter. You create a SqlParameter object. What should you do next?
A. Set the SqlDbType of SqlParameter to Udt.
B. Set the SqlDbType of SqlParameter to Variant.
C. Set the ParameterDirection of SqlParameter to Output.
D. Set the SqlDbType of SqlParameter to Structured. Set the TypeName of SqlParameter to Udt.

Answer: D
Question 49
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. You need to use a spatial value type as a parameter for your database query. What should you do?
A. Set the parameter's SqlDbType to Binary.
B. Set the parameter's SqlDbType to Variant.
C. Set the parameter's SqlDbType to Udt. Set the parameter's UdtTypeName to GEOMETRY.
D. Set the parameter's SqlDbType to Structured. Set the parameter's TypeName to GEOMETRY.

Answer: C
Question 50
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application contains the following XML fragment:











The application queries the XML fragment by using the XmlDocument class. You need to select all the descendant elements of the MenuItem element that has its name attribute as File. Which XPath expression should you use?
A. //*[@name='File'][name()='MenuItem']
B. /ApplicationMenu/MenuItem['File']//MenuItem
C. /ApplicationMenu/MenuItem/descendant::MenuItem['File']
D. /ApplicationMenu/MenuItem[@name='File']/descendant::MenuItem

Answer: D
Question 51
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Communication Foundation (WCF) Data Services service. You deploy the service to the following URL: http://contoso.com/Northwind.svc. You want to query the WCF Data Services service to retrieve a list of customer objects.
You need to ensure that the query meets the following requirements:


Only customers that match the following filter criteria are retrieved: City="Seattle" AND Level > 200. Data is sorted in ascending order by the ContactName and Address properties. Which URL should you use for the query?
A. http://contoso.com/Northwind.svc/Customers?City=Seattle & Level gt 200 & $orderby=ContactName,Address
B. http://contoso.com/Northwind.svc/Customers?City=Seattle & Level gt 200 & $orderby=ContactName and Address
C. http://contoso.com/Northwind.svc/Customers?$filter=City eq 'Seattle' and Level gt 200 & $orderby=ContactName,Address
D. http://contoso.com/Northwind.svc/Customers?$filter=City eq 'Seattle' and Level gt 200 & $orderby=ContactName and Address

Answer: C
Question 52
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Communication Foundation (WCF) Data Services service. You deploy the data service to the following URL: http://contoso.com/Northwind.svc. You need to update the City property of the Customer record that has its ID value as 123. You also need to preserve the current values of the remaining properties. Which HTTP request should you use?
A. PUT /Northwind.svc/Customers(123) Host: contoso.com Content-Type: application/json { City: 'Seattle' }
B. PUT /Northwind.svc/Customers(123) Host: contoso.com Accept: application/json { City: 'Seattle' }
C. MERGE /Northwind.svc/Customers(123) Host: contoso.com Content-Type: application/json { City: 'Seattle' }
D. MERGE /Northwind.svc/Customers(123) Host: contoso.com Accept: application/json { City: 'Seattle' }
Answer: C Question 53

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. The application uses DataContexts to query the database. You create a function that meets the following requirements:

Updates the Customer table on the database when a customer is marked as deleted. Updates the related entries in other tables (CustomerAddress, CustomerContacts) by marking them as deleted. Prevents consumer code from setting the Deleted column's value directly.
You need to ensure that the function verifies that customers have no outstanding orders before they are marked as deleted. You also need to ensure that existing applications can use the update function without requiring changes in the code. What should you do?
A. Override the Delete operation of the DataContext object.
B. Override the Update operation of the DataContext object.
C. Modify the SELECT SQL statement provided to the DataContext object to use an INNER JOIN between the Customer and Orders tables.
D. Add new entities to the DataContext object for the Customers and Orders tables.

Answer: A
Question 54
You use Microsoft Visual Studio 2010 and the Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses DataContexts to query the database. You define a foreign key between the Customers and Orders tables in the database. You need to ensure that when you delete a customer record, the corresponding order records are deleted. You want to achieve this goal by using the minimum amount of development effort. What should you do?
A. Override the Delete operation of the customer entity.
B. Remove the foreign key between the Customers and Orders tables.
C. Use the ExecuteDynamicDelete method of the DataContext object.
D. Modify the foreign key between the Customers and Orders tables to enable the ON DELETE CASCADE option.
Answer: D Question 55

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses DataContexts to query the database. The application meets the following requirements:

Stores customer data offline. Allows users to update customer records while they are disconnected from the server. Enables offline changes to be submitted back to the SQL Server by using the DataContext object. You need to ensure that the application can detect all conflicts that occur between the offline customer information submitted to the SQL Server and the server version. You also need to ensure that you can roll back local changes. What should you do?
A. Add a try/catch statement around calls to the SubmitChanges method of the DataContext object and catch SqlExceptions.
B. Add a try/catch statement around calls to the SubmitChanges method of the DataContext object and catch ChangeConflictExceptions.
C. Override the Update operation of the DataContext object. Call the ExecuteDynamicUpdate method to generate the update SQL.
D. Call the SubmitChanges method of the DataContext object. Pass System.Data.Linq.ConflictMode.ContinueOnConflict to the method.

Answer: D
Question 56
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a multi-tier application. You use Microsoft ADO.NET Entity Data Model (EDM) to model entities. The model contains entities named SalesOrderHeader and SalesOrderDetail. For performance considerations in querying SalesOrderHeader, you detach SalesOrderDetail entities from ObjectContext.
You need to ensure that changes made to existing SalesOrderDetail entities updated in other areas of your application are persisted to the database. Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)
A. Re-attach the SalesOrderDetail entities.
B. Set the MergeOption of SalesOrderDetail to MergeOptions.OverwriteChanges.
C. Set the MergeOption of SalesOrderDetail to MergeOptions.NoTracking.
D. Call ObjectContext.ApplyCurrentValue.
E. Call ObjectContext.ApplyOriginalValue.


Answer: AE
Question 57
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to manage customer and related order records. You add a new order for an existing customer. You need to associate the Order entity with the Customer entity. What should you do?
A. Set the Value property of the EntityReference of the Order entity.
B. Call the Add method on the EntityCollection of the Order entity.
C. Use the AddObject method of the ObjectContext to add both Order and Customer entities.
D. Use the Attach method of the ObjectContext to add both Order and Customer entities.

Answer: A
Question 58
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database over the network. The application uses data from multiple related database tables. You need to ensure that the application can be used if the connection is disconnected or unavailable. Which object type should you use to store data from the database tables?
A. DataSet
B. DataAdapter
C. DataReader
D. Data Services

Answer: A
Question 59
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use a TableAdapter object to load a DataTable object. The DataTable object is used as the data source for a GridView control to display a table of customer information on a Web page.
You need to ensure that the application meets the following requirements: Load only new customer records each time the page refreshes. Preserve existing customer records. What should you do?


A. Set the ClearBeforeFill property of the TableAdapter to false. Use the Fill method of the TableAdapter.
B. Set the ClearBeforeFill property of the TableAdapter to false. Use the GetData method of the TableAdapter to create a new DataTable.
C. Set the ClearBeforeFill property of the TableAdapter to true. Use the Fill method of the TableAdapter to load additional customers.
D. Set the ClearBeforeFill property of the TableAdapter to true. Use the GetData method of the TableAdapter to create a new DataTable.

Answer: A
Question 60
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application stores user names and passwords in the database. You need to ensure that users cannot read passwords extracted from the database. What should you do?
A. Encrypt stored passwords by using the RC2CryptoServiceProvider class.
B. Encrypt stored passwords by using the TripleDESCryptoServiceProvider class.
C. Append a random salt to the password by using the RNGCryptoServiceProvider class. Encrypt stored passwords by using the RijndaelManaged class.
D. Append a random salt to the password by using the RNGCryptoServiceProvider class. Hash stored passwords by using the SHA1CryptoServiceProvider class.

Answer: D
Question 61
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application stores encrypted credit card numbers in the database. You need to ensure that credit card numbers can be extracted from the database. Which cryptography provider should you use?
A. DSACryptoServiceProvider
B. AESCryptoServiceProvider
C. MD5CryptoServiceProvider

D. SHA1CryptoServiceProvider

Answer: B
Question 62
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Microsoft ASP.NET application. The application connects to a Microsoft SQL Server database. The application is hosted on a Web server along with other applications.
You need to secure the transmission of data between the application and the database. You need to achieve this goal without affecting other applications. What should you do?
A. Encrypt the connection string.
B. Use encryption to store sensitive data in the database.
C. Use Secure Sockets Layer (SSL) to establish connections to the database.
D. Use Internet Protocol Security (IPSec) to secure the communication channel.

Answer: C
Question 63
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. The application allows users to make changes to entities while disconnected from the central data store.
You need to ensure that when the user connects to the central data store and retrieves new data, the
application meets the following requirements: Changes made to the local data store in disconnected mode are preserved. Entities that have already been loaded into the local data store, but have not been modified by the user, are

updated with the latest data. What should you do?
A. Call the query's Execute method by using the MergeOptions.AppendOnly option.
B. Call the query's Execute method by using the MergeOptions.OverwriteChanges option.
C. Call the Refresh method of ObjectContext by using the RefreshMode.StoreWins option.
D. Call the Refresh method of ObjectContext by using the RefreshMode.ClientWins option.
Answer: D
Question 64

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model persistence-ignorant entities. The application operates in a disconnected mode. You need to ensure that changes made to local entities while the application is in the disconnected mode are correctly persisted. Which method should you call before persisting changes?
A. ObjectContext.Refresh
B. DataContext.AcceptAllChanges
C. ObjectStateEntry.AcceptChanges
D. ObjectStateEntry.SetModifiedProperty

Answer: D
Question 65
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. You deploy an application to a production server. The application uses the model and mapping files that are deployed as application resources.
You need to update the conceptual model for the application on the production server. What should you do?
A. Copy the updated .edmx file to the production server.
B. Copy the updated .csdl file to the production server.
C. Copy the updated .ssdl file to the production server.
D. Recompile the application and redeploy the modified assembly file.

Answer: D
Question 66
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. You need to ensure that the model and mapping files are not deployed as application resources. What should you do?
A. Modify the connection string in the application's .config file to refer to the absolute physical path to the .edmx file.
B. Modify the connection string in the application's .config file to refer to the relative path to the .edmx file.
C. Set the value of the .edmx file's Metadata Artifact Processing property to Copy to Output Directory.

D. Set the value of the .edmx file's Build Action property to Copy to Output.

Answer: C
Question 67
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application updates several Microsoft SQL Server databases within a single transaction. You need to ensure that after a resource failure, you can manage unresolved transactions. What should you do?
A. Call the EnlistVolatile method of the Transaction class.
B. Call the EnlistDurable method of the Transaction class.
C. Call the Reenlist method of the TransactionManager class.
D. Call the RecoveryComplete method of the TransactionManager class.

Answer: C
Question 68
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to several SQL Server databases. You create a function that modifies customer records that are stored in multiple databases. All updates for a given record are performed in a single transaction. You need to ensure that all transactions can be recovered. What should you do?
A. Call the EnlistVolatile method of the Transaction class.
B. Call the EnlistDurable method of the Transaction class.
C. Call the Reenlist method of the TransactionManager class.
D. Call the RecoveryComplete method of the TransactionManager class.

Answer: B
Question 69
You use Microsoft Visual studio 2010 and Microsoft NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. The model includes the entity shown in the following exhibit:


You need to add a function that returns the number of years since a person was hired. You also need to ensure that the function can be used within LINQ to Entities queries. What should you do?
A. //Add the following conceptual model function returns the number of years since an instructor was hired

Year(CurrentDateTime()) -Year(date)

// add the following method to your application and use an EdmFunctionAttribute to map it to
the conceptual model function:
[EdmFunction("SchoolModel", "YearsSince")] public static int YearsSince(DateTime date){ thrownewNotSupportedException("Directcallsarenotsupported."); }
B. //Add the following conceptual model function returns the number of years since an instructor was hired

Year(CurrentDateTime()) -Year(date)

// add the following method to your application and use an EdmFunctionAttribute to map it to the conceptual model function:

[EdmFunction("SchoolModel", "YearsSince")] public static int YearsSince(DateTime date){ return CurrentDateTime() -Year(date); }
C. //Add the following conceptual model function returns the number of years since an instructor was hired

YearsSince(DateTime date)

// add the following method to your application and use an EdmFunctionAttribute to map it to the conceptual model function:
[EdmFunction("SchoolModel", "YearsSince")] public static int YearsSince(DateTime date){ return CurrentDateTime() -Year(date); }
D. Use the Entity Data Model Designer to create a complex property named YearsSinceNow that can be accessed throuqh the LINQ to Entites query at a Later time

Answer: A
Question 70
You use Microsoft Visual Studio 2010 and Microsoft Entity Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You use the ADO.NET LINQ to SQL model to retrieve data from the database. The applications contains the Category and Product entities as shown in the following exhibit:


You need to ensure that LINO to SQL executes only a single SQL statement against the database. You also need to ensure that the query returns the list of categories and the list of products. Which code segment should you use?
Exhibit:


A. using (NorthwindDataContext dc = new NorthwindDataContext()) { dc.ObjectTrackingEnabled = false; var categories = from c in dc.Categories
select c; foreach (var category in categories) { Console.WriteLine("{0} has {1} products", category.CategoryName, category.Products.Count); } }
B. using (NorthwindDataContext dc = new NorthwindDataContext()) { dc.DeferredLoadingEnabled = false; DataLoadOptions dlOptions = new DataLoadOptions(); dlOptions.LoadWith(c => c.Products); dc.LoadOptions = dlOptions; var categories = from c in dc.Categories
select c; foreach (var category in categories) { Console.WriteLine("{0} has {1} products", category.CategoryName, category.Products.Count); } }
C. using (NorthwindDataContext dc = new NorthwindDataContext()) { dc.DeferredLoadingEnabled = false; var categories = from c in dc.Categories
select c; foreach (var category in categories) { Console.WriteLine("{0} has {1} products", category.CategoryName, category.Products.Count); } }
D. using (NorthwindDataContext dc = new NorthwindDataContext()) { dc.DeferredLoadingEnabled = false; DataLoadOptions dlOptions = new DataLoadOptions(); dlOptions.AssociateWith(c => c.Products); dc.LoadOptions = dlOptions; var categories = from c in dc.Categories
select c; foreach (var category in categories) { Console.WriteLine("{0} has {1} products", category.CategoryName,

category.Products.Count); } }

Answer: B
Question 71
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You use the ADO.NET Entity Framework to model your entities. The application connects to a Microsoft SQL Server 2008 database named AdventureWorks by using Windows Authentication. Information about the required Entity Data Model (EDM) is stored in the following files:

model.csdl model.ssdl model.msl
These files are embedded as resources in the MyCompanyData.dll file.You need to define the connection string that is used by the application. Which connection string should you add to the app.config file?
A. connectionString=��metadata=res://MyComparny.Data,Culture=neutral,PublicKeyToken=null/m
odel.csdIl res://MyCompany.Data,Culture=neutral, PublicKeyToken=null/model.ssdl| res://MyCompany.Data,Culture=neutral, PublicKeyToken=null/model.msl; provider=System.Data.EntityClient; provider connection string=��DataSource=localhost;Initial
Catalog=AdventureWorks;lntegrated Security=True;multipleactivesuitsets=true'�� providerName=��System.Data.SqlClient��/>
B. connectionString=��metadata=res://MyComparny.Data,Culture=neutral,PublicKeyToken=null/m
odel.csdIl res://MyCompany.Data,Culture=neutral, PublicKeyToken=null/model.ssdl| res://MyCompany.Data,Culture=neutral, PublicKeyToken=null/model.msl; provider=System.Data.SqlClient; provider connection string=��DataSource=localhost;Initial
Catalog=AdventureWorks;lntegrated Security=True;multipleactivesuitsets=true'�� providerName=��System.Data.EntityClient��/>

C. Catalog=AdventureWorks;lntegrated Security=SSPI;multipleactivesuitsets=true'�� providerName=��System.Data.EntityClient��/>
D. connectionString=��metadata=res://MyComparny.Data,Culture=neutral,PublicKeyToken=null/m
odel.csdIl res://MyComparny.Data,Culture=neutral,PublicKeyToken=null/model.ssdIl res://MyComparny.Data,Culture=neutral,PublicKeyToken=null/model.msl; provider=System.Data.OleDBClient; provider connection string=��Provider=sqloledb;DataSource=localhost;Initial
Catalog=AdventureWorks;lntegrated Security=SSPI;multipleactivesuitsets=true'�� providerName=��System.Data.EntityClient��/>

Answer: B
Question 72
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The Data Definition Language (DDL) script of the database contains the following code segment:
CREATE TABLE [Sales].[SalesOrderHeader]( [SalesOrderID] [int] IDENTITY(1,1) NOT NULL, [BillToAddressID] [int] NOT NULL, �� CONSTRAINT [PK_SalesOrderHeader_SalesOrderID] PRIMARY KEY CLUSTERED ([SalesOrderID] ASC)
)
ALTER TABLE [Sales].[SalesOrderHeader] WITH CHECK ADD CONSTRAINT [FK_SalesOrderHeader_Address] FOREIGN KEY([BilIToAddressID]) REFERENCES [Person].[Address]([AddressID])
You create an ADO.NET Entity Framework model. You need to ensure that the entities of the model correctly

map to the DDL of the database. What should your model contain?





Answer: A

Question 73
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You create a Database Access Layer (DAL) that is database-independent. The DAL includes the following code segment. (Line numbers are included for reference only.)
01 static void ExecuteDbCommand(DbConnection connection) 02 { 03 if (connection != null){ 04 using (connection){ 05 try{ 06 connection.Open(); 07 DbCommand command = connection.CreateCommand(); 08 command.CommandText = "INSERT INTO Categories (CategoryName) VALUES ('Low Carb')"; 09 command.ExecuteNonQuery(); 10 } 11 ... 12 catch (Exception ex){ 13 Trace.WriteLine("Exception.Message: " + ex.Message); 14 } 15 } 16 } 17 }
You need to log information about any error that occurs during data access. You also need to log the data provider that accesses the database. Which code segment should you insert at line 11?
A. catch (OleDbException ex){ Trace.WriteLine("ExceptionType: " + ex.Source); Trace.WriteLine("Message: " + ex.Message);
}
B. catch (OleDbException ex){ Trace.WriteLine("ExceptionType: " + ex.InnerException.Source); Trace.WriteLine("Message: " + ex.InnerException.Message);
}
C. catch (DbException ex){ Trace.WriteLine("ExceptionType: " + ex.Source); Trace.WriteLine("Message: " + ex.Message);
}

D. catch (DbException ex){ Trace.WriteLine("ExceptionType: " + ex.InnerException.Source); Trace.WriteLine("Message: " + ex.InnerException.Message);
}

Answer: C
Question 74
Which code segment will properly return the TimeSpan returned by the stopWatch variable?
A. Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); DoSomething(); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine(elapsedTime, "RunTime");
private void DoSomething()
{ ... }
B. Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); DoSomething(); stopWatch.Reset(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine(elapsedTime, "RunTime");
private void DoSomething()
{ ... }
C. Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); DoSomething(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine(elapsedTime, "RunTime");

private void DoSomething() { ... }
D. Stopwatch stopWatch = new Stopwatch(); stopWatch.Begin(); DoSomething(); stopWatch.End(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine(elapsedTime, "RunTime");
private void DoSomething() { ... }

Answer: A
Question 75
You are a tasked with performing a code review. The business rule is the following: If INSERTs into the first table succeed, then INSERT into the second table. However, if the INSERTs into the second table fail, roll back the inserts in the second table but do not roll

back the inserts in the first table. Although this can also be done by way of regular transactions, It needs to be performed using TransactionScope objects.
Whis code would fit this business rule?
A. try
{ using (TransactionScope scope1 = new TransactionScope(TransactionScopeOption) {
.... try {
..... using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption)) { .... } } }

}
B. try { using (TransactionScope scope1 = new TransactionScope(TransactionScopeOption.Required))
{ ... using (TransactionScope scope2 = new
TransactionScope(TransactionScopeOption.RequiresNew)) { .... } ......
} }
C. try { using (TransactionScope scope1 = new TransactionScope(TransactionScopeOption.Required)) {
... }
using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew)) { .... } }
D. try { using (TransactionScope scope1 = new TransactionScope(TransactionScopeOption.Required))
{ .... try {
..... using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequiresNew)) { .... } }

} }

Answer: D
Question 76
Which method will return all nodes of an XDocument?
A. doc.DescendantNodes();
B. doc.Descendants();
C. doc.Root.Allnodes();
D. doc.GetAllnodes();

Answer: A
Question 77
Which one of these samples it the correct way to close the connection using Command Behavior?
A. SqlDataReader rdr = new SqlDataReader(); string sql = @"sql statement"; SqlConnection conn = connection.GetConnection(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); Console.WriteLine("{0}", rdr);
B. SqlDataReader rdr = new SqlDataReader(); string sql = @"sql statement"; SqlConnection conn = connection.GetConnection(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); rdr.Close(); Console.WriteLine("{0}", rdr);
C. SqlDataReader rdr = new SqlDataReader(); string sql = @"sql statement"; SqlConnection conn = connection.GetConnection(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); conn.Close(); Console.WriteLine("{0}", rdr); D. using (SqlDataReader rdr = new SqlDataReader())

{ string sql = @"sql statement"; SqlConnection conn = connection.GetConnection(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); Console.WriteLine("{0}", rdr);
}

Answer: B
Question 78
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. The database includes a database table named ProductCatalog as shown in the exhibit:

You add the following code segment to query the first row of the ProductCatalog table. (Line numbers are included for reference only.)
01 using(SqlConnection cnx = new SqlConnection(connString)
02 {
03 var command = cnx.CreateCommand();
04 command.CommandType = CommandType.Text;
05 command.CommandText = "SELECT TOP 1 * FROM dbo.ProductCatalog";
06 cnx.Open();
07 var reader = command.ExecuteReader();
08 if (reader.Read())
09 {
10 var id = reader.GetInt32(0);
11 ...
12 reader.Close();
13 }
14 }

Which answer belongs in line 11?


A. var weight = reader.GetDouble(1); var price = reader.GetDecimal(2); var status = reader.GetBoolean(3);
B. var weight = reader.GetFloat(1); var price = reader.GetDecimal(2); var status = reader.GetByte(3);
C. var weight = reader.GetDouble(1); var price = reader.GetFloat(2); var status = reader.GetBoolean(3);
D. var weight = reader.GetFloat(1); var price = reader.Doublel(2); var status = reader.GetByte(3);

Answer: A
Question 79
You have been assigned the task of writing code that executes an Entity SQL query that returns entity type objects that contain a property of a complex type. (Line numbers are included for reference only.)
01 using (EntityCommand cmd = conn.CreateCommand()) 02 { 03 cmd.CommandText = esqlQuery; 04 EntityParameter param = new EntityParameter(); 05 param.ParameterName = "id"; 06 param.Value = 3; 07 cmd.Parameters.Add(param); 08 using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) 09 { 10 while (rdr.Read()) 11 { 12 ... 13 Console.WriteLine("Email and Phone Info:"); 14 for (int i = 0; i < nestedRecord.FieldCount; i++) 15 {

Console.WriteLine(" " + nestedRecord.GetName(i) + ": " +
nestedRecord.GetValue(i)); 17 } 18 } 19 } 20 }
Which code segment should you insert at line 12?
A. DbDataRecord nestedRecord = rdr["EmailPhoneComplexProperty"] as DbDataRecord;
B. DbDataRecord nestedRecord = rdr["EmailPhoneComplexProperty"]
C. DataSet nestedRecord = rdr["EmailPhoneComplexProperty"] as ComplexDataSet
D. ComplexDataRecord nestedRecord = rdr["EmailPhoneComplexProperty"]

Answer: A
Question 80
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You create the classes shown in the following exhibit:

You add the following code segment to the application. (Line numbers are included for reference only.)
01 public void QueryPlayers (List leagues) { 02 ... 03 }
You create a LINQ query to retrieve a collection of Player objects. You need to ensure that the collection includes all the players from each team and every league. Which code segment should you insert at line 02?
A. var query = leagues.Select(l => l.Teams.Select(t => t.Players));
B. var query = leagues.Select(l => l.Teams.SelectMany(t => t.Players));
C. var query = leagues.SelectMany(l => l.Teams.SelectMany(t => t.Players));


D. var query = leagues.SelectMany(l => l.Teams.Select(t => t.Players));

Answer: C
Question 81
How do you call a model-defined function as static method on a custom class?
A. Add a class to your application with a static method that does the following: Apply an EdmFunctionAttribute to the method and ensure it accepts an IQueryable argument and returns the results of the Execute method that is returned by the Provider property.
B. Add a class to your application with a static method that does the following: Apply an EdmFunctionAttribute to the method and ensure it accepts IEntityWithRelationships argument and returns the results of the Execute method that is returned by the Provider property.
C. Add a class to your application with a static method that does the following: Apply an EdmFunctionAttribute to the method and ensure it accepts ICollection argument and returns the results of the Execute method that is returned by the Provider property.
D. Add a class to your application with a static method that does the following: Apply an EdmFunctionAttribute to the method and ensure it accepts and returns the results of the Execute method that is returned by the Provider property.

Answer: A
Question 82
The database contains a table named Categories. The Categories table has a primary key identity column named CategoryID. The application inserts new records by using the following stored procedure.
CREATE PROCEDURE dbo.InsertCategory @CategoryName nvarchar(15), @Identity int OUT
AS INSERT INTO Categories (CategoryName) VALUES(@CategoryName) SET @Identity = SCOPE_IDENTITY() RETURN @@ROWCOUNT
You write the following code segment.

SqlDataAdapter adapter = new SqlDataAdapter("SELECT categoryID, CategoryName FROM dbo.Categories",connection); adapter.InsertCommand = new SqlCommand("dbo.InsertCategory", connection); adapter.InsertCommand.CommandType = commandType.StoredProcedure; adapter.InsertCommand.Parameters.Add(new SqlParameter("@CategoryName", SqlDbType.NVarChar, 15,"CategoryName"));
You need to retrieve the identity value for the newly created record. Which code segment should you add?
A. SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@CategoryName", SqlDbType.Int); parameter.Direction = ParameterDirection.Output; parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.Output;
B. SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@CategoryName", SqlDbType.Int); parameter.Direction = ParameterDirection.Output; parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.ReturnValue;
C. SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@RowCount", SqlDbType.Int); parameter.Direction = ParameterDirection.ReturnValue; parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.Output;
D. SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@RowCount", SqlDbType.Int); parameter.Direction = ParameterDirection.Output; parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.ReturnValue;
Answer: C
Question 83
The application populates a DataSet object by using a SqlDataAdapter object.

You use the DataSet object to update the Categories database table in the database. You write the following code segment. (Line numbers are included for reference only.)
01 SqlDataAdapter dataAdpater = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM Categories", connection); 02 SqlCommandBuilder builder = new SqlCommandBuilder(dataAdpater); 03 DataSet ds = new DataSet(); 04 dataAdpater.Fill(ds); 05 foreach (DataRow categoryRow in ds.Tables[0].Rows) 06 { 07 if (string.Compare(categoryRow["CategoryName"].ToString(), searchValue, true) == 0) 08 { 09 ... 10 } 11 } 12 dataAdpater.Update(ds);
You need to remove all the records from the Categories database table that match the value of the searchValue variable. Which line of code should you insert at line 09?
A. categoryRow.Delete();
B. ds.Tables[0].Rows.RemoveAt(0);
C. ds.Tables[0].Rows.Remove(categoryRow);
D. ds.Tables[0].Rows[categoryRow.GetHashCode()].Delete();

Answer: A
Question 84
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses the ADO.NET Entity Framework to model entities. The database includes objects based on the exhibit. (Click the Exhibit button.)
The application includes the following code segment. (Line numbers are included for reference only.)
01 using (AdventureWorksEntities advWorksContext = new AdventureWorksEntities()){ 02 ... 03 }
You need to retrieve a list of all Products from todays sales orders for a specified customer.

You also need to ensure that the application uses the minimum amount of memory when retrieving the list. Which code segment should you insert at line 02?
A. Contact customer = context.Contact.Where("it.ContactID = @customerId", new ObjectParameter("customerId", customerId)).First(); customer.SalesOrderHeader.Load(); foreach (SalesOrderHeader order in customer.SalesOrderHeader) {
order.SalesOrderDetail.Load(); if (order.OrderDate.Date == DateTime.Today.Date) {
foreach (SalesOrderDetail item in order.SalesOrderDetail) { Console.WriteLine(String.Format("Product: {0} ", item.ProductID)); } } }
B. Contact customer = context.Contact.Where("it.ContactID = @customerId", new ObjectParameter("customerId", customerId)).First(); customer.SalesOrderHeader.Load(); foreach (SalesOrderHeader order in customer.SalesOrderHeader) {
if (order.OrderDate.Date == DateTime.Today.Date)
{ order.SalesOrderDetail.Load(); foreach (SalesOrderDetail item in order.SalesOrderDetail) {
Console.WriteLine(String.Format("Product: {0} ", item.ProductID)); } } }
C. Contact customer = (from contact in context.Contact.Include("SalesOrderHeader") select contact).FirstOrDefault(); foreach (SalesOrderHeader order in customer.SalesOrderHeader) {
order.SalesOrderDetail.Load(); if (order.OrderDate.Date == DateTime.Today.Date) {
foreach (SalesOrderDetail item in order.SalesOrderDetail) {

Console.WriteLine(String.Format("Product: {0} ", item.ProductID)); } } }
D. Contact customer = (from contact in context.Contact.Include("SalesOrderHeader.SalesOrderDetail") select contact).FirstOrDefault(); foreach (SalesOrderHeader order in customer.SalesOrderHeader) {
if (order.OrderDate.Date == DateTime.Today.Date)
{ foreach (SalesOrderDetail item in order.SalesOrderDetail) {
Console.WriteLine(String.Format("Product: {0} ", item.ProductID)); } } }

Answer: B
Question 85
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application contains the following code segment. (Line numbers are included for reference only.)
01 class DataAccessLayer 02 {
03 private static string connString;
04 ...
05 ...
06 public static DataTable GetDataTable(string command){
07 ...
08 ...
09 }

10 }
You need to define the connection life cycle of the DataAccessLayer class. You also need to ensure that the application uses the minimum number of connections to the database. What should you do?
A. Insert the following code segment at line 04.

private static SqlConnection conn = new SqlConnection(connString); public static void Open() {
conn.Open(); } public static void Close() {
conn.Close(); }
B. Insert the following code segment at line 04.
private SqlConnection conn = new SqlConnection(connString); public void Open() {
conn.Open(); } public void Close() {
conn.Close(); }
C. Replace line 01 with the following code segment.
class DataAccessLayer : IDisposable
Insert the following code segment to line 04.
private SqlConnection conn = new SqlConnection(connString); public void Open() {
conn.Open(); } public void Dispose() {
conn.Close(); }
D. Insert the following code segment at line 07:
using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); }
Answer: D Question 86

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. The application contains two SqlCommand objects named cmd1 and cmd2. You need to measure the time required to execute each command. Which code segment should you use?
A. Stopwatch w1 = new Stopwatch(); w1.Start(); cmd1.ExecuteNonQuery(); w1.Stop(); Trace.WriteLine(w1.ElapsedMilliseconds); w1.Start(); cmd2.ExecuteNonQuery(); w1.Stop(); Trace.WriteLine(w1.ElapsedMilliseconds);
B. Stopwatch w1 = new Stopwatch(); w1.Start(); cmd1.ExecuteNonQuery(); w1.Stop(); Trace.WriteLine(w1.ElapsedMilliseconds); w1.Reset(); cmd2.ExecuteNonQuery(); w1.Stop(); Trace.WriteLine(w1.ElapsedMilliseconds);
C. Stopwatch w1 = Stopwatch.StartNew(); cmd1.ExecuteNonQuery(); w1.Stop(); Trace.WriteLine(w1.ElapsedMilliseconds); w1.Start(); cmd2.ExecuteNonQuery(); w1.Stop(); Trace.WriteLine(w1.ElapsedMilliseconds);
D. Stopwatch w1 = Stopwatch.StartNew(); cmd1.ExecuteNonQuery(); w1.Stop(); Trace.WriteLine(w1.ElapsedMilliseconds); w1 = Stopwatch.StartNew(); cmd2.ExecuteNonQuery();

w1.Stop(); Trace.WriteLine(w1.ElapsedMilliseconds);

Answer: D
Question 87
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to two different Microsoft SQL Server 2008 database servers named Server1 and Server2. A string named sql1 contains a connection string to Server1. A string named sql2 contains a connection string to Server2.
01 using (TransactionScope scope = new 02 ... 03 ) 04 {
05 using (SqlConnection cn1 = new SqlConnection(sql1))
06 {
07 try{
08 ...
09 }
10 catch (Exception ex)
11 {
12 }
13 }
14 scope.Complete();

15 }
You need to ensure that the application meets the following requirements: There is a SqlConnection named cn2 that uses sql2. The commands that use cn1 are initially enlisted as a lightweight transaction.
The cn2 SqlConnection is enlisted in the same TransactionScope only if commands executed by cn1 do not throw an exception. What should you do?
A. Insert the following code segment at line 02.
TransactionScope(TransactionScopeOption.Suppress)
Insert the following code segment at line 08.
using (SqlConnection cn2 = new SqlConnection(sql2)) { try

{ cn2.Open(); ... cn1.Open(); ...
} catch (Exception ex){} }
B. Insert the following code segment at line 02.
TransactionScope(TransactionScopeOption.Suppress)
Insert the following code segment at line 08.
cn1.Open(); ... using (SqlConnection cn2 = new SqlConnection(sql2)) {
try
{ cn2.Open(); ...
} catch (Exception ex){} }
C. Insert the following code segment at line 02.
TransactionScope(TransactionScopeOption.RequiresNew)
Insert the following code segment at line 08.
using (SqlConnection cn2 = new SqlConnection(sql2)) {
try{ cn2.Open(); ... cn1.Open(); ...
} catch (Exception ex){} }
D. Insert the following code segment at line 02.
TransactionScope(TransactionScopeOption.RequiresNew)

Insert the following code segment at line 08.
cn1.Open(); ... using (SqlConnection cn2 = new SqlConnection(sql2)) {
try
{ cn2.Open(); ...
} catch (Exception ex){} }

Answer: B
Question 88
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application uses the ADO.NET Entity Framework to model entities. The conceptual schema definition language (CSDL) file contains the following XML fragment.
... Nullable="false" /> ...


You write the following code segment. (Line numbers are included for reference only.)
01 using (EntityConnection conn = new EntityConnection("name=AdvWksEntities")) 02 {
03 conn.Open();
04 string esqlQuery = @"SELECT VALUE contacts FROM
05 AdvWksEntities.Contacts AS contacts
06 WHERE contacts.ContactID == 3";


07 using (EntityCommand cmd = conn.CreateCommand()) 08 { 09 cmd.CommandText = esqlQuery; 10 using (EntityDataReader rdr = cmd.ExecuteReader()) 11 { 12 while (rdr.Read()) 13 { 14 ... 15 } 16 } 17 } 18 conn.Close(); 19 }
You need to ensure that the code returns a reference to a ComplexType entity in the model named EmailPhone. Which code segment should you insert at line 14?
A. int FldIdx = 0; EntityKey key = record.GetValue(FldIdx) as EntityKey; foreach (EntityKeyMember keyMember in key.EntityKeyValues) {
return keyMember.Key + " : " + keyMember.Value; }
B. IExtendedDataRecord record = rdr["EmailPhone"]as IExtendedDataRecord; int FldIdx = 0; return record.GetValue(FldIdx);
C. DbDataRecord nestedRecord = rdr["EmailPhoneComplexProperty"] as DbDataRecord; return nestedRecord;
D. int fieldCount = rdr["EmailPhone"].DataRecordInfo.FieldMetadata.Count; for (int FldIdx = 0; FldIdx < fieldCount; FldIdx++) { rdr.GetName(FldIdx); if (rdr.IsDBNull(FldIdx) == false) {
return rdr["EmailPhone"].GetValue(FldIdx).ToString(); } }


Answer: C
Question 89
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. You must retrieve a connection string. Which of the following is the correct connection string?
A. string connectionString = ConfigurationSettings.AppSettings["connectionString"];
B. string connectionString = ConfigurationManager.AppSettings["connectionString"];
C. string connectionString = ApplicationManager.ConnectionStrings["connectionString"];
D. string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;

Answer: D
Question 90
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database.
SQLConnection conn = new SQLConnection(connectionString); conn.Open(); SqlTransaction tran = db.BeginTransaction(IsolationLevel. ...); ...
You must retrieve not commited records originate from various transactions. Which method should you use?
A. ReadUncommited
B. ReadCommited
C. RepeatableRead
D. Serializable

Answer: A
Question 91
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. The application uses a Microsoft ADO.NET SQL Server managed provider.
"Data Source=myServerAddress; Initial Catalog=myDataBase; User Id=myUsername;

Password=secret;"
You need to ensure that the database credentials are secure. Which is the correct Property to insert?
A. Integrated Security=SSPI;
B. Persist Security Info=true;
C. Persist Security Info=false;
D. Integrated Security=false;

Answer: C
Question 92
You use Microsoft .NET Framework 4.0 to develop an ASP.NET application. The application uses Integrated Windows authentication. The application accesses data in a Microsoft SQL Server 2008 database that is located on the same server as the application. You use the following connection string to connect to the database.
Integrated Security=SSPI; Initial Catalog=AdventureWorks;
The application must also execute a stored procedure on the same server on a database named pubs. Users connect to the ASP.NET application through the intranet by using Windows-based authentication. You need to ensure that the application will use connection pooling whenever possible and will keep the number of pools to a minimum. Which code segment should you use?
A. command.CommandText = "USE [pubs]; exec uspLoginAudit;"; using (SqlConnection connection = new SqlConnection( "Initial Catalog=AdventureWorks; Integrated Security=SSPI; MultipleActiveResultSets=True")) {
connection.Open(); command.ExecuteNonQuery(); }
B. command.CommandText = "exec uspLoginAudit;";
using (SqlConnection connection = new SqlConnection( "Integrated Security=SSPI;")) { connection.Open(); command.ExecuteNonQuery();
}
C. command.CommandText = "USE [pubs]; exec uspLoginAudit;"; using (SqlConnection connection = new SqlConnection( "Integrated Security=SSPI; Initial Catalog=AdventureWorks")) {

connection.Open(); command.ExecuteNonQuery(); }
D. command.CommandText = "exec uspLoginAudit;"; using (SqlConnection connection = new SqlConnection( "Integrated Security=SSPI; Initial Catalog=pubs")) {
connection.Open(); command.ExecuteNonQuery(); }

Answer: C
Question 93
You use Microsoft Visual Studio 2010 and .NET Framework 4.0 to enhance and existing application use Entity Framework. The classes that represent the entites in the model are Plain old CLR Object (POCO) Classes. You need to connect the existing POCO classes to an entity framework context. What should you do?
A. 1. Generate a MetadataWorkspace and create an ObjectContext for the model.
2.
Disable Proxy object creation on the ContextOptions of the ObjectContext.

3.
Enable lazy loading on the ContextOptions of the ObjectContext.


B. 1. Generate a MetadataWorkspace and create an ObjectContext for the model.
2.
Create an ObjectSet fort he POCO classes.

3.
Disable Proxy object creation on the ContextOptions of the ObjectContext.


C. 1. Generate an Entity Data Model fort he POCO classes.
2.
Create an ObjectSet fort he POCO classes.

3.
Disable Proxy object creation on the ContextOptions of the ObjectContext.

4.
Enable lazy loading on the ContextOptions of the ObjectContext.


D. 1. Generate an Entity Data Model for the POCO classes.
2.
Create an ObjectSet for the POCO classes.

3.
Set Code Generation Strategy on the Entity Data Model to none.

4.
Create an ObjectContext for the model.


Answer: D Question 94

You use Microsoft Visual Studio 2010 and .NET Framework 4.0 to develop an application. You use entity Framework Designer to create an Entity Data Model from an existing database by using the Generate From Database wizard. The model contains an entity type named Product. The Product type requires an additional property that is not mapped to database colomn. You need to add the property to product. What should you do?
A. Add the property in the generated class file, and select Run Custom Tool from the solution menu.
B. Add the property in a partial class named Product in a new source file.
C. Create a comlex type with the name of the property in the Entity Framework Designer.
D. Create a function import with the name of property in the Entity Framework Designer.

Answer: B
Question 95
You use Microsoft Visual Studio 2010 and .NET Framework 4.0 to develop an application that uses the Entity Framewok. You need to execute custom logic when an entity is attached to the ObjectContext. What should you do?
A. Create a partial method named OnStateChanged in the partial class for the entity.
B. Create a partial method named OnAttached in the partial class for the entity.
C. Create an event handler to handle the ObjectStateManagerChanged event.
D. Create an event handler to handle the ObjectMaterialized event.

Answer: C
Question 96
You use Microsoft Visual Studio 2010 and .NET Framework 4.0 to develop an application that uses the Entity Data Model for the fallowing database tables.


You need to ensure that the entity that is mapped to the ContectTypeDerived table derives from the entity that is mapped to the ContentTypeBase table. What should you do?
A. Use a Table-Per-Type mapping method.
B. Use a Table-Per-Hierarchy mapping method.
C. Create a function import for each entity.
D. Create a complect type for each entity.

Answer: A
Question 97
You use Microsoft Visual Studio 2010 and .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. The application contains the following code segment.
string SQL = string.Format(��SELECT * FROM Customer WHERE CompanyName LIKE ��%{0}%��, companyName); var cmd = new SqlCommand(SQL, con);
You need to reduce the vulnerability to SQL injection attacks. Which code segment should you use?
A. string SQL = ��SELECT * FROM Customer Where �� + ��CompanyName LIKE @companyName��; var cmd = new SqlCommand(SQL,con); cmd.Parameters.AddWithValue(��@companyName��, string.Format(��%{0}%��, companyName));
B. string SQL = ��SELECT * FROM Customer Where �� + ��CompanyName LIKE @companyName��; var cmd = new SqlCommand(SQL,con); var param = new SqlParameter (��@companyName��, string.Format(��%{0}%��, companyName));
C. string SQL = string.Format(��SELECT * FROM �� + �� Customer Where CompanyName LIKE {0}��,
new SqlCommand(��@companyName��, string.format(��%{0}%��, companyName))); var cmd = new SqlCommand(SQL, con);
D. string SQL = ��SELECT�� * FROM Customer @companyName; var cmd = new sqlcommand(SQL,con); cmd.Parameters.AddWithValue(��companyName��, string.format(��where

companyName LIKE ��%{0}%����, companyName));

Answer: A
Question 98
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Communication Foundation (WCF) Data Services service. WCF Data Services uses an authentication scheme that requires an HTTP request that has the following header format:
GET /Odata.svc/Products(1) Authorization: WRAP access_token=��123456789��
The application includes the following code. (Line numbers are included for reference only.)
01 public class program 02 { 03 Public void GetProducts() 04 { 05 var proxy = new MyDataServiceContext("..."); 06 ... 07 } 08 }
You need to ensure that the correct authentication header is present when requests are made by using MyDataServiceContext. What should you do?
A. Insert the following code segmen at line 06:
Proxy.Credentials = new NetworkCredential(��WRAP access_token��,
��123456789��);
B. Insert the following code segment at line 06:
Proxy.Credentials = new NetworkCredential(��Authorization��, ��WRAP
access_token=\��123456789��\����);
C. Insert the following code segmen at line 06:
Proxy.SendingRequest += new
EventHandler(proxy_SendingRequest);
Insert the following code segmen at line 09:

void proxy_SendingRequest(object sender, SendingRequestEventArgs e){ e.RequestsHeaders.Add(��WRAP access_token��, ��123456789��); }
D. Insert the following code segment at line 06:
Proxy.SendingRequest += new EventHandler(proxy_SendingRequest);
Insert the following code segment at line 09:
void proxy_SendingRequest(object sender, SendingRequestEventArgs e){
e.RequestsHeaders.Add(��Authorization��,��WRAP access_token��, ��123456789��); }

Answer: D
Question 99
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create a Windows Communication Foundation (WCF) Data Services service. The solution contains the projects shown in the following table.

The WCF data service exposes an Entity Framework model. You need to Access the service by using a WCF Data Services client. What should you do in the Application.Client Project?
A. Add a referance to the Application.Model Project.
B. Add a referance to the Application.Service Project.
C. Add a service reference that uses the URL of the WCF data service.
D. Add a web reference that uses the URL of the WCF data service.

Answer: C
Question 100
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application contains the following XML document:


Author1

Author1 Author2 Author3

Author4 Author3

You add the following code fragment. (Line numbers are included for reference only.)
01 public IEnumerable GetBooks(string xml) 02 { 03 XDocument doc = XDocument.Parse(xml); 04 ... 05 }
You need to return a list of book XML element that are authored by Author1. Which code segment should you insert at line 04?
A. return doc.Element("bib").Elements()
.SelectMany(el => el.Elements() .Where(e2 => e2.Equals(new XElement("author", "Author1"))));
B. return doc.Element("bib").Elements()
.SelectMany(el => el.Elements() .Where(e2 => (string)e2 == "Author1"));
C. return doc.Elements("bib").Elements() .Where(e1 => e1.Elements().Any(e2 => (string)e2 == "Author1"));
D. return doc.Elements("bib").Elements()
.Where(e1 => e1.Elements().Any(e2 => e2.Equals(new XElement("author", "Author1"))));


Answer: C
Question 101
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. You add the following store procedure to the database.
CREATE PROCEDURE GetProducts AS BEGIN
SELECT ProductID, Name, Price, Cost FROM Product END
You create a SqlDataAdapter named adapter to execute the stored procedure. You need to fill a DataTable instance with the first 10 rows of the result set. What are two possible code segments that you can use to achieve the goal?
A. DataSet ds = new DataSet(); adapter.Fill(ds, 0, 10, "Product");
B. DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add("Product"); adapter.Fill(0, 10, dt);
C. DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add("Product"); dt.ExtendedProperties["RowCount"] = 10; dt.ExtendedProperties["RowIndex"] = 0; adapter.Fill(dt);
D. DataSet ds = new DataSet(); ds.ExtendedProperties["RowCount"] = 10; ds.ExtendedProperties["RowIndex"] = 0; adapter.Fill(ds);
Answer: AB
Question 102
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application.

The application retreives data from Microsoft SQL Server 2008 database named AdventureWorks.
The AdventureWorks.dbo.ProductDetails table contains a column names ProductImages that uses a varbinary(max) data type.
You write the following code segment. (Line numbers are included for reference only.)
01 SqlDataReader reader = command.ExecureReader(--empty phrase here --); 02 while(reader.Read()) 03 { 04 pubID = reader.GetString(0); 05 stream = new FileStream(...); 06 writer = new BinaryWriter(stream); 07 startIndex = 0; 08 retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize); 09 while(retval == bufferSize) 10 { 11 ... 12 } 13 writer.Write(outbyte, 0, (int)retval-1); 14 writer.Flush(); 15 writer.Close(); 16 stream.Close(); 17 }
You need to ensure that the code supports streaming data from the ProductImages column. Which code segment should you insert at the empty phrase in line 01?
A. CommandBehavior.Default
B. CommandBehavior.KeyInfo
C. CommandBehavior.SingleResult
D. CommandBehavior.SequentialAccess

Answer: D
Question 103
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. The application performs a database query within a transaction. You need to ensure that the application can read data that has not yet beed commited by other transactions. Which IsolationLevel should you use?
A. ReadUncommitted

B. ReadCommitted
C. RepeatableRead
D. Unspecified

Answer: A
Question 104
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. The application includes a SqlConnection named conn and a SqlCommand named cmd. You need to create a transaction so that database changes will be reverted in the event that an exception is thrown. Which code segment should you use?
A. var transaction = conn.BeginTransaction(); cmd.Transaction = transaction; try {
...
transaction.Commit(); } catch {
transaction.Rollback(); }
B. var transaction = conn.BeginTransaction(); cmd.Transaction = transaction; try {
...
transaction.Commit(); } catch {
transaction.Dispose(); }
C. var transaction = conn.BeginTransaction(); cmd.Transaction = transaction; try {

... } catch {
transaction.Commit(); }
D. var transaction = conn.BeginTransaction(); cmd.Transaction = transaction; try {
...
transaction.Rollback(); } catch {
transaction.Dispose(); }

Answer: A
Question 105
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You create a stored procedure to insert a new record in the Categories table according to following code segment.
CREATE PROCEDURE dbo.InsertCategory @CategoryName navrchar(15), @Identity int OUT
AS INSERT INTO Categories(CategoryName) VALUES (@CategoryName) SET @Identity = SCOPE_IDENTITY() RETURN @@ROWCOUNT
You add the following code fragment. (Line numbers are included for reference only.)
01 private static void ReturnIdentity(string connectionString)
02 {
03 using(SqlConnection conn ec tion = new SqlConnection(connectionString))
04 {
05 SqlDataAdpater adapter = new SqlDataAdapter("SELECT CategoryID, CategoryName

FROM dbo.Categories", connection);

06 adapter.InsertCommand = new SqlCommand("InsertCategory", connection); 07 adapter.InsertCommand.CommandType = CommandType.StoredProcedure; 08 SqlParameter rowcountParameter = adapter.InsertCommand.Parameters.Add("@RowCount", SqlDbType.Int); 09 ... 10 adapter.InsertCommand.Parameters.Add("@CategoryName", SqlDbType.NChar, 15, "CategoryName"); 11 SqlParameter identityParameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); 12 ... 13 DataTable categories = new DataTable(); 14 adapter.Fill(categories); 15 DataRow ctegoryRow = categories.NewRow(); 16 categoryRow["CategoryName"] = "New beverages"; 17 categories.Rows.Add(categoryRow); 18 adapter.Update(categories); 19 Int32 rowCount = (Int32)adapter.InsertCommand.Parameters["@RowCount"].Value; 20 } 21 }
Which code elements needs to be added in the empty lines?
A. Insert the following code segment at line 09:
rowcountParameter.Direction = ParameterDirection.ReturnValue;
Insert the following code segment at line 12:
identityParameter.Direction = ParameterDirection.ReturnValue;
B. Insert the following code segment at line 09:
rowcountParameter.Direction = ParameterDirection.Output;
Insert the following code segment at line 12:
identityParameter.Direction = ParameterDirection.Output;
C. Insert the following code segment at line 09:
rowcountParameter.Direction = ParameterDirection.ReturnValue;
Insert the following code segment at line 12:
identityParameter.Direction = ParameterDirection.Output;
D. Insert the following code segment at line 09:
rowcountParameter.Direction = ParameterDirection.Output;

Insert the following code segment at line 12:
identityParameter.Direction = ParameterDirection.ReturnValue;

Answer: C
Question 106
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses the EntityFramework. The application has an entity named Person. A Person instance named person1 and an ObjectContext instance named model exist. You need to delete the person1 instance. Which code segment should you use?
A. model.DeleteObject(person1); model.SaveChanges();
B. model.Detach(person1); model.SaveChanges();
C. model.ExecuteStoreCommand("Delete", new []{new ObjectParameter("Person", person1)}; model.SaveChanges();
D. model.ExecuteStoreCommand("Detach", new []{new ObjectParameter("Person", person1)}; model.SaveChanges();

Answer: A
Question 107
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that connects to a MS SQL server 2008 database by User Authentication. The application contains the following connection string:
SERVER=DBSERVER-01; DATABASE=pubs; uid=sa; pwd=secret;
You need to ensure that the password value in the connection string property of a SqlConnection object does not exist after is called.

What should you add to the connection string?
A. Persist Security Info = True
B. Trusted_Connection = True
C. Persist Security Info = False
D. Trusted_Connection = False

Answer: C
Question 108
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the Entity Framework Designer to create an Entity Data Model using model-first development.
The database has the following requirements:

each table must have a datetime column named time_modified
each table requires a trigger that updates the value of the time_modified column when a row is inserted or
updated
You need to ensure that the database script that is created by using the Generate Database From Model option meets the requirements. What should you do?
A. Create a new T4 template, and set the DDL Generation template to the name of the new template.
B. Create a new Windows Workflow Foundation workflow, and set Database Generation Workflow to the name of the new workflow.
C. Add a DateTime property named time_modified to each entity in the model and set the property's StoreGeneratedPattern to Computed.
D. Add a new entity named time_modified to the model, and modify each existing entity so that it inherits from the new entity.

Answer: A
Question 109
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities as shown in the following diagram.


You create an ObjectContext instance named objectContext1 and use it to create a SalesPerson instance named person1. You create an ObjectContext instance named objectContext2 and use it to create a SalesTerritory instance named territory1. You need to create and persist a relationship between person1 and terrotory1. What should you do?
A. Detach person1 from objectContext1. Attach person1 to objectContext2. Set the SalesTerritory property of person1 to territory1. Call SaveChanges on objectContext2.
B. Attach person1 to objectContext2. Attach territory1 to objectContext1. Set the SalesTerritory property of person1 to territory1. Call SaveChanges on both objectContext1 and objectContext2.
C. Detach person1 from objectContext1. Detach territory1 from objectContext2. Set the SalesTerritory property of person1 to territory1. Call Refresh on both objectContext1 and objectContext2.
D. Attach person1 to objectContext2.

Detach territory1 from objectContext2. Set the SalesTerritory property of person1 to territory1. Call Refresh on objectContext1.

Answer: A
Question 110
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses the Entity Framework. You create the following Entity Data Model.

You add the following code fragment:
using(var context = new AdventureWorksLTEntities())
{ Customer cust = context.Customers.First(); cust.CompanyName = "Contoso"; int count = 0;
}
The changes to the cust entity must be saved. If an exception is thrown, the application will attempt to save up to 3 times. If not, an exception is thrown. Which code segment should you use?
A. while(count++ < 3)
{ try

{ context.SaveChanges(); break;
} catch(Exception) { }
}
B. while(cust.EntityState == EntityState.Modified)
{ try {
context.SaveChanges();
} catch(Exception) {
if(count++ > 2 && context.Connection.State == ConnectionState.Broken { throw new Exception(); } } }
C. while(true) { context.SavingChanges += delegate(System.Object o, System.EventArgs e)
{ if(count++ >2) {
throw new Exception(); } context.SaveChanges();
} }
D. while(context.ObjextStateManager.GetObjectStateEntry(cust).OriginalVa lues.IsDBNull(0)) {
if(count++ >2) {

break;
} context.SaveChanges(); }

Answer: B
Question 111
You develop a Microsoft .NET application that uses Entity Framework to store entities in a Microsft SQL Server 2008 database. While the application is disconnected from the database, entities that are modified, are serialized to a local file.
The next time the application connects to the database, it retrieves the identity from the database by using an object context named context and stores the entity in a variable named remoteCustomer. The application then serializes the Customer entity from the local file and stores the entity in a variable named localCustomer. The remoteCustomer and the localCustomer variables have the same entity key.
You need to ensure that the offline changes to the Customer entity is persisted in the database when the ObjectContext.SaveChanges() method is called. Which line of code should you use?
A. context.ApplyOriginalValues("Customers", remoteCustomer);
B. context.ApplyOriginalValues("Customers", localCustomer);
C. context.ApplyCurrentValues("Customers", remoteCustomer);
D. context.ApplyCurrentValues("Customers", localCustomer);

Answer: D
Question 112
You use Microsoft .NET framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database named AdventureWorksLT. The database resides on an instance named INSTA on a server named SQL01. You need to configure the application to connect to the database. Which connection string should you add to the .config file?
A. Data Source=SQL01; Initial Catalog=INSTA; Integrated Security=true; Application Name=AdventureWorksLT;
B. Data Source=SQL01; Initial Catalog=AdventureWorksLT; Integrated Security=true; Application

Name=INSTA;
C. Data Source=SQL01\INSTA; Initial Catalog=AdventureWorksLT; Integrated Security=true;
D. Data Source=AdventureWorksLT; Initial Catalog=SQL01\INSTA; Integrated Security=true;

Answer: C
Question 113
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application uses the ADO.NET Entity Framework to model entities. The database includes objects based on the exhibit (click the Exhibit button).
The application includes the following code segment. (Line numbers are included for reference only.)
01 using(AdventureWorksEntities context = new AdventureWorksEntities()) 02 { 03 ... 04 foreach (SalesOrderHeader order in customer.SalesOrderHeader) 05 { 06 Console.WriteLine(String.Format("Order: {0} ", order.SalesOrderNumber)); 07 foreach (SalesOrderDetail item in order.SalesOrderDetail) 08 { 09 Console.WriteLine(String.Format("Quantity: {0} ", item.Quantity)); 10 Console.WriteLine(String.Format("Product: {0} ", item.Product.Name)); 11 } 12 } 13 }
You want to list all the orders for a specific customer. You need to ensure that the list contains following fields: Order number Quantity of products Product name Which code segment should you insert in line 03?

A. Contact customer = context.Contact.Where("it.ContactID = @customerId",
new ObjectParameter("customerId", customerId)).First();
B. Contact customer = context.Contact.Where("it.ContactID = @customerId",
new ObjectParameter("@customerId", customerId)).First();
C. Contact customer = (from contact in

context.Contact.Include("SalesOrderHeader.SalesOrderDetail")
select contact).FirstOrDefault();
D. Contact customer = (from contact in
context.Contact.Include("SalesOrderHeader") select contact).FirstOrDefault();

Answer: A
Question 114
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You are creating the data layer of the application. You write the following code segment. (Line numbers are included for reference only.)
01 public static SqlDataReader GetDataReader(string sql)
02 {
03 SqlDataReader dr = null;
04 ...
05 return dr;
06 }

You need to ensure that the following requirements are met: The SqlDataReader returned by the GetDataReader method can be used to retreive rows from the database. SQL connections opened within the GetDataReader method will close when the SqlDataReader is closed.
Which code segment should you insert at the line 04?
A. using(SqlConnection cnn = new SqlConnection(strCnn))
{ try {
SqlCommand cmd = new SqlCommand(sql, cnn); cnn.Open(); dr = cmd.ExecuteReader();
} catch {
throw; } }
B. SqlConnection cnn = new SqlConnection(strCnn); SqlCommand cmd = new SqlCommand(sql, cnn); cnn.Open();

{ try {
dr = cmd.ExecuteReader(); } finally {
cnn.Close(); } }
C. SqlConnection cnn = new SqlConnection(strCnn); SqlCommand cmd = new SqlCommand(sql, cnn); cnn.Open(); { try { dr = cmd.ExecuteReader(); cnn.Close(); } catch {
throw; } }
D. SqlConnection cnn = new SqlConnection(strCnn); SqlCommand cmd = new SqlCommand(sql, cnn); cnn.Open(); { try { dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch {
cnn.Close(); throw; } }
Answer: D Question 115

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses the Entity Framework. The application has an entity model that includes SalesTerritory and SalesPerson entities as shown in the following diagram.

You need to calculate the total bonus for all sales people in each sales territory. Which code segment should you use?
A. from person in model.SalesPersons group person by person.SalesTerritory into territoryByPerson select new {
SalesTerritory = territoryByPerson.Key, TotalBonus = territoryByPerson.Sum(person => person.Bonus) };
B. from territory in model.SalesTerritories group territory by territory.SalesPerson into personByTerritories select new {
SalesTerritory = personByTerritories.Key, TotalBonus = personByTerritories.Key.Sum(person => person.Bonus) };

C. model.SalesPersons .GroupBy(person => person.SalesTerritory) .SelectMany(group => group.Key.SalesPersons) .Sum(person => person.Bonus);
D. model.SalesTerritories .GroupBy(territory => territory.SalesPersons) .SelectMany(group => group.Key) .Sum(person => person.Bonus);

Answer: A
Question 116
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server 2008 database. You add the following store procedure to the database.
CREATE PROCEDURE GetSalesPeople AS BEGIN
SELECT FirstName, LastName, Suffix, Email, Phone FROM SalesPeople END
You write the following code segment. (Line numbers are included for reference only.)
01 SqlConnection connection = new SqlConnection("..."); 02 SqlCommand command = new SqlCommand("GetSalesPeople", connection); 03 command.CommandType = CommandType.StoredProcedure; 04 ...
You need to retreive all of the results from the stored procedure. Which code segment should you insert at line 04?
A. var res = command.ExecuteReader();
B. var res = command.ExecuteScalar();
C. var res = command.ExecuteNonQuery();
D. var res = command.ExecuteXmlReader();
Answer: A Question 117

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You add the following table to the database.
CREATE TABLE ObjectCache ( Id INT IDENTITY PRIMARY KEY, SerializedObjectData XML)
You write the following code segment to retreive records from the ObjectCache table. (Line numbers are included for reference only.)
01 string s = GetConnectionStringFromConfigFile("xmldb"); 02 using (SqlConnection conn = new SqlConnection(s)) 03 using (SqlCommand cmd = new SqlCommand("select * from ObjectCache", conn)) 04 { 05 conn.Open(); 06 SqlDataReader rdr = cmd.ExecuteReader(); 07 while(rdr.Read()) 08 { 09 ... 10 DeserializeObject(obj); 11 } 12 }
You need to retreive the data from the SerializedObjectData column and pass it to a method named DeserializeObject. Which line of code should you insert at line 09?
A. XmlReader obj = (XmlReader)rdr[1];
B. SByte obj = (SByte)rdr[1];
C. String obj = (String)rdr[1];
D. Type obj = (Type)rdr[1];

Answer: C
Question 118
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application contains following XML document.
Products

Entry title 1 Author 1
some description some notes some comments

...

You plan to add localization features to the application. You add the following code segment. (Line numbers are included for reference only.)
01 public IEnumerable GetTextNodesForLocalization(XDocument doc) 02 { 03 ... 04 return from n in nodes 05 where n.NodeType = XmlNodeType.Text 06 select n; 07 }
You need to ensure that the GetTextNodeForLocalization method returns all the XML text nodes of the XML document. Which code segment should you inser at line 03?
A. IEnumerable nodes = doc.Descendants();
B. IEnumerable nodes = doc.Nodes();
C. IEnumerable nodes = doc.DescendantNodes();
D. IEnumerable nodes = doc.NodesAfterSelf();

Answer: C
Question 119
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. The application includes two ObjectContext instances named context1 and context2. You need to persist the changes in both object contexts within a single transaction. Which code segment should you use?

A. using (TransactionScope scope = new TransactionScope())
{ context1.SaveChanges(); context2.SaveChanges();
}
B. using (TransactionScope scope = new TransactionScope())
{ context1.SaveChanges(); context2.SaveChanges(); scope.Complete();
}
C. using (TransactionScope scope = new TransactionScope()) { using (TransactionScope scope1 = new TransactionScope(TransactionScopeOption.RequireNew))
{ context1.SaveChanges(); scope1.Complete();
} using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.RequireNew))
{ context2.SaveChanges(); scope2.Complete();
} scope.Complete(); }
D. using (TransactionScope scope = new TransactionScope()) { using (TransactionScope scope1 = new TransactionScope(TransactionScopeOption.RequireNew)) {
context1.SaveChanges(); } using (TransactionScope scope2 = new
TransactionScope(TransactionScopeOption.RequireNew)) { context2.SaveChanges(); }

}

Answer: B
Question 120
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. The application includes self-tracking entities as shown in the following diagram.

There is a Person entity names person1 that has TrackChanges turned on. You need to delete all e-mail addresses that are associated with person1 by using an ObjectContext.
What are two possible code segments that you can use to achieve this goal? (Each correct answer presents a complete solution. Choose two).
A. foreach(var email in person1.EMailAddresses){
email.MarkAsDeleted(); } context.SaveChanges();
B. while(person1.EMailAddresses.Count>0){
person1.EmailAddresses.RemoveAt(0); } context.SaveChanges();
C. person1.EMailAddresses = null; context.SaveChanges();

D. person1.EMailAddresses = new TrackableCollection(); context.SaveChanges();

Answer: AB
Question 121
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses LINQ to SQL. You create a data model name AdvWorksDataContext, and you add the Product table to the data model. The Product table contains a decimal column named ListPrice and a string column named Color. You need to update ListPrice column where the product color is Black or Red. Which code segment should you use?
A. string[] colorList = new string[] {"Black", "Red"}; AdvWorksDataContext dc = new AdvWorksDataContext(); var prod = from p in dc.Products
where colorList.Contains(p.Color) select p; foreach(var product in prod){
product.ListPrice = product.StandardCost * 1.5M; } dc.SubmitChanges();
B. AdvWorksDataContext dc = new AdvWorksDataContext("..."); var prod = from p in dc.Products
select p; var list = prod.ToList(); foreach(Product product in list){
if(product.Color == "Black, Red"){ product.ListPrice = product.StandardCost * 1.5M;
} } dc.SubmitChanges();
C. AdvWorksDataContext dc = new AdvWorksDataContext("...");
var prod = from p in dc.Products where p.Color == "Black, Red" select p;
foreach(var product in prod){

product.ListPrice = product.StandardCost * 1.5M; } dc.SubmitChanges();
D. AdvWorksDataContext dc = new AdvWorksDataContext("..."); var prod = from p in dc.Products
select p; var list = prod.ToList(); foreach(Product product in list){
if((product.Color == "Black) && (product.Color == "Red")){ product.ListPrice = product.StandardCost * 1.5M;
} } dc.SubmitChanges();

Answer: A
Question 122
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. You create an Entity Data Model (EDM) by using the Microsoft ADO.NET Entity Data Model Designer (Entity Designer). The EDM contains a complex type. You need to map a stored procedure to the complex type by using the Entity Designer. What should you do?
A. Add an association to the stored procedure.
B. Add a code generation item that has the name of the stored procedure.
C. Add a function import for the stored procedure.
D. Add an entity that mirrors the properties of the complex type.

Answer: C
Question 123
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The configuration file contains the following code segment.

connectionString="DataSource=SQL01;InitialCatalog=AdventureWorksLT;IntegratedSecu
rity=True;" providerName="System.Data.SqlClient"/>

You need to retrieve the connection string named AdventureWorksLT from the configuration file. Which line of code should you use?
A. varconnectionString=ConfigurationManager.ConnectionStrings["AdventureWorksLT"].Connect ionString;
B. varconnectionString=ConfigurationManager.ConnectionStrings["AdventureWorksLT"].Name;
C. varconnectionString=ConfigurationManager.AppSettings["AdventureWorksLT"];
D. varconnectionString=ConfigurationSettings.AppSettings["AdventureWorksLT"];

Answer: A
Question 124
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses the Entity Framework. You create an Entity Data Model (EDM) named Model. You need to ensure that the Storage Schema Definition Language (SSDL) of the EDM can be modified without rebuilding the application. What should you do?
A. Set the Metadata Artifact Processing property to Embed in Output Assembly and use the following connection string: metadata=res://*/Model.csdl| res://*/Model.ssdl| res://*/Model.msl; provider=System.Data.SqlClient; provider connection string="& "
B. Set the Metadata Artifact Processing property to Copy to Output Directory and use the following connection string: metadata=res://*/Model.csdl| res://*/Model.ssdl| res://*/Model.msl; provider=System.Data.SqlClient; provider connection string ="& "
C. Set the Metadata Artifact Processing property to Embed in Output Assembly and use the following connection string:

metadata=.\Model.csdl| .\Model.ssdl| .\Model.msl; provider=System.Data.SqlClient; provider connection string="& "
D. Set the Metadata Artifact Processing property to Copy to Output Directory and use the following connection string: metadata=.\Model.csdl| .\Model.ssdl| .\Model.msl; provider=System.Data.SqlClient; provider connection string ="& "

Answer: D
Question 125
You use Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You need to prevent dirty or phantom reads. Which IsolationLevel should you use?
A. Serializable
B. Snapshot
C. ReadCommited
D. ReadUncommited
Answer: B
Question 126
You have a ContosoEntities context object named context and a Color object stored in a variable named color.
You write the following code:
context.Colors.DeleteObject(color); context.SaveChanges();
When the code runs, it generates the following exception:
System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for detials. ---> System.Data.SqlClient.SqlException:The DELETE satement conflicted with the REFERENCE

constraint "FK_PartColor".
The conflict occurred in database "Contoso", table "dbo.Parts", column 'ColorId'
You need to resolve the exception without negatively impacting the rest of the application. What should you do?
A. In the database, remove the foreign key association between the Parts table and the Colors table, and then update the entity data model.
B. Add a transation around the call to the SaveChanges() method and handle the exception by performing a retry.
C. Add code before the call to the DeleteObject() method to examine the collection of Part objects associated with the Color object and then assign null to the Color property for each Part object.
D. Change the End2 OnDelete proprety of the FK_PartColor association from None to Cascade
E. Change the End1 OnDelete proprety of the FK_PartColor association from None to Cascade

Answer: C
Question 127
The application user interface displays part names or color names in many plases as '## Name ##'. You need to provide a method named FormattedName() to format part names and color names throughout the application. What should you do?
A. Add the following code segment to the ExtensionMethods class in ExtensionMethods.cs:
public static string FormattedName (this IName entity){ return string.Format("## {0} ##", entity.Name) }
B. Add the following code segment to the ExtensionMethods class in ExtensionMethods.cs:
public static string FormattedName (this Color entity){ return string.Format("## {0} ##", entity.Name) }
C. Add the following code segment to the ExtensionMethods class in ExtensionMethods.cs:
public static string FormattedName (this Part entity){ return string.Format("## {0} ##", entity.Name) }
D. Add the following code segmend to the Color class in Color.cs:
public string FormattedName(){ return string.Format("## {0} ##", this.Name);

}
E. Add the following code segmend to the Part class in Part.cs:
public string FormattedName(){ return string.Format("## {0} ##", this.Name); }

Answer: A
Question 128
The entity data model must be configured to provide a way you cal the sp_FindObsolete stored procedure. The returned data must implement the Descendants property.
In Visual Studio 2010, you open the Add functions Import dialog box from the EDMX diagram and enter the information shown in the following graphic.

You need to complete the configuration in the dialog box. What should you do?


A. Click the Get Column Information button, click Create New Complex Type and then, in the Complex box, enter Parts.
B. In the Returns a Collection Of area, click Scalars and then, in the Scalars list, click string

C. In the Returns a Collection Of area, click Entities and then, in the Entities list, click Component
D. In the Returns a Collection Of area, click Scalars and then, in the Scalars list, click Int32

Answer: C
Question 129
The Entity Data Model file (.edmx file) must be updated to support inheritance mapping for Products and Componets.
You need to add the following code to the \Model\Model.edmx file: the code in line EX243 that maps the Product type the code in line EX250 that maps the Component type What should you do?

A. Insert the following code at line EX243:

Insert the following code at line EX250:

B. Insert the following code at line EX243:

Insert the following code at line EX250:

C. Insert the following code at line EX243:

Insert the following code at line EX250:

D. Insert the following code at line EX243:

Insert the following code at line EX250:

Answer: A Question 130

A performance issue exists in the application. The following code segment is causing a performance bottleneck:
var colors = context.Parts.GetColors();
You need to improve application performance by reducing the number of database calls. Which code segment should you use?
A. var colors = context.Parts.OfType().Include("Colors").GetColors();
B. var colors = context.Parts.OfType().Include("Product.Color").GetColors();
C. var colors = context.Parts.OfType().Include("Parts.Color").GetColors();
D. var colors = context.Parts.OfType().Include("Color").GetColors();

Answer: D
Question 131
The application must be configured to run on a new development computer. You need to configure the connection string to point to the existing named instance. Which connection string fragment should you use?
A. Data Source=INST01\SQL01
B. Initial Catalog= SQL01\INST01
C. Data Source=SQL01\INST01
D. Initial Catalog= INST01\SQL01

Answer: C
Question 132
You have an existing ContosoEntities context object named context. Calling the SaveChanges() method on the context object generates an exception that has the following inner exception:
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Colors' with unique index 'IX_Colors'.

You need to ensure that a call to SaveChanges() on the context object does not generate this exception. What should you do?
A. Examine the code to see how Color objects are allocated. Replace any instance of the new Color() method with a call to the ContosoEntities.LoadOrCreate() method.
B. Add a try/catch statement around every call to the SaveChanges() method.
C. Remove the unique constraint on the Name column in the Colors table.
D. Override the SaveChanges() method on the ContosoEntities class, call the ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added) method, and call the AcceptChanges() method on each ObjectStateEntry object it returns

Answer: A
Question 133
Refer to the following lines in the case study: PA40 in \Model\Part.cs, PR16 in\Model\Product.cs, and CT14 in \Model\Component.cs
The application must create XML files that detail the part structure for any product. The XML files must use the following format:





You need to update the application to support the creation of an XElement object having a structure that will serialize to the format shown above. What should you do? (Each correct answer presents part of the solution. Choose two.)
A. Insert the following code segment at line PR16 in \Model\Product.cs:
return new XElement("product, new XAttribute("name", this.Name), new XElement("description", this.Description), new XElement("productType", this.ProductType));

B. Insert the following code segment at line CT14 in \Model\Component.cs:
return new XElement("component, new XElement("name", this.Name), new XElement("description", this.Description), new XElement("partType", this.PartType));
C. Insert the following code segment at line PR16 in \Model\Product.cs:
return new XElement("product, new XElement("name", this.Name), new XElement("description", this.Description), new XElement("productType", this.ProductType));
D. Insert the following code segment at line PR16 in \Model\Product.cs:
return new XElement("product, new XAttribute("name", this.Name), new XAttribute("description", this.Description), new XAttribute("productType", this.ProductType));
E. Insert the following code segment at line CT14 in \Model\Component.cs:
return new XElement("component, new XAttribute("name", this.Name), new XElement("description", this.Description), new XElement("partType", this.PartType));
F. Insert the following code segment at line CT14 in \Model\Component.cs:
return new XElement("component, new XAttribute("name", this.Name), new XAttribute("description", this.Description), new XAttribute("partType", this.PartType));

Answer: DF
Question 134
You need to ensure that an exception is thrown when color names are set to less than two characters. What should you do?
A. Add the following method to the Color partial class in Model\Color.cs:
protected overrride void OnPropertyChanged(string property) {

if (property == "Name" && this.Name.Length < 2)
throw new ArgumentOutOfRangeException("Name must be at least two characters"); }
B. Add the following code segment to the ContosoEntities partial class in Model\ContosoEntities.cs:
public override in SaveChanges(System.Data.Objects.SaveOptions options)
{ var changes = this.ObjectStateManager.GetObjectSateEntries(System.Data.EntityState .Added); foreach (var change in changes) {
if (change.Entity is Color) if (((Color)change.Entity.Name.Length < 2) throw new ArgumentException("Name too short");
} return base.SaveChanges(options); }
C. Add the following attribute to the Name property of the Color class in the entity designer file:
[StringLength(256, MinimumLength = 2)]
D. Add the following method to the Color partial class in Model\Color.cs:
protected overrride void OnPropertyChanging(string property) {
if (property == "Name" && this.Name.Length < 2) throw new ArgumentOutOfRangeException("Name must be at least two characters");
}
Answer: A
Question 135
You are adding a process to the application. The process performs the following actions:
1.
Opens a ContosoEntities context object named context1.

2.
Loads a Part object into a variable named part1.

3.
Calls the Dispose() method on context1.

4.
Updates the data in part1.

5.
Updates the database by using a new ContosoEntities context object named context2.



You need to update the database with the changed data from part1. What should you do?
A. Add the following code segment before calling SaveChanges() on context2:
context2.ApplyCurrentValues("Parts", part1);
B. Add the following code segment before calling SaveChanges() on context2:
context2.Attach(part1); context2.ApplyCurrentValues("Parts", part1);
C. Add the following code segment before calling SaveChanges() on context2:
context2.Attach(part1); context2.ObjectStateManager.ChangeObjectState(part1, System.Data.EntitySate.Modified);
D. Add the following code segment before calling SaveChanges() on context2:
context2.ApplyOriginalValues("Parts", part1);

Answer: C
Question 136
The application must provide a component part list for any product. The component part list must give the quantity of each distinct part that is required to manufacture that product.
You need to create a LINQ expression that delivers a a result of type IEnumerable> to meet the requirements. Which expression should you use?
A. IEnumerable> result = part.Children .Distinct() .GroupBy(p => p) .Select(g => Tuple.Create(g.Count(), g.Key));

B. IEnumerable> result = part.Descendants .GroupBy(p => p) .Select(g => Tuple.Create(g.Count(), g.Key));
C. IEnumerable> result = part.Descendants .ToDictionary(c => c) .Select(d => Tuple.Create(d.Value.Children.Count(), d.Key));
D. IEnumerable> result = part.Children .GroupBy(p => p) .Select(g => Tuple.Create(g.Count(), g.Key));
E. IEnumerable> result = part.Descendants .Distinct() .GroupBy(p => p) .Select(g => Tuple.Create(g.Count(), g.Key));

Answer: B
Question 137
You are developing a new feature that displays an auto-complete list to users as the type color names. You have an existing ContosoEntities context object named contex.
To support the new feature you must develop code that will accept a string object named text containing a user's partial input and will query the Colors database table to retrieve all color names that begin with that input.
You need to create an Entity SQL (ESQL) query to meet the requirement. The query must not be vulnerable to a SQL injection attack. Which code segment should you use?
A. var parameter = new ObjectParameter("text", text + "%");
var result = context.CreateQuery( "SELECT VALUE (c.Name) FROM Colors AS c WHERE c.Name LIKE '@text'", parameter);
B. var parameter = new ObjectParameter("text", text + "%");
var result = context.CreateQuery( "SELECT VALUE (c.Name) FROM Colors AS c WHERE c.Name LIKE @text", parameter);

C. var parameter = new ObjectParameter("text", text + "%");
var result = context.CreateQuery( "SELECT (c.Name) FROM Colors AS c WHERE c.Name LIKE @text", parameter);
D. var parameter =new ObjectParameter("text", HttpUtility.HtmlEncode(text)
+ "%");
var result = context.CreateQuery( "SELECT (c.Name) FROM Colors AS cWHERE c.Name LIKE '@text'@, parameter);

Answer: B
Question 138
The database contains orphaned Color records that are no longer connected to Part records. You need to clean up the orphaned records. You have an existing ContosoEntities context object named context. Which code segment should you use?
A. var unusedColors = context.Colors.Where(c => !c.Parts.Any()).ToList(); foreach (var unused in unusedColors){
context.DeleteObject(unused) } context.SaveChanges();
B. context.Colors.TakeWhile(c => !c.Parts.Any()); context.SaveChanges();
C. context.Colors.ToList().RemoveAll(c => !c.Parts.Any()); context.SaveChanges();
D. var unusedColors = context.Colors.Where(c => !c.Parts.Any()); context.DeleteObject(unusedColors); context.SaveChanges();

Answer: A
Question 139
You need to write a LINQ query that can be used against a ContosoEntities context object named context to find all parts that have a duplicate name. Which of the following queries should you use?

(Each correct answer presents a complete solution. Choose two).
A. context.Parts.Any(p => context.Parts.Any(q => p.Name == q.Name));
B. context.Parts.GroupBy(p => p.Name).Where(g => g.Count() > 1).SelectMany(x => x);
C. context.Parts.SelectMany(p => context.Parts.Select(q => p.Name == q.Name && p.Id != q.Id));
D. context.Parts.Where(p => context.Parts.Any(q => q.Name == p.Name && p.Id != q.Id);

Answer: BD
Question 140
You add a table to the database to track changes to part names. The table stores the following row values: the username of the user who made the change a part ID the new part name a DateTime value

You need to ensure detection of unauthorized changes to the row values. You also need to ensure that database users can view the original row values.
A. Add a column named signature. Use System.Security.Cryptography.RSA to create a signature for all of the row values. Store the signature in the signature column. Publish only the public key internally.
B. Add a column named hash. Use System.Security.Cryptography.MD5 to create an MD5 hash of the row values, and store in the hash column.
C. Use System.Security.Cryptography.RSA to encrypt all the row values. Publish only the key internally.
D. Use System.Security.Cryptography.DES to encrypt all the row values using an encryption key held by the application.
Answer: A
Question 141
The user interface requires that a paged view be displayed of all the products sorted in alphabetical order.

The user interface supplies a current starting index and a page size in variables named startIndex and pageSize of type int. You need to construct a LINQ expression that will return the appropriate Parts from the database from an existing ContosoEntities context object named context. You begin by writing the following expression:
context.Parts
Which query parts should you use in sequence to complete the expression? (To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.)
A. .OrderBy(x => x.Name)
B. .Skip(pageSize)
C. .Skip(startIndex)
D. .Take(pageSize);
E. .Take(startIndex)

Answer: ACD
Question 142
You are developing a new feature in the application to display a list of all bundled products. You need to write a LINQ query that will return a list of all bundled products. Which query expression should you use?
A. context.Parts.Cast() .Where(p => p.Descendants.Any(d => d is Product))
B. context.Parts.OfType() .Where(p => p.Descendants.Any(d => d is Product))
C. context.Parts.Cast() .ToList() .Where(p => p.Descendants.Any(d => d is Product))
D. context.Parts.OfType() .ToList() .Where(p => p.Descendants.Any(d => d is Product))

Answer: D
Question 143
You use Microsoft .NET Framework 4.0 to develop an application that uses LINQ to SQL. The Product entity in the LINQ to SQL model contains a field named Productlmage. The Productlmage field holds a large amount of binary data.

You need to ensure that the Productlmage field is retrieved from the database only when it is needed by the application. What should you do?
A. Set the Update Check property on the Productlmage property of the Product entity to Never.
B. Set the Auto-Sync property on the Productlmage property of the Product entity to Never.
C. Set the Delay Loaded property on the Productlmage property of the Product entity to True.
D. When the context is initialized, specify that the Productlmage property should not be retrieved by using DataLoadOptions

Answer: C
Question 144
You use Microsoft .NET Framework 4.0 to develop an application that uses Entity Framework. The application includes the following Entity SQL (ESQL) query.
SELECT VALUE product FROM AdventureWorksEntities.Products AS product ORDER BY product.ListPrice
You need to modify the query to support paging of the query results. Which query should you use?
A. SELECT TOP Stop VALUE product FROM AdventureWorksEntities.Products AS product ORDER BY product.ListPrice SKIP @skip
B. SELECT VALUE product FROM AdventureWorksEntities.Products AS product ORDER BY product.ListPrice SKIP @skip LIMIT @limit
C. SELECT SKIP @skip VALUE product FROM AdventureWorksEntities.Products AS product ORDER BY product.ListPrice LIMIT @limit
D. SELECT SKIP @skip TOP Stop VALUE product FROM AdventureWorksEntities.Products AS product ORDER BY product.ListPrice
Answer: B Question 145

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the Entity Framework Designer to create the following Entity Data Model.

The application contains a class as shown in the following code segment. (Line numbers are included for reference only.)
01 public class MyBaseClass : EntityObject 02 { 03 ��. 04 }
You need to ensure that all generated entities inherit from MyBaseClass. What should you do?
A. Change MyBaseClass to inherit from ObjectContext.
B. Create a new ObjectQuery that uses MyBaseClass as the type parameter.
C. Modify the generated code file so that all entities inherit from MyBaseClass.
D. Use the ADO.NET EntityObject Generator template to configure all entities to inherit from MyBaseClass.

Answer: D
Question 146
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses the Entity Framework. The application defines the following Entity Data Model.


Within the .edmx file, the following function is defined:

CAST(val as Edm.Int32)

The application includes the following LINQ query.
var query = from detail in context.SalesOrderDetails select detail.LineTotal.Round();
You need to ensure that the Round function executes on the database server when the query is executed. Which code segment should you use?
A. public static class DecimalHelper
{ [EdmFunction("SqlServer", "Round")] public static Decimal Round(this Decimal Amt) {
throw new NotSupportedException(); } }
B. public static class DecimalHelper
{ [EdmFunction("Edm", "Round")] public static Decimal Round(this Decimal Amt) {
throw new NotSupportedException();

} }
C. public static class DecimalHelper
{ public static SqlDecimal Round(this Decimal input) {
return SqlDecimal.Round(input, 0); } }
D. public static class DecimalHelper
{ public static Decimal Round(this Decimal input) {
return (Decimal)(Int32)input; } }

Answer: B
Question 147
You use Microsoft .NET Framework 4.0 to develop an application. You write the following code to update data in a Microsoft SQL Server 2008 database. (Line numbers are included for reference only.)
01 private void ExecuteUpdate(SqlCommand cmd, string connString, string updateStmt) 02 { 03 ... 04 }
You need to ensure that the update statement executes and that the application avoids connection leaks. Which code segment should you insert at line 03?
A. SqlConnection conn = new SqlConnection(connString); conn.Open(); cmd.Connection = conn; cmd.CommandText = updateStmt; cmd.ExecuteNonQuery(); cmd.Connection.Close() ;

B. using (SqlConnection conn = new SqlConnection(connString))
{ cmd.Connection = conn; cmd.CommandText = updateStmt; cmd.ExecuteNonQuery(); cmd.Connection.Close();
}
C. using (SqlConnection conn = new SqlConnection(connString))
{ conn.Open() ; cmd.Connection = conn; cmd.CommandText = updateStmt; cmd.ExecuteNonQuery() ;
}
D. SqlConnection conn = new SqlConnection(connString); conn.Open(); cmd.Connection = conn; cmd.CommandText = updateStmt; cmd.ExecuteNonQuery();

Answer: C
Question 148
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the Entity Framework Designer to create an Entity Data Model (EDM). You need to create a database creation script for the EDM. What should you do?
A. Use a new Self-Tracking Entities template.
B. Drag entities to Server Explorer.
C. Run the Generate Database command.
D. Select Run Custom Tool from the solution menu.

Answer: C
Question 149
You use Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You need to ensure that the application connects to the database server by using SQL Server authentication.

Which connection string should you use?
A. SERVER=MyServer; DATABASE=AdventureWorks; Integrated Security=SSPI; UID=sa; PWD=secret;
B. SERVER=MyServer; DATABASE=AdventureWorks; UID=sa; PWD=secret;
C. SERVER=MyServer; DATABASE=AdventureWorks; Integrated Security=false;
D. SERVER=MyServer; DATABASE=AdventureWorks; Trusted Connection=true;

Answer: B
Question 150
You use Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You add the following stored procedure to the database.
CREATE PROCEDURE dbo.GetClassAndStudents AS BEGIN
SELECT * FROM dbo.Class SELECT * FROM dbo.Student END
You create a SqIConnection named conn that connects to the database. You need to fill a DataSet from the result that is returned by the stored procedure. The first result set must be added to a DataTable named Class, and the second result set must be added to a DataTable named Student. Which code segment should you use?
A. DataSet ds = new DataSet(); SqlDataAdapter ad = new SqlDataAdapter(��GetClassAndStudents��, conn); ds.Tables.Add(��Class��); ds.Tables.Add(��Student��); ad.Fill(ds);
B. DataSet ds = new DataSet(); SqlDataAdapter ad = new SqlDataAdapter(��GetClassAndStudents��, conn); ad.TableMappings.Add("Table��, ��Class��); ad.TableMappings.Add(��Table1��, ��Student��) ; ad.Fill(ds) ;
C. DataSet ds = new DataSet(); SqlDataAdapter ad = new SqlDataAdapter(��GetClassAndStudents��, conn);

ad.MissingMappingAction = MissingMappingAction.Ignore; ad.Fill(ds, ��Class��); ad.Fill(ds, ��Student��);
D. DataSet ds = new DataSet(); SqlDataAdapter ad = new SqlDataAdapter(��GetClassAndStudents��, conn); ad.Fill(ds);

Answer: B
Question 151
You use Microsoft .NET Framework 4.0 to develop an application that uses the Entity Framework. The application defines the following Entity SQL (ESQL) query, which must be executed against the mode.
string prodQuery = ��select value p from Products as p where p.ProductCategory.Name = @p0��;
You need to execute the query. Which code segment should you use?
A. var prods = ctx.CreateQuery(prodQuery, new ObjectParameter("p0��, "Road Bikes")).ToList();
B. var prods = ctx.ExecuteStoreCommand(prodQuery, new ObjectParameter("p0��, "Road Bikes")).ToList();
C. var prods = ctx.ExecuteFunction(prodQuery, new ObjectParameter("p0��, "Road Bikes")).ToList();
D. var prods = ctx.ExecuteStoreQuery(prodQuery, new ObjectParameter("p0��, "Road Bikes")).ToList();

Answer: A
Question 152
You use Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. The application uses nested transaction scopes. An inner transaction scope contains code that inserts records into the database. You need to ensure that the inner transaction can successfully commit even if the outer transaction rolls back.
What are two possible TransactionScope constructors that you can use for the inner transaction to achieve this goal? (Each correct answer presents a complete solution. Choose two.)

A. TransactionScope(TransactionScopeOption.Required)
B. TransactionScope()
C. TransactionScope(TransactionScopeOption.RequiresNew)
D. TransactionScope(TransactionScopeOption.Suppress)

Answer: CD
Question 153
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses the Entity Framework. Entity types in the model are generated by the Entity Data Model generator tool (EdmGen.exe). You write the following code. (Line numbers are included for reference only.)
01 MemoryStream stream = new MemoryStream(); 02 var query = context.Contacts.Include(��SalesOrderHeaders.SalesOrderDetails��); 03 var contact = query.Where(��it.LastName = @lastname��, new ObjectParameter(��lastname��, lastName)).First(); 04 ....
You need to serialize the contact and all of its related objects to the MemoryStream so that the contact can be deserialized back into the model. Which code segment should you insert at line 04?
A. var formatter = new XmlSerializer(typeof(Contact), new Type[] {
typeof(SalesOrderHeader),
typeof(SalesOrderDetail)
}); formatter.Serialize(stream, contact);
B. var formatter = new XmlSerializer(typeof(Contact)); formatter.Serialize(stream, contact);
C. var formatter = new BinaryFormatter(); formatter.Serialize(stream, contact);
D. var formatter = new SoapFormatter(); formatter.Serialize(stream, contact);


Answer: A
Question 154
You use Microsoft Visual Studio 2010 to create a Microsoft .NET Framework 4.0 application. You create an Entity Data Model for the database tables shown in the following diagram.

You need to modify the .edmx file so that a many-to-many association can exist between the Address and Customer entities. Which storage Model section of the .edmx file should you include?
A.





StoreGeneratedPattern=��Identity�� />




B.






DefaultValue=��Home�� />


C.


StoreGeneratedPattern=��Identity�� />




D.









Answer: D
Question 155
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. You need to ensure that the entities are self-tracking. What should you do in the ADO.NET Entity Framework Designer?
A. Change the Code Generation Strategy option from Default to None.
B. Change the Transform Related Text Templates On Save option to False.
C. Add an ADO.NET Self-Tracking Entity Generator to the model.
D. Add an ADO.NET EntityObject Generator to the model.
Answer: C
Question 156
You are developing an ADO.NET 4.0 application that interacts with a Microsoft SQL Server 2008 server

through the SQL Server Native Client. You create a trace DLL registry entry and you register all of the trace schemas. You need to trace the application data access layer. Which control GUID file should you use?
A. ctrl.guid.snac10
B. ctrl.guid.mdac
C. ctrl.guid.adonet
D. ctrl.guid.msdadiag

Answer: A
Question 157
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to several SQL Server databases. You create a function that modifies customer records that are stored in multiple databases. All updates for a given record are performed in a single transaction. You need to ensure that all transactions can be recovered. What should you do?
A. Call the RecoveryComplete method of the TransactionManager class.
B. Call the EnlistDurable method of the Transaction class.
C. Call the Reenlist method of the TransactionManager class.
D. Call the EnlistVolatile method of the Transaction class.

Answer: B
Question 158
You are developing a WCF data service that will expose an existing Entity Data Model (EDM).
You have the following requirements: Users must be able to read all entities that are exposed in the EDM. Users must be able to update or replace the SalesOrderHeader entities. Users must be prevented from inserting or deleting the SalesOrderHeader entities You need to ensure that the data service meets the requirements. Which code segment should you use in the Initialize method?

A. config.SetEntitySetAccessRule(��*��, EntitySetRights.AllRead); config.SetEntitySetAccessRule(��SalesOrderHeader��, EntitySetRights.AllWrite);
B. config.SetEntitySetAccessRule(��*��, EntitySetRights.AllRead); config.SetEntitySetAccessRule(��SalesOrderHeader��, EntitySetRights.WriteMerge | EntitySetRights.WriteReplace);

C. config.SetEntitySetAccessRule(��*��, EntitySetRights.AllRead); config.SetEntitySetAccessRule(��SalesOrderHeader��, EntitySetRights.WriteAppend | EntitySetRights.WriteDelete);
D. config.SetEntitySetAccessRule(��*��, EntitySetRights.AllRead); config.SetEntitySetAccessRule(��SalesOrderHeader��, EntitySetRights.All);

Answer: B
Question 159
You use Microsoft .NET Framework 4.0 to develop an application that uses LINQ to SQL. The LINQ to SQL model contains the Product entity. A stored procedure named GetActiveProducts performs a query that returns the set of active products from the database. You need to invoke the stored procedure to return the active products, and you must ensure that the LINQ to SQL context can track changes to these entities. What should you do?
A. Select the Product entity, view the entity��s property window, and change the Name for the entity to GetActiveProducts.
B. Add a property named GetActiveProducts to the Product entity.
C. Navigate to the GetActiveProducts stored procedure in Server Explorer, and drag the procedure onto the Product entity in the LINQ to SQL model designer surface.
D. Select the Product entity, view the entity��s property window, and change the Source for the entity to GetActiveProducts.

Answer: C
Question 160
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. You retrieve an entity from an object context. A different application updates the database. You need to update the entity instance to reflect updated values in the database. Which line of code should you use?
A. context.Refresh(RefreshMode.StoreWins, entity);
B. context.LoadProperty(entity, ��Client��, MergeOption.OverwriteChanges);
C. context.AcceptAllChanges() ;
D. context.LoadProperty(entity, "Server", MergeOption.OverwriteChanges);


Answer: A
Question 161
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses LINQ to SQL. The application contains the following model.

Each region contains a single vendor. Customers order parts from the vendor that is located in their region. You need to ensure that each row in the Customer table references the appropriate row from the Vendor table. Which code segment should you use?
A. SalesDataContext dc = new SalesDataContext("...");
var query = from v in dc.Vendors join c in dc.Customers on v.VendorlD equals c.VendorID select new { Vendor = v, Customer = c };
foreach (var u in query){
u.Customer.Region = u.Vendor.Region; } dc.SubmitChanges();
B. SalesDataContext dc = new SalesDataContext("...");
var query = from c in dc.Customers join v in dc.Vendors on c.VendorlD equals v.VendorID select new { Customer = c, Vendor = v };
foreach (var u in query){
u.Vendor.Region = u.Customer.Region; } dc.SubmitChanges();

C. SalesDataContext dc = new SalesDataContext("...");
var query = from v in dc.Vendors join c in dc.Customers on v.Region equals c.Region select new { Vendor = v, Customer = c };
foreach (var u in query){
u.Customer.VendorlD = u.Vendor.VendorlD; } dc.SubmitChanges();
D. SalesDataContext dc = new SalesDataContext("...");
var query = from c in dc.Customers join v in dc.Vendors on c.Region equals v.Region select new { Customer = c. Vendor = v };
foreach (var u in query){
u.Vendor.VendorlD = u.Customer.VendorID; } dc.SubmitChanges();

Answer: C
Question 162
You use Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 200B database. You populate a SqlDataAdapter by using the following code. (Line numbers are included for reference only.)
01 SqlDataAdapter dataAdapter1 =newSqlDataAdapter("SELECT *FROM [BlogEntries]ORDER BY CreationDate��, connection); 02 cmdBuilder = new SqlCommandBuilder(dataAdapter1); 03 dataAdapter1.Fill(BlogEntryDataSet, ��BlogEntries��); 04 .... 05 connection.Close();
You need to update the blog owner for all BlogEntry records. Which code segment should you insert at line 04?
A. foreach(DataRow row in BlogEntryDataSet.Tables["BlogEntries"].Rows) {
row.Item["BlogOwner""] = ��New Owner��; } dataAdapter1.Update(BlogEntryDataSet, ��BlogEntries��);

B. foreach(DataRow row in BlogEntryDataSet.Tables["BlogEntries"].Rows) {
row.Item["BlogOwner""] = ��New Owner��; } dataAdapter1.Fill(BlogEntryDataSet, ��BlogEntries��);
C. SqlDataAdapter dataAdapter2 = new SqlDataAdapter(��UPDATE [BlogEntries] SET [BlogOwner] = "New 'Owner' 3��, connection); dataAdapter2.Update(BlogEntryDataSet, ��BlogEntries��);
D. SqlDataAdapter dataAdapter2 = new SqlDataAdapter(dataAdapterl.UpdateCommand); dataAdapter2.Fill(BlogEntryDataSet, ��BlogEntries��);

Answer: A
Question 163
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses LINQ to SQL. The application contains the following model. You write the following code. (Line numbers are included for reference only.)
01 static void Insert() 02 { 03 NorthwindDataContext dc = new NorthwindDataContext(); 04 Customer newCustomer = new Customer(); 05 newCustomer.Firstname = ��Todd��; 06 newCustomer.Lastname = ��Meadows��; 07 newCustomer.Email = ��[email protected]��; 08 ..... 09 dc.SubmitChanges(); 10 }


A product named Bike Tire exists in the Products table. The new customer orders the Bike Tire product.
You need to ensure that the correct product is added to the order and that the order is associated with the new customer. Which code segment should you insert at line 08?
A. Order newOrder = new Order();
newOrder.Product = (from p in dc.Products where p.ProductName == ��Bike Tire�� select p) .First();
B. Product newProduct = new Product(); newProduct.ProductName = ��Bike Tire��; Order newOrder = new Order(); newOrder.Product = newProduct;
C. Product newProduct = new Product(); newProduct.ProductName = ��Bike Tire��; Order newOrder = new Order (); newOrder.Product = newProduct; newCustomer.Orders.Add(newOrder) ;
D. Order newOrder = new Order();
newOrder.Product = (from p in dc.Products where p.ProductName == ��Bike Tire�� select p).First();
newCustomer.Orders.Add(newOrder) ;

Answer: D
Question 164
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application that connects to a database by using the Entity Framework. You create an Entity Data Model (EDM) by using the Generate from database wizard for the following tables.

You need to ensure that the EDM contains an entity type named Employee that contains all of the data from

both tables.
What should you do?
A. Delete the EmployeeAccess entity, create a new property named CanAccessBuildings on the Employee entity, and add a mapping for the new property.
B. Create an inheritance relationship between the Employee and EmployeeAccess entities, and use CanAccessBuildings as an inheritance condition.
C. Modify the .edmx file to include the following line of code.
D. Create a one-to-one association named CanAccessBuildingsAssociation between the EmployeeAccess entity and the Employee entity.

Answer: A
Question 165
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses the Entity Framework. The application has an entity model that contains a SalesOrderHeader entity. The entity includes an OrderDate property of type DateTime. You need to retrieve the 10 oldest SalesOrderHeaders according to the OrderDate property. Which code segment should you use?
A. var model = new AdventureWorksEntities(); var sales = model.SalesOrderHeaders.Take(10).OrderByDescending(soh => soh.OrderDate);
B. var model = new AdventureWorksEntities(); var sales = model.SalesOrderHeaders.OrderByDescending(soh => soh.OrderDate).Take(10);
C. var model = new AdventureWorksEntities(); var sales = model.SalesOrderHeaders.OrderBy(soh => soh.OrderDate).Take(10);
D. var model = new AdventureWorksEntities(); var sales = model.SalesOrderHeaders.Take(10).OrderBy(soh => soh.OrderDate);
Answer: C Question 166

You use Microsoft .NET Framework 4.0 to develop an application that connects to two separate Microsoft SQL Server 2008 databases. The Customers database stores all the customer information, and the Orders database stores all the order information. The application includes the following code. (Line numbers are included for reference only.)
01 try 02 { 03 conn.Open(); 04 tran = conn.BeginTransaction("Order"); 05 SqlCommand cmd = new SqlCommand(); 06 cmd.Connection = conn; 07 cmd.Transaction = tran; 08 tran.Save("save1"); 09 cmd.CommandText = "INSERT INTO [Cust].dbo.Customer " + "(Name, PhoneNumber) VALUES ('Paul Jones', " + "'404-555-1212')"; 10 cmd.ExecuteNonQuery(); 11 tran.Save("save2"); 12 cmd.CommandText = "INSERT INTO [Orders].dbo.Order " + "(CustomerID) VALUES (1234)"; 13 cmd.ExecuteNonQuery(); 14 tran.Save("save3"); 15 cmd.CommandText = "INSERT INTO [Orders].dbo." + "OrderDetail (OrderlD, ProductNumber) VALUES" + "(5678, 'DC-6721')"; 16 cmd.ExecuteNonQuery(); 17 tran.Commit(); 18 } 19 catch (Exception ex) 20 { 21 ... 22 }
You run the program, and a timeout expired error occurs at line 16. You need to ensure that the customer information is saved in the database. If an error occurs while the order is being saved, you must roll back all of the order information and save the customer information. Which line of code should you insert at line 21?
A. tran.Rollback();
B. tran.Rollback("save2"); tran.Commit();

C. tran.Rollback(); tran.Commit();
D. tran.Rollback("save2");

Answer: B
Question 167
You use Microsoft .NET Framework 4.0 to develop an application. You use the XmlReader class to load XML from a location that you do not control. You need to ensure that loading the XML will not load external resources that are referenced in the XML. Which code segment should you use?
A. XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.None; XmlReader reader = XmlReader.Create("data.xml", settings);
B. XmlReaderSettings settings = new XmlReaderSettings(); settings.CheckCharacters = true; XmlReader reader = XmlReader.Create("data.xml", settings);
C. XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = null; XmlReader reader = XmlReader.Create("data.xml", settings);
D. XmlReaderSettings settings = new XmlReaderSettings(); settings.ConformanceLevel = ConformanceLevel.Auto; XmlReader reader = XmlReader.Create("data.xml", settings);

Answer: C
Question 168
You use Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You add the following table to the database.
CREATE TABLE Orders( ID numeric(18, 0) NOT NULL, OrderName varchar(50) NULL, OrderTime time(7) NULL, OrderDate date NULL)

You write the following code to retrieve data from the OrderTime column. (Line numbers are included for reference only.)
01 SqlConnection conn = new SqlConnection("��"); 02 conn.Open(); 03 SqlCommand cmd = new SqlCommand("SELECT ID, OrderTime FROM Orders", conn); 04 SqlDataReader rdr = cmd.ExecuteReader(); 05 .... 06 while(rdr.Read()) 07 { 08 .... 09 }
You need to retrieve the OrderTime data from the database. Which code segment should you insert at line 08?
A. TimeSpan time = (TimeSpan)rdr[1];
B. Timer time = (Timer)rdr[1];
C. string time = (string)rdr[1];
D. DateTime time = (DateTime)rdr[1];

Answer: A
Question 169
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. The model contains an entity type named Product.
You need to ensure that a stored procedure will be invoked when the ObjectContext.SaveChanges method is executed after an attached Product has changed. What should you do in the ADO.NET Entity Framework Designer?
A. Add a new entity that has a base class of Product that is mapped to the stored procedure.
B. Add a stored procedure mapping for the Product entity type.
C. Add a complex type named Product that is mapped to the stored procedure.
D. Add a function import for the Product entity type.
Answer: B
Question 170
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application.

You use the Entity Framework Designer to create the following Entity Data Model.

You write a method named ValidatePostalCode to validate the postal code for the application. You need to ensure that the ValidatePostalCode method is called before the PostalCode property set method is completed and before the underlying value has changed. Which code segment should you place in the entity��s partial class?
A. partial void OnPostalCodeChanged(string value) {
PostalCode = GetValidValue(value, "ValidatePostalCode", false, true) ; }
B. public string ValidatedPostalCode
{ set {
ValidatePostalCode(value);
_PostalCode = value; } get {
return _PostalCode; } }
C. partial void OnPostalCodeChanging(string value)
{ ValidatePostalCode(value);

}
D. public string ValidatedPostalCode
{ set {
_PostalCode = StructuralObject.SetValidValue("ValidatePostalCode", false); } get {
return _PostalCode; } }

Answer: C
Question 171
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that uses the ADO.NET Entity Framework to model entities. You create an entity model as shown in the following diagram.

You need to ensure that all Person entities and their associated EmailAddresses are loaded. Which code segment should you use?

A. var people = context.People.Include("EmailAddresses").ToList();
B. var people = context.People.Except(new ObjectQuery("Person.EmailAddresses", context)).ToList();
C. var people = context.People.Except(new ObjectQuery("EmailAddresses", context)).ToList();
D. var people = context.People.Include("Person.EmailAddresses").ToList();

Answer: A
Question 172
You use Microsoft .NET Framework 4.0 to develop an application that connects to a local Microsoft SQL Server 2008 database. The application can access a high-resolution timer. You need to display the elapsed time, in sub-milliseconds (<1 millisecond), that a database query takes to execute. Which code segment should you use?
A. int Start = Environment.TickCount; command.ExecuteNonQuery(); int Elapsed = (Environment.TickCount) -Start; Console.WriteLine("Time Elapsed: {0:N} ms", Elapsed);
B. Stopwatch sw = Stopwatch.StartNew(); command.ExecuteNonQuery() ; sw.Stop() ; Console.WriteLine("Time Elapsed: {0:N} ms", sw.Elapsed.TotalMilliseconds);
C. DateTime Start = DateTime.UtcNow; command.ExecuteNonQuery(); TimeSpan Elapsed = DateTime.UtcNow -Start; Console.WriteLine("Time Elapsed: {0:N} ms", Elapsed.Milliseconds);
D. Stopwatch sw = new Stopwatch(); sw.Start() ; command.ExecuteNonQuery(); sw.Stop(); Console.WriteLine("Time Elapsed: {0:N} ms", sw.Elapsed.Milliseconds);
Answer: D
Question 173

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. You need to associate a previously deserialized entity named person1 to an object context named model and persist changes to the database. Which code segment should you use?
A. person1.AcceptChanges(); model.SaveChanges();
B. model.People.ApplyChanges(person1) ; model.SaveChanges();
C. model.AttachTo("People", person1); model.SaveChanges();
D. model.People.Attach(person1); model.SaveChanges();

Answer: C
Question 174
You use Microsoft .NET Framework 4.0 to develop an application that uses WCF Data Services to persist entities from the following Entity Data Model.

You create a new Blog instance named newBlog and a new Post instance named newPost as shown in the following code segment. (Line numbers are included for reference only.)
01 Blog newBlog = new Blog(); 02 Post newPost = new Post(); 03 .... 04 Uri serviceUri = new Uri("��"); 05 BlogsEntities context = new BlogsEntities(serviceUri);

06 ....
You need to ensure that newPost is related to newBlog through the Posts collection property and that newPost and newBlog are sent to the service. Which code segment should you insert at line 06?
A. context.AttachLink(newBlog, "Posts", newPost); context.SaveChanges(SaveChangesOptions.Batch) ;
B. newBlog.Posts.Add(newPost); context.AddToBlogs(newBlog); context.AddToPosts(newPost); context.SaveChanges(SaveChangesOptions.Batch);
C. newBlog.Posts.Add(newPost); context.AttachTo("Blogs", newBlog); context.AttachTo("Posts", newPost); context.SaveChanges(SaveChangesOptions.Batch);
D. newBlog.Posts.Add(newPost); context.UpdateObject(newBlog); context.UpdateObject(newPost); context.SaveChanges(SaveChangesOptions.Batch);

Answer: C
Question 175
You use Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. The application includes a table adapter named taStore, which has the following DataTable.

There is a row in the database that has a ProductID of 680. You need to change the Name column in the row to

"New Product Name". Which code segment should you use?
A. var dt = new taStore.ProductDataTable(); var ta = new taStoreTableAdapters.ProductTableAdapter(); ta.Fill(dt); taStore.ProductRow row = (taStore.ProductRow)dt.Rows.Find(680) ; row.Name = "New Product Name"; ta.Update(row);
B. var ta = new taStoreTableAdapters.ProductTableAdapter(); var dt = ta.GetData(); var row = dt.Select("680") ; row[0]["Name"] = "New Product Name"; ta.Update(row);
C. var dt = new taStore.ProductDataTable(); var ta = new taStoreTableAdapters.ProductTableAdapter(); ta.Fill(dt); var dv = new DataView(); dv.RowFilter = "680"; dv[0]["Name"] = "New Product Name"; ta.Update(dt);
D. var dt = new taStore.ProductDataTable(); var row = dt.NewProductRow(); row.ProductID = 680; row.Name = "New Product Name"; dt.Rows.Add(row) ;

Answer: A
Question 176
You use Microsoft .NET Framework 4.0 to develop an application that exposes a WCF Data Services endpoint. The endpoint uses an authentication scheme that requires an HTTP request that has the following header format.
GET /OData.svc/Products(1) Authorization: WRAP access_token "123456789"
You add the following method to your DataService implementation.

01 protected override void OnStartProcessingRequest(ProcessRequestArgs args) 02 { 03 .... 04 }
You need to ensure that the method retrieves the authentication token. Which line of code should you use?
A. string token = args.OperationContext.RequestHeaders["Authorization"];
B. string token = args.OperationContext.RequestHeaders["WRAP access_token"];
C. string token = args.OperationContext.ResponseHeaders["Authorization"];
D. string token = args.OperationContext.ResponseHeaders["WRAP access_token"];

Answer: A
Question 177
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You use the ADO.NET Entity Framework Designer to model entities. You add the following stored procedure to the database, and you add a function import to the model.
CREATE PROCEDURE [dbo].[InsertDepartment] @Name nvarchar(50), @ID int NULL OUTPUT
AS INSERT INTO Department (Name) VALUES (@Name) SELECT @ID = SCOPE_IDENTITY()
You need to insert a new department and display the generated ID. Which code segment should you use?
A. using (SchoolEntities context = new SchoolEntities())
{ var id = new ObjectParameter("ID", typeof(int)); context.InsertDepartment("Department 1", id); Console.WriteLine(id.Value);
}
B. using (SchoolEntities context = new SchoolEntities())
{ var id = context.InsertDepartment("Department 1", null); Console.WriteLine(id);
}

C. using (SchoolEntities context = new SchoolEntities())
{ ObjectParameter id = null; context.InsertDepartment("Department 1", id); Console.WriteLine(id.Value);
}
D. using (SchoolEntities context = new SchoolEntities())
{ var id = new ObjectParameter("ID", null)); context.InsertDepartment("Department 1", id); Console.WriteLine(id.Value);
}

Answer: A
Question 178
You use Microsoft .NET Framework 4.0 to develop an ASP.NET Web application that connects to a Microsoft SQL Server 2008 database. The application uses Integrated Windows authentication in Internet Information Services (IIS) to authenticate users. A connection string named connString defines a connection to the database by using integrated security.
You need to ensure that a SqlCommand executes under the application pool's identity on the database server. Which code segment should you use?
A. using (var conn = new SqlConnection())
{ conn.ConnectionString = connString; SqlCommand cmd = null; using (HostingEnvironment.Impersonate()) {
cmd = new SqlCommand("SELECT * FROM BLOG", conn); } conn.Open(); var result = cmd.ExecuteScalar();
}
B. using (var conn = new SqlConnection(connString)) {

var cmd = new SqlCommand ("SELECT * FROM BLOG, conn); conn.Open(); using(HostingEnvironment.Impersonate()) {
var result = cmd.ExecuteScalar(); } }
C. using (var conn = new SqlConneccion())
{ using (HostingEnvironroent.Impersonate()) {
conn.ConnectionString = connString; } var cmd = new SqlCommand("SELECT * FROM BLOG, conn); conn.Open() ; var result = cmd.ExecuteScalar();
}
D. using (var conn = new SqlConnection())
{ conn.ConnectionString = connString; var cmd = new SqlCommand("SELECT * FROM BLOG", conn); using (HostingEnvironment.Impersonate()) {
conn.Open(); } var result = cmd.ExecuteScalar();
}

Answer: D
Question 179
You use Microsoft .NET Framework 4.0 to develop an ASP.NET 4 Web application. You need to encrypt the connection string information that is stored in the web.config file. The application is deployed to multiple servers. The encryption keys that are used to encrypt the connection string information must be exportable and importable on all the servers. You need to encrypt the connection string section of the web.config file so that the file can be used on all of the servers. Which code segment should you use?

A. Configuration config = WebConfigurationManager.OpenWebConfiguration("~��) ; ConnectionStringsSection section = (ConnectionStringsSection)config.GetSection("connectionStrings"); section.Sectionlnformation.ProtectSection("RsaProtectedConfigurationProvider"); config.Save();
B. Configuration config = WebConfigurationManager.OpenMachineConfiguration("~"); ConnectionStringsSection section = (ConnectionStringsSection)config.GetSection("connectionStrings"); section.Sectionlnformation.ProtectSection("RsaProtectedConfigurationProvider'*); config.Save();
C. Configuration config = WebConfigurationHanager.OpenWebConfiguration ("~") ; ConnectionStringsSection section = (ConnectionStringsSection)config.GetSection("connectionStrings") ; section.Sectionlnformation.ProtectSection("DpapiProtectedConfigurationProvider"); config.Save ();
D. Configuration config = WebConfigurationManager.OpenMachineConfiguration ("~") ; ConnectionStringsSection section = (ConnectionStringsSection)config.GetSection("connectionStrings") ; section.Sectionlnformation.ProtectSection("DpapiProtectedConfigurationProvider"); config.Save () ;

Answer: A
Question 180
You use Microsoft .NET Framework 4.0 and the Entity Framework to develop an application. You create an Entity Data Model that has an entity named Customer. You set the optimistic concurrency option for Customer. You load and modify an instance of Customer named loadedCustomer, which is attached to an ObjectContext named context.
You need to ensure that if a concurrency conflict occurs during a save, the application will load up-to-date values from the database while preserving local changes. Which code segment should you use?
A. try {
context.SaveChanges(); }

catch(EntitySqlException ex) { context.Refresh(RefreshMode.StoreWins, loadedCustomer); }
B. try {
context.SaveChanges(); } catch(OptimisticConcurrencyException ex) {
context.Refresh(RefreshMode.ClientWins, loadedCustomer); }
C. try {
context.SaveChanges(); } catch(EntitySqlException ex) {
context.Refresh(RefreshMode.ClientWins, loadedCustomer); }
D. try {
context.SaveChanges(); } catch(OptimisticConcurrencyException ex) {
context.Refresh(RefreshMode.StoreWins, loadedCustomer); }

Answer: B
Question 181
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. You need to create a Plain Old CLR Object (POCO) class that can be used with the ObjectContext.CreateObject method to create a proxy. What should you do?

A. Create a custom data class that has a Protected constructor that does not have parameters.
B. Create a custom data class in which all properties and methods are virtual.
C. Create a custom data class that is abstract.
D. Create a custom data class that is sealed.

Answer: A
Question 182
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an ASP.NET Web application that uses the Entity Framework.
The build configuration is set to Release. The application must be published by using Microsoft Visual Studio
2010, with the following requirements:

The database schema must be created on the destination database server.
The Entity Framework connection string must be updated so that it refers to the destination database server.
You need to configure the application to meet the requirements. Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)
A. Generate the DDL from the Entity Framework Designer and include it in the project. Set the action for the DDL to ApplicationDefinition.
B. Set Items to deploy in the Package/Publish Web tab to All files in this Project Folder for the release configuration.
C. Use the web.config transform file to modify the connection string for the release configuration.
D. Include the source database entry in the Package/Publish SQL tab and update the connection string for the destination database.

Answer: CD
Question 183
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. You need to retrieve an entity, and you must ensure that the entity is loaded in a detached state. Which MergeOption enumeration value should you use to retrieve the entity?
A. PreserveChanges
B. OverwriteChanges
C. AppendOnly
D. NoTracking
Answer: D Question 184

How do you define a WCF Data Service query to grab the first 10 records. Options are something like:
A. DataServiceQuery selectedOrders = context.Orders.AddQueryOption("$top", "10");
B. DataServiceQuery selectedOrders = context.Orders.AddQueryOption("$filter", "10");
C. DataServiceQuery selectedOrders = context.Orders.AddQueryOption("$select", "10");
D. DataServiceQuery selectedOrders = context.Orders.AddQueryOption("$expand", "10");

Answer: A
Question 185
There are Entities -States Class, Cities class. Deleting of state id raises exception. Which of the following?
A. EntityException
B. ConstraintException
C. UpdateException
D. EntityUpdateException

Answer: B
Question 186
Class Workflow -Has Workstepflow inside. Get workflow data as well as related workstepflow.
A.
B.
C.
D.

Answer:
Question 187
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4 to develop an application. A file named books.xml contains the following XML.

Author1 Author2

Author 3

The application must generate an XML result that contains an XML element named BookTitle for each book. The text content of the element must contain the title of the book. You need to create a query that generates the new XML result. What should you do?
A. XDocument document = XDocument.Load("books.xml");
var query = from node in document.Descendants() where node.Name.LocalName == "book" select new XElement("BookTitle", node.FirstAttribute.Value);
B. XDocument document = XDocument.Load("books.xml");
var query = from node in document.DescendantNodes() where node.ToString() == "book" select new XText("BookTitle" + node.ToString());
C. XDocument document = XDocument.Load("books.xml");
var query = from node in document.Descendants() where node.Name.LocalName == "book" select new XElement("BookTitle").Value = node.FirstAttribute.Value;
D. XDocument document = XDocument.Load("books.xml");
var query = from node in document.DescendantNodes() where node.ToString() == "book" select new XElement("BookTitle", node.ToString());

Answer: A
Question 188
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4 to develop an application that uses the Entity Framework. The application has the entity model shown in the following diagram.


The application must create a projection of the unique set of names and year-to-date sales for territories where at least one sales person had sales last year of more than $100,000. The projection must consist of properties named Sales and Name. You need to write a query that will generate the required projection. Which code segment should you use?
A. (from person in model.SalesPersons where (person.SalesLastYear > 100000) select new {
Name = person.SalesTerritory.Name, Sales = person.SalesTerritory.SalesYTD } ).Distinct();
B. (from person in model.SalesPersons where (person.SalesLastYear > 100000) select new {
Name = person.SalesTerritory.Name, Sales = person.SalesTerritory.SalesYTD }
);
C. model.SalesTerritories.Where( t => t.SalesPersons.Any( p => p.SalesLastYear > 100000)) .Select( t=> new { t.Name, t.SalesYTD}) .Distinct();
D. model.SalesTerritories.Where( t=> t.SalesPersons.Any( p => p.SalesLastYear > 100000)) .Select( t=> new { t.Name, Sales = t.SalesYTD});
Answer: A Question 189

You use Microsoft .NET Framework 4 to develop an application that connects to a Microsoft SQL Server 2008 database. You add the following stored procedure to the database.
CREATE PROCEDURE [dbo].[InsertTag] @Name nvarchar (15)
AS INSERT INTO [dbo].[Tags] (Name) VALUES(@Name) RETURN @@ROWCOUNT
You need to invoke the stored procedure by using an open SqlConnection named conn. Which code segment should you use?
A. SqlCommand cmd = new SqlCommand("EXEC InsertTag", conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Name", "New Tag 1"); cmd.ExecuteNonQuery();
B. SqlCommand cmd = new SqlCommand("EXEC InsertTag", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Name", "New Tag 1"); cmd.ExecuteNonQuery();
C. SqlCommand cmd = new SqlCommand("InsertTag", conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Name", "New Tag 1"); cmd.ExecuteNonQuery();
D. SqlCommand cmd = new SqlCommand("InsertTag", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Name", "New Tag 1"); cmd.ExecuteNonQuery();

Answer: D
Question 190
You use Microsoft .NET Framework 4 to develop an application that connects to a Microsoft SQL Server 2008 database. The database contains a ClassStudent table that contains the StudentID for students who are enrolled in the classes.
You add the following stored procedure to the database.

CREATE PROCEDURE [dbo].[GetNumEnrolled]
@ClassID INT, @NumEnrolled INT OUTPUT
AS BEGIN SET NOCOUNT ON SELECT @NumEnrolled = COUNT(StudentID)
FROM ClassStudent WHERE (ClassID = @ClassID) END
You write the following code. (Line numbers are included for reference only.)
01 private int GetNumberEnrolled(string classID) 02 { 03 using (SqlConnection conn = new SqlConnection(GetConnectionString()) 04 { 05 SqlCommand cmd = new SqlCommand("GetNumEnrolled", conn); 06 cmd.CommandType = CommandType.StoredProcedure; 07 SqlParameter parClass = cmd.Parameters.Add("@ClassID", SqlDbType.Int, 4, "classID"); 08 SqlParameter parNum = cmd.Parameters.Add("@NumEnrolled", SqlDbType.Int); 09 ... 10 conn.Open() 11 ... 12 } 13 }
You need to ensure that the GetNumberEnrolled method returns the number of students who are enrolled for a specific class. Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)
A. Insert the following code at line 09.
parNum.Direction = ParameterDirection.Input;
B. Insert the following code at line 09.
parNum.Direction = ParameterDirection.Output;
C. Insert the following code at line 11.
int numEnrolled = 0; SqlDataReader reader = cmd.ExecuteReader(); while(reader.Read()) {
numEnrolled = numEnrolled + (int)cmd.Parameters["@NumEnrolled"].Value; }

return numEnrolled;
D. Insert the following code at line 11.
cmd.ExecuteNonQuery(); return (int)parNum.Value;

Answer: BD
Question 191
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. The application has two DataTable objects that reference the Customers and Orders tables in the database. The application contains the following code segment. (Line numbers are included for reference only.)
01 DataSet customerOrders = new DataSet(); 02 customerOrders.EnforceConstraints = true; 03 ForeignKeyConstraint ordersFK = new ForeignKeyConstraint("ordersFK", 04 customerOrders.Tables["Customers"].Columns["CustomerID"], 05 customerOrders.Tables["Orders"].Columns["CustomerID"]); 06 ... 07 customerOrders.Tables["Orders"].Constraints.Add(ordersFK);
You need to ensure that an exception is thrown when you attempt to delete Customer records that have related Order records. Which code segment should you insert at line 06?
A. ordersFK.DeleteRule = Rule.SetDefault;
B. ordersFK.DeleteRule = Rule.None;
C. ordersFK.DeleteRule = Rule.SetNull;
D. ordersFK.DeleteRule = Rule.Cascade;

Answer: B
Question 192
The database contains a table named Categories. The Categories table has a primary key identity column named CategoryID. The application inserts new records by using the following stored procedure.
CREATE PROCEDURE dbo.InsertCategory @CategoryName nvarchar(15),

@Identity int OUT
AS INSERT INTO Categories (CategoryName) VALUES(@CategoryName) SET @Identity = SCOPE_IDENTITY() RETURN @@ROWCOUNT
You write the following code segment.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT categoryID, CategoryName FROM dbo.Categories",connection); adapter.InsertCommand = new SqlCommand("dbo.InsertCategory", connection); adapter.InsertCommand.CommandType = commandType.StoredProcedure; adapter.InsertCommand.Parameters.Add(new SqlParameter("@CategoryName", SqlDbType.NVarChar, 15,"CategoryName"));
You need to retrieve the identity value for the newly created record. Which code segment should you add?
A. SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@CategoryName", SqlDbType.Int); parameter.Direction = ParameterDirection.Output; parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.Output;
B. SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@CategoryName", SqlDbType.Int); parameter.Direction = ParameterDirection.Output; parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.ReturnValue;
C. SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@RowCount", SqlDbType.Int); parameter.Direction = ParameterDirection.ReturnValue; parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.Output;
D. SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@RowCount", SqlDbType.Int); parameter.Direction = ParameterDirection.Output; parameter = adapter.InsertCommand.Parameters.Add("@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.ReturnValue;


Answer: C
Question 193
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You add the following table to the database.
CREATE TABLE ObjectCache ( Id INT IDENTITY PRIMARY KEY, SerializedObjectData XML)
You write the following code segment to retreive records from the ObjectCache table. (Line numbers are included for reference only.)
01 string s = GetConnectionStringFromConfigFile("xmldb"); 02 using (SqlConnection conn = new SqlConnection(s)) 03 using (SqlCommand cmd = new SqlCommand("select * from ObjectCache", conn)) 04 { 05 conn.Open(); 06 SqlDataReader rdr = cmd.ExecuteReader(); 07 while(rdr.Read()) 08 { 09 ... 10 DeserializeObject(obj); 11 } 12 }
You need to retreive the data from the SerializedObjectData column and pass it to a method named DeserializeObject. Which line of code should you insert at line 09?
A. XmlReader obj = (XmlReader)rdr[1];
B. SByte obj = (SByte)rdr[1];
C. String obj = (String)rdr[1];
D. Type obj = (Type)rdr[1];
Answer: C
Question 194

The user interface requires that a paged view be displayed of all the products sorted in alphabetical order. The user interface supplies a current starting index and a page size in variables named startIndex and pageSize of type int. You need to construct a LINQ expression that will return the appropriate Parts from the database from an existing ContosoEntities context object named context. You begin by writing the following expression:
context.Parts
Which query parts should you use in sequence to complete the expression? (To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.)
A. .OrderBy(x => x.Name)
B. .Skip(pageSize)
C. .Skip(startIndex)
D. .Take(pageSize);
E. .Take(startIndex)

Answer: ACD
Question 195
You use Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You need to ensure that the application connects to the database server by using SQL Server authentication. Which connection string should you use?
A. SERVER=MyServer; DATABASE=AdventureWorks; Integrated Security=SSPI; UID=sa; PWD=secret;
B. SERVER=MyServer; DATABASE=AdventureWorks; UID=sa; PWD=secret;
C. SERVER=MyServer; DATABASE=AdventureWorks; Integrated Security=false;
D. SERVER=MyServer; DATABASE=AdventureWorks; Trusted Connection=true;

Answer: B
Question 196
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to several SQL Server databases. You create a function that modifies customer records that are stored in multiple databases. All updates for a given record are performed in a single transaction. You need to ensure that all transactions can be recovered. What should you do?

A. Call the RecoveryComplete method of the TransactionManager class.
B. Call the EnlistDurable method of the Transaction class.
C. Call the Reenlist method of the TransactionManager class.
D. Call the EnlistVolatile method of the Transaction class.

Answer: B
Question 197
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities. You retrieve an entity from an object context. A different application updates the database. You need to update the entity instance to reflect updated values in the database. Which line of code should you use?
A. context.Refresh(RefreshMode.StoreWins, entity);
B. context.LoadProperty(entity, ��Client��, MergeOption.OverwriteChanges);
C. context.AcceptAllChanges() ;
D. context.LoadProperty(entity, "Server", MergeOption.OverwriteChanges);

Answer: A
Question 198
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application. The application connects to a Microsoft SQL Server database. You create a DataSet object in the application. You add two DataTable objects named App_Products and App_Categories to the DataSet. You add the following code segment to populate the DataSet object. (Line numbers are included for reference only.)
01 public void Fill(SqlConnection cnx, DataSet ds) 02 { 03 var cmd = cnx.CreateCommand(); 04 cmd.CommandText="SELECT*FROMdbo.Products;"+"SELECT *FROMdbo.Categories"; 05 var adapter = new SqlDataAdapter(cmd); 06 ... 07 }
You need to ensure that App_Products and App_Categories are populated from the dbo.Products and dbo.Categories database tables. Which code segment should you insert at line 06?

A. adapter.Fill(ds, "Products"); adapter.Fill(ds, "Categories");
B. adapter.Fill(ds.Tables["App_Products"]); adapter.Fill(ds.Tables["App_Categories"]);
C. adapter.TableMappings.Add("Table", "App_Products"); adapter.TableMappings.Add("Table1", "App_Categories"); adapter.Fill(ds);
D. adapter.TableMappings.Add("Products", "App_Products"); adapter.TableMappings.Add("Categories", "App_Categories"); adapter.Fill(ds);

Answer: D
Question 199
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. The application performs a database query within a transaction. You need to ensure that the application can read data that has not yet beed commited by other transactions. Which IsolationLevel should you use?
A. ReadUncommitted
B. ReadCommitted
C. RepeatableRead
D. Unspecified

Answer: A
Question 200
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application. You use the ADO.NET Entity Framework Designer to model entities as shown in the following diagram.


You create an ObjectContext instance named objectContext1 and use it to create a SalesPerson instance named person1. You create an ObjectContext instance named objectContext2 and use it to create a SalesTerritory instance named territory1. You need to create and persist a relationship between person1 and terrotory1. What should you do?
A. Detach person1 from objectContext1. Attach person1 to objectContext2. Set the SalesTerritory property of person1 to territory1. Call SaveChanges on objectContext2.
B. Attach person1 to objectContext2. Attach territory1 to objectContext1. Set the SalesTerritory property of person1 to territory1. Call SaveChanges on both objectContext1 and objectContext2.
C. Detach person1 from objectContext1. Detach territory1 from objectContext2. Set the SalesTerritory property of person1 to territory1. Call Refresh on both objectContext1 and objectContext2.
D. Attach person1 to objectContext2.

Detach territory1 from objectContext2. Set the SalesTerritory property of person1 to territory1. Call Refresh on objectContext1.

Answer: A
Question 201
You use Microsoft .NET Framework 4.0 to develop an application that connects to two separate Microsoft SQL Server 2008 databases. The Customers database stores all the customer information, and the Orders database stores all the order information. The application includes the following code. (Line numbers are included for reference only.)
01 try 02 { 03 conn.Open(); 04 tran = conn.BeginTransaction("Order"); 05 SqlCommand cmd = new SqlCommand(); 06 cmd.Connection = conn; 07 cmd.Transaction = tran; 08 tran.Save("save1"); 09 cmd.CommandText = "INSERT INTO [Cust].dbo.Customer " + "(Name, PhoneNumber) VALUES ('Paul Jones', " + "'404-555-1212')"; 10 cmd.ExecuteNonQuery(); 11 tran.Save("save2"); 12 cmd.CommandText = "INSERT INTO [Orders].dbo.Order " + "(CustomerID) VALUES (1234)"; 13 cmd.ExecuteNonQuery(); 14 tran.Save("save3"); 15 cmd.CommandText = "INSERT INTO [Orders].dbo." + "OrderDetail (OrderlD, ProductNumber) VALUES" + "(5678, 'DC-6721')"; 16 cmd.ExecuteNonQuery(); 17 tran.Commit(); 18 } 19 catch (Exception ex) 20 { 21 ... 22 }
You run the program, and a timeout expired error occurs at line 16. You need to ensure that the customer information is saved in the database. If an error occurs while the order is being saved, you must roll back all of the order information and save the

customer information. Which line of code should you insert at line 21?
A. tran.Rollback();
B. tran.Rollback("save2"); tran.Commit();
C. tran.Rollback(); tran.Commit();
D. tran.Rollback("save2");

Answer: B
Question 202
You use Microsoft .NET Framework 4.0 to develop an ASP.NET Web application that connects to a Microsoft SQL Server 2008 database. The application uses Integrated Windows authentication in Internet Information Services (IIS) to authenticate users. A connection string named connString defines a connection to the database by using integrated security.
You need to ensure that a SqlCommand executes under the application pool's identity on the database server. Which code segment should you use?
A. using (var conn = new SqlConnection())
{ conn.ConnectionString = connString; SqlCommand cmd = null; using (HostingEnvironment.Impersonate()) {
cmd = new SqlCommand("SELECT * FROM BLOG", conn); } conn.Open(); var result = cmd.ExecuteScalar();
}
B. using (var conn = new SqlConnection(connString))
{ var cmd = new SqlCommand ("SELECT * FROM BLOG, conn); conn.Open(); using(HostingEnvironment.Impersonate()) {
var result = cmd.ExecuteScalar(); }

}
C. using (var conn = new SqlConneccion())
{ using (HostingEnvironroent.Impersonate()) {
conn.ConnectionString = connString; } var cmd = new SqlCommand("SELECT * FROM BLOG, conn); conn.Open() ; var result = cmd.ExecuteScalar();
}
D. using (var conn = new SqlConnection())
{ conn.ConnectionString = connString; var cmd = new SqlCommand("SELECT * FROM BLOG", conn); using (HostingEnvironment.Impersonate()) {
conn.Open(); } var result = cmd.ExecuteScalar();
}

Answer: D
Question 203
You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application that connects to a Microsoft SQL Server 2008 database. You add the following table to the database.
CREATE TABLE ObjectCache ( Id INT IDENTITY PRIMARY KEY, SerializedObjectData XML)
You write the following code segment to retreive records from the ObjectCache table. (Line numbers are included for reference only.)
01 string s = GetConnectionStringFromConfigFile("xmldb"); 02 using (SqlConnection conn = new SqlConnection(s))
03 using (SqlCommand cmd = new SqlCommand("select * from ObjectCache", conn))
04 {
05 conn.Open();


06 SqlDataReader rdr = cmd.ExecuteReader(); 07 while(rdr.Read()) 08 { 09 ... 10 DeserializeObject(obj); 11 } 12 }
You need to retreive the data from the SerializedObjectData column and pass it to a method named DeserializeObject. Which line of code should you insert at line 09?
A. XmlReader obj = (XmlReader)rdr[1];
B. SByte obj = (SByte)rdr[1];
C. String obj = (String)rdr[1];
D. Type obj = (Type)rdr[1];
Answer: C