Geeks With Blogs

@Sorskoot
  • Sorskoot "Visual Studio 2013, will be available later this year, with a preview build publicly available at Build" http://t.co/SV28646Qr6 about 421 days ago

News


Timmy Kokke's Blog

↑ Grab this Headline Animator

Timmy Kokke at Blogged
Timmy Kokke …just sorting my bubbles…

PivotViewer series

  1. Building your first PivotViewer application
  2. Runtime PivotViewer collection creation
  3. PivotViewer - Working with Facets
  4. Handling PivotViewer events
  5. PivotViewer - Custom actions
  6. PivotViewer and MVVM

Intro

Today I would like to show you how you can consume web services in the PivotViewer control for Silverlight and build a collection at runtime. This tutorial is based on examples found on www.getpivot.com and the getting started tutorial I posted earlier this week. This tutorial used the previous as a starting point, so if you haven’t read that you probably want to do that first. The only difference is that I named the project PivotViewerDynamic this time.

The PivotViewer control loads a collection by reading an .CXML file. To get the PivotViewer to load a generated collection HTTP handlers are used to redirect the request for an .CXML file to custom code. This code, the Collection Factory, returns the collection in .CXML format. Requests for the DeepZoom images used in the collection are also redirected to custom code is capable of generating images on the fly or load them from the web.

Building a Factory

The factory class that will be building the collection is based on a class that can be found in one of the examples on www.getpivot.com. You can download this example here. Add the PivotServerTools project from this example to the project created in the Getting Started tutorial. And add a reference to the PivotServerTools project from the Web project. It is also include in the sample code for this tutorial.

To be able to use the factory a custom HTTP handler needs to be build. This sounds more complex than it is.

Start by adding a new class to the Web project and name this class CxmlHandler. Make this class implement the IHttpHandler interface. This will give you one method, ProcessRequest, and one property, IsReusable. Add one line of code to the ProcessRequest() method as shown below. The PivotHttpHandlers.ServceCxml() method will look for factories and returns the collection in .CXML format. Don’t forget to resolve a using to the PivotServerTools namespace.

public class CxmlHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        PivotHttpHandlers.ServeCxml(context);
    }
 
    public bool IsReusable
    {
        get { return true; }
    }
}

To get the HTTP handler to work it has to be configured in Web.Config. To do this add the code below.

<system.webServer>
  <handlers>
    <add name="CXML" path="*.cxml" verb="GET" 
          type="PivotViewerDynamic.Web.CxmlHandler"/>
  </handlers>
</system.webServer>

 

 

 

 

 

 

 

 

It also has to be defined in the system.web section of the config file. Add the code below to the system.web section

<httpHandlers>
        <add path="*.cxml" verb="GET" type="PivotViewerDynamic.Web.CxmlHandler"/>
</httpHandlers>

 

 

 

 

 

 

 

 

This makes sure that every request for a .CXML file is redirected to the PivotViewerDynamic.Web.CxmlHandler class.

It’s time to add the actual factory class now. Add a new class to the Web project and name this DemoCollectionFactory. Make this class implement the base class CollectionFactoryBase and make sure you resolve the PivotServerTools namespace. Only the MakeCollection method is overridden from the base class. We’ll add the functionality of this method later.

Add a constructor to this class to set the name of the factory. This name is going to correspond with the name of the .CXML file requested. The constructor will look something like this now:

public DemoCollectionFactory()
{
    this.Name = "Demo";
}

The collection factory is ready to use now. Lets load it from the Silverlight part of the application.

The PivotViewer control should already be there if you’re using the code from the first tutorial. If not, add the control like below:

<UserControl x:Class="PivotViewerDynamic.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:Pivot="clr-namespace:System.Windows.Pivot;assembly=System.Windows.Pivot">
    <Grid x:Name="LayoutRoot" Background="White">
        <Pivot:PivotViewer x:Name="Pivot"/>
    </Grid>
</UserControl>

Add or change the Pivot.LoadCollection method in the code behind MainPage.xaml.cs to

 Pivot.LoadCollection("http://localhost:49000/demo.cxml",string.Empty);

 

 

 

 

 

 

 

 

This examples assumes the Web project is running on port 49000. If not, go to the Project properties and on the Web tab set Specific Port, in this case 49000.

image

Add a breakpoint to the MakeCollection() method in the factory to make sure it works. Now hit F5 to compile and run.

Filling the Collection

If all went well you should have got the application running, although it doesn’t do much yet. Let us fill the collection.

To fill the collection an .XML file is downloaded from the server and fed to the collection.

public override Collection MakeCollection(
    CollectionRequestContext context)
{
    string data;
    using (var web = new WebClient())
    {
        data = web.DownloadString(
            "http://localhost:49000/DemoData.xml");
    }

 

 

 

 

 

 

 

 

Next, a string reader is created. Which in turn is passed to the XElement.Load() method which parses the XML.

    var reader = new StringReader(data);
    XElement root = XElement.Load(reader);

A collection has to be instantiated before it can be filled with data. For each DemoData element in the parsed XML the MakeItem() method is called. This method is described a little later. It fills the collection with data from the the XML entries. Before the collection will be returned, its name is set.

 

 

 

 

 

 

 

 

    var collection = new Collection();
    foreach (XElement entry in root.Elements("DemoData"))
    {
        MakeItem(collection, entry);
    }
    collection.Name = "Demo Collection";
    return collection;
}

 

 

 

 

 

 

 

 

The MakeItem() method takes the instance of the collection and an entry from the XML data. It extracts three values, Id, Value1 and Description. These are passed into the AddItem() method. This method takes 5 parameters. The first is the Name of the item. The second is for a URL. The third is a description of the item. The fourth an image. If the image is omitted an image will be generated. The last parameter is a collection of Facets. Facets are the properties of the collection. You filter and sort the collection by facets. The PivotViewer control decides the best way to show them in the filter section. There a five types of facets: String, LongString, Number, DateTime and Link. In this case we let the control figure out what type to use.

MakeItem:

private void MakeItem(Collection collection, XElement entry)
{
    int id= int.Parse(entry.Element("Id").Value);
    double value = double.Parse(entry.Element("Value1").Value);
    string description = entry.Element("Description").Value;
 
    collection.AddItem(
            id.ToString(),
            null, 
            description,
            null,
            new Facet("Value",value));
}

 

 

 

 

 

 

 

 

To get the runtime generated collection to show the right images, HTTP handlers have to be added for the DeepZoom images.

Add empty .cs file named DeepZoomHandlers.cs and place the four handlers below in there: DeepZoomCollection(.DZC), DeepZoomImage(.DZI) and  two paths to images to handle the loading of images by code. All these handlers call methods in the PivotServerTools in the same way the CxmlHandler does.

using System.Web;
using PivotServerTools;
 
namespace PivotViewerDynamic.Web
{
    public class DzcHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            PivotHttpHandlers.ServeDzc(context);
        }
 
        public bool IsReusable
        {
            get { return true; }
        }
    }
    public class ImageTileHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            PivotHttpHandlers.ServeImageTile(context);
        }
 
        public bool IsReusable
        {
            get { return true; }
        }
    }
    public class DziHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            PivotHttpHandlers.ServeDzi(context);
        }
 
        public bool IsReusable
        {
            get { return true; }
        }
    }
 
 
    public class DeepZoomImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            PivotHttpHandlers.ServeDeepZoomImage(context);
        }
 
        public bool IsReusable
        {
            get { return true; }
        }
    }
}

 

 

 

 

 

 

 

 

Add these handlers to the web.config too. Add the lines below to the HttpHandler section in system.web.

<add path="*.dzc" verb="GET" 
      type="PivotViewerDynamic.Web.DzcHandler"/>
<add path="*.dzi" verb="GET" 
      type="PivotViewerDynamic.Web.DziHandler"/>
<add path="*/dzi/*_files/*/*_*.jpg" verb="GET" 
      type="PivotViewerDynamic.Web.DeepZoomImageHandler"/>
<add path="*_files/*/*_*.jpg" verb="GET" 
      type="PivotViewerDynamic.Web.ImageTileHandler"/>

 

 

 

 

 

 

 

 

Add the lines below to the Handlers section in System.WebServer:

<add name="DZC" path="*.dzc" verb="GET" 
      type="PivotViewerDynamic.Web.DzcHandler"/>
<add name="DZI" path="*.dzi" verb="GET" 
      type="PivotViewerDynamic.Web.DziHandler"/>
<add name="DeepZoomImage" path="*/dzi/*_files/*/*_*.jpg" 
      verb="GET" type="PivotViewerDynamic.Web.DeepZoomImageHandler"/>
<add name="ImageTile" path="*_files/*/*_*.jpg" 
      verb="GET" type="PivotViewerDynamic.Web.ImageTileHandler"/>

 

 

 

You should be able to run the application now.

image

Wrap-up

In this example I used a very simple .XML file. It won’t be hard to change the code to consume external web services. As long as there are items return that can contain sets of data it can be shown in the PivotViewer, like Rss feeds, Twitter and even OData.

In this first version of the PivotViewer it is not possible to style the control, but you can do other fun stuff with it. You can expect more tutorials on the PivotViewer in the future. To be the first to know about that you can subscribe to the RSS-feed or follow me on twitter.

You can download the code for this tutorial here.

Technorati Tags: ,

Share



 

kick it on DotNetKicks.com


 

Shout it

Posted on Tuesday, August 17, 2010 11:14 PM Silverlight , dotnetmag , PivotViewer | Back to top


Comments on this post: Runtime PivotViewer collection creation

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
Hi Timmy, Great series.

1) In this tutorial code download i had to add clientaccesspolicy.xml to the web project to see anything on the screen. You do mention it but would be nice to include it.

2) Tile images dont show up, no matter what i do, just a blue border around the items.
Error: Unhandled Error in Silverlight Application
Code: 4009
Category: ManagedRuntimeError
Message: Element is already the child of another element.

The tile images are not generated automatically if they are not provided. I also created my ItemImages in collection.AddItem - no difference.

Any idea what might be the problem ?

Cheers
Left by Dan on Sep 04, 2010 10:28 AM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
Hi Timmy,

I managed to make progress -
1) IIS must be used, cassini gives unpredictable results
2) each and every image file must be a valid one, so one must include code that checks the image files existance on disk, its size and image type - after these tests pass the image can be added to the collection.

the pivotviewer does not handle sing le item or image errors gracefully, everything must be perfect.
Left by Dan on Sep 23, 2010 12:10 AM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
Hey Timmy,

Really enjoying these tutorials. One quick question if I may. I can't seem to get a decription to appear in the information window even though the items I am adding to the collection have descriptions defined.
have you came across this yourself?

Cheers for all of the information
vince
Left by vince on Oct 18, 2010 9:11 PM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
Hey again,
I posted the last comment. If anyone reads it and wonders how to get the description to display on a runtime generated collection then just add this code to the PivotServerTools.Internal.CxmlSerialiser class in the method - private IEnumerable<object> MakeItemContent(CollectionItem item, int id)

For some reason the Microsoft project was not adding the description there - maybe it's intentional, I don't know, but if you want to see a description enter these lines somewhere in the method:
if (!string.IsNullOrEmpty(item.Description)) {
yield return new XStreamingElement(Xmlns + "Description", item.Description);
}

And on the front end there's a description now if one was specified.

Once again thanks for these tutorials. They were the best introduction I could have hoped for. I've started generating collections now with web services and databases quite easily because of all of your information.

Cheers
Vince Mcc
Left by Vince on Oct 19, 2010 7:37 PM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
Is there a way to save the deepzoom images created at runtime? After I create the collection I am using Collection.ToCxml and Collection.ToDzc to save the collection so that cache canbe used but I cannot figure out how to save the images themselves and the .dzi file.

The cache works correctly (and load-time goes from 2+ minutes to 10-20 seconds) but no images..

This is how I'm creating cxml and .dzc files:
Inside: public override Collection MakeCollection(CollectionRequestContext context)

Collection col = new Collection();
string szCxml = col.ToCxml().ToString();

//Tell the Cxml where to find DZC..
szCxml = szCxml.Replace("<Items>","<Items ImgBase=\"tt.dzc\">");

//Write out everything..
File.WriteAllText(@"c:\cxml\tt.cxml", szCxml);
col.ToDzc(twTTDzc);

Jesse
Left by Jesse on Nov 06, 2010 10:47 PM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
Hi there,...

I'm having trouble finding a way to debug the collectionfactory. I can step through the HttpHandlers but breakpoints in the collection factory don't get hit. Any ideas?
Left by Stimul8d on Nov 30, 2010 11:46 AM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
@Jesse,

Can you post or send me the code you use to re-create the Collection from the CXML file? IN order words, the code to deserialize the Collection from the file.

Thanks,
Jim McCurdy
Left by Jim McCurdy on Jan 28, 2011 12:11 AM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
Hi there any progress with caching created cxml collection with images... pls would be very appreciated for any hint on this direction, I'm creating cxml from 100000 xml files so caching is very important for my scenario
Left by tankist on Jan 30, 2011 10:21 PM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
I am experiencing the same issue that Dan described earlier:

"Tile images dont show up, no matter what i do, just a blue border around the items.
Error: Unhandled Error in Silverlight Application
Code: 4009
Category: ManagedRuntimeError
Message: Element is already the child of another element."

What was the resolution?

Will there be an update to the source code files that resolves these issues for us beginners?

Once again, thank you for this valuable information.
Left by Scott Nimrod on Mar 02, 2011 1:30 AM

# re: Runtime PivotViewer collection creation
Requesting Gravatar...
After some debuggin I notices the startup project was set to the silverlight project. You'll have to set the .WEB project as a startup project. Than it should work. I'll update the demo code too...

Thanks for commenting!
Left by Timmy Kokke on Mar 02, 2011 8:56 AM

Your comment:
 (will show your gravatar)
 


Copyright © Timmy Kokke | Powered by: GeeksWithBlogs.net | Join free