I am trying to make a simple program using a firebase database. But i would like to code my client in C# is there any good APIs available? I found a few but some are lacking functions and i would like to know the opinion of someone more experienced in these waters.
There is a REST API which is fairly portable, and you can use this from any .NET language on any supported platform. Dina Cruz has a thorough example of using this API, and you could easily convert this info and use the portable/basic HttpWebRequest type from the BCL instead of whatever Dina used, for example, this is a transliteration of the first POST example from Dina's blog:
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
user = "UserNameValue",
message = "MessageValue"
});
var request = WebRequest.CreateHttp("https://tm-admin-test.firebaseio.com/.json");
request.Method = "POST";
request.ContentType = "application/json";
var buffer = Encoding.UTF8.GetBytes(json);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
var response = request.GetResponse();
json = (new StreamReader(response.GetResponseStream())).ReadToEnd();
// TODO: parse response (contained in `json` variable) as appropriate
There are also several open source projects including Fire#, FirebaseDatabase.net and FirebaseSharp. I'm not sure if these support "all the things."
References
Firebase REST API on google.com
C# example of using Firebase REST API on dinacruz.com
REST examples in C# using WebRequest on StackOverflow.com
Fire# project on github.com
FirebaseDatabase.net project on github.com
FirebaseSharp project on github.com
Related
I am breaking my head trying to upload a feed to walmart, after many times trying i used postman to generate C# restsharp code for me, in postman it works, but when using the c# restsharp code it returns a mysterious error. like this:
"No message body writer has been found for response class FeedAcknowledgement"
what does that mean?
here is my code:
string requestUrl = "";
requestUrl = string.Format("https://marketplace.walmartapis.com/v2/feeds?feedType=inventory");
string method = "POST";
// string[] sig = getSig(method, requestUrl).Replace("\r", "").Split('\n');
var mySig = new Signature(ConsumerID, SecretKEY, requestUrl, method);
var s = mySig.TimeStamp;
var returendSigniture = mySig.GetSignature(s);
var client = new RestClient("https://marketplace.walmartapis.com/v2/feeds?feedType=inventory");
var request = new RestRequest(Method.POST);
//request.AddHeader("postman-token", "c325ba5f-813a-f990-7899-6bfc4b14aa1b");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddHeader("accept", "application/xml");
request.AddHeader("wm_consumer.id", "--");
request.AddHeader("wm_sec.auth_signature", returendSigniture);
request.AddHeader("wm_sec.timestamp", mySig.TimeStamp);
request.AddHeader("wm_qos.correlation_id", "123456abcdef");
request.AddHeader("wm_svc.name", "Walmart Marketplace");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"BOUNDERY\"\r\n\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<wm:inventory xmlns:wm=\"http://walmart.com/\">\n <wm:sku>PP00500-2PC</wm:sku>\n <wm:quantity>\n <wm:unit>EACH</wm:unit>\n <wm:amount>120</wm:amount>\n </wm:quantity>\n <wm:fulfillmentLagTime>1</wm:fulfillmentLagTime>\n</wm:inventory>\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
I spent all day in figuring out how to request Walmart v3. I propose you the following two steps:
Use Walmart signer in order to generate signed token.
You will need to use HttpWebRequest for getting response from Walmart in a way similar to what is described here.
I have not been able to get this to work natively in C#, but I do have a work around.
The Java SDK can successfully submit multi-part requests to Walmart. I wrote a wrapper around the SDK functions that can accept basic command line input to read a text file and send the appropriate call with attached files. From here, you can just call the .jar file (I do it via dynamically generated batch file) from your C# program and receive responses back via text file. This is a sub-optimal system, but it works reliably and when the choice was between updating inventory on 2000 items every day and using some dirty code, I went with the Java wrapper method. This will be replaced as soon as the C# SDK comes out, but I believe this is one of the reasons why the C# SDK may be being delayed.
This solution was used, only after spending about a week trying to get boundaries / streams / attachments to work in C# and having zero success. Cases were also submitted to walmart and I was able to work with some of their top tier engineering support staff and this problem completely stumped them. I was able to trace the Java SDK execution all the way down to a built in Maven / Java function that constructed the web request so there's something under the hood that Java is doing with a multi-part request that isn't immediately clear in C#.
When setting up an application with TradeKing, you get:
A Consumer Key
A Consumer Secret
A Oauth Token
A Oauth Token Secret
For accessing TradeKing's API, that's apparently all you need to build personal applications. However, I can't find a way to build the correct Oauth headers in C#/.NET.
The examples seem fairly simple, like this Node.js sample. The Oauth library for Node.js takes care of generating the appropriate headers. There are similar samples for a few other languages, but they all seem to have libraries to build the proper header from the provided keys and tokens. I can't find a library to do this with C#/.NET.
I'm trying to wrap my head around what's going on in this SO question that builds the headers from scratch, but it's pretty advanced. I'm poking around in the ASP.NET Security repo, because they must be handling this somewhere. But I can't quite find what I'm looking for.
How can I generate an Oauth header from these keys with .NET?
There is an open source library on CodePlex that has some Oauth management classes set up.
I still need to go through it and take out what isn't necessary, but fortunately it doesn't depend on any other classes from the repo. Once I added it to my project, it was pretty easy to test the connection:
public async Task<IActionResult> MakeRequest()
{
string result;
var oauth = new Oauth.Manager();
// _tradeKing is a configuration object I set up to hold user secrets
oauth["consumer_key"] = _tradeKing.ConsumerKey;
oauth["consumer_secret"] = _tradeKing.ConsumerSecret;
oauth["token"] = _tradeKing.OauthToken;
oauth["token_secret"] = _tradeKing.OauthTokenSecret;
var url = "https://api.tradeking.com/v1/accounts.json";
var authzHeader = oauth.GenerateAuthzHeader(url, "GET");
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Headers["Authorization"] = authzHeader;
var response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
return Content(result);
}
There are some more instructions on how to use it from this SO post.
i'm having a little piece of python code which makes a web request using the urllib2 as you can se below
import json
import urllib2
urlRequest = urllib2.Request('<link>')
urlRequest.add_header('Content-Type', 'application/json')
urlRequest.add_header('RegistrationToken', '<token>')
data = {
'content': '<c>',
'messagetype': 'RichText',
'contenttype': 'text',
'id': '<id>'
}
urllib2.urlopen(urlRequest, json.dumps(data))
As i was trying to do it in C# i came across the following problems
how to i send the data
how do i add the headers?
After googling for a while i managed to write this code:
var request = (HttpWebRequest)WebRequest.Create(url_input.Text);
request.ContentType = "application/json";
request.Headers["RegistrationToken"] = rtoken_input.Text;
request.GetResponse();
I managed to deal with the headers part but the question on the data still remains. Also what is the best way to json encode something?
Anyone who knows what to do?
If you are after serializing the POST data to a JSON payload there are few options.
1) System.Web.Helpers.Json.Encode MSDN Link
2) using the JSON.NET library Link
As for your attempt on converting python to C# you are on the correct track.
Refer to this link
Alternatively you could make use of the WebClient class MSDN Link
Refer to this link as well
Pseudo code
var client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("RegistrationToken", "<token>");
string response = client.UploadString("<link>", "<json string>");
The lack of documentation on this subject coupled with the fact that I'm struggling with a learning curve on all fronts and making me really confused about where to start. I need to get this done using C# if possible. I apologize for the vagueness of this question, but I'm really lost. I would love links to comprehensive guides/references.
In my efforts to get this done, I've run into the following problems/questions:
I've created a web service using the otrs gui, with the operation CreateTicket, but requests via C# to my chosen namespace are returning 404 (not found). When I try to add a service reference or web reference with that namespace, I get the same error. However, when I plug that namespace into my browser as the url, it displays "customer.pl".
Can I send a soap request without adding the web service as a service reference in visual studio? Given the previous problem I'm having I can't do it that way. Would I just build the soap request string and write it to the web request's data stream with http://domain/rpc.pl as the uri?
If the answer to the previous question is yes... When trying the below code segment I get an internal server error (500) on the last line. However the header looks like a SOAP header which confuses me because I wouldn't have thought it got that far.
var document = new StringBuilder();
document.Append("<UserLogin>some user login</UserLogin>");
document.Append("<Password>some password</Password> ");
document.Append("<Ticket>");
document.Append("<Title>some title</Title> ");
document.Append("<CustomerUser>some customer user login</CustomerUser>");
document.Append("<Queue>some queue</Queue>");
document.Append("<State>some state</State>");
document.Append("<Priority>some priority</Priority>");
document.Append("</Ticket>");
document.Append("<Article>");
document.Append("<Subject>some subject</Subject>");
document.Append("<Body>some body</Body>");
document.Append("<ContentType>text/plain; charset=utf8</ContentType>");
document.Append("</Article>");
//var uri = new Uri("http://domain/injest");
var uri = new Uri("http://domain/rpc.pl");
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(document.ToString());
httpWebReq.Timeout = 5 * 1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
httpWebReq.ContentType = "text/xml;charset=utf-8";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
Even if all you can offer is where to start, it would help me to know how to proceed, as I'm stumped.
You're using the rpc.pl endpoint which is part of the 'old' RPC-style interface.
You mention you added the web service via the GUI which means you're using the 'new' Generic Interface, which is indeed much easier from .Net.
The address of the endpoint is /otrs/nph-genericinterface.pl/Webservice/GenericTicketConnector or whatever you have called the web service in the admin section.
I am trying to send an xml document to a REST web service. Using a tool like Poster, the call works fine (With the xml in the body of the "content"), but in my code, I get error 503 server unavailable.
Link to Poster: https://addons.mozilla.org/en-US/firefox/addon/poster/
My code is as follows (this is a test-harness so no error handling etc):
string s = "";
using (StreamReader sr = new StreamReader(#"c:\users\dev.admin\documents\visual studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\XMLFile1.xml"))
{
s = sr.ReadToEnd();
}
string url = FULL_URL_WITH_PARAMETERS; // SAME URL AS USED IN POSTER
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
string data = s;
Stream postStream = null;
using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
{
requestStream.Write(data);
}
HttpWebResponse pervasiveResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr1 = new StreamReader(pervasiveResponse.GetResponseStream(), System.Text.Encoding.Default);
string backstr = sr1.ReadToEnd();
}
else
{
throw new ArgumentNullException();
}
REST Starter Kit? WCF Web API (Glenn Block's project, now part of AppFabric int he 4.5 time frame? (although I believe there will be a standalone))? Roll your own joint?
Regardless, I think working with binary is the correct method to go. For that reason, I would start with something like this article. Not because I tried the code and think it is a great article, but merely because the article shows sending XML and I don't have time to find the client I wrote a few months ago. ;-)
If I can break free long enough to find my code, I will post a sample.
Oh, another tool you should look at is SoapUI. No, it is not just for testing SOAP, as it supports REST (and other methodologies) as well as SOAP. One nice benefit of using SoapUI is the ability to move the tests over to LoadUI and stress testing a service. If you are merely consuming services, it might not have the greatest value, of course.