Test Proxy to see if it requires Authentication - c#

I have a list of proxies that I want to loop through and test to make sure they are working and also test to make sure that they do not require a username and password.
However, the test does not seem to be working correctly. For example I have one proxy that I know requires a username and password to use, but it is somehow getting through the test.
Here is the sample code that I have:
HttpWebRequest webReq = (HttpWebRequest)System.Net.HttpWebRequest.Create("http://www.google.com");
webReq.Proxy = new WebProxy(proxy);
HttpWebResponse webRes = (HttpWebResponse)webReq.GetResponse();
if (webRes.StatusCode != HttpStatusCode.ProxyAuthenticationRequired)
{
Stream myStream = webRes.GetResponseStream();
if (myStream != null)
{
success = true;
}
}
For example the following proxy requires authentication: "66.60.148.11:3128". However when I run the code, the webRes.StatusCode comes back as OK and passes the webRes.StatusCode != HttpStatusCode.ProxyAuthenticationRequired test.
Any ideas or sugestions are appreciated.
Thanks!

I would imagine the request to the proxy that is allowing it through (so to speak) is not following HTTP standards by not returning a 407 status code. You can view this by doing a packet sniff with something like WireShark http://www.wireshark.org/ or using browser debug tools like Chromes Developer Tools (Ctrl+Shift+I). You could also check to see what status code is being returned by looking at the value of webRes.StatusCode for this case.

Related

SnipCart API Authorization returns 401 Unauthorized

I want to use the V3 SnipCart API to get data about specific orders on my thank you page. I am using C# to do this. I keep getting this error when trying to use the API
System.Net.WebException:'The remote server returned an error: (401)
Unauthorized.'
I have tried to follow their documentation by using only the API key with no password as shown here. Below is my code that I wrote that is giving me the error. I wrote this inside my controller. I get the error as soon as the breakpoint hits this line responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
//Testing API get data begin
string strurltest = String.Format("https://app.snipcart.com/api/orders/c5541254-r8541-8501-0024-juy85vv002154");
WebRequest requestObjGet = WebRequest.Create(strurltest);
requestObjGet.Credentials = new NetworkCredential("HihiukoJOUBVCTYIiijiGiiYTd6tOiUyTYo", "");
requestObjGet.Method = "GET";
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse(); //401 is triggered here
string strresulttest = null;
using (Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresulttest = sr.ReadToEnd();
sr.Close();
}
Concerns that I have as well are the following:
1.The API key that I entered here is my public api key since I am still in the development and testing phase. I am not sure if this api call will work with the test api key or if I have to use the real secret production key. Any thoughts?
2.I am debugging this off my local machine (localhost:) for now before I deploy these API calls to production to test these changes in prod still with the test api key, could that be a reason for the 401? Since the URL that is trying to get the info is my localhost: url and not my actual domain that I added to SnipCart Dashboard. I was thinking maybe I have to try and hit this from prod environment instead? Any thought?
These are the 2 possibilities that come to mind for me. I am not too savvy on APi's yet so I don't know if my call is missing something.
Summary: All I am trying to do is be able to use the API so that I can load the data I want for an order when users reach my custom thank you page with their token.
Our 401 "Unauthorized" status code is returned when the authentication failed to our API with your Authorization header's value.
Here's the documentation about the auth to our APIs. Make sure to return us a base64 value of your secret API key and the trailing single colon character at the end to respect the Basic Authentication Scheme.
And if you are trying to get data for an order that was placed in live mode then you would need to use the live secret API key.

Session-aware webclient not working properly

I'm trying to web-crawl a site that uses php sessions via cookies. It is a good-ol' Squirrelmail webmail server.
I saw a couple of posts like this one, but it's not working for me.
When reaching the part when the cookies are sent by the host, I tried to retrieve the cookies using:
HttpWebResponse rs = (HttpWebResponse)rq.GetResponse();
CookieCollection cc = new CookieCollection();
cc.Add(rs.Cookies);
But rs.Cookies comes empty. However, there are set-cookie headers on the response, which I try to use as a guide to build actual cookies, like this:
for (int i = 0; i < rs.Headers.Count; i++)
{
if (rs.Headers.Keys[i].ToLower().Contains("cookie"))
{
string val = rs.Headers[i];
string[] vv = val.Split(";=,".ToCharArray());
Cookie co = new Cookie(vv[0], vv[1]);
// I know this is not the cleanest way to do it
// I've tried to manually set different values for
// co.Domain, co.Path and co.HttpOnly, just to get a working
// example. I tried different alternatives, but it doesn't
// seem to change anything
cc.Add(co);
}
}
Next, I send the cookies to request the next page, which is nothing but a frameset. The fact that I reach the frameset means I've been successfully authenticated and the session cookie is working. However, when I request one of the frames, I get an authentication-error web page. I've done my research, and the cookies do not change in the meantime. What may be going wrong?
Some may wonder why I'm trying to access webmail when there is pop/smtp to do a cleaner job. The answer is this is just a first example to learn the basics, I don't really care what the site is as long as I can successfully manage sessions.
I don't think posting all the code is a good idea yet, since it is a bit messy, and long: I planned to clean it once it worked (I'll post it, if you think it's worth the confusion). Moreover, I think I may have a conceptual error related to the frames, that may be the key to solve the problem.

Adobe AIR & Web Service Call. Errors with Error #1085: The element type "br" must be terminated by the matching end-tag "</br>"

Here is my simple code, which works fine if called from php or any other client then adobe air. Same code also works from calling from SWF, there is fluorineFX code for other part of project as well, but then it doesn't do anything to break this.
I do find one thing that all POST calls were somehow changing to GET, which really amazes me. I would be so glad to get the answer for this. Thanks in Advance everyone. Below is the almost same code from my web service. with AIR code just under it.
[WebMethod(EnableSession = true)]
public bool Authenticate(string UserName,string Password)
{
try
{
if (Membership.ValidateUser(UserName, Password)){
FormsAuthentication.SetAuthCookie(UserName, true);
return true;
}
return false;
}
catch (Exception ex)
{
return false;
}
}
and my call from adobe AIR code as below
var ws:WebService = new WebService();
ws.wsdl="http://mysite.com/myservice.asmx?WSDL";
ws.useProxy=false;
ws.addEventListener(LoadEvent.LOAD,onWSDLLoad);
ws.loadWSDL();
ws.Authenticate.addEventListener(ResultEvent.RESULT,resultHandler);
ws.Authenticate.addEventListener(FaultEvent.FAULT,onLoginFaultHandler);
ws.Authenticate("usrname","password");
protected function onLoginFaultHandler(event:FaultEvent):void
{
Alert.show('Login Failed with messsage\r\n[ '+event.fault.faultString+' ]');
/* Error #1085: The element type "br" must be terminated
by the matching end-tag "</br>". */
/* checking the content value of fault event shows
same out put as http://mysite.com/myservice.asmx */
}
protected function onLoginResultHandler(event:ResultEvent):void
{
/* on success code */
}
This guy tells us following in page http://verveguy.blogspot.com/2008/07/truth-about-flex-httpservice.html
All HTTP GET requests are stripped of headers. It's not in the Flex stack so it's probably the underlying Flash player runtime.
All HTTP GET requests that have content type other than "application/x-www-form-url-encoded" are turned into POST requests
All HTTP POST requests that have no actual posted data are turned into GET requests. See 1/ and 2/
All HTTP PUT and HTTP DELETE requests are turned into POST requests. This appears to be a browser limitation that the Flash player is stuck with.
I do see my request above turns into GET, but then I DO have post values in it. OR if those are somehow are not sent or recorded by Web Service Object ?
This is pretty simple... The Flex XML parser uses strict xml checking, so all tags must be closed. If you can change the web service, then change all <br> tags to <br />.
I finally found the answer myself. turns out I was having cookies set to AutoDetect. Which meant that the AIR would call a URL and it would need to redirect to keep the cookie/session value in side the URI itself.
Now I switched that to UseCookies and Everything is back to normal. I could test this from a sample web services and realized it was the server-side that was doing something wrong. And from AIR to Browser that's the only difference of cookies.
Somehow nusoap for PHP is smart to know that there is AutoDetect or New URI of the Web Services available. But AIR couldn't locate that. Anyways Thanks everyone for helping me solve this.

Differentiate between client app and browser in ASMX Web Service?

This is a follow-up to Choosing a Connection String based on kind of request for which I got no answer and what I thought worked doesn't.
I have a webservice that needs to choose a specific connection string based on the user calling it from a browser or from a client application.
I tried:
HttpContext.Current != null? ConnectionStrings["Website"].ConnectionString : ConnectionStrings["Client"].ConnectionString
but realized that at some point even if I'm using the client application, there is some HttpContext (if someone can explain why it'd be great) but the Browser field under Request is "Unknown". So, then I tried:
if ( HttpContext.Current != null )
{
if ( HttpContext.Current.Request.Browser != "Unknown" )
{
//browser connection string here
}
else
//client app connection string here
}
else
//client app connection string here
This worked wonders when debugging, but on testing environment it still points to Browser connection string even when calling from the client app, as if at some point the Browser isn't "Unknown" ...
Is there a MUCH easier/simpler way to do this? The way I'm doing it seems really ugly.
I'm quite desperate at the moment as I have no idea why this is happening..
Rather than detecting and switching on the browser type, consider these two suggestions:
Add Custom Request Headers
In your various callers, define a new custom header in your Http request.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("CallerType", "ClientApp"); // "Browser", etc.
Then you know exactly and reliably what type of client is calling. This would be hard to get wrong, and couldn't be spoofed/mistaken.
Include The Caller Type in the QueryString
myService.asmx?BrowserType=1
Add a simple new querystring parameter to your .asmx webmethod. This will work just the same in a controlled environment, but if other users/developers get it wrong, or malform the expected values, you'd have to take other measures to correct/handle.
Both allow you to easily determine the connString on the incoming value. Perhaps the absense of a modifier/header, you could assume a default. Your sample question has 2 basic outcomes, and either suggested solution will be easy to extend (browser, client app, iPhone, whathaveyou).

Check if website is online with ASP.NET C#?

I would like to know how to check if a website is offline or online using C#?
Try to hit the URL using HttpWebClient over an HTTP-GET Request. Call GetResponse() method for the HttpWebClient which you just created. Check for the HTTP-Status codes in the Response.
Here you will find the list of all HTTP status codes. If your request status code is statrting from 5 [5xx] which means the site is offline. There are other codes that can also tell you if the site is offline or unavailable.You can compare the codes against your preferred ones from the entire List.
//Code Example
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://www.stackoverflow.com");
httpReq.AllowAutoRedirect = false;
HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
if (httpRes.StatusCode==HttpStatusCode.NotFound)
{
// Code for NotFound resources goes here.
}
// Close the response.
httpRes.Close();
First off, define "online" and "offline". However, if your codebehind code is running, your site is online.
For my web apps, I use a setting called Offline, which admin can set on/off.
Then I can check that setting programmatically.
I use this Offline setting, to show friendly maintenance message to my users.
Additionally you can use App_Offline.htm,
reference :
http://www.15seconds.com/issue/061207.htm
http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx
If you mean online/offline state that controls IIS, then you can control this, with custom Web Events (Application Lifetime Events)
http://support.microsoft.com/kb/893664
http://msdn.microsoft.com/en-us/library/aa479026.aspx
You can use Pingdom.com and its API's. Check the source code of the 'Alerter for Pingdom API' at the bottom of this page

Categories

Resources