b

blu

Monday, 14 May 2012

How to Call Javascript Elements from Silverlight

Step 1) Create Silverlight Project
Step 2)  Add following element to Silverlight hosted page
           <p id="ID1">Hello SIlverlight from HTML</p>
Step 3) Add following code in Page_Load / button event handler.
Step 4) In order to access html content in Silverlight


             using System.Windows.Browser; //should be added
             HtmlElement ele=HtmlPage.Document.GetElementById("ID1");
            MessageBox.Show(ele.GetAttribute("innerHTML").ToString());


Sample Code:


XAML


<Grid x:Name="LayoutRoot" Background="White">
        <TextBox Height="36" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" VerticalAlignment="Top" Width="364" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,87,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>

in MainPage.xaml.cs

private void button1_Click(object sender, RoutedEventArgs e)
        {
            HtmlElement ele=HtmlPage.Document.GetElementById("ID1");

            textBox1.Text=ele.GetAttribute("innerHTML").ToString();
        }


SilverlightHostedTestPage.aspx/html

    <form id="form1" runat="server" style="height:100%">
    <div id="silverlightControlHost">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
 <param name="source" value="ClientBin/SilverlightApplication6.xap"/>
 <param name="onError" value="onSilverlightError" />
 <param name="background" value="white" />
 <param name="minRuntimeVersion" value="4.0.50826.0" />
 <param name="autoUpgrade" value="true" />
 <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
   <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
 </a>
   </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
        <p id="ID1">Hello SIlverlight from javascript</p>
    </form>

Message: Unhandled Error in Silverlight Application Invalid cross-thread access


Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.3)
Timestamp: Mon, 14 May 2012 08:52:25 UTC


Message: Unhandled Error in Silverlight Application Invalid cross-thread access.   at MS.Internal.XcpImports.CheckThread()
   at MS.Internal.XcpImports.MessageBox_ShowCore(String messageBoxText, String caption, UInt32 type)
   at System.Windows.MessageBox.ShowCore(String messageBoxText, String caption, MessageBoxButton button)
   at System.Windows.MessageBox.Show(String messageBoxText)
   at SilverlightApplication5.MainPage.Succeeded1(Object sender, ClientRequestSucceededEventArgs args)
   at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryGetResponseAsyncCallback(IAsyncResult asyncResult)
   at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassd.<InvokeGetResponseCallback>b__b(Object state2)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Line: 1
Char: 1
Code: 0
URI: http://sp2010:21016/SitePages/silverlight1.aspx

Friday, 11 May 2012

Parse XML in SilverLight 4.0

Step1) Create Silverlight Applicatication using .NET 4.0

Step 2)  Add new Order class in Silverlight Project.


File Name:  Order.cs

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;




namespace SilverlightApplication3
{
    public class Order
    {
        private string OrderID, Amount, Qty, Product,Total;
        public string PRODUCT
        {
            get { return Product; }
            set { Product = value; }
        }
        public string ORDERID
        {
            get { return OrderID; }
            set { OrderID = value; }
        }
        public string AMOUNT
        {
            get { return Amount; }
            set { Amount = value; }
        }
        public string QTY
        {
            get { return Qty; }
            set { Qty = value; }
        }
        public string TOTAL
        {
            get { return Total; }
            set { Total = value; }
        }
    }
}


Step 3)  Drag & Drop Label and DataGrid in MainPage.xaml
XAML excert 

    <Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid AutoGenerateColumns="True" Height="156" HorizontalAlignment="Left" Margin="10,51,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="390" />
        <sdk:Label Height="58" HorizontalAlignment="Left" FontSize="16" Margin="10,10,0,0" Name="label1" VerticalAlignment="Top" Width="378" Content="Silverlight XML Source in DataGrid" Foreground="#FFBE2C2C" FontWeight="Bold" FontStyle="Italic" />
    </Grid>

Step 4) Open MainPage.XAML.cs

Add following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication3
{
    public partial class MainPage : UserControl
    {
        List<Order> ordList = new List<Order>(); //Declare list of Orders
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
//Declare  inline XML or it can be generic handler emiting xml from other website
            String xmlString =
                @"<?xml version='1.0'?>
                  <Orders>
                   <Order>
                       <ID>1</ID>
                        <Product>Cloths</Product>
                        <Amount>1500</Amount>
                        <Qty>10</Qty>
                    </Order>
                   <Order>
                       <ID>2</ID>
                        <Product>Shoes</Product>
                        <Amount>15000</Amount>
                        <Qty>20</Qty>
                    </Order>
                    </Orders>
                ";
            //Read xml--> element by element

            //Samething can be done  using LINQ to XML.
            //Silverlight doesnot support  XPathNavigator. 
            System.Text.StringBuilder output = new System.Text.StringBuilder();
            using (System.Xml.XmlReader reader =
                System.Xml.XmlReader.Create(new System.IO.StringReader(xmlString)))
            {
                while (reader.Read())
                {
                    Order o = new Order();
                    reader.ReadToFollowing("ID");
                    o.ORDERID = reader.ReadInnerXml();
                    //output.Append("ID=" + reader.ReadInnerXml());
                    reader.ReadToFollowing("Product");
                    o.PRODUCT = reader.ReadInnerXml();
                    //output.Append("Product=" + reader.ReadInnerXml());
                    reader.ReadToFollowing("Amount");
                    o.AMOUNT = reader.ReadInnerXml();
                    //output.Append("Amount=" + reader.ReadInnerXml());
                    reader.ReadToFollowing("Qty");
                    o.QTY = reader.ReadInnerXml();
                    //output.Append("Qty=" + reader.ReadInnerXml());
                    if (!String.IsNullOrEmpty(o.AMOUNT))
                    {
                        o.TOTAL = (Int16.Parse(o.AMOUNT) * Int16.Parse(o.QTY)).ToString();
                        ordList.Add(o); //Add to OrderList
                    }

                }

                dataGrid1.ItemsSource = ordList; //Assign it to DataGrid Item Source
            }

            
        }
    }
}


Step 5)  Run the Applictaion/F5

OUTPUT 







Silverlight(2007) is a Microsoft's  Browser based plugin for Vector Graphics, ,Multimedia & Gaming.
Silverlight supports native .NET language support.
Silverlight runs in Windows, Linux (as a Mono Version), in Macintosh IE & Safari browsers.
Silverlight does have limited support in Windows Mobile Cell phones.
Silverlight Equivalent is Falsh Player(1997).  It also supports same features as Silverlight, But Programmer needs to learn Action Script.
It runs on all platforms. Including Mobile Phones.