I'm developing a project for windows phone 7. It's very simple I guess but I don't know very well C# especially C# for wp7.
I have an existing php page with this code
<?php
if(isset($_GET['name'])) {
$ssid=$_GET['name'];
}
$name .= "Hello";
?>
I want to make a wp7 application where I can write a name in text, press the button to connect to server, pass the name in the text as php parameter and write server response in another text on mobile screen. How can I do this?
Something like this perhaps?
POST Request
Try this (read the first comment tho... author made a typo):
Post Request
Create an HttpWebRequest with your query :
private void MyMethod(Action action){
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://website/page.php?name={0}",name));
webRequest.BeginGetResponse((callBack)=>{
HttpWebRequest request = (HttpWebRequest)callBack.AsyncState;
WebResponse webResponse = request.EndGetResponse(callBack);
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
{
string response = string.Empty;
try
{
response = sr.ReadToEnd();
}
catch (Exception ex)
{
response = ex.Message;
}
action.Invoke(response);
}
webResponse.Close();
},webRequest)
}
where textresponse is your server response
Try this one, it helps you
in first page or form,
NavigationService.Navigate(new Uri("/Projectname;component/pagename.xaml?name=" + variable1 + "&country="+variable2, UriKind.Relative));
in second page or form,
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string myname = NavigationContext.QueryString["name"];
string Mycountry = int.Parse(NavigationContext.QueryString["country"]);
}
The 'name' and 'country' in OnNavigatedTo are same as navigateservice
In this way you send values from one page to another page.
Related
Sorry if my question was not in proper manner do edit if required.
USE CASE
I want a function which will find the given string or text from a web page as soon as it updated in wepage in c#.
Take example as https://www.worldometers.info/world-population/ i am trying to get "40" data.So,when the current page will load "40" data or content my function should stop.I think its not loading the AJAX calls.
public static void WaitForWebPageContent(string url,string text)
{
while (true)
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
if(pageContent.Contains(text))
{
Debug.WriteLine("Found it");
break;
}
}
}
My Question
I am searching for a method where i can get the page content by calling it from my function.Currently i am using httpclient to get the response from a URL but the data its not stopping even the content is loaded in browser.I am continously sending the request in each and every second by using the above code.Please guide me to proper solution
Thanks
I wish to call the get function from a button click on my web application
my code in my application is
protected void btngetbtanches_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest req = WebRequest.Create(#"http://localhost:54691/") as HttpWebRequest;
WebResponse resp = req.GetResponse();
using (Stream branchstream = resp.GetResponseStream())
{
StreamReader loResponseStream =
new StreamReader(branchstream, Encoding.UTF8);
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
resp.Close();
}
}
catch (Exception ex)
{
}
}
in my service is
[ServiceContract]
public interface IRestSerivce
{
[OperationContract]
[WebGet(UriTemplate = "Default")]
string GetBranchData();
}
}
}
get data is defined in another file in the service project. When I try to click the button some html is returned and the service is not called.
Any help would be appreciated
Your web request does not match the end point of the service:
You should try:
HttpWebRequest req = WebRequest.Create
(#"http://localhost:54691/RestSerivce/GetBranchData") as HttpWebRequest;
or at least the one which matches your routing.
You can also add the service as reference and consume it's type, which is a common approache.
You can check this answer for more details.
How to consume WCF web service through URL at run time?
I'm trying to write an android application with a simple form. The user will send a string to a server and will get an SMS back with the same string + "thank you!".
I know Java but I'm more fluent in C#. I did manage to send the string to the web-service.
On Android Client:
public void sendFeedback(View button) {
final EditText nameField = (EditText) findViewById(R.id.EditTextName);
String name = nameField.getText().toString();
postData(name);
}
public void postData(String name) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:53811/WinnerSite/WebService.asmx?op=WriteToDB");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", name));
// nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getFirstHeader(getPackageName()));
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Web-Service is pretty slim:
[WebMethod]
public string WriteToDB(string json)
{
return "Hello World "+ json;
}
I ran the web-service with Visual-Studio built in server service.
The code behind the application got the string properly, but the code never recieved the string. Does someone has an idea what could be the problem?
the next phase, I cannot find the SMS email gate to SMS from my web-service SMS to one of the following Israeli operators:
Orange (a.k.a Partner)
Cellcom
Can someone help me find that gate?
try to use
JSONObject json = new JSONObject();
json.but("name",name)
and in the server send a message by using
json_encode("name than you ");
that may help you
I need to write a simple C# app that should receive entire contents of a web page currently opened in Firefox. Is there any way to do it directly from C#? If not, is it possible to develop some kind of plug-in that would transfer page contents? As I am a total newbie in Firefox plug-ins programming, I'd really appreciate any info on getting me started quickly. Maybe there are some sources I can use as a reference? Doc links? Recommendations?
UPD: I actually need to communicate with a Firefox instance, not get contents of a web page from a given URL
It would help if you elaborate What you are trying to achieve. May be plugins already out there such as firebug can help.
Anways, if you really want to develop both plugin and C# application:
Check out this tutorial on firefox extension:
http://robertnyman.com/2009/01/24/how-to-develop-a-firefox-extension/
Otherwise, You can use WebRequest or HttpWebRequest class in .NET request to get the HTML source of any URL.
I think you'd almost certainly need to write a Firefox plugin for that. However there are certainly ways to request a webpage, and receive its HTML response within C#. It depends on what your requirements are?
If you're requirements are simply receive the source from any website, leave a comment and I'll point you towards the code.
Uri uri = new Uri(url);
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri.AbsoluteUri);
req.AllowAutoRedirect = true;
req.MaximumAutomaticRedirections = 3;
//req.UserAgent = _UserAgent; //"Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Searcharoo.NET)";
req.KeepAlive = true;
req.Timeout = _RequestTimeout * 1000; //prefRequestTimeout
// SIMONJONES http://codeproject.com/aspnet/spideroo.asp?msg=1421158#xx1421158xx
req.CookieContainer = new System.Net.CookieContainer();
req.CookieContainer.Add(_CookieContainer.GetCookies(uri));
System.Net.HttpWebResponse webresponse = null;
try
{
webresponse = (System.Net.HttpWebResponse)req.GetResponse();
}
catch (Exception ex)
{
webresponse = null;
Console.Write("request for url failed: {0} {1}", url, ex.Message);
}
if (webresponse != null)
{
webresponse.Cookies = req.CookieContainer.GetCookies(req.RequestUri);
// handle cookies (need to do this incase we have any session cookies)
foreach (System.Net.Cookie retCookie in webresponse.Cookies)
{
bool cookieFound = false;
foreach (System.Net.Cookie oldCookie in _CookieContainer.GetCookies(uri))
{
if (retCookie.Name.Equals(oldCookie.Name))
{
oldCookie.Value = retCookie.Value;
cookieFound = true;
}
}
if (!cookieFound)
{
_CookieContainer.Add(retCookie);
}
}
string enc = "utf-8"; // default
if (webresponse.ContentEncoding != String.Empty)
{
// Use the HttpHeader Content-Type in preference to the one set in META
doc.Encoding = webresponse.ContentEncoding;
}
else if (doc.Encoding == String.Empty)
{
doc.Encoding = enc; // default
}
//http://www.c-sharpcorner.com/Code/2003/Dec/ReadingWebPageSources.asp
System.IO.StreamReader stream = new System.IO.StreamReader
(webresponse.GetResponseStream(), System.Text.Encoding.GetEncoding(doc.Encoding));
webresponse.Close();
This does what you want.
using System.Net;
var cli = new WebClient();
string data = cli.DownloadString("http://www.heise.de");
Console.WriteLine(data);
Native messaging enables an extension to exchange messages with a native application installed on the user's computer.
Although i can grasp the concepts of the .Net framework and windows apps, i want to create an app that will involve me simulating website clicks and getting data/response times from that page. I have not had any experience with web yet as im only a junior, could someone explain to me (in english!!) the basic concepts or with examples, the different ways and classes that could help me communicate with a website?
what do you want to do?
send a request and grab the response in a String so you can process?
HttpWebRequest and HttpWebResponse will work
if you need to connect through TCP/IP, FTP or other than HTTP then you need to use a more generic method
WebRequest and WebResponse
All the 4 methods above are in System.Net Namespace
If you want to build a Service in the web side that you can consume, then today and in .NET please choose and work with WCF (RESTfull style).
hope it helps you finding your way :)
as an example using the HttpWebRequest and HttpWebResponse, maybe some code will help you understand better.
case: send a response to a URL and get the response, it's like clicking in the URL and grab all the HTML code that will be there after the click:
private void btnSendRequest_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
String queryString = "user=myUser&pwd=myPassword&tel=+123456798&msg=My message";
byte[] requestByte = Encoding.Default.GetBytes(queryString);
// build our request
WebRequest webRequest = WebRequest.Create("http://www.sendFreeSMS.com/");
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.ContentLength = requestByte.Length;
// create our stram to send
Stream webDataStream = webRequest.GetRequestStream();
webDataStream.Write(requestByte, 0, requestByte.Length);
// get the response from our stream
WebResponse webResponse = webRequest.GetResponse();
webDataStream = webResponse.GetResponseStream();
// convert the result into a String
StreamReader webResponseSReader = new StreamReader(webDataStream);
String responseFromServer = webResponseSReader.ReadToEnd().Replace("\n", "").Replace("\t", "");
// close everything
webResponseSReader.Close();
webResponse.Close();
webDataStream.Close();
// You now have the HTML in the responseFromServer variable, use it :)
textBox1.Text = responseFromServer;
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
}
The code does not work cause the URL is fictitious, but you get the idea. :)
You could use the System.Net.WebClient class of the .NET Framework. See the MSDN documentation here.
Simple example:
using System;
using System.Net;
using System.IO;
public class Test
{
public static void Main (string[] args)
{
if (args == null || args.Length == 0)
{
throw new ApplicationException ("Specify the URI of the resource to retrieve.");
}
WebClient client = new WebClient ();
// Add a user agent header in case the
// requested URI contains a query.
client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream data = client.OpenRead (args[0]);
StreamReader reader = new StreamReader (data);
string s = reader.ReadToEnd ();
Console.WriteLine (s);
data.Close ();
reader.Close ();
}
}
There are other useful methods of the WebClient, which allow developers to download and save resources from a specified URI.
The DownloadFile() method for example will download and save a resource to a local file. The UploadFile() method uploads and saves a resource to a specified URI.
UPDATE:
WebClient is simpler to use than WebRequest. Normally you could stick to using just WebClient unless you need to manipulate requests/responses in an advanced way. See this article where both are used: http://odetocode.com/Articles/162.aspx