Windows Management Instrumentation
Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems. You can write WMI scripts or applications to automate administrative tasks on remote computers but WMI also supplies management data to other parts of the operating system and products, for example System Center Operations Manager, formerly Microsoft Operations Manager (MOM), or Windows Remote Management (WinRM).
Where Applicable
WMI can be used in all Windows-based applications, and is most useful in enterprise applications and administrative scripts.
System administrators can find information about using WMI at the TechNet ScriptCenter, and in various books about WMI. For more information.
The Developer Audience
WMI is designed for programmers who use C/C++, the Microsoft Visual Basic application, or a scripting language that has an engine on Windows and handles Microsoft ActiveX objects. While some familiarity with COM programming is helpful, C++ developers who are writing applications can find good examples for getting started at Creating a WMI Application Using C++.
To develop managed code providers or applications in C# or Visual Basic .NET using the .NET Framework, see WMI in .NET Framework.
The WMI Software Developer Kit (SDK) is available as a download that includes documentation at the Download Center. The WMI Redistributable Components version 1.0 file, is required only for Windows 2000 and is available to download at the same location.
WMI functionality introduced in the Windows 2000 Professional with Service Pack 2 (SP2) operating system is also available to earlier operating systems by downloading the .NET Framework SDK, and the .NET Framework Redistributable. These can be obtained at http://msdn2.microsoft.com/en-us/netframework/aa731542.aspx.
Overview Run-Time Requirements
For more information about which operating system is required to use a specific API element or WMI class, see the Requirements section of each topic in the WMI documentation.
If an expected component appears to be missing, see Operating System Availability of WMI Components.
Posted in: programming | Tags: c# introduction intro wmi overviewNamed and Optional Arguments in C# 4.0
Named and optional parameters are really two distinct features, but are often useful together. Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list.
Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted.
Even in APIs for .NET however you sometimes find yourself compelled to write many overloads of a method with different combinations of parameters, in order to provide maximum usability to the callers. Optional parameters are a useful alternative for these situations.
Optional parameters
A parameter is declared optional simply by providing a default value for it:
public void M(int x, int y = 5, int z = 7);
Here y and z are optional parameters and can be omitted in calls:
M(1, 2, 3); // ordinary call of M
M(1, 2); // omitting z – equivalent to M(1, 2, 7)
M(1); // omitting both y and z – equivalent to M(1, 5, 7)
Named and optional arguments
C# 4.0 does not permit you to omit arguments between commas as in M(1,,3). This could lead to highly unreadable comma-counting code. Instead any argument can be passed by name. Thus if you want to omit only y from a call of M you can write:
M(1, z: 3); // passing z by name
or
M(x: 1, z: 3); // passing both x and z by name
or even
M(z: 3, x: 1); // reversing the order of arguments
All forms are equivalent, except that arguments are always evaluated in the order they appear, so in the last example the 3 is evaluated before the 1.
Optional and named arguments can be used not only with methods but also with indexers and constructors.
Overload resolution
Named and optional arguments affect overload resolution, but the changes are relatively simple:
A signature is applicable if all its parameters are either optional or have exactly one corresponding argument (by name or position) in the call which is convertible to the parameter type.
Betterness rules on conversions are only applied for arguments that are explicitly given – omitted optional arguments are ignored for betterness purposes.
If two signatures are equally good, one that does not omit optional parameters is preferred.
M(string s, int i = 1);
M(object o);
M(int i, string s = “Hello”);
M(int i);
M(5);
Given these overloads, we can see the working of the rules above. M(string,int) is not applicable because 5 doesn’t convert to string. M(int,string) is applicable because its second parameter is optional, and so, obviously are M(object) and M(int).
M(int,string) and M(int) are both better than M(object) because the conversion from 5 to int is better than the conversion from 5 to object.
Finally M(int) is better than M(int,string) because no optional arguments are omitted.
Thus the method that gets called is M(int).
Posted in: programming | Tags: c# .net 4.0 c# 4.0 named and optional arguments optional parameters resolutionFeatures for COM interop in C# 4.0
Dynamic lookup as well as named and optional parameters greatly improve the experience of interoperating with COM APIs such as the Office Automation APIs. In order to remove even more of the speed bumps, a couple of small COM-specific features are also added to C# 4.0.
Dynamic import
Many COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object from context, but explicitly has to perform a cast on the returned value to make use of that knowledge. These casts are so common that they constitute a major nuisance.
In order to facilitate a smoother experience, you can now choose to import these COM APIs in such a way that variants are instead represented using the type dynamic. In other words, from your point of view, COM signatures now have occurrences of dynamic instead of object in them.
This means that you can easily access members directly off a returned object, or you can assign it to a strongly typed local variable without having to cast. To illustrate, you can now say
excel.Cells[1, 1].Value = "Hello";
instead of
((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello";
and
Excel.Range range = excel.Cells[1, 1];
instead of
Excel.Range range = (Excel.Range)excel.Cells[1, 1];
Compiling without PIAs
Primary Interop Assemblies are large .NET assemblies generated from COM interfaces to facilitate strongly typed interoperability. They provide great support at design time, where your experience of the interop is as good as if the types where really defined in .NET. However, at runtime these large assemblies can easily bloat your program, and also cause versioning issues because they are distributed independently of your application.
The no-PIA feature allows you to continue to use PIAs at design time without having them around at runtime. Instead, the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded.
Omitting ref
Because of a different programming model, many COM APIs contain a lot of reference parameters. Contrary to refs in C#, these are typically not meant to mutate a passed-in argument for the subsequent benefit of the caller, but are simply another way of passing value parameters.
It therefore seems unreasonable that a C# programmer should have to create temporary variables for all such ref parameters and pass these by reference. Instead, specifically for COM methods, the C# compiler will allow you to pass arguments by value to such a method, and will automatically generate temporary variables to hold the passed-in values, subsequently discarding these when the call returns. In this way the caller sees value semantics, and will not experience any side effects, but the called method still gets a reference.
Open issues
A few COM interface features still are not surfaced in C#. Most notably these include indexed properties and default properties. As mentioned above these will be respected if you access COM dynamically, but statically typed C# code will still not recognize them.
There are currently no plans to address these remaining speed bumps in C# 4.0.
Posted in: programming | Tags: c# .net 4.0 dynamic c# 4.0 dynamic import interop open issues omitting refCOM Example in C# 4.0
Here is a larger Office automation example that shows many of the new C# features in action.
using System;
using System.Diagnostics;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main(string[] args) {
var excel = new Excel.Application();
excel.Visible = true;
excel.Workbooks.Add(); // optional arguments omitted
excel.Cells[1, 1].Value = "Process Name"; // no casts; Value dynamically
excel.Cells[1, 2].Value = "Memory Usage"; // accessed
var processes = Process.GetProcesses()
.OrderByDescending(p => p.WorkingSet)
.Take(10);
int i = 2;
foreach (var p in processes) {
excel.Cells[i, 1].Value = p.ProcessName; // no casts
excel.Cells[i, 2].Value = p.WorkingSet; // no casts
i++;
}
Excel.Range range = excel.Cells[1, 1]; // no casts
Excel.Chart chart = excel.ActiveWorkbook.Charts.
Add(After: excel.ActiveSheet); // named and optional arguments
chart.ChartWizard(
Source: range.CurrentRegion,
Title: "Memory Usage in " + Environment.MachineName); //named+optional
chart.ChartStyle = 45;
chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
Excel.XlCopyPictureFormat.xlBitmap,
Excel.XlPictureAppearance.xlScreen);
var word = new Word.Application();
word.Visible = true;
word.Documents.Add(); // optional arguments
word.Selection.Paste();
}
}
The code is much more terse and readable than the C# 3.0 counterpart.
Note especially how the Value property is accessed dynamically. This is actually an indexed property, i.e. a property that takes an argument; something which C# does not understand. However the argument is optional. Since the access is dynamic, it goes through the runtime COM binder which knows to substitute the default value and call the indexed property. Thus, dynamic COM allows you to avoid accesses to the puzzling Value2 property of Excel ranges.
Posted in: programming | Tags: c# linq c# 4.0 microsoft.office.interop.excel microsoft.office.interop.word getprocesses processxlcopypictureformat xlbitmap xlscreen excel.xlpictureappearance.xlscreenLogging with Spring in .NET
Introduction
To avoid introducing a dependency on a particular logging framework Spring uses it's own logging abstraction: the "Common.Logging" library. This library is based on work done by the developers of IBatis.NET and it's usage is inspired by log4net. It provides an easy mechanism to plug in any logging framework using FactoryAdapters.
Configuring Logging
Declarative Configuration
Logging configuration can be done declaratively in your app.config:
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Simple.TraceLoggerFactoryAdapter, Common.Logging">
<arg key="showDateTime" value="true" />
</factoryAdapter>
</logging>
</common>
</configuration>
The concrete set of <arg> elements you may specify depend on the FactoryAdapter being used.
Configuring Logging in your code
You may manually configure logging by setting a LoggerFactoryAdapter in your code:
// create properties
NameValueCollection properties = new NameValueCollection();
properties["showDateTime"] = "true";
// set Adapter
Common.Logging.LogManager.Adapter =
new Common.Logging.Simple.TraceLoggerFactoryAdapter(properties);
The concrete set of properties you may specify depend on the FactoryAdapter being used.
Using Common.Logging API in your own code
Usage of the Logging API is fairly simple. You need to obtain a logger from the LogManager and call the appropriate logging method:
using Common.Logging;
...
ILog log = LogManager.GetLogger(this.GetType());
log.Debug("hello world");
It is also possible to obtain a logger by name:
ILog log = LogManager.GetLogger("mylogger");
The methods available for logging are:
- Debug()
- Info()
- Warn()
- Error()
- Fatal()
All methods are overloaded to support logging exceptions as well.
Since ILog interface mimics the look&feel of log4net, migration is just a matter of changing the "using" statement.
Posted in: programming asp.net | Tags: .net c# asp.net configuration logging spring configuring logging configsections sectiongroup configurationsectionhandler factoryadapter