Friday, August 28, 2009

70-536 MCTS .NET 2.0 Configuration #33

 

Hey Now Everybody,

Please feel free to check out my MCTS 70-536 reference page on Chris Catto.com. It’s a page with a summary of all of my posts.
As I study for this test I thought this would be good to post on to learn the content & others would be able to view & comment on it.

This content below is from section #3 of the exam.NET 2.0 Configuration Debug!.

Thx,

Catto

3. Embedding configuration, diagnostic, management & installation features

  • Code

1. Which of the following configuration files shows the best way to define a database connection string in an application configuration file?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<connectionStrings>

<add name="AdventureWorksString" providerName="System.Data.SqlClient"

connectionString="Data Source=localhost;Initial Catalog=AdventureWorks; Integrated Security=true"/>

</connectionStrings>

</configuration>

Explanation:

The .NET Framework 2.0 adds support for the <connectionStrings> configuration section for defining database connection information. Define this section within the <configuration> section using the <add> element with properties of name, providerName, and connectionString.

While you can define database connection information in the appSettings section (and you had no choice in earlier versions of the .NET Framework), your best choice is to use the strongly-typed <connectionStrings> section.

2. You are writing an application that requires the user to open a second application named "Application.exe", make a configuration change, and then close the application. You want to automatically launch the application for the user, and then wait indefinitely until the user closes the application. Which of the following code samples accomplishes this?

' VB

Dim p As Process = New Process

p.StartInfo.FileName = "Application.exe"

p.Start

p.WaitForExit

Explanation:

To launch a new process, first create an instance of the Process class, and then specify the Process.StartInfo.FileName property. Finally, call the Process.Start method. To stop processing until the application closes, call the Process.WaitForExit method without specifying a time.

You cannot specify an application filename in the Process constructor.

Specifying a time for the Process.WaitForExit method causes the runtime to continue execution after the specified time even if the application hasn't closed.

You cannot specify an application filename in the Process constructor. Additionally, specifying a time for the Process.WaitForExit method causes the runtime to continue execution after the specified time even if the application hasn't closed.

3. As part of a troubleshooting tool for the systems administrators at your organization, you are writing a command-line tool that automatically kills any unresponsive applications. Which of the following code samples accomplishes this?

' VB

For Each p As Process In Process.GetProcesses

If Not p.Responding Then

p.Kill

End If

Next

Explanation: First, you must retrieve an array of all processes by calling Process.GetProcesses. Then you should call Process.Kill for each process that you need to terminate.

There is no Process.GetUnresponsiveProcesses method, and Process.Kill is not a static method.

4. You are creating a tool for the IT department that displays the MAC address and description of every network adapter on a remote computer with the IP address 192.168.1.200. Which of the following code samples does this correctly?

' VB

Dim ms As ManagementScope = New ManagementScope("\\192.168.1.200\root\cimv2")

Dim oq As ObjectQuery = New ObjectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration")

Dim mos As ManagementObjectSearcher = New ManagementObjectSearcher(ms, oq)

Dim moc As ManagementObjectCollection = mos.Get

For Each mo As ManagementObject In moc

Console.WriteLine(mo("MacAddress") + ": " + mo("Description"))

Next

Explanation:

To query running network adapters on a remote computer:

1. Create a ManagementScope object to define the remote computer. The scope is not simply the computer name, however. It must be in the form "\\computername\root\cim2".

2. Create an instance of ObjectQuery using a Windows Management Instrumentation (WMI) query. The WMI query must be in the form "SELECT fields FROM Win32_NetworkAdapterConfiguration".

3. Create an instance of ManagementObjectSearcher by providing both the scope and the query.

4. Create an instance of ManagementObjectCollection by calling the ManagementObjectSearcher.Get method.

You can then iterate through the ManagementObjects in the ManagementObjectCollection to examine individual network adapters.

You can create a ConnectionsOptions object if you want to specify a username and password. However, you cannot use a ConnectionsOptions object in place of a ManagementScope object.

5. You are writing an application that communicates with a database. You need to be able to communicate with any type of database configured by the system administrator. Systems administrators can choose either a Microsoft SQL Server, Oracle, OleDB, or ODBC connection. Which of the following code samples would establish a database connection named db to any of those database types?

' VB

Dim css As ConnectionStringSettings = ConfigurationManager.ConnectionStrings(0)

Dim db As IDBConnection = Nothing

Select css.ProviderName

Case "System.Data.SqlClient"

db = New SqlConnection(css.ConnectionString)

' break

Case "System.Data.OracleClient"

db = New OracleConnection(css.ConnectionString)

' break

Case "System.Data.OleDb"

db = New OleDbConnection(css.ConnectionString)

' break

Case "System.Data.Odbc"

db = New OdbcConnection(css.ConnectionString)

' break

End Select

Explanation:

To determine the database type based on a ConnectionStringSettings object, examine ConnectionStringSettings.ProviderName.

ConnectionStringSettings.Name stores the server name, not the database type.

ConnectionStringSettings.ConnectionString stores the entire connection string, which does not include the database type.

ConnectionStringSettings.ElementInformation.Type describes the type of element, which will always be System.Configuration.ConnectionStringSettings.

6. You are writing an application that stores window state in the application's configuration file. Given the following configuration file, which of the following code samples correctly tests the IsMaximized element in a .NET Framework 2.0 application? (Choose all that apply.)

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="IsMinimized" value="False"/>

<add key="IsMaximized" value="True"/>

<add key="username" value="user1"/>

</appSettings>

</configuration>

Answer ' VB

If ConfigurationManager.AppSettings("IsMaximized") = "True" Then

' VB

If ConfigurationManager.AppSettings.Get("IsMaximized") = "True" Then

Explanation:

The ConfigurationManager.AppSettings collection provides access to elements defined in the <appSettings> section of a configuration file. Because it is a collection, you can access elements as an

array or by using the Get method.

The ConfigurationSettings class is obsolete in the .NET Framework 2.0.

ConfigurationManager does not contain AppSettings elements. You must access ConfigurationManager.AppSettings instead.

7. Which of the following configuration files correctly defines the information required to connect to a database by defining the first element of ConfigurationManager.ConnectionStrings regardless of other configuration files that might exist?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<connectionStrings>

<clear/>

<add name="AdventureWorksString"

providerName="System.Data.SqlClient"

connectionString="Data Source=localhost;Initial Catalog=AdventureWorks; Integrated Security=true"/>

</connectionStrings>

</configuration>

Explanation:

To define the first element of ConfigurationManager.ConnectionStrings, you must include the <clear/> element, which removes any existing <connectionStrings> elements. You must set the providerName attribute to the database type, such as System.Data.SqlClient. The Name element is a friendly name used to refer to that specific connection string.

8. Which of the following code samples successfully writes the entire contents of the Application log to the console?

' VB

Dim el As New EventLog()

el.Log = "Application"

For Each ele As EventLogEntry In el.Entries

Console.WriteLine(ele.Source + ": " + ele.Message)

Next

Explanation: To read an entire log file, create an instance of the EventLog class, specify the EventLog.Log property, and then iterate through EventLog.Entries. EventLog.Entries is an EventLogEntryCollection property containing EventLogEntry objects.

9. While performing a security review of a peer's code, you see an If statement that checks the ConfigurationManager.AppSettings("username") value and grants additional privileges if it is equal to "Tom". You need to test the behavior, but the application does not currently have a configuration file. How would you create the configuration file to define that value?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="username" value="Tom"/>

</appSettings>

</configuration>

Explanation:

Elements accessed through ConfigurationManager.AppSettings must be defined in the application configuration file, in an <appSettings> element nested within <configuration>. To define a specific

key, use the <add key> element.

10. You are writing an application that communicates with a database. The connection string is stored in the application configuration file. Which of the following would correctly retrieve the connection string?

' VB

ConfigurationManager.ConnectionStrings(0).ConnectionString

Explanation: ConfigurationManager.ConnectionStrings is a collection of type ConnectionStringSettingsCollection that contains the connection strings loaded from the application's configuration file. Because it is a collection, you must access it using an index. ConfigurationSettings, which is obsolete, does not contain a ConnectionStrings property.

11. You have created a custom event log for your application. Your application provides tools for managing the event log, and one of the methods you need to implement clears all events from the event log. Which of the following code samples would do this?

' VB

Public Sub ClearEventLog()

Dim el As New EventLog("MyApp")

el.Source = "DemoApp"

el.Clear()

End Sub

Explanation: To clear an event log, create an EventLog object and specify the EventLog.Source property. Then call EventLog.Clear.

There is no EventLog.Commit or EventLog.Log.Clear method.

Iterating through EventLogEntry objects and calling EventLogEntry.Dispose would not remove the events from the event log; it would only destroy the instances of the EventLogEntry objects created

in the runtime.

12. Which of the following code samples correctly displays the modules loaded by Application.exe?

' VB

Dim p As Process = New Process

p.StartInfo.FileName = "Application.exe"

p.Start

For Each m As ProcessModule In p.Modules

Console.WriteLine(m.FileName)

Next

Explanation: To retrieve a list of modules loaded by a process, access the ProcessModule array in Process.Modules.

Process.Modules is an array of ProcessModule objects, not ProcessModuleCollection, and Process.Modules is not a static method.

13. As a favor to your IT department, you are writing a console application that outputs information related to the security of the current computer. Which of the following code samples correctly displays running services?

' VB

Dim oq As New ObjectQuery("SELECT Caption FROM Win32_Service WHERE Started = TRUE")

Dim mos As New ManagementObjectSearcher(oq)

Dim moc As ManagementObjectCollection = mos.Get

For Each mo As ManagementObject In moc

Console.WriteLine(mo("Caption").ToString())

Next

Explanation:

To query running services:

1. Create an instance of ObjectQuery using a Windows Management Instrumentation (WMI) query. The WMI query must be in the form "SELECT fields FROM Win32_Service WHERE criteria". In this case, the criteria must be "WHERE Started = True" to return services that have started.

2. Create an instance of ManagementObjectSearcher based on the query.

3. Next, create an instance of ManagementObjectCollection by calling the ManagementObjectSearcher.Get method.

You can then iterate through the ManagementObjects in the ManagementObjectCollection to examine individual services.

ManagementObjectSearcher.Query is a property used to define the query; it is not a method. You must use ManagementObjectSearcher.Get to run a query.

14. You need to establish a database connection to a server based on configuration information stored in the application's configuration file. Which of the following properties would you examine to determine the server name?

Answer: ConnectionStringSettings.Name

Explanation:

ConnectionStringSettings.Name stores the server name.

The ConnectionStringSettings.ProviderName describes the database type and allows you to distinguish between Oracle, SQL Server, and other databases.

ConnectionStringSettings.ConnectionString stores the entire connection string, which does not include the server name.

ConnectionStringSettings.ElementInformation.Properties contains all the attributes that apply to the element. It does not normally include a Name element.

15. Which class would you use to programmatically access the connection strings stored in the following configuration file?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<connectionStrings>

<clear/>

<add name="AdventureWorksString"

providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=AdventureWorks; Integrated Security=true"/>

<add name="MarsEnabledSqlServer2005String" providerName="System.Data.SqlClient" connectionString="Server=Aron1;Database=pubs;Trusted_Connection=True;MultipleActiveResultSets=true" />

<add name="OdbcConnectionString"

providerName="System.Data.Odbc"

connectionString="Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\adatabase.mdb;Uid=Admin;Pwd=R3m3emberToUseStrongPasswords;"/>

</connectionStrings>

</configuration>

Answer: ConfigurationManager.ConnectionStrings

Explaination:

Use ConfigurationManager.ConnectionStrings to access database connection strings

16. You are writing an application that performs long-running calculations. To minimize the impact on the responsiveness of the user's computer, you want to warn the user if your application is running at Normal or higher priority. Which of the following code samples accomplishes this?

' VB

If Process.GetCurrentProcess.BasePriority >= 8 Then

Console.WriteLine("For best results, run this application at low priority.")

End If

Explanation: You should examine the Process.GetCurrentProcess().BasePriority property. A value of 4 is considered low priority, 8 is normal priority, 13 is high priority, and 24 is real-time priority. Therefore, a value of 8 or higher indicates the current application is running at Normal priority.

There is no Process.BasePriority.IsNormal property.

There is no Process.BasePriority.IsLow property.

Checking Process.GetCurrentProcess().BasePriority for a value of 4 or higher would be true even if the process were running as a low priority.

17. You are writing an application that remembers a username in the application settings. Which of the following code samples is the best way to retrieve a username?

' VB

Dim nvc As NameValueCollection = ConfigurationManager.AppSettings

Dim un As String = nvc("username")

Explanation: When writing assemblies for the .NET Framework version 2.0, you should use ConfigurationManager.AppSettings instead of ConfigurationSettings.AppSettings. ConfigurationSettings is now obsolete, and using it will result in a compiler warning.

ConfigurationManager.AppSettings does not have a GetSetting method.

18. You are in the process of isolating a complicated bug in a console application that occurs only in rare circumstances. You want to be able to write messages to the Output window in Microsoft Visual Studio 2005, as shown in the following figure. Which of the following code samples accomplishes this by writing the message, "Entering main processing loop"?

clip_image002

Answer:

' VB

Dim dtl As New DefaultTraceListener

Trace.Listeners.Add(dtl)

Debugger.Log(2, "Information", "Entering main processing loop")

Explanation: To write information to the Output window, first create an instance of DefaultTraceListener. Then add it to the Trace.Listeners collection. Finally, call Debugger.Log to write the message. Debugger.Log takes three parameters: a level, a category, and a message. The third parameter is the message that appears in the Output window.

There is no Trace.Listeners.Log method.

19. You need to provide users with a list of network drives so that they can choose where to store a file. Which of the following code samples correctly displays network drives and available space?

' VB

Dim oq As New ObjectQuery("SELECT Size, Name FROM Win32_LogicalDisk where DriveType=4")

Dim mos As New ManagementObjectSearcher(oq)

Dim moc As ManagementObjectCollection = mos.Get

For Each mo As ManagementObject In moc

Console.WriteLine(mo("Name").ToString() + ", Free Space: " + mo("Size").ToString())

Next

Explanation:

To query available drives:

1. Create an instance of ObjectQuery using a Windows Management Instrumentation (WMI) query. The WMI query must be in the form "SELECT fields FROM Win32_LogicalDisk WHERE criteria".

2. Create an instance of ManagementObjectSearcher based on the query.

3. Create an instance of ManagementObjectCollection by calling the ManagementObjectSearcher.Get method.

You can then iterate through the ManagementObjects in the ManagementObjectCollection to examine individual drives.

ManagementObjectSearcher.Get is not a static method; you must create an instance to use it.

  • Installer class: The following steps need to be taken to use a class derived from the Installer class:
    • * Inherit the Installer class.
    • * Override the Install, Commit, Rollback, and Uninstall methods.
    • * Add the RunInstallerAttribute to your derived class, and set it to true.
    • * Put your derived class in the assembly with your application to install.
    • * Invoke the installers.

The Installer class does not have OnInstall, OnCommit, OnRollback, or OnUninstall methods.

  • To uninstall the installation, only the following tasks need to be done:
    • 1. Create a new AssemblyInstaller or ComponentInstaller object.
    • 2. Specify the name of the assembly or application.
    • 3. Call the Uninstall method.

The Rollback method is used to cancel an installation that is in progress before it is committed. The Commit method finalizes an installation.

  • EventLogEntry.InstanceId, in the .NET Framework version 2.0, defines the Event ID number shown in the Event Log console.
    • EventLogEntry.EventID was used to define the Event ID in the .NET Framework versions 1.0 and 1.1; however, it is now obsolete.
    • EventLogEntry.Index gets the index of an event in the Event Log.
    • EventLogEntry.Source gets the name of the application that generated the event.
  • To wait for a management event:

1. Create a new ManagementEventWatcher object.

2. Associate an EventQuery object with the ManagementEventWatcher object.

3. Call the ManagementEventWatcher.WaitForNextEvent method.

4. Call the ManagementEventWatcher.Stop method.

    • You do not need to call the ManagementEventWatcher.Start method when calling ManagementEventWatcher.WaitForNextEvent. You only need to call ManagementEventWatcher.Start when
  • registering an event handler.
  • When writing an Application that must perform event logging, the correct time to create an event source is during installation.

o You should create a new event source durning app installation. This will require the user to have admin privileges.

o You only need to create an event source once. Therefore, it is unnecessary to create it before each event.

o You should create a new event source during application installation, rather than before you write the first event.

· Application that performs event logging are supported by the following OS’

o Windows Server 2003

o Windows XP

· OnBeforeInstall – is the method of the installer class which is called first when installing an app.

o When installing an app, methods are called in the following order: OnBeforeInstaller, Install, OnAfterInstall, OnCommiting, Commit, & finally Oncommitted

  • Debug.Assert – evaluates a condition & displays a message to the debugging output window. Debug methods do not run in release code. Ex. To assist w/ debugging, you want to write an output message if a configuration setting has not been defined. You do not want to waste processing time in released code. You should use the Debug.Assert method
    • Debug.Fail causes the debugger to break @ the line of code & output a failure message.
    • Debug.Flush flushes the debug output buffer
    • Debug.Indent controls the output formatting
  • Debugger.Break – acts just like a hard-coded breakpoint, except you can call it programmatically. You would like to pause execution to examine the value of variables during debugging, but you do not want to pause execution when users run release versions of the app. You should use the Debugger.Break method.
    • Console.Read & Console.ReadLine interrupt processing in both debug & release versions of code.
    • Debug.Assert validates a value & does not stop execution during debugging.
  • Application configuration files should be located in the same folder as the executable file & named <filename.exe> config. ex. You are writing a windows form app called MyApp. You need to define application settings & database connection strings in a custom configuration file in the same folder as your MyApp.exe file You should name the configuration file MyApp.exe.config.
  • You are writing an app that adds events to an event log. Based on the EventLogEntryType enumeration, the following are valid entry types:
    • Error
    • Information
    • Warning
    • FailureAudit
    • SuccessAudit
  • Debugger.Log – Debugger Log posts information to the attached Debugger in one is present. If no Debugger is present, the results is effectively nothing. ex. You need to write info to the debugging console, but you do not want to waste processing cycles when users run release versionso f the application. You should call the Debugger.Log method
  • To query local resources, you need instances of ObjectQuery, ManagementObjectSearcher & ManagementObjectCollection. You need to perform a management query for resources located on the local computer. You’ll need to create instances of the following classes:
    • ManagementObjectSearcher
    • ObjectQuery
    • ManagementObjectCollection
  • PerformanceCounter.RawValue – offers the best performance in single-threaded app. Ex. You are writing a single threaded app that performs custom performance logging to enable users to use the Performance console to track the current number of users who have connected to your app. You should call the PerformanceCounter.RawValue
    • PerformanceCounter.Decrement words well in Multi-Threaded environments. However PerformanceCounter.RawValue offers the best performance in single-treaded apps
  • Rollback method – to remove changes made during installation when install is cancelled.
    • The Install method performs the actual installation
    • The Commit method finalizes the installation changes
    • The OnCommitting method runs immediately before the Commit method
    • There is no OnRollback method
  • PerformanceCounter.Decrement – works well in multithreaded environments, Because users are disconnecting you would want to decrease the user counter. Ex. you’re writing a multithreaed app that performs custom logging to enable users to use the Performance console to track the current number of users who have connected to your app. You should call the PerformanceCounter.Decrement method when a user disconnects.
    • You would call Performancecounter.Increment when a user connects, not disconnects.
    • You would call PerformanceCounter.IncrementBy when a user connects, not disconnects.
    • PerformanceCounter.RawValue would offer better performance than PerformanceCounter.Decrement. However PerformanceCounter.RawValue may yield an inaccurate count in multithreaded apps.
  • Application event log – You should always write events to the Application event log or a custom event log. ex. You are writing an application that implements a custom authentication mechanism. You should write entries related to unsuccessful authentication attempts to the application event log.
    • The Security log is reserved for the operating system to store auditing events.
    • The System event log is reserved for operating system events.
    • The Active Directory event log is reserved for events relating to an Active Directory domain controller.
  • Commit – During a successful installation, Installer.Commit is the last method called, Commit finalizes all changes made during the installation.
  • Debug.Fail – causes the debugger to break at the line of code & output a failure message. ex. you want to verify an important value & stop execution if the value is not set properly. However, you only want to stop execution during debugging. You don’t want users with released versions of your app to experience problems. You should use the Debug.Fail method
    • Debug.Assert evaluates a condition & displays a message, but it does not interrupt processing.
    • Debug.Flush flushes the debug output buffer
    • Debug.Indent controls the output formatting.

1 comment:

Rauland said...

Question 14:

If I have a Config as:







And use this code:
ConnectionStringSettings cSS=ConfigurationManager.ConnectionStrings["myConn"];
string name = cSS.Name;

I dont get the server Name, I get the connectionString name.

Or am I missing something?(I bet I am! :)

Cheers, :)

http://msdn.microsoft.com/en-us/library/system.configuration.connectionstringsettings.name(VS.80).aspx