Rohit Singh

Rohit Singh

  • NA
  • 1
  • 2.8k

How to pass data from asxp page to silverlight

Nov 8 2012 5:02 AM
Hi. 

I am already having an application in asp.net 4.0 now.I want to use silverlight control instead of asp.net control, for this I have send data from aspx.cs to xaml.cs so that i can bind my Silverlight control with the data so suggest me  how to send data from aspx to xaml...and xaml to aspx page. My WCF service return Dataset to aspx page. I want to get data on XamL  without using Entity framework as well as Linq to SqL.

Any help or suggestion will be appreciated 

Rohit Singh

Below Code: Xaml.cs
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.ServiceModel;
using System.Collections;
using System.Windows.Data;
using System.Windows.Navigation;


namespace SilverlightApplication1
{

    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            WCservice.Service1Client cl = new WCservice.Service1Client();

            cl.ShareListVarCompleted += new EventHandler<WCservice.ShareListVarCompletedEventArgs>(cl_ShareListVarCompleted);
            cl.ShareListVarAsync("strList");

            //WCservice.Service1Client c2 = new WCservice.Service1Client();
            //c2.LstDatsSetCompleted += new EventHandler<WCservice.LstDatsSetCompletedEventArgs>(c2_LstDatsSetCompleted);
            //c2.LstDatsSetAsync("strList");
        }

        void c2_LstDatsSetCompleted(object sender, WCservice.LstDatsSetCompletedEventArgs e)
        {
            //DataGrid dtGrid = new DataGrid();
            //string strSvc;
            //List<WCservice.Service1Client> svc= new List<WCservice.Service1Client>((IEnumerable<WCservice.Service1Client>)e.Result);
               

            throw new NotImplementedException();
        }

        void cl_ShareListVarCompleted(object sender, WCservice.ShareListVarCompletedEventArgs e)
        {
            DataGrid dtGrid = new DataGrid();
            List<Dictionary<string, object>> source = new List<Dictionary<string, object>>();
            SilverlightApplication1.WCservice.ArrayOfKeyValueOfstringanyTypeKeyValueOfstringanyType[][] listArr = e.Result;

            int HeaderCre = 0;
            foreach (var d in listArr)
            {
                Dictionary<string, object> dictObj = new Dictionary<string, object>();

                for (int j = 0; j < d.Length; j++)
                {
                    dictObj[String.Format("{0}", d[j].Key)] = String.Format("{0}", d[j].Value);
                    if (HeaderCre == 0)
                    {
                        string propertyName = String.Format("{0}", d[j].Key);
                        DataGridTextColumn column = new DataGridTextColumn();
                        column.Binding = new System.Windows.Data.Binding { Converter = new MyConverter(), ConverterParameter = propertyName };
                        column.Header = propertyName;
                        dtGrid.Columns.Add(column);
                    }
                }
                HeaderCre++;
                source.Add(dictObj);
            }

            dtGrid.ItemsSource = source;
            dtGrid.AutoGenerateColumns = false;
            //LayoutRoot.Children.Add(dtGrid);
            innerRoot.Children.Add(dtGrid);
        }



        public class MyConverter : IValueConverter
        {
            #region IValueConverter Members

            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return ((Dictionary<string, object>)value)[(string)parameter];
            }

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
            #endregion
        }

        private void btnRedirect_Click(object sender, RoutedEventArgs e)
        {
            //NavigationContext.Navigate(new Uri("/Views/Home.xaml", UriKind.Relative));
            //NavigationContext.

            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("http://stackoverflow.com"), "_blank");
        }

        private void h_Click(object sender, RoutedEventArgs e)
        {
            h.NavigateUri = new Uri("SecondPage.xaml", UriKind.RelativeOrAbsolute);
        }
           
    }
   
}

My WCF-Service code: class Servce.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Web;
using System.Data.SqlClient;
using System.ServiceModel.Activation;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Collections;


namespace WCFservices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
       static private DataSet dtGolbal = new DataSet();
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }


        public String DoWork()
        {
            String strTstVal = string.Empty;
            strTstVal = HttpContext.Current.Session["strTest"].ToString();
            return strTstVal;
        }


        public DataSet DsReturn()
        {
            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["SQLConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand("select * from hari_login", con);
            con.Open();
            SqlDataAdapter ad = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            ad.Fill(ds);
            con.Close();

            var s = from u in ds.Tables[0].AsEnumerable()
                    select new Dictionary<string, string> {
            { "Name", u["lname"].ToString() },
            { "LastName", u["pass"].ToString() }
        };
            dtGolbal = ds;
            return ds;
        }


        public List<Dictionary<string, object>> ShareListVar(String strSession)
        {
            List<Dictionary<string, object>> source = new List<Dictionary<string, object>>();
            if (dtGolbal != null)
            {
                DataSet ds = dtGolbal;
                DataTable st = new DataTable();
                IEnumerable<Dictionary<string, object>> IEnu = ds.Tables[0].AsEnumerable().Select
                    (r => ds.Tables[0].Columns.Cast<DataColumn>().Select( // for each row of datatable
                        c => new { Column = c.ColumnName, Value = r[c] }) //c => [for each symbol] for each Column of datatable
                        .ToDictionary(i => i.Column, i => i.Value != DBNull.Value ? i.Value : null));

                foreach (Dictionary<string, object> VDict in IEnu)
                {
                    source.Add(VDict);
                }
                var ss = IEnu.First().Keys;
            }
            return source;
        }

        public List<string[]> LstDatsSet(String strSession)
        {
            object h = null;
            StringWriter stringWriter = new StringWriter();
            XmlDocument xmlDoc = new XmlDocument();
            DataSet ds = (DataSet)HttpContext.Current.Session["test"];
            XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);

            List<ArrayList> ListArr = new List<ArrayList>();
            List<string[]> ListArray = new List<string[]>();


            //ArrayOfString newVar = new ArrayOfString();
            foreach (DataRow dataRow in ds.Tables[0].Rows)//Ftb is datatable
            {
                ArrayList values = new ArrayList();
                string[] ss = new string[ds.Tables[0].Columns.Count];
                string ssd;
                int d = 0;
                foreach (object value in dataRow.ItemArray)
                {
                    values.Add(value.ToString());
                    ssd = value.ToString();
                    ss[d++] = ssd;
                }
                ListArray.Add(ss);
                ListArr.Add(values);
            }
            XmlSerializer serializer = new XmlSerializer(ListArr.GetType());
            serializer.Serialize(xmlWriter, ListArr);
            string xmlResult = stringWriter.ToString();
            xmlDoc.LoadXml(xmlResult);

            return ListArray;
        }
    }
}

WCF service interface: IService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.ServiceModel.Activation;
using System.Collections.ObjectModel;

namespace WCFservices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract(SessionMode = SessionMode.Allowed)]
   
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here

        [OperationContract]
        String DoWork();

        [OperationContract]
        DataSet DsReturn();

        [OperationContract]
        List<Dictionary<string, object>> ShareListVar(String strSession);

        [OperationContract]
        List<string[]> LstDatsSet(String strSession);
       
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}