How to get known folder path (Windows Vista/7)?

 
Windows Vista and above supports independent software vendors (ISV) to add support for custom known folder locations. Previously a fixed set of IDs were provided to use with SHGetFolderPath, SHGetFolderLocation and SHSetFolderPath APIs.
For adding this flexibility, the known file APIs has been rename and designed with COM Interfaces.
New Shell APIs and COM Interfaces are introduced to replace the old Shell APIs

New Function Replaces COM Equivalent
SHGetKnownFolderPath SHGetFolderPath IKnownFolder::GetPath
SHGetKnownFolderIDList SHGetFolderLocation IKnownFolder::GetIDList
SHSetKnownFolderPath SHSetFolderPath IKnownFolder::SetPath

Old APIs were using CSIDL for representing the known location identifier. This has been replaced by KNOWFOLDERID. However Windows Vista and 7 still supports CSIDL and associated APIs for compatibility reasons. The new applications has to use the new APIs or COM Interface. When using both COM/New Shell API, you’ve to ensure that CoTaskMemFree function is called to release the output resources. Otherwise memory leak may occur. Also don’t call any other memory release function like free or delete operator. It may cause undefined behavior

How to Enumerate All Known Folders?

void EnumerateAllKnownFolders(CStringArray& strArray)
{
	CStringArray strPathRet;
	IKnownFolderManager* pkfm = NULL;
	HRESULT hr = CoCreateInstance(CLSID_KnownFolderManager, NULL,
		CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pkfm));

	if( SUCCEEDED(hr))
	{
		KNOWNFOLDERID* rfid;
		UINT uCount = 0;

		if( FAILED( pkfm->GetFolderIds( &rfid, &uCount )))
			return;

		for (UINT uIdx = 0; uIdx < uCount; ++uIdx )
		{
			IKnownFolder* pFolder;
			pkfm->GetFolder( rfid[uIdx], &pFolder );
			LPWSTR szPath;
			pFolder->GetPath(0, &szPath );
			strArray.Add( szPath );
			CoTaskMemFree( szPath );
			pFolder->Release();
		}

		CoTaskMemFree( rfid );
		pkfm->Release();
	}
}

How to get the path of a specific known folder using new COM Interface?

CString GetKnownFolderIDCOM( KNOWNFOLDERID rfid )
{
	CString strPathRet;
	LPWSTR szPath;
	IKnownFolderManager* pkfm = NULL;
	HRESULT hr = CoCreateInstance(CLSID_KnownFolderManager, NULL,
		CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pkfm));

	if( SUCCEEDED(hr))
	{
		IKnownFolder* pFolder;
		pkfm->GetFolder( rfid, &pFolder );

		pFolder->GetPath(0, &szPath );
		strPathRet = szPath;
		CoTaskMemFree( szPath );
		pFolder->Release();
	}
	pkfm->Release();
	return strPathRet;
}

How to get path of a specific known folder Shell API?

CString GetKnownPathShell( KNOWNFOLDERID rfid )
{
	CString strPath;
	LPWSTR szPath;
	SHGetKnownFolderPath( rfid, 0, 0, &szPath );
	strPath = szPath;
	CoTaskMemFree( szPath );
	return strPath;
}
 

Windows Registry Virtualization

 

Registry virtualization is implemented in Windows Vista and 7 for providing application support for legacy applications. The legacy application (till Windows XP) runs in administrator privilege by default which enables the crappy applications to access the sensitive system area without user knowledge. UAC is the solution introduced to defend this kind of attacks. By default the applications will be launched in user privileged mode and the application can request user if it requires to have elevated privilege.

Registry Virtualization emulates the HKEY_LOCAL_MACHINE\Software write operations under HKEY_USER\<User SID>_Classes\VirtualStore\Machine\Software path.

Open Registry Virtualization – If the application doesn’t have enough privilege to open a specific key, the virtualized key will be opened with maximum privilege.

Write Registry Virtualization – If the application doesn’t have enough privilege to write to the specified location, the write operation will be performed under virtual store path.

Read Registry Virtualization – System provides a merged copy of information from Virtual store and the original global store together.

Virtualization is provided for

  • 32 bit interactive process
  • Keys in HKEY_LOCAL_MACHINE\Software
  • Keys that an administrator write to (if the application doesn’t have privilege)

Virtualization is disabled for

  • 64 bit processes
  • Processes which doesn’t have GUI (e.g Services)
  • Process that impersonate a user
  • Kernel mode processes such as drivers
  • Process that has specified requestedExecutionLevel in their manifest
  • Keys and subkeys of HKEY_LOCAL_MACHINE\Software\Classes, HKEY_LOCAL_MACHINE\Software\Microsoft\Windows, and HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT.

The applications which required to run under Windows Vista and 7 must follow the UAC guidelines and should not use registry to store the applications information. Microsoft may stop supporting this feature in the upcoming versions of Windows. So keep your applications compatible with the latest platform.

See more

 

Programming Windows Phone 7 – Hello World

 

I was really excited about to see the upcoming release of Windows Phone 7. This is truly a great answer from Microsoft to the rest of world. Apple iOS which is currently the most popular mobile platform, Google Android, BlackBerry etc. were taking pace with the new technologies and Microsoft was still battling to find a space in the mobile world. Of course Windows Mobile operating system was popular some time before but the smart phones were not really popular and on aging, the platform itself being outdated in front of other new age platforms.

All programs for Windows Phone 7 can be written in .NET managed code. Currently C# is the only programming language supported. The tools for Windows Phone 7 can be freely downloaded from Windows Phone 7 website. It includes

  • Visual Studio 2010 Express Edition
  • XNA Game Studio 4.0
  • On Screen Phone Emulator

Windows Phone 7 can be programmed mainly using XNA FrameWorks and the popular Silverlight platform. XNA is used for high performance games (usually 3D games) and Silverlight is usually used for the 2D graphical applications.

Windows Phone 7 contains the stripped down version of Silverlight 3. Microsoft has avoided the silverlight features which are not really compatible with the Windows Phone 7 platform. The animations for the programs can be down using the Microsoft Expression Blend

Ultimately it comes to programmer’s responsibility to choose which platform should be used for programming Windows Phone 7 application.

Windows Phone 7 contains the Azure services to access the cloud service. One of the examples are XBox Live (runs on cloud). Programs are location aware and can access data through bing, social networking websites etc.

Windows Phone 7 features Multi-Touch screen with 3 navigation buttons. Back (like the back button in the browser. This will terminate the application),  Start button (to navigate to home screen), Search. Currently the native resolution of a Windows Phone hardware is 400×800. Also 320×480 resolution screen is expected. The hardware component features

  • Wi-Fi
  • Camera
  • Accelerometer – to detect the movement of the phone
  • GPS based Location
  • Vibration (programmable)
  • FM Radio
  • Push notifications

Once after downloading the tools, you can either start programming in the Visual Studio Express Edition or Visual Studio 2010 (if it’s already installed).

Here I’m demonstrating a basic Windows Phone 7 application in Silverlight. The code is only tested in Simulator not on any real hardware.

Create the new project using the Wizard

image

The basic layouts will automatically be created using the XAML and corresponding C# source will also be created. Notice that the standard controls available in the Windows phone 7 is not similar to the controls available in Windows. They’re transparent and designed for the phone. The entire theme is based on black. You can simply start debugging/execute the code using the emulator available. It’s better not to close the emulator Windows frequently as it may take time to start it up. The program will automatically deployed and starts in the emulator.

The user actions like home screen, back button, search etc will end up the application by default. The application must manage itself to restore the previous state if necessary on quit.On startup Windows phone 7 emulator will ask for the basic setup. It’s very easy to set it up and this is a one time process. The emulator can be used for changing the orientation between portrait and landscape. The buttons are available on the right top corner of the emulator window on hovering the mouse.

The demo application loads the posts from this blog and display it, whlie tap on the post titles listed, the article will be loaded on webBrower.

The layout and controls are as follows

image

Loading the feed items

The silverlight application had put lot of restrictions in accessing the APIs and resources of other websites. Loading news feed (RSS/Atom) is not really painful using the C# code. Silverlight supports asynchronous read operations for web requests. SyndicationFeed class is not supported supported bu default. Basically it’s safe to add this assembly to the project (System.ServiceModel.Syndication,dll) You can browse to Windows SDK folder, locate and add the same assembly in the “Client” folder

private void buttonRefresh_Click(object sender, RoutedEventArgs e)
{
    // Load the feed items
    LoadFeedItems();
}

private void LoadFeedItems()
{
    // Asynchronously load the feed content.
    WebClient client = new WebClient();
    Uri address = new Uri(&quot;http://feeds.feedburner.com/sharingmythoughts&quot;);
    client.OpenReadCompleted += client_openReadComplete;
    // Add the callback on completion
    client.OpenReadAsync(address);
    webBrowser.Visibility = Visibility.Collapsed;
    buttonBack.Visibility = Visibility.Collapsed;

}
private void client_openReadComplete(object sender, OpenReadCompletedEventArgs args)
{
    try
    {
        listBoxPosts.Items.Clear();
        // try to load the result in the XML reader.
        // Exception may occur if the request is failed
        XmlReader reader = XmlReader.Create(args.Result);

        // Syndication Feed is not supported by default.
        // It's safe to add this assembly.
        SyndicationFeed feed = SyndicationFeed.Load(reader);
        Items = feed.Items.ToArray();
        foreach (SyndicationItem e in Items)
            listBoxPosts.Items.Add(e.Title.Text);
    }
    catch
    {
        MessageBox.Show(&quot;Error downloading feed&quot;);
    }

}

Navigate to the base URL on tapping

private void OnTapItem(object sender, MouseButtonEventArgs e)
{
    if (listBoxPosts.SelectedIndex >= 0)
    {
        buttonRefresh.Visibility = Visibility.Collapsed;
        buttonBack.Visibility = Visibility.Visible;
        webBrowser.Visibility = Visibility.Visible;
        Uri address = new Uri(Items[listBoxPosts.SelectedIndex].Id);
        webBrowser.Navigate(address);
    }
}

The mobile theme I’ve enabled for this blog is not really working well. The WPTouch theme I installed seems not really identifying Windows Phone 7 user agent string. (Amazingly it works well when I load using Intenet Explorer App in the Phone 7).

Adding support for Orientation

By default, the wizard creates application with Portrait Orientation. The page content will not be arranged according to the current orientation if we don’t add support for it. Change the orientation to Portrait/Landscape/PortraitOrLandscape in the XAML file

SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"

Handling Orientation Events

It’s possible to override OnOrientationChanged function do if we need to manage something else other than the default orientation change support implemented in the base class. For the simple applications using controls, we can use the standard alignment surppot provided by the grids and panels. The controls will be perfectly aligned according the vertical and horizontal settings of the controls.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <ListBox Margin="0" x:Name="listBoxPosts" MouseLeftButtonUp="OnTapItem" />
    <phone:WebBrowser Margin="0" x:Name="webBrowser" />
</Grid>
<Button Content="Refresh" Height="71" HorizontalAlignment="Right" Margin="320,145,0,0" x:Name="buttonRefresh" VerticalAlignment="Top" Width="160" Click="buttonRefresh_Click" />
<Button Content="Back" Height="71" HorizontalAlignment="Left" Margin="0,145,0,0" x:Name="buttonBack" VerticalAlignment="Top" Width="160" Click="buttonBack_Click" />

Override the OnOrientationChanged if more flexibility is necessary

protected override void OnOrientationChanged(OrientationChangedEventArgs args)
{
    // do your code. If base is not called, then the orientation will not be changed
    base.OnOrientationChanged(args);
}

Portrait Orientation

image

 

Landscape Orientation

image

Putting it all together

Download the source from GIT Hub

Closing note

I feel Windows Phone 7 is a solid platform. It uses the modern programming languages and technologies. C# is one of the most popular language and it’s expressive. The Apple’s iOS platform is truly a solid and great foundation but the object C has a slight learning curve. It’s obvious because it’s my father’s programming language, not mine. But Apple made the platform truly solid and cash cow for the developers. So nobody really care it’s his father’s or his. :)

Microsoft has chosen right technologies for Windows Phone 7 is proven and popular. XNA, Silverlight with C# will surely give edge for Microsoft to get a pace on their platform. Also the developer tools are easy to work and available for free.

Charles Petzold is working for a free version of book for Programming Windows Phone 7 which is expected to out soon. Apple has a definite documentation, video tutorials and lot more stuffs to help the developers. The MSDN documentation is slightly noisy with too many languages technologies. Even if we check the documentation for silverlight, some of the functionalities may not work under Windows Phone 7. Hopefully we can see lot of good stuffs in MSDN and Channel 9 for Windows Phone 7( Channel 9 offer Windows Phone 7 Training Kit now). Now I’m exploring more about deploying the phone applications. See you son.