Posts
133
Comments
328
Trackbacks
0
June 2010 Entries
Working with the Grid in SilverLight/WPF

I’ve been trying to wrap my head around the Grid in Silverlight/WPF today and decided that I’d share this with others. I made this diagram and the following xaml code snippet to remember how to position controls/etc in the grid.

From looking at the image below, we have a 3x3 Grid that starts at 0.

image

After you create a Grid, debugging is easier if you turn the ShowGridLines to true. Now its time to setup the RowDefinitions and ColumnDefinitions. We can create a button control now. You should pay special attention to the “Grid.Column” and “Grid.Row” properties of the button as they will determine where the button is placed in the control.

 

<Grid ShowGridLines="True">
    <Grid.RowDefinitions>
        <RowDefinition Height="60" />
        <RowDefinition Height="60" />
        <RowDefinition Height="60" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="175" />
        <ColumnDefinition Width="175" />
        <ColumnDefinition Width="175" />
    </Grid.ColumnDefinitions>
    <Button Grid.Column="0" Grid.Row="0" Content="Button 1" FontSize="18" Width="150" Height="45" />
    <Button Grid.Column="2" Grid.Row="0" Margin="10" Content="Button 2" FontSize="18" Width="150" Height="45" />
    <Button Grid.Column="1" Grid.Row="2" Margin="10" Content="Button 3" FontSize="18" Width="150" Height="45" />
</Grid>

 

This is what the XAML looks like in the VS2010 Editor with ShowGridLines turned on.

image

You can right click on the XAML file and open the file with Expression Blend 4 if you have it installed. Using Expression Blend it is much easier to drag/drop buttons and build the actual grid.

image

Posted On Wednesday, June 30, 2010 3:05 PM | Feedback (1)
Getting started with MVVM (General Info+Links)

OK, Lots of confusion around this pattern. I am also trying to wrap my head around this pattern and wanted to present what I have learned so far as well as my favorite links on the subject. I’m also working on a sample program that is from start-to-finish.

Model View ViewModel is usually called:

  • MVVM 
  • PresentationModel
  • or just the plain ViewModel
  1. It is just an architectural pattern for Silverlight of WPF.
  2. It is designed to allow Designers to focus on the user experience instead of the business logic
  3. It’s been around since 2005, but has just now taken off because of the success of WPF/Silverlight.
  4. UI Unit Testing

So what is it and why is it so scary for a beginner.

Model- A class file
View – Usually a user control
ViewModel – Another class file : Your user control will get its data from the ViewModel. Please see the image below:

image

Image taken from orbifold.net – please don’t sue me. =)

I am planning on creating an application that shows you how to build it from start/finish. If you can’t wait on mine, here is a silverlight MVVM app that contains a full project using the pattern. Stay tuned!

Articles for more information:

WPF Apps With The Model-View-ViewModel Design Pattern by Josh Smith.
Introduction to Model/View/ViewModel pattern for building WPF apps
Advanced MVVM Book (Cost $10 but was written by Josh Smith)
MVVM – It’s Not Kool-Aid*

Videos for more information about the pattern:

Hands-On Model-View-ViewModel (MVVM) for Silverlight and WPF –recommended to watch the one on SilverLight first.
MVVM, a WPF UI Design Pattern - Essential Edition

Libraries of classes useful when building applications based on the MVVM philosophy.

MVVM Foundation
MVVM Light Toolkit

Posted On Sunday, June 27, 2010 9:54 PM | Feedback (1)
TextBox Validation for alpha/numeric chars.

I’ve been answering this question over and over about TextBox validation on the MSDN forums. I wanted to post it on my blog as a point of reference for future users. Basically the question is, I have a textbox and want to restrict numeric values or alpha only. I’ve seen so many version of this involving Regular Expressions to some crazy alpha/numeric array searches. Below is the method that I am using in several production apps as well as community apps. I hope this helps the people on the MSDN forums as well as any one else.

 

//For limiting to access numbers
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 

{ 
 if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 

  e.Handled = true; 
 
 // To allow only one decimal point 
 if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 

    e.Handled = true; 
}

//For limiting to use alphabets
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e) 

{ 
 if (Char.IsLetter(e.KeyChar) || Char.IsSeparator(e.KeyChar) || Char.IsPunctuation(e.KeyChar)) 
  // Allow input. 
  e.Handled = false; 

 else 
  // Stop the character from being entered into the control since not a letter, nor punctuation, nor a space. 
  e.Handled = true; 

} 

To check for a certain numbers of characters in textbox.
Int n = Regex.Matches(TextBox1.Text, "[a-zA-Z]").Count;
Posted On Sunday, June 27, 2010 9:07 PM | Feedback (2)
Building a simple “About” Screen using FlowDocument [WPF]

I am using this blog to assist other beginner/intermediate developers with anything that deals with developing software. I also use this blog to help myself remember things or ideas. This is the first blog post on several ideas that I have using WPF and would like to share with the community. Some of my ideas may be crazy or far-fetched but I would like to think of myself as a little strange anyways.

This post is about using the FlowDocument to create an “About” box. First, an overview straight from Microsoft.

“A flow document is designed to "reflow content" depending on window size, device resolution, and other environment variables. In addition, flow documents have a number of built in features including search, viewing modes that optimize readability, and the ability to change the size and appearance of fonts. Flow Documents are best utilized when ease of reading is the primary document consumption scenario. In contrast, Fixed Documents are designed to have a static presentation. Fixed Documents are useful when fidelity of the source content is essential. See Documents in WPF for more information on different types of documents.

The following illustration shows a sample flow document viewed in several windows of different sizes. As the display area changes, the content reflows to make the best use of the available space.”

If most “About” boxes are text, that have some interactivity, then how would it look if we built our “About” box using the FlowDocument in WPF?

Below is an example of one that I created:

image

As you can see at the bottom of the screen you could flip pages, change the view, zoom in/out or even search for text on the screen. This method would only involve code for the click events (on the button for example). Everything else is done in pure xaml as shown below:

<Window x:Class="WPFExam.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="About" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="282" Width="245">
    <FlowDocumentReader>
        <FlowDocument FontSize="12">
            <Paragraph FontSize="14" TextAlignment="Center">About:</Paragraph>
        <Paragraph TextAlignment="Left" FontSize="12">
            Please continue to visit <Bold>http://michaelcrump.net</Bold> 
            for more tips/tricks on the .net framework. You can even have 
            interactive buttons like this one: <Button Content="Click me" Click="Button_Click_1"></Button>
        </Paragraph>
            <List>
                <ListItem><Paragraph>C#</Paragraph></ListItem>
                <ListItem><Paragraph>WPF</Paragraph></ListItem>
                <ListItem><Paragraph>Tools and Utilities 
                    for the .NET Developer</Paragraph></ListItem>
            </List>
            <Paragraph TextAlignment="Left" FontSize="12">
            You may also want to check out my <Italic> tools/utilities </Italic>
                for the .NET developer page at http://tools.michaelcrump.net. 
        </Paragraph>
        </FlowDocument>
    </FlowDocumentReader>
</Window>

Simple enough right? If you have any questions/suggestions/comments then please feel free to drop me a line on my contact page above.

Posted On Tuesday, June 22, 2010 1:21 PM | Feedback (1)
3 Things that I wish someone would have told me about WPF controls.

As you begin your WPF journey, you will have many frustrations with learning XAML. The three WPF control listed here were the things that frustrated me the most and I hope this helps someone out there.

1) Content controls such as the button can contain only a single nested element. But you can easily get around this with adding a StackPanel.

Not allowed!

image

Allowed!

image

2) Suppose you want to create a Mnemonic Keys and you are familiar with WinForms. Your first thought it to use “&Click Me”. In XAML, you create it with a “_” like “_Click Me”. This

Not allowed!

image

Allowed!

image

3) You should refer to the class name instead (Grid) when setting an attached property. If you refer to the instance name (grid1) it will not work.

Not allowed!

image

Allowed!

image

Posted On Friday, June 18, 2010 5:57 PM | Feedback (0)
Configuring Application/User Settings in WPF the easy way.

In this tutorial, we are going to configure the application/user settings in a WPF application the easy way. Most example that I’ve seen on the net involve the ConfigurationManager class and involve creating your own XML file from scratch. I am going to show you a easier way to do it. (in my humble opinion)

First, the definitions:

User Setting – is designed to be something specific to the user. For example, one user may have a requirement to see certain stocks, news articles or local weather. This can be set at run-time.

Application Setting – is designed to store information such as a database connection string. These settings are read-only at run-time.

1) Lets create a new WPF Project and play with a few settings. Once you are inside VS, then paste the following code snippet inside the <Grid> tags.

    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="12,11,0,0" Name="textBox1" VerticalAlignment="Top" Width="285" Grid.ColumnSpan="2" />
        <Button Content="Set Title" Name="button2" Click="button2_Click" Margin="108,40,96,114" />
        <TextBlock Height="23" Name="textBlock1" Text="TextBlock" VerticalAlignment="Bottom" Width="377" />
    </Grid>

Basically, its just a Textbox, Button and TextBlock. The main Window should look like the following:

image

 

2) Now we are going to setup our Configuration Settings. Look in the Solution Explorer and double click on the Settings.settings file. Make sure that your settings file looks just like mine included below:

 image

What just happened was the designer created an XML file and created the Settings.Designer.cs file which looks like this:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WPFExam.Properties {
    
    
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute
("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
        
        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
        
        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("ApplicationName")]
        public string ApplicationName {
            get {
                return ((string)(this["ApplicationName"]));
            }
            set {
                this["ApplicationName"] = value;
            }
        }
        
        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("SQL_SRV342")]
        public string DatabaseServerName {
            get {
                return ((string)(this["DatabaseServerName"]));
            }
        }
    }
}

The XML File is named app.config and looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" 
type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="WPFExam.Properties.Settings" type="System.Configuration.ClientSettingsSection, 
System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" 
requirePermission="false" />
        </sectionGroup>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="WPFExam.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <WPFExam.Properties.Settings>
            <setting name="ApplicationName" serializeAs="String">
                <value>ApplicationName</value>
            </setting>
        </WPFExam.Properties.Settings>
    </userSettings>
    <applicationSettings>
        <WPFExam.Properties.Settings>
            <setting name="DatabaseServerName" serializeAs="String">
                <value>SQL_SRV342</value>
            </setting>
        </WPFExam.Properties.Settings>
    </applicationSettings>
</configuration>

3) The only left now is the code behind the button. Double click the button and replace the MainWindow() method with the following code snippet.

        public MainWindow()
        {
            InitializeComponent();
            this.Title = Properties.Settings.Default.ApplicationName;
            textBox1.Text = Properties.Settings.Default.ApplicationName;
            textBlock1.Text = Properties.Settings.Default.DatabaseServerName;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.ApplicationName = textBox1.Text.ToString();
            Properties.Settings.Default.Save();
        }

Run the application and type something in the textbox and hit the Set Title button. Now, restart the application and you should see the text that you entered earlier.

 

image

If you look at the button2 click event, you will see that it was actually 2 lines of codes to save to the configuration file. I hope this helps, for more information consult MSDN.

Posted On Thursday, June 17, 2010 5:40 PM | Feedback (3)
10 Best Programming Podcast 2010 Edition

image image image image image

 image image image image image

This list is in no particular order. Just the 10 best programming podcast that I have found so far.

  1. Stack Overflow Podcast -  Jeff Atwood (of codinghorror.com) and Joel Spolsky (of joelonsoftware.com) discuss the development of their new programming community, StackOverflow.com.
    [This Podcast hasn’t been updated in a while, but its always great to hear more from Jeff Atwood]
  2. Hanselminutes - Hanselminutes is a weekly audio talk show with noted web developer and technologist Scott Hanselman and hosted by Carl Franklin. Scott discusses utilities and tools, gives practical how-to advice, and discusses ASP.NET or Windows issues and workarounds.
    [This Podcast has recently started talking about random topics like diabetes, plane travel and geek relationship tips.  I am not sure if Scott is trying to move to a more mainstream audience or not]
  3. Herding Code - A weekly discussion featuring K. Scott Allen (odetocode.com), Kevin Dente, Scott Koon (lazycoder.com), and Jon Galloway.
    [Great all all-around podcast that I would recommend to all]
  4. Deep Fried Bytes - Deep Fried Bytes is an audio talk show with a Southern flavor hosted by technologists and developers Keith Elder and Chris Woodruff. The show discusses a wide range of topics including application development, operating systems and technology in general. Anything is fair game if it plugs into the wall or takes a battery.
    [This is one that just keeps getting better]
  5. Dot Net Rocks - .NET Rocks! is an Internet Audio Talk Show for Microsoft .NET Developers.
    [One of the first and usually very high quality content]
  6. Connected Show - Connected Show Podcast! A podcast covering new Microsoft technology for the developer community. The show is hosted by Dmitry Lyalin and Peter Laudati.
    [This and Polymorphic are one of my favorite podcast – Dmitry is a great host and would recommend this to all]
  7. Polymorphic Podcast - Object oriented development, architecture and best practices in .NET
    [Craig is a ASP.NET MVP and a great presenter. His podcast is great and it could only be better if he recorded it more often]
  8. ASP.NET Podcast - Wallace B. (Wally) McClure presents interviews and short technical talks on .NET Technologies.
    [Has great information on ASP.NET of course as well as iPhone Dev]
  9. Ruby on Rails Podcast - News and interviews about the Ruby language and the Rails website framework.
    [Even though I am not a Ruby programmer, I’ve found this podcast very interesting]
  10. Software Engineering Radio - Software Engineering Radio is a podcast targeted at the professional software developer. The goal is to be a lasting educational resource, not a newscast. Every ten days, a new episode is published that covers all topics software engineering. Episodes are either tutorials on a specific topic, or an interview with a well-known character from the software engineering world. All SE Radio episodes are original content ? we do not record conferences or talks given in other venues. Each episode comprises two speakers to ensure a lively listening experience. SE Radio is an independent and non-commercial organization.
    [Another excellent podcast – I would recommend any programmer add this to his/her drive home]

If I have missed something, please feel free to email me and it might make the 2011 list. =)

Posted On Tuesday, June 15, 2010 6:40 PM | Feedback (5)
A .NET Developers day with the iPad.

The Apple iPad is currently getting a lot of buzz because of the app store, the book store and of course iTunes. I had the chance to play with one and this is what I have learned about the device.

Let’s get this out of the way first, the iPad is awesome. It is the device for media consumption and casual web browsing. But how does it measure up to those of us with .NET on our brains all days. Let’s find out…

Main Screen – you can customize everything on this page.

I guess I should replace that image with a C# or VS logo. Its pretty standard stuff if you have an iPhone.

IMG_0019

 

Programming Books

If you have a subscription to Safari Books Online, then you are in luck, its very easy to read the books on the iPad. Just fire up Safari web browser and goto the Safari Books Online. The biggest benefit that I can see with the iPad is the ability to read books wherever and not have to worry about purchasing books that I already have the .PDF for.

Below is a sample from Code Complete 2nd Edition.

IMG_0006

Below is a PDF of the ECMA-334 C# Language Specification. As you can see its very readable and you should have no problem reading actual code.

 IMG_0007

Example of Code shown below:

IMG_0008

It is however easier to read the PDF and store them with a 3rd party PDF reader. I have seen several for .99 cents or less.

You can however switch the screen to vertical to get more viewing space as shown below:

IMG_0009

I was disappointed with the iBooks application. I could not find a single .NET programming book anywhere. I was able to download the excellent sci-fi book “A memory of Wind” for free though. If I just overlooked them, then please email me with the names and titles. I couldn’t even find a technology category in the categories list.

IMG_0013

Web Surfing – Technical Sites

Below is an example of my site in Safari. The code is very readable and the experience was identical to viewing it in Firefox. I tried multiple programming site and the pages looked great except those that used flash and of course it did not display on those pages.

 IMG_0010

News Apps - Technical Content

The standard NY Times and USA Today looked great, but the Technical Content was lacking. It would probably be better to use Google Reader for online technical news.

  IMG_0012 

IMG_0014

YouTube Videos – Technical Content 

Since its YouTube, we already know that a lot of technical content exist and it plays great on the iPad. I watched several programming videos and could clearly see the code being written.

IMG_0015

Taking Technical Notes

The iPad comes with a great notepad for taking notes. I found that it was easy to take notes regarding projects that I am currently working on.

 IMG_0017

Calendar

The calendar that ships with the iPad is great for organizing. You can setup exchange server or manually enter the information. Pretty standard stuff.

 IMG_0018 

Random Applications that I like: TweetDeck.

 IMG_0020

and Adobe Ideas. Adobe Ideas is kinda like SketchFlow except you use your finger to mock up the sketches. 

IMG_0011

 

 

 

 

Don’t forget that the iPad is great for any type of podcasting. That pretty much sums it up, I would definitely recommend this device as it will only get better. I believe the iOS4 comes out on the 24th and the iPad will only get more and more apps. You could save a few bucks by waiting for the 2nd generation, but that’s a call that only you can make.

Posted On Saturday, June 12, 2010 2:36 PM | Feedback (0)
Garage Sale Code – Everything must go!

Garage Sale Code

image 

 

The term “Garage Sale Code” came from a post by Scott Hanselman. He defines Garage Sale Code as:

  • Complete – It’s a whole library or application.
  • Concise – It does one discrete thing.
  • Clear – It’ll work when you get it.
  • Cheap – It’s free or < 25 cents.
  • (Quite Possibly) Crap – As with a Garage Sale, you’ll never know until you get it home if it’s useless.

With the code I’ve posted here, you’ll get all 5 of those things (with an emphasis on crap). All of the projects listed below are available on CodePlex with full source code and executables (for those that just want to run it).  I plan on keeping this page updated when I complete projects that benefit the community.  You can always find this page again by swinging by http://garagesale.michaelcrump.net or you can keep on driving and find another sale.

Name Description Language/Technology Used
WPF Alphabet WPF Alphabet is a application that I created to help my child learn the alphabet. It displays each letter and pronounces it using speech synthesis. It was developed using WPF and c# in about 3 hours (so its kinda rough). C#, WPF
Windows 7 Playlist Generator This program allows you to quickly create wvx video playlist for Windows Media Center. This functionality is not included in WMC and is useful if you want to play video files back to back without selecting the next file. It is also useful to queue up video files to keep children occupied! C#, WinForms
Windows 7 Automatic Playlist Creator This application is designed to create W7MC playlist automatically whenever you want. You can select if you want the playlist sorted Alphabetical, by Creation Date or Random. C#, WinForms, Console
Generator Twitter Message for Live Writer This is a plug-in for Windows Live Writer that generates a twitter message with your blog post name and a TinyUrl link to the blog post. It will do all of this automatically after you publish your post. C#, LiveWriter API
Posted On Wednesday, June 02, 2010 7:51 AM | Feedback (1)
Tag Cloud