Delete (MediaWiki) Page with C# (HTTP POST) - c#

I try to delete a page like this:
WebClient wClient = new WebClient();
wClient.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
string str_post = "action=delete" + "&title=Vorlage:" + str_zuloeschendeVorlage + "&token=" + str_token + "%2B%5C";
wClient.UploadStringAsync(new Uri(#"http://localhost/mediawiki/api.php"), "POST", str_post);
The Token is not the problem (i got a correct one). And i'm logged in as admin. The callback client_UploadStringCompleted is called correct (with a correct connection). No error code returns (from api). The result is just the code from the api.php (with no error code). But the site is still there. I think the uri or the str_post is wrong.
Please help!

i found the problem...
the headers-information was missing:
WebClient wClient = new WebClient();
wClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wClient.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
the rest of the code is correct

Why do you append "%2B%25C" to your querystring? It translates to " \" (space - antislash) which is strange since it will be part of the received token.
Try to issue the POST request without these noise characters.

Related

Why am I not getting anything from my webrequest? What am I supposed to look for?

First of all I am new to C#. I am writing a WPF program in Visual Studio 2019.
In my project I have multiple web requests and whilst testing how they work the functionality was minimal: only the web requests were made and they were working fine until now. The login authorization request still works.
This is my webrequest.
using (var client = new WebClientEx())
{
client.BaseAddress = serverurl.serviceurl;
client.UseDefaultCredentials = true;
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(excelvertibas.username + ":" + excelvertibas.password));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
client.Timeout = 90000;
byte[] postArray = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(domObjectVariables));
client.Headers.Add("Content-Type", "application/json");//----------------
client.Encoding = Encoding.UTF8;
byte[] responseArray = client.UploadData(serverurl.serviceurl + "StartAddDigitalObject", "post", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(domObjectVariables))); //----------------------------
domMetadataAddResponse = JsonConvert.DeserializeObject<StartAddDigitalObjectResponse>(Encoding.UTF8.GetString(responseArray));
}
The base address works, I tested it manually through Postman.
Username and password are also correct which I have tested.
Post array is also passing information which is needed, and I have checked it whilst adding breakpoints.
My question is why could this be not working anymore and what should I look for?
fyi this is the line of code where is should be getting information back into the response array but for some reason it stays null.
byte[] responseArray = client.UploadData(serverurl.serviceurl + "StartAddDigitalObject", "post", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(domObjectVariables)));
After this the program breaks because the response array contains nothing when I try to pass it further.
Ok i understood what was the problem , when i got the response from the server , it was me who didnt provide the necessary field for the server to respond with anything.So everything was fine with the code.

Pentaho Authentication Method in Silver light Application.

I want to integrate Pentaho with Silverlight platform.For the Authentication, there is log in page for user console. I do not want use above login page to login, I want to login in code behind.
I tried basic authentication, but in new version it won't work.
string[] parts = System.Text.RegularExpressions.Regex.Split(ae.Result, "/");
String data = "userid=" + App.UserName + "&password=" + App.Password;
WebClient webClient = new System.Net.WebClient();
Uri uri = new Uri("http://localhost:8080/pentaho/Home?" + data);
webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
webClient.Encoding = Encoding.UTF8;
App.WindowManager.ConsoleWrite(uri.ToString());
webClient.UploadStringAsync(uri, "POST", "");
But its worked with previous version of Pentaho. I know there are few other methods available in Pentaho. But it should able to do in Silverlight application.
do you know any other solution for do it in Silverlight Application ?
Thanks you very much in advance!!!
In previous version we could pass userid=admin&password=password as part of URL while calling prpt, xaction or Analyzer.
In 5.0 we can authenticate via URL only to Home page.
Try the following to enable it.
i) Stop your Bi server.
ii) Open applicationContext-spring-security.xml and look for filterChainProxy bean.
iii) Comment the existing value section in the bean and add the new value section provided below.
<value>
<![CDATA[CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/api/repos/dashboards/print=securityContextHolderAwareRequestFilter,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,preAuthenticatedSecurityFilter,httpSessionReuseDetectionFilter,logoutFilter,authenticationProcessingFilter,basicProcessingFilter,requestParameterProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor
/webservices/**=securityContextHolderAwareRequestFilterForWS,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,basicProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilterForWS,filterInvocationInterceptorForWS
/api/**=securityContextHolderAwareRequestFilterForWS,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,requestParameterProcessingFilter,basicProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilterForWS,filterInvocationInterceptorForWS
/plugin/**=securityContextHolderAwareRequestFilterForWS,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,requestParameterProcessingFilter,basicProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilterForWS,filterInvocationInterceptorForWS
/**=securityContextHolderAwareRequestFilter,httpSessionPentahoSessionContextIntegrationFilter,httpSessionContextIntegrationFilter,httpSessionReuseDetectionFilter,logoutFilter,authenticationProcessingFilter,basicProcessingFilter,requestParameterProcessingFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor]]>
</value>
iv) Restart your server, you should be able to call a report or xaction with user credientials in the url.
v) Use this test URL http://localhost:8080/pentaho/api/repos/:public:Steel%20Wheels:Buyer%20Report%20%28sparkline%20report%29.prpt/viewer?userid=admin&password=password
Authenticate with query string method is unsecured one, so I found a solution with Basic Authentication method.
WebClient webClient = new System.Net.WebClient();
Uri uri = new Uri("http://serverDomain:8080/pentaho/Home");
//Give user name and password here
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("username:password");
var encodedString = System.Convert.ToBase64String(plainTextBytes);
webClient.Headers["Authorization"] = "Basic " + encodedString;
webClient.Encoding = Encoding.UTF8;
App.WindowManager.ConsoleWrite(uri.ToString());
webClient.UploadStringAsync(uri, "POST", "");

Web api HttpContext.Current.Request.UserAgent is always null

I'm trying to get some of api users request information like the device that they use and the operating system so I tried it like this :
private string GetDeviceInfo()
{
var userAgent = HttpContext.Current.Request.UserAgent;
var uaParser = Parser.GetDefault();
var c = uaParser.Parse(userAgent);
return c.Device + "|" + c.OS + "|" + c.UserAgent;
}
but the HttpContext.Current.Request.UserAgent is always null !. I searched about it and tried this link , could you please tell me what is wrong?
Request.UserAgent is just value of "user agent" header in HTTP request. Browser will automatically send it with all requests (including AJAX), no-browser clients generally will not include such header.
If your "client" is not browser it needs to add the header with appropriate values itself.
Sample if using HttpWebRequest
var request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
request.UserAgent="My custom user agent string";
var response = (HttpWebResponse)myHttpWebRequest.GetResponse();

search strings google

How do you enter a search string into Google and then see how many results it gets? I've tried doing this:
string uri = "http://google.com/search?q=" + stringsToSearchFor[0];
string response = wc.UploadString (uri, stringsToSearchFor[0]);
Console.WriteLine ("Response: " + response);
Console.ReadKey (true);
I figured the string response would get relevant information such as how many results there are, but when I run the program, I get this error message: The remote server returned an error: (503) Server Unavailable.
I think it is more comfortable and easier to use the Google API.
There you get the results as string. No more need to filter the input / web page for infos.
If you really want to do it via getting the html coded page, use
var response = new WebClient().DownloadString("https://www.google.com/search?q="+mySearchString);
Before using the WebClient Class you have to import the namespace:
using System.Net;
But remember:
If the search string contains whitespaces you have to replace them with '%20'.
To do so, use the String.Replace-Function.
searchString.Replace(" ","%20");
Change
string uri = "http://google.com/search?q=" + stringsToSearchFor[0];
string response = wc.UploadString (uri, stringsToSearchFor[0]);
to
string uri = "http://google.com/search?q=" + WebUtility.UrlEncode(stringsToSearchFor[0]);
string response = wc.DownloadString(uri);
and It will work...

How to call an external URL from a ASP.NET MVC solution

First post inhere ever. So better make it a good one.
I have a ASP.NET MVC 2 web application in which I have an actionResult I need to do a call for me.
The thing is I need this A.R to handle some data operations and after that I need it to call an external URL which is actually a Company Module that handles sending messages to our company handset phones.
It just needs to call the URL that looks like this:
string url = "http://x.x.x.x/cgi-bin/npcgi?no=" + phoneNumber + "&msg=" + message;
I don't need any return message or anything. Just want to call that external URL which is of course outside the scope of my own web application. (I do not want to Redirect). That URL must be called behind the GUI without the user ever realising. And the page that they are viewing must not be affected.
I tried with:
Server.Execute(url);
However did not work. I've heard that some ppl go about this by having a hidden iFrame on the page. The setting the src to the url one may need and then somehow execute that, to get the call instantiated. It doesn't seem so elegant to me, but if that is the only solution, does anyone have an example as to how that is done. Or if you have a more sleek suggestion I am all ears.
I finally got it working with this piece of code:
string messageToCallInPatient = "The doctor is ready to see you in 5 minutes. Please wait outside room " + roomName;
string url = "http://x.x.x.x/cgi-bin/npcgi?no=" + phoneNumber + "&msg=" +
messageToCallInPatient;
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
webReq.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
//I don't use the response for anything right now. But I might log the response answer later on.
Stream answer = webResponse.GetResponseStream();
StreamReader _recivedAnswer = new StreamReader(answer);
Since you don't expect a return value from the url, simplest way is
After the AR Execution, use Webclient to trigger the URL
Either by HTTP GET or POST (Synchronous or Asynchronous)
Sample code
WebClient wc = new WebClient();
wc.UploadProgressChanged += (sender, evtarg) =>
{
Console.WriteLine(evtarg.ProgressPercentage);
};
wc.UploadDataCompleted += (sender, evtarg) =>
{
String nResult;
if (evtarg.Result != null)
{
nResult = Encoding.ASCII.GetString(evtarg.Result);
Console.WriteLine("STATUS : " + nResult);
}
else
Console.WriteLine("Unexpected Error");
};
String sp= "npcgi??no=" + phoneNumber + "&msg=" + message;
System.Uri uri = new Uri("http://x.x.x.x/cgi-bin/");
wc.UploadDataAsync(uri, System.Text.Encoding.ASCII.GetBytes(sb);
The sample uses HTTP POST and Asynchronous call( So it will return immediately after triggering the URL - Non blocking)
You can use simply " return Redirect(url);"

Categories