Wednesday, April 29, 2009

Some times we have requirements in SharePoint that we need to pull images from SharePoint library and display those images in Silverlight module with rich UI. But we know that Silverlight runs on client side, we can't access the SharePoint libraries in the Silverlight projects because of permission issues as well.
So, here we build an architecture that SharePoint will build the XML for us and write it on the page and Silverlight grabs the XML from the page and displays the images on the UI. How nice it is. You can get the first part i.e. get xml (image) data from the SharePoint libraries here.

Here, we are discussing about the code we need to place in Page.xaml.cs file to read xml from web page.
public Page()
{
string controlid = "divImgs"; //You can also use intiparams of Silverlight params to get the id.
InitializeComponent();

string xmlstring = string.Empty;
if (controlid != null)
{
HtmlElement ctl = HtmlPage.Document.GetElementById(controlid);
if (ctl != null)
xmlstring = (string)ctl.GetProperty("innerHTML");
}

if (!string.IsNullOrEmpty(xmlstring))
{
ProcessXML(xmlstring);
}
}
The above code is the Page constructor of the Page. Xaml.cs file.
1. Here, we are catching the control on the HTML document and reading it's HTML. if you remember, while coverting the data view web part data from HTML to XML, in the XSLT i assigned an id for a html tag called "divImgs". We are using this id here in the cs file, and reading the HTML, obviously it will get the xml data to the xmlstring variable.
2. No, we need to process the XML and bind the data to the silverlight control. This is why i am calling a function called "Process XML".
private void ProcessXML(string xml)
{
images = new List<string>();
if (xml != string.Empty)
{
try
{
StringReader textStream = null;
textStream = new StringReader(xml);

if (textStream != null)
{
using (XmlReader reader = XmlReader.Create(textStream))
{
while (!reader.EOF)
{
if ((reader.IsStartElement()) && (reader.LocalName == "slides"))
{
if (reader.HasAttributes)
{
reader.MoveToAttribute("baseUrl");
}
}
else
{
if ((reader.LocalName == "slide") && (reader.HasAttributes))
{
reader.MoveToAttribute("imageUrl");
string imageName = reader.Value.ToLower();
if ((imageName.Contains(".jpg")
|| imageName.Contains(".png")))
images.Add(reader.Value);
}

}
reader.Read();
}
}
}
}
catch (Exception ex)
{
}
}
}
3. In the above code, images is the global variable of type List<string>. We are filling this object with the image urls by reading the xml string.
4. Now by calling the ProcessXML function, we are done with getting image urls. So we have collection of image urls, and use this object to give input as the Silverlight module controls and display on the UI.

Very simple and nice.
Happy coding!!!
Categories: ,

0 comments:

Post a Comment