I have Skype web API which can be called and used inside javascript.
Now, I have created a simple C#.Net console application and want to use the API.
So, Does c# has any API using which we can run javascript and get the output in json or xml or any other standard format.
Thanks in advance.
You don't need to run Javascript inside your C# code. .NET has its own set of functionality to get the information.
The System.Net.WebClient class has a .DownloadString() method that you can use to get the same information from the Skype API as you would in your JavaScript code.
Take that string that you receive from there and use Newtonsoft's JSON DLL (available through NuGet) to turn that string into a JSON object that you can get all of the information from.
Here is an example of the code that I used to do this in one of my projects, modified for generality. For reference, the DLL's you'll need to add usings for are System.Net, and Newtonsoft.Json.Linq.
private static GetData(string urlParameter) {
string response = string.Empty; // This will be the data that is returned.
string url = "http://skype.api.com/someCall?param={0}"; // The API URL you want to call.
using (var client = new WebClient()) {
// This will get the data from your API call.
response = client.DownloadString(string.Format(url, urlParameter));
}
JObject obj = null; // This is the Newtonsoft object.
try {
obj = JObject.Parse(response);
// Continue on processing the data as need be.
}
catch {
// Always be prepared for exceptions
}
The API you are attempting to call is used by the client through their web browser. It makes no sense to attempt to integrate with it using C# on the server side; it'll never work because it won't be able to talk to Skype running on the user's computer. If you're writing a web app in C# then you need to make the Skype API calls in client-side JS running in the user's browser. If you're not writing a web app then I have no idea what you're trying to accomplish, but it's not going to work.
Related
I'm trying to write an ASMX web service to receive a block of JSON data from elsewhere (meaning I have no control over the format of the data - it's documented and consistent, but outside my control). As a test, I've created a simple webpage that sends that same data via an AJAX request. The data is definitely attached as the payload of my POST request:
Picture of chrome devtools showing payload
But when I try to receive that data in my ASMX webservice, I get an empty string:
[WebMethod]
public string UpdateProjectImage()
{
using (var sr = new System.IO.StreamReader(HttpContext.Current.Request.InputStream))
{
string json = sr.ReadToEnd(); // this comes out as an empty string!
return json;
}
}
Please note that this is being built with VS 2012 and IIS 7.5 running on Win2008R2, and I cannot change the technology stack.
The streamreader technique ought to work, because I copied it from another webservice that's working - but it doesn't work in this case (it just gives me an empty string), and I don't know why. It's probably some weird configuration setting, but I just don't know what setting it might be.
Apparently I have to set sr.BaseStream.Position = 0 before the call to sr.ReadToEnd(). I'm not 100% it's the "right" solution (I've done this elsewhere and I didn't need to set the position, and it just seems weird to have to do that), but it's working now and that's good enough for me.
Special thanks to Jasen for pointing me in the right direction.
I am developing a website along with an API to serve it data and have noticed that my current process involves repeated serialization and deserialization of the same data when an API call is made. I was wondering if there is a better way to go about things. Both the website and API are written in C# using ASP.Net Core 2.0.
My current process is as follows:
1) End user loads website page
2) AJAX call is made from client side JavaScript, calling a C# function in the website.
3) The C# website function calls the API (using a Swagger generated client).
4) The API serializes data and returns it to website as JSON.
5) The Swagger client in the web site deserializes the data back to a POCO class.
6) The Website C# function serializes the data back to JSON to return it to AJAX function.
7) Something is done with the JSON data in the client - inevitably after first parsing the JSON.
Example Code:
AJAX call:
var xhr = new XMLHttpRequest();
xhr.open('get', "/GetData", true);
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
doSomething(data);
}.bind(this);
xhr.send();
Website method:
[Route("/GetData")]
public async Task<IActionResult> GetData()
{
var data = await ApiClient.ApiDataGetAsync();
return Json(data);
}
API Method:
[HttpGet]
public Dictionary<int, string> GetData()
{
return _logic.GetData();
}
As the above shows the data is serialized to JSON by the API before being deserialized to a POCO by the Swagger client, then serialized back to JSON in the website to be processed client side.
I realize I could simplify this by calling the API directly from the AJAX rather than going through the website but I would rather avoid this for a number of reasons:
1) It would tightly couple the API to the front end of the website, at the moment I have the option of implementing an interface layer in the site to simplify things if the API needs to be replaced in the future.
2) It would reduce my control over who can access the API - at the moment it is locked down by IP address.
Is there a way I can improve this process so the data doesn't have to be serialized twice whilst retaining the Swagger client?
What problem are you actually trying to solve? The time taken to serialize/deserialize the json is tiny compared to the time taken for networked i/o.
At this point I would say you are trying to optimise something without knowing whether it will improve application performance or reduce cost, which is generally considered a waste of time.
Well, you can forgo the client and simply make your action a proxy using HttpClient to fetch from the API.
The client is intended to actually give you C# objects to work with, so it serializes/deserializes the request/response to make it easier for you to work with the API. That's sort of the whole point. What you're saying is that you don't actually want this, so simply drop the client.
Instead, you can make the request directly to your API from the action, using HttpClient, and then simply return the the response from the HttpClient call. Since the API returns JSON and you need JSON, no further processing needs to be done.
I've searched some time, looking for easy way to connect with some other sites WebAPI. There are some solutions, but they are made in very complicated way.
What I want to do:
Connect with server using URL adress
Provide login and password to get some data
Get data as JSON/XML
Save this data in an "easy-to-read" way. I mean: save it to C# variable which could be easy to modify.
Currently, API that I want to work with is Bing Search, but I'm looking for some universal way. I found an example, but it doesn't work for me and in my app I can't use this class: "DataServiceQuery" because it doesn't exsist.
How do you usually do it? Do you have your favourite solutions? Are there some universal ways or it depends on type of API that you work with?
I'm currently working on .NET MVC app (in case it could make any difference)
From server side
You can use that like below.
// Create an HttpClient instance
HttpClient client = new HttpClient();
// Send a request asynchronously continue when complete
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
var result = readTask.Result
//Do something with the result
});
});
You can see example on following link.
https://code.msdn.microsoft.com/Introduction-to-HttpClient-4a2d9cee
For JavaScirpt:
You could use jQuery and WebAPI both together to do your stuff.
There are few steps to it.
Call web api with Ajax jquery call.
Get reponse in JSON
Write javascript code to manipulate that response and do your stuff.
This is the easiest way.
See following link for reference:
http://www.codeproject.com/Articles/424461/Implementing-Consuming-ASP-NET-WEB-API-from-JQuery
It entirely depends on the type of API you want to use. From a .Net point of view, there could be .Net 2 Web Services, WCF Services and Web API Services.
Web APIs today are following the REST standard and RMM. Some APIs need API Keys provided as url parameters, others require you to put in request's header. Even some more robust APIs, use authentication schemes such as OAuth 2. And some companies have devised their own standards and conventions.
So, the short answer is that there is no universal way. The long answer comes from documentation of each API and differs from one to another.
I have recently returned to .net programming after a 7 year break.
I need to learn how to write a project within an existing open source asp.net mvc 5 ecommerce solution to receive posted json strings from a remote server running php with cURL, send acknowledgement responses, create my own json strings to post back to the remote server and receive acknowledgement responses. This must all be done with server side code, with no client side component whatsoever.
Serializing and deserializing json is not the issue, its using the correct kind of pages or services to send and receive json on the server without any client component, and using http objects directly. I have no experience or knowledge of creating this kind of project.
This is my question: I have had a look at a couple of tutorials about using .ashx and httpClient and httpContext but found them a little confusing. I would like to find a comprehensive guide about how to use json to communicate server to server with realistic examples. Is there one available?
Sounds like a perfect use case for WebApi. It is made specifically to work with JSON (or XML) requests and should work fine with requests issued by other scripts (not browsers).
There are plenty of tutorials available. Here is the official introduction tutorial.
What I often do to create JSON in C# is make an object/class which I serialize to JSON.
My controller has an function:
public JsonResult FunctionName()
{
var json = new { x1 = 10, y1 = "Hello" };
return Json(json);
}
You can call that function with PHP.
Its going to a grt puzzle for me now a days. I have developed a product which is implemented using multiple languages such as a C# Windows app, Titanium iOS app, and a Java application with a team of friends.
I am using a c# web service which is taking parameter of datatype byte[]. I have completed my work on windows app by adding it in service reference.
My Titanium team mate asked me to create some sample code for this web service without using service refrence directly by the url, but instead, either:
Call it with soap or http post methods.
Create a web sevice that they will use with titanium in a easy way
Any other useful idea on how to use the same webservice with titanium
As titanium boy is fresher with titanium right now so I have to do something but I am also stuck and don't know how to suggest him something so I need help from your side.
I suggest you encode your binary data into a Base64 string and send it as such to your C# service. Since you're using SOAP, it would be a very simple solution.
Just use the built in Titanium utilities to encode your data to base64:
// Encode your data
var data = Titanium.Utils.base64encode(dataToSendToWebService);
Now send it using a HTTPClient:
var postDataTOServer = Ti.Network.createHTTPClient({
onload : function(e) {
// If the service returns successfully : true, or false
var isUserAllowed = this.responseText;
},
onerror : function(e) {
// Web service failed for some reason
Ti.API.info(this.responseText);
Ti.API.info('webservice failed with message : ' + e.error);
}
});
// POST
postDataTOServer.open('POST', 'http://yoursite.com/aspwebservice');
// you may have to change the content type depending on your service
// but this is the correct type for binary data
postDataTOServer.setRequestHeader("Content-Type", "application/octet-stream");
// This does a POST to server
postDataTOServer.send(data);