Silverlight 2 (beta1) – Database Operations with ASP.NET Web Service in Silverlight 2

Update You can download the latest version of sample that works with Silverlight 2 beta2 from this link.


This is the step-by-step tutorial for how to do database operations (Create, Retrieve, Update, Delete) with ASP.NET web service (asmx) in Silverlight 2 beta 1.


A few people asked me how to do database operations (CRUD) in Silverlight 2 (beta1). As I have some experiences in using Astoria in Silverlight 1.1 Alpha, I was thinking to use Astoria service in Silverlight 2. Unfortunately, Astoria Client add-on doesn’t work with Silverlight 2 (beta1) and Astoria team said that the next version will be available around the end of April. So, for now, I made this sample with normal ASP.NET web service for those who like to do CRUD operations in Silverlight 2.

Software Needed

  • Silverlight 2 (beta1) (Please read this post if you don’t know where you can get those installers.)
  • Visual Studio 2008
  • SQL 2005 Express with Management Studio

Download : (1.45 MB)

Silverlight 2

Fig: Retrieving data from ASP.NET web service and displaying those data in Silverlight Datagrid.


Fig: Entry Form for adding new record to database from Silverlight 2 application

Creating the database in SQL 2005

Note: If you already know about how to create the database in SQL 2005, please skip and jump to next section.

Step 1: Open SQL Server Management Studio Express

SQL Server Management Studio Express - FREE edition

Step 2: Connect to SQL Server that you have installed on your local machine

Connect to Server

Step 3: Right-click on Database node from Object Explorer and Select “New Database”

New Database - SQL 2005

Step 4: Type your database name ( I named it “MyStore” in this sample) and Click “OK” button


Step 5: Right-click on Table node of the database that you have created and select “New Table”

New Table

Step 5: Create two columns called “ProductID(INT Identity PK)” and “ProductName”. Name the table “Products”

Structure of Products Table

Okay. That is all about creating new table in SQL 2005.

Creating the Silverlight 2 (beta1) project in Visual Studio 2008

  • Open VS 2008 and Create new Silverlight 2 project.


  • It will ask you whether you want to create ASP.NET project or HTML page to host Silverlight content. Just click “OK” button


  • You will get two projects (ASP.NET and Silverlight) under one solution.


Creating Web Service in ASP.NET project

  • Right-click on ASP.NET project node and Choose “Add New Item” as shown in picture below.


  • “Add New Item” dialog will be shown. Please choose “Web Service” item in that dialog.


  • Give the name “ProductManager.asmx” to this web service and click “OK” button.
  • Go to web.config and Add the connection string as below under <configuration> in web.config. (Note: You have to add your connection string for SQL so that it might not be the same as mine.)
    <add name="sqlConnectionString" connectionString="Data Source=MICHAELSYNC-PC\SQLEXPRESS;Initial Catalog=MyStore;Integrated Security=True"/>
  • Go to the ProductManager.asmx again. Uncomment [System.Web.Script.Services.ScriptService] at the top of Class
  • Write the four methods for CRUD operations. (I will show the code for retrieving data from SQL in this post. If you want to know about CUD operations, please download the sample and take a look at that asmx file.)
    public string RetrieveProduct(int productId) {
    try {
    SqlConnection _sqlConnection = new SqlConnection();
    _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["sqlConnectionString"].ToString();
    _sqlConnection.Open();SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = new SqlCommand("SELECT * FROM Products WHERE ProductID = " + productId.ToString().Replace("'", "''"), _sqlConnection);
    DataSet ds = new DataSet();
    StringBuilder sb = new StringBuilder();
    sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
    foreach (DataRow dr in ds.Tables[0].Rows) {
    return sb.ToString();
    catch (Exception ex) {
    return string.Empty;
  • Go to the propertypad of ASP.NET project and set False to “Use dynamic ports” property.static-port.jpg
  • then, Build ASP.NET project.

Consuming ASP.NET web service in Silverlight 2 (beta1)

  • Right-click on the Reference node of Silverlight project. And choose “Add Service Reference” as shown in picture below.add-service-reference.jpg
  • The following dialog will be shown. Click “Discover” buttondiscover-thumb.jpg
  • (One web service will be shown in “Service:” panel after clicking “Discover” button.) Double-click on that one.discovering-webservice.jpg
  • It will show “ProductManager” service that we created in ASP.NET project
  • Change the namespace to “WebServiceProxy” and hit “OK” button
  • Now, you can start using web service from Silverlight project. I will show you how to retrieve the data from web service.
  • Please take a look at “ListingControl.xaml.cs. You will see the following code that retrieve the data from Web Service
    void ListingControl_Loaded(object sender, RoutedEventArgs e) {WebServiceProxy.ProductManagerSoapClient productMgrSoapClient =
    new SL2WebSrv.WebServiceProxy.ProductManagerSoapClient();
    productMgrSoapClient.RetrieveProductsCompleted +=
    new EventHandler<SL2WebSrv.WebServiceProxy.RetrieveProductsCompletedEventArgs>(productMgrSoapClient_RetrieveProductsCompleted);
    void productMgrSoapClient_RetrieveProductsCompleted(object sender, SL2WebSrv.WebServiceProxy.RetrieveProductsCompletedEventArgs e) {
    if (e.Error == null)

    Note: ListingControl_Loaded is attached in ListingControl constructor. displayData(string) is another function for showing data.

  • I created Product class in Silverlight project too. Because Silverlight doesn’t support binding Datagrid with anonymous type. (You can read about this issue more details in this post.)
  • The following code is for displayData() function.
    void displayData(string xmlContent) {
    try {if (xmlContent != string.Empty) {
    XDocument xmlProducts = XDocument.Parse(xmlContent);
    var products = from product in xmlProducts.Descendants("Product")
    select new
    ProductID = Convert.ToInt32(product.Element("ProductId").Value),
    ProductName = (string)product.Element("ProductName").Value
    List<Product> productsList = new List<Product>();
    foreach (var p in products) {
    Product pdt = new Product { ProductID = p.ProductID, ProductName = p.ProductName };
    productsDataGrid.ItemsSource = productsList;
    else {
    productsDataGrid.ItemsSource = null;
    catch (Exception ex) {
  • Yes. That’s all about retrieving data from Web Service. If you run that sample, the data from database will be displayed in DataGrid.
  • You can also read the code from EntryControl.xaml.cs file if you want to know how to insert the data.

How to run this sample

First thing that you need to do is that you should attach the database to your SQL express. After that, you have to change the connection string. then, try to run the sample. If you are not seeing anything then please try to uncomment the code for calling web service. (because I’m not sure whether you have the connection problem or not.) then, run it again. You should be able to see the silverlight content as shown in my screenshot except datagrid. If it’s running fine then try to check the connection string again.

Feel free to let me know if you have any problem or suggestion. I hope you will find it useful.

Related ~

109 Replies to “Silverlight 2 (beta1) – Database Operations with ASP.NET Web Service in Silverlight 2”

  1. hmm.. i cant find any files under

    Service References\WebServiceProxy

    no .disco nothing.. is this normal? because project runs under Visual Studio.. but still isnt working through IIS???

  2. Hello Taimur,

    I’m not sure why there is no file under Service Ref. maybe, you should try to rebuild again. My Webservice is not WCF service. It’s just asmx web service that enables Ajax calls.. (so, should we call it ASP.NET Ajax Web Service? )

    I was thinking to reply you when i get the machine that has IIS7 installed. but I can’t find that machine in my office. my laptop doesn’t have IIS7, man. So, it’s a lit bit hard for me to find out what the problem is…

    I will ask some of my friend whether they have IIS7 or not.. if they have then I will go and try out in their machines.

    What about asking in Silverlight forum? I used to be there.. please take a look “Calling web services with Silverlight 2” article too..

  3. Hello Michael.

    Your Blog is simply great!
    Now about the above project..
    I have done all the steps above. I can see the data in the datagrid. The only problem is that I cannot attach the database file you provided(MyStore). So I created another database file named MyStore from Management Studio and put some products in it. I can see them but I cannot add anything to it. When I try to attach your file, it gives me the following error:

    TITLE: Microsoft SQL Server Management Studio Express

    Attach database failed for Server ‘KUNAL-PC\SQLEXPRESS’. (Microsoft.SqlServer.Express.Smo)


    An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.Express.ConnectionInfo)


    Unable to open the physical file “C:\SL2WebSrv\SL2WebSrv\SQL Database\MyStore.mdf”. Operating system error 5: “5(error not found)”. (Microsoft SQL Server, Error: 5120)

    Also, When I try to add the same file by Server Explorer in VS2008, it works, but I cannot see any data or add any products. But, I can see the table list in the database.
    Please help me in this regards.


  4. Hello Kunal,

    So, you have two problems?

    1) You can’t insert new record to the database.

    2) You can’t attach my .mdf to your SQL Express.

    >>1) You can’t insert new record to the database.

    – Have you changed the insert statement (T-SQL) in web service? If you are able to get the datas from database, you should be able to insert the new record also.

    – You have the permission to insert the data to your database, right? What error did you get while inserting new record to your new database?

    — Please open SQL Management Studio and open one database. then, try to do some CUD operations.

    >>2) You can’t attach my .mdf to your SQL Express.

    – Please install Express SP 2 or latest one.

    – Under what account is the SQL Server service running? Does that account have read/write privileges on that directory?

  5. Hi Michael,

    Thanks for your help. Now I have attached the database to SQL. I opened Management Studio in “Run as administrator”. That worked. Now I can access your database as well as add products to it. I have added a new delete button to the page. I have also added the user control. When I try to delete, it says Product Deleted. But the data in listing(& database) are still the same. PLease take a look at the code I used:

    public DeleteControl()
    deleteButton.Click += new RoutedEventHandler(deleteButton_Click);

    void deleteButton_Click(object sender, RoutedEventArgs e)
    if (productid.Text.Trim() == string.Empty)
    errMessage.Foreground = new SolidColorBrush(Colors.Red);
    errMessage.Text = “Please Enter Product id!”;
    errMessage.Visibility = Visibility.Visible;
    WebServiceProxy.ProductManagerSoapClient productMgrSoapClient =
    new SL2WebSrv.WebServiceProxy.ProductManagerSoapClient();

    productMgrSoapClient.DeleteProductAsync(int.Parse(productid.Text), productname.Text);
    productMgrSoapClient.DeleteProductCompleted += new EventHandler(productMgrSoapClient_DeleteProductCompleted);


    void productMgrSoapClient_DeleteProductCompleted(object sender, SL2WebSrv.WebServiceProxy.DeleteProductCompletedEventArgs e)
    if (e.Error == null)
    errMessage.Text = “Product Deleted.”;
    errMessage.Foreground = new SolidColorBrush(Colors.Blue);
    errMessage.Visibility = Visibility.Visible;

    Also, Do I have to ask the user for both product id and name??


  6. When I add the service reference, I get this Warning message in the error this normal? If it is not, how would I resolve it? Thanks.

    Warning 1 Custom tool warning: Removing unsupported type System.Windows.Controls.OpenFileDialog
    System.TypeLoadException: Could not load type ‘System.Security.SecuritySafeCriticalAttribute’ from assembly ‘mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089’.
    at System.ModuleHandle.ResolveType(Int32 typeToken, RuntimeTypeHandle* typeInstArgs, Int32 typeInstCount, RuntimeTypeHandle* methodInstArgs, Int32 methodInstCount)
    at System.ModuleHandle.ResolveTypeHandle(Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
    at System.Reflection.Module.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
    at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, Module decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, RuntimeMethodHandle& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
    at System.Reflection.CustomAttribute.IsCustomAttributeDefined(Module decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Boolean mustBeInheritable)
    at System.Reflection.CustomAttribute.IsDefined(RuntimeType type, RuntimeType caType, Boolean inherit)
    at System.RuntimeType.IsDefined(Type attributeType, Boolean inherit)

  7. Hi Kunal,

    >>Also, Do I have to ask the user for both product id and name??

    No. you just need to ask product ID only..

    Hi RezaMohamed,

    >>>Warning 1 Custom tool warning: Removing unsupported type System.Windows.Controls.OpenFileDialog

    I don’t think it’s related to “Add Service Reference”. Is there any place that you are using OpenFileDialog?

  8. >>>Warning 1 Custom tool warning: Removing unsupported type System.Windows.Controls.OpenFileDialog

    >>I don’t think it’s related to “Add Service Reference”. Is there >>any place that you are using OpenFileDialog?

    I have no refernce to the OpenFileDialog in my project.

  9. I think you are referencing wrong dll or something. mscorlib (Microsoft Core Library) should be This dll located under c:\Program Files\Microsoft Silverlight\2.0.30226.2\.

  10. Hi! Great tutorial but I seem to have a little trouble with the Linq part. The data is retrieved from the webservice and I want to use the data.. thats when it stops to work..

    my function pretty much look the same as yours..

    XDocument xmlPoints = XDocument.Parse(xmlContent);

    var hpoints = from hpoint in xmlPoints.Descendants(“points”)
    select new
    xvalue = Convert.ToInt32(hpoint.Element(“xvalue”).Value),
    yvalue = Convert.ToInt32(hpoint.Element(“yvalue”).Value),
    type = Convert.ToInt32(hpoint.Element(“type”).Value)

    foreach (var pt in hpoints)
    CreateChartEllipse(pt.xvalue, pt.yvalue);


    the problems is that the hpoints never gets any data.. after the LINQ query it’s still Null
    the sql returned from the webservice looks like this..


    so it’s at the foreach it gets thrown to the catch.. do you have any thoughts that might help me understand. LINQ is a new concept for me btw.

  11. Seems like the xml didn’t show.. but it’s standard sql.. nothing strange about it..and it goes trough the parser without any probs.

  12. Hi Michael,

    Really nice article you have here. I really liked it. Thank you.

    I have a question:

    So this works great by running it within VS2008. The Silverlight part works and the datagrid is populated with records from the DB.

    But when I publish the website to my local IIS (5.1), the Silverlight part works. However, nothing shows up in the datagrid and I don’t get any errors.

    I just don’t know how to transfer the working project in VS2008 and deploy it on IIS…

    Could you please shed some light?


  13. Have you changed the URL of web reference after deploying the webservice?? If we are running it within VS 2008, we normally have the port specified in the web service URL. You will need to remove that port after deploying the web service in IIS.

    The best way to do is that put the webservice in IIS first. (so, the URL of your web service will be like http://localhost/SL2WebSrv/blahblah.asmx ).. then, open the SL project in VS 2008.. Add the web reference from http://localhost/SL2WebSrv/blahblah.asmx .. (not the one from project in VS 2008).. then, rebuild the SL project. Copy the SL project under SL2WebSrv (So, your aspx page will be like that http://localhost/SL2WebSrv/youraspxpage.aspx).. then, run it in IE..

    Hope it will work..

  14. Great workaround,

    When I tried the common codes for Database accessing through WCF “service.svc” , The browser kept crashing.
    Now Iam more comfy with Webservice.asmx and the XML way of data exported by your code.

    Thanks a lot

  15. Thank you! I had a few minor issues, but it had more to do with ampersands in my data causing the XML bomb out during parsing rather than the code. This worked very nicely!

  16. Dear Michael,
    When I tried to add EntryControl inside the main page in Blend2, it has mistakes:
    INNEReXCEPTION: age_runtime_managed_unknow error [Line: 27 Position: 112]
    Ihen, i tried to add it by VS2008, and it works, but i cant add any new element, even it doesnt appear any . My listbox is ok, the problem is in EntryControl.
    This is its code:


    using System;
    using System.Collections.Generic;
    using System.Linq;
    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 ITLAB_1

    public partial class EntradaControl : UserControl
    public EntradaControl()
    saveButton.Click += new RoutedEventHandler(saveButton_Click);

    void saveButton_Click(object sender, RoutedEventArgs e)
    if (participanteName.Text.Trim() == string.Empty)
    errMessage.Foreground = new SolidColorBrush(Colors.Red);
    errMessage.Text = “Ingrese Nombre del Participante!”;
    errMessage.Visibility = Visibility.Visible;
    WebServiceProxy.AsistenciaManagerSoapClient participanteMgrSoapClient =
    new ITLAB_1.WebServiceProxy.AsistenciaManagerSoapClient();

    participanteMgrSoapClient.CrearParticipanteCompleted +=
    new EventHandler(participanteMgrSoapClient_CrearParticipantesCompleted);

    void participanteMgrSoapClient_CrearParticipantesCompleted(object sender, ITLAB_1.WebServiceProxy.CrearParticipanteCompletedEventArgs e)
    if (e.Error == null)
    errMessage.Text = participanteName.Text + ” ha sido ingresado exitosamente”;
    errMessage.Foreground = new SolidColorBrush(Colors.Blue);
    errMessage.Visibility = Visibility.Visible;
    errMessage.Foreground = new SolidColorBrush(Colors.Red);
    errMessage.Text = e.Error.ToString();
    errMessage.Visibility = Visibility.Visible;



  17. Hello Lucia,

    I’m not very clear..

    >>>When I tried to add EntryControl inside the main page in Blend2, it has mistakes: INNEReXCEPTION: age_runtime_managed_unknow error [Line: 27 Position: 112]

    Did you add xmlns: in Main Page?

    >>i tried to add it by VS2008, and it works,

    Actually, you don’t need to have two projects.. You can open the same project in both Blend and VS 2008. There is an option “Edit in Visual Studio” in Blend and “Open in Expression Blend” in VS 2008.

    I wanna suggest you one thing. Please don’t add the webservice code firstly.. You should do other things like adding control or etc before writing the code for webservice. Once everything is working fine, you can start writing code for webservice.

    So, please remove web reference and the code for webservice from your project. then, add the control and test it in Blend and VS 2008. Let me know whether it’s working fine or not. . If It’s working fine then we will move on to the next step..

  18. Having a problem with listingControl.xaml.cs

    Get error
    ‘The type or namespace name ‘WebServiceProxy’ does not exit in the namespace ‘Sl2WebSrv4’ on line

    void productMgrSoapClient_RetrieveProductsCompleted(object sender, sl2WebSrv4.WebServiceProxy.RetrieveProductsCompletedEventArgs e)

    (Sl2WebSrv4 is my project name)

    Intellicence on provides three options for Sl2WebSrv4,
    app, listingcontrol, and page.

    My usings are:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    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;

    Can’t add using System.Xml.Linq;
    namespace not in System.Xml

    I’ve gone over the steps 4 times; so suspect it is
    something in my environment.

    Using SQLserver instead of express, (don’t have express installed) but put working connectionstring in web.config and Web control appears to work.


  19. Get error
    ‘The type or namespace name ‘WebServiceProxy’ does not exit in the namespace ‘Sl2WebSrv4′ on line

    What did you give the name when you referenced the webservice? Please take a look this screenshot I gave ‘WebServiceProxy’ as a namespace.

    Can’t add using System.Xml.Linq;
    namespace not in System.Xml

    You need to add System.Xml.Linq assembly to your project. Go to Solution Explorer. Right-click on Reference of Silverlight project. Add Reference. Choose “System.Xml.Linq” dll.

    Using SQLserver instead of express, (don’t have express installed) but put working connectionstring in web.config and Web control appears to work.

    that’s should be fine.

    Let me know if you are still having the problem..

  20. Michael,

    I am very pleased with your tutorial but I am experience a minor issue, one which I hope you can clear up for me easily. I downloaded your VB converted form of the app, which I did myself before I read the comments. I thought maybe it would be best if I just loaded your original source code in C# and try debugging it. However, I cannot even debug the code, do you know why? Every time I set a breakpoint and debug it, it never even hits.

    Thank you,

  21. Hello,

    Which edition of VS 2008 are you using? If you are using standard edition, there is one known issue. you will need to remove “SilverlightLink” and “Add Silverlight link” ….

    but if you are using Professional edition, team suite then it should be working fine.. just clean the solution and rebuild it. then, set the breakpoint at page’s constructor.. then run the application and wait for the application get loaded…

  22. Here is the VB.NET code for LINQ statement..

    Dim xmlProducts As XDocument = XDocument.Parse(xmlContent)

    Dim products = From product In xmlProducts.Descendants(“Product”) _
    Select New Product With _
    {.ProductID = Convert.ToInt32(product.Element(“ProductId”).Value), _
    .ProductName = product.Element(“ProductName”).Value _

    Dim productsList As List(Of Product) = New List(Of Product)

    For Each p As Object In products
    Dim pdt As Product = New Product() With {.ProductID = p.ProductID, .ProductName = p.ProductName}
    productsDataGrid.ItemsSource = productsList

    I hope it will be helpful for those who are having some problems in converting C# code to VB.NET..

  23. Hi

    I´m using this tutorial to create a Webservice and use it in a silverlight application. I followed every step and the web service is working, but when i try to access it from the silverlight application I get this exception.

    Could not find default endpoint element that references contract ‘CampStatSite.WebServiceProxy.wsTesteSoap’ in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

    I´m using silvertlight 2 beta 2

  24. This is a very very usefull site for all those who want to have db capabilities with SilverLight. I don’t understand why Microsoft does not provide a straight forward implementation of db with silverlight.

    Any idea?

  25. Hi Rms81,

    Silverlight is a client-side technology that runs on the user’s browser. Like Javascript that runs on the client-side. Due to the security reason, we are not able to communicate database directly from Silverlight.

  26. >>when i try to access it from the silverlight application I get this exception

    Just make sure that your ASP.NET project and Web Service are under same domain name and same port.. The URL for Service is under wsdl file. Unlike WCF service, no need to have the config file or etc..

  27. Hi ,

    this code does not run when there is only one descendent
    var employees = from employee in xmlEmployees.Descendants(“Employee”)
    select new
    EmployeeID = Convert.ToInt32(employee.Element(“ID”).Value),
    EmployeeName = (string)employee.Element(“Name”).Value,
    EmployeeAddress = (string)employee.Element(“Address”).Value,
    EmployeeEmail = (string)employee.Element(“Email”).Value,
    .i am not sure why.
    Any clues why.


  28. hey hi Michael,
    I did get my code to work but I had to change my code a little bit.
    var employees = (from employee in xmlEmployees.Descendants(“Employee”) select employee).First();
    txtName.Text = employees.Element(“Name”).Value;
    txtAddress.Text = employees.Element(“Address”).Value;
    txtEmail.Text = employees.Element(“EmailId”).Value;
    I will email you the the project anyways. Please do tell me if I am missing something.

  29. I got this error while trying this sample..

    Error 2 The “ValidateXaml” task failed unexpectedly.
    System.NullReferenceException: Object reference not set to an instance of an object.
    at Microsoft.Silverlight.Build.Tasks.ValidateXaml.Execute()
    at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) AV_SilverlightApplication

    any help..
    thanx in advance..

  30. i had follow throught your sample with VB code, after all i’m get a error that i not understand.

    The code i used to implement my page is like below:

    Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
    Dim objMyService As New MyServiceRef.DatabaseEngineSoapClient
    AddHandler objMyService.getLzTenLoggedInDataCompleted, AddressOf objMyService_getLzTenLoggedInDataCompleted
    Catch ex As Exception
    tbMessage.Text = “Page Loaded Error: ” & ex.Message
    End Try
    End Sub

    Private Sub objMyService_getLzTenLoggedInDataCompleted(ByVal sender As Object, ByVal e As MyServiceRef.getLzTenLoggedInDataCompletedEventArgs)
    myDataGrid.ItemsSource = e.Result
    Catch ex As Exception
    tbMessage.Text = “Event Trigger Error : ” & e.Error.Message
    End Try
    End Sub

    But i got error like below,

    Could not find default endpoint element that references contract ‘SilverlightTest.MyServiceRef.DatabaseEngineSoap’ in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

    Could you let me know what is the problem about.

  31. When I clicked run in VS it showed blank page. But when I browse the SL2B2WebSrvTestPage.aspx it showed the interface where I can Add item and List item but when I try to click save, it took a long time to appear “success”. However, when I click listing, I saw nothing. What’s wrong?

  32. Can you try to Astoria service directly from the browser and see whether you can get the data from service or not?

    If you can, you should try to check the URL of service and port number that you specify in Silverlight. It might be the cross-domain problem…..

    Let me know if you are still facing some problems.

  33. I am getting this error , when I am adding service reference.

    There was an error downloading ‘http://localhost:1342/DatabaseConnectivityWeb/Service.svc’. The request failed with the error message: —

    The service encountered an error.

    An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
    System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
    contract: Service —-> System.Runtime.Serialization.InvalidDataContractException: Type ‘tbl1’ cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.
    at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
    at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
    at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
    at System.Runtime.Serialization.DataContract.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
    at System.Runtime.Serialization.DataContract.GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
    at System.Runtime.Serialization.DataContract.GetDataContract(RuntimeTypeHandle typeHandle, Type type)
    at System.Runtime.Serialization.DataContract.GetDataContract(Type type)
    at System.Runtime.Serialization.DataContractSet.GetDataContract(Type clrType)
    at System.Runtime.Serialization.DataContractSet.AddCollectionDataContract(CollectionDataContract collectionDataContract)
    at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
    at System.Runtime.Serialization.XsdDataContractExporter.Export(Type type)
    at System.ServiceModel.Description.MessageContractExporter.ExportType(Type type, String partName, String operationName, XmlSchemaType& xsdType)
    at System.ServiceModel.Description.DataContractSerializerMessageContractExporter.ExportBody(Int32 messageIndex, Object state)
    at System.ServiceModel.Description.MessageContractExporter.ExportMessage(Int32 messageIndex, Object state)
    at System.ServiceModel.Description.MessageContractExporter.ExportMessageContract()
    at System.ServiceModel.Description.DataContractSerializerOperationBehavior.System.ServiceModel.Description.IWsdlExportExtension.ExportContract(WsdlExporter exporter, WsdlContractConversionContext contractContext)
    at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
    — End of inner ExceptionDetail stack trace —
    at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
    at System.ServiceModel.Description.WsdlExporter.CallExportContract(WsdlContractConversionContext contractContext)
    at System.ServiceModel.Description.WsdlExporter.ExportContract(ContractDescription contract)
    at System.ServiceModel.Description.WsdlExporter.ExportEndpoint(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName)
    at System.ServiceModel.Description.WsdlExporter.ExportEndpoints(IEnumerable`1 endpoints, XmlQualifiedName wsdlServiceQName)
    at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
    at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
    at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
    at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
    at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
    at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
    at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.Get(Message message)
    at SyncInvokeGet(Object , Object[] , Object[] )
    at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
    at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
    at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
    at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
    at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
    at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
    at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
    at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
    –. Metadata contains a reference that cannot be resolved: ‘http://localhost:1342/DatabaseConnectivityWeb/Service.svc’. Content Type application/soap+xml; charset=utf-8 was not supported by service http://localhost:1342/DatabaseConnectivityWeb/Service.svc. The client and service bindings may be mismatched. The remote server returned an error: (415) Unsupported Media Type. If the service is defined in the current solution, try building the solution and adding the service reference again.

    please tell me solution….

  34. I’m getting the following error in ListingControl.xaml.cs:

    The type or namespace name ‘RetrieveProductsCompletedEventArgs’ does not exist in the namespace ‘SL2WebSrv.WebServiceProxy’ (are you missing an assembly reference?)

    at the following line:
    void productMgrSoapClient_RetrieveProductsCompleted(object sender, SL2WebSrv.WebServiceProxy.RetrieveProductsCompletedEventArgs e)

    what am i doing wrong?

  35. Hi Michael

    I am sticking into one problem while consuming the database with listbox.
    While the application loads on the server, Listbox is taking a very long time to display the dynamic content. Its really frustating me as i was unable to figure out the problem….
    Please Help…Its very urgent…


  36. @huzan

    i have a problem same to u .
    it pass a longtime while you write comment.

    i want to know you have success this problem?

    sorry for my bad english.

  37. Hi

    Great, great article. Followed it to the “T” and works beautifully. Thanks a million for such a good tutorial.

    Need a bit of help.

    This works perfectly on the local ASP.Net Development web server with port fixed to 5000 and a virtual directory configured.

    When I publish this to a IIS 6.0 (Win2K3 Standard Server) system, no data comes into Silverlight – even though the Silverlight app loads fine.

    From the server itself, I can access the operations of the webmethods, pass parameters and get them to return the data.

    The webservice, obviously, has got published correctly.

    Now what do I check?

    Thanks a million, again – your article has helped me write my first Silverlight app – and I have a number of them in the pipeline :-)


  38. Thanks for your excellent tutorials on ado data services. However, I having a problem with accessing stored procedures in our database, that returns data from a cross-join, with X number of columns. Below is some sample code.

    When I go to show the data service in the browser, I get a Request Error – The server encountered an error processing the request. See server logs for more details.

    What’s a good approch for dealing with this type of dynamic data?

    Thanks for you help,


    Imports System.Data.Services
    Imports System.Linq
    Imports System.ServiceModel.Web
    Imports System.Data.SqlClient
    Imports System.Web
    Imports System

    Public Class PlayerDataServices

    Inherits DataService(Of [PlayerEntities])

    Public Shared Sub InitializeService(ByVal config As IDataServiceConfiguration)

    config.SetEntitySetAccessRule(“Player”, EntitySetRights.AllRead)
    config.SetServiceOperationAccessRule(“*”, ServiceOperationRights.All)
    End Sub

    Public Function FetchPlayerStats(ByVal PlayerId As Integer, ByVal HeaderId As Integer, ByVal Year As Integer) As IEnumerable(Of DataRow)

    Dim ds As DataSet = New DataSet(“PlayerStats”)
    Dim da As SqlDataAdapter = New SqlDataAdapter()


    Using sqlConn As New SqlConnection(My.Settings.DBCn)
    Using sqlCmd As New SqlCommand(“uspLIST_Stats”, sqlConn)
    sqlCmd.CommandType = CommandType.StoredProcedure
    sqlCmd.Parameters.AddWithValue(“id”, PlayerId)
    sqlCmd.Parameters.AddWithValue(“HeaderID”, HeaderId)
    sqlCmd.Parameters.AddWithValue(“Year”, Year)

    da.SelectCommand = sqlCmd
    End Using
    End Using

    Catch ex As Exception
    End Try

    Return ds.Tables(0).AsEnumerable
    End Function
    End Class

  39. Hi Michael,
    I just gone through your site and happy to say “U r the man” really helping us.

    I have one query. My job is to get the Entity information from CRM and populate the date into Silver Light Webpage. For this I added the webservice and almost done everything. My problem is I am unable to retrieve the data and show it on Silver Light page. Can u just guide me step by step by code how to retieve the data through web service? Is it not possible to show the data into silver light directly without using any Input say “btn click”. Pls help me and thanks a ton in advance.

  40. Hi Michael,

    First of all I want to say that I am kind of new in the programming world. I have a problem and maybe you can help me.
    I made everything step by step, but I can’t insert new information in table. I even get the message that the “New Product has been saved successfully” but nothing changes in the table.
    I changed a little the web service for what I needed.
    Is there something wrong with the code? Maybe the sintax, I don’t really know because the program is error free.

    public bool CreateProduct(string TextBox_Prenume, string TextBox_Nume,
    int ComoBox_Zi, int ComoBox_Luna, int ComoBox_An, string Sexmf,
    string TextBox_AdresaEmail, string parola)
    SqlConnection _sqlConnection = new SqlConnection();
    _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings[“sqlConnectionString”].ToString();

    SqlCommand command = new SqlCommand();
    command.Connection = _sqlConnection;
    command.CommandType = CommandType.Text;
    command.CommandText = “INSERT INTO Utilizatori(Prenume, Nume, Zi, Luna, An, Sex, AdresaEmail)VALUES(‘” + TextBox_Prenume.ToString().Replace(“‘”, “””) + “‘,'” + TextBox_Nume.ToString().Replace(“‘”, “””) +
    “‘,'” + ComoBox_Zi.ToString().Replace(“‘”, “””) +
    “‘,'” + ComoBox_Luna.ToString().Replace(“‘”, “””) +
    “‘,'” + ComoBox_An.ToString().Replace(“‘”, “””) +
    “‘,'” + Sexmf.ToString().Replace(“‘”, “””) +
    “‘,'” + TextBox_AdresaEmail.ToString().Replace(“‘”, “””)+
    “‘,'” + parola.ToString().Replace(“‘”, “””) + “‘)”;
    return true;

    catch (Exception ex)
    return false;

    Thank you very much.

  41. hi….

    Can U provide how to insert ,update,Delete modify DAta in Database Table using SQL query and LinQ with ADO.NET dataservices.

    thx in advance

    Nice site….!! Have Nice Day..

Leave a Reply