Silverlight

One Click CheckBox in a Silverlight DataGrid

by JBrooks 16. December 2011 09:54

I found this code on the internet to create a CheckBox in a DataGrid that wouldn’t require more than one click to change.  But it didn’t work for me.

<sdk:DataGridTemplateColumn>
    <sdk:DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <CheckBox IsThreeState="False" IsChecked="{Binding Path=IsActive, Mode=TwoWay}" 
                      HorizontalAlignment="Center" VerticalAlignment="Center" />
        </DataTemplate>
    </sdk:DataGridTemplateColumn.CellEditingTemplate>
</sdk:DataGridTemplateColumn>
The reason it didn’t work is because I also had this as part of my DataGrid
<sdk:DataGrid CurrentCellChanged="dgTotals_CurrentCellChanged" …

 

That method had a dgTotals.BeginEdit(); in it to allow the user to begin editing the DataGrid cells without having to first click on them.  The simple solution was to just skip that for my CheckBox column.

if(dgTotals.CurrentColumn != null && dgTotals.CurrentColumn.DisplayIndex != 1)
    dgTotals.BeginEdit();

Tags:

Development | Silverlight

Troubleshooting the Silverlight to RIA Services Connection

by JBrooks 6. December 2011 11:41

The first thing I do when troubleshooting a Silverlight startup error (like where it just has the startup progress bar sitting at 100% forever) is to make sure I can reach the RIA Service and it doesn’t return an error.

This example shows how to decode the URL back to the service:

http://localhost:1893/MWEntry5-Web-Services-ScheduleDomainService.svc

This is just the path delimited with dashes to the service as seen in your project and also with all of the periods changed to dashes and then just add “.svc” at the end.

clip_image001

You should see a page for the RIA Service if you put this URL in a browser.

When calling a method it is ClientBin first, followed by the name space, followed by “binary” and then your method name.  Here are 2 examples:

http://localhost:1893/ClientBin/MWEntry5-Web-Services-ScheduleDomainService.svc/binary/GetSchedulableEntities

http://MyDomain/MyWebApp/ClientBin/MyWebApp-Web-AuthenticationService.svc/binary/GetUser

I just needed to put this somewhere so I can reference it in the future.

Tags:

Silverlight | Development

.NET and Silverlight Rounding

by jbrooks 10. November 2011 09:09
In Excel 34.5 will round to 35 and in .NET it will round to 34. This is because .NET defaults to using the MidpointRounding.ToEven mode – also called banker’s rounding.  In .NET you have the option of overriding this by passing in the other MidpointRounding like:
 
    Math.Round(34.5, MidpointRounding.AwayFromZero);   // Now rounds to 35

A little annoying since in all of the applications that I’ve ever written the users expect rounding to match Excel’s and I’ve never needed the default. Worse, in Silverlight you don’t even have the option to change the default when using Math.Round().

So I had to write my own extension that can be used like:

 
    double myValue = 34.5;
    
    int myRoundedValue = (int) myValue.RoundCorrect(0);  // rounds to 35
 

Here is the extension code:

public static class DoubleExtensions
{
    public static double RoundCorrect(this double d, int decimals)
    {
        double multiplier = Math.Pow(10, decimals);
 
        if (d < 0)
            multiplier *= -1;
                                   
        return Math.Floor((d * multiplier) + 0.5) / multiplier;
    }
}

or if you want the code for a normal method it would be

public double RoundCorrect(double d, int decimals)
{
    double multiplier = Math.Pow(10, decimals);
 
    if (d < 0)
        multiplier *= -1;
 
    return Math.Floor((d * multiplier) + 0.5) / multiplier;
 
}

Tags:

Development | Silverlight

Changing the RIA Services Connection String for Different Environments.

by jbrooks 9. November 2011 07:24

On one project we keep our connection string as an AppSetting (See: HERE).  So that is what I use to build my RIA Services connection string to account for the differences between Dev, Test, QA and Prod.  You could also do the same with a regularly stored connection sting.  Here is how we did it:

public partial class MyDomainService
   {

       protected override MyEntities CreateObjectContext()
       {
           string ConnString = Common.cApp.AppSettings["DefaultConnection"];

           string seConn = ConfigurationManager.ConnectionStrings["MyEntities"].ToString();

           EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(seConn);
           ecsb.ProviderConnectionString = ConnString;

           EntityConnection ec = new EntityConnection(ecsb.ToString());

           ScheduleEntities ctx = new ScheduleEntities(ec);

           return ctx;

       }

   }

Tags:

Silverlight

MSBuild with Silverlight / RIA Services

by jbrooks 2. November 2011 09:36

I introduced a Silverlight project to my ASP.Net application and every thing worked fine in development but when I went to build it with out automatic build process MSBuild would kick out the following error:

[msbuild]   App.xaml.cs(2,17): error CS0234: The type or namespace name 'Services' does not exist in the namespace 'MyProject.Web' (are you missing an assembly reference?)

Had to change a registration key, the DefaultToolsVersion was set to 2.0, changed  it to 4.0

image

 

Ran the install selecting repair for the Silverlight 5.0 sdk (silverlight5_sdk.exe) – it was originally installed as part of the tool kit, but found others saying the real install still needed to be done to get it to work with MSBuild.

Next go the error:  error MSB4044: The "CreateRiaClientFilesTask" task was not given a value for the required parameter "ClientFrameworkPath"

Had to install EntityFramWork4.1 on my build server and then reboot.

Now on to the next problem.

Tags:

Silverlight | Development

Binding a Silverlight DataGrid’s ComboBox

by JBrooks 6. May 2011 07:13

Some things in Silverlight seem harder than they should be.  Binding a list of strings to a combobox is one such thing.  This involves the following steps to do a simple bind.

1. Have a private list of the strings in your page code.

 
private List<string> FuelList = new List<string>()
         {
             "OIL",
             "GAS",
             "COAL"
         };
 

2. In your initialization method add the list as a resource so your XAML can use it.  This must be done before the InitializeComponent(); call.

 
        public ucMyUserControl()
        {
            this.Resources.Add("FuelList", FuelList);
 
            InitializeComponent();
        }

 

3. Then you can reference the list as the source to you combo box.

<sdk:DataGrid AutoGenerateColumns="False"  MinHeight="130" Name="dgMyDataGrid" 
    ItemsSource="{Binding Path=ScheduleRows, Mode=TwoWay}"  
        CurrentCellChanged="dgMyDataGrid_CurrentCellChanged">
 
 
  <sdk:DataGrid.Columns>
     <sdk:DataGridTemplateColumn  Header="Fuel Type">
         <sdk:DataGridTemplateColumn.CellTemplate>
             <DataTemplate>
                  <TextBlock Margin="2" VerticalAlignment="Center"  
            HorizontalAlignment="Left" Text="{Binding FUEL_TYPE}" Width="120" />
             </DataTemplate>
             </sdk:DataGridTemplateColumn.CellTemplate>
                  <sdk:DataGridTemplateColumn.CellEditingTemplate>
                     <DataTemplate>
                         <ComboBox Height="23" Name="cbxFuelType" 
                                 ItemsSource="{StaticResource FuelList}"
                                 SelectedValue="{Binding Path=FUEL_TYPE, Mode=TwoWay}" Width="120">
 
                         </ComboBox>
                      </DataTemplate>
             </sdk:DataGridTemplateColumn.CellEditingTemplate>
        </sdk:DataGridTemplateColumn>
...

4. One last item, notice the datagrid’s current cell changed event is wired up to start editing without requiring the user to click first.  That method is simple enough:

private void dgMyDataGrid_CurrentCellChanged(object sender, EventArgs e)
  {
      dgMyDataGrid.BeginEdit();
  }

 

 

That gives me my datagrid with my combo box:

image

 

 

Here is a sample solution that has the full code: 

 ComboBoxTest.zip (1,016.17 kb)

Tags:

Development | Silverlight

Silverlight TextBox Watermark

by JBrooks 8. April 2011 07:45

The Silverlight TextBox does have a Watermark property, but Microsoft says “Do not use in a Silverlight 4 application” HERE.    So I looked into making one myself and it didn’t take much to do it. 

I just wanted the text box below to show the text “Search” in a grayed out way.

image

To do this it is just setting the forground color.

<TextBox Name="tbxSearch" Width="120" Text="Search" Foreground="#5A000000" 
    VerticalAlignment="Center" GotFocus="tbxSearch_GotFocus" />

 

I also wanted to reset the text to the normal color and to clear the text box when the user gave it focus.  Simple enough. If you notice above, the GotFocus event is wired up to the following method:

private void tbxSearch_GotFocus(object sender, RoutedEventArgs e)
{
    if (((SolidColorBrush)tbxSearch.Foreground).Color != Colors.Black)
    {
        tbxSearch.Text = "";
        ((SolidColorBrush)tbxSearch.Foreground).Color = Colors.Black;
    }
}

So that is it except that this should be made into a user control.

Tags:

Silverlight

Get a Reference to MainPage in a Silverlight Application

by JBrooks 30. November 2010 08:57

Once the user was logged in I wanted to change the menu options that are shown.  To do this I had to get a reference to MainPage.  Here is the code for that:

 
 
    MainPage m;
 
    if (Application.Current.RootVisual.GetType().Name == "BusyIndicator")
        m = (MainPage)((BusyIndicator)Application.Current.RootVisual).Content;
    else
        m = (MainPage)Application.Current.RootVisual;

The code below was a PREVIOUS TRY, but didn’t work because sometimes I would get an exception because the first Parent was null.  Didn’t have time to look into this, and thought the code had some value so I left it here for now.

========= PREVIOUS TRY ============================================================

First I created a static method in the App class that walks up the hierarchy of parents until it finds a match.  This can be used for more than just finding MainPage.  Everything in the hierarchy should be derived from the FrameworkElement class.

 
public static FrameworkElement GetParentByName(FrameworkElement currentPage, string ParentName)
        {
 
            FrameworkElement fe = (FrameworkElement)currentPage.Parent;
 
            // Walk your way up the chain of Parents until we get a match
            while(fe.GetType().Name != ParentName)
                fe = (FrameworkElement)fe.Parent;
 
            return fe;
 
        }

Then in the page Home I have the following code that calls that method.

 
private void Page_LayoutUpdated(object sender, System.EventArgs e)
{
    if (WebContext.Current.User.IsAuthenticated)
    {
        MainPage m = (MainPage)App.GetParentByName(this, "MainPage");
 
        m.LinkResetPassword.Visibility = System.Windows.Visibility.Collapsed;
        m.LinkChangePassword.Visibility = System.Windows.Visibility.Visible;
 
    }     
}

Tags:

Silverlight

Silverlight 3 for Business Applications

by JBrooks 28. July 2009 10:49

A few weeks ago I saw a demo of Silverlight 3 at the PhillyDotNet User Group - WOW. Wow for business applications, not graphic applications. There is a learning curve, but you get a lot for it. For example, the demo showed a grid being bound to a table without needing to write any code.

Right out of the box you had sorting, editing, paging, etc. But it wasn't the lame stuff you normally get and then have to rework. For example the paging was smart enough to write the sql that would only bring back the 20 rows you needed for the page.

The demo continued with him putting a detail form on the page for editing. Again no code, but it was smart enough to know that it had the same datasource as the grid on the page. So as you were moving row to row on the grid - the detail form was showing the current row (and it was very fast).

Both the grid and the detail form were editable and as you changed a field in one the other would reflect the new value. The editing was smart enough to validate the field on its own. So you couldn't put a letter in a field that was an integer type, etc. It also limited the number of characters that could be entered based on the column size found in the database. All the date fields on the detail form automatically had a calendar next to them. You get the idea - no coding for any of this.

If this weren't enough, it can be used to build occasionally connected applications. So he showed how he updated a few records on a few different pages, had the option to revert back a field later (ctrl-Z), and then at the end submitted all the changed records to be saved.

Also, they said it works with Linq2SQL and the entity framework.

Here is a link to a demo (not the one I saw.)  http://videos.visitmix.com/MIX09/T40F

 

Tags:

Silverlight