I have a simple webclient that connects to a webpage and returns the data. The code is as follows:
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("https://domain.com/register.php?username=" + txtbUser.Text);
webClient.OpenReadCompleted +=
new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
//Process web service result here
MessageBox.Show(e.Result.ToString());
}
else
{
//Process web service failure here
MessageBox.Show(e.Error.Message);
}
}
The data coming from e.Result is MS.InternalMemoryStream and not the data coming back from the webpage, the data coming back from the webpage should just be a 0 or 1. Any idea's?
thanks,
Nathan
.ToString() returns the name of the class - in this case, InternalMemoryStream. You have to READ the stream to get the result. Check this out
Related
I have an issue where I keep getting an error
No provider registered for 'svn.ssl.server' credentials
I am using the same code that works on another SVN server, but a new server I setup can't seem to connect even though I can connect no problem through a web browser.
//SVN Client repo sync
public void DownloadSVNStartup(string url, string path)
{
using (SvnClient client = new SvnClient())
{
try
{
client.CleanUp(path); //will go to catch block since there's no working copy yet I
//want to checkout for the first time then next time this part
//will work.
SvnUI.Bind(client, this);
SvnCheckOutArgs sco = new SvnCheckOutArgs();
sco.AllowObstructions = false;
}
catch (Exception ex)
{
MessageBox.Show("Line 88");
MessageBox.Show(ex.ToString());
myLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
client.Configuration.SetOption("servers", "global", "http-auth-types", "basic;digest");
client.Authentication.Clear();
client.Authentication.ForceCredentials("user", "password");
try
{
client.Authentication.SslServerTrustHandlers += delegate (object sender,
SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = false; // Save acceptance to authentication store
};
Object[] args = { url, path };
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += backgroundWorker1_DoWork;
worker.RunWorkerAsync(args);
this.Hide();
}
catch (Exception ex)
{
MessageBox.Show("Line126");
MessageBox.Show(ex.ToString());
myLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //connect to the Svn
//server
{
try
{
Object[] arg = e.Argument as Object[];
string url = (string)arg[0];
string path = (string)arg[1];
using (SvnClient client = new SvnClient())
{
client.Authentication.Clear(); // Prevents saving/loading config to/from disk
client.Authentication.ForceCredentials("user", "password");
client.CheckOut(new Uri(url), path); //fails here with the error No provider registered for 'svn.ssl.server' credentials
client.CleanUp(path);
client.Update(path);
client.CleanUp(path);
}
}
catch (Exception ex)
{
MessageBox.Show("Line166", ex.Message.ToString());
MessageBox.Show(ex.ToString());
}
}
I have searched for hours for solutions and can't find anything.
Both servers are setup with same port, same HTTPS settings and created certificates, same VisualSVN server editions.
I have tried only the one solution that I could find as this is not a common issue at all.
This is supposed to fix that error but it doesn't.
client.Authentication.SslServerTrustHandlers += delegate (object sender, SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = false; // Save acceptance to authentication store
};
I fixed it with adding an event handler for the certificate
private void SslClientCertificateHandlers(object sender, SvnSslClientCertificateEventArgs e)
{
e.Save = true;
e.CertificateFile = #"where you want to save certs";
}
I used WebClient to download a file in my apk. But I got this error:
Unhandled Exception:
System.Net.WebException: An exception occurred during a WebClient request.
And this is the code that I tried:
{
using (WebClient client = new WebClient())
{
client.DownloadFile(
"https://code.org/images/social-media/code-2018-creativity.png",
#"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
}
Since you are only referring to a WebException, it may have to do with one of these cases:
The URI formed by combining BaseAddress and address is invalid.
The file or destination folder does not exist. Make sure your path to
the destination folder already exists and that you have permissions to access it.
An error occurred while
downloading data.
If you provide us more information about the exception we may be able to reduce the error to one of these cases. To get the InnerException you can do something like this:
{
using (WebClient client = new WebClient ())
{
try
{
client.DownloadFile (
"https://code.org/images/social-media/code-2018-creativity.png",
#"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
catch (Exception ex)
{
while (ex != null)
{
Console.WriteLine (ex.Message);
ex = ex.InnerException;
}
}
}
}
You have to ask permissions on run time even you have mentioned them in your manifest file if you are running Android api level 23 or greater.
Have a look at this blog would help about how to ask a run time permission:requesting-runtime-permissions-in-android
Also, this is the official sample of how to check RuntimePermissions
Refer: xamarin-system-unauthorizedaccessexception-access-to-the-path-is-denied
Update:
To ask run time permissions, you can use this plugin:Plugin.Permissions, install it to your project.
And then, call CheckMyPermissionAsync(); before you download the file:
private void FabOnClick(object sender, EventArgs eventArgs)
{
View view = (View) sender;
CheckMyPermissionAsync();
}
In the method CheckMyPermissionAsync(), check your Storage permission and then download file:
public async void CheckMyPermissionAsync()
{
var permissionsStartList = new List<Permission>()
{
Permission.Storage
};
var permissionsNeededList = new List<Permission>();
try
{
foreach (var permission in permissionsStartList)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status != PermissionStatus.Granted)
{
permissionsNeededList.Add(permission);
}
}
}
catch (Exception ex)
{
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
//Check the persimmison again
var storeagePermission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (storeagePermission == PermissionStatus.Granted)
{
//Download file here
DownloadFile("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg", "XF_Downloads");
}
else {
Console.WriteLine("No permissions");
}
}
You can check the result in the completed event:
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("success");
}
else
{
if (OnFileDownloaded != null) { }
Console.WriteLine("fail");
}
}
Note: pay attention to your filePath,make sure your path is correct, I use:
string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);
I updated my sample here: runtime-permission-xamarin.android
After searching in the Net for about 4 hours I still don't understand Async functions on Windows Phone 7. I tried to run that code but it looks like the event "DownloadStringCompleted" for my webClient is never raised. I tried to wait here for an answer, but it just freeze my app. Anyone could help and explain why it don't work?
internal string HTTPGet()
{
string data = null;
bool exit = false;
WebClient webClient = new WebClient();
webClient.UseDefaultCredentials = true;
webClient.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
data = e.Result;
exit = true;
}
};
webClient.DownloadStringAsync(new Uri(site, UriKind.Absolute));
//while (!exit)
// Thread.Sleep(1000);
return data;
}
Ok. Found something!
http://blogs.msdn.com/b/kevinash/archive/2012/02/21/async-ctp-task-based-asynchronous-programming-for-windows-phone.aspx
Yay! :)
Its not a problem with emulator. you want to return the data from your HttpGet() method, but the data is already returned (as null) before the actual response from the webClient occurs. hence I suggest you to make some changes to the code and try.
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(site, UriKind.Absolute));
and then in the DownloadCompleted event handler(or callback), you manupulate the actual result
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var response= e.Result; // Response obtained from the site
}
I'm trying to read from a Uri which i created and to display it on windows phone 7 app.
(I'm doing this tutorial:http://msdn.microsoft.com/en-us/windowsmobile/Video/hh237494).
My problem is that the program doesnt get into the OpenReadCompletedEventHandler and i dont know why. (i putted message box in order to debug and i found out that the program doesnt get into the OpenReadCompletedEventHandler). Here is the relevant code:
void myButton_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://localhost:44705/Service1.svc/GetAllBrands");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenWriteAsync(uri);
MessageBox.Show("opening sucsseded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
MessageBox.Show("OpenRead Handler");
// OpenWriteCompletedEventArgs temp = (OpenWriteCompletedEventArgs)e;
DataContractJsonSerializer serializer = null;
try
{
serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Brand>));
ObservableCollection<Brand> Brands = serializer.ReadObject(e.Result) as ObservableCollection<Brand>;
foreach (Brand b in Brands)
{
int id = b.BrandId;
string name = b.BrandName;
listBrands.Items.Add(id + " " + name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance!
I have never used this but a quick google takes me to this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openreadcompleted.aspx
This should tell you why it's not working - because you are using a read event for a write operation. You should be using OpenWriteCompletedEventHandler with OpenWriteAsync as per this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openwritecompleted.aspx
I'm having problems creating a linkchecker, I'd like to have it online mainly for learning..
The problem is that i first had it as a console application which worked kinda well (i got broken urls to show i debug console), now that i'm trying to get it to web I'm having trouble..
How do I go about getting this into the document? I'm kinda stumped at the moment..
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public bool UrlIsValid(string url)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load
request.Method = "HEAD"; //Get only the header information -- no need to download any content
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
int statusCode = (int)response.StatusCode;
if (statusCode >= 100 && statusCode < 400) //Good requests
{
return true;
}
else if (statusCode >= 500 && statusCode <= 510) //Server Errors
{
string cl = (String.Format("The remote server has thrown an internal error. Url is not valid: {0}", url));
// Debug.WriteLine(cl, Convert.ToString(url));
return false;
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError) //400 errors
{
return false;
}
else
{
string cl = String.Format("Unhandled status [{0}] returned for url: {1}", ex.Status, url);
/// Debug.WriteLine(cl, Convert.ToString(ex));
}
}
catch (Exception ex)
{
object cl = String.Format("Could not test url {0}.", url);
Debug.WriteLine(cl, Convert.ToString(ex));
}
return false;
}
private void button1_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
string checker = wc.DownloadString("http://administration.utbildningssidan.se/linkcheck.aspx");
while (checker.Contains("<a href="))
{
int checkstart = checker.IndexOf("<a href=") + 8;
int checkstop = checker.IndexOf(">", checkstart);
string validator = checker.Substring(checkstart, checkstop - checkstart);
// perform the check
if (!UrlIsValid(validator)) { Debug.WriteLine(validator); }
checker = checker.Substring(checkstop + 1);
}
}
}
Hope you understand what I want accomplished, having a hard time making sense right now..
I think you want Response.Write() in place of your Debug.WriteLine() methods. OR, you could create a TextArea object in your markup and use myTextArea.Text += "Some text";