http in c# GET a page - http

this is my for read a web page. in c# lang.
but it got some exceptions when I execute it.
any one know why ?
try
{
string address = "http://" + txtMsg.Text;
int port = int.Parse(textBox1.Text);
System.Net.WebClient webclient = new WebClient();
String content = webclient.DownloadString(address);
Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
skt.Connect(address, port);
string hdrs = "GET " + address + ":" + port + " HTTP/1.1\r\n"
+ "Host: " + address + ":" + port + "\r\n";
byte[] req_as_bytes = Encoding.UTF8.GetBytes(hdrs);
skt.Send(req_as_bytes);
byte[] data = new byte[1024 * 200];
int t = skt.Receive(data);
lstMsg.Items.Add(Encoding.UTF8.GetString(data, 0, t));
skt.Shutdown(SocketShutdown.Both);
skt.Close();
btnConnect.Text = "done";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

OK !
I found the solution:
private void btnConnect_Click(object sender, EventArgs e)
{
var address = "http://" + txtMsg.Text;
var webclient = new System.Net.WebClient();
var content = webclient.DownloadString(address);
//any work
btnConnect.Text = "done";
}

Related

How to used a http conection for send a string like email to a server? on Blackberry

I have a little trouble, i need to create a way to send a string to a server, i a kinda system of complains
try {
String errMsg = validateData();
if(errMsg == null){
String mailURL = CLIENT_CONTACT_URL_MAIL_SERVICE;
mailURL = Utils.replaceAll(mailURL, "#toAddress", TO_DEFAULT_ADDRESS);
String content = "";
content = "Nombre: " + this.names.getText() + "\n";
content += "Apellido: " + this.surname.getText() + "\n";
content += "Email: " + this.email.getText() + "\n";
content += "Telefono: " + this.phone.getText() + "\n";
content += "Mensaje: " + this.complains.getText() + "\n";
mailURL = Utils.replaceAll(mailURL, "#bodyContent", URLUTF8Encoder.encode(content));
Utils.getWebData(mailURL, this);
}else{
Dialog.alert(errMsg);
}
} catch (IOException e) {
Logger.logErrorEvent("Error while sending client contact mail");
}
break;
The following code will send data to server.
static String responce;
static String httpURL;
httpURL=your_server_url+content; //here add your server url like- http://www.google.com/ then append the string content.
try {
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
httpURL += ";interface=wifi"+";ConnectionTimeout=30000";
}
//Dialog.alert(httpURL);
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
responce = res.trim();
//Dialog.alert(responce);
httpConn.close();
}catch (Exception e) {
Dialog.alert("Connection Time out");
}
return responce;

File created insted of Folder in Alfresco

I am trying to create a folder in Alfresco using XMSI below is the code i am using .
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
String host = "127.0.0.1";
int port = 9080;
String username = "admin";
String password = "admin";
String parentFolder = "Company%20Home";
String folderName = "sales3";
String description = "sales space3";
RulesRequest request = new RulesRequest();
//request.setRemediationProfileObj(remediationProfile);
Gson gs = new Gson();
String json = gs.toJson(request);
DefaultHttpClient client = new DefaultHttpClient();
RestClient rstClnt = new RestClient();
String ticket = rstClnt.restClientPost(json, "http://127.0.0.10:9080/alfresco/service/api/login?u=admin&pw=admin", client);
//String url = "http://" + host + ":" + port + "/alfresco/service/api/path/workspace/SpacesStore/" + parentFolder + "/children";
String url = "http://localhost:9080/alfresco/service/cmis/s/workspace:SpacesStore/i/078b05c6-14bd-439c-a1ae-db032c5d98fc/children?alf_ticket="+ticket;
String contentType = "application/atom+xml;type=entry";
String xml =
"<?xml version='1.0' encoding='utf-8'?>\n" +
"<entry xmlns='http://www.w3.org/2005/Atom' xmlns:cmis='http://www.cmis.org/2008/05'>\n" +
"<title>" + folderName + "</title>\n" +
"<summary>" + description + "</summary>\n" +
"<cmis:object>\n"+
"<cmis:properties>\n" +
"<cmis:propertyString cmis:name='cmis:objectTypeId'>\n" +
"<cmis:value>cmis:folder</cmis:value>\n" +
"</cmis:propertyString>\n" +
"</cmis:properties>\n" +
"</cmis:object>\n" +
"</entry>\n";
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", contentType);
StringEntity requestEntity = new StringEntity(xml, "UTF-8");
httppost.setEntity(requestEntity);
System.out.println("executing request" + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content type: " + entity.getContentType());
long contentLength = entity.getContentLength();
System.out.println("Response content length: "
+ entity.getContentLength());
if (contentLength > 0) {
byte [] b = new byte[(int) contentLength];
entity.getContent().read(b);
System.out.println("Response content: " + new String(b));
}
entity.writeTo(System.out);
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
long end = System.currentTimeMillis();
System.out.println("Time spend: " + (end-start) + "ms");
}
Instead of creating a folder it is creating a file of size 0.
Thanks
Garvit
Your property is of the wrong type. You are incorrectly using cmis:propertyString instead of cmis:propertyId Try the following
<cmis:propertyId propertyDefinitionId="cmis:objectTypeId">
<cmis:value>cmis:folder</cmis:value>
</cmis:propertyId>
As #Gagravarr says, problems like this are easily avoided if you can use well-known client libraries. If you are constructing the HTTP requests yourself you'd better have a good reason for that.

Sending Push SMS from an Asp.net Application

PLease let me know a method on, How I can send a Push SMS to mobile numbers from asp.net application. Thanks in Advance.
Try out this code,
protected void Page_Load(object sender, EventArgs e)
{
textboxRecipient.Width = 400;
textboxMessage.Width = 450;
textboxMessage.Rows = 10;
textboxError.Width = 400;
textboxError.Rows = 5;
textboxError.ForeColor = System.Drawing.Color.Red;
textboxError.Visible = false;
textboxError.Text = "";
if (!Page.IsPostBack)
{
textboxRecipient.Text = "+7588451632";
textboxMessage.Text = "Hello World!";
}
}
protected void buttonSendOnClick(object sender, EventArgs e)
{
//are required fields filled in:
if (textboxRecipient.Text == "")
{
textboxError.Text += "Recipient(s) field must not be empty!\n";
textboxError.Visible = true;
return;
}
//we creating the necessary URL string:
string ozSURL = "http://127.0.0.1"; //where Ozeki NG SMS Gateway is running
string ozSPort = "9501"; //port number where Ozeki NG SMS Gateway is listening
string ozUser = HttpUtility.UrlEncode("admin"); //username for successful login
string ozPassw = HttpUtility.UrlEncode("abc123"); //user's password
string ozMessageType = "SMS:TEXT"; //type of message
string ozRecipients = HttpUtility.UrlEncode(textboxRecipient.Text); //who will get the message
string ozMessageData = HttpUtility.UrlEncode(textboxMessage.Text); //body of message
string createdURL = ozSURL + ":" + ozSPort + "/httpapi" +
"?action=sendMessage" +
"&username=" + ozUser +
"&password=" + ozPassw +
"&messageType=" + ozMessageType +
"&recipient=" + ozRecipients +
"&messageData=" + ozMessageData;
try
{
//Create the request and send data to Ozeki NG SMS Gateway Server by HTTP connection
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(createdURL);
//Get response from Ozeki NG SMS Gateway Server and read the answer
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
//inform the user
textboxError.Text = responseString;
textboxError.Visible = true;
}
catch (Exception)
{
//if sending request or getting response is not successful Ozeki NG SMS Gateway Server may do not run
textboxError.Text = "Ozeki NG SMS Gateway Server is not running!";
textboxError.Visible = true;
}
}

here is the code am using... but i want to send the html part as email.

i have converted the aspx page to html and hv stored it in a var myPageHTML . here is the code am using... but i want to send the html part as email as an attachment or as the body of the mail. please help.
//this method on providing the url of the webpage copies the image of that webpage.
protected void Button1_Click(object sender, System.EventArgs e)
{
{
WebClient myClient = new WebClient();
string myPageHTML = null;
byte[] requestHTML;
// Gets the url of the page
string currentPageUrl = Request.Url.ToString();
UTF8Encoding utf8 = new UTF8Encoding();
// by setting currentPageUrl to www.yahoo.com it will fetch the source (html)
// of the yahoo.com and put it in the myPageHTML variable.
// currentPageUrl = "http://www.yahoo.com";
requestHTML = myClient.DownloadData("http://localhost:31788");
myPageHTML = utf8.GetString(requestHTML);
Response.Write();
try
{
SendMail();
}
catch (Exception) { }
}
protected void SendMail()
{
var userName = " from email";
var toAddress = YourEmail.Text.ToString();
const string Password = "password";
string subject = YourSubject.Text.ToString();
string body = "From: " + YourName.Text + "\n";
body += "Email: " + YourEmail.Text + "\n";
body += "Subject: " + YourSubject.Text + "\n";
body += "Question: \n" + Comments.Text + "\n";
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "10.238.52.880";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(userName, Password);
smtp.Timeout = 20000;
}
smtp.Send(userName, toAddress, subject, body);
}
}
I believe you should look at below links to have understanding of Mail sending.
http://csharp.net-informations.com/communications/csharp-email-attachment.htm
http://www.codeproject.com/Articles/10828/Sending-Email-with-attachment-in-ASP-NET-using-SMT
You must also check Generate HTML file at runtime and send as email attachment for generating HTML
Happy Coding !!!

How to make a STS using Gmail OAuth

We want to make an STS that outsources the authentication to google.
Following the steps stated in https://developers.google.com/accounts/docs/OAuth2Login?hl=es-ES we have the following code in the Login.aspx generated by the sts web site template in vs2010:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
//I'm coming from google, already authenticated
FormsAuthentication.SetAuthCookie(GetUserName(Request.QueryString["code"]), false);
Response.Redirect("default.aspx");
}
else
{
//I want to authenticate
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=988046895016.apps.googleusercontent.com&" +
"redirect_uri=" + HttpUtility.UrlEncode("https://localhost/GmailSTS/login.aspx") + "&" +
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email")
);
}
}
But I get an error beacuse wa is not specified in the QueryString, debugging the samples and the generated template I saw that wa,wtrealm,wctx and wct are the parameters needed so I used the state parameter so they roundtrip and get them back:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
//I'm coming from google, already authenticated
FormsAuthentication.SetAuthCookie("johannsw", false);
String lQueryStrings = HttpUtility.UrlDecode(Request.QueryString["state"]);
lQueryStrings.Replace('?', '&');
Response.Redirect("default.aspx" + "?" + lQueryStrings);
}
else
{
//I want to authenticate
String lState = String.Empty;
foreach (var key in Request.QueryString.AllKeys)
{
if (String.Equals("wa", key) ||
String.Equals("wtrealm", key) ||
String.Equals("wctx", key) ||
String.Equals("wct", key))
lState += key + "=" + Request.QueryString[key] + "&";
}
lState = lState.Remove(lState.Length - 1);
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=988046895016.apps.googleusercontent.com&" +
"redirect_uri=" + HttpUtility.UrlEncode("https://localhost/GmailSTS/login.aspx") + "&" +
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email") + "&" +
"state=" + HttpUtility.UrlEncode(lState)
);
}
}
but now I get an error saying "The HTTP verb POST used to access path '/WebSite1/' is not allowed."
Any hints?
Thanks!
Well finally I made it. Here is how I solved it just in case it helps someone else:
Login.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null && Request.QueryString["error"] != "access_denied")
{
// If I got code and no error then
// ask for access_code so I can get user email
//Here I ask for the access_code.
WebRequest requestLogIn = null;
Stream stream = null;
WebResponse response = null;
StreamReader reader = null;
string sendData = "code=" + Request.QueryString["code"] + "&";
sendData += "client_id=" + ObtenerClientID() + "&";
sendData += "client_secret=" + ObtenerClientSecret() + "&";
sendData += "redirect_uri=" + System.Configuration.ConfigurationManager.AppSettings["urlLogin"] + "&"; //TODO: ver si es necesario
sendData += "grant_type=authorization_code";
requestLogIn = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
requestLogIn.Method = "POST";
requestLogIn.ContentType = "application/x-www-form-urlencoded";
byte[] arrayToSend = Encoding.UTF8.GetBytes(sendData);
requestLogIn.ContentLength = arrayToSend.Length;
stream = requestLogIn.GetRequestStream();
stream.Write(arrayToSend, 0, arrayToSend.Length);
stream.Close();
response = requestLogIn.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
reader = new StreamReader(stream);
string responseValue = reader.ReadToEnd();
reader.Close();
var lJSONResponse = new JavaScriptSerializer().Deserialize<JSONResponseToken>(responseValue);
//Now that I have the access_code ask for the user email so I can match him in my base and load claims.
WebRequest myRequest = WebRequest.Create("https://www.googleapis.com/oauth2/v2/userinfo");
myRequest.Method = "GET";
myRequest.Headers.Add("Authorization", "Bearer " + lJSONResponse.Access_Token);
response = myRequest.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
reader = new StreamReader(stream);
responseValue = reader.ReadToEnd();
var lUserMail = new JavaScriptSerializer().Deserialize<JSONResponseUserMail>(responseValue);
// User is authenticated
FormsAuthentication.SetAuthCookie(lUserMail.Email, false);
// default.aspx will load claims
Response.Redirect("default.aspx?" + Request.QueryString.ToString());
}
}
}
else
{
//redirect to google for login.
//Save original url in a cookie for later use.
Guid lGuid = Guid.NewGuid();
CreateContextCookie(lGuid.ToString(), this.Request.Url.AbsoluteUri);
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=" + ObtenerClientID() + "&" +
//I want to return here again
"redirect_uri=" + HttpUtility.UrlEncode(System.Configuration.ConfigurationManager.AppSettings["urlLogin"]) + "&" +
//Add scope so I can get user mail.
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email") + "&" +
//Reference to the cookie so I can get the original url again
"state=" + HttpUtility.UrlEncode(lGuid.ToString())
);
}
}
Default.aspx.cs:
protected void Page_PreRender(object sender, EventArgs e)
{
String lCode = Request.QueryString["code"];
String lSTate = Request.QueryString["state"];
var ctxCookie = this.Request.Cookies[lSTate];
var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(ctxCookie.Value));
//Erase cookie
var contextCookie = new HttpCookie(lSTate)
{
Expires = DateTime.UtcNow.AddDays(-1)
};
//process login request
SecurityTokenService sts =
new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
SignInResponseMessage responseMessage =
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response);
this.Response.Cookies.Add(contextCookie);
}

Resources