Discussing the nuts and bolts of software development

Monday, March 09, 2009

 

Single Instance Applications in WPF

In some design scenarios launching multiple copies of the same WPF application is a problem, especially for document-based applications or server applications.

WPF does not provide a native solution for single instance applications; however there are several workarounds for this issue.

The most commonly used solution is to check whether another instance of the application is already running when the Application.Startup event fires. This is easily done using a system wide mutex (provided by the operating system to allow interprocess communication). While this is easily done, it limits the developer’s options by not providing a way for the new instance to communicate with the already running instance. Mainly this will provide only a simple way of limiting the number of running instances to one, while a separate system will be required to handle the new calls (usually through remoting or Windows Communication Foundation).

The recommended and more useful approach is to use the built-in support that’s provided in Windows Forms and originally intended for Visual Basic applications. This approach handles the messy plumbing behind the scenes. This means using an old style application class as wrapper for the WPF application. The wrapper will handle the instance management and will communicate the request to the already running instance of the WPF application.

Solution steps:

1) Add a reference to the Microsoft.VisualBasic.dll assembly.

2) Add a new custom class derived from the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class.

3) The IsSingleInstance must be set to true in the constructor. This enables a single instance application.

4) Override the OnStartup() method to create the WPF application object. (Note: The OnStartup() method is triggered when the application starts)

5) Overide the OnStartupNextInstance() method to handle future instances. (Note: The OnStartupNextInstance() method is triggered in when another instance of the application starts up)

6) Define a Main entry point for the application and create the wrapper object

7) Create the WPF application class

Sample of the application wrapper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.ApplicationServices;
using System.Windows;
 
namespace SingleInstanceApplication
{
    //The Main entry point class
    public class Startup
    {
        [STAThread]
        public static void Main(string[] args)
        {
            SingleInstanceAppWrapper wrapper = new SingleInstanceAppWrapper();
            wrapper.Run(args);
 
        }
    }
 
    //The old-style application wrapper
    public class SingleInstanceAppWrapper : WindowsFormsApplicationBase
    {
        public SingleInstanceAppWrapper()
        {
            // Enable single-instance mode.
            this.IsSingleInstance = true;
        }
 
        // Create the WPF application class.
        private WPFApplication _app;
 
        //Override OnStartup() method to create the WPF application object
        protected override bool OnStartup(
             Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
        {
            _app = new WPFApplication();
 
            _app.Run();
 
            return false;
 
        }
 
        // Override OnStartupNextInstance() to handle multiple application instances.
        protected override void OnStartupNextInstance(
             Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs e)
        {
            //In case of command line arguments, send them to the WPF application object    
            if (e.CommandLine.Count > 0)
            {
                _app.HandleCommandLine(e.CommandLine);
            }
 
 
        }
    }
}

As you can see, the sample above contains the Main entry point for the application. This is required because the wrapper must be created first.
If Visual Studio is used, by default the App.xaml application definition style is used. This will not work with the wrapper because the App.xaml approach already has a Main entry point.
Remove App.xaml and App.xaml.cs from the project and create a new class for the entry point.


The only thing left to do is to create the WPF application definition:



public class WPFApplication : System.Windows.Application
{
 
    //Override the OnStartup() method
    protected override void OnStartup(System.Windows.StartupEventArgs e)
    {
        base.OnStartup(e);
        
        //Load the main window
        Window _MainWindow = new Window();
        _MainWindow.Show();
 
        //Set the MainWindow property for the WPF application object
        this.MainWindow = _MainWindow;
 
    }
 
    //Method used to handle command line arguments
    public void HandleCommandLine (System.Collections.ObjectModel.ReadOnlyCollection<string> e)
    {
        //Code to handle command line arguments from other instances goes here
        
    }
 
}

Because the wrapper approach does not contain a XAML application definition (App.xaml), if you need to load application level resources, the following code can be placed the OnStartup() of the WPF application definition to load the resources from a resource dictionary:



 
        Application.Current.Resources.MergedDictionaries.Add(
            Application.LoadComponent(
                new Uri("AssemblyName;component/ApplicationResourceDictionary.xaml",
                UriKind.Relative)) as ResourceDictionary);

The above code will work for dynamic resource definitions. The static resource lookup process will fail because the source for the application resources dictionary need to be specified. In that case the code to load the resources will be replaced with the following:



Application.Current.Resources.Source = 
    new Uri("/AssemblyName;component/ApplicationResourceDictionary.xaml", UriKind.Relative);

Note: AssemblyName is a placeholder for the actual assembly name. The Uri for the resource dictionary location can be changed as required.

Labels: , , , , ,


Friday, September 12, 2008

 

Bridge SharePoint - User Profiles and User Profile Properties (part 2 of 2)

As we have found out in part 1, SharePoint can manipulate data using the user profile management objects and can accept data from external sources. Using these two features apart we have two limited tools with limited usage, but using them together gives us a powerful, flexible and efficient method of storing and using data from any internal or external resource.

It’s time to see this solution to our problems in action.

Code example of getting/setting the profile property from a C# application

The concept is the same for any source of information (web services, web applications, etc.):
Get the user’s profile->Get the required profile property->Get/Set profile property value

Code example: (note that to access profile properties, this code must run with elevated privileges)

string value;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{

// Change the site address for different deployment environments
// Note: WIN2003STD is a place holder for your environment, usually your server name
SPSite site = new SPSite("http://WIN2003STD/");
SPWeb web = site.OpenWeb();

// Get the profile manager object for the site
UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(site));

// Use the username from the User Information Item to get the full profile of an user
UserProfile user_profile = profileManager.GetUserProfile(System.Web.HttpContext.Current.User.Identity.Name);

// Get the required profile property value from the profile
value = user_profile["MyProperty"].Value.ToString();


});
}
catch (Exception e)
{
return "Error getting user info: " + e.Message.ToString();
}

user_profile["MyProperty"].Value gets or sets the profile property value.

This is a very convenient way of using profile properties to store required information for each user. Properties can be set as read-only or not to appear in the user’s profile, which gives you even more control.

System.Web.HttpContext.Current.User.Identity.Name returns the username (the login username) and it is used in the code example above to get the profile of the currently logged-in user.

Tools You Never Knew You Had… (and what to do with them now that you’ve wised up!)

With this simple solution to getting/setting a user’s profile property value, endless opportunities are now at hand. This small code snippet helps developers control, validate and use values stored for each user, without corrupting the database or resorting to other more complex and error-prone solutions.
For those not needing to use an external application to get information from the users, a custom SharePoint web application can be developed and deployed on SharePoint. This way all the controls offered by ASP .NET or custom controls can be used to perform required operations on the data before it’s stored.

External applications running on the server can access this information the same way, so a bridge between SharePoint and applications like web sites, game servers, messaging apps, etc. can be easily created.

SharePoint Complications, As Usual

Watch out that the profile property might be set as read-only in SharePoint. Even if it’s the case however, the above code should still be able to access the profile because it’s running with elevated privileges. So if there is a situation in which the user is allowed to see the data but only modify it by using a service (like a web application or web service), this is a good way of doing it.

Another gotcha is that the code above can only be used on the SharePoint server machine. This is due to the framework that SharePoint uses. To get information or to change data from a network on internet location, a SharePoint custom web service or web application can come in handy. Other ways of passing information will work too, like server-client applications, as long as the part running the above code is on the SharePoint server machine.

So we now have a way to store data and manipulate it according to our needs. We can control it, we can validate it and most important of all, we decide how the user interacts with the data.

We’re now ready to start doing some serious SharePoint development!

Labels: , , , , ,


Wednesday, May 14, 2008

 

Chmod-me Win32 - A quick look at NTFS file system permissions

Even if NTFS is the de-facto standard file system on Windows machines today, the NTFS security model uses a set of concepts that are somewhat unfamiliar to most of us or may seem familiar until we actually use them, programmatically.

A while ago, I installed a C++ application I wrote using a local administrator account on an WinXP machine. Later, I tested the application using a restricted user account and got into a situation where a "config.ini" file, copied to the Windows shared application data folder the first time the application was launched, couldn't be modified. I quickly figured that fixing the problem would just be a matter of setting the proper "config.ini" file permissions since the file, being initially copied in an Administrator security context, wouldn't have the proper permissions to be modified by a restricted user.
In the Unix world, a shell command called 'chmod' sets file access permissions for user and groups. It's simple easy, simple, effective and on a C++ program, a single system call is all you need.
Now in Windows, the NTFS security model has a much finer grain, so there's multiple things to consider:

1) In NTFS permission are chained in a list, for files permissions that list is a Discretionary Access Control List (DACLs).

2) An Access Control List contain one or more Access Control Entries (ACE) which allows to grant or deny specifics permissions. Since file permissions can inherit permissions from parent folders (provided the parent folder allows permissions to be inherited), file permission can either be granted or denied.

3) An ACE uses Security Identifiers (SIDs) to identify a user or group.

To change the permission of a single file in a Win32 C++ program, you may end-up coding something like this:

Notes:
1) For the sake of clarity, only the *Unicode* character set is used in this example.
2) The header files "AclApi.h" and "Sddl.h" are required."
3) _WIN32_WINNT 0x0500" needs to be added to your project "Preprocessor Definitions" settings.
/*******************************************************************************
*
* FUNCTION SetFilePermissions
*
* DESCRIPTION Sets file permissions for a specific file
*
* PARAMETERS string filename: full pathname of the file to change permissions
* string username: name of a user or a group
* int permissions: can be one or more of the following:
* {GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE OR GENERIC_ALL}
*
* If a permission is omitted and is currently associated
* with the specified file, it will be removed,
* unless that permission is inherited.
*
* RETURNS non-zero if succeeds, zero if it fails.
* Use GetLastError() to get extended the error information.
*
******************************************************************************/
bool SetFilePermissions(LPCWSTR filename, LPCWSTR username, int permissions)
{
SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY;
EXPLICIT_ACCESS eAcc;

PSID pSid = NULL;
PACL dacl = NULL;
int lRes = ERROR_SUCCESS;

eAcc.grfAccessMode = GRANT_ACCESS;
eAcc.grfAccessPermissions = permissions;
eAcc.grfInheritance = OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE;
eAcc.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
eAcc.Trustee.pMultipleTrustee = NULL;
eAcc.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;

// NOTE: In some cases, you will want to use a "well-known security identifiers"
// (http://support.microsoft.com/kb/243330) instead of a username or group
// since SIDs remain the same from one operating system language to another.
if( ConvertStringSidToSid(username, &pSid) )
{
eAcc.Trustee.TrusteeForm = TRUSTEE_IS_SID;
eAcc.Trustee.ptstrName = static_cast(pSid);
}
else
{
// Reset lasterror since ConvertSidToStringSid() is also used
// to determine if a username is a SID or not.
SetLastError(0);
eAcc.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
eAcc.Trustee.ptstrName = const_cast(username);
}

// Create a DACL
lRes = SetEntriesInAcl(1, &eAcc, NULL, &dacl);
if (lRes == ERROR_SUCCESS)
{
// Set DACL
lRes = SetNamedSecurityInfo( const_cast(filename), SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION, NULL, NULL, dacl, NULL);
}

if (pSid != NULL)
LocalFree((HLOCAL)pSid);

if (dacl != NULL)
LocalFree((HLOCAL)dacl);

return lRes == ERROR_SUCCESS;
}

int wmain(int argc, WCHAR* argv[])
{
// As an example, let's allow "Read" and "Write" permissions to the group
// "Everyone" for the file "myconfig.ini". Since the actual name "Everyone"
// depends on the actual operating system language, we'll use its
// matching SID string representation (S-1-1-0) instead.
bool success = SetFilePermissions(
L"C:/Documents and Settings/All Users/Application Data/myapp/myconfig.ini",
L"S-1-1-0", GENERIC_READ | GENERIC_WRITE);

// For security purposes, It might make more sense to allow only
// authenticated users ( SID: S-1-5-11 ) instead of the group "Everyone".

return !success; // zero means the program ran successfully
}
The Windows security model isn't trivial, but fortunately some good articles have been published on the subject. The following gives a good overviews of permissions precedence and this one provides more details about ACL Inheritance. For a more in-dept API coverage, please refer to the MSDN documentation .

You if are in a hurry you can always get away by using the real Microsoft chmod command line equivalent - CACLS.EXE in a script.

Happy Chmoding - Thanks Mikhail for your input.

Labels: , , ,


This page is powered by Blogger. Isn't yours?