I try to create a simple client for WCF REST service' that I found
here.
I Added the service reference and I wrote this code:
private void button1_Click(object sender, EventArgs e)
{
WebClient proxy = new WebClient();
string serviceURL =
string.Format("http://localhost:53215/IBookService.svc/GetBooksNames");
byte[] data = proxy.DownloadData(serviceURL);
Stream stream = new MemoryStream(data);
DataContractJsonSerializer obj =
new DataContractJsonSerializer(typeof(finalProject_ClientX.ServiceReference3.Book));
finalProject_ClientX.ServiceReference3.Book book = obj.ReadObject(stream) as finalProject_ClientX.ServiceReference3.Book;
MessageBox.Show("book ID : " + book.BookName);
}
When I run the code (press the button) I get the following error:
An unhandled exception of type
'System.Runtime.Serialization.SerializationException' occurred in
System.Runtime.Serialization.dll
Additional information: The type
'finalProject_ClientX.ServiceReference3.Book' cannot be serialized to
JSON because its IsReference setting is 'True'. The JSON format does
not support references because there is no standardized format for
representing references. To enable serialization, disable the
IsReference setting on the type or an appropriate parent class of the
type.
When I run "http://localhost:53215/IBookService.svc/GetBooksNames" in the browser I got the books:
"["MVC Music Store - Tutorial -
v3.0","Pro.ASP.NET.MVC.3.Framework","Application Architecture Guide
v2","Gang of Four Design Patterns","CS4 Pocket Reference"]"
What is the problem?
Seems like Entity framework include the property IsReference = true when it add the attribute DataContract.
So , I would recommend you to include the JSON.Net nuget package in your project.
Then modify you code to something like:
private void button1_Click(object sender, EventArgs e)
{
WebClient proxy = new WebClient();
string serviceURL =
string.Format("http://localhost:53215/IBookService.svc/GetBooksNames");
byte[] data = proxy.DownloadData(serviceURL);
var jsonString = Encoding.UTF8.GetString(data);
IList<string> bookNames = JArray.Parse(jsonString).ToObject<IList<string>>();
//Do something with the list
//foreach (string bookName in bookNames)
//{
//}
}
Related
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for 'Language''
Does anyone know why I'm always getting this error? I found this code on a youtube video to make a calculator. Pleas help.
private void result_Click(object sender, RoutedEventArgs e)
{
result.Background = Brushes.BlueViolet;
Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));
dynamic obj = Activator.CreateInstance(scriptType, false);
obj.Language = "javascript";
string str = null;
try
{
var res = obj.Eval(screen.Text);
str = Convert.ToString(res);
screen.Text = screen.Text + "=" + str;
}
catch (SystemException)
{
screen.Text = "syntax error";
}
Might be you are hitting this issue: https://github.com/dotnet/runtime/issues/13274
Thanks for reporting this issue. Support for usage of the dynamic keyword with COM objects wasn't done for .NET Core 3.0. This issue is being track in https://github.com/dotnet/coreclr/issues/24246 for .Net 5. The work around is to cast the class to the corresponding interface.
Just make sure there is a language definition in the com object and the corresponding interface.
I need to create an application that gets the stock value of a corporation using web services. I currently have a reference to the web service but I do not know how to parse the XML string I get. How do I select just the stock value?
protected void Button1_Click(object sender, EventArgs e)
{
StockRefrence.StockQuote callWeb = new StockRefrence.StockQuote();
string stock = callWeb.GetQuote("CSCO");
Label1.Text = stock;
}
The web service I'm using http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2
You probably want to use XPath:
.Net XPath Examples
I am new to webservices. I'm trying to call one this way just to see the result:
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(getServiceResult("http://prod.sivaonline.pt/SAG.WS.SIVA.SVOLB2C/ViaturasNovas.asmx?wsdl"));
}
public string getServiceResult(string serviceUrl)
{
HttpWebRequest HttpWReq;
HttpWebResponse HttpWResp;
HttpWReq = (HttpWebRequest)WebRequest.Create(serviceUrl);
HttpWReq.Method = "GetMarcas";
HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
if (HttpWResp.StatusCode == HttpStatusCode.OK)
{
//Consume webservice with basic XML reading, assumes it returns (one) string
XmlReader reader = XmlReader.Create(HttpWResp.GetResponseStream());
while (reader.Read())
{
reader.MoveToFirstAttribute();
if (reader.NodeType == XmlNodeType.Text)
{
return reader.Value;
}
}
return String.Empty;
}
else
{
throw new Exception("Error on remote IP to Country service: " + HttpWResp.StatusCode.ToString());
}
}
Now, it doesn't give me any message box. Is this normal? I want to add some parameters, like:
configurador=true
Visual Studio makes it easy to call web services by creating proxy classes for them on the client side. You create an object of the proxy class and calls its respective methods, which are internally converted into SOAP calls by the framework. Simply right-click on your project and use Add Service Reference instead of using HttpWebRequest.
I am connecting to an ODATA Service via a C# ASP.NET application, which has service operations such as:
GetItems(int? itemID, double? price)
I can consume this without issues in my browser, e.g.
http://api.mycompany.com/companycatalogue/GetItems?itemID=4
I understand how to use LINQ to Entities to consume an ODATA service, but can't find a decent explanation of how to consume service operations like the one above in C#. I have made a web reference to the service in my Visual Studio solution.
So far, I have something like this for my usual consuming of the data:
using CompanyCatalogue; //my web reference
...
protected void Page_Load(object sender, EventArgs e)
{
CompanyCatalogueEntities dataContext = new CompanyCatalogueEntities (new Uri("http://api.mycompany.com/companycatalogue/"));
var result = from i in dataContext.Items select i; //just an example
//this is where I get into problems
var operationResults = CompanyCatalogue.GetItems(6, 20.5); //I just made this up
}
Any pointers?
OK, got the answer:
using CompanyCatalogue; //my web reference
...
protected void Page_Load(object sender, EventArgs e)
{
CompanyCatalogueEntities dataContext = new CompanyCatalogueEntities();
DataServiceQuery<GetItemsResult> q = dataContext.CreateQuery<GetItemsResult>("GetItems")
.AddQueryOption("paramName", 6)
.AddQueryOption("paramName2", 20.5);
List<GetItemsResult> items = q.Execute().ToList();
}
This may be help for you.
This sample code used to consume the service operation in the WFC Data Service. This service operation(GetRowCount) returns the integer(int) type value. input para name is "code"
var q = context.CreateQuery<int>("GetRowCount").AddQueryOption("code", "'" + serviceProvider.Code + "'");
int RecordCount = context.Execute<int>(new Uri(q.RequestUri.ToString().Replace("GetRowCount()", "GetRowCount"))).FirstOrDefault();
Have you tried using HttpWebRequest?
I have a Silverlight application that is calling out to an ashx that is hosted in the same application as the Silverlight control.
The ashx does the following (stripped down):
// Basic object
class SomeObject
{
int ID { get; set; }
string Description { get; set; }
double Value { get; set; }
}
// ASHX details
DataLayer dl = GetDataLayer();
List<SomeObject> lst = dl.ListObjects();
string result = "";
if (lst != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
result = serializer.Serialize(lst);
}
context.Response.ContentType = "application/json";
context.Response.Write(result);
context.Response.End();
Now the part I am having trouble with is what to do with the ashx on my Silverlight control.
I am looking to call the ashx and then map the JSON result into my internal silverlight objects. Seems like a pretty simple task but I am not sure how to access the ashx or deal with the response from it. Since Silverlight has a stripped down version of .NET it is throwing me for off.
Any help / suggestions?
Using Silverlight 3, ASP.NET 3.5.
Use System.Json to load the string into a JsonArray. JsonValue.Load() takes a response stream and can populate a JsonArray - from there, you can either iterate through or use LINQ to query the values.
Links:
Working with JSON Data on MSDN
JsonValue.Load on MSDN
Blog post with some sample code
Thanks for the reply Jon. Your links helped me figure it out and I thought I should include the code I used in this question for others that come across this question in the future.
Two ways of handling the Json. For both methods you need to setup a handler to get the Json data.
// This gets the URL to call to get the Json data
Uri uri = GetSomeUrl();
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
downloader.OpenReadAsync(uri);
You then need to implement the event handler downloader_OpenReadCompleted specified above with the code to handle the Json. In both case the code below should be wrapped in a using statement:
using (System.IO.Stream strResult = e.Result)
{
}
First way to handle the Json data that is part of the Silverlight framework is to add a reference to System.Json.
JsonArray jsonArray = (JsonArray)JsonArray.Load(e.Result);
List<SomeObject> lst = new List<SomeObject>();
foreach (System.Json.JsonObject obj in jsonArray)
{
SomeObject obj = new SomeObject();
obj.ID = int.Parse(obj["ID"].ToString();
obj.Description = obj["Description"].ToString();
obj.Value = double.Parse(obj["Value"].ToString());
lst.Add(obj);
}
The other way that is possible with or without Silverlight is:
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<SomeObject>));
List<SomeObject> lst = (List<SomeObject>)(serializer.ReadObject(strResult));
Both methods end up getting me a list of my objects which I can then use as I see fit.
Thanks for the help Jon!