Monday, May 31, 2010

STEPS FOR XBAP SAMPLE DEPLOYMENT

The following are the steps for deploying the XBAP samples.

1. VIRTUAL DIRECTORY CREATION IN IIS

Create a Virtual Directory in local machine with local path. Please use the following steps to do this.

I. Open Internet Information Services (IIS) Manager. (Start -> Run -> inetmgr.exe).
II. Navigate to (Machine name -> Sites -> Default Web Sites).
III. Right click on “Default Web Sites” and select “Add Application option”.



IV. It will open “Add Application” dialog box. From this dialog box, please enter the “Alias” and “Physical Path”. Then Click OK button.




V. It will create a “Virtual directory” with the name of “Sample” to the physical path of “E:\Work\SourceCode\Version\Project\Control”.


2. WORKING SAMPLE APPLICATION WITH VS IDE


We should always work with Admin mode for deploying the XBAP application since we don’t have rights to access IIS in non-admin mode. Open VS IDE in Admin mode.




3. DEPLOYING SAMPLE APPLICATION


I. Open the solution file.

II. Do necessary changes in the application and build it.

III. Once the build get succeeded then open the properties of “Sample” application.

IV. From the properties window, go to Signing tab and make sure that “Sign the ClickOnce manifests” check box is checked. If not, select the certificate key from the Certificate storage.



V. Then navigate to “Security” tab and make sure that “This is a full trust application” radio button is in checked condition. Normally XBAP applications are run within a security sandbox to prevent untrusted applications from controlling local system resources. (E.g. deleting local files). In order to access local file system, port access, bitmap effects, etc., you need to run your application in “Full trust” mode.




VI. After that, select “Publish” tab and enter the publish location (Both local path and internet path where we would like to Run the application) and publish version information.




VII. Before that, make sure that the files needed to include with the application along with the published folder. This can be achieved with help of “Application Files” dialog by clicking the “Application Files” button.




VIII. We need to mention the “Prerequisites” to run our application. This will be provided by using “Prerequisites” dialog.




IX. Then provide the publishing details which will be shown in the main “index.htm” page.




X. Once you complete all above steps, please use publish wizard and publish the sample application.

4. DEPLOYING AN APPLICATION TO THE REMOTE SERVER
 I. Since we already given the internet URL while publishing the project application, we need to create a sample virtual directory in “Remote server’s IIS”. It will make URL available over the internet.

II. Then place the sample application’s (XBAP application) files and folder from local machine to the remote server.

Monday, May 17, 2010

How to get the DependencyObject under the mouse cursor?

With help of VisualTreeHelper and its HitTest() methods, we can easily find the DependencyObject under the mouse cursor. Use the following code snippet to achieve this.

    List<DependencyObject> hitTestList = null;

    //Raised When Mouse is entered inside Panel
    private void Panel_MouseEnter(object sender, MouseEventArgs e)
    {
        hitTestList = new List<DependencyObject>();       

        Point pt = e.GetPosition(sender as IInputElement);       

        VisualTreeHelper.HitTest(
            sender as Visual, null,
            CollectAllVisuals_Callback,
            new PointHitTestParameters(pt));       

        hitTestList.Reverse();

        DependencyObject elementToFind = null;
        foreach (DependencyObject element in hitTestList)
        {
            if (element.GetType().Name.Equals("ElementToFind"))
            {
                elementToFind = element;
                // ...
                // ...
            }
        }
    }

    HitTestResultBehavior CollectAllVisuals_Callback(HitTestResult result)
    {
        if (result == null || result.VisualHit == null)
            return HitTestResultBehavior.Stop;

        hitTestList.Add(result.VisualHit);
        return HitTestResultBehavior.Continue;
    }

Drop me a comment if you have any queries.

Friday, May 14, 2010

How to load Bitmap image to Image object in WPF

I am doing an application (which I am converting Windows forms 2.0 application into WPF application for rich look) in WPF and I am need of the load the Image from an instance of a System.Drawing.Bitmap. Initially I was struggled to do this. After a few minutes of search in goggle, I found the following solution. With help of Imaging class, we can create a BitmapSource and assign the BitmapSource value to the Image. The following code will help you to do this.

    public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
    {
        BitmapSource bitmapSrc = null;
        var hBitmap = source.GetHbitmap();
        try
        {
            bitmapSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
        catch (Win32Exception)
        {
            bitmapSrc = null;
        }  
        finally
        {
            NativeMethods.DeleteObject(hBitmap);
        }
        return bitmapSrc;
    }

    internal static class NativeMethods
    {
        [DllImport("gdi32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool DeleteObject(IntPtr hObject);
    }

Please check this link for more details.

Tuesday, May 4, 2010

How to close the whole application in WPF Browser based application (XBAP application)


In Windows based WPF application, there is an option to close the whole application using (Application.Current.ShutDown) statement. But the same statement is not working in Web based WPF application (perhaps it will close the application. But not close the IE browser – It showing with the blank inactive tab).  We have an option to close the application along with the IE window by using the following code,

    private void buttonClose_Click(object sender, RoutedEventArgs e)
    {
        WindowInteropHelper wih = new WindowInteropHelper(Application.Current.MainWindow);
        IntPtr ieHwnd = GetAncestor(wih.Handle, 2 /*GA_ROOT*/);
        PostMessage(ieHwnd, 0x10/*WM_CLOSE*/, IntPtr.Zero, IntPtr.Zero);
    }

    [DllImport("user32", ExactSpelling = true, CharSet = CharSet.Auto)]
    private static extern IntPtr GetAncestor(IntPtr hwnd, int flags);   

    [DllImport("user32", CharSet = CharSet.Auto)]
    private static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);

Wednesday, April 28, 2010

How to find the visual parent or child element using VisualTreeHelper

VisualTreeHelper is very useful class which help us to find or drill-down element from the hosted container.

The following method will help you to find the visual parent element from the container.

    public static T FindVisualParent<T>(UIElement element) where T : UIElement
    {
        UIElement parent = element;
        while (parent != null)
        {
            T correctlyTyped = parent as T;
            if (correctlyTyped != null)
            {
                return correctlyTyped;
            }
            parent = VisualTreeHelper.GetParent(parent) as UIElement;
        }
        return null;
    }

The following method will help you to find the child element from the container.

    public static T FindChild<T>(DependencyObject parent)where T : DependencyObject
    {
        if (parent == null) return null;

        T childElement = null;
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            T childType = child as T;
            if (childType == null)
            {
                childElement = FindChild<T>(child);
                if (childElement != null) break;
            }
            else
            {
                childElement = (T)child;
                break;
            }
        }
        return childElement;
    }

Friday, February 26, 2010

How to detect CTRL + ALT key combinations in WPF


Key combinations are a fancy pair of words to describe pressing/holding multiple keyboard buttons to perform a command.

Ex:- Few of ever using key combinations are,
  • Ctrl + S to Save,
  • Ctrl + C to Copy,
  • Alt + F4 to close an application,
  • Ctrl + Alt + Del to lock our computer, etc.,  
There are many such combinations, and while I provided some common ones, many applications like Visual Studio provide their own key combinations to help save you some time. Let's add some key combinations to our little program also.

    void SpecialKeyHandler(object sender, KeyEventArgs e)
    {
        // Ctrl + N
        if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.N))
        {
            MessageBox.Show("New");
        }

        // Ctrl + O
        if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.O))
        {
            MessageBox.Show("Open");
        }

        // Ctrl + S
        if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.S))
        {
            MessageBox.Show("Save");
        }

        // Ctrl + Alt + I
        if ((Keyboard.Modifiers == (ModifierKeys.Alt | ModifierKeys.Control)) && (e.Key == Key.I))
        {
            MessageBox.Show("Ctrl + Alt + I");
        }
    }

The key approach doesn't work for another reason because your commonly used Alt, Ctrl, Shift, and Windows keys can't be accessed from the Key enum at all. Instead, those four keys can only be accessed using the ModifierKeys enum and checking whether Keyboard.Modifiers is equal to that key.

Wednesday, December 30, 2009

How to enable .NET Framework 3.5 SP1 Bootstrapper package in ClickOnce application.

I have struggled with the issue which I was not able to include the .NET Framework 3.5 SP1 bootstrapper package in my click once WPF XBAP application. Even If the .NET Framework 3.5 SP1 bootstrapper package is selected in the Prerequisite dialog box for a Setup project or in ClickOnce publishing, and also the "Download prerequisites from the same location as my application" option is selected, the following build error is shown: 

The install location for prerequisites has not been set to 'component vendor's web site' and the file 'dotNetFx35setup.exe' in item 'Microsoft.Net.Framework.3.5.SP1' cannot be located on disk.

To resolve this issue, please do the following steps:

Update the Package Data

  1. Open the <Drive>:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFx35SP1 folder or %ProgramFiles(x86)%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFx35SP1 on x64 operating systems.
  2. Edit the Product.xml file in Notepad.
  3. Paste the following into the <PackageFiles> element:
    <PackageFile Name="TOOLS\clwireg.exe"/>
    <PackageFile
    Name="TOOLS\clwireg_x64.exe"/>
    <PackageFile
    Name="TOOLS\clwireg_ia64.exe"/>
  4. Find the element for <PackageFile Name="dotNetFX30\XPSEPSC-x86-en-US.exe" and change the PublicKey value to: 3082010A0282010100A2DB0A8DCFC2C1499BCDAA3A34AD23596BDB6CBE2122B794C8EAAEBFC6D526C232118BBCDA5D2CFB36561E152BAE8F0DDD14A36E284C7F163F41AC8D40B146880DD98194AD9706D05744765CEAF1FC0EE27F74A333CB74E5EFE361A17E03B745FFD53E12D5B0CA5E0DD07BF2B7130DFC606A2885758CB7ADBC85E817B490BEF516B6625DED11DF3AEE215B8BAF8073C345E3958977609BE7AD77C1378D33142F13DB62C9AE1AA94F9867ADD420393071E08D6746E2C61CF40D5074412FE805246A216B49B092C4B239C742A56D5C184AAB8FD78E833E780A47D8A4B28423C3E2F27B66B14A74BD26414B9C6114604E30C882F3D00B707CEE554D77D2085576810203010001
  5. Find the element for < PackageFile Name="dotNetFX30\XPSEPSC-amd64-en-US.exe" and change the PublicKey value to the same as in step 4 above
  6. Save the product.xml file

Download and Extract the Core Installation Files

  1. Navigate to the following URL: http://go.microsoft.com/fwlink?LinkID=118080
  2. Download the dotNetFx35.exe file to your local disk.
  3. Open a Command Prompt window and change to the directory to which you downloaded dotNetFx35.exe.
  4. At the command prompt, type:
    dotNetFx35.exe /x:
    This will extract the Framework files to a folder named “WCU” in the current directory.
  5. Copy the contents of the WCU\dotNetFramework folder and paste them in the %Program Files%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFx35SP1 folder (%ProgramFiles(x86)%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFx35SP1 on x64 operating systems).

Note: Do not copy the WCU\dotNetFramework folder itself. There should be 5 folders under the WCU folder, and each of these should now appear in the DotNetFx35SP1 folder. The folder structure should resemble the following:

ü  DotNetFx35SP1 (folder)

ü  dotNetFX20 (folder)

ü   dotNetFX30 (folder)

ü  dotNetFX35 (folder)

ü  dotNetMSP (folder)

ü  TOOLS (folder)

ü  en (or some other localized folder)

ü  dotNetFx35setup.exe (file)

6.       You may now delete the files and folders you downloaded and extracted in steps 2 and 4.

Please refer the following link for more details.

http://download.microsoft.com/download/A/2/8/A2807F78-C861-4B66-9B31-9205C3F22252/VS2008SP1Readme.htm#General%20Issues

Friday, December 18, 2009

How to read all countries using C#

We can use CultureInfo & RegionInfo class for getting all the countries information. From the CultureInfo class, we can get all the Culture information available in .Net Framework. Then we can use RegionInfo class for reading all the information about the region along with the Country name. Please use the following code snippet to achieve this.

static void Main(string[] args)
{
    List<string> countriesList = new List<string>();
    foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures))
    {
        if (!string.IsNullOrEmpty(culture.Name))
        {
            RegionInfo ri = new RegionInfo(culture.LCID);
            if (!countriesList.Contains(ri.EnglishName))
            countriesList.Add(ri.EnglishName);
        }
    }

    countriesList.Sort();           

    foreach (string str in countriesList)
        Console.WriteLine(str);          

    Console.ReadLine();
}


Wednesday, December 16, 2009

How to get all Culture information using C#

The CultureInfo class will provide us all Culture information available in .Net Framework.  You can use CultureInfo.Get­Cultures static method for getting all the culture information. To get associated specific culture, please use static method CultureInfo.Cre­ateSpecificCul­ture. 

The following example will show you how to get all culture information.

static void Main(string[] args)
{
     // Get culture names
     List<string> list = new List<string>();
     foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
     {
          string specName = "(none)";
          try { specName = CultureInfo.CreateSpecificCulture(ci.Name).Name;}
          catch(Exception) { }

          list.Add(string.Format("{0,-12}{1,-12}{2}", ci.Name, specName, ci.EnglishName));
     }

     list.Sort();

     Console.WriteLine("CULTURE  SPEC.CULTURE  ENGLISH NAME");
     Console.WriteLine("----------------------------------------------------");

     foreach (string str in list)
          Console.WriteLine(str);

     Console.ReadLine();
}

Tuesday, November 3, 2009

How to load the WPF controls dynamically at Runtime

In order to load the WPF controls dynamically at Runtime,  please do the following steps.

1. Create a dummy XAML content file (Dynamic_Content.xaml) with Controls details.
<StackPanel
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">


    <Button x:Name="buttonStart" IsEnabled="True" Content="Start" Height="25" Width="100" Margin="5" />
    <Button x:Name="buttonStop" IsEnabled="False" Content="Stop" Height="25" Width="100" Margin="5" />


</StackPanel>

2. Select the file (Dynamic_Content.xaml) in Solution Explorer and  go to the properties.

3. Set “Build Action” as “Content” and “Copy to Output Directory” as “Copy always”.

4. Then you can use XamlReader class for reading the XAML content which we have the controls.

5. Please use the following code to read and load controls from XAML content file.



private void tab_TabItemAdded(object sender, TabItemEventArgs e)
{
    FileStream stream = new FileStream(@"Dynamic_Content.xaml", FileMode.Open, FileAccess.Read);
    StackPanel panel = XamlReader.Load(stream) as StackPanel;

    e.TabItem.Content = panel;
    e.TabItem.Header = string.Format("Tab Item - {0}", tab.Items.Count);
    stream.Close();

    Button buttonStart = panel.Children[0] as Button;
    buttonStart.Click += new RoutedEventHandler buttonStart_Click);           
}


void buttonStart_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Start button invloked");
}

Friday, October 30, 2009

How to push certificate to "Trusted root certificate authorities" using Installer

In order to run your Full Trust enabled WPF XBAP application, you have to use “Self signed certificate authority file” for running and deploying XBAP application. The certificate should pushed it into “Trusted Publisher” and “Authority Root” certificate storages. You can use X509Certificate2 and X509Store classes in your installer assembly for pushing the certificate to certificate storage. Please use the following code snippet.


string certPath = string.Format(@"{0}\Aaa.cer", Environment.GetFolderPath(Environment.SpecialFolder.System));
X509Certificate2 certificate = new X509Certificate2(certPath);
X509Store trustedPublisherStore = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
X509Store trustedAuthorityRootStore = new X509Store(StoreName.AuthRoot, StoreLocation.LocalMachine);

try
{
     trustedPublisherStore.Open(OpenFlags.ReadWrite);
     trustedPublisherStore.Add(certificate);
     trustedAuthorityRootStore.Open(OpenFlags.ReadWrite);
     trustedAuthorityRootStore.Add(certificate);
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
}
finally
{
     trustedPublisherStore.Close();
     trustedAuthorityRootStore.Close();
}


Please refer the following link to know more about “WPF - XBAP as Full Trust Application