Skip to main content

Microsoft Silverlight

Unanswered Question How to Display DataSet in Silverlight DataGridRSS Feed

(0)

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

How to Display DataSet in Silverlight DataGrid

A lot of people have asked this question. The answer is that there is no direct way.

Current Silverlight does not support DataSet object. I was hoping to see DataSet support in beta 2, but according to people from Microsoft (http://silverlight.net/forums/p/16297/54531.aspx#54531) that DataSet support is not likely even in version 2 final release.

So what should we do? In our application we hold our Data in DataSet from the Data tier to the UI tier. We don't want to covert it to a list of object with pre-defined properties in WCF before we pass it to Silverlight. In our case that is not even possible. In our application almost every SQL is dynamically generated.

One solution is to pass the DataSet Column Information and DataSet XML to the silverlight. On the Silverlight side we build a Dynamic Data Object based on those data with functions provided by System.Reflection.Emit namespace. Then we bind the List of dynamically build DataObject to the DataGrid. The Dynamic Data Object will have one property for each column in the DataSet with the same DataType.

Because we have the Column Information besides the Data,  binding to the DataGrid can be very flexible. I can set AutoGeneratedColumn = true so it display all the Data in the DataSet or I can dynamically generate columns I want to display.


Here is my code in case anybody wants to try:

Steps to Test:

1) Download the Source from http://cid-9cffd385fd75195b.skydrive.live.com/self.aspx/Silverlight/DataSetInDataGrid.zip

2) Open the solution file in VS 2008

3) Find GetData.cs in DataSetInDataGrid.Silverlight project and change the Database connection string to a connection string that connects to your SQL server database.

     private const string connectionString = @"Data Source=LOCALHOST;Initial Catalog=Northwind;Integrated Security=True;";  // change this


4) Set start page to Default.html in DataSetInDataGrid.Silverlight_Web project. Build and run the application.

5) Type in any SQL statement to do a query to your database. The returning data should be displayed in the DataGrid automatically.

6) Implement your UpdateDataSet function in the GetData.cs to update the Data in the DataSet to DB (such as build Update sql statement based on the current data in the DataSet).

 

Let me know if you see any problems.

 

 


       

 

 

 

 

 

 

 

 


 

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

slhungry
slhungry

Member

Member

44 points

30 Posts

Re: How to Display DataSet in Silverlight DataGrid

wow looks like alot of deep heavy stuff to get this working, but i'm glad u have a solution.  i converted it over to beta2 with a few tweaks and works great, but only problem is i can't get it to sort by clicking on the columns.  beta2 supports CanUserReorderColumns property for datagrid but when i click on it, it gives me an error.  "SortDescription's property name is invalid"

it would be so awesome if i can get sorting too, any idea?

samcov
samcov

Participant

Participant

969 points

379 Posts

Re: How to Display DataSet in Silverlight DataGrid

What you want is to be able to dynamically build a DataGrid in SilverLight with ANY data you may deliver from the server.  The data could be an Array of records, a DataSet, XML, or weakly typed JSON, it doesn't matter.  Here is the code I use to do that, and also dynamically create the columns.  I found this code somewhere, but I don't remember where, but it works great.

Here is the code that creates the DataGrid:
    public partial class DynamicGrid : UserControl
    {
        public DynamicGrid()
        {
            InitializeComponent();

            Canvas.SetLeft(butt, 500);

            this.theGrid.Columns.Add(
                        new DataGridTextColumn
                        {
                            Header = "ID",
                            DisplayMemberBinding = new Binding("ID")
                        });
            this.theGrid.Columns.Add(
                        new DataGridTextColumn
                        {
                            Header = "Name",
                            DisplayMemberBinding = new Binding("Name")
                        });
            this.theGrid.Columns.Add(
                        new DataGridTextColumn
                        {
                            Header = "Index",
                            DisplayMemberBinding = new Binding("Index")
                        });
            this.theGrid.Columns.Add(
                        new DataGridCheckBoxColumn
                        {
                            Header = "Is Even",
                            DisplayMemberBinding = new Binding("IsEven")
                        });
            this.theGrid.ItemsSource = GenerateData().ToDataSource();
        }

        public IEnumerable<IDictionary> GenerateData()
        {
            for (var i = 0; i < 1000; i++)
            {
                var dict = new Dictionary<string, object>();
                dict.Add("ID", Guid.NewGuid());
                dict.Add("Name", "Name_" + i);
                dict.Add("Index", i);
                dict.Add("IsEven", i % 2 == 0);
                yield return dict;
            }
        }
    }

To make this work, you need the following Extension Method:
    public static class DataSourceCreator
    {
        private static readonly Regex PropertNameRegex =
                new Regex(@"^[A-Za-z]+[A-Za-z1-9_]*$", RegexOptions.Singleline);

        public static object[] ToDataSource(this IEnumerable<IDictionary> list)
        {
            IDictionary firstDict = null;
            bool hasData = false;
            foreach (IDictionary currentDict in list)
            {
                hasData = true;
                firstDict = currentDict;
                break;
            }
            if (!hasData)
            {
                return new object[] { };
            }
            if (firstDict == null)
            {
                throw new ArgumentException("IDictionary entry cannot be null");
            }

            Type objectType = null;

            TypeBuilder tb = GetTypeBuilder(list.GetHashCode());

            ConstructorBuilder constructor =
                        tb.DefineDefaultConstructor(
                                    MethodAttributes.Public |
                                    MethodAttributes.SpecialName |
                                    MethodAttributes.RTSpecialName);

            foreach (DictionaryEntry pair in firstDict)
            {
                if (PropertNameRegex.IsMatch(Convert.ToString(pair.Key), 0))
                {
                    CreateProperty(tb,
                                    Convert.ToString(pair.Key),
                                    pair.Value == null ?
                                                typeof(object) :
                                                pair.Value.GetType());
                }
                else
                {
                    throw new ArgumentException(
                                @"Each key of IDictionary must be
                                alphanumeric and start with character.");
                }
            }
            objectType = tb.CreateType();
            return GenerateArray(objectType, list, firstDict);
        }

        private static object[] GenerateArray(Type objectType, IEnumerable<IDictionary> list, IDictionary firstDict)
        {
            var itemsSource = new List<object>();
            foreach (var currentDict in list)
            {
                if (currentDict == null)
                {
                    throw new ArgumentException("IDictionary entry cannot be null");
                }
                object row = Activator.CreateInstance(objectType);
                foreach (DictionaryEntry pair in firstDict)
                {
                    if (currentDict.Contains(pair.Key))
                    {
                        PropertyInfo property =
                            objectType.GetProperty(Convert.ToString(pair.Key));
                        property.SetValue(
                            row,
                            Convert.ChangeType(
                                    currentDict[pair.Key],
                                    property.PropertyType,
                                    null),
                            null);
                    }
                }
                itemsSource.Add(row);
            }
            return itemsSource.ToArray();
        }

        private static TypeBuilder GetTypeBuilder(int code)
        {
            AssemblyName an = new AssemblyName("TempAssembly" + code);
            AssemblyBuilder assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    an, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");

            TypeBuilder tb = moduleBuilder.DefineType("TempType" + code
                                , TypeAttributes.Public |
                                TypeAttributes.Class |
                                TypeAttributes.AutoClass |
                                TypeAttributes.AnsiClass |
                                TypeAttributes.BeforeFieldInit |
                                TypeAttributes.AutoLayout
                                , typeof(object));
            return tb;
        }

        private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
        {
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName,
                                                        propertyType,
                                                        FieldAttributes.Private);


            PropertyBuilder propertyBuilder =
                tb.DefineProperty(
                    propertyName, PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder getPropMthdBldr =
                tb.DefineMethod("get_" + propertyName,
                    MethodAttributes.Public |
                    MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig,
                    propertyType, Type.EmptyTypes);

            ILGenerator getIL = getPropMthdBldr.GetILGenerator();

            getIL.Emit(OpCodes.Ldarg_0);
            getIL.Emit(OpCodes.Ldfld, fieldBuilder);
            getIL.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                  MethodAttributes.Public |
                  MethodAttributes.SpecialName |
                  MethodAttributes.HideBySig,
                  null, new Type[] { propertyType });

            ILGenerator setIL = setPropMthdBldr.GetILGenerator();

            setIL.Emit(OpCodes.Ldarg_0);
            setIL.Emit(OpCodes.Ldarg_1);
            setIL.Emit(OpCodes.Stfld, fieldBuilder);
            setIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
    }

This will yield the following Grid:

"The difference between genius and stupidity is that genius has its limits." - Albert Einstein

samcov
samcov

Participant

Participant

969 points

379 Posts

Re: How to Display DataSet in Silverlight DataGrid

I posted all that, and then later saw your link, which is a very similar solution.

I wish I could remember where I got that code, but it works, and is quite fast.

Sam...

"The difference between genius and stupidity is that genius has its limits." - Albert Einstein

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

slhungry:

wow looks like alot of deep heavy stuff to get this working, but i'm glad u have a solution.  i converted it over to beta2 with a few tweaks and works great, but only problem is i can't get it to sort by clicking on the columns.  beta2 supports CanUserReorderColumns property for datagrid but when i click on it, it gives me an error.  "SortDescription's property name is invalid"

it would be so awesome if i can get sorting too, any idea?

Because I have not put any sort code in that sample. Also how to do sort really depend on how you want it. Do you want to go back to the database to re-run the query so your sort really means against all the data or you just want to sort with the current dataset. You can implement that part yourself to fit your need. It should not be that difficult.

 


 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

samcov
samcov

Participant

Participant

969 points

379 Posts

Re: How to Display DataSet in Silverlight DataGrid

samcov:

I wish I could remember where I got that code, but it works, and is quite fast.

Well, I can stop wishing.  Here is the article I got this from.

_uacct = "UA-2223138-1"; urchinTracker();

"The difference between genius and stupidity is that genius has its limits." - Albert Einstein

batmansilver
batmansi...

Member

Member

61 points

58 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hello Sladaper,

As your instruction, I found this post and I tried to download your demo from your link.

When I open it I got some errors like the following...

1. I cannot find the GetData.cs in DataSetInDataGrid.Silverlight project.

2. In the reference of SL project, there are warning icons on System.Windows.Controls.Data, System.Windows.Controls.Data. So I tried to remove and add reference again. But I got the errors:

Library project file cannot specify ApplicationDefinition element.

The project file contains a property value that is not valid


I'm using Silverlight 2 Beta 1. Is this the Silverlight 2 Beta 2 project? if so how can I use it in Beta 1?

Thank you. 

Thanks and Best Regards

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

It used to be beta1 project. But I updated it after beta2 was released. I don't know if I can still find the original zip file. 

Why are you still using beta1?

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

batmansilver
batmansi...

Member

Member

61 points

58 Posts

Re: How to Display DataSet in Silverlight DataGrid

I have many small projects in Beta 1 and now I don't have enought time to convert (also I must look in detail of Beta 2 to convert...).

If you can give me the version in Beta 1, that'll be very good. But I don't want you to cost much time to find back so it's ok. Maybe I will try another way.

Thank you. 

Thanks and Best Regards

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

Sorry, I do not have the original file any more.

For converting from beta 1 to beta 2, it will take some effort. It took me a few days to fully convert my projects and have every issues resolved. But issues mainly come from a few areas. MouseDownEvent break for many controls is one, WCF Service cross-domain file change is another. Other than that, I just need to fix some Xaml and code to use the new syntax.

But you have to do it anyway. Because now all the code samples are in beta2. All the demo sites are updated to beta2. Most discussions here are about beta2. You have no other choice.

 

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

 

samcov:

I posted all that, and then later saw your link, which is a very similar solution.

I wish I could remember where I got that code, but it works, and is quite fast.

Sam...

Sam,

Have you tried your Dynamic Grid code in beta 2? Does the new DataGrid built-in Sort function work in your grid? Is does not work on mine. I think it's because we bind the ItemsSource to a List<object> so Linq won't work on this dynamically build object list.

I looked at the code you posted, it's basically the same idea to Dynamically build a object using functions/objects provided by System.Reflection.Emit name space. So I'm wondering if the sort function works for you.

I don't know if I can figure out a way to make Linq work on those list.

Thanks!

 

Never mind. I got it working now. Thanks for that link you provided.

 

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

 

slhungry:

wow looks like alot of deep heavy stuff to get this working, but i'm glad u have a solution.  i converted it over to beta2 with a few tweaks and works great, but only problem is i can't get it to sort by clicking on the columns.  beta2 supports CanUserReorderColumns property for datagrid but when i click on it, it gives me an error.  "SortDescription's property name is invalid"

it would be so awesome if i can get sorting too, any idea?

 slhungry,

Get the latest, sorting is working now.

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

samcov
samcov

Participant

Participant

969 points

379 Posts

Re: How to Display DataSet in Silverlight DataGrid

The code works well in Beta 2, but you're right, the sorting doesn't work.

I'll take a look at your code.

Thanks!

"The difference between genius and stupidity is that genius has its limits." - Albert Einstein

RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid


RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter,

Thanks for your code. Its working fine.

 I have tried to reproduce it. But I am not able to get the results.

I am getting following error.

The remote server returned an unexpected response: (404) Not Found.

Could you please help me with this.

Thanks and Regards,

Rams

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

That must be WCF connection error. You can remove the Service Reference first then re-add it back.  If it still not working let me know. I'll help you to figure out.

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid

 Hi Sladapter,

Thanks for your reply.

I have done that. But no success.

I have noticed one chage ServiceReferences.ClientConfig file

In ur code it is 

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="LargeSize_IGetData" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:3317/DataSetInDataGrid.Silverlight_Web/GetData.svc"
                binding="basicHttpBinding" bindingConfiguration="LargeSize_IGetData"
                contract="DataSetInDataGrid.Silverlight.GetDataService.IGetData"
                name="LargeSize_IGetData" />
        </client>
    </system.serviceModel>
</configuration>

In my code it generated like this

<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IGetData" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Message">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="Windows" negotiateServiceCredential="true"
                            algorithmSuite="Default" establishSecurityContext="true" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>        
    </system.serviceModel>
</configuration>

I guess it is the problem.

Thanks,

Rams.

 

 

 

RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter,

My problem was solved.

I have changed the  <system.serviceModel> in my web.config file.

Now its working fine.

Thank you very much for your support.

Rams.

 

jhoffa
jhoffa

Member

Member

22 points

29 Posts

Re: How to Display DataSet in Silverlight DataGrid

sladapter:
WCF Service cross-domain file change is another
 

I was going to ask what you meant by that, but was able to track it down myself.  In case it might save anyone some time, clientaccesspolicy.xml now needs the bolded "http-request-headers" attribute.  Here's what I have for the most generic clientaccesspolicy.xml as of Silverlight 2 Beta 2.

<?xml version="1.0" encoding="utf-8"?>
   <access-policy>
     <cross-domain-access>
       <policy>
         <allow-from http-request-headers="*">
           <domain uri="*"/>
         </allow-from>
         <grant-to>
           <resource path="/" include-subpaths="true"/>
         </grant-to>
       </policy>
     </cross-domain-access>
   </access-policy>

batmansilver
batmansi...

Member

Member

61 points

58 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter,

I tried your demo. It's work fine but I have some questions.
#1. I have a class or struct in SL. This class will receive the information the user input in SL project (eg. Student - a custom data) and in my asp.net project I have create a WCF webservice to save the student information to database but it must receive from the Student class in SL project so how to send this information as a parameter to the webservice in asp.net.

#2. the same as the first one, if the webservice return a class defined in asp.net project or the database object like DataTable, DataRow,... so how to use the return value in Silverlight?

#3. I see you have the DynamicDataBuilder class. I don't understand the code but I understand it is for using the data return from webservice to use in Silverlight.
But is this class is general solution for receiving any custom data ? can I use it in my case to bind to my SL usercontrol...? if not, please tell me how to archive this to use in my specific case. I really want to know because I need to do SCUD in SL but in the old way using SqlServer data provider.

Could you explain or give me guide material what I need to know about transfer defined data between SL and asp.net and use the transfer data in both SL and asp.net side???
Waiting for the reply!!!

Thank you and Regard.

John.


 

Thanks and Best Regards

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

John,

My solution is mainly for generic data display which means I do not have or I do not I want a pre-defined data object. Because our data is very dynamic.  We have more than 1000 tables which I do not want to define object for each of them. Plus our tables also can be customized which means the table fields could be changed/added/removed by customer(Company who brought our application) later. The SQL for query data is also very dynamic. Each user can set filter based on different field and can select different column as they want.

That is why I have to create a dynamic data object based on the DataSet data and column infomation. In real case my column infomation is really comming from our meta data which describe each field of our object. Because Silverlight does not support DataSet/DataTable, so I can not pass back DataSet directly. I have to pass back serialized Xml string to Silverlight then convert it to a list of DynamicDataObject. When I try to save data, I covert my List of DynamicDataObject to XML string and pass it back to WCF. On the WCF I process this Xml and do the update to database accordingly.

If you have a pre-defined data object such as Student class and your application is not as complicated as ours,  then you do not need to use this solution. Use LinQ + Entity model + WCF service or use .Net DataService might be better for your case. By using that, your code would be easy to program and understand.

If you still like to use the old way of SQL + DataSet  to access your data, then you can convert the DataSet to your Student object on WCF code before you return it to Silverlight. You need to move your Student class defination to the Service side. Then just pass populated Student List back to Silverlight. Then bind the list to your DataGrid or other controls.

There are a lot of tutorials on this subject. Take a look at them. Here is one  http://silverlight.net/learn/tutorials/sqldatagrid.aspx

 

 

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

batmansilver
batmansi...

Member

Member

61 points

58 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter,

I really thank you for your detail explaination. It will help me alot because I am using SqlServer data provider and store procedure and of course my data is not complicated. I'm trying to test by making 2 same class of pre-defined object in SL and asp.net about Student so I can test if this way will work.

Thank you and Regard,

John. 

Thanks and Best Regards

RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter,

I have a small doubt.

In your code after getting details from database we are converting them to list of objects using the following line. Right?

theGrid.ItemsSource = DynamicDataBuilder.GetDataList(e.Result);

But in my case i need to access induvidual recored.

for example, I am retrieving user details and I want display the first user's name.

I have tried like this

  • created a class named User
  • List<User> UserDetails =(List<User>)DynamicDataBuilder.GetDataList(e.Result);
     txtUserName.Text = ((User)UserDetails[0]).UserName;

But it results in typecasting problem.

Please suggest me a better way to get the details.

Thanks,

Rams.

 

 


 

 

 

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

For the DynamicData List, you can not do something like this:

((User)UserDetails[0]).UserName;

The reason I build DynamicDataList is because I have no pre-defined data object such as the User object. If you have pre-defined data object you can just populate your User List using the DataSet XML data. That would be easier.

But with DynamicData I have made single row data access possible. It's not in this demo.

Right now I'm building my List page and Details page using the same list of data. I can build all the pages for our application (for all our objects) without pre-define any object structure. If you are interested, I can mail you some demo.

Besically I have made the DymanicData a sub class of my DataObject class. The DataObject class has GetFieldValue and SetFieldValue function. that is for accessing each field value.

public class DataObject : INotifyPropertyChanged
    {       
        public enum DataStates
        {
            Unchanged = 2,
            Added = 4,
            Deleted = 8,
            Modified = 16,
        }
        public DataStates State { get; set; }
        public object GetFieldValue(string fieldname)
        {
            PropertyInfo pi = this.GetType().GetProperty(fieldname);
            if(pi != null)
                return pi.GetValue(this, null);
            return null;
        }
        public void SetFieldValue(string fieldname, object value, bool initial)
        {
            this.SetFieldValue(fieldname, value);
            if (initial)
                this.State = DataStates.Unchanged;

        }
        public void SetFieldValue(string fieldname, object value)
        {
            PropertyInfo pi = this.GetType().GetProperty(fieldname);
            if (pi != null)
            {
                object pValue = Convert.ChangeType(value, pi.PropertyType, null);
                if (pValue != null)
                    pi.SetValue(this, pValue, null);
            }   
        }
        public void Delete()
        {
            this.State = DataStates.Deleted;
        }
        public void NewRow()
        {
            this.State = DataStates.Added;
        }
        protected void NotifyChange(params string[] properties)
        {
            if (PropertyChanged != null)
            {
                foreach (string p in properties)
                    PropertyChanged(this, new PropertyChangedEventArgs(p));
                this.State = DataStates.Modified;
            }
        }
        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }

 

The new DynamicDataBuilder code:

public class DynamicDataBuilder
    {
        private static System.Type BuildDataObjectType(ObservableCollection<GenericService.ColumnInfo> Columns, string DataObjectName)
        {
            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("AprimoDynamicData"), AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DataModule");

            TypeBuilder tb = moduleBuilder.DefineType(DataObjectName,
                                                    TypeAttributes.Public |
                                                    TypeAttributes.Class,                                                   
                                                    typeof(DataObject));

            ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
            foreach (var col in Columns)
            {
                string propertyName = col.ColumnName.Replace(' ', '_');
                col.DataType = System.Type.GetType(col.DataTypeName, false, true);
                if (col.DataType != null)
                {
                    FieldBuilder fb = tb.DefineField("_" + propertyName, col.DataType, FieldAttributes.Private);
                    PropertyBuilder pb = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, col.DataType, null);
                    MethodBuilder getMethod = tb.DefineMethod("get_" + propertyName,
                                                                MethodAttributes.Public |
                                                                MethodAttributes.HideBySig |
                                                                MethodAttributes.SpecialName,
                                                                col.DataType,
                                                                Type.EmptyTypes);

                    ILGenerator ilgen = getMethod.GetILGenerator();
                    //Emit Get property, return _prop
                    ilgen.Emit(OpCodes.Ldarg_0);
                    ilgen.Emit(OpCodes.Ldfld, fb);
                    ilgen.Emit(OpCodes.Ret);
                    pb.SetGetMethod(getMethod);
                    MethodBuilder setMethod = tb.DefineMethod("set_" + propertyName,
                    MethodAttributes.Public |
                    MethodAttributes.HideBySig |
                    MethodAttributes.SpecialName,
                    null,
                    new Type[] { col.DataType });
                    ilgen = setMethod.GetILGenerator();
                    LocalBuilder localBuilder = ilgen.DeclareLocal(typeof(String[]));
                    //Emit set property, _Prop = value;
                    ilgen.Emit(OpCodes.Ldarg_0);
                    ilgen.Emit(OpCodes.Ldarg_1);
                    ilgen.Emit(OpCodes.Stfld, fb);

                    //Notify Change:
                    Type[] wlParams = new Type[] { typeof(string[]) };
                    MethodInfo notifyMI = typeof(DataObject).GetMethod("NotifyChange",
                    BindingFlags.NonPublic |
                    BindingFlags.Instance,
                    null,
                    CallingConventions.HasThis,
                    wlParams,
                    null);

                    //NotifyChange Property change
                    ilgen.Emit(OpCodes.Ldc_I4_1);
                    ilgen.Emit(OpCodes.Newarr, typeof(String));
                    ilgen.Emit(OpCodes.Stloc_0);
                    ilgen.Emit(OpCodes.Ldloc_0);
                    ilgen.Emit(OpCodes.Ldc_I4_0);
                    ilgen.Emit(OpCodes.Ldstr, propertyName);
                    ilgen.Emit(OpCodes.Stelem_Ref);
                    ilgen.Emit(OpCodes.Ldarg_0);
                    ilgen.Emit(OpCodes.Ldloc_0);
                    ilgen.EmitCall(OpCodes.Call, notifyMI, null); // call nodifyChange function

                    ilgen.Emit(OpCodes.Ret);
                    pb.SetSetMethod(setMethod);
                }
            }
            System.Type rowType = tb.CreateType();
            //assemblyBuilder.Save("DynamicData.dll");
            return rowType;
        }

        public static IEnumerable GetDataList(GenericService.DataSetData data)
        {
            if (data.Tables.Count() == 0)
                return null;

            GenericService.DataTableInfo tableInfo = data.Tables[0];

            System.Type dataType = BuildDataObjectType(tableInfo.Columns, "MyDataObject");

            ObservableCollection<DataObject> l = new ObservableCollection<DataObject>();

            var listType = typeof(ObservableCollection<>).MakeGenericType(new[] { dataType });
            var list = Activator.CreateInstance(listType);
           
            XDocument xd = XDocument.Parse(data.DataXML);
            var table = from row in xd.Descendants(tableInfo.TableName)
                        select row.Elements().ToDictionary(r => r.Name, r => r.Value);
           
            foreach (var r in table)
            {
                var rowData = Activator.CreateInstance(dataType) as DataObject;
                if (rowData != null)
                {
                    foreach (GenericService.ColumnInfo col in tableInfo.Columns)
                    {
                        if (r.ContainsKey(col.ColumnName) && col.DataType != null && col.DataType != typeof(System.Byte[]))
                            rowData.SetFieldValue(col.ColumnName, r[col.ColumnName], true);              
                    }
                }
                listType.GetMethod("Add").Invoke(list, new[] { rowData });                              
            }
           
            return list as IEnumerable;
        }

        public static string GetUpdatedDataSet(IEnumerable list)
        {
            XElement root = new XElement("DataSet");           
            foreach (DataObject d in list)
            {               
                if (d.State == DataObject.DataStates.Modified)
                {
                    XElement row = new XElement("Data", new XAttribute("RowState", d.State.ToString()));                   
                    PropertyInfo[] pis = d.GetType().GetProperties();
                    foreach (PropertyInfo pi in pis)
                        row.Add(new XElement(pi.Name, pi.GetValue(d, null).ToString()));
                    root.Add(row);
                }
            }
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), root);
            return xdoc.ToString();                           
        }
    }

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid

 Hi Sladapter,

Thanks for your reply.

I am very much interested to see you code. Please give me sample code for inserting and Updating also if you have.

Here is my email id.

ramsjone@hotmail.com

I will be thankful if you send me the code.

Rams.

peterralphylee
peterral...

Member

Member

21 points

11 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter, I have just posted this question in this thread http://silverlight.net/forums/p/18852/71882.aspx#71882 (in case anybody wants to look), but I am moving it here as you suggested, for the benefit of others I'll post all of the information so far:

basically I am trying to implement sladapter's solution to displaying a dataset in my datagrid as I need to display dynamic data that I will not always know the exact structure for, therefore this solution is perfect, apart from I am writing it in vb. Now everything appears to be working absolutely fine and I have converted it into vb nicely and I can see the data populating the object that I create within my web service.svc.vb, I'm stepping through it with debug watching it populate, but as soon as it tries to return the result from the service to the silverlight it gets stuck in the transfer and throws up the 404 error. It happens in my Reference.vb in this function:

 

Public Function EndGetOneRecCRMTable(ByRef CRMTableName As String, ByRef ErrorStr As String, ByVal result As System.IAsyncResult) As Object Implements ServiceReference1.SLService.EndGetOneRecCRMTable

Dim _args((2) - 1) As Object

_args(0) = CRMTableName

_args(1) = ErrorStr

Dim _result As Object = CType(MyBase.EndInvoke("GetOneRecCRMTable", _args, result),Object)

CRMTableName = CType(_args(0),String)

ErrorStr = CType(_args(1),String) Return _result

End Function

 

it always highlights the object at the end of this line: Dim _result As Object = CType(MyBase.EndInvoke("GetOneRecCRMTable", _args, result),Object)

The data I am trying to return is a single record from a sql table made up of fields which include integers and strings, my vb version of your GetData.cs is below, it is not exactly identical as it needs to fit in with the way I have already populated my dataset and also with the way we organise our tableobjects, hopefully I've converted it from c# correctly, thank you again for responding to this:

 

    <OperationContract()> _

Public Function GetOneRecCRMTable(ByRef CRMTableName As String, ByRef ErrorStr As String)

        Dim CRMTemplateObj As New BusinessLayer.BL_CRMTemplate

        Dim CRMDataSet As New DataSet

        Dim Valid As Boolean = False

        GetOneRecCRMTable = Nothing

 

        Valid = CRMTemplateObj.GetOneRecSLDataSet(CRMTableName, CRMDataSet, ErrorStr)

 

        If Valid Then

            Dim CRMDataSetData As New TableObjects.DynamicDataSetData

            Dim CRMDataTable As New DataTable

 

            CRMDataSetData.Tables = New List(Of TableObjects.DynamicDataTableInfo)

 

            For Each CRMDataTable In CRMDataSet.Tables

                Dim CRMDataTableInfo = New TableObjects.DynamicDataTableInfo

                Dim CRMDataColumn As New DataColumn

 

                CRMDataTableInfo.TableName = CRMDataTable.TableName

                CRMDataSetData.Tables.Add(CRMDataTableInfo)

                CRMDataTableInfo.Columns = New List(Of TableObjects.DynamicDataColumnInfo)

 

                For Each CRMDataColumn In CRMDataTable.Columns

                    Dim CRMDataColumnInfo As New TableObjects.DynamicDataColumnInfo

 

                    CRMDataColumnInfo.ColumnName = CRMDataColumn.ColumnName

                    CRMDataColumnInfo.DataTypeName = CRMDataColumn.DataType.FullName

 

                    CRMDataTableInfo.Columns.Add(CRMDataColumnInfo)

 

                Next

 

            Next

 

            CRMDataSetData.DataXML = CRMDataSet.GetXml

 

            GetOneRecCRMTable = CRMDataSetData

 

        End If

 

        CRMTemplateObj = Nothing

 

    End Function

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

I saw your function defination is this:

  Public Function GetOneRecCRMTable(ByRef CRMTableName As String, ByRef ErrorStr As String)

I don't know if the using ByRef type Parameter works in WCF or not (I have never tried it). You can first test this by taking out "ByRef". I know you might want to return the TableName and error string back. For error string back you can use "Out" parameter ( I know that would work because some one showed code). For table name, you can return the Table name in your DataSetData so you do not need it return as a function parameter.

Make sure update your service reference after you changed service code. 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

peterralphylee
peterral...

Member

Member

21 points

11 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi, the byref definately works on my other functions, it's pretty useful, I'll take it out and try it with this one though, (nice tip with the out parameter) however.....I think I may have found my problem; I'm not serializing properly in my tableobjects. A silly (and embarrassing) mistake of mine, I'm fairly certain it's this that is the problem though! I'll try a couple of things and I'll be back!

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

 If "byref" works in other functions, then you can keep it. That's not the problem. It's good to know too, I might need it in the future as well.

 If you find serialization problem that most likely is the cause of your 404 error.

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

peterralphylee
peterral...

Member

Member

21 points

11 Posts

Re: How to Display DataSet in Silverlight DataGrid

Ok if I wasn't bald I'd be tearing my hair out with this now. I think I am serializing my table objects correctly, however where as I notice in the c# version the wcf service seems to be serializing the returned result correctly in reference.cs. However my wcf service does not appear to be serializing my datasetdata at all from looking in reference.vb, in fact from what I can tell it doesn't seem to acknowledge that it needs to be serialized, which seems very strange.

Does anybody know exactly how to do the serilization in VB? I've tried looking everywhere, but everyones examples all seem to be in c#! Some example code of one of my tableobjects is below, the function remains the same as previously posted.

 

Imports System.Runtime.Serialization

 

<DataContract()> Public Class DynamicDataTableInfo

 

    Private mTableName As String

    Private mColumns As List(Of DynamicDataColumnInfo)

 

    <DataMember()> Property TableName() As String

        Get

            Return mTableName

        End Get

        Set(ByVal Value As String)

            mTableName = Value

        End Set

    End Property

 

    <DataMember()> Property Columns() As List(Of DynamicDataColumnInfo)

        Get

            Return mColumns

        End Get

        Set(ByVal Value As List(Of DynamicDataColumnInfo))

            mColumns = Value

        End Set

    End Property

 

End Class

peterralphylee
peterral...

Member

Member

21 points

11 Posts

Re: How to Display DataSet in Silverlight DataGrid

Ha ha! I've solved the passsing over issue, it didn't know what to send it back as and I was not explicitly telling the function. I needed to include this extra part on the end of the first line of the function: as TableObjects.DynamicDataSetData

RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter,

I have to save changes made in data grid to the database.

I have tried to find the modified object in the RowEdited, DataGridColumn_EndEditing events.

But I am not able find the RowOject because this solution is mainly for generic data display.

Is there any disadvantages in using LINQ to SQL ?I think we can achieve this easily using LINQ to SQL.

Could you please suggest me a better way to reflect datagrid changes in database.

Thanks in advance,

Rams.

 

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

Rams,

I've been busy with something else lately so I have not had time to put up a sample project for you as you asked before. I'll try to do to it today.

Anyway the only disadvantage for using LINQ to SQL is you need to pre-define object. If your data table is fixed and your list is fixed, your database is Sql server, then using Linq to SQL might be the easiest.

I can not do it because our data table is not fixed (after we deploy our app, the customer can even change the table to add more columns). Our app need to support both Sql server and Oracle (and other DB). The SQL statement in our application is dynamically build by end user (they use a Filter object and Filter page to define what column they want to see, based on what criteria for each list). In that case, I can not use Linq to SQL because Linq to SQL is still lack those dynamic features. Plus I want to automate the process to generate each list in our application. So for me using generic data list is the best option. 

But every one has different need. If your case is not like ours then you might be better off to use Linq to SQL. It's very a elegent way to do programming. The code is much easier to understand than the generic way. I like it a lot. If I need to write a simple quick Web application (using Sql server) I definately would choose Linq to SQL.

 

 

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter,

Thank you very much for your continuous support.

You are right. LINQ to SQL lack dynamic feature which is very important for our applications.

I have tried like this

  • In GetData.cs I have created a function which return list of objects some thing like this.
              public List<Order> GetOrders(string Sql)
              {
                  --------------------------
              }
  • In IGetData interface

             [OperationContract]
             List<Order> GetOrders(string SQL);

When I try to update service reference I am getting the following error.

The remote server returned an error:(415) Unsupported media type.

Anyway.... I am waiting for your code.Smile

Thanks again,

Rams.

 

 



sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

 Rams,

The link is updated. You can get the latest now.

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

RamsZone
RamsZone

Member

Member

160 points

159 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi Sladapter,

Thanks you very much for spending your valuable time for me.

I will check this and get back to you soon.

Thanks again.

Rams.

 

mithunster
mithunster

Member

Member

3 points

31 Posts

Re: How to Display DataSet in Silverlight DataGrid

Thats some sweet code and does an awesome job. I am running into a weird issue though. My column info is getting repeated on every row.

This is what i mean:

 Col1 Col2 Col3 Col1 Col2 Col3 State

where Colx is a column in a row. Also, it adds a State Column at the end. When i debug the code, the columns collection does not contain repeated values and it does not contain the "State" column either.

Any help would be appreciated.

 

Thanks,

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

Make sure AutoGenerateColumns="False" on your DataGrid. The "State" Column is a Property for every DataObject to indicate any DataChange for that row. When you build you DataGrid.Columns collection, you should check to skip this column because you do not want to display it. I'll update my demo when I have time. 

The code I provided only meant to show people how to do things this way. It is not the code you can just use without any modification. If you want to go this way, you need to understand the code. Then you can make it work for your case.


 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

varshavmane
varshavmane

Contributor

Contributor

6575 points

1,551 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hello Sladapter,

I am trying to use your code for the datagrid in my Porject as our requirement is very much similiar to get the data Runtime. I wrote a Store Procedure to get the data, here is what I get:

Description                    Stage 1 To Stage 2             Stage 2 To Stage 3               Stage 3 To Stage 4

----------------------------------------------------------------------------------------------------------------------------------------

Untreated                           100.00                                     60.00                                40.00
Quarters                               5.00                                      3.00                                  2.00
Deaths                                 100.00                                 50.00                                 20.00
Quarters                                 3.00                                   1.50                                   0.60
Cures                                 100.00                                    50.00                                 50.00
Quarters                                 4.00                                   2.00                                   2.00

 What we want is to do calculations on the editable cells. Here 1st, 3rd and 5th rows 3th and 4th cell is editable. Whenever user changes 60 to anything then the calculation will be as follows:

consider A[0][0] as Untreated cell and likewise others.

so A[1][2] = A[1][1] * (A[0][2] / 100)

A[1][3] = A[1][1] * (A[0][3] / 100 )

but when I edit A[0][2] it updates the dataset but doesnt do the calculation. I hope I made myself clear.

Can you please help me.

Thnanks in advance.

Please "Mark as Answer" if this post answered your question. :)
Visit my Blog: http://varshavmane.blogspot.com/

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

 varshavmane,

I'm not sure I understand you. Where did put your logic to do the calculation? Do you have code in Silverlight to do the calculation based on user input and update your data that bind to the DataGrid?

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

varshavmane
varshavmane

Contributor

Contributor

6575 points

1,551 Posts

Re: How to Display DataSet in Silverlight DataGrid

Thanks for the reply. Actually I am trying to put the logic in LostFocus Event of Datagrid but the problem is that I dont get the next row index. I have to do the calculation on the edit cel and the next row of that editable row.

Can you please tell me how to do this as I dont want to go to WCF Service to do the calculations.

Also once I finish with everything I have to save all the values to database on save button click event.

Thanks again.

Please "Mark as Answer" if this post answered your question. :)
Visit my Blog: http://varshavmane.blogspot.com/

chadbr
chadbr

Member

Member

53 points

27 Posts

Re: Re: How to Display DataSet in Silverlight DataGrid

If this has any appeal to you -- please vote for a DataTable / DataSet feature to be added to the Silverlght toolkit:

DataTable and DataSet support - http://silverlight.codeplex.com/WorkItem/View.aspx?WorkItemId=2810

anil_litam
anil_litam

Member

Member

552 points

258 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi sladapter,

I downloaded the source code of the given URL. But It was coded in C#.

I tried to convert this code to VB.NET resulting so many syntax errors.  ( I am using Silverlight 3.0 beta)

Is there any option for me to download this same project in VB.NET.

Thanks in Advance...

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

Sorry, I don't have the project in VB.NET. But I'm not sure converting it to VB.NET should be that hard. I used to use VB before C# came out, so I don't think the syntax difference between VB and C# are that significant.  

I haven't tried the project in SL3 beta yet.

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

rrvenki
rrvenki

Member

Member

20 points

15 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi,

I converted the entire solution into VB.NET.  I'm facing unsolvable issues in few places.

1.  DynamicDataBuilder.VB has error in following lines.

Dim listType = GetType(ObservableCollection(Of )).MakeGenericType(New() {dataType})

listType.GetMethod("Add").Invoke(List,new() {rowData})

Also.  In the WCF service i imported system.data.common and used "DBParameter" as one of the parameter to the OperationContract.  This gives error in Reference.VB.  This applies to generic "DBTransaction" too.  Below is the error causing line.

 <System.Diagnostics.DebuggerStepThroughAttribute(), _
     System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0"), _
     System.Runtime.Serialization.DataContractAttribute(Name:="DbParameter", [Namespace]:="http://schemas.datacontract.org/2004/07/System.Data.Common"), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(System.MarshalByRefObject)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.DBFrameworkExecuteMethod)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(System.Collections.ObjectModel.ObservableCollection(Of OPaLDataService.DbParameter))), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.DbTransaction)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.CustomException)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.DataSetData)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(System.Collections.ObjectModel.ObservableCollection(Of OPaLDataService.DataTableInfo))), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.DataTableInfo)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(System.Collections.ObjectModel.ObservableCollection(Of OPaLDataService.DataColumnInfo))), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.DataColumnInfo)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.DbType)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.ParameterDirection)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.DataRowVersion)), _
     System.Runtime.Serialization.KnownTypeAttribute(GetType(OPaLDataService.CommandType))> _
    Partial Public Class DbParameter
        Inherits System.MarshalByRefObject
        Implements System.ComponentModel.INotifyPropertyChanged

 

Any help will be appreciated.

Regards

RV

RV

anil_litam
anil_litam

Member

Member

552 points

258 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi,

I read lot of articles regarding Returning dataset result to Silverlight to fill Grid control.

None matched with my requirement.

Procedure i am following to Bind the Grid: 

Step 1) I am requesting to WCF to bind grid.

Step 2) wcf is going to class file called as controller.vb

Step 3) controller is requesting to BuildQuery class file

Step 4) BuildQuery.vb file requesting to ExecQuery.vb file.

Step 5) In this class file (ExecQuery.vb) , query is executing against the DataBase, and result is storing in DATASET.

As i know, we can't pass DATASET directly from WCF to bind the grid.

So, i need to perform some manipulations here and the result is passed through WCF to bind my Grid.

Whats the mechanism i need to follow here.

REQUIREMENT is no class files should be added in Silverlight application.

Can any one please help me on this..

jvanderbiest
jvanderb...

Member

Member

56 points

15 Posts

Re: How to Display DataSet in Silverlight DataGrid

 this is a really nice piece of programming skills

 

thanks for this sladapter!

I hope this helps. Please click on the "Mark as Answer" if it has answered your question.

anil_litam
anil_litam

Member

Member

552 points

258 Posts

Re: How to Display DataSet in Silverlight DataGrid

HI sladapter,

I worked on your link and it's working fine.

If suppose i don't to perform any operations at client side, [as you did sending data to dynamicbuilder class etc],

Every thing should be done at service and the resultSet should be bind to grid directly.

Is there any approach for this.

OR  Shall i get the data from WCF method( in the form of DataSetData and doing any manipulations at SL xaml page)

(I did the following work, it worked only for columns, but data is not binding)

AT WCF Side:

<OperationContract()> _
    Public Function ReceiveFromSL(ByVal sAppFlow As String, ByVal sStepName As String) As DataSetData
        Dim oController As XICore.XIController
        oController = New XICore.XIController()
        Dim strr12 As String = ""
        Return oController.StepExecute(sAppFlow, sStepName)
    End Function
 At xaml side  

MessageBox.Show(e.Result.DataXML())   --> displaying total result in the form of xml (columns  +   Data)

For Each mylval In e.Result.Tables()

For Each col In mylval.Columns

Dim TextColumn As New DataGridTextColumn

TextColumn.Header = col.ColumnTitle

TextColumn.Binding = New Binding("kumar")

GrdCollection.Columns.Add(TextColumn)    --> only column is binding, but not data

Next

Next

 How can i bind Column followed by data to my GRID

Thanks in Advance....

rushi199
rushi199

Member

Member

8 points

5 Posts

Re: How to Display DataSet in Silverlight DataGrid

 

 Sir,

i  have started using silverlight before few days.This post  related to Display DataSet in Silverlight DataGrid was as per my requirement as i do not want to create class and its object while binding data to silverlight datagrid I downloaded this code and when i was debugging to understand its flow, i found out that i am getting exception of type System.NotSupportedException  in DynamicDataBulider.cs and a result after execution of very first line  i.e.         AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("AprimoDynamicData"), AssemblyBuilderAccess.Run); in BuildDataObjectType() function.I guessed that it has something to do with assembly AprimoDynamicData which i do not find in application.And as a result of all these things,i am not getting data to bind it to my grid.So can u plz help me out in solving this issue.

Thanks and Kind Regards,

Rushi Patel.

anil_litam
anil_litam

Member

Member

552 points

258 Posts

Re: How to Display DataSet in Silverlight DataGrid

i don't think so you will get any problem while running the application as it is.

Might you need to change database connections. try deleting and adding reference once again.

let me know still any problems

rushi199
rushi199

Member

Member

8 points

5 Posts

Re: Re: How to Display DataSet in Silverlight DataGrid

 Hi,

As you have mentioned that i need to give reference to dll.But i did not find concerned dll with the code i have downloaded.I have also make sure that i have connection with my local database.Error which i was facing before still persists.

Thanks and Kind Regards,

Rushi.

 

 

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

"AprimoDynamicData" is the name I gave to the Dynamic Assembly I was trying to build. That assembly is dynamically built when you run the code trying to build the dynamic data object. You can not add reference of this dll in your project because it's dynamically built. You can change  "AprimoDynamicData" to any name you want.

The solution file should already have everything you need to run this demo. The only thing you need to do is to change the connection string in the GetData.cs under the DataSetInDataGrid.Silverlight_Web/App_Code folder to a connection string to connect to your SQL server database, then build your solution.

public class GetData
{
    // Change this connection string to your need.
    private const string connectionString = @"Data Source=LOCALHOST;Initial Catalog=Northwind;Integrated Security=True;";
   

...

}

 

Are you sure you are getting error on the following line?

AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("AprimoDynamicData"), AssemblyBuilderAccess.Run);

 

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

rushi199
rushi199

Member

Member

8 points

5 Posts

Re: Re: How to Display DataSet in Silverlight DataGrid

Thanks sladapter,

It works perfectly this time. 

Thanks and Regards,

Rushi Patel.

 

pn
pn

Member

Member

8 points

29 Posts

Re: Re: Re: How to Display DataSet in Silverlight DataGrid

 I know its a silly thing to ask, but can u please tell me the steps to create this program ..

 

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: Re: Re: How to Display DataSet in Silverlight DataGrid

 I listed all the steps on my first post.

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

pn
pn

Member

Member

8 points

29 Posts

Re: Re: Re: Re: How to Display DataSet in Silverlight DataGrid

 My problem is that i have to create a custom datagrid control with a dynamic wcf service. The linq class will be in the client application. So how should i know the return type of my wcf service when i don't know the table the user wants the data from .

Please help .. 

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: Re: Re: Re: How to Display DataSet in Silverlight DataGrid

I still don't quite understand your problem. But sounds like you do not need this displaying DataSet in DataGrid approach. There are many ways to display DB data in a DataGrid. Such as Linq to SQL + WCF service, ADO DataService,  the new .NET RIA Services in SL3 etc. You might want to read more about them.

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

VitalyL
VitalyL

Member

Member

34 points

24 Posts

Re: Re: Re: Re: Re: How to Display DataSet in Silverlight DataGrid

Hi guys,

There is a way to bind ADO.Net DataSet to Silverlight DataGrid or any other controls.

Here is a solution: http://silverlightdataset.codeplex.com/

You can ping me for additional information at vlaskarzhevsky@msn.com

Enjoy your coding.

Vitaly Laskarzhevsky

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: Re: Re: Re: Re: How to Display DataSet in Silverlight DataGrid

 Vitaly,

Thanks for the link and solution. I downloaded your code and tried it. Nice stuff! Glad more people are working on this direction. Because DataSet support is definitely needed.

One problem I found with your demo is that if I set DataGrid.AutoGeneratedColumn to true, then no real data is displayed. Same problem with the SL3 DataForm.  Have you noteced?

 


 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

bydia2
bydia2

Member

Member

12 points

7 Posts

Re: How to Display DataSet in Silverlight DataGrid

Read all the posts to date, read the linked articles and tried some of the samples.  I'm impressed, I should have checked here a long time ago.

Here's what I'm looking for. I already have a large investment in server(and client) processing of non-typed datasets. Both our web and winform clients use the results.  It would be nice to have a CSharp class for Silverlight that takes in an dataset xml, changes it into a strong typed object for multple data binding: data grid and data form... and then finally, allows me to return a dataset diffgram xml to the server for optimistic(optional) updating.

Besides the actual objects for data binding in Silverlight, it should also allow indexed access should we need to get at the table and fields from code.  Maybe something like the following code:

DataSet ds= ParseData(DataSetXml).ToDataSet();
this.theGrid.ItemsSource = ds["Table1"]; //bind to strong typed table

Anyone interested?

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

Didn't you see VitalyL's code? That's similar to what you want, having Silverlight DataSet (restored from the DataSet XML string) mimic the ADO.DataSet.

The only thing I found in that code is that it does not quite work with autogenerate columns. Seems I have to pre-define each column for DataGrid or DataForm which I'd prefer not to do. That's kind of missing the benefit of using the generic feature of a DataSet. Maybe VitalyL already figured out the problem and solved it.

With the new tagging method provided by SL3 System.ComponentModel.DataAnnotations namespace and DataForm, I found more benifit of using DataSet. A DataSet not only holds the data, it can also holds the data schema which contains the meta data for each field.  Now my code can convert a DataSet to a Dynamic Data structure with all the necessary meta data tags on each Data Field being added. So I can just bind them to a DataGrid or a DataForm without any extral code or XAML setup. 

If a data field can not be null in the database, it will be a required field in the DataForm. If a data field is a string in database with certain length limit, it will has the same length limit in the DataForm textbox. If a data field is an identity field in database which is autogenerated,  it will be a read only field in DataForm and DataGrid. Most of the validations are build-in without any extral code. When data is changed in Silverlight, only the changed data is sent back to Server for updating.

 

 

 

 

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

bydia2
bydia2

Member

Member

12 points

7 Posts

Re: How to Display DataSet in Silverlight DataGrid

Yes, I did say I saw the samples.  It still requires work to make it a true diffgram xml.

What you say it lacks... I agree with.

Have you tried ComponentOne's DataTable, etc.? Does it come close to MS DataSet?

 

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

 No, I have never tried ComponentOne's DataTable.

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

Eyo
Eyo

Member

Member

8 points

11 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi sladapter

I've downloaded the code that VitalyL has provided. But I'am not able to get that working.

I created my project and tried to like this:

 

SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=svlsample;Integrated Security=True");

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "SELECT * FROM " + table_name;

DataSet ds = new DataSet();

// DataTable dt = new DataTable("TableRecords");

SqlDataAdapter da = new SqlDataAdapter(cmd);

 

cmd.Connection = con;

con.Open();

da.Fill(ds);

con.Close();

The code work fine untill here. However when adding 2 code line below it will not work

string response = (string) Connector.ToXml(ds);

return response;

When am trying to debug without the last 2 lines of code, everything ok... but when i add them and while debugging i can't enter the service method and this exception occured:

public string EndGetMyDataSet(System.IAsyncResult result) {                object[] _args = new object[0];                string _result = ((string)(base.EndInvoke("GetMyDataSet", _args, result)));                return _result;            }

Error: The remote server returned an error: Not Found

Can you guide me plz?

I hope am clear... !!!

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

Eyo:

Hi sladapter

I've downloaded the code that VitalyL has provided. But I'am not able to get that working.



I'm not  VitalyL, maybe you asked wrong person?

 

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

Eyo
Eyo

Member

Member

8 points

11 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi,

Sorry, I've asked u because I read that u have downloaded the code and tested it. And you are right I must ask Vitalyl.

Hi VitalyL, please can u guide me what am doing wrong ?

 

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

No problem.

I read your post again, do you mean the error happens at the following line? Didn't you debug the code to see what happens there? Do you even got the DataSet?

string response = (string) Connector.ToXml(ds); 

I have no problem running the sample code. The only problem I found is to auto bind the data to control as I mentioned in earlier post.

 

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

Eyo
Eyo

Member

Member

8 points

11 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi,

Thanks sladapter,

Plz let me tell what i had since i downloaded the demo sample. Am using VS 08 professional edition , Windows Vista Tongue Tied, , IIS 7

First when i opened the project i got a warninig message told that i dont have IIS6 metabase and configuration I've downloaded them, then

when am opening the project in normal user ( it show warning msg i need windows authentication :S) and i found that the website is not accessible. Until i run as administrator.And also when am runniing i also see the default page then nothing....

So, I decided to open new SL project which contains web app, to get rid of this headache. The SL app contains the service method (GetMyDataSet) i put in the previous post.

So when I debugg the mothod without the code line below, the debugger enters to the method and everything works fine.

string response = (string) Connector.ToXml(ds); 

However, when i add this method, the debugger will not access the mothod at all, and i will get the exception in this method in this line.

public string EndGetMyDataSet(System.IAsyncResult result) {                object[] _args = new object[0];                string _result = ((string)(base.EndInvoke("GetMyDataSet", _args, result)));                return _result;            }Error:

The remote server returned an error: Not Found.

And really thank u in advance.

 

sladapter
sladapter

All-Star

All-Star

17439 points

3,172 Posts

Re: How to Display DataSet in Silverlight DataGrid

Eyo:

However, when i add this method, the debugger will not access the mothod at all

 

You mean you could not catch the break point you set on the WCF GetMyDataSet function at all when you added one line of code there?

Try to update your Service Reference first, rebuild the solution then try it again.

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

VitalyL
VitalyL

Member

Member

34 points

24 Posts

Re: How to Display DataSet in Silverlight DataGrid

Hi guys,

Silverlight DataSet supports DataGrid with AutoGenerateColumns="True" now.

You can download the latest libraries from http://silverlightdataset.codeplex.com

Enjoy your coding

Vitaly

VitalyL
VitalyL

Member

Member

34 points

24 Posts

Re: Re: How to Display DataSet in Silverlight DataGrid

 Silverlight DataSet project was moved to http://silverlightdataset.net

chaple2008
chaple2008

Member

Member

20 points

10 Posts

Re: How to Display DataSet in Silverlight DataGrid

If you check out www.silverlightDS.com they have a download which makes doing SQL alot easier, simplifies the whole process, just need to define the CrUD in the webservice, and then wala!  It's pretty slick.

kobruleht
kobruleht

Member

Member

158 points

568 Posts

Re: Re: How to Display DataSet in Silverlight DataGrid

Where to download source code of silverlightdataset.net ?

There is no source download link.

Andrus.

varshavmane
varshavmane

Contributor

Contributor

6575 points

1,551 Posts

Re: Re: Re: How to Display DataSet in Silverlight DataGrid

Check this:

http://slbindabledatagrid.codeplex.com/

Hope it helps.

Please "Mark as Answer" if this post answered your question. :)
Visit my Blog: http://varshavmane.blogspot.com/

kobruleht
kobruleht

Member

Member

158 points

568 Posts

Re: Re: Re: How to Display DataSet in Silverlight DataGrid

http://slbindabledatagrid.codeplex.com/ has GPL licence. So unfortunately I cannot use it.

Andrus.

VitalyL
VitalyL

Member

Member

34 points

24 Posts

Re: Re: How to Display DataSet in Silverlight DataGrid

Hi there,

Source code is located at http://silverlightdataset.net

Scroll treeview down untill you see "Source Code" node.

Best regards

Vitaly

kobruleht
kobruleht

Member

Member

158 points

568 Posts

Re: Re: How to Display DataSet in Silverlight DataGrid

Where to downlaod whole solution as zip file ?

Andrus.

VitalyL
VitalyL

Member

Member

34 points

24 Posts

Re: Re: Re: How to Display DataSet in Silverlight DataGrid

Hi Andrus,

There is no such an ability. Contact me directly at vlaskarzhevsky@msn.com for futhure discussion, please.

Regards

Vitaly

samcov
samcov

Participant

Participant

969 points

379 Posts

Re: Re: Re: How to Display DataSet in Silverlight DataGrid

VitalyL:

Hi Andrus,

There is no such an ability. Contact me directly at vlaskarzhevsky@msn.com for futhure discussion, please.

Regards

Vitaly


You removed the project from Codeplex, are you taking it commercial?

"The difference between genius and stupidity is that genius has its limits." - Albert Einstein

sangsanj
sangsanj

Member

Member

2 points

1 Posts

Memory Leak

Is there a way to dispose and reclaim the memory taken by this dynamically generated assembly and type? I tried your sample and it works great. But I could see memory leaking at the TypeBuilder.CreateType line. After binding to the grid, how can we dispose this type?

VitalyL
VitalyL

Member

Member

34 points

24 Posts

Re: Memory Leak

Hi Sangasan,

It is not a memory leak. According to Miocrosoft, loaded assembly (doesn't matter generated or created at design time) cannot be unloaded from memory until application shutdown. You just need to be aware of this effect when you design any of your application.

Regards

Vitaly

bonnieb
bonnieb

Member

Member

6 points

3 Posts

Re: Re: Memory Leak

Hi Vitaly,

I downloaded your stuff ... looks promising, but I haven't had a chance to really look at it yet. I'm curious though, as to why you removed it from CodePlex? It seems to me that you might get a lot of exposure by having it there ... or is that not the case?

... just curious.  Thanks.

~~Bonnie

 

 

VitalyL
VitalyL

Member

Member

34 points

24 Posts

Re: Re: Re: Memory Leak

Hi Bonnie,

Unfortunately CodePlex doesn't provide the level of freedom we need in posting documentation for Silverlight DataSet a la MSDN Reference. That was the first obstacle. Te second dissapointment was the unability to upload information using simple FTP and Windows Explorer.

That's why we chose DiscountAsp as a host for our project.

Sincerely

Vitaly Laskarzhevsky

bonnieb
bonnieb

Member

Member

6 points

3 Posts

Re: Silverlight DataSet

Thanks Vitaly.

Another question ... I assumed (wrongly apparently), that we could also download the source code, but apparently you're only giving access to the DLL? Any chance of getting the source code from you guys?

 UPDATE: Oh, I see you include the source code on your website, but not as a download. It looks like I'd have to copy/paste every single class. But, if that's what I have to do, I guess I can manage.

Thanks!

~~Bonnie

VitalyL
VitalyL

Member

Member

34 points

24 Posts

Re: Re: Silverlight DataSet

Hi Bonnie,

Source code was published only for public classes on our website. We see no business value in publishing internal and private classes.

Best Regards

Vitaly Laskarzhevsky

bonnieb
bonnieb

Member

Member

6 points

3 Posts

Re: Re: Silverlight DataSet

Hi Vitaly,

I will email you via your website with further questions.

~~Bonnie

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities