Sergey Zwezdin

Microsoft MVP, Visual C#
The blog has been moved

Dear readers of my blog,

currently I’ve moved my blog to weblogs.asp.net platform and actual address of my blog is http://weblogs.asp.net/SergeyZwezdin/. Please, update your links.

I’d like to communicate with each of you. Welcome to my main blog.

weblogs.asp.net/SergeyZwezdin

Thanks for your understanding.

Stay connected.

glowing-world-map-background

ADO.NET Data Services – what waits for us in the future

ADO.NET Data ServicesApproximately hardly there is more than year back we have seen a new services platform - ADO.NET Data Services. Its occurrence has marked the beginning of wide use of the REST-approach by many developers. At that time this platform was represented as the convenient tool for access to data through HTTP.

Lately it is possible to understand, that this tool is really successful - huge number of developers have started to use immediately it in the projects. The reason for it is quite logical - use of ADO.NET Data Services allows to cut down expenses on realisation of the most typical scenarios at work with services. It does not mean that SOAP-services and WCF have left in the past, however, in scenarios of the data access preference began to give to ADO.NET Data Services.

In spite of the fact that this platform had some defects at work in non-standard situations, its realisation was enough successful. Therefore among developers there could be a wrong impression that development of ADO.NET Data Services has stopped. It is wrong. Here I will tell that we should see in new versions of this product.

As is known in RTM status now is ADO.NET Data Services 1.0. Subsequently in plans there is a release of version 1.5 which will be a part of .NET 4.0 and Visual Studio 2010. At present version 1.5 is in CTP2 state.

That is interesting, the further direction of development of the project got out proceeding from comments which went from developers community. Thus, version 1.5 will be focused on closer integration with WPF/Silverlight applications, will expand possibilities on executing of server queries and will allow to use even more conveniently services at the client side.

New possibilities of ADO.NET Data Services 1.5 it is much more and we will discuss them with you in the near future. And now I wish to make the small review of that we should see in the new version.

  • One of weak places of ADO.NET Data Services at present is that in some scenarios we are compelled to load superfluous quantity of data on the client. For example, if the entity contains 40 fields at the access to a corresponding collection we are compelled to load 40 fields all these. At present for such situations it is offered to split entity into smaller and to work with them separately, and for the main query to generate representation with association. However, all it creates additional problems by working out. Other even more unpleasant problem is in case of need to receive quantity of objects in a collection we are compelled to load all collection entirely and already on the client to consider quantity of objects. In new version of ADO.NET Data Services the special attention is paid to these problems. Now we can query projections of any data, and not just entirely all entity. There was a new operator $count which will allow to receive quantity of entities in a collection.
  • As for an application programming even more often use platforms WPF and Silverlight in new version ADO.NET Data Services the special attention is paid to data binding. This mechanism is successfully enough applied in WPF/Silverlight projects and declarative binding with data became already habitual approach to working out. In the new version all entities which are generated on the client will implement INotifyPropertyChanged interface, thanks to what begins possible to carry out declarative binding with service data.
  • Also in the new version of a considered platform the attention is paid to work with binary large objects (BLOB), for example, with images. Also fields will be allocated in a special way in metadata and to be loaded on the client side only if necessary.
  • Interaction with other platforms. In spite of the fact that services ADO.NET Data Services are based on open standards, for work with these services, for example, from Java it is necessary to parse answers from service and to generate queries manually. For simplification of this problem within version 1.5 the mechanism of change of appearance of the answer is implemented (feed customization). Besides, client libraries for work with services ADO.NET Data Services, for example, PHP Toolkit for ADO.NET Data Services which we certainly also will consider already have started to appear.

Thus, the general tendencies and directions are visible to where project ADO.NET Data Services moves and that we should expect from it in the near future.

In the near future we will talk in more details about each of possibilities of ADO.NET Data Services v.1.5, and now I wish to wish you successes in construction of your distributed applications!

ADO.NET Data Services v.1.5 CTP2

Astoria team has released next CTP of ADO.NET Data Services 1.5. In comparison with previous release, CTP2 is really big work and we can observe now already that ADO.NET Data Services becomes even more powerful platform. As a whole it is visible, that development of Astoria is directed on more closer integration with Silverlight and .NET Framework 3.5 SP1.

What’s new in CTP2:

  • Projection. It is new feature for Astoria which has appeared only in this CTP. This feature allows to build more difficult projections using ADO.NET Data Services, and is accessible both server functionality, and client.
  • Data Binding. Feature of binding with the user interface in WPF and Silverlight already was in previous CTP, however in new release here has occurred small refactoring and binding began to do even easier.
  • Row count. Has changed nothing, bugs has been fixed.
  • Feed customization. The quantity of elements which can be adjusted is expanded.
  • Server driven paging. Support in client library is added.
  • Enhanced LOB Support. Support in client library is added.
  • Request Pipeline. Now it is possible to handle something in a chain of processing of request using model of events (something similar on model of events ASP.NET). It is necessary for even big possibilities of expansion of functionality of services.
  • New “Service Provider” interface. Refactoring has been executed.

It is besides, informed, that has been fixed a number of errors. Thus, release of ADO.NET Data Services v.1.5 on one CTP became nearly.

Also there was an information that all these possibilities of version 1.5 will be a part.NET Framework 4.

Source: http://blogs.msdn.com/astoriateam/archive/2009/08/31/ado-net-data-services-v1-5-ctp2-now-available-for-download.aspx

PHP Toolkit for ADO.NET Data Services – erasing bounds of technologies: PHP + .NET

Microsoft Interoperability team announced an release of the new project which is the bridge between PHP and.NET and erases bounds of technologies even more. This project allows developers on PHP even more easier to access and use all power of .NET  services which based on ADO.NET Data Services.

From the point of view of working out the scheme looks classically enough. By working out it is necessary to use utility PHPDataSvcUtil which is in PHP Toolkit for ADO.NET Data Services. This utility will generate proxies-classes on PHP using metadata which are accessible to service on the basis of ADO.NET Data Services. After that on PHP also it will be necessary to connect libraries PHP Toolkit to the project for ADO.NET Data Services. Further, after all these simple actions it will be possible to use all power of ADO.NET Data Services platform within of appendices on PHP in more convenient way.

Let's look how the code on platform PHP for executing of queries to ADO.NET Data Services will look. Firstly it is necessary to connect a file with proxies-classes, which generated by PHPDataSvcUtil utility:

<?PHP
    require_once 'NorthwindClient.php';
    define("SERVICE_URI", "http://localhost:8080/Northwind.svc");
?>

After that it is possible to create the objects of a class which implements the logic of the client and to carry out queries to remote service. Unfortunately, here we cannot take advantage of LINQ syntax for construction of queries to service. Therefore it is necessary to write query manually in the form of URI.

<?PHP
    $client = new NorthwindEntities(SERVICE_URI);
    $query = $client->ExecuteQuery("Customers?\$filter=Country eq 'UK'");
?>

Now, after successful designing of query it is possible to access for a data and to show result to the user:

<?PHP
    foreach($query as $customer)
    {
        echo "<p>";
        echo $customer->CustomerID;
        echo "<br/>";
        echo $customer->CompanyName;
        echo "</p>";
    }
?>

Here it is well visible, that we access to strongly typified objects, and result we receive in the form of objective collections. Such way is very similar to how we work with services of ADO.NET Data Services within  the .NET-client. These of entity classes also have been generated by utility PHPDataSvcUtil.

Pablo Castro (program manager, ADO.NET Data Services) and Claudio Caldato (program manager, interoperability, techincal strategy team) have made the small review of this library on Channel 9 in which they tell more details

At last that the project is the project with an open source code is very interesting and is accessible on CodePlex. Besides, the project is developed by company Persistent Systems, but fund by Microsoft.

Links:

  1. The announcement in a blog of Astoria team - http://blogs.msdn.com/astoriateam/archive/2009/08/21/announcing-the-php-toolkit-for-ado-net-data-services.aspx
  2. The description in a blog of Interoperability team - http://blogs.msdn.com/interoperability/archive/2009/08/21/a-new-bridge-for-php-developers-to-net-through-rest-php-toolkit-for-ado-net-data-services.aspx
  3. Channel9 - http://channel9.msdn.com/posts/jccim/Consuming-data-over-the-web-between-PHP-and-NET-with-REST-and-ADONET-Data-Services/
  4. The project at CodePlex - http://phpdataservices.codeplex.com/
Windows Marketplace for Windows Mobile users

Marat Bakirov already wrote in his blog about Windows Marketplact for Mobile users. Till now over Windows Marketplace the curtain of secret kept and it was not clear as this direction will develop. And here recently, at WPC some details Windows Marketplace for mobile devices became known.

Some facts about Windows Marketplace for Windows Mobile users (some of them already have been sounded earlier):

  • For application placing on Windows Marketplace it is required to pay $99 per year. Thus it will be possible to place five applications. For each additional application it is required to pay $99 per a year.
  • The developer will receive 70% from application cost. 30% will leave in favour of Windows Marketplace.
  • Before placing in Windows Marketplace all application should pass certification.
  • The applications placed in Windows Marketplace can be bought conveniently and safely directly from the mobile device. Application for Windows Marketplace will be accessible to these purposes in Windows Mobile 6.5 out of the box, and for versions 6.0 and 6.1 it it will be possible to install in addition in the end of 2009.
  • On 27th of July, 2009 Windows Marketplace it will be accessible to a wide range of users and developers. Subsequently applications from Windows Marketplace can be downloaded from 30 million mobile devices worldwide. The list of the countries in which works Windows Marketplace:
    • Australia
    • Austria
    • Belgium
    • Brazil
    • Canada
    • Denmark
    • Finland
    • France
    • Germany
    • Greece
    • Hong Kong SAR
    • India
    • Ireland
    • Italy
    • Japan
    • Luxembourg
    • Mexico
    • New Zealand
    • Netherlands
    • Norway
    • Poland
    • Portugal
    • Singapore
    • Spain
    • Sweden
    • Switzerland
    • Taiwan
    • United Kingdom
    • United States

What does it mean for us, developers? It means, that in the near future there will be a platform which for small money will allow to place easily and simply our applications in the global market and to earn on it.

References:

Windows 7 Sensor and Location platform: Implementation of own sensor (Part 3/3)

Windows 7 +1Recently I have told about use Sensor and Location platform in the applications. We have seen, that use of this component set can be very convenient for the application and do not demand many efforts. Also we have an opportunity to work with set of devices in the unified style. Problem of use of this platform there is a presence of drivers for Windows 7 and presence of wrappers for Sensor API. Development of the driver for the device - a task of the manufacturer. And implementation of support in Sensor API can be made own forces.

As I already spoke an entry point is SensorManager class . By means of this class it is possible to get access to the necessary sensor controls and to work with them. This class has methods of getting of the list of all sensors, sensor getting by ID or on type, request to sensor use, and also event of change of quantity of sensors in system.

SensorManager

Each sensor has two main types of identifiers - SensorId and TypeId. TypeId identifies a separate class of devices. For example, by it it is possible to get all sensors of light in system, or any other types of devices. SensorId it is given it is unique to each device. For example, if in system three same sensors of movements everyone will have the unique identifier. Is also CategoryId which unites sensors in a category.

Each identifier represents GUID. They are set by manufacturers by developing of the device and drivers. Thus, it is possible to get a concrete sensor only knowing it ID. Each sensor is presented by Sensor class. It has the general information about a sensor and methods which data from the generalised collections in not typified kind allow to obtain. It is clear, that such data presentation is not so convenient for our applications. Therefore for each sensor it is accepted to implement a class-wrapper within Sensor API. It is implemented by inheritance from general class Sensor. In demonstration examples already there are two such realisations - for 3D accelerometer and for light sensor. However, at the device which we considered earlier there are also touch buttons which also can be used. Therefore let's implement such class for this sensor.

We will define a new class which will be the inheritor of Sensor class. That it was recognised in Sensor API it it is necessary to mark with SensorDescription attribute in which to specify TypeId for this type of sensors. In base class Sensor there are two important things for us - DataReport property and DataReportChanged event. This property contains data from a sensor, and event fires at their change. The task of our class - to take advantage of these data and to deliver to their user of our class in a convenient kind. For this purpose we will create one more small class which will be engaged in analysis of the information from DataReport.

Experimental by we will find out, that by pressing of the button 1 the code 1 is generated, by pressing 2 - the code 2 is generated, by pressing 3 - the code 4 is generated, and by pressing 4 - the code 8 is generated. It is visible, that binary bits here are used. Also the code 0 in a case unpress of all buttons is generated. Thus, we can write the following code.

[SensorDescription("545C8BA5-B143-4545-868F-CA7FD986B4F6")]
public class SwitchArraySensor : Sensor
{
    public class SwitchArraySensorData
    {
        private static Guid KeyStateProperyId = new Guid(@"38564a7c-f2f2-49bb-9b2b-ba60f66a58df");
 
        public SwitchArraySensorData(SensorReport report)
        {
            uint state = (uint) report.Values[KeyStateProperyId][0];
            Button1Pressed = (state & 0x01) != 0;
            Button2Pressed = (state & 0x02) != 0;
            Button3Pressed = (state & 0x04) != 0;
            Button4Pressed = (state & 0x08) != 0;
        }
 
        public bool Button1Pressed { get; private set; }
        public bool Button2Pressed { get; private set; }
        public bool Button3Pressed { get; private set; }
        public bool Button4Pressed { get; private set; }
    }
 
    public SwitchArraySensorData Current
    {
        get { return new SwitchArraySensorData(DataReport); }
    }
 
    public event EventHandler StateChanged;
 
    public SwitchArraySensor()
    {
        DataReportChanged += SwitchArraySensor_DataReportChanged;
    }
 
    void SwitchArraySensor_DataReportChanged(Sensor sender, EventArgs e)
    {
        if (StateChanged != null)
        {
            StateChanged.Invoke(sender, e);
        }
    }
}

Actually, this class is a wrapper in Sensor API for the sensor necessary to us. For its use I should subscribe for StateChanged event and receive the information through Current property.

For getting of the list of accessible sensor of the some type it is possible to use GetSensorsByTypeId method of SensorManager class. Thus TypeId these sensor it will be defined on the basis of set SensorDescription attribute. Now, using these sensors we can subscribe on necessary event and obtain data in a kind convenient for the application. For example, we can display on the form a state of pressing of buttons.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var sensors = SensorManager.GetSensorsByTypeId<SwitchArraySensor>();
    foreach (SwitchArraySensor sensor in sensors)
    {
        switch (sensor.FriendlyName)
        {
            case "Left Switch Array Sensor":
                sensor.StateChanged += delegate(object leftSensor, EventArgs arg)
                {
                    var buttons = ((SwitchArraySensor)leftSensor).Current;
                    SwitchState(LeftButton1, buttons.Button1Pressed);
                    SwitchState(LeftButton2, buttons.Button2Pressed);
                    SwitchState(LeftButton3, buttons.Button3Pressed);
                    SwitchState(LeftButton4, buttons.Button4Pressed);
                };
                break;
            case "Right Switch Array Sensor":
                sensor.StateChanged += delegate(object rightSensor, EventArgs arg)
                {
                    var buttons = ((SwitchArraySensor)rightSensor).Current;
                    SwitchState(RightButton1, buttons.Button1Pressed);
                    SwitchState(RightButton2, buttons.Button2Pressed);
                    SwitchState(RightButton3, buttons.Button3Pressed);
                    SwitchState(RightButton4, buttons.Button4Pressed);
                };
                break;
        }
 
    }
}

As a result we will receive the application which looks as follows.

Certainly, an example with realisation of a similar sensor synthetic enough. However, it obviously shows process of connection of the sensor to Sensor API.

I wish successes to you in creation of your context-aware applications!

Sample application:

Windows 7 Sensor and Location platform: Sensors programming (Part 2/3)

Windows 7 +1 Recently I wrote about Sensor and Location platform in Windows 7 and for what purposes it is necessary. Now we will talk about how this platform can be used in the applications.

To make experiments with not virtual sensors, but with something more approached to a reality, we will use the device from Freescale semiconductor, constructed on the basis of JMBADGE2008-B microcontroller. This device represents the small circuit board on which also there are some sensors - 3D accelerometer, ambient light and buttons.

Freescale

This device is developed specially for demonstration of possibilities of Sensor and Location platform in Windows 7. Actually, everyone can buy it. Thus, this device is good for using for demonstration of this possibility Windows 7.

Before to consider concrete applications, let's look inside Sensor and Location platform. Before creation of Windows 7 and Sensor&Location platform the connection of various sensors was reduced to implementation of driver and software for it.

 

At such organisation of a task of interaction with external sensors it is possible, but it is heavy. For this purpose each application should interact with that API which will be offered by the vendor of a sensor and a software which serves this sensor. The problem is especially unpleasant in case when the application should use set of the same sensors from different vendors. How Sensor&Location platform suggests to solve this problem?

At level of operational system there are mechanisms of work with sensors. There is a standard unified program interface for work with sensors - Sensor API. Thus all interactions occur to the sensor through Sensor API. It is important, that interactions with all sensors occurs in uniform style. Now you do not need to be integrated with native API through p/invoke.

To work with Sensor and Location API it is necessary to download corresponding library ".NET Interop Sample Library". In it there are.NET-wrappers for work with Sensor API. In it there are some classes with which help it is possible to work with sensors.

Class SensorManager is an entry point. Through it it is possible to receive the information of sensor controls, and also to work with them. For example, by means of GetSensorBySensorId <> method it is possible to get access to the sensor which interested us. Each sensor should have a class-wrapper which is inherited from base class Sensor. In NET Interop Sample Library already there are such three realisations - AmbientLightSensor, Accelerometer3D, UnknownSensor.

Sensor API

The main idea at work with sensors consists in the following. At change of a state of the sensor (connected/disconnected/active/etc) StateChanged event is throwed. This event is necessary to begin with or end of work with sensors. After communication with the sensor is adjusted, the DataReportChanged event is generated at receiving of new data . This event will be generated how much often depends on sensor and driver. At processing of this event it is possible to read a state of sensors and somehow to change work of application. For these purposes GetProperty method is used. In parameters of this method the identifier of property as which it is necessary to read from the sensor is transferred. As a rule, details of calls of this method disappear in classes which are implements for the specific sensor.

Besides, each sensor has own identifier (GUID) on which it is possible to identify the device. At implementation of a class-wrapper for the sensor this ID is set by means of attribute. Thus, the sensor can be accessed  as obviously having specified the identifier of this sensor, or having referred on this class-wrapper.

/// <summary>
/// Represents a generic ambient light sensor
/// </summary>
[SensorDescription( "97F115C8-599A-4153-8894-D2D12899918A" )]
public class AmbientLightSensor : Sensor
{
 
// .....
// .....
// .....
 
var sensors = SensorManager.GetSensorsByTypeId<AmbientLightSensor>();

Let's try implement some examples of work with sensors which are accessible in the device from Freescale. We will work with two types of sensors - accelerometer (allows to measure a corner of an inclination of the device) and light (measures light exposure level indoors).

The first application which we implement will display level of light exposure in the form of a burning bulb on the form. To begin with we will subscribe to event of change of a state in Sensor API. It is necessary that the application has started to work, if the sensor is connected in a hot mode. In the handler of this event we will receive the list of all sensors of the necessary type and we will subscribe at them for DataReportChanged event.In the handler of this event we will read value from the sensor of light exposure and to write it in TextBox at the form. Because event is generated in an additional thread, also it is required to make a call of method Dispatcher.Invoke that processing went in the main thread and we could co-operate with elements on the form. Thus we will get the following code.

 
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SensorManager.SensorsChanged += SensorManagerSensorsChanged;
}
 
void SensorManagerSensorsChanged(SensorsChangedEventArgs change)
{
    Dispatcher.Invoke((System.Threading.ThreadStart)(UpdateSensorsList));
}
 
private void UpdateSensorsList()
{
    var sensors = SensorManager.GetSensorsByTypeId<AmbientLightSensor>();
    foreach (var sensor in sensors)
        sensor.DataReportChanged += delegate(Sensor sender, EventArgs e)
                                        {
                                            Dispatcher.Invoke((System.Threading.ThreadStart)(delegate
                                            {
                                                if (ActiveSensorsListBox.SelectedItem == sender)
                                                {
                                                    CurrentValue.Text =
                                                        ((AmbientLightSensor)sender).CurrentLuminousIntensity.Intensity.ToString();
                                                }
                                            }));
};
}

Now in TextBox on the form current value of light exposure is displayed. Now it is easy to implement any visualisation for it. By means of bindings in WPF we will display degree of light exposure in the form of bulbs. As a result we will receive the following application.

As on a photo it is very difficult to see application work, I have recordered short video in which how the sensor reacts to light exposure degree is well visible.

Other sensor is more interesting - he allows to define degree of an inclination of the device on different axes. For demonstration of degree of an inclination we take 3D model of the airplane for WPF application and we will rotate it in space depending on sensor indicators. The principle of this application is similar previous - we find the necessary sensors, we subscribe for events and at their processing we write down co-ordinates in entry fields on the form. After that we bind model's coordinates to values of these TextBoxs.

private void UpdateSensorsList()
{
    foreach (var sensor in SensorManager.GetSensorsByTypeId<Accelerometer3D>())
    {
        sensor.DataReportChanged += delegate(Sensor sender, EventArgs e)
                                        {
                                            Dispatcher.Invoke((System.Threading.ThreadStart)(delegate
                                            {
                                                    if (UseXCoordinate.IsChecked == true)
                                                        CurrentXValue.Text = ((Accelerometer3D)sender).CurrentAcceleration[Accelerometer3D.AccelerationAxis.X].ToString();
                                                    if (UseYCoordinate.IsChecked == true)
                                                        CurrentYValue.Text = ((Accelerometer3D)sender).CurrentAcceleration[Accelerometer3D.AccelerationAxis.Y].ToString();
                                                    if (UseZCoordinate.IsChecked == true)
                                                        CurrentZValue.Text = ((Accelerometer3D)sender).CurrentAcceleration[Accelerometer3D.AccelerationAxis.Z].ToString();
                                            }));
};
    }
 
}

Apparently from this example, the code for work with sensors has changed not so strongly. Actually, the code of data acquisition from sensors has changed only, and the rest remains invariable.

Apparently from a photo at a device inclination, the sensor transfers the information to the application and model coordinates change. Thus, we can see effect of an inclination of three-dimensional model.

That is interesting, these sensors can use some applications simultaneously. Also in one application it is possible to use some sensors. Let's combine application of rotation of three-dimensional model with light sensor. In this case except turn of model we will show the sun. If light exposure indoors decreases, also the sun will disappear. The more illumination indoors, the the sun will shine more intensively. Accordingly in this application the code from two previous examples is used. Therefore I will not bring a code, and at once I will show result.

Also it is possible to look this application in dynamics.

On these examples it is well visible, that work with sensors in Windows 7 is very simple. However, for this purpose it is necessary to have the driver for Windows 7 and a class-wrapper for Sensor&Location platform. As a rule, the driver are delivered by the vendor of a hardware platform, and the class-wrapper can be implemented independently. Next time we will talk just on this theme.

Sample applications:

Windows 7 Sensor and Location platform: What is it? (Part 1/3)

Windows 7 +1One of components Windows 7 is Sensor and Location platform. Sensor and Location is part of Windows 7 which allows to work with various sensors and additional devices for measurement something.

What for it is necessary? Sensors are necessary to make more simple some trivial actions. Especially actually it for owners of laptops, whose life is very dynamical. Imagine, that the ambient sensor which is accessible to all applications is built in the computer and gives the chance to these applications to correct the picture depending on illumination. Other example the sensor of GPS-coordinates can be. In this case applications can be adjusted that depend on district where you are at present. For example, applications can display the information on weather for that city where you are. It is possible to see a considerable quantity of examples, all depends on imagination and concrete cases. Applications which change the behavior depending on external conditions are allocated in a separate class of applications and are named context-aware applications.

There can be a question - “and what, actually, has changed?”, “why it could not be made earlier?”. The answer is simple - earlier these scenarios also could be implemented. However, to make it was not so simply. Actually, work with external sensors was exchange of information through COM-port and each sensor had specific API. For this reason it was very heavy to organise any universal program interface with which it was possible to work simultaneously from several applications.

This problem is solved by Sensor and Location library. With its help it is possible to access to various sensors and to receive from them the information in uniform style for all. It is important, that this problem has been solved at level of operational system. It can give a new push for development of context-aware applications. Further the diagramme of structure of objects for work with sensors is displayed. In following parts we will consider it more in detail.

For sensor connection to Sensor and Location platform in Windows 7 it is necessary to implement for it the driver and simple classes-wrappers on.NET for work with this sensor.

Certainly, in the near future end users hardly can feel power of all this platform to the full. For this purpose it is needed some time that developers of hardware could develop in the hardware platforms some sensors hardware platforms. However, to us, developers, it is possible to start to prepare for it already today. Therefore further I plan to tell about how to work with Sensor and Location platform in a context of business applications.

Work with the taskbar of Windows 7 in WPF applications

Windows 7 +1Recently I have published a series of articles that has been devoted to possibilities of Windows 7 for developers to work with the task panel. I have received a large quantity of responses for this time. Thanks you very much for it. That is interesting, questions were absolutely various subjects. However, the most part of questions was on a theme of use of similar functionality in WPF applications. Really, in the majority of examples I have lost sight WPF applications. I will try to compensate this defect here.

Really, use of these possibilities in WPF applications not strongly differs from their implementation in WinForms. As is known, for use of possibilities of the task panel of Windows 7 we used WindowsFormsExtensions static class in which to contain extension-methods for Form class (form representation in Windows Forms). Unfortunately, in.NET Interop Sample Library there is no have similar class for WPF applications. However it is completely not difficult to create it independently.

If to look at WindowsFormsExtensions class it becomes clear, that all calls are forwarded to Windows7Taskbar class which for form identification is used Handle of window. In a case with Windows Forms the form has property Handle which returns the necessary value. The first task is to receive handle of WPF window. Unfortunately, WPF windows do not have Handle property. However, it is possible to take advantage of WindowInteropHelper class and to receive this information. For this purpose I have made one more method which returns Handle of WPF-window.

private static IntPtr GetWindowHandle(Window window)
{
    return (new WindowInteropHelper(window)).Handle;
}

Further in all extension methods it is necessary to change parametre type (type to which it is applied extension method) from Form to Window. After that the majority of possibilities are already accessible to WPF-applications.

Other problem at work with the task panel of Windows 7 is that in some situations it is required to intercept Windows messages which come to a current window. In Windows Forms for these purposes it was possible to override WndProc method and in it to catch all necessary messages.

protected override void WndProc(ref Message m)
{
    if (m.Msg == Windows7Taskbar.TaskbarButtonCreatedMessage)
    {
        // ...
    }
 
    base.WndProc(ref m);
}

Unfortunately, for WPF windows of such method is not present. However, in WPF application it is possible to take advantage of HwndSource object and to add interception of Windows messages through it.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    HwndSource.FromHwnd(new WindowInteropHelper(this).Handle).AddHook(WndProc);
}
 
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    if (msg == WM_DWMSENDICONICLIVEPREVIEWBITMAP)
    {
        // ...
    }
    return IntPtr.Zero;
}

In other the usage of possibilities of the task panel of Windows 7 in WPF applications is implemented similarly Windows Forms.

Sample applications:

Integration of your data sources with Windows 7 Federated Search

Windows 7 +1

How often you should search for the various information? Most likely it occurs every day. It is important, that an information search problem not trivial. Also the information can is in various sources - in files, in e-mail messages, in documents etc. Not the secret, that most part of an information is in a network - local and global.

Windows Search which allows to search easily and conveniently on the basis of indexes has been developed in Windows Vista. In Windows 7 a theme of search has found the continuation and in new OS there was additional tool - Windows 7 Federated Search.

Windows 7 Federated SearchWindows 7 Federated Search is a tool which allows to search of information in a network within Windows Explorer. As a data source in this case can act anything you like - a corporate site, Internet shop, Internet auctions etc.

Difference between federated search and Windows Search consists that mechanisms of federated search do not index data sources, and simply call to them with the request to execute search query. Federated search is focused on the distributed remote sources of an information. Indexation of remote sources can be inefficient and lead to the excessive expense of the Internet traffic. For this reason the approach at which the task of processing of search query is assigned to a remote source. Thus, there is a possibility to connect all necessary remote sources and to search in them not leaving from Windows Explorer.

Despite all convenience of such search, implementation of the search provider is very simple. Federated search in Windows 7 is based on OpenSearch 1.1 standard, and works as follows. For search execution, the Windows 7 will call to the external web service constructed on the basis of the REST-approach. It means, that search query, and also other data necessary for search, are transferred in URI at the calling to this web service. Web-service on the basis of these data should execute search in the data source and will return result in RSS or AtomPub format. After that Windows 7 will present results of search from the received data in the form of files and will display to their user.

For addition of own search provider in Windows 7 it is necessary to create a file of the description of this provider. The format of this file is based on XML and contains the information on the given search service, including URI format for the calling to a web-service.

 

Thus, for implementation of own provider of federated search in Windows 7 it is necessary to execute two simple actions - to create REST-service for information search and to make for it a description file.

Let's consider process of creation of the search provider on a following example. There is a list of books with the description, the author and other information. In this case this list contains in XML file (for a demonstration example). As a data source it is possible to use anything you like. Let's make the search provider for this list.

The file of the description of a search provider represents a XML-file and has “.osdx” extension. This file has the following structure.

<?xml version="1.0" encoding="utf-8" ?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
    <ShortName>Federated Search sample provider</ShortName>
    <Url type="application/rss+xml" template="http://somehost.com/search/
?q={searchTerms}&amp;start={startIndex}&amp;count={count}"
/>
</OpenSearchDescription>

In Url section of this file the template of the address which will be used at the call to web service is set. It is visible, that this address can assume absolutely various representation. In the address template some sections in which values will be substituted are used. The main section is a “searchTerms” section. In this section the line for search will be substituted. Federated search in Windows 7 obtains data page by page, therefore there are sections “count” and “startIndex” which set the size and page number. It is necessary for, that Windows could receive the first results of search, display their to user, and then work with other elements.

<?xml version="1.0" encoding="utf-8" ?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
    <ShortName>Federated Search sample provider</ShortName>

<Url type="application/rss+xml" template="http://localhost:8731/
FederatedSearchProviderSample/search/{searchTerms}/
?start={startIndex}&amp;count={count}"
/>

</OpenSearchDescription>

The last, that it is necessary to make is to create service which will carry out search. In this case there is no binding to concrete technology and the only requirement - service should return result in RSS/Atom format. It is clear, that service can be constructed on absolutely various platforms and technologies. For these purposes the best choice - the usage of possibilities of WCF for creation of REST-services. A lot of attention is already given construction of similar services, therefore I will not stop in detail on it, and I will describe only key steps.

The first, that it is necessary to make is to define the contract. At the contract there will be two operations - execution of search and generating of the detailed information.

[ServiceContract]
[ServiceKnownType(typeof(Atom10FeedFormatter))]
[ServiceKnownType(typeof(Rss20FeedFormatter))]
public interface ISearchProvider
{
    [OperationContract]
    [WebGet(UriTemplate = "search/{searchTerms}/*")]
    SyndicationFeedFormatter Search(string searchTerms);
 
    [OperationContract]
    [WebGet(UriTemplate = "details/{id}")]
    Stream Description(string id); 
}

The most important thing, on what it is necessary to pay attention during this moment - definition of URI template. Apparently in this case the “search/{searchTerms}/*” template completely corresponds to that has been defined in a description file.

It is necessary to implement this service only. At implementation it is necessary to consider the specified parametres at the call to service (searchTerms, start, count) and to divide search result into pages if it is necessary. For this purpose it is possible to use LINQ methods - Take/Skip. Thus, service implementation will look as follows.

public class SearchProvider : ISearchProvider
{
    public SyndicationFeedFormatter Search(string searchTerms)
    {
        int count;
        int startIndex;
 
        int.TryParse(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters.Get("count"), out count);
        int.TryParse(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters.Get("start"), out startIndex);
 
 
        var result = SearchBooks(searchTerms);
 
        if (count > 0)
        {
            if (startIndex >= 0)
            {
                result = result.Skip(count * (startIndex - 1)).Take(count);
            }
            else
            {
                result = result.Take(count);
            }
        }
 
 
        return new Rss20FeedFormatter(
            new SyndicationFeed("Federated search sample", String.Empty, null,
                from item in result
                select new SyndicationItem(item.Element(XName.Get("name")).Value,
                    item.Element(XName.Get("description")).Value,
                    new Uri(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri.ToString() + @"/details/" + item.Element(XName.Get("id")).Value))
                    {
                        PublishDate = DateTimeOffset.Parse(item.Element(XName.Get("date")).Value),
                    }));
    }
 
    //...
}

Also at service there are methods for display of the detailed information and search execution. At desire it is possible to download an example and to look their implementation there.

After service is ready and started, it is necessary to open a file of the description of service (.osdx) in Windows and to agree with offer to add the search provider. After that this provider will appear in the list of search providers.

Add Search Connector image

Now, when web service works and also the provider of search is successfully added, it is possible to search on a network resource directly from Windows Explorer.

Windows 7 Federated Search sample provider

Apparently, implementation of the search provider for Windows 7 Federated Search is very simple. However, it can make use of your data much more conveniently and easier. One of the most successful examples of using of federated search in external sources is the search provider for corporate sites on the basis of Sharepoint. Why and to us not to implement similar functionality for our applications?

Sample application:

Change of the background image on the logon screen in Windows 7

1 As it has been announced earlier, in new operational system Windows 7 it is possible to easily change a background of a logon screen. For this purpose it is not required to change resources in executable files or to carry out still any special actions. Process of changing of the image is very simple and can be executed without use of additional tools. This functionality is accessible and correctly works since 7057 build.

To change a background on the logon screen it is necessary to do following steps.

  1. To open the registry editor and to find section “HKEY_LOCAL_MACHINE –> Software –> Microsoft –> Windows –> CurrentVersion –> Authentication –> LogonUI –> Background”. In this section there is a special key “OEMBackground” (DWORD type). Value “1” herein says that it is necessary to use special appearance of the logon screen. If the key does not exist, he can be created manually.
  2. To be convinced, that there is folder “%windir%\system32\oobe\info\backgrounds”. Here Windows 7 will search for background images for the logon screen. If this folder does not exist, she is necessary for creating.
  3. To put in this folder all necessary images. For each screen resolution it is necessary to put the image in this folder with a specific name. If the image with the necessary name is not found, file backgroundDefault.jpg will be used. It is important, that each image should be no more than 256 KB, differently it will be ignored. The list of files which are necessary for putting in this folder:
    1. backgroundDefault.jpg
    2. background768×1280.jpg  (0.6)
    3. background900×1440.jpg  (0.625)
    4. background960×1280.jpg  (0.75)
    5. background1024×1280.jpg (0.8)
    6. background1280×1024.jpg (1.25)
    7. background1024×768.jpg  (1.33)
    8. background1280×960.jpg  (1.33)
    9. background1600×1200.jpg (1.33)
    10. background1440×900.jpg  (1.6)
    11. background1920×1200.jpg (1.6)
    12. background1280×768.jpg  (1.66)
    13. background1360×768.jpg  (1.770833)
  4. For display of changes there is no necessity to reboot. It is enough to lock Windows (Win + L) or to leave a current session (Log off).

Also it is possible to take advantage of 3rd-party utilities. One of such utilities – Tweaks Logon Changer for Windows 7. This utility will execute all necessary changes in the system registry, and also will compress the image till the necessary sizes and will put in the necessary folder.

Tweaks Logon Changer for Windows 7

Animation of switching of tasks in Windows 7

Windows 7 +1Among an users of Windows there are such people to whom smooth animations are not necessary at switching of windows etc. It is important for these users is speed of work and convenience. In a word, that is necessary for them - the responsible user interface. More recently we communicated with such user by e-mail. Its problem consisted that it is necessary to wait few time before he will see a preview window for the application at hovering on an application icon in the task panel. For this reason I have decided to write pair of tips for such category of users.

Acceleration of animation of showing of a preview window

Situation: At hovering on a icon of the application the preview window appears with a delay.

How to accelerate animation:

  1. We start the registry editor (Start –> Run –> regedit)
  2. We find key HKEY_CURRENT_USER –> Control Panel –> Mouse
  3. Herein we find value MouseHoverTime
  4. We correct this value from 400 to 50 (time of a delay of animation in milliseconds)
  5. Reboot

Switching-off an animation when maximize/minimize of window

Situation: At minimize/maximize of windows there is an animation which can stir in work. If it is fair for your case it can be switched-off.

Animation switching-off:

  1. We open the control panel (Control Panel)
  2. We open section System and Security, then subsection System
  3. In the left side of a window we choose item Advnced system settings
  4. In the appeared window in Advanced tab, in Performance group we press Settings button
  5. In the appeared window we switch off Animate windows when minimizing and maximizing option 

Microsoft Sync Framework 2.0 CTP2

Today next preview version of Sync Framework became accessible.

Version Sync Framework v.2 CTP2 became accessible on June, 4th, 2009. Main features of this version:

  • New database providers
  • Custom filters
  • Improved conflict handling
  • Data conversion between providers
  • Change application service

All new features are interesting that them to look.

Microsoft Download Center: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=89adbb1e-53ff-41b5-ba17-8e43a2e66254

Windows Mobile 6.5 SDK is accessible to download

Windows Mobile 6.5Today it became accessible SDK to develop for Windows Mobile 6.5. This pack includes the documentation, examples, header files and libraries (for native), tools for Visual Studio and images of emulators. Emulator's versions are accessible:

  • Windows Mobile 6.5 Professional Square Emulator
  • Windows Mobile 6.5 Professional QVGA Emulator
  • Windows Mobile 6.5 Professional WQVGA Emulator
  • Windows Mobile 6.5 Professional VGA Emulator
  • Windows Mobile 6.5 Professional WVGA Emulator
  • Windows Mobile 6.5 Standard Square Emulator
  • Windows Mobile 6.5 Standard QVGA Emulator

The following locales is accessible to these emulators:

  • 0804 CHS Chinese Simplified
  • 0409 USA English
  • 0407 GER German
  • 040c FRA French
  • 0410 ITA Italian
  • 0c0a ESN Spanish

One of important features of Winodws Mobile 6.5 SDK is Windows Mobile 6.5 touch gesture framework. By means of this component and gesture APIs it is possible to operate the application by means of gestures.

Hasten to download!

Download link: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=20686a1d-97a8-4f80-bc6a-ae010e085a6e

Give green light to your applications together with Windows 7!

Windows 7 +1 Is your applications are completely compatible with Windows 7 and Windows Server 2008 R2? You can outstrip the competitors, having checked up your applications on compatibility with Windows 7 already today. If your company is ISV you can be helped by a isvappcompat.com resource.

On this resource you can be registered in the program “Green light” and specify the reference to your application. In this case you receive the necessary information, toolkit and resources for check of compatibility of your applications with Windows 7. If your application is already compatible with Windows Vista or Windows Server 2008 check of compatibility with new operational systems will be very easy.

After check of compatibility of your applications with Windows 7 you can inform this information to your clients and let to them know, that you it is the best than all competitors. As one of the first ISV registered in the program, you will get priority access to marketing materials, templates of messages and the other documents, called to help you to inform about your application to your clients.

Green light program’s site: https://www.isvappcompat.com/

Register link: https://www.isvappcompat.com/signup.aspx

Windows 7 programming: Taskbar. Part 10 (final part) – JumpLists.

Windows 7 +1One of the major features of the task panel of Windows 7 are Jump Lists. Jump lists are displayed if to select an application icon in the task panel and to press the right button of the mouse. If the application uses functionality of JumpLists, then except standard actions (pin, close) there will be some more additional actions which facilitate our daily work.

This functionality of the task panel various appendices actively use. For example, Windows Media Player displays switching options for play lists. Internet Explorer and Windows Explorer contain in jump lists with references to last places where you came. Windows Live Messanger displays options of switching of a state.

WLM's jump list

In jump list there can be some various types of elements: tasks, references to last open documents and references to constant documents. Besides, these items can be pinned. Such elements will not disappear from jump list in due course. It is convenient, for example, if we often work with the same document. Schematically jump list it is possible to present as follows.

Actually, each item in jump list represents the reference to the program or a file. So, for example, we can start the calculator, or any document of the some format. Unfortunately, we do not have possibility directly to intercept event of pressing item in jump list. Each time when we choose the item, it will be started a new copy of the application. It is so because jump list it is possible to cause even then when the application is not started.  In this case it should be pinned on the task panel. For example, in a following drawing it is visible, that Internet Explorer at present it is not started, but jump list we can open.

So, let's look how similar functionality can be implemented in our applications. For work with jump list we need to use the object of type JumpListManager which is a part of .NET Interop Sample Library. To create it it is necessary at the moment of creation of the button of our application on the task panel. For these purposes it is possible to override WndProc method as follows.

protected override void WndProc(ref Message m)
{
    if (m.Msg == Windows7Taskbar.TaskbarButtonCreatedMessage)
    {
        _jumpListManager = WindowsFormsExtensions.CreateJumpListManager(this);
        _jumpListManager.UserRemovedItems += (o, e) =>
        {
            e.CancelCurrentOperation = false;
        };
    
        // add items
    
        _jumpListManager.Refresh();
    }
    
    base.WndProc(ref m);
    }

Pay attention to a call of Refresh method after creation of object JumpListManager. The call of this method is necessary for updating of items in jump list. Also obligatory action is the subscription to UserRemovedItems event. It is executed when attempt of removal of out-of-date items from jump list is made. Let's now try add new items in jump list. For these purposes there are classes-wrappers and the necessary methods at object JumpListManager.

The most simple type of items in jump list - tasks. The tasks there can be a start of the external application or our application with any parametres. In WLM in the form of tasks switching of a state of the user is implemented. For task creation in jump list AddUserTask method is used.

_jumpListManager.AddUserTask(new ShellLink
{
    Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "calc.exe"),
    Title = "Calculator",
    Category = "Applications",
    IconLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "calc.exe"),
    IconIndex = 0
});

As we see, the new object of type ShellLink in which the way to the application is transferred, heading and a icon here is created. I have added in the application two tasks and have the following result.

Other variant of filling jump list - references to documents which have been loaded earlier.  For these purposes I have created some text files with extension “.myapp” and I have associated this type of files with the application. Whether at an application launch I check the name of a file as parametre is transferred at an application launch. If the name is set, I read out this file and I add it in the list before the loaded files. For these purposes there is AddToRecent method.

if (File.Exists(Environment.GetCommandLineArgs().Skip(1).FirstOrDefault() ?? String.Empty) == true)
{
    _jumpListManager.AddToRecent(Environment.GetCommandLineArgs().Skip(1).FirstOrDefault() ?? String.Empty);
}

Now from Windows Explorer I will open these files. My demonstration application (if we correctly associated the given type of files with the application) will be started thus. Thus by a call jump list I will see, that in a category “Recent” there were references to earlier open files.

I can pin those items with which I work more often. In this case I can quickly open the documents necessary to me via jump list.

Other way of placing of items  in jump list - creation of references to constant documents/programs. In this case we also can group these items into categories.  For these purposes there is AddCustomDestination method.

_jumpListManager.AddCustomDestination(new ShellLink
{
    Path = @"about.txt",
    Title = "About",
    Category = "My application",
    IconLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "shell32.dll"),
    IconIndex = 11
});

I have added some such references in jump list and I have following result.

In this drawing it is visible, that there were two additional groups with references inside.

Remarkable feature of jump list is that its contents also are accessible in the "Start" menu. So, for example, if we actively use this functionality it it is possible to be used and from the starting menu.

 

Thus we can use additional functionality which gives us the task panel of Windows 7 for much as possible comfortable work of the user.

Sample application:

 

On it I finish a series of articles devoted to programming of the task panel for Windows 7. I hope this information it will appear useful to you and your applications. I wish to notice especially, that implementation of possibilities of the task panel of Windows 7 for your applications will not demand many efforts, but the result will not keep itself waiting long - will communicate with your application much more pleasantly and more conveniently.

Good luck to you in development of your Windows 7 applications!

Windows 7 programming: Taskbar. Part 9 – PeekBitmap.

Windows 7 +1

Earlier I wrote about possibility of the task panel of Windows 7 to change preview for a window. We said that in preview it is possible to display both a window part, and own image. At Windows 7 there is such pleasant feature, that if we will hover the mouse cursor on preview windows all other windows will disappear, and the selected window will be displayed. It looks as follows.

 

In this case the panel of problems Windows 7 allows us to set own behaviour too. In this case we have possibility to set contents of our form our own image. For example, we can write any useful text. In this case the work scenario can look as follows. The user in the panel of problems has an application which something does. It can observe its state on the basis of ProgressBar and OverlayIcon about which I wrote earlier. If this information has not enough, he can hover the mouse cursor at an icon of the application. In this case preview in which the additional information contains it will be displayed (about what I wrote too). The user can hover on window preview and in this case all windows will disappear and on the screen there will be only an selected window. In this window we can display even more information which is necessary for the user.

By default at such scenario at concealment of other windows window contents will be displayed. Such redefinition of the content of a window can be useful, if on the form the information is separated and at once is not clear that occurs in the application.

To implement the similar scenario in our application we will take advantage .NET Interop Sample Library. SetPeekBitmap method of a class-wrapper is intended for these purposes. When the user hovers on preview windows it is necessary to generate the image. For these purposes we will redefine method WndProc and we will catch event WM_DWMSENDICONICLIVEPREVIEWBITMAP. Just during this moment of time it is necessary to generate the image.

protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_DWMSENDICONICLIVEPREVIEWBITMAP)
    {
        WindowsFormsExtensions.SetPeekBitmap(this, GeneratePeekBitmap(this, Images._111), true);
    }
 
    base.WndProc(ref m);
}

In this case we invoke a method which will generate necessary to us Bitmap. Generation of this image also does not represent any complexity. Generally we can copy in this Bitmap a picture of our window and over it to draw the information necessary to us. I will fill this area with a certain background and I will draw a icon of a state atop it.

private static Bitmap GeneratePeekBitmap(Form form, Image stateImage)
{
    var preview = new Bitmap(form.ClientSize.Width, form.ClientSize.Height);
 
    var g = Graphics.FromImage(preview);
 
    g.DrawImage(Images.background.GetThumbnailImage(form.ClientSize.Width, form.ClientSize.Height, null, IntPtr.Zero), 0, 0);
    
    if (stateImage != null)
    {
        Size thumbSize = new Size(100, 100);
        g.DrawImage(stateImage.GetThumbnailImage(thumbSize.Width, thumbSize.Height, null, IntPtr.Zero), form.ClientSize.Width / 2 - thumbSize.Width / 2, form.ClientSize.Height / 2 - thumbSize.Height / 2);
    }
 
    return preview;
}

Pay attention, that for correct display the sizes of this image should coincide with the size of the form. After that at us the application which looks as follows will turn out.

 

Actually, after that the image to is established whence it can be necessary. The main thing that this image also was generated at the moment of processing specified above event. For example, in the demonstration sample I also set this image in the timer. Thus I can hover the mouse cursor on preview and observe of that as the form changes at timer tick.

Besides, SetPeekBitmap method has a third parametre of logic type (boolean). Whether changing this parametre it is possible to specify it is necessary to remove a border of application. For example, if I set this parametre in false I will see the following result.

Sample application:

Windows 7 programming: Taskbar. Part 8 – IconicThumbnail.

Windows 7 +1

Recently I have told about how it is possible to influence on preview windows in the task panel of Windows 7. We displayed only that part of a window which is most important for the user in that time. Nevertheless in certain situations be much more useful displaying of other picture (an application state), instead of window parts.

For example, this possibility uses Windows Live Messanger. If we hover the mouse cursor to WLM icon it will display avatars of the current user in an preview window .

Windows Live Messanger

Let's understand this possibility of the task panel of Windows 7. For implementation of similar behaviour in .NET Interop Sample Library there is SetIconicThumbnail method. With its help we can create easily and simply own preview for our window. However, before we will start it to use we should enable this behaviour by means of EnableCustomWindowPreview method. Otherwise at executing of SetIconicThumbnail method we will receive a corresponding exception. To make it it is possible directly in the designer of the form.

public Form1()
{
    InitializeComponent();
    WindowsFormsExtensions.EnableCustomWindowPreview(this);
}

It is necessary to tell, that the sizes of the image which we wish to display in preview are limited. It is logical, because would present that was, if preview could be the size 1024x768. These sizes are limited by value 200x120. The image can be less than this size. In this case the window preview also will be reduced. If the image more than these sizes the exception will be throwed.

In parametres of SetIconicThumbnail method the reference to the current form and the image (Bitmap) which need to be displayed is passed. Our goal - to generate this Bitmap. And in this case at us hands are completely untied - we can generate all that is necessary for us. It can be a window picture, with any additional text atop. It can be any own picture containing the information. It can be the text with a some statistics. All depends on your imagination.

I will generate the image displaying a state of application by the text and graphically, and also a small picture of a window in the demonstration application. For this purpose I will create Bitmap with necessary sizes to me and I will fill in with its background. After that I will draw there the image of the state and a window picture. Then I will write the text of the state on this image and I will transfer result in SetIconicThumbnail method.

private static void SetState(Form form, string stateText, Image stateImage)
{
    // blank image
    var preview = new Bitmap(200, 120);
    var g = Graphics.FromImage(preview);
 
    // fill background
    g.DrawImage(Images.background, 0, 0);
 
    // file image of state
    if (stateImage != null)
    {
        g.DrawImage(stateImage.GetThumbnailImage(100, 100, null, IntPtr.Zero), 100, 10);
    }
 
    // fill image of form
    g.DrawImage(GetFormImage(form, 50, 60), 10, 10);
 
    // draw text
    g.DrawString(stateText, new Font("Verdana", 18), Brushes.White, 10, 70);
 
    // setting thumbnail
    WindowsFormsExtensions.SetIconicThumbnail(form, preview);
}

We can see that the code has turned out laconic enough. Finally, we can see a window with the following preview.

That is interesting, our application can change itself this state in a background. Thus, if the mouse is on a icon the application and preview at present is displayed, image change in an emerging window occurs smoothly, without any by-effects. So, for example, I can create the timer in which handler through certain time intervals to change a state.

private readonly string[] _stateTexts = new[] { "Deleting..", "Wireless", "Security", "Stop", "Help", "O'kay", "Playing", "Login", "Warning", "Showcase", "Search", "Processing..", "Locked", "Error", "Refreshing.." };
private readonly Bitmap[] _stateImages = new[] { Images._104, Images._110, Images._111, Images._112, Images._113, Images._114, Images._120, Images._125, Images._129, Images._134, Images._17, Images._25, Images._41, Images._50, Images._52 };
private int _currentIndex = 0;
 
private void timer1_Tick(object sender, EventArgs e)
{
    if (_currentIndex + 1 >= _stateImages.Length)
    {
        _currentIndex = 0;
    }
    else
    {
        _currentIndex++;
    }
    SetState(this, _stateTexts[_currentIndex], _stateImages[_currentIndex]);
}

Preview windows of our application will dynamically change, and the user can see this state easily and conveniently

Sample application:

Windows 7 programming: Taskbar. Part 7 – ThumbnailClip.

Windows 7 +1

As we already saw, Windows 7 possesses convenient functionality for display preview of windows of applications. It is possible to look the reduced representation of a window for few seconds at mouse hover at a window icon in the task panel. It is very convenient when at the user openly considerable quantity of windows.

All contents of a window are displayed by default in these preview . However, for some appendices it would be much more convenient to show in preview not all contents of a window, but only its part. Such functionality also is provided for the task panel of Windows 7 and we can use it for the out applications. Let's understand this possibility of the task panel of Windows 7.

As usually we will use for this purpose .NET Interop Sample Library. In wrappers for functions from system libraries of Windows here there is SetThumbnailClip method which will help us with implementation of the given functionality. By a call of the given method in parametres it is necessary to transfer a current form and the co-ordinates limiting area of a window.

private void Clip5_Click(object sender, EventArgs e)
{
    WindowsFormsExtensions.SetThumbnailClip(this, new Rectangle(10, 10, 145, 145));
}

On this example it is well visible that to use this method very easily.

Let's create the small application where we will look at possibilities of this functionality. For this purpose I will create the empty application in which I will add some some controls. After an application launch preview windows will look as follows.

image

It is visible, that in preview all window is displayed. Let's limit area of display by means of SetThumbnailClip method. Let's display, for example, only entry fields which are on the form.

image

It is interesting, that if the form has a dynamic content (for example, video) it will be displayed in dynamics. I have placed some animated images and have displayed them in preview in the my demonstration application. Thus there is no necessity for this purpose to do something else.

image image

It is important, that we can change contents preview in the course of application work. For example, during any moment of time it can be necessary to display contents of some important entry field, and during other moment - to display the image from the form. Such dynamism can give the chance to receive to the user the actual information for it.

Finally, if it is necessary for us to display all contents of the form it is possible to use the same method, but to pass it the sizes of all form. In this case all window will be displayed in preview again.

private void NoClip_Click(object sender, EventArgs e)
{
    WindowsFormsExtensions.SetThumbnailClip(this, new Rectangle(new Point(0, 0), Size));
}

Sample application:

Windows 7 programming: Taskbar. Part 6 – AppId.

Windows 7 +1Recently I wrote how it is possible to display tabs for child windows of our application. In this case we needed to display child windows of our application. For these purposes we used CustomWindowManager class.

The same effect can achieve, if we start some copies of same our application. In this case Windows 7 will define that this same application and will group windows in one icon.

Let's try understand how it works. Basis is concept Application ID. For each window we can set the ID. This feature also can be used when it is necessary to avoid such behaviour. In this case it is necessary to set various AppId for each such window. To make it it is possible using. For this purpose it is necessary to invoke SetAppId method.

private void SetAppIdButton_Click(object sender, EventArgs e)
{
    WindowsFormsExtensions.SetAppId(this, “SomeAppId”);
}

Thus, we can set various AppId for each window and they will not be grouped.

However, similarly also probably to group some windows from different applications. For this purpose it is necessary to set identical AppId for each of windows. In this case the task panel of Windows 7 will group these applications in one icon. For example, in this case I have set identical AppId for different windows from different applications and these windows have appeared grouped in the task panel of Windows 7.

Sample application:

More Posts Next page »