Dynamically Loading Images in SilverLight 1.0 using C#

18. April 2008 18:40

Here is an easy way to dynamically load images from a directory into your SilverLight 1.0 application using C#. I'm going to assume you already know how to set up your application to use an aspx (with codebehind) page instead of a static HTML page. If not, this article may be useful.

The aspx page (I'll call it sampleXAML.aspx) contains your XAML declaration for the SilverLight 1.0 application. For this elucidation, we will only have one main canvas. In it, we will call your loadImages() method from the codebehind.

<Canvas>
  <%= loadImages() %>
</Canvas>

In your codebehind (sampleXAML.aspx.cs), we dynamically load images that will be displayed in the SilverLight app. First will create a string variable that will house our XAML declaration for an image.

string strImages = @"<Image x:Name=""image-{0}"" Source=""{1}"" Canvas.Left=""{2}"" Canvas.Right=""{3}"" />;

I've included Canvas.Left and Canvas.Right so images will be placed in a cascading fashion to ensure they were all loaded.

Keep in mind you will need the following namespaces:

System.IO; 
System.Text; 


Next step, read in your files from a directory using the loadImages() method...

protected string loadImages()
{
  StringBuilder strXML = new StringBuilder();

  int intCounter = 0;

  DirectoryInfo dirs = new DirectoryInfo(MapPath("~/images")); //Change path here for a specific folder you want to read in from

  foreach (FileInfo fi in dirs.GetFiles("*.jpg"))
  {
    strXml.AppendFormat(strImages, intCounter, "images/" + fi.Name, intCounter*100, intCounter*100);
    intCounter++;
  }
 
  return strXML.ToString();
}

The strXML is used to build your <Image> XAML tag and is populated in the foreach loop by four parameters. You can add or remove parameters as needed, but at mininum you'll need the Source.

Note that I've filtered for JPGs. First, SilverLight 1.0 can only read JPGs and PNGs. Secondly, Windows loves to create the thumbs.db to display the cool little folder with tiny images of the pictures. While you may not get an error, it will attempt to create another <Image> XAML tag that is empty for that thumbs.db file.

When you run your application, the XAML generated should read to something similar:

<Image x:Name="image-0" Source="images/img01.jpg" Canvas.Left="0" Canvas.Right="0" />
<Image x:Name="image-1" Source="images/img02.jpg" Canvas.Left="100" Canvas.Right="100" />
<Image x:Name="image-2" Source="images/img03.jpg" Canvas.Left="200" Canvas.Right="200" />
<Image x:Name="image-3" Source="images/img04.jpg" Canvas.Left="300" Canvas.Right="300" />

The end. Post any questions you may have.

Tags: , ,

Silverlight

Run Server Side Code from Silverlight objects

14. February 2008 04:37

This article will describe how you can make AJAX callbacks when using Silverlight.  Pretty much what this is, is a concept on how when you handle and event in your XAML it will run some server side code.  This example will provide steps you need to accomplish this and assume you are running ASP.NET 2.0:

Step 1) Have your object in your xaml that has and event tied to it.  For example in your XAML you may have something like this:

<Image Source="/images/pic1.jpg"
       Tag="myPic"
       x:Name="myPicXName"
       Width="100"
       Height="100"
       Canvas.Top="20"
       Canvas.Left="8"
       Opacity=".5"
       MouseLeftButtonDown="leftDownClick" />

Step 2) Have a function in one of your javascript files named what we named it in Step 1 for the MouseLeftButtonDown property.  In addition, have the function you want to run when the call back is done.  For example:

function leftDownClick(sender, args)
{
 
   var objSender = sender;
   var objTag = sender["Tag"];  
   var objName = sender["Name"];
   
   //this function is located on default.aspx
   doCallBack(objName);
 
}

//this is called from default.aspx.cs
function runClientCallBack(message, context)
{
    //message is the returnValue variable in default.aspx.cs
    //do whatever you want
}

Step 3) Have javascript functions your main ASPX page. For the purpose of this article will say on your default.aspx page. So for example your page may look something like this:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <script type='text/javascript' src="js/Silverlight.js"></script>
    <script type='text/javascript' src="js/createSilverlightMain.js"></script> 

    <script type="text/javascript">
       
        //this gets called from createSilverlightMain.js
        // in leftDownClick
        function doCallBack(name)
        {
           var message = name;
           var context = '';
          
           //this is located in default.aspx.cs              
           <%=sCallBackFunctionInvocation%>
        }
       
        //this is used for ICallbackEventHandler
        //in the Page_Load
        function OnError(message, context)
        {
           alert('An unhandled exception has occurred:\n' + message);
        }
       
    </script>

</head>
<body>
    <form id="form1" runat="server">
       <div id="SilverlightHost" style="width:650px; height:425px;">
           <script  type='text/javascript'>
     createSilverlight();       
    </script>
       </div>

    </form>
</body>
</html>

Step 4) Handle the call back in your default.aspx.cs file:

1 - you need to have default.aspx.cs inherit the following:

System.Web.UI.ICallbackEventHandler

You can do this in the top where it looks something like this:

public partial class _default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler


2 - Use the code sample below in your default.aspx.cs file:

        protected string returnValue = "default";
        public string sCallBackFunctionInvocation;

        protected void Page_Load(object sender, EventArgs e)
        {
            sCallBackFunctionInvocation = this.Page.ClientScript.GetCallbackEventReference(this, "message", "runClientCallBack", "context", "OnError", false);
        }

        public void RaiseCallbackEvent(String eventArgument)
        {

           //whatever code you want to run

           returnValue = //whatever string value you want

           //you could even write out another xaml object here in a string
        }

        public string GetCallbackResult()
        {
            return returnValue;
        }

 

This concept should get you started.  This still doesn't let you access silverlight objects directly in code behind but does give you the ability to run server side code from a silverlight object. you'll notice on the initial leftDownClick button I pass the name property from the silverlight object.  This lets me keep track of what object is making the callback.

Tags:

ASP.NET | Silverlight




My Random Thought

I think the OCW is a great thing to have available to those who are in school, just finished school or just want to educate themself

http://ocwconsortium.org/

John On Twitter

Discounts