Sharing our knowledge

Michael Sync

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

March 10th, 2008 by Michael Sync

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

Introduction

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.

Background

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 : SL2WebSrv.zip (1.45 MB)

Screenshots
Silverlight 2

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

sl2-entry.jpg

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

create-new-database-small.jpg

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.

new-project-thumb.jpg

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

add-silverlight-application.jpg

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

solution-explorer.jpg

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.jpg

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

add-new-item-detail-thumb.jpg

  • 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.)
    <connectionStrings>
    <add name="sqlConnectionString" connectionString="Data Source=MICHAELSYNC-PC\SQLEXPRESS;Initial Catalog=MyStore;Integrated Security=True"/>
    </connectionStrings>
    
  • 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.)
    [WebMethod]
    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();
    da.Fill(ds);
    
    StringBuilder sb = new StringBuilder();
    sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
    sb.Append("<Products>");
    foreach (DataRow dr in ds.Tables[0].Rows) {
    sb.Append("<Product>");
    sb.Append("<ID>");
    sb.Append(dr[0].ToString());
    sb.Append("</ID>");
    sb.Append("<Name>");
    sb.Append(dr[1].ToString());
    sb.Append("</Name>");
    sb.Append("</Product>");
    }
    sb.Append("</Products>");
    _sqlConnection.Close();
    
    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.RetrieveProductsAsync();
    productMgrSoapClient.RetrieveProductsCompleted +=
    new EventHandler<SL2WebSrv.WebServiceProxy.RetrieveProductsCompletedEventArgs>(productMgrSoapClient_RetrieveProductsCompleted);
    }
    void productMgrSoapClient_RetrieveProductsCompleted(object sender, SL2WebSrv.WebServiceProxy.RetrieveProductsCompletedEventArgs e) {
    if (e.Error == null)
    displayData(e.Result);
    }
    

    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
    };
    
    //Bug: http://silverlight.net/forums/t/11147.aspx
    List<Product> productsList = new List<Product>();
    
    foreach (var p in products) {
    Product pdt = new Product { ProductID = p.ProductID, ProductName = p.ProductName };
    productsList.Add(pdt);
    }
    productsDataGrid.ItemsSource = productsList;
    }
    else {
    productsDataGrid.ItemsSource = null;
    }
    
    }
    catch (Exception ex) {
    Console.Write(ex.Message);
    }
    }
    
  • 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 ~

101 Responses

  1. Ben Hayat Says:

    Michael, I haven’t digged into yet, but I tell you, ->You’re ‘D’ man!<-

  2. Michael Sync Says:

    You’re ‘D’ man!

    this guy? :)

  3. Michael Sync » CRUD operations in Siverlight using ADO.NET Data Service Says:

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

  4. Michael Sync » Consuming ADO.NET Data Service (Astoria) from Silverlight Says:

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

  5. Michael Sync Says:

    One interesting thing. I found this issue. http://silverlight.net/forums/t/11147.aspx

    The following code makes crashing the IE7. :( so, I put a workaround in my code to avoid this error..

    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
    };

    datagrid1.ItemsSource = products;

  6. Florian Says:

    Hi, nice code!! Is there a way to manipulate the database without the webservice directly with silverlight? i am concerned about the firewall-issues…
    thanks for pointing in the right direction…
    regards
    florian

  7. Bryan Lahartinger Says:

    Hi…I’m new to silverlight and I would really like to get webservices running, I tried your demo code above but the webpage comes back blank and I’m not sure why? :S Any ideas?

  8. Michael Sync Says:

    Hi Florian,

    Why do you think that http webservice might have the problem with firewall? Please take a look my reply in SL forum..

    Bryan,

    Have you installed SL 2.0 in your machine?

  9. Bryan Lahartinger Says:

    Yes I have indeed. =)

  10. Michael Sync Says:

    Hi Bryan,

    :)

    Please comment out the code for calling web service and try again. I just want to make sure whether you are able to run the Silverlight content in your web browser…

    If you can see the silverlight page as screenshot except datagrid from my sample, please do the following steps.

    1. Attach the SQL database to your SQL server.. if you dont have SQL express, please install SQL express with advanced service because it has Management Studio build-in.

    2. change the connection in web.config of ASP.NET project.

    3. build the solution and update web service from SL project.

    4. uncomment the code for calling web service.. and try to run the application..

    I hope it should be working fine..

  11. Hassan Says:

    Thanks for your time Michael, we really appreciete your hard work and dedication to the new Silverlight family. Can you please create step by step instructions “if and when time permits”.

    Thanks again.

  12. Michael Sync Says:

    Hello Hassan,

    Yes. I have updated the post right now. Let me know if you have some suggestions or comments. Thanks.

  13. Hassan Says:

    Hi Michael, I looked at the tutorial and it looks nice and clear.
    I am going to create an application using the tutorial and let you know how things go. “this evening”

    Thank you so much, like Ben said You Are D Man

  14. David Miranda Says:

    Hi, I am currently trying to something like this. However, i am using VB.Net….is it still possible using VB or is this a stricly C# thing for the moment. I tried translating it into VB but the code but this bit:
    productMgrSoapClient.RetrieveProductsCompleted += new EventHandler(productMgrSoapClient_RetrieveProductsCompleted);

    is confusing the hell out of me…for a start i cant a find a “MyFunctionCompleted” method, I have got the line prior to this though… “MyFunctionAsync”

    Any help would be really appreciated! Great Work by the way!

  15. Michael Sync Says:

    I tried translating it into VB but the code but this bit:
    productMgrSoapClient.RetrieveProductsCompleted += new EventHandler(productMgrSoapClient_RetrieveProductsCompleted);

    You know how to add event handler, right?

    In VB.NET, it will be like that..

    Addhandler productMgrSoapClient.RetrieveProductsCompleted, AddressOf(YourFuncName)

  16. David Miranda Says:

    Hi, yeah thanks, i figured out thats what was going on in the end, was just a little confused by the C# syntax for adding an event handler….
    Though i have a new problem now. My Web Service resides in my Web Project. The Silverlight app is in the same solution. But i get a cross domain error:
    “An exception of type ‘System.ServiceModel.CommunicationException’ occurred in System.ServiceModel.dll but was not handled in user code

    Additional information: [CrossDomainError]”

    It fails at the point of executing the Method: “MyBase.BeginInvoke(“HelloWorld”, _args, callback, asyncState)”

    Cant quite figure out why its happening..?

  17. Michael Sync Says:

    Hi David,

    Please check the port of ASP.NET project. Please change it to static port if it’s not.

    then, please check the port of proxy class. (I think it’s is in disco file.)

  18. David Miranda Says:

    Hi Mike,

    Thanks for your Help. I managed to fix my last error. I did start having a few other issues…like i was getting an Error: HRESULT E_FAIL has been returned from a call to a COM component. But i somehow managed to sort that out as well (still dont quite know why i was getting that error, though i have am idea).

    Cheers!

  19. Michael Sync Says:

    Hello David,

    Please download this sample

    http://michaelsync.net/demo/SL2WebSrvVB.zip

    I converted C# project to VB project using converter. but there is one thing that you need to do. I’m not sure how to use implicitly-typed variable and LINQ in VB.NET. that’s why I didn’t implement the code in displayData() function of ListingControl.xaml.vb. The parameter “xmlContent” has the XML that we got from web service. you have to parse it to object and bind with datagrid. As you are familiar with VB.NET, it might be easy for you to read the XML string and parse it to object. ..

    Hope it helps..

  20. Wöchentliche Rundablage: ASP.NET MVC, Silverlight 2, LINQ… | Code-Inside Blog Says:

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

  21. Silverlight Cream for March 17, 2008 -- #227 Says:

    [...] 2.5? If you can’t find the DataGrid in Expression Blend 2.5, Michael has a blog to guide you in! Silverlight 2 (beta1) – Database Operations with ASP.NET Web Service in Silverlight 2 Seems to me I saw some discussion somewhere this morning about problems with Web Services. Well… [...]

  22. Mikhail Says:

    Hi Michael! If database contains field with image is it possible to have it binded in the grid? How to do that?

  23. Michael Sync Says:

    Hello Mikhail,

    I haven’t tried using image field with datagrid… I will take a look and will let you know.

  24. Marc Roussel Says:

    Ops. I did write it at the wrong place. Here it is :

    Hi,

    I’ve implemented the Web service for my silverlight and it works perfectly when running inside VS2008, the data is gathered from sql and placed in my controls. the same way as you explained.

    Now when I run my application from IIS7, as you can see here :

    http://gearworld.homedns.org:8082/devpreview
    OPENED BETWEEN 6:30am and 8:00PM EST

    press the small ball at the bottom, you’ll see that my controls doesn’t get any data and I don’t know how to debug it to see what’s going on.

    Must be something like the port number and the communication between the app and the service but I’m not sure.

    Any ideas ?

    Oh and Thank you for your tutorial. Its amazing to see it working, well half working actually

  25. Marc Roussel Says:

    I’m going to let the application running all night.

    Try this : http://gearworld.homedns.org:8082/devpreview

    Once the application is loaded, press the small ball at the bottom and once in the Data form, click the button [Get Data]

    Wait a few seconds and you’ll get the error message returned by the e.Error in the Aync completed

    This is happenning only when running from IIS. When I run from VS2008 in Debug or release mode, the all thing works perfectly…

  26. Michael Sync Says:

    Hi Marc,

    Good Morning!

    Yes. I have checked your website and I found that it seems like cross-domain error. (different URL or different ports are considered as x-domain.For example: “http://abc.com/test and http://def.com/test” and “http://adc:1000:test/ and http://adc:2000:test”)

    Please read this article. How to: Make a Service Available Across Domain Boundaries

    Hope it helps.

  27. JohnMcNamara Says:

    Hi Michael,

    Good work. I have issue that I can insert data, but when I select
    the show listings option no datagrid is displayed.

    Any ideas appreciated.

    John

  28. Rui Marinho Says:

    Hi there michael, first i want to give my congratulations for the great blog and examples you have here, great for whos getting started with silverligh 2.0.

    Well my 1st question is the following, is this way better then using astoria to connect to database in silverlight?

    I m afraid i can’t get an image stored in binary with this webservice, or could i?

    best regards.. from Portugal

    Rui Marinho

  29. Michael Sync Says:

    Hi JohnMcNamara,

    What error you are getting? you may set the breakpoint at the line where you call the web service and you can check what you get from web service..

    Hi Rui,

    >>is this way better then using astoria to connect to database in silverlight?

    It’s hard to say which one is the best.. The reasons that I wrote this post are ~

    1) it’s useful for those who are familiar with asmx web service and don’t know about astoria.

    2) As of now, Astoria Client addon is not compatible with SL 2 so I was just showing the alternative way to Silverlight developers who like to work with database in Silverlight.

    >>I m afraid i can’t get an image stored in binary with this webservice, or could i?

    I think you can. Could you please try to test and let me know the result?

  30. Marc Roussel Says:

    How about DELETE and UPDAT ?

  31. Michael Sync Says:

    Hi Marc,

    Please download the code. I wrote the code in web service. The codes for deleting and updating are very similar to the code for inserting and retrieving. You can easily figure out how to call update and delete function.. please let me know if you can’t figure out.

  32. Aykut Ucar Says:

    Can we replace our existing sqldatareader, dataset etc. websites with this silverlight thing?
    Do you think this Silverlight and webService thing can be responsive under heavy load?
    Regards

  33. Killik Says:

    Thanks for the example the source code. Is it possible to dynamically update the silverlight product list? In ajax, we could make the client query the database every second, refresh it’s page content if needed. Can we do that in Silverlight 2? Thanks!

  34. Michael Sync Says:

    Hello Killik,

    Yes. there is a timer called DispatcherTimer. you can use that timer to execute the update/retreive method every second or etc.. but normally, we dont need to do for every second. maybe. every 2 or 5 mins might be enough.

  35. lucia Says:

    hi Michael, this is a good blog!
    Im a beginner, i dont know where i have to uncomment (i dont know what u mean about the code for calling the web service)to see something ,could You explain it please?
    Thank Tou

  36. Carrie Says:

    Thanks Michael, That’s a really useful & easy to follow example – there’s not alot out there about this at the moment – thanks for filling the gap

  37. kravik Says:

    THANK YOU VERY MUCH!!

  38. Michael Sync Says:

    Hello,

    >>>>Im a beginner, i dont know where i have to uncomment (i dont know what u mean about the code for calling the web service)to see something ,could You explain it please?

    Calling for web service is in EntryControl.xaml.cs and ListingControl.xaml.cs. So, please try to comment (not uncomment) this line

    //Loaded += new RoutedEventHandler(ListingControl_Loaded);

    And see whether you are able to see the Silverlight content in your browser or not.

    then, Attach the SQL database to your SQL.

    then, change the connection string in your web service.

    Are you able to see Silverlight content in your browser? Please visit to this web site. http://memorabilia.hardrock.com/ and let me know whether you are able to see it or not.

    You can also follow the step-by-step instruction to create new project from scratch.

    And also, you need to make sure that your connection is working fine.

    One more thing. Have you set the startup page in ASP.NET project? Please set this page “SL2WebSrvTestPage.aspx” as startup page.

    Hope it helps..

  39. Geordie Says:

    nice, thanks
    in your humble opinion, if i am creating multiple CRUD’s (50 or so of tables), should i have many service reference, or all in one, or group then (rarely used, some times, often). Also, anywhere to look for information such as this

    thanks – great article

  40. Michael Sync Says:

    >>should i have many service reference,

    no. No need to create many service reference.. Just add the service reference once. the VS will generate the proxy(ies) based on your asmx…

    If you are already familiar with ASP.NET and ASP.NET Web Service, you may already aware of this.

  41. Taimur Says:

    great tutorial Michael!!!

    however i am having little problem.. the project works perfectly when compiled through Visual Studio. But when i set everything up in II7 and then try to run it through browser, i get silverlight stuff running but the datagrid displays no result.. why is that so?? please guide me in this regard

    with kind regards,
    Taimur

  42. Taimur Says:

    i have one more question.. is this webservice a WCF service?

  43. Michael Sync Says:

    Hello Taimur,

    Here is some possiblities.

    1. Attach the SQL database to your SQL server.. if you dont have SQL express, please install SQL express with advanced service because it has Management Studio build-in.

    2. change the connection in web.config of ASP.NET project.

    3. build the solution

    4. update web service from SL project. (the URL is hard-coded in disco file. you need to change it or re-reference the webservice from Silverlight)

    5. another thing is that you may need to config the cross-domain policy in your web server root if it’s cross-domain…

  44. Taimur Says:

    Thanks for replying..
    Michael could you please elobrate your points 4 & 5 a bit more?

  45. Michael Sync Says:

    Hello,

    >>Michael could you please elobrate your points 4 & 5 a bit more?

    4.

    If we add the service reference in Silverlight, the proxy class is generated based on wsdl. You can check what files are generated under “Service Reference” folder of your Silverlight project. The URL of your web service will be hard-coded in *.disco file.

    For example: You named your webservice “ServiceReference1″ and the web service name is “WebService1″. When you add this web service in Silverlight, the following file will be generated under “Service References” folder of Silverlight

    Service References
    –[ServiceReference1]
    —–configuration91.svcinfo
    —–configuration.svcinfo
    —–Reference.cs
    —–Reference.svcmap
    —–SL2RightClick.ServiceReference1.HelloWorldResponse.datasource
    —–WebService1.disco
    —–WebService1.wsdl

    The URL of web service “http://localhost:7259/SL2RightClick_Web/WebService1.asmx” will be hard-coded in *.disco, datasource,Reference.cs and etc.

    You will need to change those URLs. So, the best way to change in one shot is that just remove the reference and re-add the reference again.

    OR,

    Some people use the EndpointAddress with custom URL..

    Please take a look this post too. Calling web services with Silverlight 2

    5.

    Do you know what “cross-domain” is?

    The following URLS are “cross-domain”

    Different Domain Names

    The URL of web service is “http://michaelsync.net:200/webservice”
    The URL of web app is “http://syncmichael.net:200/webapp”

    Different Ports Names

    The URL of web service is “http://michaelsync.net:200/webservice”
    The URL of web app is “http://michaelsync.net:300/webapp”

    OR Both

    The URL of web service is “http://michaelsync.net:300/webservice”
    The URL of web app is “http://syncmichael.net:200/webapp”
    two URLs that have either different domain name or different port.

    If your web application (that includes Silverlight content) and web service are under different URL, you need to config cross-domain policy..

    Please read my reply in this post. http://silverlight.net/forums/p/13659/44890.aspx#44890

    Let’s say you have three projects.

    * One project is the Silverlight project that is gonna invoke the service or page or something. (e.g. SLTests1)
    * The other one is the ASP.NET project that is hosted Silverlight content. (e.g. WebApplication1 )
    * Another one is the PHP or ASP.NET project that is gonna receive the POST request from Silverlight. ( e.g. PHP website. http://www.imaginando.net)

    SLTests1
    — Page.xaml
    —-App.xaml

    WebApplication1
    —- [ClientBin]
    ————–SLTests1.xap
    —-SLTests1TestPage.aspx

    ့့့h့ttp://www.imaginando.net ( NOT http://www.imaginando.net/pedroremy/)
    —– clientaccesspolicy.xml
    —– crossdomain.xml

    So, you have to put those two xml files under PHP website.

    I have tried to test with VS Development web server but not working because we can’t put our crossdomain under http://localhost:50782/. Whenever we run the project, those xml files will go under “http://localhost:50782/SilverlightApplication5_Web/”.

    If you want to do POST request, create the Virtual Directory in IIS. then, you can put those XML files under wwwroot.

  46. Taimur Says:

    Michael sorry to bother u again but i am still not able to get this thing run using IIS7.

    i dont think my web server is cross-domain. see i’ll explain..

    1. I have put following folders & files under inetpub\wwwroot\sws\

    App_Code
    App_Data
    Bin
    ClientBin
    Resources
    Default.aspx
    StudentsService.asmx
    web.config

    2. my database is attached in SQL Server.

    3. web.config has following connection string:

    4. I changed the port in ASP.NET from 5588 to 8009 and removed then added the web service again.

    4. when i access my site using http://192.168.1.6:8009/ what i see is the default.aspx page which has silverlight content hosted. everything works fine but i cant get any result onto my grid. but it doesnt throw any error. just doesnt display anything on the grid. However the same thing works fine when run through Visual Studio.
    Now i am not sure if i am using a cross domain or not?

  47. Taimur Says:

    ^^ connection string didnt appear in my comment above ??

  48. Rui Marinho Says:

    I am with the exact same problem.. the grid and webservice work fine in the VS2008 but in the IIS7 the grid dosen’t load any content.

    my service vconfig has

    my pre compiled application is in localhost.

    if i go to: http://localhost/DataService.asmx

    adn invoke the webservice it works as expected…

  49. Rui Marinho Says:

    well i think is difficult to post code here.. wil ltry again my servicereference as the following

    onfiguration>

    /configuration>

  50. Rui Marinho Says:

    well lets try again

    configuration>
    system.serviceModel>
    bindings>
    basicHttpBinding>
    binding name=”DataServiceSoap” maxBufferSize=”65536″ maxReceivedMessageSize=”65536″>
    security mode=”None” />
    /binding>
    /basicHttpBinding>
    /bindings>
    client>
    endpoint address=”http://localhost/DataService.asmx”
    binding=”basicHttpBinding” bindingConfiguration=”DataServiceSoap”
    contract=”iffire_TV.DataServiceProxy.DataServiceSoap” name=”DataServiceSoap” />

    /configuration>

  51. Taimur Says:

    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???

  52. Michael Sync Says:

    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..

  53. Kunal Says:

    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)

    ——————————
    ADDITIONAL INFORMATION:

    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.

    Cheers,
    Kunal.

  54. Michael Sync Says:

    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?

  55. Kunal Says:

    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()
    {
    InitializeComponent();
    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;
    return;
    }
    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??
    Thanks!

    Kunal.

  56. RezaMohamed Says:

    When I add the service reference, I get this Warning message in the error list..is 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=2.0.0.0, 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)

  57. Michael Sync Says:

    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?

  58. Michael Sync Says:

    Hello Kunal,

    Someone from Silverlight forum was facing the same problem that you are facing. He said that uninstall IIS7 and remove all websites. then, reinstall everything works for him..

    Please take a look this thread.

    http://silverlight.net/forums/p/13963/46627.aspx#46627

  59. RezaMohamed Says:

    >>>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?

    Michael,
    I have no refernce to the OpenFileDialog in my project.

  60. Michael Sync Says:

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

  61. Maximilian Says:

    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..

    4000300

    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.

  62. Maximilian Says:

    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.

  63. Darius Says:

    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?

    Thanks.

  64. Michael Sync Says:

    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 asp.net 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..

  65. Manotosh Says:

    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

  66. Rant: Web Service Woes « J-Unleashed! Says:

    [...] me a little bewildered that my own code was having so many troubles. That said, I just found another example from Michael Sync that I’m going to take a look at. It looks a lot more thorough at first glance. I’ll [...]

  67. Joe Says:

    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!

  68. Thank You, Michael Sync! « J-Unleashed! Says:

    [...] You, Michael Sync! I tried out the step-by-step example by Michael Sync for getting data into a datagrid in Silverlight via webservices. I skipped some steps as I already [...]

  69. Lucia Says:

    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:

    EntradaControl.cs

    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()
    {
    InitializeComponent();
    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;
    return;
    }
    WebServiceProxy.AsistenciaManagerSoapClient participanteMgrSoapClient =
    new ITLAB_1.WebServiceProxy.AsistenciaManagerSoapClient();

    participanteMgrSoapClient.CrearParticipanteAsync(participanteName.Text);
    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;
    }
    else
    {
    errMessage.Foreground = new SolidColorBrush(Colors.Red);
    errMessage.Text = e.Error.ToString();
    errMessage.Visibility = Visibility.Visible;
    }

    }
    }

    }

  70. Michael Sync Says:

    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..

  71. Dave Says:

    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.

    Dave

  72. Michael Sync Says:

    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..

  73. Jeremy Hardin Says:

    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,

  74. Michael Sync Says:

    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…

  75. Michael Sync Says:

    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}
    productsList.Add(pdt)
    productsDataGrid.ItemsSource = productsList
    Next

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

  76. Rms81 Says:

    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

  77. Soma Says:

    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?

  78. Michael Sync Says:

    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.

  79. Michael Sync Says:

    >>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..

  80. Cherian Says:

    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.

    Regards,
    Cherian

  81. Michael Sync Says:

    I have tested and it works.. Can you send me your sample project and database? My Email is mchlsync AT gmail DOT com

  82. Cherian Says:

    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.
    regards,
    Cherian

  83. Arun vinoth Says:

    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..

  84. Taimur Says:

    will this work with Silverlight 2 Beta 2??

  85. Michael Sync Says:

    Nope. But I’m updating all of my samples. It will be up this weekend.

  86. Michael Sync Says:

    Hello,

    I have updated the sample. Please get the latest code from this link http://michaelsync.net/2008/06/29/silverlight-2-beta2-samples-updated

    thanks.

  87. Always 英文技术文章参照( 七 ){ UpdateTime:2008-7-15; } My article in the cnblogs - cnblogs.com Says:

    [...] 9.Silverlight 2 (beta1) – Database Operations with ASP.NET Web Service in Silverlight 2 http://michaelsync.net/2008/03/10/silverlight-2-beta1-database-operations-with-aspnet-web-service-in... [...]

  88. Spring Says:

    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
    Try
    Dim objMyService As New MyServiceRef.DatabaseEngineSoapClient
    objMyService.getLzTenLoggedInDataAsync()
    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)
    Try
    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.

  89. qhnz Says:

    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?

  90. Michael Sync Says:

    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.

  91. jai Says:

    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: —
    Service

    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….

  92. huzan Says:

    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?

  93. Jimmie Says:

    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…

    Jimmie

  94. interperfect Says:

    @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.

  95. Iyer Says:

    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 :-)

    Y

  96. brian flowers Says:

    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,

    Brian

    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()

    Try

    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)
    sqlConn.Open()

    da.SelectCommand = sqlCmd
    da.Fill(ds)
    End Using
    sqlConn.Close()
    End Using

    Catch ex As Exception
    End Try

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

  97. Rama Says:

    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.

  98. 2TIND Groep8: Silverlight Says:

    [...] http://michaelsync.net/2008/03/10/silverlight-2-beta1-database-operations-with-aspnet-web-service-in... [...]

  99. Alexandra Says:

    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.

    [WebMethod]
    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)
    {
    try
    {
    SqlConnection _sqlConnection = new SqlConnection();
    _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["sqlConnectionString"].ToString();
    _sqlConnection.Open();

    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(“‘”, “””) + “‘)”;
    command.ExecuteNonQuery();
    _sqlConnection.Close();
    return true;

    }
    catch (Exception ex)
    {
    return false;
    }
    }

    Thank you very much.

  100. Viral Patel Says:

    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..

  101. Siddharth Dahiya Says:

    Hey Michael,

    I need to retrieve data from my MSSQL server for a silverlight App. The problem is that if I do make a webservice and set it up, I will be putting it on the testing server ONLY. When the project is complete and the data is transfered to the deployment server, there is a posibility that the server IP/URL might change. therefore, can you make a suggestion as to how I should retrieve data from the SQL? the server is going to be static so I know the database will be where it is now.

    Also, I also tried to make a blank aspx page that writes the required data to the response stream. But silverlight does not allow to download the contents of the web page.

    Any suggestions?

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.