Windows Vista File and Registry Virtualization

Enabling UAC (User Access Control) feature in Windows Vista, Administrator users in Windows Vista, by default, don’t have administrative privileges. Every Windows process has two security tokens associated with it, one with normal user privileges and one with admin privileges. With applications that require administrative privileges, the user can elevate the application to run with Administrator rights. And that process called Elevation.

As you expect, it’s the least-privilege principle well-recognized for security pros and people who use Linux.

User can elevate an application either by clicking “Run as Administrator” from the context menu of the application icon, or even by editing the Compatibility tab in the properties of the application file.
Also, while an application running it can ask the user to provide administrative permission to complete a specific operation (a good example is switching to the All Users mode in Task Manager).

Compatibility Options

Windows Vista keeps track of the compatibility options edited for an application by adding a compatibility flag to the registry at HKCUSoftwareMicrosoftWindows NTCurrentVersionAppCompatFlagsLayers.

Try changing any of the compatibility options for an application and see how Windows tracks that.

Because UAC feature of Windows Vista, it doesn’t allow users to access some folders like Program Files and Windows folder. Also it doesn’t allow them to access the registry without administrative permission.

But, there’re lots of applications that write lots of data to the Program Files folder for instance. And Windows Vista must keep them away from doing such these operations without administrative permission -you can imagine the amount of applications that require administrative privileges-. So to handle this dilemma, Windows Vista has a new technique called Virtualization.

When a program tries to write to the Program Files folder for instance, Windows Vista redirects it to a special virtual store so that the application can read/write data without generating errors (because of course it doesn’t have the permission).

As we would see in the next example Windows Vista uses this technique with registry too.

For folders, Virtualization called File Virtualization. For registry, it’s called Registry Virtualization.

File Virtualization

To see virtualization in action let’s try this example:

string programFiles =
    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
string appDir = Path.Combine(programFiles, "MyApplication");

if (Directory.Exists(appDir) == false)
    Directory.CreateDirectory(appDir);

string file = Path.Combine(appDir, "SampleFile.txt");

File.WriteAllText(file, "Hello, World!");

When you run the example it doesn’t write to C:Program FilesMyApplication. Instead it writes to the Program Files virtual store in C:UsersAppDataLocalVirtualStoreProgram FilesMyApplication

Note that if you are running your Visual Studio instance in elevated mode and run your application it gets the elevated mode from Visual Studio. So you need to run it manually from its icon.

Try changing the application so it writes to Windows folder. And check the virtual store folder.

Registry Virtualization

Virtualization is not only done with folders but also with registry entries. If the application tries to write to the registry key Software in HKEY_LOCAL_MACHINE hive, it is redirected to the HKEY_CURRENT_USER hive. Instead of writing to HKLMSoftware{Manufacturer}, it writes to the registry Virtual Store HKCUSoftwareClassesVirtualStoreMACHINESOFTWARE{Manufacturer}.

File and registry virtualization is available only for 32-bit applications. This feature is not available for 64-bit applications on Windows Vista.

Don’t use virtualization as a feature of your application. It is better to fix your application than to write to Program Files folder and the HKLM hive without elevated user privileges. Redirection is only a temporary means to fix broken applications.

Visual Basic 6.0 to be Supported on Windows 7

Contrary to widely circulated rumors, Visual Basic 6.0 will ship and will be supported on Windows 7 for the lifetime of the OS. Microsoft has released an updated support statement detailing the exact nature of ongoing support.

The Visual Basic team is committed to “It Just Works” compatibility for Visual Basic 6.0 applications on Windows Vista, Windows Server 2008 and Windows 7. The Visual Basic team’s goal is that Visual Basic 6.0 applications that run on Windows XP will also run on Windows Vista, Windows Server 2008 and Windows 7.

The Visual Basic team is also committed to the Visual Basic 6.0 development environment running on Windows Vista, Windows Server 2008 and Windows 7.

As detailed in the support document, the core Visual Basic 6.0 runtime will be supported for the full lifetime of Windows Vista, Windows Server 2008 and Windows 7, which is five years of mainstream support followed by five years of extended support, per the standard support agreement.

The support statement addresses Windows 7 directly:

Since the initial release of this support statement, the Windows 7 operating system has been announced. This document has been updated to clarify Microsoft’s support for VB6 on Windows 7.

VB6 runtime will ship and will be supported in Windows 7 for the lifetime of the OS. Developers can think of the support story for Vista being the same as it is for Windows 7. However there are no plans to include VB6 runtime in future versions of Windows beyond Windows 7.

Source- InfoQ

Creating Transacted Files

Lastly but not last, and after a long while, Windows Vista introduced a way to create transacted files or even to write to registry.

While market grows remarkably in the last years, its requirements increase as well. And every day you face a new problem that you must overcome to accommodate market requirements.

Transacted operations are one of the commonly demanded requirements by market.

While it’s true that you can easily do database operations transactionally, it’s not enough. Sometimes you will need to write files or make changes to registry in a transactional way.

With previous versions of Windows, you weren’t able to create a file transactionally without writing a huge amount of disorganized code to create it manually. You couldn’t use normal transactions or even COM+ Enterprise Services to create this type of transactions.

With Windows Vista you can easily create transacted files the common way you used to create normal files.

Unfortunately, from .NET 3.5 you cannot create transacted files. So you need to dive into API to create it.

Not Windows Vista only that supports this type of transactions, Windows Server 2008 also supports it.

Creating a transacted file function

To create a transacted file you can use the Kernel23.dll new function CreateFileTransacted.

This function takes the same arguments as the normal CreateFile function plus three more arguments that we are interested of the first one of them, the transaction handle that will be used while creating the file and writing to it.

The definition of this function in C is as follows:

HANDLE CreateFileTransacted(
    LPCTSTR lpFileName,
    DWORD dwDesiredAccess,
    DWORD dwShareMode,
    LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    DWORD dwCreationDisposition,
    DWORD dwFlagsAndAttributes,
    HANDLE hTemplateFile,
    HANDLE hTransaction,
    PUSHORT pusMiniVersion,
    PVOID pExtendedParameter);

We are interested in 6 parameters of these 9.

  • lpFileName:
    The path of the file being created.
  • dwDesiredAccess:
    Defines how file will be accessed. Read only (0x80000000), right only (0x40000000), or both read and write (0xC0000000).
  • dwShareMode:
    Defines the sharing mode -during the operation- for the file. Enabling reading file contents (0x1), writing to it (0x2), reading and writing (0x3), or deleting the file (0x4).
  • dwCreationDisposition:
    Action to take if file exist or do not exist. This argument can take one of the values:
    0x1: Create the file and throw an error if it exists.
    0x2: Always create the file even if it exists.
    0x3: Open the file and throw an error if it doesn’t exist.
    0x4: Open the file or create it if it doesn’t exist.
    0x5: Open the file and clear its contents. Or throw an error if it doesn’t exist.
  • dwFlagsAndAttributes:
    Any additional options. This can be a combination of file attributes like Archive, Hidden, and Encrypted. Also it supports combining options like deleting the file after closing it.
  • hTransaction:
    A handle to our created transaction that we wish to use it in this operation. To get the handle you may take a step further into COM.

Also there’re three arguments that we are not interested on, so you can safely pass it a NULL value:

  • lpSecurityAttributes:
    A SECURITY_ATTRIBUTES object contains an optional security descriptor information for the file.
  • hTemplateFile:
    A handle to a file to read it’s attributes and options to fill the arguments automatically.
  • pusMiniVersion:
    The miniversion to be opened. When creating transacted file -by specifying the hTransaction argument, this must be NULL.
  • pExtendedParameter:
    Reserved.

For a complete discussion of this API function, see MSDN Library.

PInvoking CreateFileTransacted API function

PInvoke is a service that enables you to call unmanaged functions in DLLs, such as those in the Win32 API like the CreateFileTransacted API function last mentioned.

PInvoke stands for Platform Invokation.

In order to PInvoke a function you need to know some things:

  1. Where this function resides (which DLL).
  2. Function definition and order of arguments -if found.-
  3. How to marshal between unmanaged types in .NET types.

Marshaling in .NET is the process of creating a bridge between new .NET types and legacy COM types. This is done by finding equivalents for those legacy types in the new data types or creating it if needed.

Most of the COM data types have equivalents in .NET, also it’s very easy to create your own.

For the function on hands we could write it in C# as following:

[DllImport("kernel32.dll")]
    public static extern
    IntPtr CreateFileTransacted(
    string lpFileName,
    uint dwDesiredAccess,
    uint dwShareMode,
    IntPtr lpSecurityAttributes,
    uint dwCreationDisposition,
    uint dwFlagsAndAttributes,
    IntPtr hTemplateFile,
    IntPtr hHandle,
    IntPtr pusMiniVersion,
    IntPtr pExtendedParameter);

Code explanation:
static extern modifiers are required for creating PInvoke functions.
DllImport attribute used to define the DLL that contains the function.
System.IntPtr is the managed type equivalent to unmanaged HANDLE.
LPCSTR can be easily replaced by the managed System.String.
In unmanaged code DWORD is a 32-bit unsigned integer, so we could safely replace it with System.UInt32.

Because we need to pass a NULL value to the LPSECURITY_ATTRIBUTES argument we marshaled it as IntPtr, so we can use IntPtr.Zero to pass NULL values.
We did that too with the last two arguments.

For creating the PInvoke methods easily, you could use the Red Gate’s PInvoke.NET Visual Studio add-in.
Also you should visit the interop wiki.

After we create our PInvoke method we can call it. But after that we need to create the transaction and get its handle to fill the arguments of the method.

To get a transaction handle we need to dive into COM and call a method to get the handle. This method is wrapped to .NET using COM Interop.

[ComImport]
[Guid("79427A2B-F895-40e0-BE79-B57DC82ED231")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IKernelTransaction
{ void GetHandle(out IntPtr ktmHandle); }

Don’t forget adding a using System.Runtime.InteropServices statement.

Now we can call the method:

private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
private const uint GENERIC_WRITE = 0x40000000;
private const uint CREATE_ALWAYS = 0x2;
private const uint FILE_SHARE_NONE = 0x0;

static void Main()
{
    using (TransactionScope scope = new TransactionScope())
    using (FileStream stream = CreateTransactedFile("D:SampleFile.txt"))
    using (StreamWriter writer = new StreamWriter(stream))
    {
        writer.WriteLine("Hello, World!");

        // To commit the transaction use the followind line
        scope.Complete();
    }
}

public static FileStream CreateTransactedFile(string fileName)
{
    IKernelTransaction ktx = (IKernelTransaction)
        TransactionInterop.GetDtcTransaction(Transaction.Current);

    IntPtr txHandle;
    ktx.GetHandle(out txHandle);

    IntPtr fileHandle =
        CreateFileTransacted(fileName,
        GENERIC_WRITE, FILE_SHARE_NONE, IntPtr.Zero,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
        IntPtr.Zero, txHandle, IntPtr.Zero, IntPtr.Zero);

    return new FileStream(fileHandle, FileAccess.Write);
}

Don’t forget adding a reference to System.Transactions and a using statement.

Code explanation:
Constants define the input for the function arguments.
In method CreateTransactedFile() we get the handle of the ambient transaction created in method Main(). Then we call the CreateFileTransacted() function which returns a pointer to the create file. Lastly we created the FileStream object with the created the file handle and used it to create a StreamWriter object to write textual data to the file.

Calling Commit() of the transaction object ensures that all operations completed successfully and now we can apply it. Otherwise, nothing would be done. That’s the main characteristic of transactions. All or nothing.

You don’t need to close the transaction handle manually because when disposing the TransactionScope object it will close its handle automatically.
If you are interested in closing it manually you can use the .NET wrapper System.Runtime.InteropServices.Marshal.Release() method. Or try the difficult way using the CloseHandle unmanaged handle.

Transactional support not limited to creating a file only. Most file system operation now support transactions, some examples are CopyFileTransacted, CreateDirectoryTransacted, CreateHardLinkTransacted, DeleteFileTransacted, MoveFileTransacted, RemoveDirectoryTransacted, and SetFileAttributesTransacted.

The complete example can be downloaded here.

Visual Studio 2010’s New Look Unveiled at VSLive!

Microsoft kicked off VSLive! San Francisco 2009 this week with more news about what’s planned for Visual Studio 2010.

In the keynote on Tuesday, Microsoft General Manager for Visual Studio Jason Zander showcased advances in the new VS 2010 user interface (UI) for the first time to VSLive! attendees.

“We’ve announced so far that we are using WPF for the new editor that we’ve put in place and made a lot of progress on that,” he said in a pre-show interview. “With this release of the product, we will be showing our overall new UI for the product.”

According to Zander, Microsoft has “modernized the look and feel for VS 2010” with a new UI built on WPF that rearranges file menus and commands at the top of the IDE. “We are making extensive use of the .NET Framework 4.0…as well as the WPF technology within the framework,” he said. “We’ve improved the way you can examine your source code, your project system, the hierarchies that you have and all the data stored in TFS, as well.” Screenshots of the new UI can be viewed at Zander’s blog.

Source- Redmond Developer News

Download SDK for Windows 7 and .NET Framework 3.5 SP1

The Windows SDK for Windows 7 and .NET Framework 3.5 SP1: BETA provides the documentation, samples, header files, libraries, and tools (including C++ compilers) that you need to develop applications to run on Windows 7 BETA and the .NET Framework 3.5 SP1.

To build and run .NET Framework applications, you must have the corresponding version of the .NET Framework installed. This SDK is compatible with Visual Studio® 2008, including Visual Studio Express Editions, which are available free of charge.

Download now…
http://www.microsoft.com/downloads/details.aspx?FamilyID=a91dc12a-fc94-4027-b67e-46bab7c5226c&DisplayLang=en

Search.Net – A site for .NET developers

Like most developers, I find myself spending a great amount of time searching for answers or solutions online, much of that time on Google and other search engines. SearchDotNet is a new search engine based on Google Custom Search technology that search the top .NET related sites and forums to help make searching more effective, while filtering out unrelated or duplicate content.

Site Features

  • OpenSearch support:
    If you’re using Firefox 2.0 or IE7 (or other OpenSearch client), you can add SearchDotNet to your list of search engines.
  • Google Gadgets:
    Add SearchDotNet to your website, Google home page or Google Desktop.
  • Component search engine:
    Distinct Custom Search Engine includes the sites of hundreds of component vendors.
  • Book site:
    Top rated .NET related books.

In addition you can recommend a site or even a book for SearchDotNET to inculde it in the searching progress.

Don’t wait, give it a shot! …. http://searchdotnet.com

Merge your assemblies using ILMerge

ILMerge is a utility that can be used to merge multiple .NET assemblies into a single assembly. ILMerge takes a set of input assemblies and merges them into one target assembly. The first assembly in the list of input assemblies is the primary assembly. When the primary assembly is an executable, then the target assembly is created as an executable with the same entry point as the primary assembly. Also, if the primary assembly has a strong name, and a .snk file is provided, then the target assembly is re-signed with the specified key so that it also has a strong name.

ILMerge is packaged as a console application. But all of its functionality is also available programmatically.

There are several options that control the behavior of ILMerge. See the documentation that comes with the tool for details.

The current version is 2.9.0210 (created on 10 February 2009). NOTE: There is no longer a version of ILMerge that runs in the v1.1 runtime.

The v2.0 version of ILMerge runs in the v2.0 .NET Runtime, but it is also able to merge v1 or v1.1 assemblies. However, it can merge PDB files only for v2 assemblies.

The v2 version of ILMerge was built with v2.0.50727 of the .NET Runtime. If you have an earlier version (e.g., Beta2 is v2.0.50215), then you need to use a config file: ILMerge.exe.config. (Copy the text from the browser and put into a file with that name. But check to see if you get any extraneous characters that the browser throws in. If so, please let me know and I’ll see what I can do.)

Currently, ILMerge works only on Windows-based platforms. It does not yet support Rotor or Mono.

If you use ASP.NET v2.0, then it provides a tool (based on ILMerge) to combine assemblies created during precompilation. You can get more details from the ASP.NET web site.

ILMerge Change History.

Download ILMerge (Current version is 2.8.0626):
http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en

Visit ILMerge Website:
http://research.microsoft.com/en-us/people/mbarnett/ILMerge.aspx

Microsoft Small Basic

Microsoft Small Basic

Small Basic is a project that’s aimed at bringing “fun” back to programming. By providing a small and easy to learn programming language in a friendly and inviting development environment, Small Basic makes programming a breeze. Ideal for kids and adults alike, Small Basic helps beginners take the first step into the wonderful world of programming.

  • Small Basic derives its inspiration from the original BASIC programming language, and is based on the Microsoft .NET platform. It is really small with just 15 keywords and uses minimal concepts to keep the barrier to entry as low as possible.
  • The Small Basic development environment is simple, yet provides powerful modern environment features like Intellisenseâ„¢ and instant context sensitive help.
  • Small Basic allows third-party libraries to be plugged in with ease, making it possible for the community to extend the experience in fun and interesting ways.

Go now and download Microsoft Small Basic 0.3.1 for Free:
http://www.microsoft.com/downloads/details.aspx?FamilyID=B006D58D-C2C7-44AD-936B-E7E2D7DE793E&displaylang=en

Also you may download Microsoft .NET Framework 3.5 SP1 as a reqirement for starting Microsoft Small Basic:
http://www.microsoft.com/downloads/details.aspx?FamilyId=AB99342F-5D1A-413D-8319-81DA479AB0D7&displaylang=en

Microsoft Small Basic Blog:
http://blogs.msdn.com/smallbasic/

Microsoft Small Basic is one of DevLabs projects. Checkout DevLabs projects:
http://msdn.microsoft.com/en-us/devlabs/dd125421.aspx

Microsoft Small Basic Snapshots:

Microsoft Small Basic Snapshot (0)
Microsoft Small Basic Snapshot (6) Microsoft Small Basic Snapshot (2) Microsoft Small Basic Snapshot (4)
Microsoft Small Basic Snapshot (3) Microsoft Small Basic Snapshot (5) Microsoft Small Basic Snapshot (1)

Creating/Extending a Culture

Haven’t you ever used a culture and want to extend it by changing e.g. the currency symbol? Haven’t you ever want to create a custom culture for formatting purposes? Answers will vary depending on the developer and the users targeted by his application.

Overtime, more and more cultures are started to be supported by the .NET Framework. However, not all cultures of the world are available in .NET. If you want to use a culture that is not available or you want to support a minority with a region you will need to create your custom culture.

Custom cultures and regions can be created with the class System.Globalization.CultureAndRegionInfoBuilder that resides in the assembly sysglobl.dll (you will need to reference it of course.)

Now, we are going to create a custom culture that extends the U.S. English culture. This culture is for New York. We’ll step further and change some of the characteristics of the base culture (en-US) to accommodate our needs for a good example.

We’ll start by referencing the assembly sysglobl.dll and add a using statement for the namespace System.Globalization.

sysglobl.dll is very tiny assembly. It contains only one class CultureAndRegionInfoBuilder and one enumeration CultureAndRegionModifiers that we will talk about it soon.

Next, we will instantiate a new instance of CultureAndRegionInfo class. That class is the key class for creating/extending a culture. Plus, it allows you to register/unregister your “baby.” It is required to register your custom culture on the system before you start using it.

CultureAndRegionInfoBuilder builder =
new CultureAndRegionInfoBuilder("en-US-NY",
CultureAndRegionModifiers.None);

The constructor of CultureAndRegionInfoBuilder class requires two parameters. The first is the name of the new culture. The second can one of the three values defined by the CultureAndRegionModifiers enumeration. And that parameter is used to identify the new culture.

The values of CultureAndRegionModifiers are:

  • None:
    For new cultures and the cultures that extends existing ones.
  • Neutral:
    For neutral cultures such as English, French, etc.
  • Replacement:
    For the cultures that you intend to be a replacement of existing culture in .NET Framework or even Windows. A replacement culture is like en-US that would replace the existing culture English (United States.)

In cultures world, there’s a unique name for every culture. And that name follows the naming convention xx-XX. The first lowercase xx is for language like en (English,) fr (French,) es (Spanish,) and so on. The second uppercase XX is for the country/region like US, FR, and ES. So an example like de-DE is the unique name German in Germany.

There’re exceptions to these rules. First, there’re languages like Dhivehi and Konkani that are abbreviated to three letters like div and kok. In addition, there’re two neutral cultures zh-CHS and zh-CHT for Simplified and Traditional Chinese; those have three letters for the country. In addition, there’re cultures that have the suffix -Cyrl and -Latn for defining the script Cyrillic or Latin. See RFC 1766 Standards.

After instantiating a new object of type CultureAndRegionInfoBuilder you need to initialize its properties with valid values. For the example in our hands, we will load the values from the parent culture en-US because we intend to extend it. Actually, there’s no rules to admit in loading the values for the new culture. You can load it from existing culture or you can write it yourself. In addition, we will set the Parent property to the parent culture that we wish to extend.

CultureInfo parent = new CultureInfo("en-US");
builder.LoadDataFromCultureInfo(parent);
builder.LoadDataFromRegionInfo(new RegionInfo("US"));
builder.Parent = parent;

You might review the properties of both CultureInfo and RegionInfo and compare it to the properties of CultureAndRegionInfoBuilder to know exactly why we are loading both objects.

Now comes the hardest part, changing the properties to accommodate our needs and setting the name of the new culture.

builder.RegionEnglishName = "New York";
builder.RegionNativeName = "New York";
builder.CultureEnglishName = "New York (United States)";
builder.CultureNativeName = "New York (United States)";
builder.NumberFormat.CurrencySymbol =  "*";

In the last few lines we changed the region “English” and its native name “English” to “New York”.

In addition, we changed the currency symbol from the dollar sign $ to an asterisk *.

Notice the difference between the English name and native name. The native name is the name of the culture in the native language that the culture is supposed to support. For example, “French” is the English name is and native name is “français”.

Here comes the hottest part, registering your new culture:

builder.Register();

You might get an exception of type InvalidOperationException if you tried to re-register it or if you chose a name that’s existed and you are not creating a replacement culture.

Now, Test your new culture:

CultureInfo newYork = new CultureInfo("en-US-NY");
double money = 100.99;
Console.WriteLine(money.ToString("C", newYork));
// "C" means currency formatting

Congratulations! You created a new culture and you can see it in action.

There’re some things that you need to take into account:

  1. You can unregister your created culture by using the static method Unregister of CultureAndRegionInfoBuilder class.
    CultureAndRegionInfoBuilder.Unregister("en-US-NY");
  2. After creating the desired culture and you don’t want to register it immediately (for example) you can save it as XML and load it later.
    // Saving the culture
    builder.Save("D:New York Culture.xml");
    // Loading the saved culture
    CultureAndRegionInfoBuilder.CreateFromLdml
    ("D:\New York Culture.xml");
  3. Windows saves the custom cultures you create in the folder %windir%Globalization.
  4. You are not ended using the custom culture in your .NET code only. You can go to Regional and Language Settings in Control Panel and change the culture to your created one and that affects the entire system.

Need more?

Links are subject to change if you found a bad link in our site please report it to us as soon as possible.

Download the example