Silverlight 2 (beta1) - Database Operations with ASP.NET Web Service in Silverlight 2
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)
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

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

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

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”

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

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

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

- The following dialog will be shown. Click “Discover” button

- (One web service will be shown in “Service:” panel after clicking “Discover” button.) Double-click on that one.

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

























Ben Hayat said
am March 10 2008 @ 8:05 pm
Michael, I haven’t digged into yet, but I tell you, ->You’re ‘D’ man!<-
Michael Sync said
am March 10 2008 @ 8:34 pm
this guy?
Michael Sync » CRUD operations in Siverlight using ADO.NET Data Service said
am March 10 2008 @ 8:57 pm
[...] Silverlight 2 (beta1) - Database Operations with ASP.NET Web Service in Silverlight 2 [...]
Michael Sync » Consuming ADO.NET Data Service (Astoria) from Silverlight said
am March 10 2008 @ 8:58 pm
[...] Silverlight 2 (beta1) - Database Operations with ASP.NET Web Service in Silverlight 2 [...]
Michael Sync said
am March 10 2008 @ 10:55 pm
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;
Florian said
am March 13 2008 @ 10:17 am
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
Bryan Lahartinger said
am March 14 2008 @ 7:02 am
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?
Michael Sync said
am March 14 2008 @ 9:27 pm
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?
Bryan Lahartinger said
am March 14 2008 @ 9:31 pm
Yes I have indeed. =)
Michael Sync said
am March 14 2008 @ 11:28 pm
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..
Hassan said
am March 15 2008 @ 4:57 am
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.
Michael Sync said
am March 15 2008 @ 10:59 am
Hello Hassan,
Yes. I have updated the post right now. Let me know if you have some suggestions or comments. Thanks.
Hassan said
am March 15 2008 @ 1:05 pm
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
David Miranda said
am March 15 2008 @ 9:22 pm
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!
Michael Sync said
am March 15 2008 @ 10:44 pm
You know how to add event handler, right?
In VB.NET, it will be like that..
Addhandler productMgrSoapClient.RetrieveProductsCompleted, AddressOf(YourFuncName)
David Miranda said
am March 16 2008 @ 10:03 am
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..?
Michael Sync said
am March 16 2008 @ 6:46 pm
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.)
David Miranda said
am March 17 2008 @ 12:10 am
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!
Michael Sync said
am March 17 2008 @ 8:37 am
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..
Wöchentliche Rundablage: ASP.NET MVC, Silverlight 2, LINQ… | Code-Inside Blog said
am March 17 2008 @ 1:14 pm
[...] Silverlight 2 (beta1) - Database Operations with ASP.NET Web Service in Silverlight 2 [...]
Silverlight Cream for March 17, 2008 -- #227 said
am March 17 2008 @ 3:34 pm
[...] 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… [...]
Mikhail said
am March 18 2008 @ 9:34 am
Hi Michael! If database contains field with image is it possible to have it binded in the grid? How to do that?
Michael Sync said
am March 18 2008 @ 4:47 pm
Hello Mikhail,
I haven’t tried using image field with datagrid… I will take a look and will let you know.
Marc Roussel said
am March 19 2008 @ 4:17 pm
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
Marc Roussel said
am March 19 2008 @ 6:05 pm
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…
Michael Sync said
am March 19 2008 @ 7:07 pm
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.
JohnMcNamara said
am March 21 2008 @ 2:27 am
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
Rui Marinho said
am March 25 2008 @ 9:23 am
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
Michael Sync said
am March 25 2008 @ 10:01 am
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?
Marc Roussel said
am March 26 2008 @ 4:33 am
How about DELETE and UPDAT ?
Michael Sync said
am March 26 2008 @ 6:03 am
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.
Aykut Ucar said
am March 26 2008 @ 10:38 am
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
Killik said
am March 28 2008 @ 11:03 am
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!
Michael Sync said
am March 28 2008 @ 10:36 pm
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.
lucia said
am March 29 2008 @ 8:43 pm
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
Carrie said
am March 31 2008 @ 7:52 pm
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
kravik said
am April 1 2008 @ 1:28 am
THANK YOU VERY MUCH!!
Michael Sync said
am April 4 2008 @ 12:56 am
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..
Geordie said
am April 8 2008 @ 9:11 am
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
Michael Sync said
am April 8 2008 @ 9:15 am
>>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.
Taimur said
am April 10 2008 @ 2:02 pm
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
Taimur said
am April 10 2008 @ 2:36 pm
i have one more question.. is this webservice a WCF service?
Michael Sync said
am April 10 2008 @ 7:18 pm
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…
Taimur said
am April 10 2008 @ 10:52 pm
Thanks for replying..
Michael could you please elobrate your points 4 & 5 a bit more?
Michael Sync said
am April 10 2008 @ 11:22 pm
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
Taimur said
am April 11 2008 @ 1:47 am
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?
Taimur said
am April 11 2008 @ 1:48 am
^^ connection string didnt appear in my comment above ??
Rui Marinho said
am April 11 2008 @ 2:11 am
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…
Rui Marinho said
am April 11 2008 @ 2:13 am
well i think is difficult to post code here.. wil ltry again my servicereference as the following
onfiguration>
/configuration>
Rui Marinho said
am April 11 2008 @ 2:14 am
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>
Taimur said
am April 11 2008 @ 6:10 am
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???
Michael Sync said
am April 12 2008 @ 10:55 pm
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..
Kunal said
am April 13 2008 @ 11:49 am
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.
Michael Sync said
am April 13 2008 @ 7:40 pm
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?
Kunal said
am April 14 2008 @ 3:54 am
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.
RezaMohamed said
am April 14 2008 @ 2:22 pm
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)
Michael Sync said
am April 14 2008 @ 5:30 pm
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?
Michael Sync said
am April 15 2008 @ 8:47 am
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
RezaMohamed said
am April 15 2008 @ 8:55 am
>>>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.
Michael Sync said
am April 15 2008 @ 11:09 pm
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\.
Maximilian said
am April 18 2008 @ 11:44 am
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.
Maximilian said
am April 18 2008 @ 11:46 am
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.
Darius said
am April 22 2008 @ 7:59 am
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.
Michael Sync said
am April 22 2008 @ 8:18 am
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..
Manotosh said
am April 27 2008 @ 8:58 am
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
Rant: Web Service Woes « J-Unleashed! said
am May 2 2008 @ 8:28 am
[...] 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 [...]
Joe said
am May 2 2008 @ 6:55 pm
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!
Thank You, Michael Sync! « J-Unleashed! said
am May 2 2008 @ 7:24 pm
[...] 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 [...]
Lucia said
am May 6 2008 @ 4:53 pm
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;
}
}
}
}
Michael Sync said
am May 6 2008 @ 7:36 pm
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..