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;
}
Related
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
Im trying to send some data to a machin via LAN cable and WebRequest
this is the class im using
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;
private string status;
public String Status
{
get
{
return status;
}
set
{
status = value;
}
}
public MyWebRequest(string url)
{
request = WebRequest.Create(url);
}
public MyWebRequest(string url, string method)
: this(url)
{
if (method.Equals("GET") || method.Equals("POST"))
{
request.Method = method;
}
else
{
throw new Exception("Invalid Method Type");
}
}
public MyWebRequest(string url, string method, string data)
: this(url, method)
{
string postData = data;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
public string GetResponse()
{
WebResponse response = request.GetResponse();
this.Status = ((HttpWebResponse)response).StatusDescription;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
}
and the action code is
command="?insert_employee:cart_number=0007989222&name=علي&last_name=رمضاني&finger_number=123&?";
MyWebRequest wr = new MyWebRequest(command, "GET");
string Response = wr.GetResponse();
as you see there is some utf-8 character in my command and it dose not work both in browser and my application
but when i try this string it works perfectly:
command = "?insert_employee:cart_number=0007989222&name=ali&last_name=ramazani&finger_number=123&?"
i tested many ways which i found in stackoverflow such as "using uri instead of url", "using httpUtility.UrlEncode", ... but none of them was effective or maybe i use them in a wrong way.
do you have any idea for helping?
You can use the HttpUtility.UrlPathEncode method you encode the path portion of a URL in order to guarantee a consistent decoded URL, regardless of which platform or browser performs the decoding.
Whereas there is beautiful explanation of Encoding
urlPrueba = "http://someexample.com/?insert_employee:cart_number=0007989222&name=علي&last_name=رمضاني&finger_number=123&?";
var uri = new Uri(urlPrueba);
Console.WriteLine("urlPrueba" + " = " + uri.AbsoluteUri);
I am trying to post data from PCL project to remote server. Below is my code:
public async Task<bool> SendToken(string deviceToken, string userId)
{
HttpWebRequest request;
string url = "http://192.168.1.171:91/api/updatePushDeviceToken";
request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.Method = "POST";
string postData = string.Format("userId={0};token={1}&deviceType={2}", userId, deviceToken, deviceType);
var data = Encoding.UTF8.GetBytes(postData);
try
{
request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
}
catch (Exception e)
{
string m = e.Message;
}
return false;
}
private void FinishRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);
var responseString = readStream.ReadToEnd();
}
While running above code, below exception was thrown:
System.Net.WebException: The remote server returned an error: (411)
Length Required.
PCL doesn't contain ContentLength property, hence I added Length as below but now I am getting exception as:
try
{
request.Headers[HttpRequestHeader.ContentLength] = "0";
}
catch (Exception e)
{
}
System.ArgumentException: This header must be modified with the
appropiate property. at
System.Net.WebHeaderCollection.CheckRestrictedHeader (System.String
headerName)
Your request is missing of ContentLength property of your post parameters.
var parameters = Encoding.ASCII.GetBytes(qstring);
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.AllowAutoRedirect = false;
request.ContentType="application/x-www-form-urlencoded";
request.Method = "POST";
request.ContentLength = parameters.Length;
//Send it
var reqStream = request.GetRequestStream();
reqStream.Write(parameters, 0, parameters.Length);
reqStream.Close();
//read it
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string responseHtml = sr.ReadToEnd().Trim();
And please use querystring format to post data, for example : "userId={0}&token={1}&..."
I would like to be able to simulate a browser engine from my code to retrieve a web page from a specific link, and parse the data, the problem is that the page contains some Ajax calls and all I can get is the source code before any script is running.
Is there an easy way to get the final page from the code after the?
I'm currently using the following code:
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("https://www.kayak.com/flights/LHR-AMS/2014-09-10/2014-10-15");
//show the response string on the console screen.
Response.Write(myRequest.GetResponse());
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;
private string status;
public String Status
{
get
{
return status;
}
set
{
status = value;
}
}
public MyWebRequest(string url)
{
// Create a request using a URL that can receive a post.
request = WebRequest.Create(url);
}
public MyWebRequest(string url, string method)
: this(url)
{
if (method.Equals("GET") || method.Equals("POST"))
{
// Set the Method property of the request to POST.
request.Method = method;
}
else
{
throw new Exception("Invalid Method Type");
}
}
public MyWebRequest(string url, string method, string data)
: this(url, method)
{
// Create POST data and convert it to a byte array.
string postData = data;
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();
}
public string GetResponse()
{
// Get the original response.
WebResponse response = request.GetResponse();
this.Status = ((HttpWebResponse)response).StatusDescription;
// Get the stream containing all content returned by the requested server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content fully up to the end.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
I got a Java Servelet like
http://152.252.271.12:9999/media/servlet/RequestProcessor.do
for this I need to pass parameters in Querystring like this
http://152.252.271.12:9999/media/servlet/RequestProcessor.do?input=abc
I need to read response back.
I tried like this.
request.Method = "POST";
request.KeepAlive = false;
request.Credentials = CredentialCache.DefaultCredentials;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
}
// Read Response.
HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream(), Encoding.Default))
{
result = reader.ReadToEnd();
logtxn.LogTxn(result, "SPDCL RESPONSE");
}
webresponse.Close();
Any help appreciated..
Use WebRequest & WebResponse classes. Check http://gsraj.tripod.com/dotnet/webgetpost.html for more information.
I've had a similar problem in the past, I had to host a service in IIS that accepted a string containing a request and returned another string with a response to that request. All of the above needed to be done using HTTP POST.
The solution I found was to host a WCF service on IIS and configure it to use HTTP GET/POST protocols.
Also I remember that I needed to use a Stream class to input and output data (a simple string would not work in this case), in other words, I had a HTTP POST method in WCF that was something like:
Stream GetData(Stream data);
Take a look at this article.
You can use the WebClient class, as a client for the servlet. For example
WebClient myWebClient = new WebClient();
// Download the Web resource and save it into a data buffer.
byte[] myDataBuffer = myWebClient.DownloadData (#"http://152.252.271.12:9999/media/servlet/RequestProcessor.do?input=abc");
// Display the downloaded data.
string download = Encoding.ASCII.GetString(myDataBuffer);
Now parse the result string download and obtain the response.
Please find the below code:
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;
private string status;
public String Status
{
get
{
return status;
}
set
{
status = value;
}
}
public MyWebRequest(string url)
{
// Create a request using a URL that can receive a post.
request = WebRequest.Create(url);
}
public MyWebRequest(string url, string method): this(url)
{
if (method.Equals("GET") || method.Equals("POST"))
{
// Set the Method property of the request to POST.
request.Method = method;
}
else
{
throw new Exception("Invalid Method Type");
}
}
public MyWebRequest(string url, string method, string data): this(url, method)
{
// Create POST data and convert it to a byte array.
string postData = data;
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();
}
public string GetResponse()
{
// Get the original response.
WebResponse response = request.GetResponse();
this.Status = ((HttpWebResponse) response)
.StatusDescription;
// Get the stream containing all content returned by the requested server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content fully up to the end.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
}
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("http://www.yourdomain.com", "POST", "a=value1&b=value2");
//show the response string on the console screen.
Console.WriteLine(myRequest.GetResponse());