"TargetInvocationException" in windows phone 8 sdk - c#

An exception of type System.Reflection.TargetInvocationException
occurred in System.ni.dll but was not handled in user code.
var client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
XDocument doc = XDocument.Load(e.Result);
};
client.DownloadStringAsync(new Uri("http://mylocation.com/myfile.php?userid=xyz"));

Maybe you could add a bit of error checking to narrow things down a bit
WebClient client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
if (e.Error != null && !string.IsNullOrEmpty(e.Result))
{
XDocument doc = XDocument.Load(e.Result);
}
};
client.DownloadStringAsync(new Uri("http://mylocation.com/myfile.php?userid=xyz"));

Maybe the data passed between app and Service exceed certain size. For example, when you pass a string larger than 8K chars back to Service, you will get a 404 error. need to change the default configuration to handle large data.

Mostly e.Result or one of its children is null and hence this exception is being thrown.
Go to Tools -> Options -> Debugging and select Enable Just My Code in Visual Studio. That should help you figure out what the problem is.

Related

Create self signed certificate to use in console application for development [duplicate]

Using Visual Studio 2005 - C# 2.0, System.Net.WebClient.UploadData(Uri address, byte[] data) Windows Server 2003
So here's a stripped down version of the code:
static string SO_method(String fullRequestString)
{
string theUriStringToUse = #"https://10.10.10.10:443"; // populated with real endpoint IP:port
string proxyAddressAndPort = #"http://10.10.10.10:80/"; // populated with a real proxy IP:port
Byte[] utf8EncodedResponse; // for the return data in utf8
string responseString; // for the return data in utf16
WebClient myWebClient = new WebClient(); // instantiate a web client
WebProxy proxyObject = new WebProxy(proxyAddressAndPort, true);// instantiate & popuylate a web proxy
myWebClient.Proxy = proxyObject; // add the proxy to the client
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); // stick some stuff in the header
UTF8Encoding utf8Encoding = new UTF8Encoding(false);// create a utf8 encoding
Byte[] utf8EncodedRequest = HttpUtility.UrlEncodeToBytes(fullRequestString, utf8Encoding); // convert the request data to a utf8 byte array
try
{
utf8EncodedResponse = myWebClient.UploadData(theUriStringToUse, "POST", utf8EncodedRequest); // pass the utf8-encoded byte array
responseString = utf8Encoding.GetString(utf8EncodedResponse); // get a useable string out of the response
}
catch (Exception e)
{
// some other error handling
responseString = "<CommError><![CDATA[" + e.ToString() + "]]></CommError>";// show the basics of the problem
}
return responseString;// return whatever ya got
}
This is the error I get:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
I don't have much control to see what's happening when the request goes out. I'm told that it's reaching the correct destination and there's a "certificate error". This is supposedly because there's a literal mismatch between the IP address in my request and the URL it resolves to. I have more than one IP I'm supposed to round-robin to so specifying the URL won't work. I'm not attaching a certificate - nor am I supposed to according to the endpoint owners. Per "them" the certificate error is 'normal and I am supposed to ignore it.
The cert in question is supposedly one of the many verisign certs that is "just there" on our server. The examples I've seen for ignoring cert errors all seem to imply that the requestor is attaching a specific x509 certificate (which I'm not).
I looked over .net WebService, bypass ssl validation! which kinda-sorta describes my problem - except it also kinda-sorta doesn't because I don't know which certificate (if any) I should reference.
Is there a way for me to ignore the error without actually knowing/caring what certificate is causing the problem?
and please - kid gloves, small words, and "for dummies" code as I'm not exactly a heavy hitter.
This traffic is over a private line - so my understanding is that ignoring the cert error is not as big a deal as if it were open internet traffic.
The SSL certificate is for a machine to establish a trust relationship. If you type in one IP address, and end up talking to another, that sounds the same as a DNS hijack security fault, the kind of thing SSL is intending to help you avoid - and perhaps something you don't want to put up with from "them".
If you may end up talking to more than machine (ideally they would make it appear as one for you), you will need a certificate for each of the possible machines to initiate trust.
To ignore trust (I've only ever had to do this temporarily in development scenarios) the following snippet may work for you, but I strongly recommend you consider the impact of ignoring trust before using it:
public static void InitiateSSLTrust()
{
try
{
//Change SSL checks so that all checks pass
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate
{ return true; }
);
}
catch (Exception ex)
{
ActivityLog.InsertSyncActivity(ex);
}
}
I realize this is an old post, but I just wanted to show that there is a more short-hand way of doing this (with .NET 3.5+ and later).
Maybe it's just my OCD, but I wanted to minimize this code as much as possible. This seems to be the shortest way to do it, but I've also listed some longer equivalents below:
// 79 Characters (72 without spaces)
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
Shortest way in .NET 2.0 (which is what the question was specifically asking about)
// 84 Characters
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
It's unfortunate that the lambda way requires you to define the parameters, otherwise it could be even shorter.
And in case you need a much longer way, here are some additional alternatives:
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) => true;
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
// 255 characters - lots of code!
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
});
This is somewhat the code we're using (not polished yet - I don't think I have the error-handling setup correctly but it should be close) based on thomas's suggestion (this is .NET 4.0 code, though):
var sslFailureCallback = new RemoteCertificateValidationCallback(delegate { return true; });
try
{
if (ignoreSslErrors)
{
ServicePointManager.ServerCertificateValidationCallback += sslFailureCallback;
}
response = webClient.UploadData(Options.Address, "POST", Encoding.ASCII.GetBytes(Options.PostData));
}
catch (Exception err)
{
PageSource = "POST Failed:\r\n\r\n" + err;
return PageSource;
}
finally
{
if (ignoreSslErrors)
{
ServicePointManager.ServerCertificateValidationCallback -= sslFailureCallback;
}
}
This code is much broader than you might expect. It is process-wide. The process might be the exe, IIS on this machine, or even DLLHost.exe. After calling it, have a finally block that restores things to normal by removing the delegate that always returns true.
I wanted to disable SSL verification for a specific domain without globally deactivating it because there might be other requests running which should not be affected, so I came up with this solution (please note that uri is a variable inside a class:
private byte[] UploadValues(string method, NameValueCollection data)
{
var client = new WebClient();
try
{
ServicePointManager.ServerCertificateValidationCallback +=
ServerCertificateValidation;
returnrclient.UploadValues(uri, method, parameters);
}
finally
{
ServicePointManager.ServerCertificateValidationCallback -=
ServerCertificateValidation;
}
}
private bool ServerCertificateValidation(object sender,
X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
var request = sender as HttpWebRequest;
if (request != null && request.Address.Host.Equals(
this.uri.Host, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
Here is the VB.net code to make WebClient ignore the SSL cert.
Net.ServicePointManager.ServerCertificateValidationCallback = New Net.Security.RemoteCertificateValidationCallback(Function() True)

How can I use Bugsense to catch exceptions in specific code?

Ive added BugSense to my Windows Phone app and modified the app.xaml.cs accordingly. However, I know some users are experiencing crashes but BugSense is not seeing it. BugSense to see new sessions and what not so i know the license is correct.
I believe the crashing occurs within this code, particularly with webclient I think. What do can I add to this code so that if something occurs, BugSense will report it?
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector selector = sender as LongListSelector;
// verifying our sender is actually a LongListSelector
if (selector == null)
return;
SoundData data = selector.SelectedItem as SoundData;
// verifying our sender is actually SoundData
if (data == null)
return;
if (data.IsDownloaded)
{
this.PlaySound(IsolatedStorageFile.GetUserStoreForApplication().OpenFile(data.SavePath, FileMode.Open, FileAccess.Read, FileShare.Read));
}
else
{
if (!SimpleIoc.Default.GetInstance<INetworkService>().IsConnectionAvailable)
{
MessageBox.Show("You need an internet connection to download this sound.");
}
else
{
WebClient client = new WebClient();
client.DownloadProgressChanged += (senderClient, args) =>
{
Dispatcher.BeginInvoke(() =>
{
data.DownloadProgress = args.ProgressPercentage;
});
};
client.OpenReadCompleted += (senderClient, args) =>
{
using (IsolatedStorageFileStream fileStream = IsolatedStorageFile.GetUserStoreForApplication().CreateFile(data.SavePath))
{
args.Result.Seek(0, SeekOrigin.Begin);
args.Result.CopyTo(fileStream);
this.PlaySound(fileStream);
data.Status = DownloadStatus.Downloaded;
}
args.Result.Close();
};
client.OpenReadAsync(new Uri(data.FilePath));
data.Status = DownloadStatus.Downloading;
}
}
selector.SelectedItem = null;
}
I've just started using BugSense myself in my WP8 app and I've very impressed how it catches unhandled exceptions without anything more than the single line of code in my App.xaml.cs file:
public App()
{
BugSenseHandler.Instance.InitAndStartSession(new ExceptionManager(Current), RootFrame, "YourBugSenseApiKey");
...
}
So from my experience BugSense should be catching these exceptions for you without any extra code on your part.
How do you know about these crashes? Is it from the Windows Phone Dev Center? If so then you might still be seeing crashes reported from users that have an older version of your app installed before you added BugSense.
I find that checking for a new app version from within the app itself on start-up and alerting the user is a great was to keep people up-to-date. Many users might not visit the Windows Phone Store for extended periods of time and even then may not bother to update your app to the latest version so there's a good chance you have a lot of users on old versions.

Downloading JSON through WebClient

I'm trying to download a JSON from Twitter with all the authorization and stuff.
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (b, a) => {
if (a.Cancelled)
MessageBox.Show("Download Canceled!");
else if (a.Error != null)
MessageBox.Show("Download Error!");
else
string g = a.Result;
};
wc.DownloadStringAsync(new Uri("TWITTER_JSON"));
(TWITTER_JSON is a long address with many authorization headers that gives the JSON)
When I run this the 2nd message ("Download Error!") shows up. Why? And how do I fix this?
a.Error is actually an Exception object. Have you tried examining it to see what the exception details contain?
MessageBox.Show( a.Error.ToString() );
That will give you more information about what actually went wrong.
You may also find it helpful to read Eric Lippert's recent blog post on how to debug your code.

An exception occurred during a WebClient request. in windows phone

Here I am put my code which is "An exception occurred during a WebClient request" i put breakpoint and check .it will so this error .for developing i am using visual studio 2012 ultimate with windows phone sdk8.0 and if request is done successful than my response is in json string .that will show in messagebox .now it show me "System.Net.Webexception:An exception occurred during a WebClient request."
public match()
{
InitializeComponent();
Loaded += new RoutedEventHandler(profile1_loaded);
}
void profile1_loaded(object sender, RoutedEventArgs e)
{
WebClient wc2 = new WebClient();
var URI = new Uri("http://192.168.1.17/eyematch/rest1-7-2/api/match");
wc2.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc2.UploadStringCompleted +=
new UploadStringCompletedEventHandler(wc2_UploadStringCompleted);
wc2.UploadStringAsync(
URI, "GET", "action=getMatchNotificationData&sKey=" +
GlobalVariables.skey + "&uKey=" + GlobalVariables.ukey);
}
private void wc2_UploadStringCompleted(object sender, UploadStringCompletedEventArgs er)
{
try
{
MessageBox.Show(er.Result);
}
catch (Exception eu)
{
MessageBox.Show(eu.ToString());
}
}
thank you in advance....
Are you testing this in the emulator or on a physical device? Chances are the address is inaccessible given your network configuration (especially since it is a local network IP).
A helpful hint to other people running into this error message: the exception has a .InnerException, so if you change the code above to also output "eu.InnerException", you can get more info.

multiple file download using SkyDrive API

I have the following code where I'm trying to download 3 different files from the users SkyDrive Account.
I'm using the SkyDrive API for Windows Phone development.
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompletedVI);
client.DownloadAsync(fileIdVehicleItems);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompletedHI);
client.DownloadAsync(fileIdHistoryItems);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompletedRI);
client.DownloadAsync(fileIdRepairItems);
When I run this, the only method that gets called is the OnDownloadCompletedVI. All the files that are being downloaded are running through this method which is causing an error.
What am I doing incorrectly?
Update
I have the following method, but I have 2 other similar methods that do the exact same thing except it loads different objects (based off of the downloaded files).
The error I'm currently receiving:
An exception of type 'System.ArgumentException' occurred in
mscorlib.ni.dll but was not handled in user code
void OnDownloadCompletedVI(object sender, LiveDownloadCompletedEventArgs e)
{
if (e.Result != null)
{
using (var stream_vi = e.Result)
{
StreamReader SRVI = new StreamReader(stream_vi);
string contentVI = "";
contentVI = SRVI.ReadToEnd();
StringReader rdr_vi = new StringReader(contentVI);
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<vehicle>));
ObservableCollection<vehicle> importedVehicles = new ObservableCollection<vehicle>();
importedVehicles = (ObservableCollection<vehicle>)serializer.Deserialize(rdr_vi);
StorageHelper.Save<ObservableCollection<vehicle>>(App.vehicleData, importedVehicles);
}
//e.Result.Close();
}
else
{
infoTextBlock.Text = "Error downloading file: " + e.Error.ToString();
}
}
Actually all three methods should be called. Of course, if the first method is called and throws an exception the other two won't trigger.
What you can do is either create a new client for each call, or download them in order, so when the OnDownloadCompletedVI method is complete, remove the event handler for OnDownloadCompletedVI and add the one for OnDownloadCompletedHI and then trigger the client.DownloadAsync(fileIdHistoryItems); at the end of the method.

Categories

Resources