Poll

Which programming language do you prefer?
 
Feed Your Need!

About Me

My name is Romeo Dumitrescu

I am a Software Developer for Macadamian Technologies

Downloads

No Documents

Who's Online

We have 4 guests online
Technology
XBAP - Using the Popup Control as a Dialog Box PDF Print E-mail
User Rating: / 2
PoorBest 
Coding
Written by Romeo Dumitrescu
  
Monday, 11 May 2009 05:45

How many people have experienced the modal pop up in desktop applications? They are commonly used across a wide variety of applications, one could say, too commonly used. While not appropriate for all situations, sometimes you need to use a pop up.

In XBAP applications the ability to open a pop-up is very limited; in many cases you will use navigation and multiple pages instead of separate windows. In most cases this is sufficient, but sometimes you really need to use a pop-up, and when you do a simple work around is to use the Popup control offered by WPF.

First, you define the Popup in the markup, making sure to set its StaysOpen property to true so it will remain open until you close it. (There’s no point in using the PopupAnimation or AllowsTransparency properties, because they won’t have any effect in a web page.) Include suitable buttons, such as OK and Cancel, and set the Placement property to Center so the popup will appear in the middle of the browser window.

Code sample:

<Popup Name="dialogPopUp" StaysOpen="True" Placement="Center" MaxWidth="200">
    <Border>
        <Border.Background>
            <LinearGradientBrush>
                <GradientStop Color="AliceBlue" Offset="1"></GradientStop>
                <GradientStop Color="LightBlue" Offset="0"></GradientStop>
            </LinearGradientBrush>
        </Border.Background>
        <StackPanel Margin="5" Background="White">
            <TextBlock Margin="10" TextWrapping="Wrap">Please enter your name.
            </TextBlock>
            <TextBox Name="txtName" Margin="10"></TextBox>
            <StackPanel Orientation="Horizontal" Margin="10">
                <Button Click="dialog_boxOK_Click" Padding="3" Margin="0,0,5,0">OK</Button>
                <Button Click="dialog_boxCancel_Click" Padding="3">Cancel</Button>
            </StackPanel>
        </StackPanel>
    </Border>
</Popup>

At the appropriate time (for example, when a button is clicked), disable the rest of your user interface and show the Popup. To disable your user interface, you can set the IsEnabled property of some top-level container, such as a StackPanel or a Grid, to false. (You can also set the Background property of the page to gray, which will draw the user’s attention to Popup.) To show the Popup, simply set its IsVisible property to true.

Here’s an event handler that shows the previously defined Popup:

private void popupTriggerButton_Click(object sender, RoutedEventArgs e)
{
    DisableMainPage();
}
 
private void DisableMainPage()
{
    mainPage.IsEnabled = false;
    this.Background = Brushes.LightGray;
    dialogPopUp.IsOpen = true;
}

When the user clicks the OK or Cancel button, close the Popup by setting its IsVisible property to false, and re-enable the rest of the user interface:

private void dialog_boxOK_Click(object sender, RoutedEventArgs e)
{
    // Copy name from the Popup into the main page.
    lblName.Content = "You entered: " + txtName.Text;
    EnableMainPage();
}
 
private void dialog_boxCancel_Click(object sender, RoutedEventArgs e)
{
    EnableMainPage();
}
 
private void EnableMainPage()
{
    mainPage.IsEnabled = true;
    this.Background = null;
    dialogPopUp.IsOpen = false;
}

Using the Popup control to create this workaround has one significant limitation. To ensure that the Popup control can’t be used to spoof legitimate system dialog boxes, the Popup window is constrained to the size of the browser window. If you have a large Popup window and a small browser window, this could chop off some of your content. One solution is to wrap the full content of the Popup control in a ScrollViewer with the VerticalScrollBarVisibility property set to Auto.

If a Popup isn’t suitable for you, you can try another more “interesting” approach for showing a dialog box. Using the Windows Form library from .NET 2.0 you can safely create and host any WinForm control in your WPF application. In this case, you can create and show an instance of the System.Windows.Forms.Form class (or any custom form that derives from Form), because it doesn’t require unmanaged code permission. In fact, you can even show the form modelessly, so the page remains responsive. The only drawback is that a security balloon automatically appears superimposed over the form and remains until the user clicks the warning message. You’re also limited in what you can show in the form. Windows Forms controls are acceptable, but WPF content isn’t allowed.

 
Single Instance Applications in WPF PDF Print E-mail
Coding
Written by Romeo Dumitrescu
  
Thursday, 05 March 2009 13:20

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.

 
Starting device manager from C# app PDF Print E-mail
Coding
Written by Romeo Dumitrescu
  
Tuesday, 17 February 2009 19:18
// Show the device manager.
Process.Start("devmgmt.msc");
 
How many neural networks does it take to make a program speak? PDF Print E-mail
Coding
Written by Romeo Dumitrescu
  
Saturday, 31 January 2009 20:26

Well it seams that actually it needs only one. Today I finished implementing my first neural network on .NET. Things all good and well but my only trouble is with the contextual learning algorithm for the neurons.

Let me explain... For the last couple of years I've been playing around with the voice recognition and voice synthesizer engine from .NET trying to make myself a helping assistant. Of course, voice recognition and synthesizing is elementary but making the program actually understand the "meaning" of the expression it has to process is the hard part. So far I've built myself a static processing algorithm that processes specific instructions by context and replies to queries using grammar synthetic answers (easy and primitive) and just for fun I've named her Tanya. (Yes, it's a her)

But for the past few months Tanya has not been able to fulfill all requirements due to her lack of "meaningful" understanding and by this I mean actually understand what is requested and breaking down the query. To fix this, I needed to put some brains into her. The only solution was/is a neural network. While implementing the network base elements (axon, dendrites, neuron and synapse) was easy work (2 weeks), the learning algorithm is a big pain. The math is simple for most neural networks, but contextual learning is hard to implement. One of the things I used in making the "brain" gain some knowledge is a small open source algorithm that makes queering Wikipedia possible as if it was just another database. Also I had to use the MS SQL server dictionaries to make searching for information simpler (first query without the dictionaries finished in an hour and a half, which I wouldn't call instant). This assured that the grammars built in the voice recognition engine have some context to gather concreteness from. Of course, this is not nearly perfect. I still require a second network to interlink instructions with implemented plugins (basic stuff, SVN commands, computer state commands, file processing, etc.)

Anyway, if you've got the chance, take a couple of hours and experiment with neural networks cause you'll love them. I'll post the source code for Tanya soon (of course, without the neural network, which is impossible to export... your Tanya will need to start with a fresh network, which is relatively well usable about 200 or so queries - needs to learn context -. I'll include a file with some good commands that have raised my stats).

 
IsIn type extension PDF Print E-mail
Coding
Written by Romeo Dumitrescu
  
Wednesday, 21 January 2009 14:41

This small type extension checks wether a <T> value is in the checklist. Very useful...

public static bool IsIn<T>(this T value, params T[] checkList)
        {
            bool result = false;
            bool emptyList = (checkList == null || checkList.Length <= 0);
 
            if (emptyList && Equals(value, default(T)))
                result = true;
            else if (!emptyList)
                foreach (T item in checkList)
                    if (value.Equals(item))
                    {
                        result = true;
                        break;
                    }
 
            return result;
        }

 

Example:

string toSearch = "search";
bool found = toSearch.IsIn("This", "extension", "is", "used", "to", "search", "for", "values");

Due to the generic, this extension is not type bound and can be used with all value types. For other objects, different from primitives, you can extend this method with an IEquality comparer.

 
AppDev Free Technical Training PDF Print E-mail
Coding
Written by Romeo Dumitrescu
  
Friday, 16 January 2009 07:20

For some time now, I've been regularly visiting the AppDev site to checkout the new free and on-demand training courses from the AppDev experts. It is true that some of the videos there have titles that do not reflect the exact course aims (some of the "Advanced" topics there should be renamed to "Novice"), but I find that the quality is overall good.

I've directed a lot of friends towards the AppDev site because it covers good ground in it's courses and for most of them it's easier to download a well explained video course than to learn from books. (don't get me wrong, books and Google are the most important tools in a developer's arsenal, but books can be difficult if you've just started learning a programming language or don't have experience in software development)

If you've got the time, visit http://www.appdev.com/ I assure you that you won't be disappointed, regardless of your training level.

I'd love to get some feedback on this, if you can spare a moment or two, just post a comment to this article and state if you've found AppDev useful or not.

Cheers!

 
C# e-mail validation PDF Print E-mail
User Rating: / 2
PoorBest 
Coding
Written by Romeo Dumitrescu
  
Thursday, 15 January 2009 10:58

A friend of mine asked me yesterday how can one validate an e-mail address in C#.

He gave me the following snippet he was using:

public static bool IsValidEmailAddress(string sEmail)
        {
            if (sEmail == null)
            {
                return false;
            }
 
            int nFirstAT = sEmail.IndexOf('@');
 
            int nLastAT = sEmail.LastIndexOf('@');
            
            if ((nFirstAT > 0) && (nLastAT == nFirstAT) && (nFirstAT < (sEmail.Length - 1)))
            {
                // address is ok regarding the single @ sign
                return (Regex.IsMatch(sEmail, @"(\w+)@(\w+)\.(\w+)"));
            }
            else
            {
                return false;
            }
 
        }

While this works rather well, there is a simpler way:

public static bool IsValidEmailAddress(string sEmail)
       {
           try
           {
               MailAddress copy = new MailAddress(sEmail);
               return true;
           }
           catch
           {
               return false;
           }
       }

In order to use this, you'll need to add:

using System.Net.Mail; 

If you use the Regex solution, you have to make sure you consider all scenarios because, as we all know, e-mail addresses vary according to the domain mask and the e-mail identifier.
The above solution is much simpler and more efficient.

Explanation: If the MailAddress constructor fails to create an MailAddress object due to an invalid string, it will throw an FormatException exception.

You can extend this method by adding encoding and other options.

More info on the MailAddress Class can be found here: http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx

 
Visual Studio 2010 CTP Testing PDF Print E-mail
Coding
Written by Romeo Dumitrescu
  
Thursday, 15 January 2009 07:25

Today my curiosity got the better of me. It's been a while since Microsoft announced the CTP form of Visual Studio 2010 and seeing as I had a bit of spare time today, I started downloading the VS 10 VPC machine (7 GB total download size split in 11 parts) from the Microsoft Download Center.

I finished downloading very fast (for that download size and considering the numerous requests that MS is serving at the moment), total time was 1 hour and 7 minutes and started the virtual PC machine with ease.

As a note, Microsoft recommends that you assign a minimum of 1 GB RAM memory to the virtual machine, but I would recommend around 2 GB if you can spare them while testing. If you run it on 1 GB with a Vista edition operating system, things run slow and the enthusiasm for VS 2010 has to suffer.

As there are only a few features available (understandable seeing as this is a CTP), you don't need much time to be amazed with the new VS. Actually I consider it a breath of fresh air compared to the over populated UI of previous editions. Microsoft has done it's best to ensure a "comfortable" development environment for developers.

Will continue with screen shots and some comments. I'm too eager to get back to testing now.