Firebase C# Update&Delete Operations - c#

I am developing a desktop application which communicates with our mobile application. They use Firebase as database but since Firebase doesn't support C# I am having really hard times. I could find a solution for Select&Insert operations but I am really stacked at Update&Delete operations.
public void recordEntry(Record rec) {
var json = JsonConvert.SerializeObject(rec);
var request = WebRequest.CreateHttp("firebaseLink");
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();
}
And a part of select function is like:
public List<RecordUI> FillDataGridView()
{
string result = null;
var request = WebRequest.CreateHttp("firebaseLink");
request.Method = "GET";
request.ContentType = "application/json";
try
{
var response = (HttpWebResponse)request.GetResponse();
Encoding responseEncoding = Encoding.GetEncoding(response.CharacterSet);
using (StreamReader sr = new StreamReader(response.GetResponseStream(), responseEncoding))
{
result = sr.ReadToEnd();
}
JObject json = (JObject)JsonConvert.DeserializeObject(result);
I've tried "request.Method = "DELETE" but it deletes all the database. I think I need a kind of SQL command to delete and update but no idea how to insert it into a Http Request. Any ideas?

Related

Creating a webservice that needs input parameters

So, basically I am creating a Windows Service that is going to consult a SOAP Service and after that return an item. To find that item, who made the service created 2 "filters". customerFilter and itemFilter.
So, when I create the web request I need to insert thoose 2 parameters.
I have this:
static string date = DateTime.Now.Date.ToString("yyyy_MM_dd");
static string pathLog = "Logs/LogGetSalesLineDiscount/" + date + "LogGetSalesLineDiscount.txt";
public static string[] CallWebService(IOrganizationService service)
{
var action = "http://...";
var url = "http://...";
var request = (HttpWebRequest)WebRequest.Create(url);
var postData = "customerFilter=" + Uri.EscapeDataString("TESTE");
postData += "&itemFilter=" + Uri.EscapeDataString("TESTE");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Headers.Add("SOAPAction", action);
request.ContentLength = data.Length;
request.Accept = "text/xml";
request.Credentials = new NetworkCredential("...", "...");
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + pathLog, true))
{
file.WriteLine(responseString);
}
return null;
}
}
If I have that, it will return an error 500. I donĀ“t know why.
If I remove the action, it will return something about all the actions in the service...
Please help me, I dont know what to do....

HttpWebRequest.getResponse() returning NULL

I am attempting to create a console app that sends a WebRequest to a website so that I can get some information back from it in JSON format. Once I build up the request and try to get response I just want to simply print out the data, but when I call httpWebRequest.getResponse() it returns NULL.
I have tried multiple other methods of sending the data to the the url but those are all giving me like 404, or 400 errors, etc. This method at least isn't giving me any error, just a NULL.
Here is a snapshot of the documentation I am using for the API (albeit the docs aren't complete yet):
Here is the console app code that I have right now:
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.remot3.it/apv/v27/user/login");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("developerkey", "***KEY***");
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
email = "***EMAIL***",
password = "***PASSWORD***"
});
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
}catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.ReadLine();
}
Expected output is some JSON data, but I am getting a NULL back from getResponse().
Try to serialize the credential in your form and for header send as parameter for this class.
Check below for my code. It is not 100 % fit to your requirement, but atleast it will help to get through your logic.
Here is what I get Json Response from this code. Its work Perfect. Please remember to add timeout option on your webrequest and at the end close the streamreader and stream after completing your task. please check this code.
public static string httpPost(string url, string json)
{
string content = "";
byte[] bs;
if (json != null && json != string.Empty)
{
bs = Encoding.UTF8.GetBytes(json);
}
else
{
bs = Encoding.UTF8.GetBytes(url);
}
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
if (json != string.Empty)
req.ContentType = "application/json";
else
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = false;
req.Timeout = 30000;
req.ReadWriteTimeout = 30000;
//req.UserAgent = "test.net";
req.Accept = "application/json";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Flush();
reqStream.Close();
}
using (WebResponse wr = req.GetResponse())
{
Stream s = wr.GetResponseStream();
StreamReader reader = new StreamReader(s, Encoding.UTF8);
content = reader.ReadToEnd();
wr.Close();
s.Close();
reader.Close();
}
return content;
}

How do I make a POST call from C# that accepts a CSV file as a response?

I am making a POST method call to a Web API from C# and trying to accept a CSV file as a response. But, my code is throwing this error:
The remote server returned an error: (415) Unsupported Media Type.
My function to make the call is as follows:
public void dataPost()
{
var request = (HttpWebRequest)WebRequest.Create("http://example.com");
var postData = "filename=filename";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse(); //fails on this line
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
StreamReader sr = new StreamReader(response.GetResponseStream());
}
Any kind of help would be highly appreciated. Thanks!
Try adding:
request.Accept = "text/csv";

Request uri too long with webservice

I want to do a create via a webservice which needs a uri like this:
http://<url>/webservice.php?operation=<operation>&elementType=<elementType>&element=<element>&
my problem is, element is all information of an email with html body, which is about 6000 characters.
I want to call the url like this:
var request = WebRequest.Create(urlToUse.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlToUse.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(urlToUse);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
but it breaks at
var response = request.GetResponse();
and says the uri is too long.
I can't change the server's max length of the url and the webservice needs the parameters in the url.
I haven't found a suitable solution for me yet so any help is appreciated.Update:
For anyone facing the same issue, the solution that worked for me was to put my query into an byte-Array like
var encoding = new UTF8Encoding();
byte[] bytes = enconding.GetBytes((queryString));
and writing that into the webrequest instead of my queryString
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
You can put data in the body of the request with something a little like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<url>/webservice.php");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonContent = JsonConvert.SerializeObject(new YourObject
{
// Pseudo code... Replace <...> with your values etc
Operation = <YourOperation>,
ElementType = <YourElementType>,
Element = <YourElement>,
// etc...
});
HttpResponseMessage response;
using (HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
response = await client.PostAsync("youroperation/", httpContent);
}
// Do something with response if you want
}
This is JSON based but could be anything you want to pass... This is a simple example that will hopefully give you an idea of how you can proceed.
You need to split the urlToUse at the question mark:
Something like this (not tested)
string[] parts = urlToUse.ToString().Split(new char[]{'?'}, 2);
string url = parts[0];
string data = parts[1];
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(data);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
Good luck with your quest.

Azure AD Graph API add member to group

I am trying to add a member to a group using the aad graph api and I am keep getting 404.
A similar code works for me when I am trying to get the group members.
This is the code:
string requestUrl = string.Format("https://graph.windows.net/{0}/groups/{1}/$linkes/members?api-version=2013-04-05", tenantName, group.ObjectId);
string postData = string.Format("\"url\":\"https://graph.windows.net/{0}/users/{1}?api-version=2013-04-05\"", tenantName, user.ObjectId);
HttpWebRequest webRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Headers["Authorization"] = authenticationResult.CreateAuthorizationHeader();
webRequest.ContentType = "application/json"; //"application/x-www-form-urlencoded";
webRequest.Host = "graph.windows.net";
webRequest.ContentLength = postData.Length;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
string jsonText;
var httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (var streamReader =
new StreamReader(httpResponse.GetResponseStream()))
{
jsonText = streamReader.ReadToEnd();
}
I know there are other ways to do the same work, for example using the graph connection, but I prefer to use this way because it should work for roles as well.
Thanks
Your URL does seem to have a typo: $linkes. Should be $links.

Categories

Resources