Blogs

The Progress Bar - DevExpress XPF Blog

January 2011 - Posts

  • Silverlight Grid Control – Video Tutorial on How to Bind, Edit, and Save data using RIA Services

         

    Last week I posted a tutorial on how to use a combo box editor control to update and save the data for a field. As that tutorial referenced previous posts, I decided to create a training video that demonstrates how to go from a new application to one with a bound DXGrid Silverlight control and the ability to update and save data using a combo box in-place editor.

    Click the image below to watch the video:

    DevExpress_Silverlight_Grid_BindEdit_Video

  • Silverlight Data Grid – Binding, Editing, Saving Data Using WCF RIA Services

         

    I have covered data binding the Silverlight Grid Control using WCF RIA Services in the past, but have left out a common scenario where a user might need to update cells using in-place editors and save that data back to the data source.

    So in this blog post, we’re going to take a look at how to use the combo box editor to change the data for a field and then save that change back to the database. Here I’m assuming the presence of a DXGrid for Silverlight control bound to the “Products” table of the sample Northwinds database. The “ProductName” column should have a combobox in-place editor as well. If you are just starting out, I recommend reading the following posts first before you proceed further:

    1. Silverlight Grid Control - Data Binding using RIA Services
    2. Silverlight Grid Control – How to Embed Editors

    Updates do not occur automatically, so to save each change, I need a mechanism where the whole process is correctly automated. I’ll do this by handling the HiddenEditor and RowUpdated events of the TableView.

    1. <dxg:GridControl Name="gridControl1">
    2.     <dxg:GridControl.View>
    3.         <dxg:TableView AutoWidth="True" Name="tableView" HiddenEditor="tableView_HiddenEditor" RowUpdated="tableView_RowUpdated" />
    4.     </dxg:GridControl.View>
    5.     <dxg:GridControl.Columns>
    6.         <dxg:GridColumn FieldName="ProductName" Header="Product Name">
    7.             <dxg:GridColumn.EditSettings>
    8.                 <dxe:ComboBoxEditSettings DisplayMember="ProductName" ValueMember="ProductName" />
    9.             </dxg:GridColumn.EditSettings>
    10.         </dxg:GridColumn>
    11.         <dxg:GridColumn FieldName="UnitPrice" Header="Unit Price" />
    12.         <dxg:GridColumn FieldName="UnitsInStock" Header="Units in Stock" />
    13.         <dxg:GridColumn FieldName="UnitsOnOrder" Header="Units on Order" />
    14.     </dxg:GridControl.Columns>
    15. </dxg:GridControl>

    The HiddenEditor event is invoked every time an editor is closed. So in this case, when an item in the combo box is selected and the editor is closed, the HiddenEditor event will be triggered.

    The RowUpdated event is where we’ll submit the changes back to the database.

    Here’s the code I’ll add to handle saving and submitting the data:

    1. private void tableView_HiddenEditor(object sender, DevExpress.Xpf.Grid.EditorEventArgs e)
    2. {
    3.     if (e.Column.FieldName != "ProductName") return;
    4.     gridControl1.View.CommitEditing();
    5. }
    6.  
    7. private void tableView_RowUpdated(object sender, DevExpress.Xpf.Grid.RowEventArgs e)
    8. {
    9.     _productsContext.SubmitChanges(OnSubmitCompleted, null);
    10. }
    11.  
    12. private void OnSubmitCompleted(SubmitOperation so)
    13. {
    14.     if ((so.HasError))
    15.     {
    16.         MessageBox.Show(string.Format("Save Failed: {0}", so.Error.Message));
    17.         so.MarkErrorAsHandled();
    18.     }
    19.     else
    20.     {
    21.         MessageBox.Show("Data Saved");
    22.     }
    23. }

    The code in the OnSubmitCompleted method is purely for demonstration and error handling purposes.

    And that’s it! You can now run the application and use the combo box to select and update the values in the “ProductName” column of the grid.

    Stay tuned for a video demonstration of this tutorial on the DevExpress Channel.

  • Silverlight Upload Control – How to get started

         

    The Silverlight Upload Control... Yes, we have one! While it is installed with every DXperience Silverlight subscription, it usually does not get the publicity it deserves. So to set that straight, I decided to prepare this blog post as a means of introduction as well as a guide to get started using the control.

    The DevExpress Upload Control for Silverlight isn’t simply a text box that can accept a local file path and upload it to the server. It provides a number of advanced features, such as:

    • Uploading multiple files
    • Specifying the maximum number of simultaneous uploads
    • Specifying the maximum file size
    • File Filters
    • And more...

    This blog post will serve as a tutorial on how to get started using the DXUpload Control for Silverlight. If you like to see this in action or follow along interactively, then a video tutorial will be made available tomorrow, so keep an eyes out on my blog for the announcement.

    To start, I’ll need a new Silverlight application project. The first thing I would do is of course add the Silverlight Upload Control to the page. The XAML looks like this:

    1. <UserControl x:Class="SLUploadControl.MainPage"
    2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6.     mc:Ignorable="d"
    7.     d:DesignHeight="300" d:DesignWidth="400"
    8.     xmlns:dxco="http://schemas.devexpress.com/winfx/2008/xaml/controls">
    9.  
    10.     <Grid x:Name="LayoutRoot" Background="White">
    11.         <dxco:UploadControl x:Name="uploadControl" />
    12.     </Grid>
    13. </UserControl>

    So far so good. Now, I need to add a new Generic Handler to the web project so files can be uploaded and saved to the server:

    DevExpress_SL_Upload_Control_Handler

    As I’ll be working with files, the first thing I’ll add to the new handler is the following namespace:

    1. using System.IO;

    Next, I’ll remove the existing code and populate it with the following:

    1. string FilePath { get; set; }
    2. string FileName { get; set; }
    3. int PackageCount { get; set; }
    4. int PackageNumber { get; set; }
    5. public bool IsReusable { get { return false; } }
    6.  
    7. public void ProcessRequest(HttpContext context)
    8. {
    9.     ProcessQueryString(context);
    10.     ProcessFile(context);
    11. }
    12.  
    13. void ProcessQueryString(HttpContext context)
    14. {
    15.     var query = context.Request.QueryString;
    16.     FilePath = Uri.UnescapeDataString(query["filePath"]);
    17.     FileName = Uri.UnescapeDataString(query["fileName"]);
    18.     PackageCount = int.Parse(query["packageCount"]);
    19.     PackageNumber = int.Parse(query["packageNumber"]);
    20. }
    21.  
    22. void ProcessFile(HttpContext context)
    23. {
    24.     string serverFileName = GetServerPath(context.Server, FilePath, FileName);
    25.     FileMode fileMode = File.Exists(serverFileName) && PackageNumber > 0 ?
    26.         FileMode.Append :
    27.         FileMode.Create;
    28.     using (BinaryReader reader = new BinaryReader(context.Request.InputStream))
    29.     using (BinaryWriter writer = new BinaryWriter(File.Open(serverFileName, fileMode)))
    30.     {
    31.         byte[] buffer = new byte[4096];
    32.         int bytesRead;
    33.         while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) != 0)
    34.             writer.Write(buffer, 0, bytesRead);
    35.     }
    36. }
    37.  
    38. string GetServerPath(HttpServerUtility server, string filePath, string fileName)
    39. {
    40.     return server.MapPath(Path.Combine(filePath, Path.GetFileName(fileName)));
    41. }

    So what happens here? First, I define the properties that I’ll need throughout the application (this includes the file path, the file name, etc…). Next, the IHttpHandler.ProcessRequest method is implemented that will be called every time a new package is received from the client. Next, the ProcessQueryString method takes the query string and breaks it up into the properties we created earlier. Finally, the ProcessFile method reads data from the input stream and writes it to the specified location on the server.

    We’re almost done, let’s go back to the XAML Code of the application add a few properties to the Upload Control:

    1. <dxco:UploadControl WebHandlerUri="http://localhost:54199/UploadHandler.ashx"
    2.                     FileUploadCompleted="uploadControl_FileUploadCompleted"
    3.                     UploadServerPath="Images"
    4.                     x:Name="uploadControl"
    5.                     Width="532" />

    Notice that to keep this example simple, I’m referencing the handler using a direct URL. As it stands, this will need to be updated every time as the Development Server launches on different ports, but in a production environment, the URL can be set to a physical address.

    The UploadServerPath property of course specifies where the uploaded images should be saved on the server. For this purpose, I’ve created an empty “Images” folder in my web application project.

    Finally, the FileUploadCompleted event, as its name implies, triggers when the upload has finished. I’ll add the following code to load and display the uploaded image at runtime:

    1. ...
    2. using System.Windows.Media.Imaging;
    3. ...
    4.  
    5. private void uploadControl_FileUploadCompleted(object sender, DevExpress.Xpf.Controls.UploadItemEventArgs e)
    6. {
    7.     string path = GetPath(uploadControl.WebHandlerUri,
    8.         uploadControl.UploadServerPath,
    9.         e.ItemInfo.Name);
    10.     ImageSource source = new BitmapImage() { UriSource = new Uri(path) };
    11.     uploadControl.ShowPreviewImage(e.ItemInfo, source);
    12. }
    13.  
    14. // Gets the path to the uploaded copy of the image located on the target server.
    15. string GetPath(Uri uri, string uploadServerPath, string fileName)
    16. {
    17.     string basePath = uri.Port == -1 ?
    18.         string.Format("{0}://{1}", uri.Scheme, uri.Host) :
    19.         string.Format("{0}://{1}:{2}", uri.Scheme, uri.Host, uri.Port);
    20.     string fullPath = string.Format("{0}/{1}/{2}", basePath, uploadServerPath, fileName);
    21.     return fullPath;
    22. }

    And I’m done! I can run the application and see it in action:

    DevExpress_Silverlight_Upload_Control

    The project for this example is also available on CodeCentral: http://www.devexpress.com/Support/Center/e/E2301.aspx

  • Silverlight Grid Webinar – Summaries, Filtering and other End-User Features

         

    If you missed Monday’s webinar, the recorded version is now available on the DevExpress Channel. Click on the image below to watch the event on-demand:

    Silverlight_Grid_Webinar_End_User_Features[5]

    In this webinar, we covered...

    • Using Unbound Columns
    • Creating Unbound Expressions at design-time, runtime, and through code
    • Applying Group Summaries (design-time and code)
    • Calculating Total Summaries
    • Overview of filtering features and the Filter Editor Control
    • Quick tour of several end-user features for both the Silverlight and WPF Grid controls
  • Webinar: Silverlight/WPF Grid Control End-User Customization and Features

         

    Join me in an upcoming webinar where I’ll introduce Customization and Data Analysis features available to end-users in both the Silverlight and WPF Grid Controls. This session will cover mostly runtime functionality, therefore it will be presented in a slightly different format within a shorter demo timeframe.

    Date:

    Monday, January 10, 2011 10:00 AM Pacific Time

    Event Overview:

    The DevExpress Data Grid controls for Silverlight and WPF provide the end-user with powerful and flexible customization and data management functionality. Using the DXGrid control, your end-users will be able to take advantage of features such as Grouping, Sorting, Filtering, Column and view customization, and much more. This session will provide a thorough overview of the tools available to manage data at runtime.

    Presenter:

    Emil Mesropian – DevExpress Technical Evangelist for Silverlight and WPF

    How to Register:

    Register for this webinar free of charge by visiting the following page: https://www3.gotomeeting.com/register/840875590

  • Silverlight Grid Control - Printing and Exporting

         

    In my previous blog post, I provided an introduction to binding the grid, applying themes, and displaying the print preview embedded in the Silverlight Window Control. For the sake of simplicity, I left out details on how to print and export the grid’s data. That content was reserved for this post and so I am going to take the print preview code I posted yesterday and explain what it actually does. The last part of the post will include directions on how to implement a report service to provide printing and export functionality.

    So let’s take a look at the code...

    1. private void printGrid(){
    2.     DocumentPreview preview = new DocumentPreview();
    3.     VisualDataNodeLink link = new VisualDataNodeLink(gridControl1.View as IRootDataNodeSource);
    4.     link.ExportServiceUri = "../ExportService1.svc";
    5.     link.PrintingSystem.ExportOptions.Html.EmbedImagesInHTML = true;
    6.     LinkPreviewModel model = new LinkPreviewModel(link);
    7.     preview.Model = model;
    8.  
    9.     // Setup the DXWindow and content
    10.     printPreviewWindow.Title = "Grid Print Preview";
    11.     printPreviewWindow.Show();
    12.     printPreviewWindow.Content = preview;
    13.  
    14.     link.CreateDocument(true);
    15. }

    If you recall, this is the method from my earlier example that when called will generate the print preview and embed the preview control in a DXWindow called “printPreviewWindow”. Here, first a DocumentPreview instance is created - this is the print preview control that will generate and display the preview at runtime. Next, a VisualDataNodeLink is created and the grid’s view is passed on as an IRootDataNodeSource interface.

    The link’s ExportServiceUri property specifies the Silverlight-enabled Export Service to be used when printing the data or exporting to an external file format. If exporting the file as an HTML, the PrintingSystem.ExportOptions.Html.EmbedImagesInHTML property specifies whether or not images (if any) should be embedded in the generated HTML file. While I’ve used HTML as an example here, remember that this applies to all the export formats and can be accessed through the PrintingSystem.ExportOptions property collection. So for example, to programmatically set the PDF export image quality, I would use something like this:

    1. link.PrintingSystem.ExportOptions.Pdf.ImageQuality = DevExpress.XtraPrinting.PdfJpegImageQuality.Highest;

    Next, the preview model is created and assigned to the document preview. The three lines that follow set up the DXWindow control (specified independently in XAML) and display the print preview control.

    1. // Setup the DXWindow and content
    2.     printPreviewWindow.Title = "Grid Print Preview";
    3.     printPreviewWindow.Show();
    4.     printPreviewWindow.Content = preview;

    Finally, the last line generates the document preview:

    1. link.CreateDocument(true);

    If I run the application as is and try to export it to a PDF, I’ll get the following error:

    Print_Preview_Export_Error

    I’m seeing this error message because the application is trying to query an export service (in this case, “ExportService1.svc”) that doesn’t exist. So let’s go ahead and add that to our project.

    I’ll right-click the web application project and select to add a new item.

    Project_Add_New_Item

    From the “Add New Item” dialog, I’ll select the “Silverlight” template category, then the “Silverlight-enabled Export Service” from DevExpress.

    DevExpress_Silverlight_Export_Service

    Make sure the name is the same as the one used in code earlier. Now, when I run the application, I can print as well as export the data as displayed in the print preview control at runtime.

    The complete project for this solution can be found attached to the previous post: Silverlight Grid, Print Preview, and the Silverlight Window Control

More from DevExpress
Live Chat
Have a pre-sales question?
Need assistance with your evaluation?
We are here to help.
Chat is one of the many ways you can contact members of the DevExpress Team. We are available Monday-Friday between 8:30am and 5:00pm Pacific Time.
If you need additional product information, require pre-sales assistance, or want help with your order, write to us at info@devexpress.com or call us at
+1 (818) 844-3383.