WPF Databinding- Part 2 of 3

 

This is a follow up to my previous post WPF Databinding- Not your fathers databinding Part 1-3 you can download the source code here  http://ssccinc.com/wpfdatabinding.zip

Example 04

 

In this example we demonstrate  the use of default properties and also binding to an instant of an object which is part of a collection bound to its container. this is actually not as complicated as it sounds.

First of all, lets take a look at our Employee class notice we have overridden the ToString method, which will return employees First name , last name and employee number in parentheses,

public override string ToString()
       {
           return String.Format("{0} {1} ({2})", FirstName, LastName, EmployeeNumber);
       }

 

in our XAML we have set the itemsource of the list box to just  “Binding” and the Grid that contains it, has its DataContext set to a collection of our Employee objects.

DataContext="{StaticResource myEmployeeList}">

…..

<ListBox Name="employeeListBox"  ItemsSource="{Binding }" Grid.Row="0" />

the ToString in the method for each instance will get executed and the following is a result of it.

image

if we did not have a ToString the list box would look  like this:image

now lets take a look at the grid that will display the details when someone clicks on an Item, the Grid has the following DataContext

DataContext="{Binding ElementName=employeeListBox,
           Path=SelectedItem}">

Which means its bound to a specific instance of the Employee object. and within the gird we have textboxes that are bound to different Properties of our class.

<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=FirstName}" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=LastName}" />
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=Title}" />
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding Path=Department}" />

 

Example 05

 

This project demonstrates use of the ObservableCollection and INotifyPropertyChanged interface.

Lets take a look at Employee.cs first, notice it implements the INotifyPropertyChanged interface now scroll down and notice for each setter there is a call to the OnPropertyChanged method, which basically will will fire up the event notifying to the value of that specific property has been changed.

Next EmployeeList.cs notice it is an ObservableCollection .

Go ahead and set the start up project to example 05 and then run. Click on Add a new employee and the new employee should appear in the list box.

 

Example 06

 

This is a great example of IValueConverter its actuall a two for one deal, like most of my presentation demos I found this by “Binging” ( formerly known as g---ing) unfortunately now I can’t find the original author to give him  the credit he/she deserves.

Before we look at the code lets run the app and look at the finished product, put in 0 in Celsius  and you should see Fahrenheit textbox displaying to 32 degrees, I know this is calculating correctly from my elementary school science class , also note the color changed to blue, now put in 100 in Celsius which should give us 212 Fahrenheit but now the color is red indicating it is hot, and finally put in 75 Fahrenheit and you should see 23.88 for Celsius and the color now should be black.

Basically IValueConverter allows us different types to be bound, I’m sure you have had problems in the past trying to bind to Date values .

First look at FahrenheitToCelciusConverter.cs first notice it implements IValueConverter. IValueConverter has two methods Convert and ConvertBack. In each method we have the code for converting Fahrenheit to Celsius and vice Versa.

In our XAML, after we set a reference in our Windows.Resources section. and for txtCelsius we set the path to TxtFahrenheit and the converter to an instance our FahrenheitToCelciusConverter converter. no need to repeat this for TxtFahrenheit since we have a convert and ConvertBack.

Text="{Binding  UpdateSourceTrigger=PropertyChanged,
           Path=Text,ElementName=txtFahrenheit,
           Converter={StaticResource myTemperatureConverter}}"

As mentioned earlier this is a twofer Demo, in the second demo, we basically are converting a double datatype to a brush. Lets take a look at TemperatureToColorConverter, notice we in our Covert Method, if the value is less than our cold temperature threshold we return a blue brush and if it is higher than our hot temperature threshold we return a redbrush. since we don’t have to convert a brush to double value in our example the convert back is not being implemented.

Take time and go through these three examples and I hope you have a better understanding   of databinding, ObservableCollection  and IValueConverter . Next blog posting we will talk about ValidationRule, DataTemplates and DataTemplate triggers.

webhost4life, please give me, my data back. My website will not work without the database.

 

I have about 4 or 5 accounts with WebHost4life.com, these are all my customers that based on my recommendation have been hosting with webhost4life.com. A few days ago for some reason they decided to migrate one of these accounts to a new server. They moved everything created a new database on the new server but the new database is empty. after spending hours with Tech support they acknowledged the problem and assured me it will take up to an hour or two and my database will be populated with the data. this was about 7 hours ago. Oh by the way I pay extra for the backup plan and yes you guessed it, none of my backups are there.

Needless to say I’m very scared and disappointed. No one is responding to my emails  or phone calls. After searching the web, I found out, this has happened before, in some cases it took them days to fix the problem and many never got it resolved and switched hosting companies, I would love to do that but I need my 2 GB database before I start shopping around for a new hosting company.

Stay away from Webhost4life.

WPF Databinding- Not your fathers databinding Part 1-3

 

As Promised here is my advanced databinding presentation from South Florida Code camp and also Orlando Code camp. you can find the demo files here.

http://ssccinc.com/wpfdatabinding.zip

Here is a quick description of the first demos, there will be 2 other Blogposting in the next few days getting into more advance databinding topics.

 

  • Example00
    • Here we have 3 textboxes,
      • The first textbox mySourceElement
      • Second textbox has a binding to mySourceElement and Path= Text
      • <Binding ElementName="mySourceElement" Path="Text"  />

         

      • Third textbox is also bound to the Text property but we use inline Binding
      • <TextBlock Text="{Binding ElementName=mySourceElement,Path=Text }" Grid.Row="2" />

        Here is the entire XAML

            <Grid  >  
                <Grid.RowDefinitions >
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <TextBox Name="mySourceElement" Grid.Row="0"
                         TextChanged="mySourceElement_TextChanged">Hello Orlnado</TextBox>
                <TextBlock Grid.Row="1">           
                    <TextBlock.Text>
                        <Binding ElementName="mySourceElement" Path="Text"  />
                    </TextBlock.Text>
                </TextBlock>
                <TextBlock Text="{Binding ElementName=mySourceElement,Path=Text }" Grid.Row="2" />
            </Grid>
        </Window>

  • Example01
    • we have a slider control, then we have two textboxes bound to the value property of the slider. one has its text property bound, the second has its fontsize property bound.
    • <Grid>
           <Grid.RowDefinitions >
               <RowDefinition Height="40px" />
               <RowDefinition Height="40px" />
               <RowDefinition Height="*" />
           </Grid.RowDefinitions>
           <Slider Name="fontSizeSlider" Minimum="5" Maximum="100"
                   Value="10" Grid.Row="0" />
           <TextBox Name="SizeTextBox"     
                    Text="{Binding ElementName=fontSizeSlider, Path=Value}" Grid.Row="1"/>
           <TextBlock Text="Example 01"
                      FontSize="{Binding ElementName=SizeTextBox,  Path=Text}"  Grid.Row="2"/>
      </Grid>

  • Example02
    • very much like the previous example but it also has a font dropdown
    • <Grid>
           <Grid.RowDefinitions >
               <RowDefinition Height="20px" />
               <RowDefinition Height="40px" />
               <RowDefinition Height="40px" />
               <RowDefinition Height="*" />
           </Grid.RowDefinitions>
           <ComboBox Name="FontNameList" SelectedIndex="0" Grid.Row="0">
               <ComboBoxItem Content="Arial" />
               <ComboBoxItem Content="Calibri" />
               <ComboBoxItem Content="Times New Roman" />
               <ComboBoxItem Content="Verdana" />
           </ComboBox>
           <Slider Name="fontSizeSlider" Minimum="5" Maximum="100" Value="10" Grid.Row="1" />
           <TextBox Name="SizeTextBox"      Text="{Binding ElementName=fontSizeSlider, Path=Value}" Grid.Row="2"/>
           <TextBlock Text="Example 01" FontFamily="{Binding ElementName=FontNameList, Path=Text}"
                      FontSize="{Binding ElementName=SizeTextBox,  Path=Text}"  Grid.Row="3"/>
      </Grid>

  • Example03
    • In this example we bind to an object Employee.cs
    • Notice we added a directive to our xaml which is clr-namespace and the namespace for our employee Class
    • xmlns:local="clr-namespace:Example03"

    • In Our windows Resources we create an instance of our object
    • <Window.Resources>
          <local:Employee x:Key="MyEmployee" EmployeeNumber="145"
                          FirstName="John"
                          LastName="Doe"
                          Department="Product Development"
                          Title="QA Manager" />

      </Window.Resources>

    • then we bind our container to the that instance of the data
    • <Grid DataContext="{StaticResource MyEmployee}">
              <Grid.RowDefinitions>
                  <RowDefinition Height="*" />
                  <RowDefinition Height="*" />
                  <RowDefinition Height="*" />
                  <RowDefinition Height="*" />
                  <RowDefinition Height="*" />
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions >
                  <ColumnDefinition Width="130px" />
                  <ColumnDefinition Width="178*" />
              </Grid.ColumnDefinitions>

          </Grid>

    • and Finally we have textboxes that will bind to that textbox
    •          <Label Grid.Row="0" Grid.Column="0">Employee Number</Label>
              <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=EmployeeNumber}"></TextBox>
              <Label Grid.Row="1" Grid.Column="0">First Name</Label>
              <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=FirstName}"></TextBox>
              <Label Grid.Row="2" Grid.Column="0">Last Name</Label>
              <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=LastName}" />
              <Label Grid.Row="3" Grid.Column="0">Title</Label>
              <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding Path=Title}"></TextBox>
              <Label Grid.Row="4" Grid.Column="0">Department</Label>
              <TextBox Grid.Row="4" Grid.Column="1" Text="{Binding Path=Department}" />
Visual Studio 2010 Beta 2 ReportViewer and Click Once.

 

First of all I have to say how excited I was to see the new reportviewer with VS2010 Beta 2, I have one application that has embedded reports in it up to this point we could not use the SSRS2008 reports with it, but now we can. So we included all the new reports that we have been using for our web app,  but couldn't use it with this version of application, to the project, next went to the prerequisites and checked Microsoft Visual studio 2010 Report Viewer.

 

image

After deploying the project we started getting calls from users apparently they were getting an error installing the package the error was

Setup has detected that the file 'C:\Users\Owner\AppData\Local\Temp\VSD98D7.tmp\ReportViewer\ReportViewer.exe' has changed since it was initially published.

I realized the default “install location” is Vendor’s web site. I figured the version of reportviewer that came with Beta 2 is older than the version on the server. After installing the latest reportviewer and republishing everything was fine and i was able to install it on the clients.

Sync Framework Power Pack for SQL Azure

 

We are working on a cloud based application for a long time existing customer.  we came across a pretty interesting challenge. The problem was; the New cloud based application needed to be able to integrate with  our existing legacy applications. in particular our call center application. We have no intentions of moving this application to the cloud, however we need to be able to have access to some of that data with our new Application.

Couple of weeks ago At PDC, during the Keynote Andy Lapin of Kelley Blue Book explained how they keep their community database up-to-date using the technology to synchronize data between their on-Premises SQL Server and SQL Azure. the recording is on PDC website, Andy’s demo starts at 1:18:00.

So finally I downloaded Sync Framework Power Pack for SQL Azure November CTP Available for Download. This release includes:

  • SQL Azure provider for Sync Framework.
  • Plug-in for Visual Studio 2008 SP1.
  • SQL Azure Data Sync Tool for SQL Server.

SQL Azure Data Sync Tool for SQL Server, contains a wizard that walks users through the SQL Azure connection process, automating the provisioning and synchronization operations between SQL Server and SQL Azure.

Here is a screen shot of the tool, Stay tuned for a webcast I will be doing on this, this Friday Dec 4th for Russ' Toolshed, If you are in Boca make sure to stop by and be part of the live audience.

image

Getting Started with windows Azure development

 

This is a follow up to my usergroup presentation I recently did for Gold Coast Usergroup recently. I have many emails, ok just 2 asking me to document my presentation so they can get started developing with windows Azure.

before you get started you need to make sure your development machine is running, Vista or Windows Server 2008 or my favorite windows 7, you also need to have IIS 7.0 with  WCF HTTP activation installed.

Next you will need to have Visual Studio 2008 or Visual Web Developer Express. please make sure you have the latest service packs  installed. This way you will have .NET .35 Sp1.

Next step is downloading all the necessary SDKs, the best way is to simply go to

clip_image001[7]

http://microsoft.com/azure and look for the link “Get tools & SDK” Download and install the SDK and Azure tools for Visual studio, while you are here you might want to bookmark this page, In addition  to tools and SDKs, there are tons of whitepapers and training videos and other resources available.

 

now we are ready to launch Visual Studio, since we installed windows azure tools for visual studio, we should be able to see windows Azure template projects under cloud Service. Lets select cloud Service, I’m going to name my solution MyFirstCloudApp. press OK and you should see the “New Cloud Service Project” window.

clip_image001[5]

Highlight “ASP.NET Web Role” and add it to your Cloud Service Solution by pressing > button, before pressing OK click on the pencil icon on the newly created ASP.NET web role to rename the project to MyCouldApp from the default WebRole1.

Two projects should have been created in your solution. MyCloadApp project is very similar to a standard ASP.NET web application project, but has been modified to work with Windows Azure.

View the contents of Servicedefinition.csdef and ServiceConfiguration.cscfg in the Project MyFirstCouldApp. 

 

clip_image001

 

The ServiceDefinition.csdef file contains the metadata needed by the Windows Azure fabric to understand the requirements of your application, such as which roles are used. It will also contain configuration settings that apply to all instances. .The ServiceConfiguration.cscfg file lets you set the values for the configuration settings and the number of instances to run for each role.


The Roles node in the Cloud Services project enables you to configure what roles the services include (Web, worker or both) as well as which projects are used for these roles.
Adding configuring roles through the Roles node will update the ServiceDefinition.csdef and ServiceConfiguration.cscfg files.

Open Default.aspx, and add some HTML I’m just going to add an THML tag <H1> and ASP Button and ASP Label control, idea here is that we are working with the ASP.net application .

Lets execute the service in Windows Azure by pressing F5 . The service will build and then launch the local development fabric

 

right click the Development Fabric icon in the system tray and seimagelect  Show Development Fabric UI.

click on the service Details view the service details, you should see a URL and IP address and port number, when you execute a windows Azure service it will try to allocate the port  specified in the ServiceDefinition.csdef if this port is not available, then next available port is used.

Click on the webrole and the instance 0, you should see the log for this instance.

switch back to visual studio and stop debugging, open ServiceConfiguration.cscfg and change the number of instances from 1 to 5, Press F5 and then switch to Development Fabric UI, now you should see 5 instances instead of one, you might have to refresh if you still see one instance.

Next week I will have another blog about deploying this app to the cloud.

Short cut keys in windows 7

 

So I finally installed windows 7 on my main laptop and I can’t tell you how happy I am, performance is so much better than Vista. Boot time and shut down processes are very quick. hibernate and resume are reliable and quick. But what I really like are all these cool shortcut Keys everyday seems like I find a new short cut key, here are a few of them.

windowkey.jpg

Win + L Quickly locks your computer, very useful.

Win + D Displays your desktop by minimizing all your open windows .

Win + R opens up the Run window so you can launch and application or paste a URL.

Win + T shows the first Item on your task list you can then navigate through them by using the arrow keys.

Win + U opens up the Ease of access window, here are some useful tools such as magnifier, but you can easily zoom in by pressing Win + ‘+’ and zoom out by pressing Win + ‘-‘ this is very useful specially when you are doing a presentation, which I do a lot of.

Win + P is also very useful for presentations. it gives you the projector shortcut keys

Win + S is really cool, if you are familiar with Snag it, well it does basically the same thing allows you to grab a portion of your screen then pastes it in One Note.

Win + E Opens the explorer window.

Win + F opens of the search window.

Win + X launches the Mobility window from there you can control the volume, check battery status, Wireless setting, projector settings and Sync settings

Win + N launches OneNote

Now some really cool shortcuts, some times I want to dock one of my apps to the right and another one to the left all you have to do is press Win + right or left arrow Key, this is really cool when you use multiple monitors.

Win + Up arrow will maximizes current window, Win + Down arrow will restore the current window if it is maximized, hit it again and will minimizes the active window.

you can maximize, restore or dock the active window simply by dragging it to the top or sides, or just grab any window by its title bar shake it a bit and it automatically will minimize all the other windows, call me a geek but I think this is really cool.

South Florida Code Camp News - Code Camp News for: Feb - 03 - 2009
We have all 72 sessions for this code camp booked and registrations should break 700 today. Please register yourselves and encourage others to register. You can find links on the website: http://codecamp09.fladotnet.com/

Using Words Spellcheck and grammer check with your windows Forms application

One of my customers wanted to add spell check functionality to their windows Form application.  knowing that everyone in their organization has Microsoft Office installed, I did not want to include word interop with the application. so I found a neat way of using words spellcheck. for more information you might want to check this article that was very helpful .

  Private Sub SpellAndGrammarCheck(ByVal YourTextbox As TextBox)

        Try

            Dim oWord As Object = Nothing

            Dim oDoc As Object = Nothing

            Dim oData As IDataObject = Nothing

            oWord = System.Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"))

 

           Dim  oDocuments as object = oWord.[GetType]().InvokeMember("Documents", _

                           BindingFlags.[Default] Or BindingFlags.GetProperty, _

                           Nothing, oWord, Nothing)

 

 

            oDoc = oDocuments.[GetType]().InvokeMember("Add", BindingFlags.[Default] _

                     Or BindingFlags.InvokeMethod, Nothing, oDocuments, Nothing)

            oWord.Visible = False

 

            oWord.WindowState = 0

            oWord.Top = -3000

            Clipboard.SetDataObject(YourTextbox.Text)

 

            With oDoc

                .Content.Paste()

                .Activate()

                .CheckGrammar()

                .Content.Copy()

                oData = Clipboard.GetDataObject

                If oData.GetDataPresent(DataFormats.Text) Then

                    YourTextbox.Text = CType(oData.GetData(DataFormats.Text), String)

                End If

                .Saved = True

                .Close()

            End With

            oWord.Quit()

            MsgBox("Spelling check complete!")

            'SPELLWORKING = True

        Catch COMEcep As COMException

            MsgBox("MS Word must be installed to perform spelling checks", , _

                   "Spell check is not available")

        Catch ex As Exception

            MsgBox("Error, Make sure you have MS word installed.", , ex.Message)

 

        End Try

End Sub

 

Using Words Spellcheck and grammer check with your windows Forms application

One of my customers wanted to add spell check functionality to their windows Form application.  knowing that everyone in their organization has Microsoft Office installed, I did not want to include word interop with the application. so I found a neat way of using words spellcheck. for more information you might want to check this article that was very helpful .

  Private Sub SpellAndGrammarCheck(ByVal YourTextbox As TextBox)

        Try

            Dim oWord As Object = Nothing

            Dim oDoc As Object = Nothing

            Dim oData As IDataObject = Nothing

            oWord = System.Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"))

 

           Dim  oDocuments as object = oWord.[GetType]().InvokeMember("Documents", _

                           BindingFlags.[Default] Or BindingFlags.GetProperty, _

                           Nothing, oWord, Nothing)

 

 

            oDoc = oDocuments.[GetType]().InvokeMember("Add", BindingFlags.[Default] _

                     Or BindingFlags.InvokeMethod, Nothing, oDocuments, Nothing)

            oWord.Visible = False

 

            oWord.WindowState = 0

            oWord.Top = -3000

            Clipboard.SetDataObject(YourTextbox.Text)

 

            With oDoc

                .Content.Paste()

                .Activate()

                .CheckGrammar()

                .Content.Copy()

                oData = Clipboard.GetDataObject

                If oData.GetDataPresent(DataFormats.Text) Then

                    YourTextbox.Text = CType(oData.GetData(DataFormats.Text), String)

                End If

                .Saved = True

                .Close()

            End With

            oWord.Quit()

            MsgBox("Spelling check complete!")

            'SPELLWORKING = True

        Catch COMEcep As COMException

            MsgBox("MS Word must be installed to perform spelling checks", , _

                   "Spell check is not available")

        Catch ex As Exception

            MsgBox("Error, Make sure you have MS word installed.", , ex.Message)

 

        End Try

End Sub