Search
Saturday, July 31, 2010 ..:: Home ::.. Register  Login
   Minimize

1. What language code would you like to see on our articles?

2. Are you implementing SQLXML on your applications?

3. How do you use XSLT's translations?

Submit Survey  View Results
  

 XML News Minimize

Building Web Applications with ACT and jQuery

My second talk at TechEd is focused on integrating ASP.NET AJAX and jQuery features into websites (if you’re interested in Silverlight you can download code/slides for that talk here). The content starts out by discussing ScriptManager features available in ASP.NET 3.5 and ASP.NET 4 and provides details on why you should consider using a Content Delivery Network (CDN).  If you’re running an external facing site then checking out the CDN features offered by Microsoft or Google is definitely recommended. The talk also goes into the process of contributing to the Ajax Control Toolkit as well as the new Ajax Minifier tool that’s available to crunch JavaScript and CSS files.

The extra fun starts in the next part of the talk which details some of the work Microsoft is doing with the jQuery team to donate template, globalization and data linking code to the project. I go into jQuery templates, data linking and a new globalization option that are all being worked on. I want to thank Stephen Walther, Dave Reed and James Senior for their thoughts and contributions since some of the topics covered are pretty bleeding edge right now.The slides and sample code for the talk can be downloaded below.  


image_418B5BFB1_47FBF5721_75802FD51_32D302891_66055791[1]

 

Download Slides and Samples

 Posted by dwahlin | Permanent link to this post Wed, 09 Jun 2010 18:52:48 GMT |  Comments (0)

Tales from the Trenches – Building a Real-World Silverlight Line of Business Application

There's rarely a boring day working in the world of software development. Part of the fun associated with being a developer is that change is guaranteed and the more you learn about a particular technology the more you realize there's always a different or better way to perform a task.

I've had the opportunity to work on several different real-world Silverlight Line of Business (LOB) applications over the past few years and wanted to put together a list of some of the key things I've learned as well as key problems I've encountered and resolved. There are several different topics I could cover related to "lessons learned" (some of them were more painful than others) but I'll keep it to 5 items for this post and cover additional lessons learned in the future. The topics discussed were put together for a TechEd talk:

  1. Pick a Pattern and Stick To It
  2. Data Binding and Nested Controls
  3. Notify Users of Successes (and failures)
  4. Get an Agent – A Service Agent
  5. Extend Existing Controls

The first topic covered relates to architecture best practices and how the MVVM pattern can save you time in the long run. When I was first introduced to MVVM I thought it was a lot of work for very little payoff. I've since learned (the hard way in some cases) that my initial impressions were dead wrong and that my criticisms of the pattern were generally caused by doing things the wrong way.

In addition to MVVM pros the slides and sample app below also jump into data binding tricks in nested control scenarios and discuss how animations and media can be used to enhance LOB applications in subtle ways. Finally, a discussion of creating a re-usable service agent to interact with backend services is discussed as well as how existing controls make good candidates for customization.

I tried to keep the samples simple while still covering the topics as much as possible so if you’re new to Silverlight you should definitely be able to follow along with a little study and practice. I’d recommend starting with the SilverlightDemos.View project, moving to the SilverlightDemos.ViewModels project and then going to the SilverlightDemos.ServiceAgents project. All of the backend “Model” code can be found in the SilverlightDemos.Web project. Custom controls used in the app can be found in the SivlerlightDemos.Controls project.

image_418B5BFB1_47FBF5721_75802FD51_32D30289[1]

 

Sample Code and Slides

 Posted by dwahlin | Permanent link to this post Tue, 08 Jun 2010 19:04:00 GMT |  Comments (2)

Final Release of Silverlight Tools for Visual Studio 2010 Released

If you haven’t already heard the news, the final release of the Silverlight Tools for Visual Studio 2010 have been released! That’s great news for Silverlight developers and to top it off the crew up at Microsoft even snuck in a few new features including intellisense for styles (a big deal in my opinion) and the ability to easily manipulate Grid rows and columns.  One of the most time consuming (and boring) tasks experienced by developers is also covered with the new “Go To Value Definition” feature that allows you to jump directly to style definitions with ease.  That feature alone is worth the upgrade especially if you’re working with a large application that uses a lot of styles.

Here’s a quick run-down of the features provided by the latest release from the Microsoft team:

  • Support for targeting Silverlight 4 in the Silverlight designer and project system
  • RIA Services application templates and libraries to simplify access to your data services (check out this Silverlight.tv video and whitepaper giving full details)
  • Support for Silverlight 4 elevated trust and out-of-browser applications
  • Enhanced support for other new Silverlight 4 features, including:
    • Working with Implicit Styles
      • Go To Value Definition - navigate directly from controls on your page to styles that are applied to them.
      • Style Intellisense - easily modify styles you already have in XAML
    • Working with Data Source Window outputs
      • Data Source Selector - easily select and modify your data source information
      • Grid Row and Column context menu - Add, remove, and re-sort DSW outputs and other Grid layouts
      • Thickness Editor for editing Margins, Padding etc.
    • Sample Data Support -  see your item templates and bindings light up at design time
    • Working with Silverlight 4 Out-of-Browser applications
      • Automatically launch and debug your OOB app from inside the IDE
      • Specify XAP signing for trusted OOB apps
      • Set the OOB window characteristics

If you’d like to see some of the new features in action check out this Channel 9 video with Mark Wilson-Thomas and John Papa.

 Posted by dwahlin | Permanent link to this post Tue, 18 May 2010 02:30:59 GMT |  Comments (2)

Integrating HTML into Silverlight Applications

Looking for a way to display HTML content within a Silverlight application? If you haven’t tried doing that before it can be challenging at first until you know a few tricks of the trade.  Being able to display HTML is especially handy when you’re required to display RSS feeds (with embedded HTML), SQL Server Reporting Services reports, PDF files (not actually HTML – but the techniques discussed will work), or other HTML content.  In this post I'll discuss three options for displaying HTML content in Silverlight applications and describe how my company is using these techniques in client applications.

Displaying HTML Overlays

If you need to display HTML over a Silverlight application (such as an RSS feed containing HTML data in it) you’ll need to set the Silverlight control’s windowless parameter to true. This can be done using the object tag as shown next:

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
    <param name="source" value="ClientBin/HTMLAndSilverlight.xap"/>
    <param name="onError" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="4.0.50401.0" />
    <param name="autoUpgrade" value="true" />
    <param name="windowless" value="true" />
    <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
         <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
    </a>
</object>


By setting the control to “windowless” you can overlay HTML objects by using absolute positioning and other CSS techniques. Keep in mind that on Windows machines the windowless setting can result in a performance hit when complex animations or HD video are running since the plug-in content is displayed directly by the browser window. It goes without saying that you should only set windowless to true when you really need the functionality it offers. For example, if I want to display my blog’s RSS content on top of a Silverlight application I could set windowless to true and create a user control that grabbed the content and output it using a DataList control:

<style type="text/css">
    a {text-decoration:none;font-weight:bold;font-size:14pt;}
</style>
<div style="margin-top:10px; margin-left:10px;margin-right:5px;">
    <asp:DataList ID="RSSDataList" runat="server" DataSourceID="RSSDataSource">
        <ItemTemplate>
            <a href='<%# XPath("link") %>'><%# XPath("title") %></a>
            <br />
            <%# XPath("description") %>
            <br />
        </ItemTemplate>
    </asp:DataList>
    <asp:XmlDataSource ID="RSSDataSource" DataFile="http://weblogs.asp.net/dwahlin/rss.aspx" 
        XPath="rss/channel/item" CacheDuration="60" runat="server" />
</div>

The user control can then be placed in the page hosting the Silverlight control as shown below. This example adds a Close button, additional content to display in the overlay window and the HTML generated from the user control.

<div id="RSSDiv">
    <div style="background-color:#484848;border:1px solid black;height:35px;width:100%;">
        <img alt="Close Button" align="right" src="Images/Close.png" onclick="HideOverlay();" style="cursor:pointer;" />
    </div>
    <div style="overflow:auto;width:800px;height:565px;">
        <div style="float:left;width:100px;height:103px;margin-left:10px;margin-top:5px;">
            <img src="http://weblogs.asp.net/blogs/dwahlin/dan2008.jpg" style="border:1px solid Gray" />
        </div>
        <div style="float:left;width:300px;height:103px;margin-top:5px;">
            <a href="http://weblogs.asp.net/dwahlin" style="margin-left:10px;font-size:20pt;">Dan Wahlin's Blog</a>
        </div>                
        <br /><br /><br />
        <div style="clear:both;margin-top:20px;">
            <uc:BlogRoller ID="BlogRoller" runat="server" />
        </div>                
    </div>            
</div>


Of course, we wouldn’t want the RSS HTML content to be shown until requested. Once it’s requested the absolute position of where it should show above the Silverlight control can be set using standard CSS styles. The following ID selector named #RSSDiv handles hiding the overlay div shown above and determines where it will be display on the screen.

#RSSDiv
{
    background-color:White;
    position:absolute;
    top:100px;
    left:300px;
    width:800px;
    height:600px;
    border:1px solid black;
    display:none;
}


Now that the HTML content to display above the Silverlight control is set, how can we show it as a user clicks a HyperlinkButton or other control in the application? Fortunately, Silverlight provides an excellent HTML bridge that allows direct access to content hosted within a page. The following code shows two JavaScript functions that can be called from Siverlight to handle showing or hiding HTML overlay content. The two functions rely on jQuery (http://www.jQuery.com) to make it easy to select HTML objects and manipulate their properties:

function ShowOverlay()
{
    rssDiv.css('display', 'block');
}

function HideOverlay()
{
    rssDiv.css('display', 'none');
}


Calling the ShowOverlay function is as simple as adding the following code into the Silverlight application within a button’s Click event handler:

private void OverlayHyperlinkButton_Click(object sender, RoutedEventArgs e)
{
    HtmlPage.Window.Invoke("ShowOverlay");
}


The result of setting the Silverlight control’s windowless parameter to true and showing the HTML overlay content is shown in the following screenshot:

clip_image002

 

Thinking Outside the Box to Show HTML Content

Setting the windowless parameter to true may not be a viable option for some Silverlight applications or you may simply want to go about showing HTML content a different way. The next technique I’ll show takes advantage of simple HTML, CSS and JavaScript code to handle showing HTML content while a Silverlight application is running in the browser. Keep in mind that with Silverlight’s HTML bridge feature you can always pop-up HTML content in a new browser window using code similar to the following:

System.Windows.Browser.HtmlPage.Window.Navigate(
    new Uri("http://silverlight.net"), "_blank");

For this example I’ll demonstrate how to hide the Silverlight application while maximizing a container div containing the HTML content to show. This allows HTML content to take up the full screen area of the browser without having to set windowless to true and when done right can make the user feel like they never left the Silverlight application. The following HTML shows several div elements that are used to display HTML within the same browser window as the Silverlight application:

<div id="JobPlanDiv">
    <div style="vertical-align:middle">
        <img alt="Close Button" align="right" src="Images/Close.png" onclick="HideJobPlanIFrame();" style="cursor:pointer;" />
    </div>
    <div id="JobPlan_IFrame_Container" style="height:95%;width:100%;margin-top:37px;"></div>
</div>


The JobPlanDiv element acts as a container for two other divs that handle showing a close button and hosting an iframe that will be added dynamically at runtime. JobPlanDiv isn’t visible when the Silverlight application loads due to the following ID selector added into the page:

#JobPlanDiv
{
    position:absolute;
    background-color:#484848;
    overflow:hidden;
    left:0;
    top:0;
    height:100%;
    width:100%;
    display:none;
}


When the HTML content needs to be shown or hidden the JavaScript functions shown next can be used:

var jobPlanIFrameID = 'JobPlan_IFrame';
var slHost = null;
var jobPlanContainer = null;
var jobPlanIFrameContainer = null;
var rssDiv = null;

$(document).ready(function ()
{
    slHost = $('#silverlightControlHost');
    jobPlanContainer = $('#JobPlanDiv');
    jobPlanIFrameContainer = $('#JobPlan_IFrame_Container');
    rssDiv = $('#RSSDiv');
});

function ShowJobPlanIFrame(url)
{
    jobPlanContainer.css('display', 'block');
    $('<iframe id="' + jobPlanIFrameID + '" src="' + url + '" style="height:100%;width:100%;" />')
        .appendTo(jobPlanIFrameContainer);
    slHost.css('width', '0%');
}

function HideJobPlanIFrame()
{
    jobPlanContainer.css('display', 'none');
    $('#' + jobPlanIFrameID).remove();
    slHost.css('width', '100%');
}


ShowJobPlanIFrame() handles showing the JobPlanDiv div and adding an iframe into it dynamically. Once JobPlanDiv is shown, the Silverlight control host has its width set to a value of 0% to allow the control to stay alive while making it invisible to the user. I found that this technique works better across multiple browsers as opposed to manipulating the Silverlight control host div’s display or visibility properties.

Now that you’ve seen the code to handle showing and hiding the HTML content area, let’s switch focus to the Silverlight application. As a user clicks on a link such as “View Report” the ShowJobPlanIFrame() JavaScript function needs to be called. The following code handles that task:

private void ReportHyperlinkButton_Click(object sender, RoutedEventArgs e)
{
    ShowBrowser(_BaseUrl + "/Report.aspx");
}

public void ShowBrowser(string url)
{
    HtmlPage.Window.Invoke("ShowJobPlanIFrame", url);
}

Any URL can be passed into the ShowBrowser() method which handles invoking the JavaScript function. This includes standard web pages or even PDF files. We’ve used this technique frequently with our SmartPrint control (http://www.smartwebcontrols.com) which converts Silverlight screens into PDF documents and displays them. Here’s an example of the content generated:

clip_image004

 

Silverlight 4’s WebBrowser Control


Both techniques shown to this point work well when Silverlight is running in-browser but not so well when it’s running out-of-browser since there’s no host page that you can access using the HTML bridge. Fortunately, Silverlight 4 provides a WebBrowser control that can be used to perform the same functionality quite easily. We’re currently using it in client applications to display PDF documents, SSRS reports and standard HTML content. Using the WebBrowser control simplifies the application quite a bit since no JavaScript is required if the application only runs out-of-browser.

Here’s a simple example of defining the WebBrowser control in XAML. I typically define it in MainPage.xaml when a Silverlight Navigation template is used to create the project so that I can re-use the functionality across multiple screens.

<Grid x:Name="WebBrowserGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Visibility="Collapsed">
    <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <Border Background="#484848" HorizontalAlignment="Stretch" Height="40">
            <Image x:Name="WebBrowserImage" Width="100" Height="33" Cursor="Hand" HorizontalAlignment="Right" 
                        Source="/HTMLAndSilverlight;component/Assets/Images/Close.png" 
                        MouseLeftButtonDown="WebBrowserImage_MouseLeftButtonDown" />
        </Border>
        <WebBrowser x:Name="JobPlanReportWebBrowser" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
    </StackPanel>
</Grid>


Looking through the XAML you can see that a close image is defined along with the WebBrowser control. Because the URL that the WebBrowser should navigate to isn’t known at design time no value is assigned to the control’s Source property. If the XAML shown above is left “as is” you’ll find that any HTML content assigned to the WebBrowser doesn’t display properly. This is due to no height or width being set on the control. To handle this issue the following code is added into the XAML’s code-behind file to dynamically determine the height and width of the page and assign it to the WebBrowser. This is done by handling the SizeChanged event.

void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
{
    WebBrowserGrid.Height = JobPlanReportWebBrowser.Height = ActualHeight;
    WebBrowserGrid.Width = JobPlanReportWebBrowser.Width = ActualWidth;
}


When the user wants to view HTML content they click a button which executes the code shown in next:

public void ShowBrowser(string url)
{
    if (Application.Current.IsRunningOutOfBrowser)
    {
        JobPlanReportWebBrowser.NavigateToString("<html><body><iframe src='" + url + "' style='width:100%;height:97%;' /></body></html>");
        WebBrowserGrid.Visibility = Visibility.Visible;
    }
    else
    {
        HtmlPage.Window.Invoke("ShowJobPlanIFrame", url);
    }
}

private void WebBrowserImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    WebBrowserGrid.Visibility = Visibility.Collapsed;
}

 

Looking through the code you’ll see that it checks to see if the Silverlight application is running out-of-browser and then either displays the WebBrowser control or runs the JavaScript function discussed earlier. Although the WebBrowser control’s Source property could be assigned the URI of the page to navigate to, by assigning HTML content using the NavigateToString() method and adding an iframe, content can be shown from any site including cross-domain sites. This is especially handy when you need to grab a page from a reporting site that’s in a different domain than the Silverlight application.

Here’s an example of viewing  PDF file inside of an out-of-browser application. The first image shows the application running out-of-browser before the user clicks a PDF HyperlinkButton.  The second image shows the PDF being displayed.

 

image


image

While there are certainly other techniques that can be used, the ones shown here have worked well for us in different applications and provide the ability to display HTML content in-browser or out-of-browser. Feel free to add a comment if you have another tip or trick you like to use when working with HTML content in Silverlight applications.

 

image_418B5BFB1_47FBF5721_75802FD5[1]


Download Code Sample

 


Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com.

 Posted by dwahlin | Permanent link to this post Tue, 11 May 2010 03:05:16 GMT |  Comments (23)

Text Trimming in Silverlight 4

Silverlight 4 has a lot of great features that can be used to build consumer and Line of Business (LOB) applications. Although Webcam support, RichTextBox, MEF, WebBrowser and other new features are pretty exciting, I’m actually enjoying some of the more simple features that have been added such as text trimming, built-in wheel scrolling with ScrollViewer and data binding enhancements such as StringFormat. In this post I’ll give a quick introduction to a simple yet productive feature called text trimming and show how it eliminates a lot of code compared to Silverlight 3.

The TextBlock control contains a new property in Silverlight 4 called TextTrimming that can be used to add an ellipsis (…) to text that doesn’t fit into a specific area on the user interface. Before the TextTrimming property was available I used a value converter to trim text which meant passing in a specific number of characters that I wanted to show by using a parameter:

public class StringTruncateConverter : IValueConverter
{

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int maxLength;
        if (int.TryParse(parameter.ToString(), out maxLength))
        {
            string val = (value == null) ? null : value.ToString();
            if (val != null && val.Length > maxLength)
            {
                return val.Substring(0, maxLength) + "..";
            }
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}


To use the StringTruncateConverter I'd define the standard xmlns prefix that referenced the namespace and assembly, add the class into the application’s Resources section and then use the class while data binding as shown next:

<TextBlock Grid.Column="1" Grid.Row="3" ToolTipService.ToolTip="{Binding ReportSummary.ProjectManagers}" 
            Text="{Binding ReportSummary.ProjectManagers, Converter={StaticResource StringTruncateConverter},ConverterParameter=16}" 
            Style="{StaticResource SummaryValueStyle}" />



With Silverlight 4 I can define the TextTrimming property directly in XAML or use the new Property window in Visual Studio 2010 to set it to a value of WordEllipsis (the default value is None):

<TextBlock Grid.Column="1" Grid.Row="4" ToolTipService.ToolTip="{Binding ReportSummary.ProjectCoordinators}" 
Text="{Binding ReportSummary.ProjectCoordinators}" TextTrimming="WordEllipsis" Style="{StaticResource SummaryValueStyle}"/>

The end result is a nice trimming of the text that doesn’t fit into the target area as shown with the Coordinator and Foremen sections below. My data binding statements are now much smaller and I can eliminate the StringTruncateConverter class completely. Plus, in situations where I have text that won’t all fit in a specific area I can take advantage of TextTrimming and also leverage the ToolTipService.ToolTip feature to show the full text as a user hovers over a TextBlock.

image

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com.

 Posted by dwahlin | Permanent link to this post Thu, 06 May 2010 06:00:52 GMT |  Comments (7)

Looking for more?

Browse all of the entries in the Dan Wahlin&#39;s WebLog archives

  

 Favorite Links Minimize
  

Copyright 2005 CodersOasis.com and HotMediaStudios.net   Terms Of Use  Privacy Statement
Portal engine source code is copyright 2002-2010 by DotNetNuke. All Rights Reserved