can't get 0 from post request answer - c#

I need to send email thanks to php script. Sript in the server, I did post request to the server, and got answer. If all is good I get 0, if I get 1, all is bad.
This is my code:
public class MessagePost
{
public string to { get; set; }
public string from { get; set; }
public string title { get; set; }
public string message { get; set; }
}
[HttpPost]
public ActionResult SendMessage(FEEDBACK feedbackModel)
{
try
{
string FromEmail = feedbackModel.sEmail;
string toEmail = "zicise#mail.ru";
string title = "Сообщение с сайта народный комунальщик от " + feedbackModel.vFIO;
string message = feedbackModel.vMessage;
MessagePost MP = new MessagePost();
MP.to = toEmail;
MP.from = FromEmail;
MP.title = title;
MP.message = message;
List<MessagePost> dataMessage = new List<MessagePost>();
dataMessage.Add(MP);
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(dataMessage);
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://projects.pushnovn.com/send_email/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = json;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
string convertResult = System.Text.Encoding.UTF8.GetString(byteArray);
RootObject r = JsonConvert.DeserializeObject<RootObject>(responseFromServer);
if (r.code == 0)
{
ViewBag.RedirectMessage = r.msg;
return View("~/Views/Home/RedirectPage.cshtml");
}
else
{
ViewBag.RedirectMessage = r.msg;
return View("~/Views/Home/RedirectPage.cshtml");
}
}
catch (Exception exc)
{
ViewBag.RedirectMessage = "Невозможно отправить e-mail - error: " + exc.Message;
return View("~/Views/Home/RedirectPage.cshtml");
}
}
But I always get 1, what's wrong?
E.g. data
to: zicise#mail.ru
from: test#mail.ru
title: Test Title
message: Test message

Okay.So, I did it.But not good what I want. This is my code for send post query to the server:
public static HttpWebResponse PostMethod(string postedData, string postUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
UTF8Encoding encoding = new UTF8Encoding();
var bytes = encoding.GetBytes(postedData);
//request.ContentType = "application/javascript";
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "application/json; charset=utf-8";
//request.ContentType = "application/json";
//request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.ContentLength = bytes.Length;
using (var newStream = request.GetRequestStream())
{
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
}
return (HttpWebResponse)request.GetResponse();
}
And ActionResult:
[HttpPost]
public ActionResult SendMessage(FEEDBACK feedbackModel)
{
MessageData msgData = new MessageData();
msgData.to = "zicise#mail.ru";
msgData.from = feedbackModel.sEmail;
msgData.title = "Сообщение с сайта наркома от пользователя: " + feedbackModel.vFIO;
msgData.message = feedbackModel.vFIO;
var jsonString = JsonConvert.SerializeObject(msgData);
var response = PostMethod("to=zicise#mail.ru&from=narkom#info.by&title=Second method&message=test message", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("{to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message}", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("[{to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message}]", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod(jsonString, "http://projects.pushnovn.com/send_email/");
if (response != null)
{
var strreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var responseToString = strreader.ReadToEnd();
RootObject r = JsonConvert.DeserializeObject<RootObject>(responseToString);
ViewBag.RedirectMessage = r.msg;
}
return View("~/Views/Home/RedirectPage.cshtml");
}
But this code worked only when I send data in format: to=zicise#mail.ru&from=narkom#info.by&title=Second method&message=test message
But I need to send data from model and get 0 answer. After that PHP script send me email with data. Anyone know, how to convert object in json format name=value&name=value

Related

HttpPostedFileBase to API

I am getting a error at this line var json = JsonConvert.SerializeObject(model); I am passing in a HttpPostedFileBase which I am trying to send to a API.
Error getting value from 'ReadTimeout' on 'System.Web.HttpInputStream'."}
public string UploadToFileManager(HttpPostedFileBase file)
{
var url = string.Format("Common/UploadToFileManager");
var result = ApiHelpers.Post<HttpPostedFileBase> ("POST", url, file);
//return Json(result, JsonRequestBehavior.AllowGet);
return "";
}
public static T Post<T>(string httpMethod, string url, object model)
{
try
{
var fullUrl = cmsApiUrl + url;
var json = JsonConvert.SerializeObject(model);
Stream dataStream = null;
WebRequest Webrequest;
Webrequest = WebRequest.Create(fullUrl);
Webrequest.ContentType = "application/json";
Webrequest.Method = WebRequestMethods.Http.Post;
Webrequest.PreAuthenticate = true;
Webrequest.Headers.Add("Authorization", "Bearer " + cmsApiKey);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
Webrequest.ContentLength = byteArray.Length;
dataStream = Webrequest.GetRequestStream();
using (dataStream = Webrequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
WebResponse response = Webrequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
response.Close();
T result = JsonConvert.DeserializeObject<T>(output.ToString());
return result;
}
catch (Exception e)
{
T result = JsonConvert.DeserializeObject<T>("");
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
return result;
}

Post XML to MVC Controller C#

I'm trying to post XML from www.domain1.com a controller in www.domain2.com.
Here is my code:
www.domain2.com
[HttpPost]
public ActionResult FetchProductsXML()
{
Response.ContentType = "text/xml";
StreamReader reader = new StreamReader(Request.InputStream);
String xmlData = reader.ReadToEnd();
var products = _productService.SearchProducts(showHidden: false);
var xml = _exportManager.ExportProductsToXml(products);
return this.Content(xml, "text/xml");
}
Then in www.domain1.com I am posting as follows..
private string getProductLIstXML()
{
ASCIIEncoding encoding = new ASCIIEncoding();
string SampleXml = "<testXml>test</testXml>";
try
{
byte[] data = encoding.GetBytes(SampleXml);
string url = "http://www.domain2.com/products-xml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(SampleXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
catch (WebException webex)
{
return webex.ToString();
}
}
My Custom Route in RouteProvider class
routes.MapLocalizedRoute("FetchProductsXML",
"products-xml",
new { controller = "Product", action = "FetchProductsXML" },
new[] { "Nop.Web.Controllers" });
The error I get is
System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.HttpWebRequest.GetResponse()
I've followed what the examples from the following SOQ's
How to POST XML into MVC Controller? (instead of key/value)
HTTP post XML data in C#
After a long night, I realized I had the method in the incorrect class :(
All fixed now.

asp.net content type problems after sending data

This is my code for send post query to the server:
public static HttpWebResponse PostMethod(string postedData, string postUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
UTF8Encoding encoding = new UTF8Encoding();
var bytes = encoding.GetBytes(postedData);
//request.ContentType = "application/javascript";
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "application/json; charset=utf-8";
//request.ContentType = "application/json";
//request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.ContentLength = bytes.Length;
using (var newStream = request.GetRequestStream())
{
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
}
return (HttpWebResponse)request.GetResponse();
}
And ActionResult:
[HttpPost]
public ActionResult SendMessage(FEEDBACK feedbackModel)
{
MessageData msgData = new MessageData();
msgData.to = "zicise#mail.ru";
msgData.from = feedbackModel.sEmail;
msgData.title = "Сообщение с сайта наркома от пользователя: " + feedbackModel.vFIO;
msgData.message = feedbackModel.vFIO;
var jsonString = JsonConvert.SerializeObject(msgData);
var response = PostMethod("to=zicise#mail.ru&from=narkom#info.by&title=Second method&message=test message", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("{to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message}", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod("[{to:zicise#mail.ru,from:narkom#info.by,title:Second method,message:test message}]", "http://projects.pushnovn.com/send_email/");
//var response = PostMethod(jsonString, "http://projects.pushnovn.com/send_email/");
if (response != null)
{
var strreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var responseToString = strreader.ReadToEnd();
RootObject r = JsonConvert.DeserializeObject<RootObject>(responseToString);
ViewBag.RedirectMessage = r.msg;
}
return View("~/Views/Home/RedirectPage.cshtml");
}
But this code worked only when I send data in format: to=zicise#mail.ru&from=narkom#info.by&title=Second method&message=test message and he is broken when I try to cut my custom string like: "to="+value+"&from="+value+"&title="+value+"&message="+value
But I need to send data from model and get 0 answer. After that PHP script send me email with data. Anyone know, how to convert object in json format name=value&name=value
Maybe I need to change Content Type and send jsonString to the server? But if that true, what format I need to use?
You need to URL encode the data.
"to="+value+"&from="+value+"&title="+value+"&message="+value
should be changed to:
"to="+HttpUtility.UrlEncode (value)+"&from="+HttpUtility.UrlEncode(value)+"&title="+HttpUtility.UrlEncode(value)+"&message="+HttpUtility.UrlEncode (value)

ReOpening a mantis issue using MantisConnect

I'm trying to reopen resolved or closed Mantis issues using MantisConnect
I have thusfar succeeded in changing the status of non resolved/closed issues but when the issue is one of these two, i keep getting the following Exception:
System.ServiceModel.ProtocolException
with the message:
There is a problem with the XML that was received from the network.
See inner exception for more details.
with inner Exception:
System.Xml.XmlException
With the message:
The encoding in the declaration 'ISO-8859-1' does not match the encoding of the document 'utf-8'.
I'm using the update command to do the update described here: https://www.mantisbt.org/bugs/api/soap/mantisconnect.php?wsdl
got my mantisconnect code from github here:
https://github.com/mantishub/MantisDotNetClient
The funny thing is that the changes to other states and even to the resolved and closed state work, the Exception is only throws when the issue is already resolved or closed
I could not find any other commands in mantisconnect to reopen an issue, anyone have an idea.
Edit:
Mantis issue I was talking about in my comment The ticket: https://mantisbt.org/bugs/view.php?id=16579
Since there is a bug in the mantis API I solved this problem by navigating the website using WebRequests and the bulk UP_STATUS feature from mantis. It's dirty but it works.
class MantisWebRequest
{
public string Password { private get; set; }
public string Username { private get; set; }
public CookieContainer CookieContainer { get; private set; }
public StreamReader Reader { get; private set; }
public Stream DataStream { get; private set; }
public WebResponse Response { get; private set; }
public HttpWebRequest Request { get; private set; }
public string Page { get; private set; }
public MantisWebRequest(string username, string password)
{
Username = username;
Password = password;
CookieContainer = new CookieContainer();
}
public void Connect(string cookieName = null)
{
string loginurl = "http://mantispageurl/login.php";
// Create a request using a URL that can receive a post.
Request = (HttpWebRequest)System.Net.WebRequest.Create(loginurl);
// Set the Method property of the request to POST.
Request.Method = "POST";
Request.KeepAlive = true;
if (cookieName != null)
CookieContainer.Add(new Cookie(cookieName, Username, "/", new Uri(loginurl).Host));
Request.CookieContainer = CookieContainer;
// Create POST data and convert it to a byte array. Modify this line accordingly
string postData = String.Format("username={0}&password={1}&secure_session=on", Username, Password);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
Request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
Request.ContentLength = byteArray.Length;
// Get the request stream.
DataStream = Request.GetRequestStream();
// Write the data to the request stream.
DataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
DataStream.Close();
// Get the response.
Response = Request.GetResponse();
// Get the stream containing content returned by the server.
DataStream = Response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
Reader = new StreamReader(DataStream);
// Read the content.
Page = Reader.ReadToEnd();
// Clean up the streams.
Reader.Close();
DataStream.Close();
Response.Close();
}
private void POST(string url, string postData)
{
Request = (HttpWebRequest)System.Net.WebRequest.Create(url);
Request.Method = "POST";
Request.KeepAlive = true;
Request.CookieContainer = CookieContainer;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
Request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
Request.ContentLength = byteArray.Length;
// Get the request stream.
DataStream = Request.GetRequestStream();
// Write the data to the request stream.
DataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
DataStream.Close();
Response = Request.GetResponse();
// Get the stream containing content returned by the server.
DataStream = Response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
Reader = new StreamReader(DataStream);
// Read the content.
Page = Reader.ReadToEnd();
// Clean up the streams.
Reader.Close();
DataStream.Close();
Response.Close();
}
private void POST(string url, string postData, string tokenName)
{
string token = GetToken(tokenName);
Request = (HttpWebRequest)System.Net.WebRequest.Create(url);
Request.Method = "POST";
Request.KeepAlive = true;
Request.CookieContainer = CookieContainer;
postData = string.Format("{0}={1}&{2}", tokenName, token, postData);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
Request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
Request.ContentLength = byteArray.Length;
// Get the request stream.
DataStream = Request.GetRequestStream();
// Write the data to the request stream.
DataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
DataStream.Close();
Response = Request.GetResponse();
// Get the stream containing content returned by the server.
DataStream = Response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
Reader = new StreamReader(DataStream);
// Read the content.
Page = Reader.ReadToEnd();
// Clean up the streams.
Reader.Close();
DataStream.Close();
Response.Close();
}
private void GET(string url)
{
Request = (HttpWebRequest)System.Net.WebRequest.Create(url);
Request.Method = "GET";
Request.CookieContainer = CookieContainer;
Response = Request.GetResponse();
// Get the stream containing content returned by the server.
DataStream = Response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
Reader = new StreamReader(DataStream);
// Read the content.
Page = Reader.ReadToEnd();
// Clean up the streams.
Reader.Close();
DataStream.Close();
Response.Close();
}
private string GetToken(string tokenName)
{
int tokenIndex = Page.IndexOf(tokenName);
int endindex = tokenIndex + Page.Substring(tokenIndex).IndexOf(">", StringComparison.Ordinal);
int startindex = Page.Substring(0, tokenIndex).LastIndexOf("<", StringComparison.Ordinal);
string input = Page.Substring(startindex, endindex - startindex + 1);
string valuestring = "value=\"";
int tokenIndex2 = input.IndexOf(valuestring, StringComparison.Ordinal);
int endindex2 = tokenIndex2 + valuestring.Length + input.Substring(tokenIndex2 + valuestring.Length).IndexOf("\"", StringComparison.Ordinal);
int startindex2 = tokenIndex2 + valuestring.Length;
string output = input.Substring(startindex2, endindex2 - startindex2);
return output;
}
public void UpdateStatus(int[] issueIds, int statusId)
{
string tokenName = "bug_actiongroup_UP_STATUS_token";
string formUrl = GetUpdateStatusUrl(issueIds);
string formPostDataUrl = "http://mantispageurl/bug_actiongroup.php";
string formPostData = GetUpdateStatusPostData(issueIds, statusId);
GET(formUrl);
POST(formPostDataUrl, formPostData, tokenName);
}
private string GetUpdateStatusUrl(int[] issueIds)
{
string postData = "?";
foreach (var issueId in issueIds)
{
postData = string.Format("{0}&bug_arr%5B%5D={1}", postData, issueId);
}
postData = String.Format("{0}&action=UP_STATUS", postData);
return "http://mantispageurl/bug_actiongroup_page.php" + postData;
}
private string GetUpdateStatusPostData(int[] issueIds, int statusId)
{
string postData = "action=UP_STATUS";
foreach (var issueId in issueIds)
{
postData = string.Format("{0}&bug_arr%5B%5D={1}", postData, issueId);
}
postData = String.Format("{0}&status={1}&bugnote_text=", postData, statusId);
return postData;
}

Send JSON Stream Read XML Response

I have a unique request for me, where I need to send a JSON POST request but read a XML GET. I have tried this below, but I get an error of
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
What do I alter in order for my XML GET to succesful be able to read the response?
public bool PerformPost(Dictionary<string, string> dictFormValues, string strPageTitle, string strPageURL, ref string strMessage)
{
string strEndpointURL = string.Format("websitegoeshere");
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string strPostData = "";
foreach (var d in dictFormValues) { strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&"; }
strPostData += "hs_context=";
HttpWebRequest r = (System.Net.HttpWebRequest)WebRequest.Create(strEndpointURL);
r.Method = "POST";
r.Accept = "application/json";
r.ContentType = "application/x-www-form-urlencoded";
r.ContentLength = strPostData.Length;
r.KeepAlive = false;
Stream datastream = r.GetRequestStream();
WebResponse response = r.GetResponse();
datastream = response.GetResponseStream();
StreamReader reader = new StreamReader(datastream);
string responsefromserver = reader.ReadToEnd();
var xml = System.Xml.Linq.XElement.Parse(responsefromserver);
if (xml.Elements("sid").FirstOrDefault().Value == "1") { return true; }
else
{
var errors = xml.Elements("fail");
foreach (var error in errors.Elements("fail"))
{
strMessage = error.Value;
return false;
}
}
reader.Close();
datastream.Close();
response.Close();
return true;
}
You haven't written the post data to the request stream. You will need to call datastream.Write before you call GetResponse.
For example:
var buffer = Encoding.UTF8.GetBytes(strPostData);
r.ContentLength = buffer.Length;
datastream.Write(buffer, 0, buffer.Length);
datastream.Close();

Categories