Thursday, December 31, 2009

70-536 How to Study, Take & Pass Microsoft Exam

Hey Now Everybody,

The 70-536 Microsoft Exam .NET Foundations / Fundamentals is a very interesting exam, it's the prerequisite for over 9 certification. I've studied the content, taken the exam & passed. Below are the key items to know about studding, taking & passing the 70-536 exam.

Preparation I spend endless hours preparing for the exam by first using the self-paced book the cd in the book which included code, test exam, pdf. I didn't read every word of the book but an extremely large percentage. I also blogged about much of the content which helped me review the content in detail. Another resource which was the best resource to pass the exam (not necessarily learn the content) was a practice exam from a torrent I found which was produced by some crazy company crazytopcert.com (similar to crazytestking) which was a sample test of the exact similar questions as on the exam even the answer order some of them. They also sell these practice exams on ebay for ~$5.

Enrolling for the exam, I registered for a voucher which saved me 50% or $62.50 when to prorizion and registered on that site, picked a location & date.

Taking the exam was very intense & put quite a bit of a good kind of pressure since there is so much at stake. I went threw the test & answered all the questions, then reviewed the exam about 4 or 5 times, focusing on questions I knew I didn't get right. Now I logged into the Microsoft mcp site & obtained my logo & there is my transcript showing I passed the exam. Next up 50-562 .NET 3.5 ASP.NET & earn the MCTS!
TS: Microsoft .NET Framework - Application Development Foundation

Bye for now,

Catto

Monday, November 30, 2009

Fun Live Geek Events South FLA Dec ‘09 – Feb ‘10

Hey Now Everybody,

Looking forward to some live Geek / Technical / Training events in the near future. There are two great .NET User groups in South Florida the first Florida.NET & the second is Gold Coast User Group.
I really enjoy these two groups & the people I've meet being involved with them. If you search for a .NET user group in your location most likely there is one close by you too can check out. These events are usually free or a small charge such as a $5 donation.

December ‘09 SharePoint & Gold Coast Holiday Party
January ‘10 FLA Speaker Idol
February ‘10 South FLA .NET Code Camp

On Thursday December 3rd there is going to be Microsoft SharePoint Ft Lauderdale Microsoft SharePoint 2010 1 Day Workshop for Developers located in the local Microsoft office building. Paul Stubbs @paulstubbs will be one of the presenters who I'm looking forward to seeing present for the first time.

On Friday I'm scheduled to take my Microsoft Certification .NET Foundations 70-536 exam which I've been preparing for & I'm really looking forward to this. It will be the first Microsoft Certification exam I've ever taken so it'll be a great experience. Then to celebrate the exam I'm attending our annual Gold Coast User Group Holiday party where there are going to be some stellar session including:

Tim Huckaby -Multi Touch Silverlight applications
Ken Spencer-Windows Presentation Foundation Tips
Joe Homnick @smokingJoe -SharePoint 2010 Developer Blain Barton -Windows 7.0 Developer Tricks
Shervin Shakibi @shervsherv -SQL Azure Tips (this session is da bomb!)
Paul Stubbs @paulstubbs -SharePoint 2010 Silverlight WebParts
Miguel Castro @MiguelCastro67 -Code Generation Techniques with CodeBreeze
Jason Milgram @jmilgram -Linxter SDK
Dave Noderer @DaveNoderer -TFS 2010 Source Control
Hosts Russ Fustino @rfustino and Stan Schultes @fStanSchultes
The are going to be some great presentations this day along with a nice party with some good people @ night.

In January there is going to be the Speaker Idol continuing in FLA & there are going to be two meetings
So far we have two speaker idol sessions scheduled in January: I submitted a session for the West Palm meeting & plan to prepare for that which will be real fun. Ft Lauderdale - 1/19/2010 - 6:30 PM - Contact Rainer Haberman @RainerHabermann
West Palm - 1/26/2010 - 6:30 PM - Contact Vishal Shukla @vishal_shukla

Then in February there is our Code Camp February 27th which is the best event all year!

We all learn from each other, I’d like to thank in advance all the people who will make these event happen & participate in one way or another. These events I’m sure will be entertaining & educational.


Bye for now!

Catto

Thursday, October 1, 2009

SW FLA Code Camp .NET Exam Cram

Hey Now Everybody,

Saturday is our SW Florida Code Camp & I’m presenting my session .NET Exam Cram. It’s going to be based on exam 70-536 which is the .NET Foundations exam. Also we’ll discuss topics that we’ll use everyday. This session will be great for beginners to guru’s. These topics will make us more efficient in our everyday tasks, also we’ll discuss positive personal productivity. The session is scheduled for

Room 124 @ 4:15pm Saturday Oct. 3rd 2009.

There will also be a surprise free give away to one lucky person. If you can’t make the session much of the content is outlined below:

Windows 7
Browsers
     FireFox 3.5
     IE8
     Chrome
     Safari
     Opera
RSS
Hotkeys – Keyboarding (Catto Home Keys)
    ALT + TAB
    Opening Apps
    Tab Key
     Browser Hotkeys
     Outlook
     Windows Key
     Visual Studio
     SQL Server Management Studio 
Memory Management  

MCTS 70-536 Summary Word Document ~70 pages

As for the code camp in general it’s just a really fun all day training & networking technology event. Special thanks to John Dunagan along with others for putting the event together.

As Always all comments welcome!

Catto

Wednesday, September 30, 2009

RSS - Drinking from the Fire-Hose

RSS - Drinking from the Fire Hose

Hey Now-

RSS can greatly improve your performance by allowing you to efficiently obtain information. RSS is a technology most people such as my Mom does not know about or use & at the same time many obsessive computer users (geeks) such as myself enjoy using it daily. Microsoft always refers to ‘Drinking from the Fire Hose’ Since the info we need to follow is so intense similar to a fire hose, RSS helps us drink from that fire hose. Google Reader hands down my favorite URL on the internet.

RSS (Really Simple Syndication) can be used by a reader such as Google Reader. We can subscribe to a RSS Feed then use Google reader to view the information.

I’ve posted my list of feeds I’ve subscribe to all labeled. To use this file you can download the XML file (OPML) then go to Google Reader & click the Manage Subscriptions link (bottom right), click import & browse to the file. This list is ~500 blogs mostly technical.

A user will view many sites daily, we can click a link to a favorite website such as CNN then view the new news, then click another favorite such as ESPN & read the new news. This works however we are constantly going out to see if there is information. What we can do is automatically have all our the information we care about brought to us no us going to it.
This benefits us by having information from many sites all in one place & we see the info the instant the news is published.
We can get started using RSS by the following:
1. Login to Google
2. Go To Google Reader
3. Go to webpage with RSS feeds (get feed URL)
4. Subscribe to the feed
5. Read the feed in Google Reader

My favorite hotkeys for Google Reader is ………

J – Jump this will jump to the next post
M – Mark as unread this will mark the post un read

Here is an official Google YouTube Vid that offers a great description.








As Always all comments welcome,

Catto

Memory Management – My PC can run better!

Memory Management

Hey Now -


Often time our pc's will freeze or not respond, then we wait unproductively. One action we can take is to view the process that is using the most memory & end it. Since usually the process consuming the most memory is the one causing the system to not respond.
If we are using a large amount of memory our systems will react slower & when there is not much memory used our systems will respond quickly. Memory is critical piece of hardware to our pc's & our productivity daily. Memory is one of the most important pieces of hardware & often called RAM (random access memory).
Memory Management - Monitoring & adjusting processes are two critical actions we can take to manage our memory.
Monitoring Memory in 7 & Vista has improved greatly from XP.

101 - View Processes by mem descending.
Task Manager Process Tab (Ctrl + Shift + Esc Hotkey to open Task Manager)
Resource Monitor - 7 & Vista have a much improved app compared to the traditional task manager. (click start pearl then type in Res & resource Monitor should be on the start menu to open)
Sort by Memory Descending - We can accomplish this by first ensuring the memory column is displayed (we can add columns such as peak mem on from the View menu --> select columns or right clicking on the column headers)
In 7 & Vista it's great since one the order is sorted every time we open the app after that memory will be sorted by desc. In XP we have to click 'mem' column header two times every time task manager is opened.

201 - Ending Processes
We can end a process by highlighting the process such as iexplore.exe then right clicking & selecting end tasks. Then confirm the end process.

301 - Minimizing Windows - By minimizing windows in some programs it will free memory. If a pc stops responding we can minimize all our windows (Win + M). For example Office apps such as Word & Outlook , Firefox 3.5 if it's minimized there will be memory free'd up so the system will respond quicker.


RAM Memory Hardware - We can see how much RAM is on a workstation by pressing the windows button & pause break. Win+PauseBreak. This will display the basic info regarding your system such as your processor/chip & RAM. Currently in my notebook my RAM shows 4G (2.62 usable)
We can buy memory for ~ $10 / gig now. Word to the motherboard! Currently a large percent of mother boards have a maximum of 4g. It's not too tuff or time consuming to buy more memory & install it on a notebook or desktop (my Mom can do it). By maxing out the memory installed we are also improving performance.
We should also keep in mind we now have ReadyBoost - Vista & beyond. We can easily use USB keys as memory (a really fast cache) doubling the amount of memory we have installed.


Memory & Managing our memory is critical to our productivity daily.

We can monitor & alter process to improve pc's performance at the same time our hardware is another factor we should be aware of.


As always all comments welcome!
Catto

Keyboarding - Catto Home Keys in the 2000’s

Hey Now,

I introduce to you the

Catto Home Keys

Keyboarding 101

Catto Home Keys are a new efficient use of home keys. Keyboarding / typing is critical to being productive, efficient every day. In the 2000’s it’s time for a change & not use the same old home row keys. In 1870’s the keyboard layout which many use “QWERTY” (letters below 12345) was designed. When typing words the traditional home keys work well, there is a good amount of time we can use another set of home keys while navigating & completing many tasks daily. So, the home row has been around for ~140 years & I think it’s time to change it due to the fact we use pc’s now not just a type writer.

Left hand
     Thumb – Left Alt
     Pinky   - Tab
     Pointer – F
     Middle  - E
     Ring     - 2

Right Hand –

     a.   Mouse
     b.   201 Touchpad (keyboard w/ touchpad) 
                 Thumb – Left Click 
                 Pointer - Touchpad
     c.   301 Touchpad (keyboard w/ touchpad) 
               Thumb – Touchpad
               Left Thumb – Left click (for drag click & hold)
               Ring – J
               Pinky – Enter ready (not on enter but ready)

What this does it keep our left able to use the #1 Hotkey Alt + Tab to switch tasks since we do this so often. Catto Home Keys can be used thought our work day to improve productivity.

As always all comments welcome,

Catto

Sunday, September 20, 2009

70-536 MCTS .NET Foundations Questions #37

Hey Now,

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.
I'm try to split a previous post Here is the second half.

Question: 198

You create a class library that contains the class hierarchy defined in the following code segment.

(Line numbers are included for reference only.)
01
Public Class Group
02 Public Employees As Employee()
03 End Class
0405 Public Class Employee
06 Public Name As String
07 End Class
0809 Public Class Manager
10 Inherits Employee
11 Public Level As Integer
12 End Class
You create an instance of the Group class. You populate the fields of the instance. When you attempt to serialize the instance by using the Serialize method of the XmlSerializer class, you receive InvalidOperationException. You also receive the following error message: "There was an error generating the XML document." You need to modify the code segment so that you can successfully serialize instances of the Group class by using the XmlSerializer class. You also need to ensure that the XML output contains an element for all public fields in the class hierarchy. What should you do?

A. Insert the following code between lines 1 and 2 of the code segment:

<XmlArrayItem(Type:=GetType(Employee))> _
<XmlArrayItem(Type:=GetType(Manager))> _

B. Insert the following code between lines 1 and 2 of the code segment:

<XmlElement(Type:=GetType(Employee))> _

C. Insert the following code between lines 1 and 2 of the code segment:

<XmlArray(ElementName:="Employees")> _

D. Insert the following code between lines 5 and 6 of the code segment:

<XmlElement(Type:=GetType(Employee))>

andInsert the following code between lines 10 and 11 of the code segment:

<XmlElement(Type:=GetType(Manager))>

Answer: A

K8 – XML Array Item

Question: 199

You are testing a method that examines a running process. This method returns an ArrayList containing the name and full path of all modules that are loaded by the process. You need to list the modules loaded by a process named C:\TestApps\Process1.exe. Which code segment should you use?

A. ArrayList ar = new ArrayList();
Process[] procs;
ProcessModuleCollection modules;
procs = Process.GetProcesses(@”Process1”);
if (procs.Length > 0) {modules = porcs[0].Modules;
foreach (ProcessModule mod in modules) {
ar.Add(mod.ModuleName);
}}

B. ArrayList ar = new ArrayList();
Process[] procs;
ProcessModuleCollection modules;
procs = Process.GetProcesses(@”C:\TestApps\Process1.exe”);
if (procs.Length > 0) {modules = porcs[0].Modules;
foreach (ProcessModule mod in modules) {

ar.Add(mod.ModuleName);

}}

C. ArrayList ar = new ArrayList();
Process[] procs;
ProcessModuleCollection modules;
procs = Process.GetProcessesByName(@”Process1”);
if (procs.Length > 0) {modules = porcs[0].Modules;
foreach (ProcessModule mod in modules) {
ar.Add(mod.FileName);
}}

D. ArrayList ar = new ArrayList();
Process[] procs;
ProcessModuleCollection modules;
procs =Process.GetProcessesByName(@”C:\TestApps\Process1.exe”);
if
(procs.Length > 0) {
modules = porcs[0].Modules;
foreach (ProcessModule mod in modules) {
ar.Add(mod.FileName);
}}

Answer: C

K8 – Q:List modules loaded by process A: GetProcessesByName

Question: 200

You write the following code to implement the CompanyClass.MyMethod function.

public class CompanyClass {
public int MyMethod(int arg) {
return arg;
}}

You need to call the CompanyClass.MyMethod function dynamically from an unrelated class in your assembly. Which code segment should you use?

A. CompanyClass myClass = new CompanyClass();
Type t = typeof(CompanyClass);
MethodInfo m = t.GetMethod(“MyMethod”);
int i = (int)m.Invoke(this, new object[] { 1 });

B. CompanyClass myClass = new CompanyClass();
Type t = typeof(CompanyClass); |
MethodInfo m = t.GetMethod(“MyMethod”);
int i = (int) m.Invoke(myClass, new object[] { 1 });

C. CompanyClass myClass = new CompanyClass();
Type t = typeof(CompanyClass);
MethodInfo m = t.GetMethod(“CompanyClass.MyMethod”);
int i = (int)m.Invoke(myClass, new object[] { 1 });

D. Type t = Type.GetType(“CompanyClass”);
MethodInfo m = t.GetMethod(“MyMethod”);
int i = (int)m.Invoke(this, new object[] { 1 });

Answer: B

K8 – MyClass

Question: 201

You need to create a dynamic assembly named MyAssembly. You also need to save the assembly to disk. Which code segment should you use?

A. Dim objAssembly As New AssemblyName()objAssembly.Name = "MyAssembly"
Dim objBuilder As AssemblyBuilder =
_AppDomain.CurrentDomain.DefineDynamicAssembly( _objAssembly,
AssemblyBuilderAccess.Run)objBuilder.Save("MyAssembly.dll")

B. Dim objAssembly As New AssemblyName()objAssembly.Name = "MyAssembly"
Dim objBuilder As AssemblyBuilder =

_AppDomain.CurrentDomain.DefineDynamicAssembly( _objAssembly,
AssemblyBuilderAccess.Save)objBuilder.Save("MyAssembly.dll")

C. Dim objAssembly As New AssemblyName()objAssembly.Name = "MyAssembly"
Dim objBuilder As AssemblyBuilder =
_AppDomain.CurrentDomain.DefineDynamicAssembly( _objAssembly,
AssemblyBuilderAccess.RunAndSave)objBuilder.Save("MyAssembly.dll")

D. Dim objAssembly As New AssemblyName()objAssembly.Name = "MyAssembly"
Dim objBuilder As AssemblyBuilder =
_AppDomain.CurrentDomain.DefineDynamicAssembly( _objAssembly,
AssemblyBuilderAccess.Save)objBuilder.Save("c:\MyAssembly.dll")

Answer: B

K8 – Q: Create & Save A: AssemblyBuilderAccess.Save “MyAssebly”

Question: 202

You write the following code.

Public Delegate Sub FaxDocs(ByVal sender As Object, _
ByVal args as FaxArgs)
You need to create an event that will invoke FaxDocs. Which code segment should you use?

A. Public Shared Event Fax As FaxDocs

B. Public Shared Event FaxDocs As FaxArgs

C. Public Class FaxArgs
Inherits EventArgs
Private coverPageInfo As String
Public Sub New(ByVal coverInfo As String)
Me.coverPageInfo = coverInfo
End Sub
Public ReadOnly Property CoverPageInformation As String
Get
Return Me.coverPageInfo
End Get
End PropertyEnd Class

D. Public Class FaxArgs
Inherits EventArgs
Private coverPageInfo As String
Public ReadOnly Property CoverPageInformation As String Get
Return Me.coverPageInfo
End Get
End PropertyEnd Class

Answer: A

K8 – Create an event to invoke FaxDocs A: Public Shared Event Fax As FaxDocs

Question: 203

You are developing a method to encrypt sensitive data with the Data Encryption Standard (DES) algorithm. Your method accepts the following parameters:

The byte array to be encrypted, which is named messageAn encryption key, which is named keyAn initialization vector, which is named iv You need to encrypt the data. You also need to write the encrypted data to a MemoryStream object. Which code segment should you use?

A. DES^ des = gcnew DESCryptoServiceProvider();
des->BlockSize = message->Length;
ICryptoTransform^ crypto = des->CreateEncryptor(key, iv);
MemoryStream ^cipherStream = gcnew MemoryStream();
CryptoStream ^cryptoStream = gcnew CryptoStream(cipherStream,crypto, CryptoStreamMode::Write);
cryptoStream->Write(message, 0, message->Length);

B. DES^ des = gcnew DESCryptoServiceProvider();
ICryptoTransform^ crypto = des->CreateDecryptor(key, iv);
MemoryStream ^cipherStream = gcnew MemoryStream();
CryptoStream ^cryptoStream = gcnew
CryptoStream(cipherStream, crypto,
CryptoStreamMode::Write);
cryptoStream->Write(message, 0, message->Length);

C. DES^ des = gcnew DESCryptoServiceProvider();
ICryptoTransform^ crypto = des->CreateDecryptor();
MemoryStream ^cipherStream = gcnew MemoryStream();CryptoStream ^cryptoStream
= gcnew CryptoStream(cipherStream,crypto,
CryptoStreamMode::Write);
cryptoStream->Write(message, 0, message->Length);

D. DES^ des = gcnew DESCryptoServiceProvider();
ICryptoTransform^ crypto = des->CreateEncryptor(key, iv);
MemoryStream ^cipherStream = gcnew MemoryStream();
CryptoStream ^cryptoStream = gcnew CryptoStream(cipherStream, crypto, CryptoStreamMode::Write);
cryptoStream->Write(message, 0, message->Length);

Answer: D

K8 – Q: Encrypt A: CreateEncryptor ICryptoTransform

Question: 204

You are testing a newly developed method named PersistToDB. This method accepts a parameter of type EventLogEntry. This method does not return a value. You need to create a code segment that helps you to test the method. The code segment must read entries from the application log of local computers and then pass the entries on to the PersistToDB method. The code block must pass only events of type Error or Warning from the source MySource to the PersistToDB method. Which code segment should you use?

A. Dim myLog As New EventLog("Application", ".")
For Each entry As EventLogEntry In myLog.Entries
If entry.Source = "MySource" Then
PersistToDB(entry)
End If
Next

B. Dim myLog as New EventLog("Application", ".")
myLog.Source = "MySource"
For Each entry As EventLogEntry In myLog.Entries
If entry.EntryType = (EventLogEntryType.Error And _
EventLogEntryType.Warning) Then
PersistToDB(entry)
End If
Next

C. Dim myLog as New EventLog("Application", ".")
For Each entry As EventLogEntry In myLog.Entries
If entry.Source = "MySource" Then
If (entry.EntryType = EventLogEntryType.Error) Or _
(entry.EntryType = EventLogEntryType.Warning) Then
PersistToDB(entry)
End If
End If
Next

D. Dim myLog as New EventLog("Application", ".")
myLog.Source = "MySource"
For Each entry As EventLogEntry In myLog.Entries
If (entry.EntryType = EventLogEntryType.Error) Or _
(entry.EntryType = EventLogEntryType.Warning) Then
PersistToDB(entry)
End If
Next

Answer: C

A: Loop threw all w/ some ifs to check if

Question: 205

You are creating an undo buffer that stores data modifications. You need to ensure that the undo functionality undoes the most recent data modifications first. You also need to ensure that the undo buffer permits the storage of strings only. Which code segment should you use?

A. Stack<String^> undoBuffer = gcnew Stack<String^>();

B. Stack undoBuffer = gcnew Stack();

C. Queue<String^> undoBuffer = gcnew Queue<String^>();

D. Queue undoBuffer = gcnew Queue();

Answer: A

K8 – Most rescent Stack LIFO A: Stack String

Question: 206

You need to write a multicast delegate that accepts a DateTime argument. Which code segment should you use?

A. public delegate int PowerDeviceOn(bool result,
DateTime autoPowerOff);

B. public delegate bool PowerDeviceOn(object sender,
EventsArgs autoPowerOff);

C. public delegate void PowerDeviceOn(DataTime autoPowerOff);

D. public delegate bool PowerDeviceOn(DataTime autoPowerOff);

Answer: C

K8 – void PowerDeviceOn DataTemautoPowerOff

Question: 207

You are writing a method to compress an array of bytes. The array is passed to the method in a parameter named document. You need to compress the incoming array of bytes and return the result as an array of bytes. Which code segment should you use?

A. Dim objStream As New MemoryStream(document)
Dim objDeflate As New DeflateStream(objStream, CompressionMode.Compress)
Dim result(document.Length) As Byteobj
Deflate.Write(result, 0, result.Length)
Return result

B. Dim objStream As New MemoryStream(document)
Dim objDeflate As New DeflateStream(objStream, CompressionMode.Compress)obj
Deflate.Write(document, 0, document.Length)obj
Deflate.Close()
Return objStream.ToArray

C. Dim objStream As New MemoryStream()
Dim objDeflate As New DeflateStream(objStream, CompressionMode.Compress)obj
Deflate.Write(document, 0, document.Length)obj
Deflate.Close()
Return objStream.ToArray

D. Dim objStream As New MemoryStream()
Dim objDeflate As New DeflateStream(objStream, CompressionMode.Compress)
Dim outStream As New MemoryStreamDim b As IntegerWhile (b = objDeflate.ReadByte)
outStream.WriteByte(CByte(b))
End
WhileReturn outStream.ToArray

Answer: C

K8 – MemoryStream()

Question: 208

You create the definition for a Vehicle class by using the following code segment.

public ref class Vehicle {

public : [XmlAttribute(AttributeName = "category")]
String^ vehicleType;
String^ model;
[XmlIgnore]
int year;
[XmlElement(ElementName = "mileage")]
int miles;
Condition Type condition;
Vehicle() {}
enum ConditionType {
[XmlEnum("Poor")] BelowAverage,
[XmlEnum("Good")] Average,
[XmlEnum("Excellent")] AboveAverage
}};

You create an instance of the Vehicle class. You populate the public fields of the Vehicle class instance as shown in the following table:

Exhibit:

You need to identify the XML block that is produced when this Vehicle class instance is serialized. Which block of XML represents the output of serializing the Vehicle instance?

A. <?xml version="1.0" encoding="utf-8"?>
<Vehicle
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema""
vehicleType="car">
<model>racer</model>
<miles>15000</miles>
<condition>AboveAverage</condition>
</Vehicle>

B. <?xml version="1.0" encoding="utf-8"?>
<Vehicle
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
category="car">
<model>racer</model>
<mileage>15000</mileage>
<condition>Excellent</condition>
</Vehicle>

C. <?xml version="1.0" encoding="utf-8"?>
<Vehicle
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
category="car">
<model>racer</model>
<mileage>15000</mileage>
<conditionType>Excellent</conditionType>
</Vehicle>

D. <?xml version="1.0" encoding="utf-8"?>
<Vehicle
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<category>car</category>
<model>racer</model>
<mileage>15000</mileage>
<condition>Excellent</condition>
</Vehicle>

Answer: B

K8 – Serilize XML

Question: 209

You are writing a method to compress an array of bytes. The bytes to be compressed are passed to the method in a parameter named document. You need to compress the contents of the incoming parameter. Which code segment should you use?

A. Dim inStream As New MemoryStream(document)
Dim zipStream As New GZipStream( _inStream, CompressionMode.Compress)
Dim result(document.Length) As
BytezipStream.Write(result, 0, result.Length)
Return result

B. Dim objStream As New MemoryStream(document)
Dim zipStream As New GZipStream( _ objStream, CompressionMode.Compress)zipStream.Write(document, 0,
document.Length)zipStream.Close()
Return objStream.ToArray

C. Dim outStream As New MemoryStream
Dim zipStream As New GZipStream( _outStream, CompressionMode.Compress)zipStream.Write(document, 0,
document.Length)zipStream.Close()
Return outStream.ToArray

D. Dim objStream As New MemoryStream(document)
Dim zipStream As New
GZipStream( _objStream, CompressionMode.Compress)
Dim outStream As New
MemoryStreamDim b As IntegerWhile (b =
zipStream.ReadByte)outStream.WriteByte(CByte(b))
End While
Return outStream.ToArray

Answer: C

K8 – Compress array of bytes

Question: 210

You are developing a method to decrypt data that was encrypted with the Triple DES Algorithm. The method accepts the following parameters: The byte array to be decrypted, which is named cipherMessageThe key, which is named key An initialization vector, which is named iv You need to decrypt the message by using the TripleDES class and place the result in a string. Which code segment should you use?

A. TripleDES des = new TripleDESCryptoServiceProvider();
des.BlockSize = cipherMessage.Length;
ICryptoTransform crypto = des.CreateDecryptor(key, iv);
MemoryStream cipherStream = new MemoryStream(cipherMessage);
CryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read);
string message;
message = new StreamReader(cryptoStream).ReadToEnd();

B. TripleDES des = new TripleDESCryptoServiceProvider();
des.FeedbackSize = cipherMessage.Length;
ICryptoTransform crypto = des.CreateDecryptor(key, iv);
MemoryStream cipherStream = new MemoryStream(cipherMessage);
CryptoStream cryptoStream = new CryptoStream(
cipherStream, crypto, CryptoStreamMode.Read);
string message;
message = new StreamReader(cryptoStream).ReadToEnd();

C. TripleDES des = new TripleDESCryptoServiceProvider();
ICryptoTrans form crypto = des.CreateDecryptor();
MemoryStream cipherStream = new MemoryStream(cipherMessage);
CryptoStream cryptoStream = new CryptoStream(
cipherStream, crypto, CryptoStreamMode.Read);
string message;
message = new StreamReader(cryptoStream).ReadToEnd();

D. TripleDES des = new TripleDESCryptoServiceProvider();
ICryptoTrans form crypto = des.CreateDecryptor(key, iv);
MemoryStream cipherStream = new MemoryStream(cipherMessage);
CryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read);
string message;
message = new StreamReader(cryptoStream).ReadToEnd();

Answer: D

K8 - Des.CreateDecryptor(key, iv)

Question: 211

You are developing a utility screen for a new client application. The utility screen displays a thermometer that conveys the current status of processes being carried out by the application. You need to draw a rectangle on the screen to serve as the background of the thermometer as shown in the exhibit. The rectangle must be filled with gradient shading. Which code segment should you choose?

A - Rectangle^ rectangle = gcnew Rectangle(10, 10, 450, 25); LinearGradientBrush^ rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue,
Color::CornflowerBlue,LinearGradientMode::ForwardDiagonal);
Pen^ rectanglePen = gcnew Pen(rectangleBrush);
Graphics^ g = this->CreateGraphics();
g->DrawRectangle(rectanglePen, rectangle);

B - Rectangle^ rectangle = gcnew Rectangle(10, 10, 450, 25); LinearGradientBrush^ rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue, Color::CornflowerBlue, LinearGradientMode::ForwardDiagonal);
Pen^ rectanglePen = gcnew Pen(rectangleBrush);
Graphics^ g = this->Createsraphics();
g->FillRectangle(rectangleBrush, rectangle);

C - RectangleF^ rectangle = gcnew RectangleF(10f, 10f, 450f, 25f);
array<Point^>^ points = gcnew array<Point^>^ {gcnew Point(0, 0), gcnew Point(110, 145)};
LinearGradientBrush^ rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue, Color::CornflowerBlue, LinearGradientMode::ForwardDiagonal);
Pen^ rectanglePen = gcnew Pen(rectangleBrush);
Graphics^ g = this->CreateGraphics();
g->DrawPolygon(rectanglePen, points);

D - RectangleF^ rectangle = gcnew RectangleF(l0f, l0f, 450f, 25f);
SolidBrush^ rectangleBrush = gcnew SolidBrush(Color::AliceBlue);
Pen^ rectanglePen = gcnew Pen(rectangleBrush);
Graphics^ g = this->CreateGraphics();
g->DrawRectangle(rectangleBrush, rectangle);

Answer: B

K8 – rectangleBrush numbers w/out F

Opera 10 'The Worlds Fastest Browser' has Good Qualities

 

Hey Now,

Browsers are the most important program that we use. There are many browsers out there such as Firefox, IE, Safari & Chrome. Let us take a look at Opera 10, who call themselves 'The Worlds Fastest Browser'

image

Opera's best qualities are:

1. Early adopters new browser features – This is the reason why I really enjoy using Opera over the years. I’ve learned about new features in Opera then in year or two they become mainstream.

2. Speed, Quick, lightweight browser

3. Widgets ( ex Chuck Norris Widget )

Opera has been available for a while & has not been widely used maybe ~ 2% of the market share. Personally use Opera occasionally & like to have it installed. Opera has always been an early adopter of technology such as tabbed browsing, mouse gestures & speed dial. Now in Opera 10 there is are new features for example the ability to share your bookmarks between browsers on different computes & resizing the tab toolbar to display thumbnails of the pages.

I always felt like one reason Opera didn't have as many downloads as say IE or Firefox is a few years ago there wasn't an easy big download button on Opera's homepage such as the easy big download Java button. Instead the user had to click a link then get to the next page to find the download.

One new feature for Opera 10 is a resizable tab toolbar. It can be resized vertically to be able to view page previews. Check out the screen shot below.

image

So it's good to know about Opera to stay in tune with new browser features, use it if you want a quick, lightweight browser, is it going to be your default browser? Probably not.

As Always All Comments Welcome!

Catto

Saturday, September 19, 2009

Microsoft Visual Studio Hotkey Shortcuts 2009 Top (N)

Hey Now,

Keyboarding is very important to efficiency & hotkeys / shortcut keys are can be used many times each day to increase productivity. The way I’ve displayed my hotkeys are in a shorter list that are rated so it’s a top ten style where #1 is most used & #10 is tenth most used.

     When in Visual Studio the common tasks I try to accomplish are running / debugging code, finding files in the solution explorer, using controls & their properties, using breakpoints, comments & formatting code. This list accomplishes these tasks & can be used in VS05, VS08 & VS10.

image

0.5  Ctrl+S, Alt+Tab, F5      Save file switch to browser & refresh combo
1  F5                                   Run with debug
1b       Ctrl F5                      Run w/out Debug
2 Ctrl+Alt + L                       Unhides Solutions Explorer
3. Ctrl + Alt + X                    Unhides Toolbox
4. F4                                   Unhides Properties
5  a. F9                               Sets Breakpoints
5  b. Ctrl + Shift + F9, Alt+Y   Removes All Breakpoints
5  c. F10, F11                       Step into, Step Over
6  a. Ctrl + K, Ctrl + C           Comments line(s)
6  b. Ctrl + k, Ctrl + U           Uncomment line(s)
7. Ctrl + Pageup / Ctrl+pagedown / F7   Split View
8  a. Shift+Alt+Enter              Full Screen
8  b. Alt + U                          Resize (not full screen boo)
9  a. Ctrl + F                         Find
9  b. Ctrl + H                        Replace
10    Ctrl K, Ctrl D                 Format Code All Pretty
11.   Ctrl M, Ctrl O                Collapse Code
12.  Alt + S                           Stop internal IIS
13  a. Ctrl + Shift                  Switch Tab
13  b. Ctrl + Shift                  Switch Tab reverse 
                      

This hotkey list is compact and ordered to display hotkeys that we can use daily. Of course there are large lists of every hotkey in studio out which is just not what I wanted to concentrate on right now. From one productive efficient keyboarding fan another.

As always all comments welcome!

Bye for now,

 Catto

Monday, August 31, 2009

70-536 MCTS .NET Foundations Questions #36

Hey Now,

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 some practice questions from the internet & not sure the answers are correct. There were over 200 questions & some duplicates, I hope to study all of them. I’ve also added some of my notes to these so any line starting with K8 (my nickname, first syllable of Catt o ) are my comments.

Whew! 211 Questions reviewed!

Thx,

Catto

Q: #186 - #211

Question: 186

You are writing code for user authentication and authorization. The username, password, and roles are stored in your application data store. You need to establish a user security context that will be used for authorization checks such as IsInRole. You write the following code segment to authorize the user.

If TestPassword(UserName, Password) = False Then
Throw New Exception("Could not authenticate user")End If
Dim RolesArray() As String = LookUpUserRoles(UserName)
You need to complete this code so that it establishes the user security context. Which code segment should you use?

A. Dim objID As New GenericIdentity(UserName)
Dim objUser As New GenericPrincipal(objID, RolesArray)
Thread.CurrentPrincipal = objUser

B. Dim objID As New WindowsIdentity(UserName)
Dim objUser As New WindowsPrincipal(objID)
Thread.CurrentPrincipal = objUser

C. Dim objNT As New NTAccount(UserName)
Dim objID As New GenericIdentity(objNT.Value)
Dim objUser As New GenericPrincipal(objID, RolesArray)
Thread.CurrentPrincipal = objUser

D. Dim objToken As IntPtr = IntPtr.Zeroobj
Token = LogonUserUsingInterop(UserName, EncryptedPassword)
Dim objContext As WindowsImpersonationContext =
_WindowsIdentity.Impersonate(objToken)

Answer: A

K8 – Q: Establishes security context A: GenericIdentity GenericPrincipal

Question: 187

You need to return the contents of an isolated storage file as a string. The file is machine-scoped and is named Settings.dat. Which code segment should you use?

A. IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream( “Settings.dat”, FileMode.Open);
string result = new StreamReader(isoStream).ReadToEnd();

B. IsolatedStorageFile isoFile;
isoFile = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream( “Settings.dat”, FileMode.Open, isoFile);
string result = new StreamReader(isoStream).ReadToEnd();

C. IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream( “Settings.dat”, FileMode.Open);
string result = isoStream.ToString();

D. IsolatedStorageFile isoFile;
isoFile = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream( “Settings.dat”, FileMode.Open, isoFile);
string result = isoStream.ToString();

Answer: B

K8 - File Stream String to end

Question: 188

You need to write a code segment that will create a common language runtime (CLR) unit of isolation within an application. Which code segment should you use?

A. AppDomainSetup mySetup = AppDomain.CurrentDomain.SetupInformation;
mySetup.ShadowCopyFiles = “true”;

B. System.Diagnostics.Process myProcess;
myProcess = new System.Diagnostics.Process();

C. AppDomain domain;
domain = AppDomain.CreateDomain(“CompanyDomain”):

D. System.ComponentModel.Component myComponent;
myComponent = new System.ComponentModel.Component();

Answer: C

K8 – Q: CLR isolation A: Create AppDomain

Question: 189

You need to create a method to clear a Queue named q. Which code segment should you use?

A. foreach (object e in q) {
q.Dequeue();}

B. foreach (object e in q) {
Enqueue(null);}

C. q.Clear();

D. q.Dequeue();

Answer: C

K8 – ez question right?

Question: 190

You write the following code segment to call a function from the Win32 Application Programming Interface (API) by using platform invoke.

Dim PersonName as String = "N?el"
Dim Msg as String = "Welcome " + PersonName + "to club ''!"
Dim r As Boolean= User32API.MessageBox(0, Msg, PersonName, 0)
You need to define a method prototype that can best marshal the string data. Which code segment should you use?

A. <DllImport("user32", CharSet:=CharSet.Ansi)> _Public Function
MessageBox(ByVal hWnd As Int32, _ByVal text As String, ByVal caption As String, _ByVal t As UInt32) As BooleanEnd Function

B. <DllImport("user32", EntryPoint:="MessageBoxA", _CharSet:=CharSet.Ansi)>
_Public Function MessageBox(ByVal hWnd As Int32,
_<MarshalAs(UnmanagedType.LPWStr)> ByVal text As String,
_<MarshalAs(UnmanagedType.LPWStr)> ByVal caption As String, _ByVal t As UInt32) As BooleanEnd Function

C. <DllImport("user32", CharSet:=CharSet.Unicode)> _Public Function
MessageBox(ByVal hWnd As Int32, _ByVal text As String, ByVal caption As String,
_ByVal t As UInt32) As BooleanEnd Function

D. DllImport("user32", EntryPoint:="MessageBoxA", _CharSet:=CharSet.Unicode)>
_Public Function MessageBox(ByVal hWnd As Int32,

_<MarshalAs(UnmanagedType.LPWStr)> ByVal text As String,

_<MarshalAs(UnmanagedType.LPWStr)> ByVal caption As String, _ByVal t As

UInt32) As BooleanEnd Function

Answer: C

K8 – Q: Marshall String A: CharSet.Unicode

Question: 191

You are writing a method to compress an array of bytes. The bytes to be compressed are passed to the method in a parameter named document. You need to compress the contents of the incoming parameter. Which code segment should you use?

A. MemoryStream^ intStream = gcnew MemoryStream(document);
GZipStream^ zipStream = gcnew GZipStream(inStream, CompressionMode::Compress);
array<Byte>^ result = gcnew array<Byte>(document->Length);
zipStream->Write(result, 0, result->Length);
return result;

B. MemoryStream^ stream = gcnew MemoryStream(document);
GZipStream^ zipStream = gcnew GZipStream(stream,

CompressionMode::Compress);
zipStream->Write(document, 0, document- >Length);
zipStream->Close();
return stream->ToArray();

C. MemoryStream^ outStream = gcnew MemoryStream();
GZipStream^ zipStream = gcnew GZipStream(outStream,
CompressionMode::Compress);
zipStream->Write(document, 0, document->Length);
zipStream->Close();
return outStream->ToArray();

D. MemoryStream^ inStream = gcnew MemoryStream(document);
GZipStream^ zipStream = gcnew GZipStream(inStream,
CompressionMode::Compress);
MemoryStream^ outStream = gcnew MemoryStream();
int b;
while ((b = zipStream->ReadByte()) != -1) {
outStream->WriteByte((Byte)b);
} return outStream->ToArray();

Answer: C

K8 – OutStream!

Question: 192

You develop a service application named PollingService that periodically calls long-running procedures. These procedures are called from the DoWork method. You use the following service application code:

Partial Class PollingService Inherits ServiceBase
Dim blnExit As Boolean = False Protected Overrides Sub OnStart(ByVal args() As String)
Do
DoWork()
Loop While Not blnExit
End Sub
Protected Overrides Sub OnStop()
blnExit = True
End Sub
Private Sub DoWork()
End SubEnd Class

When you attempt to start the service, you receive the following error message: Could not start the PollingService service on the local computer. Error 1053: The service did not respond to the start or control request in a timely fashion. You need to modify the service application code so that the service starts properly. What should you do?

A. Move the loop code into the constructor of the service class from the OnStart method.

B. Drag a timer component onto the design surface of the service. Move the calls to the long-running procedure from the OnStart method into the Tick event procedure of the timer, set
the Enabled property of the timer to True, and call the Start method of the timer in the OnStart method.

C. Add a class-level System.Timers.Timer variable to the service class code. Move the call to the DoWork method into the Elapsed event procedure of the timer, set the Enabled property of the timer to True, and call the Start method of the timer in the OnStart method.

D. Move the loop code from the OnStart method into the DoWork method.

Answer: C

K8 - System.Timers.Timer

Question: 193

You are developing an application to assist the user in conducting electronic surveys. The survey consists of 25 true-or-false questions. You need to perform the following tasks:

Initialize each answer to true.Minimize the amount of memory used by each survey. Which storage option should you choose?

A. BitVector32 answers = new BitVector32(1);

B. BitVector32 answers = new BitVector32(-1);

C. BitArray answers = new BitArray(1);

D. BitArray answers = new BitArray(-1);

Answer: B

K8 – Q: init to true & min mem A: BitVector32(-1);

Question: 194

You create a method that runs by using the credentials of the end user. You need to use Microsoft Windows groups to authorize the user. You must add a code segment that identifies whether a user is in the local group named Clerk.
Which code segment should you use?

A. WindowsIdentity^ currentUser = WindowsIdentity::GetCurrent();
For each
(IdentityReference^ grp in currentUser->Groups) {

NTAccount^ grpAccount =
safe_cast<NTAccount^>(grp->Translate(NTAccount::typeid));
isAuthorized = grpAccount->Value->Equals(
Environment::MachineName + “\\Clerk”);
if(isAuthorized) break;}

B. WindowsPrincipal^ currentUser =
safe_cast<WindowsPrincipal^>(Thread::CurrentPrincipal);
isAuthorized = currentUser->IsInRole(“Clerk”);

C. GenericPrincipal^ currentUser = safe_cast<GenericPrincipal^>(Thread::CurrentPrincipal);
isAuthorized = currentUser->IsInRole(“Clerk”);

D. WindowsPrincipal^ currentUser = safe_cast<WindowsPrincipal^>(Thread::CurrentPrincipal);
isAuthorized = currentUser->IsInRole( Environment::MachineName);

Answer: B

K8 – Q: Identify if user is in local user group A: WindowsPrincipal IsInRole(“rolename”)

Question: 195

You are creating a class named Age. You need to ensure that the Age class is written such that collections of Age objects can be sorted. Which code segment should you use?

A. public class Age {
public int Value;
public object CompareTo(object obj) {
if (obj is Age) { Age_age = (Age) obj;
return Value.ComapreTo(obj);
}
throw new ArgumentException(“object not an Age”);
} }

B. public class Age {
public int Value;
public object CompareTo(int iValue) {
try {
return Value.ComapreTo(iValue);
} catch {
throw new ArgumentException(“object not an Age”);
} } }

C. public class Age : IComparable {
public int Value;
public int CompareTo(object obj) {
if (obj is Age) {
Age_age = (Age) obj;

return Value.ComapreTo(_age.Value);

}
throw new ArgumentException(“object not an Age”);
} }

D. public class Age : IComparable {
public int Value;
public int CompareTo(object obj) {
try {
return Value.ComapreTo(((Age) obj).Value);
} catch {
return -1;
} } }

Answer: C

K8 – Sorting w/ IComparable

Question: 196

You write a class named Employee that includes the following code segment.
public ref
class Employee{
String^ employeeId;
String^ employeeName;
String^ jobTitleName;
public: String^ GetName() { return employeeName; }
String^ GetJobTitle() { return jobTitleName; }

You need to expose this class to COM in a type library. The COM interface must also facilitate forward-compatibility across new versions of the Employee class. You need to choose a method for generating the COM interface. What should you do?

A. Add the following attribute to the class definition.[ClassInterface(ClassInterfaceType::None)]
public class Employee {

B. Add the following attribute to the class
definition.[ClassInterface(ClassInterfaceType::AutoDual)]
public class Employee {

C. Add the following attribute to the class definition.[ComVisible(true)]
public class Employee {

D. Define an interface for the class and add the following attribute to the class definition.[ClassInterface(ClassInterfaceType::None)]
public class Employee : IEmployee

{

Answer: D

K8 – Define an interface

Question: 197

You are developing a method to hash data for later verification by using the MD5 algorithm. The data is passed to your method as a byte array named message. You need to compute the hash
of the incoming parameter by using MD5. You also need to place the result into a byte array. Which code segment should you use?

A. HashAlgorithm ^algo = HashAlgorithm::Create(“MD5”);
hash = algo->CompueHash(message);

B. HashAlgorithm ^algo = HashAlgorithm::Create(“MD5”);
hash = BitConverter::GetBytes(algo->GetHashCode());

C. HashAlgorithm ^algo;
algo = HashAlgorithm::Create(message->ToString());
hash = algo->Hash;

D. HashAlgorithm ^algo = HashAlgorithm::Create(“MD5”);
hash = nullptr;
algo->TransformBlock(message, 0, message->Length, hash, 0);

Answer: A

K8 – Q: Compute Hash A: ComputeHash

Saturday, August 29, 2009

70-536 MCTS .NET Foundations Questions #35

Hey Now,

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 some practice questions from the internet & not sure the answers are correct. There were over 200 questions & some duplicates, I hope to study all of them. I’ve also added some of my notes to these so any line starting with K8 (my nickname, first syllable of Catt o ) are my comments.

Thx,

Catto

Q: #176 - #185

Question: 176

You develop a service application named FileService. You deploy the service application to multiple servers on your network. You implement the following code segment. (Line numbers are included for reference only.)

01 public :
02 void StartService(String^ serverName){
03
04 ServiceController^ crtl = gcnew
05 ServiceController(“FileService”);
06 if (crtl->Status == ServiceControllerStatus::Stopped){}
07 }

You need to develop a routine that will start FileService if it stops. The routine must start FileService on the server identified by the serverName input parameter. Which two lines of code should you add to the code segment? (Each correct answer presents part of the solution. Choose two.)

A. Insert the following line of code between lines 03 and 04:crtl.ServiceName = serverName;

B. Insert the following line of code between lines 03 and 04:crtl.MachineName = serverName;

C. Insert the following line of code between lines 03 and 04:crtl.Site.Name = serverName;

D. Insert the following line of code between lines 04 and 05:crtl.Continue();

E. Insert the following line of code between lines 04 and 05:crtl.Start();

F. Insert the following line of code between lines 04 and 05:crtl.ExecuteCommand(0);

Answer: B, E

K8 – Repeated questions are easier the 4th time. Crtl.MachineName = serverName & crtl.Start()

Question: 177

You are changing the security settings of a file named MyData.xml. You need to preserve the existing inherited access rules. You also need to prevent the access rules from inheriting changes in the future. Which code segment should you use?

A. FileSecurity security = new FileSecurity("mydata.xml", AccessControlSections.All);
security.SetAccessRuleProtection(true, true);
File.SetAccessControl(“mydata.xml”, security);

B. FileSecurity security = new FileSecurity();
security.SetAccessRuleProtection(true, true);
File.SetAccessControl(“mydata.xml”, security);

C. FileSecurity security = File.GetAccessControl(“mydata.xml”);
security.SetAccessRuleProtection(true, true);

D. FileSecurity security = File.GetAccessControl(“mydata.xml”);
security.SetAuditRuleProtection(true, true);
File.SetAccessControl(“mydata.xml”, security);

Answer: A

K8 – FileSecurity & AccessControlSections

Question: 178

You write the following code to implement the CompanyClass.MyMethod function.
public class CompanyClass {
public int MyMethod(int arg) {
return arg;
}}

You need to call the CompanyClass.MyMethod function dynamically from an unrelated class in your assembly. Which code segment should you use?

A. CompanyClass^ myClass = gcnew CompanyClass();
Type^ t = CompanyClass::typeid;
MethodInfo^m = t->GetMethod(“MyMethod”);
int i = (int)m->Invoke(this, gcnew array<Object^> {1});

B. CompanyClass^ myClass = gcnew CompanyClass();
Type^ t = CompanyClass::typeid;
MethodInfo^m = t->GetMethod(“MyMethod”);
int i = (int)m->Invoke(myClass, gcnew array<Object^> {1});

C. CompanyClass^ myClass = gcnew CompanyClass();
Type^ t = CompanyClass::typeid;
MethodInfo^m = t->GetMethod(“CompanyClass.MyMethod”);
int i = (int)m->Invoke(myClass, gcnew array<Object^> {1});

D. Type^ t =Type::GetType(“CompanyClass”);
MethodInfo^m = t->GetMethod(“MyMethod”);
int i = (int)m->Invoke(this, gcnew array<Object^> {1});

Answer: B

K8 – Q: Call function dynamically.

Question: 179

You are creating a class to compare a specially-formatted string. The default collation comparisons do not apply. You need to implement the IComparable<string> interface.
Which code segment should you use?

A. public class Person : IComparable<string>{
public int CompareTo(string other){
}}

B. public class Person : IComparable<string>{
public int CompareTo(object other){
}}

C. public class Person : IComparable<string>{
public bool CompareTo(string other){
}}

D. public class Person : IComparable<string>{
public bool CompareTo(object other){
}}

Answer: A

K8 – Compare special string A: int CompareTo(string

Question: 180

You are writing a custom dictionary. The custom-dictionary class is named MyDictionary. You need to ensure that the dictionary is type safe. Which code segment should you use?

A. public ref class MYDictionary : public Dictionary<String^, String^>{};

B. public ref class MYDictionary : public Hashtable{};

C. public ref class MYDictionary : public IDictionary{};

D. public ref class MYDictionary {};Distionary<String^, String^>t = gcnew Dictionary<String^, String^>();
MyDictionary dictionary = (MyDictionary)t;

Answer: A

K8 – Type Safe so use <String>

Question: 181

You are developing a utility screen for a new client application. The utility screen displays a thermometer that conveys the current status of processes being carried out by the application.

You need to draw a rectangle on the screen to serve as the background of the thermometer as shown in the exhibit. The rectangle must be filled with gradient shading. Which code segment should you choose?

Exhibit:

A. Dim objRect As New Rectangle(10, 10, 450, 25)
Dim objBrush As New LinearGradientBrush( _objRect, Color.AliceBlue, Color.CornflowerBlue, _LinearGradientMode.ForwardDiagonal)
Dim objPen As New Pen(objBrush)Dim g As Graphics =
myForm.CreateGraphicsg.DrawRectangle(objPen, objRect)

B. Dim objRect As New Rectangle(10, 10, 450, 25)
Dim objBrush As New LinearGradientBrush( _
objRect, Color.AliceBlue, Color.CornflowerBlue, _
LinearGradientMode.ForwardDiagonal)
Dim objPen As New Pen(objBrush)
Dim g As Graphics = myForm.CreateGraphicsg.FillRectangle(objBrush, objRect)

C. Dim objRect As New RectangleF(10.0F, 10.0F, 450.0F, 25.0F)
Dim points() As System.Drawing.Point = _
{New Point(0, 0), New Point(110, 145)}
Dim objBrush As New LinearGradientBrush( _
objRect, Color.AliceBlue, Color.CornflowerBlue, _
LinearGradientMode.ForwardDiagonal)
Dim objPen As New Pen(objBrush)
Dim g As Graphics = myForm.CreateGraphicsg.DrawPolygon(objPen, points)

D. Dim objRect As New Rectangle(10, 10, 450, 25)
Dim objBrush As New SolidBrush(Color.AliceBlue)
Dim objPen As New Pen(objBrush)Dim g As Graphics =
myForm.CreateGraphicsg.DrawRectangle(objPen, objRect)

Answer: B

K8 - Gradient Brush object.

Question: 182

You are developing a method to call a COM component. You need to use declarative security to explicitly request the runtime to perform a full stack walk. You must ensure that all callers have the required level of trust for COM interop before the callers execute your method. Which attribute should you place on the method?

A. [SecurityPermission(
SecurityAction.Demand,
Flags=SecurityPermissionFlag.UnmanagedCode)]

B. [SecurityPermission(
SecurityAction.LinkDemand,
Flags=SecurityPermissionFlag.UnmanagedCode)]

C. [SecurityPermission(
SecurityAction.Assert,
Flags = SecurityPermissionFlag.UnmanagedCode)]

D. [SecurityPermission(
SecurityAction.Deny,
Flags = SecurityPermissionFlag.UnmanagedCode)]

Answer: A

K8 – All callers have required trust A: Demand

Question: 183

You are writing a method that returns an ArrayList named al. You need to ensure that changes to the ArrayList are performed in a thread-safe manner. Which code segment should you use?

A. ArrayList al = new ArrayList();
lock (al.SyncRoot){
return al;}

B. ArrayList al = new ArrayList();
lock (al.SyncRoot.GetType()){
return al;}

C. ArrayList al = new ArrayList();
Monitor.Enter(al);Monitor.Exit(al);return al;

D. ArrayList al = new ArrayList();
ArrayList sync_al = ArrayList.Synchronized(al);
return sync_al;

Answer: D

K8 – Q: Changes to ArrayList Thread safe A: ArrayList sync_al

Question: 184

You are loading a new assembly into an application. You need to override the default evidence for the assembly. You require the common language runtime (CLR) to grant the assembly a permission set, as if the assembly were loaded from the local intranet zone. You need to build the evidence collection. Which code segment should you use?

A. Dim objEvidence As New Evidence( _
Assembly.GetExecutingAssembly.Evidence

B. Dim objEvidence As New EvidenceobjEvidence.AddAssembly( _
New Zone(SecurityZone.Intranet))

C. Dim objEvidence As New EvidenceobjEvidence.AddHost( _
New Zone(SecurityZone.Intranet))

D. Dim objEvidence As New Evidence( _

AppDomain.CurrentDomain.Evidence)

Answer: C

K8 Q: Grant Assembly permission A: AddHost

Question: 185

You are creating an application that lists processes on remote computers. The application requires a method that performs the following tasks: Accept the remote computer name as a string parameter named strComputer.Return an ArrayList object that contains the names of all processes that are running on that computer. You need to write a code segment that retrieves the name of each process that is running on the remote computer and adds the name to the ArrayList
object. Which code segment should you use?

A. ArrayList al = new ArrayList();
Process[] procs = Process.GetProcessesByName(s trComputer);
foreach (Process proc in procs) {
al.Add(proc);}

B. ArrayList al = new ArrayList();
Process[] procs = Process.GetProcesses(strComputer);
foreach (Process proc in procs) {
al.Add(proc);}

C. ArrayList al = new ArrayList();
Process[] procs = Process.GetProcessesByName(s trComputer);
foreach (Process proc in procs) {
al.Add(proc.ProcessName);}

D. ArrayList al = new ArrayList();
Process[] procs = Process.GetProcesses(strComputer);
foreach (Process proc in procs) {
al.Add(proc.ProcessName);}

Answer: D

K8 Get Process

70-536 MCTS .NET Foundations Questions #34

Hey Now,

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 some practice questions from the internet & not sure the answers are correct. There were over 200 questions & some duplicates, I hope to study all of them. I’ve also added some of my notes to these so any line starting with K8 (my nickname, first syllable of Catt o ) are my comments.

Thx,

Catto

#167 - #175

 

Question: 167

You create a class library that is used by applications in three departments of your company. The library contains a Department class with the following definition.

Public Class Department

Public name As String

Public manager As String

End Class

Each application uses a custom configuration section to store department-specific values in the application configuration file as shown in the following code.

<Department>

<name>Hardware</name>

<manager>Company</manager>

</Department>

You need to write a code segment that creates a Department object instance by using the field values retrieved from the application configuration file. Which code segment should you use?

A. Public Class deptElement
Inherits ConfigurationElement
Protected Overrides Sub DeserializeElement( _
ByVal reader As XmlReader, _
ByVal serializeCollectionKey As Boolean)
Dim dept As Department = New Department()
dept.name = ConfigurationManager.AppSettings("name")
dept.manager = _
ConfigurationManager.AppSettings("manager")
End Sub
End Class

B. Public Class deptElement
Inherits ConfigurationElement
Protected Overrides Sub DeserializeElement( _
ByVal reader As XmlReader, _
ByVal serializeCollectionKey As Boolean)
Dim dept As Department = New Department()
dept.name = reader.GetAttribute("name")
dept.manager = reader.GetAttribute("manager")
End Sub
End Class

C. Public Class deptHandler
Implements IConfigurationSectionHandler
Public Function Create(ByVal parent As Object, _
ByVal configContext As Object, _
ByVal section As System.Xml.XmlNode) As Object _
Implements IConfigurationSectionHandler.Create
Dim dept As Department = new Department()
dept.name = section.SelectSingleNode("name").InnerText
dept.manager = _
section.SelectSingleNode("manager").InnerText
Return dept
End Function
End Class

D. Public Class deptHandler
Implements IConfigurationSectionHandler
Public Function Create(ByVal parent As Object, _
ByVal configContext As Object, _
ByVal section As System.Xml.XmlNode) As Object _
Implements IConfigurationSectionHandler.Create
Dim dept As Department = new Department()
dept.name = section.Attributes("name").Value
dept.manager = section.Attributes("manager").Value
Return dept
End Function
End Class

Answer: C

K8 – A: IconfigurationSectionHandler & SelectSingleNode

Question: 168

You are writing a method that returns an ArrayList named al. You need to ensure that changes to the ArrayList are performed in a thread-safe manner. Which code segment should you use?

A. ArrayList^ al = gcnew ArrayList();
lock (al->SyncRoot){
return al;}

B. ArrayList^ al = gcnew ArrayList();
lock (al->SyncRoot.GetType()){
return al;}

C. ArrayList^ al = gcnew ArrayList();
Monitor::Enter(al);
Monitor::Exit(al);
return al;

D. ArrayList^ al = gcnew ArrayList();
ArrayList^ sync_al = ArrayList::Synchronized(al);
return sync_al;

Answer: D

K8 – Q: Thread safe manner to changes in array list A: Synchronized

Question: 169

You need to write a code segment that transfers the contents of a byte array named dataToSend by using a NetworkStream object named netStream. You need to use a cache of size 8,192 bytes. Which code segment should you use?

A. Dim memStream As New MemoryStream(8192)memStream.Write(dataToSend, 0, _
CType(netStream.Length, Integer))

B. Dim memStream As New MemoryStream(8192)netStream.Write(dataToSend, 0, _
CType(memStream.Length, Integer))

C. Dim bufStream As New BufferedStream(netStream, 8192)
bufStream.Write(dataToSend, 0, dataToSend.Length)

D. Dim bufStream As New BufferedStream(netStream)
bufStream.Write(dataToSend, 0, 8192)

Answer: C

K8 – BufferedStream(networkStream, CasheBytes)

Question: 170

You are creating an undo buffer that stores data modifications. You need to ensure that the undo functionality undoes the most recent data modifications first. You also need to ensure that the undo buffer permits the storage of strings only. Which code segment should you use?

A. Dim undoBuffer As New Stack(Of String)

B. Dim undoBuffer As New Stack()

C. Dim undoBuffer As New Queue(Of String)

D. Dim undoBuffer As New Queue()

Answer: A

K8 – Stack Last in first out combied with of string this is VB version

Question: 171

You are creating an undo buffer that stores data modifications. You need to ensure that the undo functionality undoes the most recent data modifications first. You also need to ensure that the undo buffer permits the storage of strings only. Which code segment should you use?

A. Stack<string> undoBuffer = new Stack<string>();

B. Stack undoBuffer = new Stack();

C. Queue<string> undoBuffer = new Queue<string>();

D. Queue undoBuffer = new Queue();

Answer: A

K8 – Stack Last in first out combied with of string C#

Question: 172

You create the definition for a Vehicle class by using the following code segment.

public class Vehicle {
[XmlAttribute(AttributeName = "category")]
public string vehicleType;
public string model;
[XmlIgnore]
public int year;
[XmlElement(ElementName = "mileage")]
public int miles;
public ConditionType condition;
public Vehicle() {
}
public enum ConditionType {
[XmlEnum("Poor")] BelowAverage,
[XmlEnum("Good")] Average,
[XmlEnum("Excellent")] AboveAverage
}}

You create an instance of the Vehicle class. You populate the public fields of the Vehicle class instance as shown in the following table:

MemberValuevehicleTypecarmodelraceryear2002miles15000conditionAboveAverage You need to identify the XML block that is produced when this Vehicle class instance is serialized. Which block of XML represents the output of serializing the Vehicle instance?

A. <?xml version="1.0" encoding="utf-8"?>
<Vehicle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema""
vehicleType="car">
<model>racer</model>
<miles>15000</miles>
<condition>AboveAverage</condition>
</Vehicle>
B. <?xml version="1.0" encoding="utf-8"?>
<Vehicle
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"

category="car">
<model>racer</model>
<mileage>15000</mileage>
<condition>Excellent</condition>
</Vehicle>

C. <?xml version="1.0" encoding="utf-8"?>
<Vehicle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
category="car">
<model>racer</model>
<mileage>15000</mileage>
<conditionType>Excellent</conditionType>
</Vehicle>

D. <?xml version="1.0" encoding="utf-8"?>
<Vehicle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<category>car</category>
<model>racer</model>
<mileage>15000</mileage>
<condition>Excellent</condition>
</Vehicle>

Answer: B

K8 – Car category along with condition Excellent.

Question: 173

You need to write a code segment that transfers the first 80 bytes from a stream variable named stream1 into a new byte array named byteArray. You also need to ensure that the code segment assigns the number of bytes that are transferred to an integer variable named bytesTransferred. Which code segment should you use?

A. bytesTransferred = stream1.Read(byteArray, 0, 80)

B. For i As Integer = 1 To 80
stream1.WriteByte(byteArray(i))
bytesTransferred = i
If Not stream1.CanWrite Then
Exit For
End IfNext

C. While bytesTransferred < 80
stream1.Seek(1, SeekOrigin.Current)
byteArray(bytesTransferred) = _
Convert.ToByte(stream1.ReadByte())bytesTransferred += 1End While

D. stream1.Write(byteArray, 0, 80)bytesTransferred = byteArray.Length

Answer: A

K8 – Bytes transferred with no loop

Question: 174

You are changing the security settings of a file named MyData.xml. You need to preserve the existing inherited access rules. You also need to prevent the access rules from inheriting changes in the future. Which code segment should you use?

A. FileSecurity^ security = gcnew FileSecurity(“mydata.xml”, AccessControlSections::All);
security->SetAccessRuleProtection( true, true);
File::SetAccessControl(“mydata.xml”, security);

B. FileSecurity^ security = gcnew FileSecurity();
security->SetAccess RuleProtection(true,true);
File::SetAccessControl(“mydata.xml”, security);

C. FileSecurity^ security = File::GetAccessControl(“mydata.xml”);
security->SetAccessRuleProtection(true, true);

D. FileSecurity^ security =
File::GetAccessControl(“mydata.xml”);security->SetAuditRuleProtection(true, true);
File::SetAccessControl(“mydata.xml”, security);

Answer: A

K8 – Change Security Settings … FileSecurity

Question: 175

You are testing a component that serializes the Meeting class instances so that they can be saved to the file system. The Meeting class has the following definition:

public class Meeting {
private string title;
public int roomNumber;
public string[] invitees;
public Meeting(){
}
public Meeting(string t){
title = t;
} }

The component contains a procedure with the following code segment.
Meeting myMeeting = new Meeting(“Goals”);
myMeeting.roomNumber = 1100;
string[] attendees = new string[2]{“Company”, “Mary”};
myMeeting.invitees = attendees;
XmlSerializer xs = new XmlSerializer(typeof(Meeting));
StreamWriter writer = new StreamWriter(@"C:\Meeting.xml");
Xs.Serialize(writer, myMeeting);
writer.Close();

You need to identify the XML block that is written to the C:\Meeting.xml file as a result of running this procedure. Which XML block represents the content that will be written to the C:\Meeting.xml file?

A. <?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<title>Goals</title>
<roomNumber>1100</roomNumber>
<invitee>Company</invitee>
<invitee>Mary</invitee>
</Meeting>

B. <?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<roomNumber>1100</roomNumber>
<invitees>
<string>Company</string>
<string>Mary</string>
</invitees>
</Meeting>

C. <?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
title="Goals">
<roomNumber>1100</roomNumber> <invitees>
<string>Company</string>
<string>Mary</string>
</invitees>
</Meeting>

D. <?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <roomNumber>1100</roomNumber>
<invitees>
<string>Company</string>
</invitees>
<invitees>
<string>Mary</string>
</invitees>
</Meeting>

Answer: B

K8 – XML

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.