add time in loading web service in windows phone - json

This is my code to load web service in my app:
public LoadData()
{
InitializeComponent();
PostData();
}
private void PostData()
{
Uri uri = new Uri("my web service url");
WebClient client= new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.UploadStringAsync(uri);
client.UploadStringCompleted += client_UploadComplete;
}
public void client_UploadComplete(object sender, UploadStringCompletedEventArgs e)
{
var test= JsonConvert.DeserializeObject<Main>(e.Result);
}
At this point if web service takes more than 10 seconds to load all the data in variable test, then a message box or a popup box open which say " Slow Connection Please retry" along with retry button which again load my PostData();
how would be possible to add time in loading web service in WP
please help me on this.....

Add a timer event and start it before your asynchronous upload. The event fires after 10 secs. But if the code reaches inside ur complete event disable the timer.

Related

Share Media Task

I'm developing app for Windows Phone 8, and i'm trying to share image via ShareMediaTask.
The procedure? that i use for it is as follows :
private static Microsoft.Phone.Tasks.ShareMediaTask shareMediaTask;
public static void shareCurrentCroppedImage ()
{
shareMediaTask = new Microsoft.Phone.Tasks.ShareMediaTask();
GC.Collect();
Debug.WriteLine("file path : {0}", currentFileName);
shareMediaTask.FilePath = currentFileName;
shareMediaTask.Show();
}
The path from console looks like this:
file path : C:\Data\Users\Public\Pictures\Saved Pictures\Lo_1.jpg
Unfortunately, when i call this proc ( from button click event ) the app shuts down, a black screen shows, but then suddenly workflow returns back to my app without any sharing UI. How can i fix this issue? Any help would be appreciated!
This is the code which worked for me..
I had created a PhotoChooserTask to capture an image or open an existing image from library and then when this PhotoChooserTask completes, I create a ShareMediaTask and set its Filepath property to The "OriginalFileName" filed from the parameter photoresult e.
The issue with your code, i think, might be this path of image.
private void OnShareMediaTaskClicked(object sender, RoutedEventArgs e)
{
var photoChooserTask = new PhotoChooserTask { ShowCamera = true };
photoChooserTask.Completed += OnPhotoChooserTaskCompleted;
photoChooserTask.Show();
}
void OnPhotoChooserTaskCompleted(object sender, PhotoResult e)
{
var photoChooserTask = (PhotoChooserTask)sender;
photoChooserTask.Completed -= OnPhotoChooserTaskCompleted;
var shareMediaTask = new ShareMediaTask ();
shareMediaTask.FilePath = e.OriginalFileName;
shareMediaTask.Show();
}
I have set the OnShareMEdiaClicked as ahandler of an onClick event for a button. and the rest flow is clear.
Hope this helps.

mvvmcross and authentication

Is there a way to authenticate a user through Facebook in mvvmcross framework? I'm currently attempting use Mobile Azure Service to authenticate to Facebook, but I don't have any success. Without using mvvmcross, I can authenticate just fine.
Thank You!
Mark
In the MVVM sense what I've found is that no, you can not. Properties on the facebook login page are not bindable, nor should they be and is best treated as a modal view out of your control
What I would do is make it a view concern and use Xamarin.Auth to authenticate.
As an example let's say that you had a LoginView and LoginViewModel.
The LoginView provides your standard login Email/Password but with an option (button) to authenticate via facebook
From that view hook up to the touchupinside event of the facebooklogin button
this.btnFacebookLogin.TouchUpInside += (object sender, EventArgs e) =>
{
DoFacebookLogin ();
}
Then in your DoFacebookLogin method 'present' the viewcontroller for facebook as described here https://github.com/xamarin/Xamarin.Auth/blob/master/GettingStarted.md
For example :
private void DoFacebookLogin ()
{
var auth = new OAuth2Authenticator (
clientId: "yournumericclientidhere",
scope: "",
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));
auth.AllowCancel = true;
auth.Completed += (sender, eventArgs) => {
DismissViewController (false, null);
if (eventArgs.IsAuthenticated) {
string user = eventArgs.Account.Serialize ();
var messenger = Mvx.Resolve<IMvxMessenger> ();
messenger.Publish (new FacebookLoggedIn (user));
} else {
// Cancelled here
}
};
var vc = auth.GetUI ();
this.PresentViewController (vc, true, null);
}
Cancelled does not need to be handled since the modal viewcontroller will take you back to your LoginView
On success that viewcontroller is dismissed then I would use mvx's interpretation of an eventaggregator (plugins.messenger) to send a message to the viewmodel that the facebook modal view is closed, with that message you can pass the account details - accesstoken etc back to the viewmodel to do as you wish.
View (as above) :
string user = eventArgs.Account.Serialize();
var messenger = Mvx.Resolve<IMvxMessenger> ();
messenger.Publish (new FacebookLoggedIn (user));
Message Class in your PCL :
public class FacebookLoggedIn : MvxMessage
{
public FacebookLoggedIn(object sender) : base(sender) {}
}
ViewModel also in your PCL :
public LoginViewModel()
{
var messenger = Mvx.Resolve<IMvxMessenger> ();
user = messenger.SubscribeOnMainThread<FacebookLoggedIn> (OnFacebookLoggedIn);
}
private void OnFacebookLoggedIn (FacebookLoggedIn MvxMessage)
{
... do something with the accesstoken? call your IUserService etc
ShowViewModel<MainViewModel> ();
}
Since you're dismissing the facebook viewcontroller you'll find yourself back on the loginview momentarily before automatically navigating to the MainView
In your view project you need to ensure the plugin is loaded otherwise you'll receive an error during construction of the viewmodel, so in setup.cs
protected override void InitializeLastChance ()
{
Cirrious.MvvmCross.Plugins.Messenger.PluginLoader.Instance.EnsureLoaded();
base.InitializeLastChance ();
}
Additionally you can also store the account credentials locally, this is described on the Xamarin.Auth link under AccountStore.Create().Save. Note that if you receive a platform not supported exception then add PLATFORM_IOS as a preprocessor directive to your project.
I realise the question is a couple of months old but since it rates high on google thought I'd provide an answer since there isn't any

Windows Phone 8 SDK - Issue with screen locking, and application starting over

I have an application with a webbrowser control in it. When I navigate in that control then step away for a bit, then come back to it (after unlocking the screen due to inactivity), the first/original page shows up again. How can I maintain the state of the browser?
Define a public property Url in App.xaml.cs to store an Url
public Uri Url { get; set; }
On WebBrowser_LoadCompleted event: save WebBrowser.Source property which contains the current loaded Url to above Url property of Application class.
App app = Application.Current as App;
app.Url = WebBrowser.Source;
On Application_Deactivated event (send app to background), save current app's state to IsolatedStorage
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings["Url"] = Url;
settings.Save();
On Application_Launching event (resume app), pull the stored data back
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
Url currentUrl;
if (settings.TryGetValue("Url", out currentUrl))
Url = (Uri)settings["Url"];
Then from the restored Url, you can re-load the last navigated page.
App app = Application.Current as App;
WebBrowser.Navigate(app.Url);
You can try this:
bool isNew = true;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
isNew = false;
}
this property will be maintained until your page is closed, so you can use it to test if this is the first time your page is navigated to.

Resubmit web requests on resuming from dormancy

I am using RestSharp (a REST client for .NET) in my Windows Phone 8 app, but I think my question also applies using HttpWebRequest or any other ways of running web requests.
I am trying to find a way to automatically resubmit the requests when app is resumed from dormant state. This is only from dormant and not from the tombstone state.
The idea I had was to create a wrapper object which subscribes to the Deactivated event before starting the request and rerunning the request in case it received the event.
I assume that since the deactivated event was received, the request failed.
public class RestClientEx
{
bool wasDeactivated = false;
public async Task<T> ExecuteTaskAsync<T>(RestClient client, RestRequest request) where T : new()
{
var phoneApplicationService = App.Current.ApplicationLifetimeObjects.OfType<PhoneApplicationService>().First();
phoneApplicationService.Deactivated += phoneApplicationService_Deactivated;
var t = await client.ExecuteTaskAsync<T>(request);
if (this.wasDeactivated)
{
// resubmit request
this.wasDeactivated = false;
t = await this.ExecuteTaskAsync<T>(client, request);
}
return t;
}
void phoneApplicationService_Deactivated(object sender, DeactivatedEventArgs e)
{
(sender as PhoneApplicationService).Deactivated -= phoneApplicationService_Deactivated;
this.wasDeactivated = true;
}
}
My question is, is there another way to achieve this?
Is it OK what I am doing?

gwt with RequestFactory, handling server side exception on client and RequestFactoryEditorDriver

i use RequestFactory for communicating with server and RequestFactoryEditorDriver on the client side. So editing workflow looks like such way. Create new proxy for editing:
RequestContext reqCtx = clientFactory.getRequestFactory().Request();
UserAndAccountProxy userAndAccountProxy = reqCtx.create(UserAndAccountProxy.class);
reqCtx.saveAndReturnProfileAndAccount(userAndAccountProxy).to(
new Receiver<UserAndAccountProxy>() {
#Override
public void onSuccess(UserAndAccountProxy response) {
...
}
#Override
public void onFailure(ServerFailure error) {
...
}}
And Save button click handling:
RequestContext reqCtx = view.getEditorDriver().flush();
reqCtx.fire();
On server side saveAndReturnProfileAndAccount method can throw exceptions on persisting, which i can handle in onFailure method. After that if I create new proxy with new request context and pass it to my editor all fields will be blanked.
So what is proper way to execute request and if something goes wrong use data that user allready fill or maybe I made mistake in my editing worklow?
So, I think, I found solution. I made changes to function, which create RequestContext:
private void edit(MyProxy proxy) {
RequestContext reqCtx = clientFactory.getRequestFactory().Request();
if (proxy == null) {
// create proxy first time
proxy = reqCtx.create(UserAndAccountProxy.class);
} else {
// create immutable copy
proxy = reqCtx.edit(proxy);
}
final UserAndAccountProxy tmp = proxy;
reqCtx.saveAndReturnMyProxy(proxy).to(new Receiver<MyProxy>() {
#Override
public void onFailure(ServerFailure error) {
eventBus.showErrorInformation(error.getMessage());
//recursive call with already filled proxy
edit(tmp);
}
#Override
public void onSuccess(UserAndAccountProxy response) {
eventBus.showInformation("It`s ok!");
eventBus.goToMainPage(null);
}
});
// start editing with editor
getView().onEdit(tmp, reqCtx);
}
When we start editing proxy function edit need to bee called with null argument and new clean proxy will be created. After that we start edit it with Editor. On Save button click we execute request to server. If it ends with success - we open another page. If request ends with error, we create new immutable copy ant push it to editor.