C# proxy at webbrowser object - c#

I wanted to create a program in C# that goes to a website, with the use of a proxy server.
If I run this program I got error at line 37 when I debug it. Can you help me please?
I always got the error that the time is occuperd. I changed TimeOut, but
It never does anything.
txtUrl is a textbox where you need to put in the url of the website you wanna visite.
txtProxyPath is a textbox that is used as a openfiledialog,
and there I can select a .txt file with proxy ips in.
Here the code I used:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YoutubeRefresh
{
public partial class Form1 : Form
{
static private ArrayList listProxy = new ArrayList();
static private short proxyShort = 0;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
Uri uriAdress = new Uri(txtUrl.Text);
object[] arrayProxy = listProxy.ToArray();
WebProxy proxyObject = new WebProxy(arrayProxy[proxyShort].ToString());
MessageBox.Show("Proxyserver used: " + arrayProxy[proxyShort].ToString());
proxyShort += 1;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
webRequest.Proxy = proxyObject;
// httpwepresponse error
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
webBrowser1.DocumentStream = receiveStream;
}
private void btnChoosListProxy_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
txtProxyPath.Text = openFileDialog1.FileName;
}
foreach (var v in File.ReadAllLines(txtProxyPath.Text))
{
listProxy.Add(v.ToString());
}
}
}
}
Thank you very much!

var request = (HttpWebRequest)WebRequest.Create("http://google.com");
request.Proxy = new WebProxy("IP", port);
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
using (var streamReader = new StreamReader(stream))
{
Console.WriteLine(streamReader.ReadToEnd());
}
}
}
Also in your App.Config file, (if you don't have one, create one) add the following.
<configuration>
<system.net>
<settings>
<servicePointManager expect100Continue="false"/>
</settings>
</system.net>
</configuration>

Related

Read api result in asp.net

I am using the below C#/ASP.net code to get the weather data from the api. The api link works if I copy/paste it on the browser, returns all the data I want .
But in my C# code, I get error "{"Unable to connect to the remote server"}"
Anyone knows what is wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Xml;
namespace WebApplication2
{
public partial class GetData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static void getData()
{
var url = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=e67fab67a2bc61c221e8a6165965c107";
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(url).Result;
}
protected void Button1_Click(object sender, EventArgs e)
{
getData();
}
}
I'm not sure why you getting unable to connect remote server may be turning off your firewall solve your problem. try below code. https://stackoverflow.com/a/16642279/2745294
https://stackoverflow.com/a/5566981/2745294
string urlAddress = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=e67fab67a2bc61c221e8a6165965c107";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);
}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
}
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
I noticed the issue was that my internet connection was using an internal dns server which its setting does not allow such a calls due to security restrictions. Outside our office, the code works just fine.

ASP.NET C# Get referer from Paypal

I have a big trouble. I've done an e-commerce site many month ago, now i wanna do that after an user has bought, paypal redirect the user in a website that confirm the bought with an e-mail.
Obviously, the return page has a control of refererpage, because it can't send a confirmation mail to all that write the page address, but the command:
Request.ServerVariables["HTTP_REFERER"]
Doesn't work, because paypal is an https webpage. So, how i can solve it?
Thank you before!
hi you can try below code for this:
First set the "notify_url" in your website
<input type="hidden" name="notify_url" value="http://www.your-website-url.com/notifypaypal.aspx" />
after that create notifypaypal.aspx Page.
notifypaypal.aspx : here not required any code ..
notifypaypal.aspx.cs :
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using System.Net;
using BLL;
public partial class notifypaypal : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Post back to either sandbox or live
// string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";//For localhost
string strLive = "https://www.paypal.com/cgi-bin/webscr";//For live server
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
string ipnPost = strRequest;
strRequest += "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
//req.Proxy = proxy;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
// logging ipn messages... be sure that you give write permission to process executing this code
string logPathDir = ResolveUrl("Messages");
string logPath = string.Format("{0}\\{1}.txt",Server.MapPath(logPathDir), DateTime.Now.Ticks);
File.WriteAllText(logPath, ipnPost);
if (strResponse == "VERIFIED")
{
#region [Update Order Status]
string txn_id = HttpContext.Current.Request["txn_id"]; //txn_id= Unique transaction number.
string payment_status = HttpContext.Current.Request["payment_status"]; //payment_status=Payment state(Completed,Pending,Failed,Denied,Refunded)
string pending_reason = HttpContext.Current.Request["pending_reason"]; //pending_reason=Reason of payment delay(echeck,multi_currency,intl,verify,...)
string item_number = HttpContext.Current.Request["item_number"]; //item_number=order number
if (HttpContext.Current.Request["payment_status"].ToString() == "Completed")
{
try
{
//update in database that particular "item_number"(Order number) is successfully Completed
}
catch
{
}
}
else
{
if (HttpContext.Current.Request["payment_status"].ToString() == "Pending")
{
try
{
//update in database that particular "item_number"(Order number) is Pending
}
catch
{
}
}
else
{
}
}
#endregion
}
else if (strResponse == "INVALID")
{
}
else
{
}
}
}

Get userstream from twitter

A month ago a build a twitter tool in c# Windows Form Application. I can send tweets and view the hometimeline,friendtimeline and the mentiontimeline. I used the twitterizer dll with the OAuthTokens method, but there is a refresh limit and it is very slow.
Now i want to start a streaming twitter application but i cant find a proper example or documentation for this. I started but i didn't find the function who can start the stream and but it in a string or textbox. My question is how to get the stream from the hometimeline.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Twitterizer;
using Twitterizer.Streaming;
namespace Twww
{
public partial class Form1 : Form
{
public OAuthTokens tokens = new OAuthTokens();
private string userAgent = null;
public Form1()
{
InitializeComponent();
/* input tokens removed in example code */
tokens.AccessToken = accessToken;
tokens.AccessTokenSecret = accesssecret;
tokens.ConsumerKey = consumerKey;
tokens.ConsumerSecret = consumerSecret;
}
private void Form1_Load(object sender, EventArgs e)
{
Twitterizer.Streaming.UserStreamOptions options = new UserStreamOptions();
OAuthTokens token = new Twitterizer.OAuthTokens ();
TwitterStream stream = new TwitterStream(token, userAgent, options);
}
}
}
I tried to make it work for a user stream, but i get 401 or 403 errors, who says i have no rights
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Twitterizer;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
OAuthTokens tokens = new OAuthTokens();
string consumerKey = "XX";
string consumerSecret = "XX";
string accessToken = "XX";
string accesssecret = "XX";
tokens.AccessToken = accessToken;
tokens.AccessTokenSecret = accesssecret;
tokens.ConsumerKey = consumerKey;
tokens.ConsumerSecret = consumerSecret;
string url = "https://userstream.twitter.com/1.1/user.json?with=followings&replies=all";
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("XX", "XX");
StreamReader reader = new StreamReader(wc.OpenRead(url));
string line;
while ((line = reader.ReadLine()) != null)
{
dynamic json = JsonConvert.DeserializeObject(line);
if (json.text != null)
{
Console.WriteLine(json.text);
}
}
}
}
}
Check this, you have a very well designed guide of TwitterStream in twitterizer:
http://thewayofcode.wordpress.com/tag/json/

Cannot set CookieContainer due to the state of the HttpWebRequest object error?

I am currently trying to login and get cookies to a remote server using windows phone 7 silverlight in visual studio. I managed to login and get a successful result for login, but when I try to put in the codes to get cookies, it just failed.
It produced error "Cannot set CookieContainer due to the state of the HttpWebRequest object." on my code "request.CookieContainer = new CookieContainer();"
Can anyone helps me? I can't seem to find the error and I try to look at the documentation and examples but with no luck. Below is my full codes on windows phone 7.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;
namespace Testing_Login_
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, RoutedEventArgs e)
{
//HttpWebRequest req = WebRequest.Create();
string POST_ADDRESS = "http://mywebsite.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(POST_ADDRESS, UriKind.Absolute));
request.Method = "POST";
// don't miss out this
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
}
// Sumbit the Post Data
void RequestReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
Stream stream = request.EndGetRequestStream(asyncResult);
// Hack for solving multi-threading problem
// I think this is a bug
this.Dispatcher.BeginInvoke(delegate()
{
// Send the post variables
StreamWriter writer = new StreamWriter(stream);
writer.Write("username=" + textBoxUsername.Text + "&password=" + passwordBoxSTAMP.Password);
writer.Flush();
writer.Close();
request.CookieContainer = new CookieContainer();
request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
});
}
// Get the Result
void ResponseReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
this.Dispatcher.BeginInvoke(delegate()
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
// get the result text
string result = reader.ReadToEnd();
if (result == "TRUE")
{
MessageBox.Show("Login Successful!");
//CookieCollection cookieValue = response.Cookies;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(isfs))
{
foreach (Cookie cookieValue in response.Cookies)
{
sw.WriteLine("Cookie: " + cookieValue.ToString());
}
sw.Close();
}
}
}
//MessageBox.Show(cookieValue.ToString());
}
else if (result == "ICRED")
{
MessageBox.Show("Username or Password incorrect!");
}
else
{
MessageBox.Show("Unknown Error!"+result);
}
});
}
private void ReadFromIsolatedStorage()
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs =
isf.OpenFile("CookieExCookies", FileMode.Open))
{
using (StreamReader sr = new StreamReader(isfs))
{
textBoxCookies.Text = sr.ReadToEnd();
sr.Close();
}
}
}
}
}
}
Move the line:-
request.CookieContainer = new CookieContainer();
out of RequestReady and put it in buttonLogin_Click just after you have constructed it.
OR since you aren't re-using it anywhere ditch line altogether.
OR if in fact for things to really work you need to re-use it then construct and hold it somewhere else (such as a field in the class) and assign it to each Request object created before you invoke any BeginGetRequestStream or BeginGetResponse.

Error 400 bing text to speech

I’m using bing’s api TTS, I get the information from: http://msdn.microsoft.com/en-us/library/ff512420.aspx
This is the code (from the webside):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Media;
namespace Apigoogleprova
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Speak();
}
private static void ProcessWebException(WebException e, string message)
{
Console.WriteLine("{0}: {1}", message, e.ToString());
// Obtain detailed error information
string strResponse = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)e.Response)
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII))
{
strResponse = sr.ReadToEnd();
}
}
}
Console.WriteLine("Http status code={0}, error message={1}", e.Status, strResponse);
}
public static void Speak()
{
string appId = "myappID"; //go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "speak to me";
string language = "en";
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId +"&text;=" + text + "&language;=" + language;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
//httpWebRequest.Proxy = new WebProxy(""); set your proxy name here if needed
WebResponse response = null;
try
{
response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (SoundPlayer player = new SoundPlayer(stream))
{
player.PlaySync();
}
}
}
catch (WebException e)
{
//ProcessWebException(e, "Failed to speak");
MessageBox.Show("Error"+e);
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
}
}
}
}
(I changed “myappID” with the ID that has provided me Microsoft)
When I run the app I get the following error:
Remote Server Error (400) Bad Request
I tried to go to the web with my browsers (firefox, chrome and IE):
http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=myappID&text;=speak to me&language;=en
And the result is:
**Argument Exception**
Method: Speak()
Parameter: text Message: Value cannot be null.
Parameter name: text message
id=3835.V2_Rest.Speak.25BD061A
Anyone know how to solve this problem?
Thank you very much!
Remove the ; from the parameter names in the query string.

Categories