How to upload json data using webclient to a custom class post method in VB.net? - asp.net

I'm trying to upload Json data via WebClient to my web service post method, which is getting the body parameter as custom class variable.
I'm getting 404 error when I post the request. Looking for help to send this post data successfully to my web service.
I tried to send the post request like below
Dim webclient As New WebClient()
Dim reqString As Byte()
Dim resByte As Byte()
Dim sendMessage As Object
sendMessage = New With {Key .chatID = "***********", .messageText = "test"}
webclient.Headers("content-type") = "application/json"
webclient.Headers("accept") = "text/plain"
reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(sendMessage))
resByte = webclient.UploadData("http://testurl/SendMessage", "post", reqString)
...
This is my web service method
...
[HttpPost("/SendMessage")]
public string SendMessage([FromBody] SendMessage sendMessage)
{
string apiToken = "*******************************************";
string urlString = "https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}";
string messageText = sendMessage.messageText;
string chatId = sendMessage.chatID;
urlString = String.Format(urlString, apiToken, chatId, messageText);
try
{
WebRequest request = WebRequest.Create(urlString);
WebResponse response = request.GetResponse();
string responseStatus = ((HttpWebResponse)response).StatusDescription;
if (responseStatus == "OK")
{
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (StreamReader reader = new StreamReader(dataStream))
{
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Check the content.
if (responseFromServer.Contains("\"ok\":true"))
{
// Display a confirmation.
return ("Message text was successfully sent to Telegram :-)");
}
else
{
// Display an error.
return ("Failed to send the message text to Telegram :-(");
}
// Display the content.
return (responseFromServer);
}
}
}
else
{
// Display an error.
return ("Failed to send the message text to Telegram :-(");
return ("Response status: " + responseStatus);
}
// Close the response.
response.Close();
//Console.ReadKey();
}
catch (Exception ex)
{
// Display an error.
return ("Failed to send the message text to Telegram :-(");
return (ex.ToString());
}
}
...
This is my custom class
public class SendMessage
{
public string chatID { get; set; }
public string messageText { get; set; }
}

Related

How can I "click" a url programatically from code behind

I have a dynamic list of URL's, which I assemble in code behind in a .NET web app. Each URL simply downloads a file when clicked or run in the address bar of a browser. I need to automate this, in other words loop through the list, and for each url I need to programmatically "click" the url to initiate the download.
Any help will be greatly appreciated.
You can call a url with HttpClient Class
this is my sample for call url and download file, hope this helps.
public async Task RequestAsync(string url, string jsonContent, HttpMethod HttpMethod, Dictionary<string, string> headers = null, bool XRequestedWithHeader = false,
string requestHeaderType = "application/json")
{
var client = new HttpClient();
HttpResponseMessage response;
//get url
if (HttpMethod == HttpMethod.Get)
{
response = await client.GetAsync(url);
}
//post url
else if (HttpMethod == HttpMethod.Post)
{
//convert json to bytes
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonContent);
//buffer bytes
var byteContent = new ByteArrayContent(buffer);
//set header content
byteContent.Headers.ContentType = new MediaTypeHeaderValue(requestHeaderType);
if (headers != null)
foreach (var header in headers)
{
byteContent.Headers.Add(header.Key, header.Value);
}
//headers
if (XRequestedWithHeader)
byteContent.Headers.Add("X-Requested-With", "XMLHttpRequest");
//post url and content
response = await client.PostAsync(url, byteContent);
}
else
{
throw new Exception("Invalid Request Method");
}
if (response.IsSuccessStatusCode)
{
Response.AddHeader("Content-disposition", "attachment; filename=" & ShortFileName)
Response.ContentType = "application/vnd.ms-excel"
Response.WriteFile(FileName)
Response.End()
}
}

Odata naming file return error message of the

I have this custom Odata function to download pdf from download pdf database. I have some issues
1.with Pdf name does not name "reportname.pdf" it is named response.pdf as
2.return error message of reportBinary is null
[HttpGet]
[ODataRoute("GetDownloadReport(downloadId={downloadId})")]
public HttpResponseMessage GetDownloadReport(Guid downloadId)
var received = DateTime.UtcNow;
byte[] reportBinary = null;
string queryString = "SELECT report FROM downloads WHERE id = #downloadId ";
bool success = false;
using (SqlConnection conn = new SqlConnection(connectionString))
{
//get the binary from database
}
HttpResponseMessage response = null;
try
{
if (reportBinary == null)
return Request.CreateResponse(HttpStatusCode.Gone);
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(reportBinary);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = "PORTName.pdf"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
}
try to set filename manually:
String headerInfo = "attachment; filename=" + System.Web.HttpUtility.UrlPathEncode("PORTName.pdf");
response.Content.Headers.Add("Content-Disposition", headerInfo);
I'm not sure what do you want to do about error message, but if you mean setting string content, just set it ;)
response = Request.CreateResponse(HttpStatusCode.Gone);
response.Content = new StringContent(...);
return response;
Consider using NotFound instead of Gone status code (Gone has very specific meaning).

Created a Soap Webservice and calling it in asp.net uisng code and getting error of The remote name could not be resolved

I had developed one web service in SOAP format and trying to access service in asp.net using the below mentioned code.
public static void CallWebService()
{
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _url = "https://test.in/ModelDetail/Service.asmx";
var _action = "https://test.in/ModelDetail/GetWarrantyDetails";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
//using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (HttpWebResponse webResponse= (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch(Exception ex) { throw ex; }
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='https://ndb.bmw.in/'><soapenv:Header/><soapenv:Body><tem:GetWarrantyDetails><tem:IP><demono>WBA3Y37070D45</demono></tem:IP></tem:GetWarrantyDetails></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
but when i call this code i get error of The remote name could not be resolved.
Tried all method but get this error only.
What is missing or wrong i am doing?

Problems sending and receiving JSON between ASP.net web service and ASP.Net web client

You would think with all the posts here that this would be easy to figure out. :| Well here is what should be a simple example. NOTE The web service is VB and the client is c#. The wb service sends and receives fine when called from JQuery. From .NET There is a problem,
If the service asks for a parameter as show below then the client's getresponse method gets error 500 Internal server error
The Web Service
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
Public Function Test(WebInfo As GetUserID) As Person
Dim Someone As New Person
Someone.Name = "Bob"
Someone.FavoriteColor = "Green"
Someone.ID = WebInfo.WebUserID.ToString()
Return Someone
End Function
The Web Client (set up to be send and receive JSON)
public Person Test(int UserID, string url) {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + "test.asmx/Test");
webRequest.Method = "POST";
webRequest.ContentType = "application/json; charset=utf-8";
StreamWriter sw = new StreamWriter(webRequest.GetRequestStream());
sw.Write("{'WebInfo':{'WebUserID':1}}"); // this works from JQuery
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
Person someone = (Person)jsonSerializer.ReadObject(responseStream);
return someone;
}
Has anyone out there done this successfully?
Thanks
Here is a method that makes calls to a JSON web service, allowing the developer to both send and receive complext data types. The object passed in can be any data type or class. The result is a JSON string, and or any error message the methods type is shown below
public class WebServiceCallReturn {
public string JSONResponse { get; set; }
public string SimpleResponse { get; set; }
public string Error { get; set; }
}
public WebServiceCallReturn WebServiceJSONCall(string uri, string requestType, object postData = null) {
WebServiceCallReturn result = new WebServiceCallReturn();
// create request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.Method = requestType;
webRequest.Accept = "application/json; charset=utf-8";
// add json data object to send
if (requestType == "POST") {
string json = "{ }";
if (postData != null) {
try { // the serializer is fairly robust when used this way
DataContractJsonSerializer ser = new DataContractJsonSerializer(postData.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, postData);
json = Encoding.UTF8.GetString(ms.ToArray());
} catch {
result.Error = "Error serializing post";
}
}
webRequest.ContentLength = json.Length;
StreamWriter sw;
try {
sw = new StreamWriter(webRequest.GetRequestStream());
} catch (Exception ex) {
// the remote name could not be resolved
result.Error = ex.Message;
return result;
}
sw.Write(json);
sw.Close();
}
// read response
HttpWebResponse webResponse;
try {
webResponse = (HttpWebResponse)webRequest.GetResponse();
} catch (Exception ex) {
// The remote server returned an error...
// (400) Bad Request
// (403) Access forbidden (check the application pool)
// (404) Not Found
// (405) Method not allowed
// (415) ...not the expected type
// (500) Internal Server Error (problem with IIS or unhandled error in web service)
result.Error = ex.Message;
return result;
}
Stream responseStream = webResponse.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
string resultString = sr.ReadToEnd();
sr.Close();
responseStream.Close();
result.JSONResponse = resultString;
return result;
}
This method could be used as follows
public SomeCustomDataClass Getsomeinformation(int userID) {
UserInfoClass postData = new UserInfoClass();
postData.WebUserID = userID;
SomeCustomDataClass result = new SomeCustomDataClass();
string uri = URL + "SomeServices.svc/GetSomething";
WebServiceCallReturn webReturn = WebServiceJSONCall(uri, "POST", postData);
if (webReturn.Error == null) {
//resultString = CleanJSON(resultString);
JavaScriptSerializer serializer = new JavaScriptSerializer();
try {
result = serializer.Deserialize<SomeCustomDataClass>(webReturn.JSONResponse);
} catch {
result.Error = "Error deserializing";
}
} else {
result.Error = webReturn.Error;
}
return result;
}
Hope that helps someone

Google voice call error

namespace GoogleVoiceCall
{
class Program
{
private const string LOGIN_URL = "https://www.google.com/accounts/ServiceLoginAuth?service=grandcentral";
private const string GOOGLE_VOICE_HOME_URL = "https://www.google.com/voice";
private const string CALL_URL = "https://www.google.com/voice/call/connect";
private static string m_emailAddress = "your email address";
private static string m_password = "password";
private static string m_gizmoNumber = "your gizmo number";
private static string m_destinationNumber = "your destination number";
static void Main(string[] args)
{
try
{
Console.WriteLine("Attempting Google Voice Call");
CookieContainer cookies = new CookieContainer();
// First send a login request to get the necessary cookies.
string loginData = "Email=" + Uri.EscapeDataString(m_emailAddress)
+ "&Passwd=" + Uri.EscapeDataString(m_password);
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
loginRequest.CookieContainer = cookies;
loginRequest.AllowAutoRedirect = true;
loginRequest.Method = "POST";
loginRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
loginRequest.ContentLength = loginData.Length;
loginRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(loginData), 0, loginData.Length);
HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
if (loginResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("Login failed.");
}
else
{
Console.WriteLine("Login request was successful.");
}
// Second send a request to the Google Voice home page to get a string key needed when placing a callback.
HttpWebRequest keyRequest = (HttpWebRequest)WebRequest.Create(GOOGLE_VOICE_HOME_URL);
keyRequest.CookieContainer = cookies;
HttpWebResponse keyResponse = (HttpWebResponse)keyRequest.GetResponse();
if (keyResponse.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("_rnr_se key request failed.");
}
else
{
Console.WriteLine("Key request was successful.");
}
StreamReader reader = new StreamReader(keyResponse.GetResponseStream());
string keyResponseHTML = reader.ReadToEnd();
Match rnrMatch = Regex.Match(keyResponseHTML, #"name=""_rnr_se"".*?value=""(?<rnrvalue>.*?)""");
if (!rnrMatch.Success)
{
throw new ApplicationException("_rnr_se key was not found on your Google Voice home page.");
}
string rnr = rnrMatch.Result("${rnrvalue}");
Console.WriteLine("_rnr_se key=" + rnr);
// Thirdly (and lastly) submit the request to initiate the callback.
string callData = "outgoingNumber=" + Uri.EscapeDataString(m_destinationNumber) +
"&forwardingNumber=" + Uri.EscapeDataString(m_gizmoNumber) +
"&subscriberNumber=undefined&remember=0&_rnr_se=" + Uri.EscapeDataString(rnr);
HttpWebRequest callRequest = (HttpWebRequest)WebRequest.Create(CALL_URL);
callRequest.CookieContainer = cookies;
callRequest.Method = "POST";
callRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
callRequest.ContentLength = callData.Length;
callRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(callData), 0, callData.Length);
HttpWebResponse callResponse = (HttpWebResponse)callRequest.GetResponse();
if (callResponse.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Call request failed.");
}
else
{
Console.WriteLine("Call request was successful.");
}
}
catch (Exception excp)
{
Console.WriteLine("Exception Main. " + excp.Message);
}
finally
{
Console.WriteLine("finished, press any key to exit...");
Console.ReadLine();
}
}
}
}
I have used the above codes for make a call like Googl voice call using Google voicall service, but i am getting an error. error is
_rnr_se key was not found
pelase tell here what are this
m_gizmoNumber and _rnr_se key
add this line before login request :
m_cookies.Add(new Uri(PRE_LOGIN_URL), galxResponse.Cookies);
see here .

Resources