Sie sind auf Seite 1von 8

Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 10

Plan

„ Lesson 1 : Logging Events


.NET Framework 2.0
Application Development
Foundation
„ Lesson 2 : Debugging and Tracing
Chapitre 10
„ Lesson 3 : Monitoring Performance

„ Lesson 4 : Detecting Management Events

Instrumentation

Mohamed Romdhani
INSAT, Octobre 2007 2
M. Romdhani, Octobre 2007

70-536 Chapitre 10 70-536 Chapitre 10


Using Microsoft Windows Events and
Logging Them
„ Later versions of Windows such as Windows 2000, Windows XP, and
Windows Server 2003 provide a mechanism to let applications log
things that happen to them.
„ This feature has many benefits. By using the event log, developers can
record certain aspects of the state of an application, including serious
errors. Essentially, developers can record just about anything that they think
might be useful after the application is deployed. The ability to review
significant events makes it much easier for support people to diagnose
Lesson 1 : Logging Events issues.
„ The MSDN documentation includes the
following caveats:
1. Creating an EventLog object, writing to it, and
passing it to code executing in a partial trust
setting can be a huge security vulnerability.
2. The EventLogPermission is required for many
actions that use EventLog manipulation.
Granting this permission to partially trusted
code can open a serious security vulnerability.
3. Reading and logging events are relatively
resource intensive in terms of disk utilization,
system processor time, and other resources.

M. Romdhani, Octobre 2007 3 M. Romdhani, Octobre 2007 4

70-536 Chapitre 10 70-536 Chapitre 10

Creating and Deleting an Event Log Writing to an Event Log

„ To create an event log, the .NET Framework provides the EventLog class. „ The WriteEntry method looks rather simple.
„ To use it, the Source property needs to be specified and a message needs „ However, there are 10 overloads for it. As is the case with many overloaded
to be written, as shown in the following code, which requires the constructors, the minimal construction can be used and then you can set all
necessary properties. Or you can specify all the information you need in the
System.Diagnostics namespace: constructor.
public static void CreateEventLog() {
„ The following example shows how to use an overload to add an event ID
EventLog DemoLog = new EventLog("Chap10Demo");
public static void CreateEventLog() {
DemoLog.Source = "Chap10Demo"; EventLog DemoLog = new EventLog("Security");
DemoLog.WriteEntry("CreateEventLog called",EventLogEntryType.Information); DemoLog.Source = "Chap10Demo";
} DemoLog.WriteEntry("CreateEventLog called",EventLogEntryType.Information, 100);
} //100 is the EventID
„ After you create an EventLog object and specify its source (which, by the way, can all
be done in one of the overloaded constructors), information about the object should be „ In addition to reading custom logs, the EventLog object also gives developers the ability to read
visible from the Windows Event Viewer. from and write to built-in event logs. The built-in logs are the Application, Security, and System
logs. Even though you might have a specified log for your application, you might want to take
advantage of the built-in logs.
„ Deleting an event log is equally simple. You may want, for example, to delete the log „ Use the following code to write to the Security log (Remember that you must have permission to write) :
that you just created as part of this exercise. To remove the demonstration log, use
the Delete method of EventLog in code like the following: public static void WriteToSecurityEventLog() {
Public static void DeleteEventLog() { EventLog DemoLog = new EventLog("Security");
EventLog.Delete("Chap10Demo"); DemoLog.Source = "DemoApp";
} DemoLog.WriteEntry("A Sql Injection Attack just occurred from IP Address 100.000.00.0",
EventLogEntryType.Warning);
}

M. Romdhani, Octobre 2007 5 M. Romdhani, Octobre 2007 6

1
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 10 70-536 Chapitre 10

Reading from an Event Log Lesson 1 Summary


„ The EventLog object has an Entries property. „ The Windows event log mechanism is a convenient tool for developers to record
information that they think might be useful in the future to system
„ This property is an instance of the EventLogEntryCollection and administrators or users.
contains EventLogEntry objects. After you have an instance of your
EventLog class, you can easily iterate through the log entries, as „ There are myriad ways to log information, but the event log mechanism
illustrated by the following code: provides a clean, object-oriented way to handle this task.
public static void ReadEventLog() {
EventLog DemoLog = new EventLog(); „ Use the Source property of the EventLog to define where the information is
coming from.
DemoLog.Log = "Chap10Demo";
foreach (EventLogEntry DemoEntry in DemoLog.Entries) { „ Use the EventLogEntryType to specify what type of entry the output will be.
Console.WriteLine(DemoEntry.Source + ":" + DemoEntry.Message);
}} „ The primary object for interacting with the event log system is the EventLog
class in the System.Diagnostics namespace.
„ The only real task left to address is clearing a log. This method for doing this is „ Although the EventLog class provides substantial functionality that is simple to
one of the simplest methods to use. All you need to do is call the Clear method use, it does have overhead in terms of resources. It should be used judiciously.
of the EventLog instance: „ Many security vulnerabilities can be raised when using EventLog objects.
public static void ClearEventLog() { Therefore, you should avoid using them in partial trust environments and avoid
EventLog LogDemo = new EventLog("Chap10Demo"); passing such objects to a partial trust environment.
LogDemo.Source = "DemoApp";
LogDemo.Clear();
„ To remove all the entries in an event log, use the Clear method.
}
„ The Message property of the EventLogEntry is used to read back the
information that was written to the EventLog object.

M. Romdhani, Octobre 2007 7 M. Romdhani, Octobre 2007 8

70-536 Chapitre 10 70-536 Chapitre 10

Writing Output

„ An important part of a developer's job is stepping through code and


tracking bugs. Effective use of these facilities includes performing the
following tasks:
„ Verify that your code is doing what you expect it to.
„ Use the Debug and Debugger classes so that your code can provide
feedback to confirm that it is or is not working as planned. You use
these classes because stepping through code in other ways is time
Lesson 2 : Debugging and Tracing consuming.
„ Use tools that help to track down bugs after your application has been
deployed.

„ The two foundational classes used for debugging, Debugger and


Debug, are both in the System.Diagnostics namespace.

M. Romdhani, Octobre 2007 9 M. Romdhani, Octobre 2007 10

70-536 Chapitre 10 70-536 Chapitre 10

The Debugger Class The Debugger Class, The Log Method

„ The Debugger class, which enables communication with a debugger „ When you use the Log method, it directs the output to whatever
application, is fairly straightforward. listener objects are attached to the debugger.
„ Methods Debugger Class Name „ To use the Log method, all you need to do is call it and indicate a level,
„ Break : Signals a break to the debugger. This is an excellent tool for category, and message.
conditionally stopping the execution of the application.
Trace.Listeners.Clear();
„ IsAttached : Indicates whether the debugger is attached to a process
already. DefaultTraceListener MyListener = new DefaultTraceListener();
„ IsLogging : Indicates whether the Debugger is currently logging. Trace.Listeners.Add(MyListener);
Debugger.Log(2, "Test", "This is a test");
„ Launch : Launches a debugger, and attaches it to a process.
Console.ReadLine();
„ Log : Posts a message to the current debugger.
„ Exemple:
„ All that we've done is cleared any existing Listeners from the Listeners collection,
String MyMessage = ReturnMessage(); added a DefaultTraceListener object, and then sent some output to it. There are
if (MyMessage == null) { multiple overloads for the DefaultTraceListener, and we could just as easily have
Debugger.Break(); directed the output to a text file, for instance. If the listener is implemented
correctly, you should see the text "This is a test" in the Output window.
}
„ This use of the Break method could
yield results similar to those shown
in figure
„ NOTE : For the Debugger or Debug
class to function, the build must be
performed in Debug mode.

M. Romdhani, Octobre 2007 11 M. Romdhani, Octobre 2007 12

2
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 10 70-536 Chapitre 10

The Debug Class The other Debugger Class methods


„ Although the Debugger class is very useful, it essentially provides only two
methods: Break and Log. „ The Fail method.
„ This method simply causes the Debugger to break at the offending line of code
„ There are times when you need more granularity. In those cases, the Debug class and output a failure message. The Fail method doesn't use an evaluation.
fits the bill quite well. Methods of the Debug Class : NameValueCollection MySettings=ConfigurationManager.AppSettings;
„ Assert, Close, Fail, Flush, Indent, Print, Unindent, Write, WriteIf, if(MySettings["Foo"] == null) Debug.Fail("Configuration Setting 'Foo' is Missing");
WriteLine, WriteLineIf
„ The Write Method
„ The Assert Method „ To use the Write method, simply call it followed by whatever message you want
„ Assume you had the following configuration file, but somehow each of the settings sent to the Output window:
was deleted: Debug.Write("WriteStatements() was reached");
<appSettings>
<add key="Foo" value="Hello World!"/>
„ The WriteIf Method
<add key="ApplicationName" value="Demo Application"/>
<add key="ApplicationVersion" value="2.0.0.1"/>
„ Works identically to the Write method except that it writes output only if a condition is met.
<add key="UserFirstName" value="John"/> String s = null;
<add key="UserLastName" value="Public"/> Debug.WriteIf(s == null, "Variable [s] is null");
</appSettings>
„ By using the following code (which requires the namespace references to „ The Print Method
System.Configuration as well as to System.Diagnostics), you would know „ Works similarly to the various write methods except that it writes output
immediately if the setting "Foo" had been accidentally deleted: only to attached listener objects.
NameValueCollection MySettings = ConfigurationManager.AppSettings; String s = null;
Debug.Assert(MySettings != null && MySettings["Foo"] != null, "There was a problem with Debug.Print(s == null, "Variable [s] is null");
either the configuration file or the Foo Setting");
Console.WriteLine(MySettings["Foo"]);
M. Romdhani, Octobre 2007 13 M. Romdhani, Octobre 2007 14

70-536 Chapitre 10 70-536 Chapitre 10

Debug Attributes Creating Trace Listeners


„ Using traditional imperative methods, you'd actually have to step over it to tell the
debugger to ignore it. This hardly makes any sense, does it? Because of this, „ Two primary instrumentation classes are provided by default: Trace
attributes are particularly well suited to debugging scenarios. and Debug.
„ Overview of Debugging attributes „ They are used almost identically, and the only substantive difference is
„ DebuggerBrowsableAttribute within their physical implementation. Trace is implemented in both
„ DebuggerDisplayAttribute Release and Debug builds, whereas Debug is implemented only in
„ DebuggerHiddenAttribute
Debug builds.
„ DebuggerNonUserCodeAttribute
„ DebuggerStepperBoundaryAttribute „ The Trace Class
„ DebuggerStepThroughAttribute „ Like the Debug class, the Trace class is mainly useful when a listener
„ DebuggerTypeProxyAttribute object is attached to it.
„ DebuggerVisualizerAttribute „ Visual Studio 2005 has many listener objects built in, including
„ Example XmlTraceListener, DefaultTraceListener,
[DebuggerDisplay("CompanyName = {_companyName}, DelimmedListTraceListener, and EventLogTraceListener
CompanyState ={_companyState}, CompanyCity={_companyCity}")] „ Methods of the Trace Class:
class SoftwareCompany „ AutoFlush, Close, Fail, Flush, Indent, IndentLevel, IndentSize, Listeners, Refresh,
{ … } TraceInformation, TraceWarning, Unindent, UseGlobalLock, Write , WriteIf , WriteLine ,
WriteLineIf
„ Here we have told the attribute to display the literal "CompanyName" and the
private variable _companyName, display the literal "CompanyState" and the „ These methods are identical to those discussed in the earlier section
private variable _companyState, and finally display the literal "CompanyCity" about the Debug class
followed by _companyCity.

M. Romdhani, Octobre 2007 15 M. Romdhani, Octobre 2007 16

70-536 Chapitre 10 70-536 Chapitre 10


The TraceSource and the TraceSwitch
Classes
Listener Objects
„ The TraceSource Class provides a mechanism that enables the tracing of code
execution as well as associating trace messages with their source. To use it : „ To be of value, the Debug and Trace classes depend on listener objects
1. Declare an instance of a TraceSource class. because, stated simply, output is valuable only if it can be analyzed.
2. Name the TraceSource.
3. Call the respective methods on it.
„ By default, Visual Studio attaches a listener object that, when written to,
directs output to the Output window.
„ The following code demonstrates the use of TraceSource:
TraceSource DemoTrace = new TraceSource("DemoApp"); „ Listeners can be added manually or through the configuration file.
DemoTrace.TraceInformation("This is a test");
„ The DefaultTraceListener Class
„ The TraceSwitch Class : It is used to dynamically alter behavior of the Trace
class. „ First, we'll add a DefaultTraceListener through code.
„ You can alter the behavior for the Trace class to log the TraceError, TraceWarning, or Trace.Listeners.Clear();
TraceInfo properties. Tracing can be turned on and off, for example. The levels can be
changed. And as with most every other object in the System.Diagnostics namespace, switch DefaultTraceListener MyListener = new DefaultTraceListener();
objects can be manipulated by using code or a configuration file: Trace.Listeners.Add(MyListener);
<configuration> Trace.WriteLine("This is a test");
<system.diagnostics>
<switches> „ The same result can be accomplished by using a Configuration file entry:
<add name="DemoApp" value="2" /> <configuration>
</switches> <system.diagnostics>
</system.diagnostics>
<trace autoflush="true" indentsize="5" />
</configuration>
</system.diagnostics>
TraceSource DemoTrace = new TraceSource("DemoApp"); </configuration
DemoTrace.Switch.ShouldTrace(TraceEventType.Information);
DemoTrace.Switch.Level = SourceLevels.Information;
DemoTrace.TraceInformation("This is a test"); 17 18
M. Romdhani, Octobre 2007 M. Romdhani, Octobre 2007

3
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 10 70-536 Chapitre 10

The TextWriterTraceListener The XmlWriterTraceListener class


„ The XmlWriterTraceListener class forwards Debug or Trace information to a
„ The TextWriterTraceListener class is one of the simplest listener objects to use TextWriter object or Stream object.
and simply directs output to a text file or stream. „ XmlWriterTraceListener strongly resembles TextWriterTraceListener, in addition, it
provides additional attributes: CallStack, Computer, Correlation, DataItem, EventId,
„ Following is an example of how you can enable the class by using code: Execution, Level, Message, Source, TimeCreated, …
Trace.Listeners.Clear(); „ Creating by code an XMLWriterTraceListener
TextWriterTraceListener MyListener = new TextWriterTraceListener(@"C:\output.txt"); Trace.Listeners.Clear();
Trace.Listeners.Add(MyListener); XmlWriterTraceListener MyListener = new XmlWriterTraceListener (@"C:\output.xml");
Trace.AutoFlush = true; Trace.Listeners.Add(MyListener);
Trace.WriteLine("This is a test"); Trace.AutoFlush = true;
„ The same result can be accomplished using a configuration file: Trace.WriteLine("This is a test");
<configuration>
<system.diagnostics> „ This can also be configured using the following:
<?xml version="1.0" encoding="utf-8" ?>
<trace autoflush="true" indentsize="5">
<configuration>
<listeners>
<system.diagnostics>
<add name="DemoListener" type="System.Diagnostics.TextWriterTraceListener"
<trace autoflush="true" indentsize="5">
initializeData="output.txt" /> <listeners>
<remove name="Default" /> <add name="DemoListener" type="System.Diagnostics.XmlWriterTraceListener"
</listeners> initializeData="output.xml" />
</trace> <remove name="Default" />
</system.diagnostics> </listeners>
</configuration> </trace>
</system.diagnostics>
M. Romdhani, Octobre 2007 19 M. Romdhani, Octobre 2007
</configuration> 20

70-536 Chapitre 10 70-536 Chapitre 10

Lesson 2 Summary

„ The Debug and Trace classes are two of the primary tools developers can use to
examine the execution of their applications while they run.

„ The Write, WriteLine, WriteIf, and WriteLineIf methods all can be used to send
output to attached listener objects.

„ The Assert method of the Debug and Trace classes is one mechanism to test a
condition of your code and receive feedback based on that evaluation.
Lesson 3 : Monitoring Performance
„ Listener objects are used as receptacles for Debug and Trace information.

„ If no listener object is specified, the DefaultTraceListener is used.

„ The XmlTraceListener can be used to output detailed information in XML format.

„ The TraceSource class allows the developer to specify information about the
source of the trace information

„ The TraceSwitch allows the developer to manipulate virtually every aspect of the
TraceSource class.

M. Romdhani, Octobre 2007 21 M. Romdhani, Octobre 2007 22

70-536 Chapitre 10 70-536 Chapitre 10

Why Monitoring Performance ? An Overview of Processes


„ The TechnoGeek definition would be something like: "A process is a
„ Performance problems can sometimes be notably more problematic memory slice that contains resources."
than traditional bugs because, unlike most bugs, performance
problems are often quite difficult to correct. Here are some common
performance problems: „ A less jargony definition would be something to the effect of: "An
isolated task performed by the operating system" or "an application
„ Slow or sluggish user interface (UI) responsiveness—for example, that's being run."
frozen screens or application locks
„ Therefore, a process owns one or more operating system threads. It
„ Slow or sluggish network access can also open private virtual addressing space that can only be
„ Slow or sluggish database connectivity, response time, or both managed by its own threads.
„ Slow or sluggish file input/output
„ Technically (assuming a typical Intel-based 32-bit processor), a
process is best described as a contiguous memory space of 4 GB.
„ Understanding how each of these areas works is critical to writing This measurement includes memory from 0x00000000 to 0xFFFFFFF.
applications the perform well. However, once an application is
deployed, life can get quite complicated. „ This memory is secure and private, and it cannot be accessed by other
processes. This configuration greatly enhances the stability and
„ You'll inevitably end up searching in some wrong directions, all the while performance of Windows applications.
wasting precious time.
„ Two things are noteworthy about how processes are managed:
„ Fortunately, the System.Diagnostics namespace provides all the tools
necessary to avoid this ineffective approach to problem solving. 1. Windows allocates whatever memory resources are necessary for a
process to operate, but nothing more. Traditional 32-bit machines have a
maximum RAM allocation of 4 GB.
2. The Virtual Memory manager saves chunks of RAM to disk as memory
pages.These pages, by default, have a size of 4 KB.
M. Romdhani, Octobre 2007 23 M. Romdhani, Octobre 2007 24

4
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 10 70-536 Chapitre 10

The Process Class Enumerating Processes


„ The following code snippet accepts a process identifier and returns
„ An instance of the Process (System.Diagnostics )object can reference information about it. (To run the code, substitute the name of your
an operating-system process. The processes that this class can machine for the "machinename" variable.)
reference are as follows: //For illustration purposes, the number 2 is randomly chosen
Process SpecificProcess = null;
„ One or more processes running on a local machine try{
„ One or more processes running on a remote machine SpecificProcess = Process.GetProcessById(2);
Console.WriteLine(SpecificProcess.ProcessName);
„ Enumerating Processes } catch (ArgumentException Problem){
Console.WriteLine(Problem.Message);
„ There are four primary methods to determine which processes are }
running at any given time or to identify specific processes: try{
1. the GetCurrentProcess method, SpecificProcess = Process.GetProcessById(2, "machinename");
2. the GetProcessById method, Console.WriteLine(SpecificProcess.ProcessName);
} catch (ArgumentException Problem){
3. the GetProcessesByName method, and
Console.WriteLine(Problem.Message);
4. the GetProcesses method. }
„ The simplest of these four methods is the GetCurrentProcess method. „ The following code will retrieve information about a process by using the
This method associates a Process object with the currently active process's name as an identifier (as opposed to using a numeric identifier as was
process and returns it. done in the previous example):
Process[] SpecificProcesses = null;
Process ThisProcess = Process.GetCurrentProcess();
SpecificProcesses = Process.GetProcessesByName("explorer", "machinename");
Console.WriteLine("Current Process: " + ThisProcess);
foreach (Process ThisProcess in SpecificProcesses) {
Console.WriteLine(ThisProcess.ProcessName);
M. Romdhani, Octobre 2007 25 }
M. Romdhani, Octobre 2007 26

70-536 Chapitre 10 70-536 Chapitre 10

Using Performance Counters Using Performance Counters


„ Because performance considerations can have a major impact on user „ The properties that identify a
acceptance of an application, being able to measure performance is PerformanceCounter object are as follows:
critical.
„ Computer Name
„ For example, if an abundance of support calls indicated that the
application was sluggish, you'd want to follow some process to „ Category Name.
diagnose and troubleshoot the problem. The procedure for doing this is „ Category Instance
outlined in the following steps:
„ Counter Name
1. Verify and confirm that the problem exists.
2. Create a baseline measurement of how the application should perform, and
compare that baseline to actual measurements. „ Windows has many built-in performance
counters, which on their own can measure
3. Record each functional area where a disparity exists between the baseline almost any resource that developers might
performance and actual performance.
be concerned with.
4. Examine the code that's running where the disparities exist.
„ These performance counters will vary
5. Take corrective action. based on what applications are installed
on the machine.
„ To accomplish this measurement, the .NET Framework provides the „ It's important to be aware of which
PerformanceCounter class. counters are installed on your machine;
„ This class can be used exclusively through code as well as through otherwise, you might end up creating your
the PerformanceCounter component, which allows developers to own counters that duplicate functionality
visually control PerformanceCounter objects at design time. already available.
„ To use this component, simply open the Components view of the Visual
Studio 2005 Toolbox, select Performance Counter, and drag it onto a form.
M. Romdhani, Octobre 2007 27 M. Romdhani, Octobre 2007 28

70-536 Chapitre 10 70-536 Chapitre 10

The CounterCreationData Class The PerformanceCounterCategory Class

„ The CounterCreationData class has one main purpose: it serves as a


container object that holds all the pertinent properties that will be „ The main purpose of the PerformanceCounterCategory class is to manage
needed to create a PerformanceCounter object. The and manipulate PerformanceCounter objects and their categories.
CounterCreationData class has three properties that developers will „ It contains the following five static methods, which allow a tremendous
want to manipulate. These properties are described in Table 10-6. amount of control over performance categories:
„ Properties of the CounterCreationData Clas,s Name : CounterHelp , 1. Create Creates a PerfomanceCounterCategory class
CounterName , CounterType , 2. Delete Deletes a PerformanceCounterCategory class
„ To create a new instance of the CounterCreationData class, do one of 3. Exists Determines whether a PerformanceCounterCategory is already in existence
the following:
4. GetCategories Lists each of the PerformanceCounterCategories on a given
1. Declare a new instance of the object, and set each property manually. machine
2. Pass in all three properties to the second overloaded constructor. 5. ReadCategory Reads all the counter and performance data associated with a
given PeformanceCategory
„ The following code snippet demonstrates the first process listed:
String DemoCounterName = "DemoCounter"; „ The following code checks to see if a given performance counter exists and if
CounterCreationData DemoData = new CounterCreationData();
not, it creates it.
PerformanceCounterCategory DemoCategory = new PerformanceCounterCategory("DemoCategory");
DemoData.CounterName = DemoCounterName;
if (!PerformanceCounterCategory.Exists("DemoCategory")) {
DemoData.CounterHelp = "Training Demo Counter"; PerformanceCounterCategory.Create("DemoCategory", "Training Demo Category",
DemoData.CounterType = PerformanceCounterType.SampleCounter; PerformanceCounterCategoryType.SingleInstance, "DemoCounter", "Training Counter Demo");
„ The following code snippet demonstrates the second process listed: }
String DemoCounterName = "DemoCounter";
CounterCreationData DemoData = new CounterCreationData(DemoCounterName,
"Training Demo Counter", PerformanceCounterType.SampleCounter );
M. Romdhani, Octobre 2007 29 M. Romdhani, Octobre 2007 30

5
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 10 70-536 Chapitre 10

The PerformanceCounter Class Starting Processes

„ Each of the previous items were parts that, when used together, help „ Many times there is a need to start external applications or processes from
provide a tremendous amount of information about within your application.
PerformanceCounter objects. „ There are two ways to start a process:
„ To illustrate what can be done with a PerformanceCounter, Here is a 1. Use without command-line arguments.
common scenario: examining how many applications are running on an 2. Specify command-line arguments.
ASP.NET process. There is a predefined category named "ASP.NET"
and a predefined counter named "Applications Running". „ Start Processes without Command-Line Arguments
StringBuilder Builder = new StringBuilder(); „ In many instances, you'll want to set many more properties than are provided in
Builder.Append("Counter Name:" + DemoCounter.CounterName + "\r\n"); the constructors. To accomplish this, the ProcessStartInfo class must be used.
Builder.Append("Counter Type:" + DemoCounter.CounterType.ToString() + "\r\n"); ProcessStartInfo Info = new ProcessStartInfo();
Builder.Append("Category Name:" + DemoCounter.CategoryName + "\r\n"); Info.FileName = this.tbProcessName.Text;
Builder.Append("Instance Name:" + DemoCounter.InstanceName+ "\r\n"); Process.Start(Info);
Builder.Append("Machine Name:" + DemoCounter.MachineName + "\r\n");
MessageBox.Show(Builder.ToString()); „ Start Processes with Command-Line Arguments
„ Specifying command-line arguments to start a process is similar to starting a process
without them.
ProcessStartInfo Info = new ProcessStartInfo();
Info.FileName = this.tbProcessName.Text;
Info.Arguments = "EACH OF THESE WORDS IS AN ARGUMENT " ;
Process.Start(Info);

M. Romdhani, Octobre 2007 31 M. Romdhani, Octobre 2007 32

70-536 Chapitre 10 70-536 Chapitre 10

The StackTrace and StackFrame Classes Lesson 3 Summary


„ A process is an executing application, with a unique identifier to
„ The StackTrace class allows you to see the state of the .NET runtime's differentiate it from other processes. Processes are mechanisms that
call stack at a given point in time. allow applications to run safely isolated from other applications.

„ Each time a method is called, a StackFrame is added and pushed onto „ The Start method of the Process class allows applications to be started
the stack. Each subsequent method is pushed onto the stack to be programmatically. The GetProcesses method of the Process class
executed in last-in, first-out order. When there are no more methods to returns information about all running processes on a machine.
be called, each method is executed and popped (removed) from the
stack.
„ To pass values into the constructor of the Main method, command-line
arguments can be specified.
„ Every time an exception is thrown by the .NET runtime, the Exception
object's current StackTrace property is set to the current StackTrace.
try {
„ The StackTrace object provides detailed information about the state of
execution for a given application. StackFrame objects make up the
Int32 x = 1;
StackTrace object. However, they are intended to support the .NET
x--; Framework and should not be used directly.
Int32 i = 10 / x;
} catch (DivideByZeroException Problem) {
„ PerformanceCounter objects are mechanisms that allow specific
Debug.Assert(false, Problem.StackTrace); measurement of an application's resource utilization.
}
„ After the Exception object is caught, the code intentionally causes a Debug
assertion to fail so that the StackTrace can be viewed.

M. Romdhani, Octobre 2007 33 M. Romdhani, Octobre 2007 34

70-536 Chapitre 10 70-536 Chapitre 10

Enumerating Management Objects

„ The System.Management namespace provides a comprehensive set of


tools to monitor and manage the system, devices, and applications via
the Windows Management Instrumentation (WMI) technology.

„ At the core of the System.Management namespace is the


DirectoryObjectSearcher object, which can programmatically access
resources through WMI.
Lesson 4 : Detecting Management Events „ This mechanism is extremely easy to use because the syntax mimics
that of Structured Query Language (SQL), which most developers are
already familiar with.
„ To execute a query using the DirectoryObjectSearcher, the following
steps need to be performed:
1. Declare an instance of the ConnectionOptions class, and set the
UserName and Password properties.
2. Declare an instance of the DirectoryObjectSearcher class.
3. Declare a ManagementScope object, and set the PathName and
ConnectionOptions properties.
4. Create an ObjectQuery object, and specify a query to run.
5. Create a ManagementObjectCollection, and set it to the return value from
the DirectoryObjectSearcher's Get method.

M. Romdhani, Octobre 2007 35 M. Romdhani, Octobre 2007 36

6
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 10 70-536 Chapitre 10


Management Objects in the
System.Management Namespace
Enumerating Logical Drives
„ To enumerate the logical drives by using System.Management objects, the
„ The Main Management Objects are : main thing that needs to be done is specify a target.
1. ManagementQuery „ In the following example, the Win32_LogicalDisk object is going to be queried.
Base class used for WMI queries. The Size and Name attributes will be returned via a
2. EventQuery ManagementObjectCollection.
ConnectionOptions DemoOptions = new ConnectionOptions();
Query object used to query WMI objects. EventQuery objects are used in DemoOptions.Username = "\\Bill";
conjunction with event watchers. DemoOptions.Password = "mp99!!swa0";
3. ObjectQuery ManagementScope DemoScope = new ManagementScope("\\machinename", DemoOptions);
ObjectQuery DemoQuery = new ObjectQuery("SELECT Size, Name FROM Win32_LogicalDisk
Query object for querying both instances and classes.
where DriveType=3");
4. ManagementObjectSearcher
Class used to query a collection of ManagementObjects based on a WMI ManagementObjectSearcher DemoSearcher = new ManagementObjectSearcher(DemoScope, DemoQuery);
query ManagementObjectCollection AllObjects = DemoSearcher.Get();

foreach (ManagementObject DemoObject in AllObjects){


Console.WriteLine("Resource Name: " + DemoObject["Name"].ToString());
Console.WriteLine("Resource Size: " + DemoObject["Size"].ToString());
}

M. Romdhani, Octobre 2007 37 M. Romdhani, Octobre 2007 38

70-536 Chapitre 10 70-536 Chapitre 10


Retrieve Information about Services that
Enumerating Network Adapters Are Paused
„ The main difference between the previous code and the code used to „ Retrieving information about Windows Services is just as straightforward
accomplish this is that the Win32_NetworkConfiguration object needs to be as retrieving information about other resources. Just do the following:
queried instead of the Win32_LogicalDisk. 1. Create a new ManagementObjectSearcher object.
„ Network adapters and disk drives have different properties, so the implementation will 2. Specify a query for it.
change slightly to allow each of the different properties to be shown:
public const String IP_Enabled = "IPEnabled"; 3. Call the Get method of the ManagementObjectSearcher.
public const String IP_Address = "IPAddress";
public const String IP_Subnet = "IPSubnet";
public const String DNS_HostName = "DNSHostName";
public const String DNS_Domain = "DNSDomain"; „ Here is an example:
public void EnumerateAllNetworkAdapters() {
private static void ListPausedServices(){
ManagementObjectSearcher DemoQuery =new ManagementObjectSearcher("SELECT * FROM ManagementObjectSearcher DemoSearcher = new ManagementObjectSearcher("SELECT *
Win32_NetworkAdapterConfiguration");
ManagementObjectCollection DemoQueryCollection = DemoQuery.Get();
FROM Win32_Service WHERE Started = FALSE");
ManagementObjectCollection AllObjects = DemoSearcher.Get();
foreach (ManagementObject DemoManager in DemoQueryCollection){
Console.WriteLine("Description : " + DemoManager["Description"]);
foreach (ManagementObject PausedService in AllObjects) {
Console.WriteLine("MacAddress : " + DemoManager["MacAddress"]); Console.WriteLine("Service = " + PausedService["Caption"]);
if (Convert.ToBoolean(DemoManager[IP_Address]) == true) {
String[] IPAddresses = DemoManager[IP_Address] as String[]; }
String[] IPSubnets= DemoManager[IP_Subnet] as String[]; }
Console.WriteLine(DNS_HostName + " : " + DemoManager[DNS_HostName]);
Console.WriteLine(DNS_Domain + " : " + DemoManager[DNS_Domain]);

foreach (String IPAddress in IPAddresses) {


Console.WriteLine(IP_Address + " : " + IPAddress);
}
foreach (String IPSubnet in IPSubnets) {
Console.WriteLine(IP_Subnet + " : " + IPSubnet);
}}}}
M. Romdhani, Octobre 2007 39 M. Romdhani, Octobre 2007 40

70-536 Chapitre 10 70-536 Chapitre 10


Subscribe to Management Events Using
the ManagementEventWatcher Class
Lesson 4 Summary

„ The ManagementEventWatcher class allows for subscription information about „ WMI is a component of the Windows operating system that provides
events that occur within the WMI context. To use it, perform the following
steps: monitoring functionality that spans virtually every machine resource.
1. Create a new ManagementEventWatcher object.
2. Associate an EventQuery object with it. „ The EventQuery class is used within the .NET Framework to represent
3. Call the WaitForNextEvent method. a WMI query.
4. Stop the notifications.
„ The Win32_Service object can be used to query information about
„ Here is an example: Windows services.
public static void QueryServices() {
EventQuery DemoQuery = new EventQuery();
DemoQuery.QueryString = "SELECT * FROM __InstanceCreationEvent WITHIN 2 „ The ManagementQuery base class is used as a foundation for all
WHERE TargetInstance isa \"Win32_Service\" management query objects.
AND TargetInstance.State = 'Paused'";
„ The ManagementObjectSearcher is used to query system resources
ManagementEventWatcher DemoWatcher = through WMI.
new ManagementEventWatcher(DemoQuery);

DemoWatcher.Options.Timeout = new TimeSpan(0, 0, 10);


Console.WriteLine("Open an application to trigger WaitForNextEvent");
ManagementBaseObject Event = DemoWatcher.WaitForNextEvent();
DemoWatcher.Stop();
}

M. Romdhani, Octobre 2007 41 M. Romdhani, Octobre 2007 42

7
Chapitre 1- Introduction aux technologies J2EE

70-536 Chapitre 10 70-536 Chapitre 10

Lesson review Chapter 10 Summary


„ The Windows event logging mechanism is an excellent way to record
„ Which of the following items cannot be queried via WMI? information about an application that has already been deployed.
1. Network adapters. „ Informational messages, warning messages, security messages, and custom
messages can all be stored in the Windows event logs.
2. Logical drives on a machine
3. A list of OleDb-compliant databases on the network „ The Debug and Trace classes are provided to allow for specific application
information to be tracked during development and after deployment.
4. A list of Windows Services on a machine and their respective states
„ Listener objects provide a location for Debug and Trace output to be directed to.

„ Visual Studio 2005 provides many new attributes that will allow you to take
„ Correct Answer: 3 finely grained control over the debugger. Examples of these new attributes
1. Incorrect: Network Adapters can be discovered using WMI. include DebuggerVisualizerAttribute and DebuggerProxyType.
2. Incorrect: Logical drives can be discovered and interrogated using „ Visualizers are a powerful new feature of Visual Studio 2005 that allow
WMI. developers to see virtually every aspect of an object at debug time.
3. Correct: Although some database information can be retrieved using
WMI, a list of all OleDb-compliant databases cannot be determined „ Windows Management Instrumentation (WMI) and the System.Management
using the WMI query syntax namespace provide a framework for querying information about virtually every
aspect of a computer's resources.
4. Incorrect: A list of Windows Services running on a machine, and their
respective states, can be queried via WMI.

M. Romdhani, Octobre 2007 43 M. Romdhani, Octobre 2007 44

Das könnte Ihnen auch gefallen