Creating a webservice that needs input parameters - c#

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

Related

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;
}

Firebase C# Update&Delete Operations

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?

How to call this Delete web api method in C#?

I have the following Delete WebAPI implemented, which is working fine and tested through swagger:
//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
SetContext(orgoid);
return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}
And I am calling from client like below:
var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");
// sending comma separated string of ids like 1,2,
// not sure if the ContentType is correct
request.ContentType = "text/html";
request.Method = "DELETE";
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
}
}
}
But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:
private static T Call<T>(string url, string body, int timeOut = 60)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "DELETE";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
then call it like this:
var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
var output = Call<dynamic>(url, body);

Server Not Found 404 in Application to read data from api But without passing parameters it works

I got one more question related to api I'm working on :p
My problem is that the application i made to read the data works perfectly when the url is all passed, but if i want to pass the general url + parameters it doesn't...
Code with Full URL
private void btn_Api_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://MyIP/api/Employee/?FirstName=Jorge");
request.Method = "POST";
string postData = "";
byte[] data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
try
{
using (WebResponse response = request.GetResponse())
{
var responseValue = string.Empty;
// grab the response
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
if (responseValue != "")
{
string _txtFileNew = #"C:\Users\Jorge.Leite\Documents\teste\" + txt_First.Text + ".txt"; //+txt_Last.Text + ".txt";
StreamWriter _srEannew = new StreamWriter(_txtFileNew);
_srEannew.WriteLine(responseValue);
_srEannew.Close();
}
}
}
catch (WebException ex)
{
// Handle error
}
Code with Url + parameters later PS: postData is passing the correct string ("?FirstName=Jorge") Jorge is the input Name
private void btn_Api_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("MyIP/api/Employee/");
request.Method = "POST";
string postData = string.Format("?FirstName=" + txt_First.Text);
byte[] data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.ContentLength = data.Length;
When using this code it has an exception server not found 404
I really don't know what going on with this :\
Thank you in advance
Web API with POST methods do not work as smooth as with GET methods.
Check this other link to know a bit more Reading FromUri and FromBody at the same time

Google Api get token request returns invalid_request

I'm trying to get Google APi's access_token using c# and always getting error message invalid_request. There is my code:
var Params = new Dictionary<string, string>();
Params["client_id"] = GoogleApplicationAPI.CLIENT_ID;
Params["client_secret"] = GoogleApplicationAPI.CLIENT_SECRET;
Params["code"] = "4/08Z_Us0a_blkMlXihlixR1579TYu.smV5ucbI8U4VOl05ti8ZT3ZD4CgMcgI";
Params["redirect_uri"] = GoogleApplicationAPI.RETURN_URL;
Params["grant_type"] = "authorization_code";
var RequestData = "";
foreach (var Item in Params)
{
RequestData += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value) + "&";
}
string Url = "https://accounts.google.com/o/oauth2/token";
var request = (HttpWebRequest) WebRequest.Create(Url);
request.Method = HttpMethod.Post.ToString();
request.ContentType = "application/x-www-form-urlencoded";
var SendData = Encoding.UTF8.GetBytes(RequestData);
try
{
request.ContentLength = SendData.Length;
Stream OutputStream = request.GetRequestStream();
OutputStream.Write(SendData, 0, SendData.Length);
} catch {}
try
{
using (var response = (HttpWebResponse) request.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
string JSON = sr.ReadToEnd();
}
} catch {}
I use https://developers.google.com/accounts/docs/OAuth2WebServer#offline
Try removing the call to HttpUtility.UrlEncode on each item in the request data. You shouldn't need to do this as the data is not going into the url it's being POSTed. This is no doubt diluting the information being sent which is resulting in your Invalid Request response.

Categories

Resources