Your best source of information and news about Vista hardware, windows and Vista hardware on the internet

Vista ARTICLES TOP 50 Spyware Virus Vista SOFT Vista HELP

.Net

You are currently browsing the articles from MS Windows Vista Compatible Software matching the category .Net.

New Windows API Code Pack Version

I am glad to announce that today we shipped a new version of the Windows API Code Pack – version 1.0.1. This is not a major version with a lot of new features, but rather a minor version focused on fixing bugs, improving performance, adding demos and few features updates (new wrappers…)

But before we dive into this new version of the Windows Code Pack let’s better understand what this Windows API Code Pack is all about.

Windows 7 offers new features like the taskbar, libraries, and the Sensor and Location platform, to name a few. These features enable new scenarios and create new opportunities for developers to make their applications shine on Windows 7. All these great features are exposed via the Win32 native API. Currently there is no “Windows 7” namespace in the .NET Framework, and no easy way to use these features from managed code applications. To help managed code developers access them, we released version 1.0 of the Windows API Code Pack for the .NET Framework in August (just after Windows 7 RTM).

The Windows API Code Pack is a free, managed Source Code Library provided by Microsoft as is. You should consider this library as if you wrote it yourself, as if it is your own code. It is a great starting point and provides a really good and solid solution for managed code developers. It covers a lot of the new Windows 7 features as well as some more fundamental core features from the Windows Vista timeframe. You may think of the Windows API Code Pack as the closest thing to an “official” managed API for Windows. But you need to remember that it’s not a product with 24x7 technical support available from Microsoft Customer Service and Support. We believe it is a great solution, and that the codebase is very solid and high quality.

Our goal with the code pack is to enable managed code developers to take advantage of Windows APIs that are not part of the .NET Framework. We feel that as a shared source that is separate from the .NET runtime libraries, the Windows API Code Pack provides an optimal compromise between the Microsoft Win32 managed wrapper, short time-to-market -we released the Windows API Code Pack just a month after the Win7 RTM, and we ship full source code of the library.

The Windows API Code Pack includes a great deal of managed API for Windows (7). For example:

  • Extensive integration with the Windows Shell namespace, with support for the Windows Shell property system, providing control like explorer browser and access to Windows Libraries
  • A completely 100% feature parity with the native Taskbar API including (but not limited to) JumpLists, Icon Overlay, Progress bar, Thumbnail, custom switcher, Thumbnail Button, etc…
  • Windows Task Dialogs , other controls
  • Support for Direct3D 11.0 and DXGI 1.0/1.1 APIs
  • Support for the Sensor Platform APIs
  • Extended Linguistic Services APIs
  • Windows Restart Manager
  • Power APIs
  • And many other features

Each technology represented in the Windows API Code Pack has multiple demos and examples (including source) in C# and VB. We are planning on releasing updates to the Windows API Code Pack roughly every three months. We will be investing mainly in stability (meaning fixing bugs), fundamentals, testing and documentation, as well as new feature support (based on customer feedback).

You may ask yourself, “Why isn't the Windows API Code Pack part of the .NET Framework?

We ship open source code that we might bring into the runtime sometime in the future, if we feel it's sufficiently core to the entire framework to be worth the size increase. Remember the .NET Framework runs on both Windows Vista and Windows XP. However, Windows 7 is here now, and we want to enable you to access this set of free, open source library sooner rather than later. We’re shipping this library in a community-supported form and, as you can see, we intend to keep updating it. While this version (1.0.1) is a minor release, we are planning on another release in the next few months. In the meantime, you get the best of both worlds in a package that you can use as a whole or in parts without restriction.

Another question you may ask is, “Will .NET 4 replace the need to use the Windows API Code pack?”

When .NET 4 ships, you will be able to use its Windows 7 features such as Taskbar and multitouch integration with WPF, DirectWrite support, and the location API via the Devices namespace. Continue to access other features such as libraries, Restart Manager, and Sensors via the Windows API Code Pack.

Last but not least, we are looking for feedback from the community – that is you the .NET developer using this library to write managed code applications for Windows 7. On the Windows API Code Pack site, you can ask questions, provide feedback, report bugs, and follow open bugs. Your input is critical for the continuation of this library, so please send us your feedback and questions.

To learn more about how to use the Windows API Code Pack check the Windows 7 Training on Channel 9

Written by Yochay Kiriaty on November 18th, 2009 with no comments.
Read more articles on Sample Code and Sensor and Location and Windows API Code Pack and Libraries and otherSoftware and Microsoft and .Net and taskbar and Windows.

Programming Windows 7 Using Visual Studio 2010

A few weeks ago, just two days before Windows 7 become generally available, Visual Studio 2010 hit its own major milestone with the release its second Community Technical Preview of Visual Studio, known as Visual Studio 2010 Beta 2. To me, it is always exciting to see how the different tools and frameworks evolve and add new features.  It seems that with every release the products get bigger and better, offering an even



VSLogo

greater number of programming  languages, and addressing an ever growing number of areas of development such as Web, client, mobile, parallel, consoles, and devices.

Despite being a “beta” product, it is much easier to work with Visual Studio 2010 than with VS 2008. It is much easier to control your solutions and, even more importantly, much easier to write and document code. The user interface is much improved; it uses the Windows Presentation Foundation (WPF) to reduce clutter and visual complexity, and modernizes the interface by removing outdated 3D bevels. Using WPF enables us to help developers focus on content areas by opening up negative space between windows and drawing attention to the current focus with a dominant accent color and a distinctive background. There are also some cool, small, and simple perks like the ability to control the size of text. You can also drag a single window from the main Visual studio application to a second monitor (just like that) and with that you have multi-monitor support via the VS client application.

Improvements to the IntelliSense allow it finally to work well for C++ projects. And let’s not forget the new debugger window that supports parallel computing debugging and lets you view your parallel stacks.

There is even a new language, F# (F stands for Functional programming), and numerous upgrades to C#, like support for dynamic keywords. Dynamic objects' operations are resolved at runtime (check out a good post about this by Scott Hanselman). There is also support for the next version of the C++ language specification, C++X0, like Lambda Expressions. Speaking of C++, we've built the C++ solutions using MSBuild, which should make everyone happy.

As always, backward compatibility is super critical, and it is important to mention that Visual Studio 2010 supports multi-targeting. Visual Studio 2010 can target .NET 2.0 through .NET 4.0 on a per-project basis, which means you can work with your older project on the new VS 2010 and enjoy all the goodies mentioned above (and many more).

But I want to focus this post on using Visual Studio 2010 to program Windows 7. There are quite few technologies and features in Visual Studio 2010 to help you write better applications targeting the specific features of Windows 7. Below are just a few of the Visual Studio 2010 features that we’ll write more about really soon.

.NET 4 and Windows 7

Visual Studio 2010 brings a complete new CLR version – version 4. This is not just an incremental upgrade on top of CLR 2 (.NET Framework 2). This enables new language enhancements like the dynamic keyword. And the new WPF brings support in a few other areas like shell and Taskbar integration, and multitouch.

WPF & Taskbar Integration

As you know, you program jump lists using the JumpList class. This exposes several methods and properties that manipulate the exposed jump lists for the application. It also has an attached property that you can apply to your application class to create, modify, and remove jump list items. If you work with specific files, you can use the JumpList.AddToRecentCategory method to add that file to the recently used file list managed by the shell.

There are two types of jump lists – tasks and items; you work with each using a JumpTask, or a JumpPath respectively. You can work with these in XAML, code-behind, or a combination of the two. The following code snippet shows a simple integration of tasks into a jump list.

<JumpList.JumpList>
   <JumpList>
      <JumpTask ApplicationPath="notepad.exe" 
                         CustomCategory="External Tools" 
                Description="Take Notes" 
                Title="Start Notepad" 
                IconResourcePath="notepad.exe" 
                IconResourceIndex="0" />

      <JumpTask ApplicationPath="calc.exe"
                         CustomCategory="External Tools" 
                         Description="Perform some calculations" 
                        Title="Start Calculator"
                        IconResourcePath="calc.exe" 
                        IconResourceIndex="0" />
    </JumpList>
</JumpList.JumpList>

In a similar way, you can use XAML to add Thumbnail Toolbar buttons as shown by the following code snippet.

<TaskbarItemInfo.ThumbButtonInfos>
   <ThumbButtonInfo DismissWhenClicked="True" 
                    ImageSource="images/booktrip.png"
                    Command="{Binding BookItinerary}"
                    Description="Book the itinerary now" />
</TaskbarItemInfo.ThumbButtonInfos>

WPF Common File Dialog Supports Libraries (Finally!)

For some strange reason, WPF 3 and 3.5 Common File Dialog (CFD) didn’t support the updated version of the CFD introduced with Windows Vista. The CFD was upgraded in Windows 7 to support libraries and provide a better user experience. It now allows seamless search integration as well as some advanced user functionality. With WPF 4, applications enjoy the power of the “new” CFD directly from WPF, and don’t need to import CFD from the WinForm namespace (which was the only way to show the updated CFD from WPF 3 and WPF 3.5).

WPF Supports Multitouch

WPF 4.0 introduces multitouch support directly into the WPF API– with no need to interop to a native service. These new features are only available on Windows 7 and are automatically deprecated when running under older operating systems, so you don’t have to detect the operating system yourself. WPF 4.0 adds a new manipulation API to the UIElement base class. This new support allows developers to track multiple touches and generate both cumulative and individual manipulations across the touches. Basically, this enables you to transform your object on the X and Y coordinates, rotation, and scale.

WPF will supply these manipulation events if the IsManipulationEnabled property on the element is set to true. It defaults to false, so you will need to turn on this property for each element where you want to manage manipulations. This is as simple as adding IsManipulationEnabled=true to your XAML as shown in the following code snippet.

<Border Margin="10,5" 
    BorderBrush="DarkGoldenrod" 
    BorderThickness="2" 
        CornerRadius="10" 
    MinHeight="75" 
    IsManipulationEnabled="true">

Optionally, you can also hook the ManipulationStarting and ManipulationCompleted events to provide code behind the implementation of these events.

WPF 4 also supports low-level touch messages, or raw touch input. You can interact with the raw touch events on any UIElement using TouchDown, TouchMove, and TouchUp events, all of which have preview event versions. This can be useful if you are trying to track multiple touches that are not manipulating the same object, or if you want to provide different behavior for touches and the mouse. We’ll soon write more about Windows 7 multitouch in general and WPF specifically.

MFC Updates

In Visual Studio 2010, C++ and MFC received a healthy dosage of “coolness” factor, adding useful features such as IntelliSense enhancements and C++0x features. The MFC Library received a major upgrade, especially in regard to the Taskbar, Multitouch, and Restart and Recovery:

Taskbar

The MFC Taskbar provides all the functionality that the native taskbar COM API provides. There is nothing that the one can do that the other cannot. The MFC simply wraps the Win32 APIs (as it always does) into a more “MFC-like” API that corresponds to the MFC Framework programming style guidelines. For example, the following code snippet sets the overlay icon.

CMainFrame* mainFrm = 
dynamic_cast<CMainFrame*>(AfxGetApp()->GetMainWnd());
if (mainFrm)
    mainFrm->SetTaskbarOverlayIcon(IDI_ICON_INFO,L"Info");

First you need to obtain a handle (a pointer) to the application's main window (the top-level window), which corresponds to Win32 HWND. Then, simply call the SetTaskbarOverlayIcon passing HICON and a string that provides an alt text version of the information conveyed by the overlay to meet accessibility requirements. Simple, right?

In MFC, the CFrameWnd class provides the functionality of a Windows single document interface (SDI), overlapped, or pop-up frame window. With the new MFC, this class was updated and now supports Taskbar functionality such as icon overlay, progress bar, jump lists, and thumbnails.

In MFC, Taskbar thumbnail preview support is built in, so the Taskbar thumbnails will show any rendering within the views. Therefore, other than implementing your own View drawing, you need not provide any explicit code to update those Thumbnails.

To enable Taskbar Thumbnails in an MFC application while using the MFC application wizard, all the user needs to do is select the “Multiple documents” application type with the option “Tabbed documents” enabled. When the application runs, MFC will take a snapshot of each view and send it to the Taskbar APIs to display as thumbnails.

image

And the output could like this:

image

Multitouch

In Visual Studio 2010, MFC also supports multitouch. By default, on a touch-enabled device (such as touch screen), Windows 7 sends gesture touch messages to any application; that is, by default Windows 7 sends WM_GESTURE messages to the target windows. All that MFC is doing is mapping these messages to its own message handlers. MFC provides a number of message handler overrides that can receive each of the gesture types, and each returns a Boolean value. If a gesture input is processed by the application, the corresponding override should return TRUE; otherwise, it returns FALSE. Therefore if you wish to handle the zoom gestures, all you need to do is implement the relevant handler. Here is the list of supported handlers.

// Gesture handlers
virtual BOOL OnGestureZoom(CPoint ptCenter, long lDelta);
virtual BOOL OnGesturePan(CPoint ptFrom, CPoint ptTo);
virtual BOOL OnGestureRotate(CPoint ptCenter, double dblAngle);
virtual BOOL OnGesturePressAndTap(CPoint ptFirstFinger, long lDelta);
virtual BOOL OnGestureTwoFingerTap(CPoint ptCenter);

 

Similarly, you can register to receive raw touch messages and the default gesture messages. In Windows 7, gestures messages and raw touch are mutually exclusive. If you register to receive the raw touch messages for a particular window, that window will stop receiving gestures messages. If you opt-in to handle raw touch messages, you need to implement the following handler:

virtual BOOL OnTouchInput(
                        CPoint pt, 
                        int nInputNumber, 
                        int nInputsCount, 
                        PTOUCHINPUT pInput);

MFC makes your life easier by providing a lot of the information per each touch point, for example, the client coordinates for the actual point where the touch-enabled device has been touched. MFC also provides the ID of the touch point, that is, the first, second, or third finger, as well as the total count of current touches.

Restart and Recovery (Restart Manager)

In Visual Studio 2010, MFC also provides native support of the Restart Manager. Restart Manager is a feature introduced by the Microsoft Windows Vista operating system. It can help applications maintain their data when an update needs to shutdown the application or when an unexpected software error or crash occurs. Instead of shutting down abnormally, Restart Manager enables an application to perform an application save before it is terminated. Furthermore, it can re-invoke the application, enabling it to restore its state from before the shutdown or crash.

For new MFC applications, you can get the application restart and recovery feature for free by using the MFC Application Wizard as you can see from the following image:

clip_image001

All configurable parts of the restart manager API are exposed to the user through virtual members that can be over-ridden. Needless to say, you can expect some more blogging about this feature.

.NET 4 and Location

.NET 4 has a new Device namespace that supports the Windows 7 Location API (part of the Windows 7 Sensor and Location. The System.Device.Location namespace allows application developers to access the user's location easily using a single API. Location information may come from multiple providers, such as GPS, Wi-Fi triangulation, and cell phone tower triangulation. The System.Device.Location classes provide a single API to encapsulate the multiple location providers on a computer and support seamless prioritization and transitioning between them. An application developer using this API does not need to know which location-sensing technologies are available on a particular computer and is freed from the burden of tailoring an application to a specific hardware configuration.

To begin accessing location, you need to create a GeoLocationProvider. This object is the main “location manager” object through which you can register for LocationChange notifications and synchronously read the latest location information. Next you need to call Start to start the acquisition of data from the current location provider. You can check the Status property to determine if data is available. If data is available, you can get the location once from the Location property, or receive continuous location updates using the LocationChanged event. The following code snippet is a VERY simple code sample showing how to retrieve the current GeoCoordinates (latitude, longitude).

GeoLocationProvider provider = new GeoLocationProvider();
provider.Start();
GeoCoordinate coordinate = provider.Location.Coordinate;
if (coordinate != GeoCoordinate.Unknown)
{
  //Business logic here
}

Unfortunately, .NET 4 supports only the Location API and not the full Sensor and Location Platform – meaning that the .NET location implementation is still missing the Sensor piece. Use the Windows API Code Pack to access sensor from managed code.

Parallel Computing and Windows 7 Multi-Core

Parallel programming in Visual Studio 2010 has many aspects, for example, Parallel LINQ and other .NET enhancements for supporting parallel computing, including statements like Parallel.For that use System.Threading.Tasks.Task. C++ developers will be happy to learn that the Task concepts also exist in C++ Version 10, which ships with VS 2010. For native code, Concurrency Runtime (ConcRT) has implicit knowledge of Win7 processor groups and will schedule work on up to 256 cores; ConcRT also takes advantage of User Mode Scheduling of threads. Therefore, any workload that sits on top of ConcRT immediately benefits. In other words, because both the Parellel Pattern Library (PPL) and Asynchronous Agents are included in Visual C++ 10 CRT and are built on top of ConcRT, any workloads you build on them will scale to 256 cores--

just like that! (Well, you will still need to write the code, but the scaling is free.)

For managed code applications, the story is less bright. Management of the managed stack thread sits on top of the .NET ThreadPool (System.Threading.ThreadPool) by default. This does not use the new processor group APIs in Windows 7, and therefore doesn’t automatically benefit from the Windows 7 ability to scale. The maximum number of processes that the threadpool can utilize is 64. But not everything is lost, it is possible to write a custom TaskScheduler that targeted more than 64 procs, and use the rest of the Task Parallel Library with that special scheduler. This would be a cool CodePlex project, right?

Overall Visual Studio 2010 includes tons of new technologies and improvements--all of it icing on the Windows 7 cake!

Written by Yochay Kiriaty on November 17th, 2009 with no comments.
Read more articles on otherSoftware and Multi-Touch and Sensor and Location and Visual Studio 2010 and windows 7 and taskbar and Microsoft and .Net and Developers and Windows.

Windows7 Trigger Start Services – Part 2: Building a Trigger Start Optimized Service

In the last post Windows 7 Trigger Start Services – Part 1: Introduction, we introduced Windows7 Trigger Services as a great way to optimize your services to have better performance and improved security. In this post you will learn how to convert a standard automatic-start service to a trigger-start service that starts up only when a certain event occurs in the system. We’ll use a WPF application (obviously managed code) that registers and monitors a service (also implemented using .NET). To bridge between the .NET world and the native Win32 APIs that we saw in the previous post, we use a C++/CLI interoperability layer.

This sample application has 3 parts:

  • A C++/CLI interoperability layer that provides a regular and easy .NET API to the controller application
  • A WPF controller application that lets you register and run the service
  • A simple .NET service that looks for a USB storage device (disk on key) and on it, a specific folder named “ToCopy” from which to copy files to your local “C:\FromUSB” folder

The following image illustrates the solution structure.

image

Let’s start by reviewing the .NET Service code implementation. This is a simple Windows service written in C#. The purpose of this service is to copy pictures automatically to your local hard-drive- “c:\FromUSB” from the USB storage device that is plugged into your computer.

The service implementation can be found at USBService.cs. This class inherits the ServiceBase base class and overrides the OnStart and OnStop methods. This class has a DoWork method that actually does all the copying of images from the USB disk to your local drive. The DoWork method writes to a log file that we will be monitoring.

The real interesting part of the service implementation is the OnStart method. This method is called once the service is started. Notice that the first line of code checks whether the service is configured as a trigger start service. If the “if” statement returns false, we create a new instance of a timer and have it poll every 5 seconds. Before Windows7, this was the only way to implement such a service, that is, by regularly polling the system to check for a USB device. Therefore, the service needs to run 24x7 to poll the system. This is highly wasteful of resources and keeps the system from transitioning to a low-power state, increases the application attack surface, among other negative things.

But, with Windows7, you can configure such a service with a USB device arrival trigger. This means that the service will not run until a USB device arrives, specifically a USB generic disk device. We’ll get to that part of the solution in a second, but for now, if you look at the OnStart method, you will notice that we check whether the service is configured as a trigger start service; if it is, we simply call the DoWork method on another thread, as shown by the following code snippet. This should work just fine because the service is NOT running, and will start to run only when the trigger happens. And then it will not default to the timer, but rather use the thread pool to queue the work.

 protected override void OnStart(string[] args)
 {
   if (ServiceControl.IsServiceTriggerStart(ServiceName))
   {
      ThreadPool.QueueUserWorkItem(_ => DoWork());
   }
   else
   {
     _timer = new Timer(_ => DoWork());
     _timer.Change(0, 5000);
   }
 }

The ServiceControl namespace contains the C++/CLI interop layer. This layer uses C++/CLI as the binding element between the native API and the WPF application. The main ServiceControlInterop.cpp file contains all the functionality that we need and that is used by the WPF application. For example using the controller application we can use AddService(…) or RemoveService(…) to add or remove a service respectively. We can also configure the service as a trigger start service for either a USB device arrival or first available IP address by using SetServiceTriggerStartOnUSBArrival or SetServiceTriggerStartOnIPAddressArrival respectively. Reviewing both function implementations reveals that basically both are following identical paths. They:

  • First, use OpenSCManager to get a handle to the Service Control Manager (SCM)
  • Then use the SCM handle OpenService, to get an actual service handle that we wish to configure
  • Finally call ChangeServiceConfig2 to set the specific trigger

All this was explained in detail in the last post (Windows7 Trigger Start Services – Part 1: Introduction

You can download the code sample for this application. Note that you will have to run Visual Studio as administrator (see image below) because you will need to register, start, and stop services. . You will also need to Windows 7 SDK to compile the C++ part of the solution.

image

When compiling and running the default solution (the WPF application) you will see the following image.

image

This is the main WPF controller application. From here, you can create the service by clicking the Create Manual button.

Next, open the Services Window by typing “Services” in the Start Menu search box. You should see the Service window. Locate the USBCopyService; it should appear as in the following image.

image

Click the Run button and then the Refresh button in the Services window, or just press F5. You will not notice a great deal of change, but the USBCopyService changed from Manual to Started, as shown in the following image.

image

 

A second look at the actual application reveals the service activity in the log file. As you can see in the following image, the services awaken every 5 seconds and poll the system, looking for USB devices:

image

Click the Stop button to stop the service and then click the Delete Service to delete it. Now click the Trigger Start button to register and configure the service as a trigger start service that is triggered once a USB Generic disk arrives. If you check the Service window, you will see the USBCopyService listed as “manual” where in reality it is configured as triggered start service (there is just no graphical representation of that).

If you plug in a USB disk with a “ToCopy” folder the service will kick into action and copy the files to c:\FromUSB. Not the best implementation, but hey, it is only a demo. The following image shows a single line in the log file because the service actually ran only once; it executed the DoWork method and then quit. It didn’t run and poll the system every 5 seconds and didn’t waste resources or become a security liability.

image

To conclude

Developing a service with Windows 7 trigger start service in mind might be a little more difficult than a regular “auto-run” service that just runs in idle from boot to shutdown. But in practice, all it takes is only a few lines of code, no more. And these few lines of code can have a very big affect in terms of resource consumption and security. So the next time you build a new Windows Service, try to incorporate triggers.

You can learn about Windows 7 using the Windows 7 Training Kit for Developers or by viewing Windows 7 videos on Channel 9.

You can also get hands-on experience for Windows 7 Trigger Start Services using the Windows 7 Online training that is part of the Channel 9 Learning Center

Written by Yochay Kiriaty on October 27th, 2009 with no comments.
Read more articles on Windows 7 Training Kit and Trigger Start Services and Windows 7 Trigger Start Services and otherSoftware and windows 7 and .Net and Performance and Microsoft.

Windows7 Trigger Start Services – Part 1: Introduction

We introduced Service 0 Isolation a few weeks ago as an application compatibility topic. It is only natural that we continue our conversation about services in the context of Windows 7. But this time, we will talk about some of the benefits to service optimization that are available in Windows 7. This post focuses on a new feature in Windows 7 called Trigger Start Services. But before we jump into the API, let’s provide some background about services.

What Are Services?

A service is an integral mechanism built into Microsoft Windows operating systems. You can think of services as “special applications” that run with no regard to the current user context. Services are different from “regular” user applications because you can configure a service to run from the time a system starts up (boots) until it shuts down, without requiring an active user to be present – that is, services can run even though no users are logged on.

We like to think about services as running tasks for us in the background without interfering with user operations. Services on Windows are responsible for all kinds of background activity that do not involve the user, ranging from the Remote Procedure Call (RPC) service, through Printer Spoolers, to the Network Location Awareness service.

Over the years, Windows has grown and with it the number background services. But to be honest, background services in Windows are a pain – the operating system ships with a lot of them in the box. On top of that, ISVs and their applications add even more services, like software updates to name only one. With that said, some of these services are critical and are required during boot sequences, some are required later when a specific user logs on, while others don’t need to execute until they are called upon. Nonetheless, when you look at the currently running services, you see a lot of services that really don’t need to run 24x7.

What’s Wrong with Services Running 24x7?

There are several issues with having services run 24x7:

First, why have something run (even in the background) when there is no need for it to run? Any running process (services included) uses valuable memory and CPU resources that could be used by other applications and services. If you total up all the services that are running at any given time, they add up to quite a lot of memory, handles, threads, and plenty of CPU usage. All of these “wasted” resources reduce the overall computer performance, decrease its responsiveness, and make users think their computers are sluggish and slow. Also, since most of the running services are configured as Auto-Start (start running upon system log-on), these services have an impact on the computer's boot time.

Second, these wasted resources, have a direct impact on power consumption. The more demands we place on the CPU, the more power our computer uses. This can be critical for laptops, and could reduce battery life from four hours to three hours.

Third, having non-productive software run all the time may lead to memory leaks and overall system instability. This can lead to application crashes and ultimately computer crashes.

Last, but not least, if a service is running 24x7, and this services is well known (any popular application might have one – like the PDF Reader), it provides a larger attack surface. A hacker might use the knowledge that a certain popular application installs a service that runs 24x7, and try to hack into that service to gain privileged access to the computer.

Given all of the above, it makes you wonder why so many developers configure their services to run all the time when there are other options. Even before Windows 7, there were several service start-up options:

  • Disabled completely disables the service and prevents it and its dependencies from running—this means that the user must start the service manually from the Control Panel or the command line
  • Manual starts a service as required (defined by dependencies to other services) or when called from an application using the relevant API as shown later in this post
  • Automatic starts the services at system logon
  • Automatic Delayed is a newer startup type introduced in Windows Vista that starts the service after the system has finished booting and after initial demanding operations have completed, so that the system boots up faster

Unfortunately, many ISVs (Microsoft included) still choose to configure their services to Automatic (or Automatic Delayed) because it is the easy solution for everyone. A service simply runs 24x7 and is always available, eliminating the need to check any dependencies or verify that the service is running.

There are many examples of existing services that can become more resource friendly and more secure by not running 24x7. For example, think of an update service that checks for new application updates. If the computer is not connected to a network and has no IP available, why should the update service run? It can't reach anywhere, so why run a program that does nothing? Think about a policy management service that is invoked when a group policy changes or when the computer joins or leaves a domain, but right now the computer is connected to my home network and again the service works in vain.

Introducing Windows 7 Trigger Start Services

The solution for the above problems is to move the service out of its “forever running state” into other types of background activity, such as scheduled tasks or trigger-start services. This post focuses on Windows 7 Trigger Start Services. Windows 7 Scheduled Tasks include a lot of valuable information that we will describe in another post.

Trigger-start services are new to Windows7. A trigger-start service is a regular service that you can configure to run (or stop running) only when it is triggered, that is, only when certain criteria and conditions that you define are met (for example, when the first network IP address becomes available, or when the last network IP is lost). Here is a list of the available triggers that you can use to configure the Start-Up mode of a given service:

  • Device interface arrival or departure
  • Joining or leaving a domain
  • Opening or closing a firewall port
  • Group policy change
  • First IP address available/ last IP address leaving
  • Custom event – Event Tracing for Windows (ETW)

The last item in the list represents the extendibility point. As a developer, you can configure any ETW event as a trigger for services, which gives you a very good tool to fine-tune your control over starting and stopping services from your application.

So what exactly is a trigger?

A trigger consists of:

  • A trigger event type
  • A trigger event subtype
  • The action to be taken in response to the trigger event
  • One or more trigger-specific data items (for certain trigger event types)

The subtype and the trigger-specific data items together specify the conditions for notifying the service of the event. The format of a data item depends on the trigger event type; a data item can be made up of binary data, a string, or a multistring.

Working with Trigger Start Services

Unfortunately, Windows 7 Services MMC UI does not include a graphical representation of the trigger start services. However, you have two options. You can still use the old and good sc.exe (Service Configuration command line tool), or you can use the WIN32 ChangeServiceConfig2 method to configure the service start option programmatically as demonstrated in this post.

Using SC.exe to Query Service Trigger Information

It's time to start have some fun. First, let’s start with just extracting some configuration information from a few services. The generic form for using the service configuration is:

sc <server> [command] [service name] <option1> <option2>...
Where server is optional and by default you work with the local computer:
  • command is the operation you wish to perform like querying trigger information
  • service name is the name of the service you wish to work with
  • options are the different values (options) you can pass to configure the service

Let’s start by querying a specific service for its trigger start configuration. To do so you need to launch a Windows Shell window:

  1. Open the start menu.
  2. Type CMD in the search box.
  3. Choose cmd.exe.
    This will open a Windows Shell window.
  4. Type sc qtriggerinfo w32time and press enter

This is how it should look:

image

As you can see, we queried the trigger information of the W32time service, which is configured to start when the computer is joined to a domain and stop when the computer leaves the domain.

Microsoft updated the sc.exe command-line tool for Windows 7 to support configuring and querying a service for supported triggers. Type sc triggerinfo in the Windows shell window and press enter. The result looks like the box below, and lists all the different triggers and how to configure a service to use trigger start services.

C:\>sc triggerinfo
DESCRIPTION:
        Changes the trigger parameters of a service.
USAGE:
        sc <server> triggerinfo [service name] <option1> <option2>...
OPTIONS:
 start/device/UUID/HwId1/... <Start the service on arrival of the
                             specified device interface class UUID
                             string with one or more hardware ID
                             strings and/or compatible ID strings>
 start/custom/UUID/data0/.. <Start the service on arrival of an
                             event from the specified custom ETW
                             provider UUID string with one or more
                             binary data items as hexadecimal
                             string format such as ABCDABCD to
                             set 4 byte data>
 stop/custom/UUID/data0/... <Stop the service on arrival of an
                             event from the specified custom ETW
                             provider UUID string with one or more
                             binary data items as hexadecimal
                             string format such as ABCDABCD to
                             set 4 byte data>
 start/strcustom/UUID/data0/.. <Start the service on arrival of an
                             event from the specified custom ETW
                             provider UUID string with one or more
                             optional string data items>
 stop/strcustom/UUID/data0/.. <Stop the service on arrival of an
                             event from the specified custom ETW
                             provider UUID string with one or more
                             optional string data items>
 start/networkon             <Start the service on first IP address>
 stop/networkoff             <Stop the service on zero IP addresses>
 start/domainjoin            <Start the service on domain join>
 stop/domainleave            <Stop the service on domain leave>
 delete                      <Delete the existing trigger parameters>

For example, to configure a service to start when the first IP address becomes available, all you need to do is type sc triggerinfo [your service name] start/networkon, where “your service name” is replaced with the name of the service that you wish to configure.

Configuring Trigger Start Services Programmatically Using ChanceServiceConfig2

The more interesting aspect, from a developer's point of view, is writing services that are trigger aware and using code to configure a service. In Windows 7, you can use the ChangeServiceConfig2 function to configure service trigger information and the QueryServiceConfig2 function to query it.

Service trigger registration is performed by calling ChangeServiceConfig2, passing SERVICE_CONFIG_TRIGGER_INFO for the dwInfoLevel parameter, and providing the trigger registration information in a SERVICE_TRIGGER_INFO structure through the lpInfo parameter. In addition, one or more trigger-specific data items can be specified. The following is an example of a service installer function that creates a USB device trigger for a service that is named MyService:

define SERVICE_NAME L"MyService"
//set the device guid
static const GUID GUID_USBDevice = {
0x53f56307, 0xb6bf, 0x11d0,
{0x94, 0xf2, 0x00, 0xa0, 0xc9,
0x1e, 0xfb, 0x8b }};

BOOL _SetServiceToStartOnDeviceTrigger()
{
BOOL fResult = FALSE;

SC_HANDLE hScm = OpenSCManager(
NULL, //local machine
NULL, //active database
SC_MANAGER_CONNECT);

if(hScm != NULL)
{
SC_HANDLE hService = OpenService(
hScm,
SERVICE_NAME,
SERVICE_ALL_ACCESS);

If( hService != NULL)
{

LPCWSTR lpszDeviceString = L"USBSTOR\\GenDisk";
SERVICE_TRIGGER_SPECIFIC_DATA_ITEM deviceData = {0};
deviceData.dwDataType = SERVICE_TRIGGER_DATA_TYPE_STRING;
deviceData.cbData =
(wcslen(lpszDeviceString)+1) * sizeof(WCHAR);
deviceData.pData = (PBYTE)lpszDeviceString;



SERVICE_TRIGGER st;
st.dwTriggerType =
SERVICE_TRIGGER_TYPE_DEVICE_INTERFACE_ARRIVAL;
st.dwAction = SERVICE_TRIGGER_ACTION_SERVICE_START;
st.pTriggerSubtype = (GUID *) &GUID_USBDevice;
st.cDataItems = 1;
st.pDataItems = &deviceData;


SERVICE_TRIGGER_INFO sti;
sti.cTriggers = 1;
sti.pTriggers = &st;
sti.pReserved = 0;

fResult = ChangeServiceConfig2(
hService,
SERVICE_CONFIG_TRIGGER_INFO,
&sti);
}
CloseServiceHandle (hService);
}
CloseServiceHandle (hScm);

if(!fResult)
{
printf("Service trigger registration failed (%d)\n",
GetLastError());
}
return fResult;
}
Note: all services are controlled by the Service Control Manager (SCM), which we’ll touch on in a different post.

In the above code snippet, you can see that first we get a handle (hScm) to the SCM by calling openSCManager. Next, we call openService and pass the handle to the SCM- hscm,and the service name – SERVICE_NAME that we wish access. The last parameter, SERVICE_ALL_ACCESS, indicates that we have complete access to the services. Assuming we got a valid handle to the service, we now start to build the specific structure that we’ll soon use to configure the service.

SERVICE_TRIGGER_SPECIFIC_DATA_ITEM defines the trigger event type. It contains trigger-specific data for the service trigger event. In our case we define the string that represents a USB gen disk arrival.

Next we define the SERVICE_TRIGGER structure, which represents a service trigger event. Note that this is where we define the trigger type (device arrival), the action (start the service), and the trigger sub type (the specific family of the USB device). Then we define one device that will trigger the service. Note that you can define an array of devices and their GUIDs. You should also note that we don’t want the service to be triggered upon just any USB device arrival like a mouse or a camera. We want the service to start only when a USB disk arrives.

Finally, we define the SERVICE_TRIGGER_INFO structure, which contains trigger event information for a service. This structure simply points to the SERVICE_TRIGGER struct that we defined previously, and the number of triggers that, in this case, is one.

Now we can call the ChanceServiceConfig2 function and pass the handle to the service we wish to configure, a SERVICE_CONFIG_TRIGGER_INFO parameter that indicates that we wish to configure the service trigger, and a null.

That is all there is to it. If we are successful, then our service will run after we insert a USB hard drive.

In the next post, we'll review how to write a simple implementation of a .NET service that we’ll program to start upon arrival of a USB generic disk.

You can learn about Windows 7 using the Windows 7 Training Kit for Developers or by viewing Windows 7 videos on Channel 9.

You can also get hands-on experience for Windows 7 Trigger Start Services using the Windows 7 Online training that is part of the Channel 9 Learning Center

Written by Yochay Kiriaty on October 26th, 2009 with no comments.
Read more articles on Labs and Windows 7 Training Kit and Triger Start Services and Channel 9 and otherSoftware and .Net and Developers and windows 7 and Microsoft.

Windows 7 GA – Time for Some New Windows 7 Developer Resources

Windows 7 is now available to the public and anyone can buy and install Windows 7, whether for a new computer or an existing one. Soon, people from around the world will run your applications on Windows 7. They will expect the application to work and to feel as though it is a native Windows 7 application that takes advantage of new Windows 7 features and technologies like the Taskbar, libraries, touch, and sensors.

As Windows 7 approached GA, we continued to release new developer content to help you get up to speed with the new operating system. Now that it's here, Windows 7 GA is a great “excuse” for us to give you a quick update on all the Windows 7 developer content that is available to help you learn how to write a great Windows 7 application.

Below is a list of locations where you can find Windows 7 developer content.

Updated Windows 7 Training Kit – (Download it now)

image To help you get your application onto Windows 7 as soon as possible, we updated the Windows 7 Training Kit for Developers. You can still find all the previous topics such as Taskbar, Sensor and Location, Libraries and Shell, Multitouch, Ribbon, etc. New to the kit are labs that work with VS2010 and use the new MFC improvements in VS2010 (download VS2010). We also added VB to all of our managed solutions – truly, no developer is left behind.

 

Windows 7 Online Training on Channel 9 Learning Center

Let’s assume you are interested in learning about Windows 7 libraries, or how to add some cool Taskbar functionality to your application, but you don’t want to download the entire training kit. Well with the Windows 7 Online Training Kit located on the Channel 9 Learning Center, you have immediate access to all Windows 7 learning units individually. Each learning unit (like the Taskbar) includes a few hands-on-labs and related videos. This gives you quick and easy access to most of our training material. For the rest of the content, like PowerPoint presentations and additional demos, you will have to download the Windows 7 Training Kit for Developers. The following image shows part of the managed code hands-on-lab for the Taskbar.

image

As always, the Windows 7 Topic Area on Channel 9 still features specific Windows 7 videos and screencasts. Over the past few weeks, we created new videos that I am sure you will find exciting and helpful, including a new Mark Russinovich video. As a friendly reminder, the last video Mark did, “Mark Russinovich: Inside Windows 7, was a Channel 9 blockbuster. If you haven't already viewed it, I highly recommend it, and make sure you see Mark’s new video Mark Russinovich: Inside Windows 7 Redux. Don’t forget to stay up-to-date with other topics:

  • Using Windows 7 – Contains consumer- and user-related videos such as how to install Windows 7 and how to set up a home group network
  • Programming Windows 7 – I don’t really need to explain what goes here, right?
  • Last but not least, “Under the Hood” –Covers deep architectural Windows concepts

MSDN Developer Center

The MSDN Developer Center also received a “Windows 7 GA refresh” and now sports a new look and much improved functionality. The MSDN Developer Center includes a lot of Windows 7 material that extends the training content on available on Channel 9. You can think of the MSDN Developer Center as a hub for the Windows 7 content that will give you a great head start as you develop applications that will shine on Windows 7. You can find information about specific topics, review different programming models, learn about the developer tools that you can use, watch videos, and read blogs.

image

A New Book for Windows 7 Developers

Among the other things that you will find on the MSDN Developer Center, is a list of recommended Windows 7 books for developers. It turns out that over the past few months, I’ve been busy writing a Windows 7 book with three amazing co-authors: Laurence Moroney, Sasha Goldshtein, and Alon Fliess. Together, we wrote Introducing Windows 7 for Developers. It covers most of the exciting Windows 7 features like the Taskbar, Libraries, Sensor and Location, Multitouch (including new WPF 4 support with VS2010), and even Silverlight out of image

browser (including touch :). As far as I know, this is the first Windows 7 developer book, and I hope you will find it useful. Mark Russinovich found this book helpful while integrating Windows 7 features with the Sysinternals tools and he wrote the foreword for this book.

I hope this list will help get you on your way to writing amazing Windows 7 applications.

Written by Yochay Kiriaty on October 22nd, 2009 with no comments.
Read more articles on Libraries and Labs and Windows 7 Training Kit and Channel 9 and otherSoftware and Microsoft and .Net and Developers and Windows.

Windows 7 At PDC09

The Professional Developers Conference (PDC) is the one event that all developers who use any Microsoft technologies must attend at least once in their professional careers. It’s the flagship event for developers, offering the most comprehensive, future-looking, technically deep, densely-packed set of sessions from Microsoft speakers you can find anywhere. This year’s PDC is no exception and you can expect it to be a very exciting event.

My first PDC was PDC08, held last November at the LA Convention Center. As one of the people at Microsoft who work on Windows 7, I was fortunate enough to be in the loop regarding Windows 7 @ PDC08, and was able to contribute (even if only in a small way) to one of the keynote. During the Day 2 keynote,

image

Steven Sinofsky presented Windows 7 to the world and for the first time people outside of Microsoft saw the new Taskbar, the Windows Ribbon, and witnessed a live multitouch demo. Attendees received a 160G hard drive (makes you wonder what they'll get this year…) with Windows 7 build 6800 (does anyone remember this build number?). The Windows team presented a lot of its technologies in a series of impressive sessions. And since then, through the different versions of Windows--Beta, RC, and RTM--we continued to push new content to help developers ramp up and get ready for Windows 7.

Windows 7 will become “Generally Available” (GA) to the public on October 22nd, exactly two weeks from today, and this year’s PDC takes place right after Windows 7 GA. With the pre-release veil of secrecy lifted, during this year's PDC we can dive deep (very deep) into Windows 7 to extend our understanding of how Windows 7 works and, even more importantly, how developers can take advantage of all the great new improvements and features Windows 7 has to offer.

To start with, on the day before PDC09 starts, there is a FREE Windows 7 (seminar) Boot Camp led by top Microsoft Windows experts like Mark Russinovich, Landy Wang, and Arun Kishan. Then, during the PDC proper, we’ll have several deep-dive Windows 7 sessions.

So here is the first set of Windows 7 sessions that we are announcing:

This first one is probably my favorite topic (I am a geek, what can I say). What could be more important than performance, especially as it relates to Windows 7 and applications running on Windows 7? This has to be a MUST Attend session for any developer who writes any software (native or .NET) for Windows (and not just Windows 7) – this is truly a unique opportunity.

Optimizing for Performance with the Windows Performance Toolkit

The Windows team uses the Windows Performance Toolkit (WPT) to optimize the Windows OS. Come and see how the Windows Performance team used the WPT throughout the Windows 7 development cycle to optimize for customer scenarios and how you can leverage many of its features and capabilities to help you build faster applications on Windows. This session will present case studies that demonstrate how you can use the toolkit to pinpoint areas for improvement in your application and provide you with some best practices to follow in order to create applications with optimum performance.

The next two sessions are also personal favorites (you can’t blame me for loving Windows 7), as I think these technologies represent new levels of user interaction and adaptive user interfaces:

Building Sensor- and Location-aware Applications with Windows 7 and .NET

How many times have you thought to yourself, “My application would be so much better if it knew where the user was?” With Windows 7 and.NET Framework 4.0, you now have the tools at your fingertips to location-enable your applications. Based on the new Location platform for Windows 7, the location API in .NET Framework 4.0 provides a single, consistent API to get you your latitude and longitude regardless of the underlying technology that acquired it—allowing you to focus on creating exciting, differentiated location-aware applications.

Windows Touch Deep Dive

Windows provides applications with a default experience for gestures and touch interaction. This provides applications that you want to go beyond that basic experience with a powerful platform to build upon. This session is targeted at developers interested in building touch-optimized experiences. We’ll look closely at some of the more powerful portions of the Touch platform, like manipulation and inertia processors, as well as cover real-world problems that developers have encountered and overcome. Come help build the next generation of user experiences!

Another highly recommended session is the Windows Ribbon session. Before you dismiss the Ribbon, I suggest you take a second look and read between the lines of the Windows Ribbon native API. There is a lot of very interesting software architecture in the current API that provides a glimpse into tomorrow’s “commanding framework.”

Windows Ribbon Technical Deep Dive

This talk will cover some of the more subtle and complex aspects of ribbon implementation, like designing a great gallery (a critical task for any ribbon), adding an outspace MRU, etc. We will draw from specific experiences with Windows Live and other partners and spread the learning that those teams amassed as Windows Ribbon guinea pigs.

A lot has been said about the update to the Windows 7 graphics stack. This stack plays a major role in the performance improvements Windows 7 offers. You, as a developer, can tap into that user experience and start enjoying a rich and modern graphic framework that pushes GPUs to their limits.

Modern 3D Graphics Using Windows 7 & Direct3D 11 Hardware

Dig deep into the capabilities of Direct3D 11 and Windows 7to gain practical knowledge that will help you push graphics to the limit. Learn about the new tessellation stage in Direct3D 11, which enables an unprecedented level of rendering quality by dynamically generating geometry on the GPU. In addition, see how the multi-core improvements in the Direct3D 11 runtime can help you scale your application to take full advantage of all of the cores on a machine. Finally, take a peek at the power of DirectCompute (the hardware-accelerated general purpose computing technology) in a graphics application context.

Advanced Graphics Functionality Using DirectX

The number of PC configurations is exploding. With both netbooks and high-end desktop systems using the latest in graphics hardware, creating an application that can target all of these systems is getting harder every year. Join us as we explore the many options available in Windows 7 to facilitate graphics development across all kinds of hardware configurations, from low-end integrated GPUs to top of the line discrete GPUs. Learn about Direct3D 10 Level 9, which enables Direct3D 10 applications to run on pretty much every computer in the market today. Check out WARP, our new software rasterizer that lets your application use high-quality graphics even when there’s no graphics card. Finally, learn about Direct2D, DirectWrite, WIC, and the interoperability of Windows 7 technologies for making slick, high-quality graphics for your applications of the future.

The last session for today’s post, but most certainly not the least, is about the Windows API Code Pack for the Microsoft .NET framework. This is a framework that I have a personal interest in and I often blog about. With Visual Studio 2010 and .NET 4, .NET developers have an easier life. Nonetheless, there are still a great number of valuable Windows APIs that are NOT in the framework. This Open Source library provides a good intermediate solution.

Developing with the Windows API Code Pack for .NET Framework

The Windows API Code Pack for Microsoft .NET Framework provides a source code library that you can use to access some new Windows 7 features (and some existing features of older versions of the Windows operating system) from managed code. These Windows features are not available to developers today in the .NET Framework. This session will show you how to access features like taskbar integration, JumpLists, libraries, the sensor platform, Direct2D, and more.

Written by Yochay Kiriaty on October 8th, 2009 with no comments.
Read more articles on Sensor and Location and Libraries and Windows 7 Application Compatibility and Windows 7 Training Kit and PDC09 and Multi-Touch and otherSoftware and .Net and Microsoft and Developers and taskbar and windows 7 and Windows.

« Older articles

No newer articles