How to handle the AmazonServiceException thrown when disconnected with network - exception

I'm using AWS mobile SDK for Xamarin (http://aws.amazon.com/about-aws/whats-new/2014/10/09/aws-mobile-sdk-for-xamarin-available-on-awslabs/) and i got a problem when i use GetObjectAsync() method to get files from my S3 Bucket. My code:
private async Task<string> GetObjectFromAmazonS3(S3Object s3Object, string fileContent, string bucketName)
{
AWSCredentials credential = new BasicAWSCredentials(Constants.S3AccessKey, Constants.S3SecretKey);
_amazonS3Client = new AmazonS3Client(credential, Amazon.RegionEndpoint.EUCentral1);
_amazonS3Client.ExceptionEvent += ClientExceptionHandler;
GetObjectRequest getObjectRequest = new GetObjectRequest
{
BucketName = bucketName,
Key = s3Object.Key
};
GetObjectResponse getObjectResponse = await _amazonS3Client.GetObjectAsync(getObjectRequest);
using (Stream responseStream = getObjectResponse.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
fileContent = reader.ReadToEnd();
}
Logger.Log(Logger.Category.Debugging, "Download S3 Objects to the phone", "Get object " + s3Object.Key + " successfully");
return fileContent;
}
The problem is that when the application waiting for the response from GetObjectAsync() method, the phone is disconnected with the network then i got an exception:
2015-03-03T07:23:27.582Z,Debugging,UnhandledException(Android),Amazon.Runtime.AmazonServiceException: A WebException with status NameResolutionFailure was thrown.
---> System.Net.WebException: Error: NameResolutionFailure
==> at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0
==> at System.Threading.Tasks.TaskFactory`1[System.Net.WebResponse].InnerInvoke (System.Threading.Tasks.TaskCompletionSource`1 tcs, System.Func`2 endMethod, IAsyncResult l) [0x00000] in <filename unknown>:0
==> --- End of stack trace from previous location where exception was thrown ---
==> at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 ==> at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[System.Net.WebResponse].GetResult () [0x00000] in <filename unknown>:0
And my application is crashed. I tried to handle the application by using ExceptionEvent but i still cannot catch this exception.
Is there any suggestion to solve this problem? (It's very terrible that the application crashes each time the wifi disconnected).

Related

Exception in thread "main" io.restassured.path.json.exception.JsonPathException: Failed to parse the JSON document while trying to "automate an API "

I am getting the following exception while trying to Automate an API:
Exception in thread "main" io.restassured.path.json.exception.JsonPathException: Failed to parse the JSON document
at io.restassured.path.json.JsonPath$ExceptionCatcher.invoke(JsonPath.java:1002)
at io.restassured.path.json.JsonPath$4.doParseWith(JsonPath.java:967)
at io.restassured.path.json.JsonPath$JsonParser.parseWith(JsonPath.java:1047)
at io.restassured.path.json.JsonPath.toJsonString(JsonPath.java:1064)
at io.restassured.path.json.JsonPath.prettify(JsonPath.java:685)
at io.restassured.path.json.JsonPath.prettyPrint(JsonPath.java:700)
at ApiAutomation_BDD.ApiAutomation_BDD.bearerToken_GETRequest.main(bearerToken_GETRequest.java:35)
Caused by: groovy.json.JsonException: Lexing failed on line: 2, column: 1, while reading '<', no possible valid JSON value or punctuation could be recognized.
at groovy.json.JsonLexer.nextToken(JsonLexer.java:86)
at groovy.json.JsonLexer$nextToken.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:130)
at io.restassured.internal.path.json.ConfigurableJsonSlurper.parse(ConfigurableJsonSlurper.groovy:97)
at io.restassured.internal.path.json.ConfigurableJsonSlurper$parse.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:171)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:185)
at io.restassured.internal.path.json.ConfigurableJsonSlurper.parseText(ConfigurableJsonSlurper.groovy:83)
at io.restassured.path.json.JsonPath$4$1.method(JsonPath.java:965)
at io.restassured.path.json.JsonPath$ExceptionCatcher.invoke(JsonPath.java:1000)
... 6 more
and the following is the code which I tried (again not sharing any values coz of security risk):
public static void main(String args[]) throws IOException {
RestAssured.baseURI = "{Url}";
RequestSpecification httpRequest = RestAssured.given()
.contentType("x-www-form-urlencoded")
.formParam("grant_type", "")
.formParam("client_id", "")
.formParam("scope", "")
.formParam("client_secret","");
Response response = httpRequest.request(Method.GET);
JsonPath res = response.jsonPath();
//String BearerToken = response.getBody().asString();
//System.out.println("The response is:" +res);
res.prettyPrint();
int code = response.getStatusCode();
System.out.println("The status code is" + code);
assertEquals(code, 200);
}
}

Unity WP8 sample not working

I am trying to develop a unity plugin for WP8. I followed the following guide: http://docs.unity3d.com/Manual/wp8-plugins-guide-csharp.html
Then copied the fake dll to assets/plugin and real dll to assets/plugin/WP8.
I created the following script:
using UnityEngine;
using System.Collections;
public class AdDemo : MonoBehaviour {
void Start () {
string t = UnityPluginForWindowsPhone.Class1.GetDeviceName;
}
}
When compiling in Unity 4.5 I get the following error:
Internal compiler error. See the console log for more information. output was:
Unhandled Exception: System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded.
at (wrapper managed-to-native) System.Reflection.Assembly:GetTypes (bool)
at System.Reflection.Assembly.GetTypes () [0x00000] in <filename unknown>:0
at Mono.CSharp.RootNamespace.ComputeNamespaces (System.Reflection.Assembly assembly, System.Type extensionType) [0x00000] in <filename unknown>:0
at Mono.CSharp.RootNamespace.ComputeNamespace (Mono.CSharp.CompilerContext ctx, System.Type extensionType) [0x00000] in <filename unknown>:0
at Mono.CSharp.GlobalRootNamespace.ComputeNamespaces (Mono.CSharp.CompilerContext ctx) [0x00000] in <filename unknown>:0
at Mono.CSharp.Driver.LoadReferences () [0x00000] in <filename unknown>:0
at Mono.CSharp.Driver.Compile () [0x00000] in <filename unknown>:0
at Mono.CSharp.Driver.Main (System.String[] args) [0x00000] in <filename unknown>:0
Did anybody get this to work?
Thanks
Finally i found solution after struggling 2 days. The solution in the tutorials it self.
You should use Plugins folder under Assets folder.
Here you missed 's' in Plugin folder assets/plugin/WP8
This should like this Assets/Plugins/WP8

WP8 Server Not Found Error

I am trying to POST JSON data to my WCF service but I get a Not Found error.
Code:
public void ReportSighting()
{
var uri = new Uri("http://demo.notifysolutions.com/MobileService.svc/ReportSighting", UriKind.Absolute);
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.Headers[HttpRequestHeader.ContentLength] = jsonData.Length.ToString();
webClient.AllowWriteStreamBuffering = true;
webClient.UploadStringAsync(uri, "POST", jsonData);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(ReportSightingCompleted);
System.Threading.Thread.Sleep(200);
}
private void PostCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show(e.Result);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Error:
InnerException = {System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at Syst...
I have tried this in Fiddler and it works fine.

Error while editing layout files

Since updating to version 3.0.1 of MonoDevelop, I've been unable to work with layout files. When I create a new layout file and then try to edit it from the "Source" tab, I get the following error:
System.InvalidOperationException: Layout not yet loaded
at Xamarin.AndroidDesigner.DesignerSession.SetLayoutXml (System.String xml, Boolean allowUndo) [0x000bf] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/md-addins/MonoDevelop.MonoDroid/Xamarin.AndroidDesigner/Xamarin.AndroidDesigner/DesignerSession.cs:353
at MonoDevelop.MonoDroid.Gui.LayoutSourceEditorView.SaveContent () [0x00025] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/md-addins/MonoDevelop.MonoDroid/MonoDevelop.MonoDroid/Gui/AndroidDesignerView.cs:641
at MonoDevelop.MonoDroid.Gui.LayoutSourceEditorView.Deselected () [0x00000] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/md-addins/MonoDevelop.MonoDroid/MonoDevelop.MonoDroid/Gui/AndroidDesignerView.cs:670
at MonoDevelop.Ide.Gui.SdiWorkspaceWindow.SetCurrentView (Int32 newIndex) [0x00032] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/SdiWorkspaceWindow.cs:571
at MonoDevelop.Ide.Gui.SdiWorkspaceWindow+<AddButton>c__AnonStoreyB0.<>m__169 (System.Object sender, System.EventArgs e) [0x00033] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/SdiWorkspaceWindow.cs:488
at MonoDevelop.Components.Tab.OnActivated (System.EventArgs e) [0x0000d] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Components/Tabstrip.cs:396
at MonoDevelop.Components.Tab.Activate () [0x00000] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Components/Tabstrip.cs:244
at MonoDevelop.Ide.Gui.SdiWorkspaceWindow.ActiveDocumentChanged (System.Object sender, System.EventArgs e) [0x0000b] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/SdiWorkspaceWindow.cs:501
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at MonoDevelop.Ide.Gui.Workbench.OnDocumentChanged (System.Object s, System.EventArgs a) [0x0000b] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Workbench.cs:606
at MonoDevelop.Ide.Gui.DefaultWorkbench.OnActiveWindowChanged (System.Object sender, System.EventArgs e) [0x00075] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/DefaultWorkbench.cs:749
at Gtk.Notebook.SwitchPageSignalCallback (IntPtr arg0, IntPtr arg1, UInt32 arg2, IntPtr gch) [0x00000] in <filename unknown>:0
I haven't found a bug indicating others are experiencing this. Could it be a configuration issue of some sort in my environment? I'm using Mono for Android 4.2.1.196198126.
This issue was addressed in version 3.0.2 of MonoDevelop.
http://monodevelop.com/Download/Release_Notes/Release_Notes_for_MonoDevelop_3.0.2

System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically

Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.