How to Capture the Web Exception in windows phone 8? - windows-phone-8

I am using the Wamp Server for back end and C# for front end. For Cheeking purpose i turn off the server. And run the program. It throw the following error in output window.
'TaskHost.exe' (CLR C:\windows\system32\coreclr.dll: Silverlight AppDomain): Loaded
'C:\windows\system32\System.Core.ni.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
My Aim is Capture that Web exception into on message box. Is it possible.
I am already use the try, catch statement for capture that exception. But it's not working.
My Code
private void Login_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(this.username.Text) || string.IsNullOrWhiteSpace(this.password.Password))
{
MessageBox.Show("Please Enter the Username and Password");
this.username.Text = "";
this.password.Password = "";
}
else
{
string url = ob.localhost + "login_validate.php";
Uri uri = new Uri(url, UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "username", HttpUtility.UrlEncode(this.username.Text));// txtUsername.Text));
postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(this.password.Password.ToString()));
try
{
WebClient client = default(WebClient);
client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
client.UploadStringCompleted += client_UploadStringCompleted;
//client.UploadProgressChanged += client_UploadProgressChanged;
client.UploadStringAsync(uri, "POST", postData.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Data.ToString());
MessageBox.Show(ex.GetBaseException().ToString());
}
}
prog = new ProgressIndicator();
prog.IsIndeterminate = true;
prog.IsVisible = true;
prog.Text = "Loading....";
SystemTray.SetProgressIndicator(this, prog);
}
Please help me. Thanks in advance.

try using:
catch(Webexception ex)
{
Messagebox.Show(ex.innerexception.tostring());
}

Related

How to use SocketChannel to connect to remote webserver

I am trying to get the response sent by the web server through Java NIO socketChannel. The read call of SocketChannel is not returning anything when it is in non-blocking
clientSocket.configureBlocking(false);
When specified true, means blocking mode, then it is returning response. Someone saying that we should use Selector when non-blocking mode enabled. But I didn't find a way to implement this.
FYI, Following is the code snippet I am trying.
public static void main(String[] args) throws IOException, InterruptedException
{
URL u = new URL("http://www.google.com");
InetSocketAddress addr = new InetSocketAddress("www.google.com", 80);
SocketChannel clientSocket = SocketChannel.open(addr);
clientSocket.configureBlocking(false);
byte[] message = new String("GET " + u.getFile() + " HTTP/1.0\r\n").getBytes();
ByteBuffer writeBuff = ByteBuffer.wrap(message);
clientSocket.write(writeBuff);
ByteBuffer readBuff = MappedByteBuffer.allocate(1500);
clientSocket.read(readBuff);
while(clientSocket.read(readBuff) > 0)
{
System.out.println(new String(readBuff.array()).trim());
}
clientSocket.close();
}
Thanks in advance.
You should use loops to read() and write() till the buffer has no remaining bytes when non-blocking mode.
There two problems in your code:
the http request body is wrong. it needs additional "\r\n".
the readBuff need to cleared each time after reading.
below code is a working version:
static void working() throws Exception {
URL u = new URL("http://www.baidu.com");
InetSocketAddress addr = new InetSocketAddress("www.baidu.com", 80);
SocketChannel clientSocket = SocketChannel.open(addr);
clientSocket.configureBlocking(false);
byte[] message = new String("GET / HTTP/1.0\r\n\r\n").getBytes();
ByteBuffer writeBuff = ByteBuffer.wrap(message);
clientSocket.write(writeBuff);
ByteBuffer readBuff = MappedByteBuffer.allocate(1500);
while (clientSocket.read(readBuff) != -1) {
System.out.println("Entring...");
System.out.println(new String(readBuff.array()).trim());
readBuff.clear();
}
clientSocket.close();
}
}
Notice, if it's http version 1.1, it will not break too. because it has a keeplive.

wp8 Handle raw push notification in more than one pages

I am developing a wp8 application and the need is the above:
My server sends some raw push notifications that i can handle in my mainpage successful. But i have more pages so i need my app continue to get and handle notifications when the user is on the other pages.
As far i have tried to add the same code as i have put in the main page to handle notifications
string channelName = "test";
pushChannel = HttpNotificationChannel.Find(channelName);
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
//pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
//pushChannel.BindToShellToast();
System.Threading.Thread.Sleep(3000);
channel = pushChannel.ChannelUri.ToString();
cSettings.device_notify_id = channel;
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
// pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
System.Threading.Thread.Sleep(3000);
channel = pushChannel.ChannelUri.ToString();
cSettings.device_notify_id = channel;
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
}
and the handlers methods
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
cSettings.device_notify_id = e.ChannelUri.ToString();
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
});
}
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
cSettings set = new cSettings();
set.LogEx(new Exception((String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))));
// Error handling logic for your particular application would be here.
Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
);
}
void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
string message;
VibrationDevice vibr = VibrationDevice.GetDefault();
vibr.Vibrate(TimeSpan.FromSeconds(3));
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
cSettings set = new cSettings();
string n_type = "";
string n_header = "";
//var obj = set.parse_stringfromnotify(message, ref n_type, ref n_header);
Dispatcher.BeginInvoke(() => nofication_received_action(message, n_type, ""));
}
private void nofication_received_action(string n_header, string n_type, object data)
{
MessageBoxResult result;
CallSrvData cdata = new CallSrvData();
Exception ex = null;
WP_MemberData m;
WP_MemberRules wpmr;
cSettings set;
MemberRules mr;
Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
Rules c_rules;
Notify.data = data;
Notify.msg_box_text = String.Format("{0}", n_header);
//dose k data sth forma
toast = new Microsoft.Phone.Shell.ShellToast();
toast.Content = "Invitation received";
toast.Title = "Title : ";
//SetProperty(toast, "Sound", new Uri("/data/alert.mp3", UriKind.Relative));
toast.NavigationUri = new Uri("/forms/Notify.xaml?type=0", UriKind.Relative);
toast.Show();
}
When the app is in background and i successfully get the notification and navigate to Notify.xaml the mechanism works fine, but when i go back or i press start button to leave from Notify.xaml and i resend a notification nothing happens. I have tried to add the same code and in Notify.xaml but again nothing happen when i send notification. In comparison with android where you just register listeners once in your app and then you can receive notification in in any page even the app is "closed" who can i succeed something like that or can i succeed something like that?
Thx a lot for your contribution.
I have found that i can create all the notification functionality in a class which will initialize on app.cs or any time is needed.

WebException thrown when locking screen of the Emulator (WindowsPhone8)

I have a webrequest to get a xml.That works great but when i press F12(lock screen) while the the server is requested by my app...I got a WebException.
I use a taskCompeltionSource object...Here is my code
public async Task<String> Query(DataRequestParam dataRequestParam)
{
_dataRequestParam = dataRequestParam;
try
{
Result = "";
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)//ERROR IS CAUGHT HERE
{
throw new WebException(we.Message);
}
catch (Exception ex)
{
throw new MyException(ex.Message);
}
return Result;
}
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
If you haven't disabled ApplisationIdleDetection, your process is stopped while entering Lock screen - thus you probably get the exception - like I've said in comment. Disabling will solve this issue, but you must be aware of few things:
you will still get the exception when hitting Start Button (or other case putting your app to dormant state). In this case your app is stopped and there is no way to prevent this behaviour.
you must fulfill certification requirements when disabling App Idle Detection - point 6.3
if you want to download files in the Background (lock screen, after closing/leaving app) then you can think of Background Transfers

Webservices object reference not set to an instance of an object error

I have to make a call to the web service (JSON) to authenticate the user who is trying to login to the app. I have the following xml provided
<summary>
http://geniewebsvc.cloudapp.net/Member.svc/Authenticate
</summary>
<param name="payload">
{"UserName":"testuser#somedomain.com","Password":"p#$$w0rd"}
</param>
<requiredHeaders>
Content-Type: application/json;charset=UTF-8
</requiredHeaders>
<returns></returns>
[OperationContract]
[WebInvoke(UriTemplate = "/Authenticate", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
AuthenticateResponse Authenticate(AuthCredentials usernamePassword);
There is similar one to check if the userid is already registered and that is a Get method. That works fine and i receive the right response for both successful and unsuccessful cases. But all the post methods are the ones which are giving me trouble. and i noticed that there is one more difference in these xmls.. i.e., the .. the isregistered webservice param tag goes something like this..
<param name="emailAddress"></param>
and here is my get() and post() please let me know whats my mistake...
public void Post()
{
RequestState myRequestState = new RequestState();
try
{
System.Uri uri = new Uri(url);
HttpWebRequest myHttpWebGetRequest;
Logger.log(TAG, "Create a HttpWebrequest object to the URL", url);
myHttpWebGetRequest = (HttpWebRequest)WebRequest.Create(uri);
_mHttpWebRequest = myHttpWebGetRequest;
myRequestState.conn = this;
myRequestState.request = myHttpWebGetRequest;
myRequestState.request.ContentType = "application/json;charset=UTF-8";
myRequestState.request.Method = "POST";
myRequestState.request.AllowReadStreamBuffering = false;
myRequestState.request.Headers["UserName"] = "rick.labarbera#gmail.com";
myRequestState.request.Headers["Password"] = "125124514";
// myRequestState.request.Headers["MemberId"] = "UdE8IwmTbxEjmzmMo2nBpg==";
IAsyncResult result = (IAsyncResult)myHttpWebGetRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (Exception e)
{
close(myRequestState);
if (this.listener != null)
{
Logger.log(TAG, "post()", e.Message);
}
}
}
public void Get()
{
RequestState myRequestState = new RequestState();
try
{
System.Uri uri = new Uri(url);
HttpWebRequest myHttpWebPostRequest;
Logger.log(TAG, "Create a HttpWebrequest object to the URL", url);
myHttpWebPostRequest = (HttpWebRequest)WebRequest.Create(uri);
_mHttpWebRequest = myHttpWebPostRequest;
myRequestState.conn = this;
myRequestState.request = myHttpWebPostRequest;
myRequestState.request.Method = "GET";
myRequestState.request.AllowReadStreamBuffering = false;
IAsyncResult result = (IAsyncResult)myHttpWebPostRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (Exception e)
{
close(myRequestState);
if (this.listener != null)
{
Logger.log(TAG, "get()", e.Message);
}
}
}
Am i doing something wrong???All these things are very very new to me.. I need help badly..
Thanks :)
I have played a bit with your code, but couldn't make it :(
What are the URL's you are using for the POST() method and for GET() methods.?
By the way, There is another way around to invoke your service. Follow these steps:
-- Create a new project.
-- Right-click on the Project name and click on "Add Service Reference"... Then provide address as "http://geniewebsvc.cloudapp.net/Member.svc" and click Go.
-- Once service information is downloaded, provide Namespace something like "MyMemberService" and click Ok.
Then Goto your MainPage.xaml.cs and write the following code.
MemberServiceClient client = new MemberServiceClient();
client.AuthenticateCompleted += new EventHandler<AuthenticateCompletedEventArgs>(client_AuthenticateCompleted);
client.AuthenticateAsync(new AuthCredentials() { UserName = "rick.labarbera#gmail.com", Password = "125124514" });
And the AuthenticateCompleted handler is
void client_AuthenticateCompleted(object sender, AuthenticateCompletedEventArgs e)
{
MessageBox.Show(e.Result.Successful.ToString());
}
This way you can simply call any service in the MemberService with just 2 or 3 lines of code. This is how a soap client is invoked in a Visual Studio project.
But again, there are some "Endpoint configuration" issues in this which you need to solve. And if you can do that you can save atleast 30 to 40 % of your development time.
Good luck.

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.