private async Task Load() { Web.UserInteractionEnabled = false; Web.LoadHtmlString("", NSBundle.MainBundle.BundleUrl); _activityView.Alpha = 1; _activityView.StartAnimating(); View.Add(_activityView); try { var request = _inAppPurchaseService.RequestProductData(FeaturesService.ProEdition).WithTimeout(TimeSpan.FromSeconds(30)); var productData = (await request).Products.FirstOrDefault(); var enabled = _featuresService.IsProEnabled; var model = new UpgradeDetailsModel(productData != null ? productData.LocalizedPrice() : null, enabled); var content = new UpgradeDetailsRazorView { Model = model }.GenerateString(); LoadContent(content); Web.UserInteractionEnabled = true; } catch (Exception e) { AlertDialogService.ShowAlert("Error Loading Upgrades", e.Message); } finally { UIView.Animate(0.2f, 0, UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.CurveEaseInOut, () => _activityView.Alpha = 0, () => { _activityView.RemoveFromSuperview(); _activityView.StopAnimating(); }); } }
private async Task HandleEditButton() { try { var page = ViewModel.CurrentWikiPage(Web.Url.AbsoluteString); var wiki = await Task.Run(() => ViewModel.GetApplication().Client.Users[ViewModel.Username].Repositories[ViewModel.Repository].Wikis[page].GetInfo()); var composer = new Composer { Title = "Edit" + Title, Text = wiki.Data }; composer.NewComment(this, async(text) => { try { await composer.DoWorkAsync("Saving...", () => Task.Run(() => ViewModel.GetApplication().Client.Users[ViewModel.Username].Repositories[ViewModel.Repository].Wikis[page].Update(text, Uri.UnescapeDataString("/" + page)))); composer.CloseComposer(); Refresh(); } catch (Exception ex) { AlertDialogService.ShowAlert("Unable to update page!", ex.Message); composer.EnableSendButton = true; }; }); } catch (Exception e) { AlertDialogService.ShowAlert("Error", e.Message); } }
protected override bool ShouldStartLoad(WKWebView webView, WKNavigationAction navigationAction) { // F*****g BitBucket and their horrible user interface. if (ForbiddenRoutes.Any(navigationAction.Request.Url.AbsoluteString.StartsWith)) { AlertDialogService.ShowAlert("Invalid Request", "Sorry, due to restrictions, you can not sign-up for a new account in CodeBucket."); return(false); } //We're being redirected to our redirect URL so we must have been successful if (navigationAction.Request.Url.Host == "codebucket") { var queryParams = navigationAction .Request.Url.Query.Split('&') .Select(x => x.Split('=').Select(Uri.EscapeDataString).ToArray()) .Where(x => x.Length >= 2) .ToDictionary(x => x[0], x => x[1]); if (queryParams.TryGetValue("code", out string code)) { ViewModel.LoginCommand.Execute(code).LoggedCatch(this).Subscribe(); return(false); } } //if (navigationAction.Request.Url.Path.StartsWith("/socialauth", StringComparison.Ordinal)) //{ // var safari = new SFSafariViewController(new NSUrl(ViewModel.LoginUrl)); // PresentViewController(safari, true, null); // return false; //} return(base.ShouldStartLoad(webView, navigationAction)); }
private async Task Save() { if (_model.Files.Count(x => x.Value != null) == 0) { AlertDialogService.ShowAlert("No Files", "You cannot modify a Gist without atleast one file"); return; } var app = MvvmCross.Platform.Mvx.Resolve <Core.Services.IApplicationService>(); var hud = this.CreateHud(); NetworkActivity.PushNetworkActive(); try { hud.Show("Saving..."); var newGist = await app.GitHubClient.Gist.Edit(_originalGist.Id, _model); Created?.Invoke(newGist); DismissViewController(true, null); } catch (Exception e) { AlertDialogService.ShowAlert("Error", "Unable to save gist: " + e.Message); } finally { hud.Hide(); NetworkActivity.PopNetworkActive(); } }
private async Task Save() { if (_model.Files.Count(x => x.Value != null) == 0) { AlertDialogService.ShowAlert("No Files", "You cannot modify a Gist without atleast one file"); return; } var app = MvvmCross.Platform.Mvx.Resolve <CodeHub.Core.Services.IApplicationService>(); var hud = this.CreateHud(); NetworkActivity.PushNetworkActive(); try { hud.Show("Saving..."); var newGist = await app.Client.ExecuteAsync(app.Client.Gists[_originalGist.Id].EditGist(_model)); Created?.Invoke(newGist.Data); DismissViewController(true, null); } finally { hud.Hide(); NetworkActivity.PopNetworkActive(); } }
private void SelectImage() { var imagePicker = new RotatableUIImagePickerController(); imagePicker.NavigationControllerDelegate = new ImagePickerDelegate(); imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary; imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary); imagePicker.MediaTypes = imagePicker.MediaTypes.Where(x => !(x.Contains("movie") || x.Contains("video"))).ToArray(); imagePicker.FinishedPickingMedia += (sender, e) => { // determine what was selected, video or image bool isImage = false; switch (e.Info[UIImagePickerController.MediaType].ToString()) { case "public.image": isImage = true; break; } // if it was an image, get the other image info if (isImage) { // get the original image UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage; if (originalImage != null) { // do something with the image try { UploadImage(originalImage); } catch { } } } else { // if it's a video AlertDialogService.ShowAlert("Not supported!", "Video upload is currently not supported."); } // dismiss the picker imagePicker.DismissViewController(true, null); UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent; }; imagePicker.Canceled += (sender, e) => { imagePicker.DismissViewController(true, null); UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent; }; NavigationController.PresentViewController(imagePicker, true, null); }
public override void ApplyButtonPressed() { if (string.IsNullOrEmpty(_filterName.Value)) { AlertDialogService.ShowAlert("Filter Name", "You must name your filter!"); return; } CreatedFilterModel(CreateFilterModel()); }
protected override void OnLoadError(NSError error) { base.OnLoadError(error); //Frame interrupted error if (error.Code == 102 || error.Code == -999) { return; } AlertDialogService.ShowAlert("Error", "Unable to communicate with Bitbucket. " + error.LocalizedDescription); }
private async Task MergeClick() { try { await this.DoWorkAsync("Merging...", ViewModel.Merge); } catch (Exception e) { AlertDialogService.ShowAlert("Unable to Merge", e.Message); } }
private async Task GoToPage(string page) { try { var data = await ViewModel.GetData(page); Web.LoadRequest(new NSUrlRequest(new NSUrl(data))); } catch (Exception e) { AlertDialogService.ShowAlert("Error", e.Message); } }
private async Task Activate(Func <Task> activation) { try { BTProgressHUD.ShowContinuousProgress("Activating...", ProgressHUD.MaskType.Gradient); using (Disposable.Create(BTProgressHUD.Dismiss)) await activation(); Load().ToBackground(); } catch (Exception e) { AlertDialogService.ShowAlert("Error", e.Message); } }
/// <summary> /// Need another function because Xamarin generates an Invalid IL if used inline above /// </summary> private async Task CommitThis(EditSourceViewModel viewModel, LiteComposer composer, string content, string message) { try { await this.DoWorkAsync("Commiting...", () => viewModel.Commit(content, message)); NavigationController.DismissViewController(true, null); } catch (Exception ex) { AlertDialogService.ShowAlert("Error", ex.Message); composer.EnableSendButton = true; } }
protected GistFileModifyViewController() : base(UITableViewStyle.Plain) { SaveCommand = ReactiveCommand.CreateFromTask(t => { if (String.IsNullOrEmpty(Content)) { throw new Exception("You cannot save a file without content!"); } Save?.Invoke(Filename, Content); return(Task.FromResult(Unit.Default)); }); SaveCommand.ThrownExceptions.Subscribe(x => AlertDialogService.ShowAlert("Error", x.Message)); }
public override void ViewDidLoad() { base.ViewDidLoad(); try { var vm = (WebBrowserViewModel)ViewModel; if (!string.IsNullOrEmpty(vm.Url)) { Web.LoadRequest(new Foundation.NSUrlRequest(new Foundation.NSUrl(vm.Url))); } } catch (Exception e) { AlertDialogService.ShowAlert("Unable to process request!", e.Message); } }
private void ShowCommentComposer(int line) { var composer = new MarkdownComposerViewController(); composer.NewComment(this, async(text) => { try { await composer.DoWorkAsync("Commenting...", () => ViewModel.PostComment(text, line)); composer.CloseComposer(); } catch (Exception e) { AlertDialogService.ShowAlert("Unable to Comment", e.Message); composer.EnableSendButton = true; } }); }
/// <summary> /// Need another function because Xamarin generates an Invalid IL if used inline above /// </summary> private async Task CommitThis(string content, string message) { try { UIApplication.SharedApplication.BeginIgnoringInteractionEvents(); await this.DoWorkAsync("Commiting...", () => ViewModel.Commit(content, message)); this.PresentingViewController?.DismissViewController(true, null); } catch (Exception ex) { AlertDialogService.ShowAlert("Error", ex.Message); } finally { UIApplication.SharedApplication.EndIgnoringInteractionEvents(); } }
protected async override void Refresh() { var page = ViewModel.CurrentWikiPage(Web.Url.AbsoluteString); if (page != null) { try { await ViewModel.GetData(page); } catch (Exception e) { AlertDialogService.ShowAlert("Error", e.Message); } } base.Refresh(); }
public override void ViewDidLoad() { base.ViewDidLoad(); var vm = ViewModel as WebBrowserViewModel; System.Uri uri; if (!System.Uri.TryCreate(vm.Url, System.UriKind.Absolute, out uri)) { AlertDialogService.ShowAlert("Error", "Unable to display webpage as the provided link (" + vm.Url + ") was invalid"); } else { var safariBrowser = new SafariServices.SFSafariViewController(new NSUrl(vm.Url)); safariBrowser.View.Frame = View.Bounds; safariBrowser.View.AutoresizingMask = UIViewAutoresizing.All; AddChildViewController(safariBrowser); Add(safariBrowser.View); } }
private async Task CommitThis(string message) { var content = _descriptionElement.Value; var name = _titleElement.Value; var path = string.IsNullOrEmpty(_path) ? name : $"{_path.TrimEnd('/')}/{name}"; var hud = this.CreateHud(); try { hud.Show("Committing..."); UIApplication.SharedApplication.BeginIgnoringInteractionEvents(); NetworkActivity.PushNetworkActive(); var encodedPath = path == null ? null : System.Net.WebUtility.UrlEncode(path); var result = await _applicationService.GitHubClient.Repository.Content.CreateFile( _username, _repository, encodedPath, new Octokit.CreateFileRequest(message, content, _branch)); this.PresentingViewController?.DismissViewController(true, null); _successSubject.OnNext(result); } catch (Octokit.ApiException ex) { var errorMessage = ex.Message; if (ex.ApiError?.DocumentationUrl == "https://developer.github.com/v3/repos/contents/#update-a-file") { errorMessage = "A file with that name already exists!"; } AlertDialogService.ShowAlert("Error", errorMessage); } catch (Exception ex) { AlertDialogService.ShowAlert("Error", ex.Message); } finally { UIApplication.SharedApplication.EndIgnoringInteractionEvents(); NetworkActivity.PopNetworkActive(); hud.Hide(); } }
protected override bool ShouldStartLoad(WKWebView webView, WKNavigationAction navigationAction) { // F*****g BitBucket and their horrible user interface. if (ForbiddenRoutes.Any(navigationAction.Request.Url.AbsoluteString.StartsWith)) { AlertDialogService.ShowAlert("Invalid Request", "Sorry, due to restrictions you can not sign-up for a new account in CodeBucket."); return(false); } //We're being redirected to our redirect URL so we must have been successful if (navigationAction.Request.Url.Host == "codebucket") { ViewModel.Code = navigationAction.Request.Url.Query.Split('=')[1]; ViewModel.LoginCommand.ExecuteIfCan(); return(false); } return(base.ShouldStartLoad(webView, navigationAction)); }
private static ICollection <Section> RenderSections(IEnumerable <Section> sections, Action moreAction) { var weakAction = new WeakReference <Action>(moreAction); ICollection <Section> newSections = new LinkedList <Section>(sections); if (moreAction != null) { var loadMore = new PaginateElement("Load More", "Loading...") { AutoLoadOnVisible = true }; newSections.Add(new Section { loadMore }); loadMore.Tapped += async(obj) => { try { NetworkActivity.PushNetworkActive(); var a = weakAction.Get(); if (a != null) { await Task.Run(a); } var root = loadMore.GetRootElement(); root?.Remove(loadMore.Section, UITableViewRowAnimation.Fade); } catch (Exception e) { AlertDialogService.ShowAlert("Unable to load more!", e.Message); } finally { NetworkActivity.PopNetworkActive(); } }; } return(newSections); }
void AddCommentTapped() { var composer = new Composer(); composer.NewComment(this, async(text) => { try { await composer.DoWorkAsync("Commenting...", () => ViewModel.AddComment(text)); composer.CloseComposer(); } catch (Exception e) { AlertDialogService.ShowAlert("Unable to post comment!", e.Message); } finally { composer.EnableSendButton = true; } }); }
private void ShowCommentComposer(int line) { var composer = new MarkdownComposerViewController(); composer.PresentAsModal(this, async() => { UIApplication.SharedApplication.BeginIgnoringInteractionEvents(); try { await composer.DoWorkAsync("Commenting...", () => ViewModel.PostComment(composer.Text, line)); this.DismissViewController(true, null); } catch (Exception e) { AlertDialogService.ShowAlert("Unable to Comment", e.Message); } UIApplication.SharedApplication.EndIgnoringInteractionEvents(); }); }
private async void UploadImage(UIImage img) { var hud = new CodeHub.iOS.Utilities.Hud(null); hud.Show("Uploading..."); try { var returnData = await Task.Run <byte[]>(() => { using (var w = new WebClient()) { var data = img.AsJPEG(); byte[] dataBytes = new byte[data.Length]; System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length)); w.Headers.Set("Authorization", "Client-ID aa5d7d0bc1dffa6"); var values = new NameValueCollection { { "image", Convert.ToBase64String(dataBytes) } }; return(w.UploadValues("https://api.imgur.com/3/image", values)); } }); var json = Mvx.Resolve <IJsonSerializationService>(); var imgurModel = json.Deserialize <ImgurModel>(System.Text.Encoding.UTF8.GetString(returnData)); TextView.InsertText("![](" + imgurModel.Data.Link + ")"); } catch (Exception e) { AlertDialogService.ShowAlert("Error", "Unable to upload image: " + e.Message); } finally { hud.Hide(); } }
private void SaveClicked() { var newName = Name.Text; var newContent = Text.Text; if (String.IsNullOrEmpty(newContent)) { AlertDialogService.ShowAlert("No Content", "You cannot save a file without content!"); return; } try { Save?.Invoke(newName, newContent); NavigationController.PopViewController(true); } catch (Exception ex) { AlertDialogService.ShowAlert("Error", ex.Message); } }
public override bool HandleOpenURL(UIApplication application, NSUrl url) { if (url == null) { return(false); } if (string.Equals(url.Host, "login", StringComparison.OrdinalIgnoreCase)) { var queries = url .Query.Split('&') .Select(x => x.Split('=')) .ToDictionary(x => x.FirstOrDefault(), x => x.LastOrDefault(), StringComparer.OrdinalIgnoreCase); var showError = new Action <string>(msg => AlertDialogService.ShowAlert( "Error", $"There was a problem attempting to login: {msg}.")); if (queries.TryGetValue("code", out string code)) { _applicationService .Value.Login(code).ToObservable() .Select(_ => new LogoutMessage()) .Subscribe(x => MessageBus.Current.SendMessage(x), err => showError(err.Message)); } else if (queries.TryGetValue("error", out string error)) { var errorDescription = "unknown error"; if (error == "access_denied") { errorDescription = "access denied"; } showError(errorDescription); } } return(true); }
/// <summary> /// Finished the launching. /// </summary> /// <param name="app">The app.</param> /// <param name="options">The options.</param> /// <returns>True or false.</returns> public override bool FinishedLaunching(UIApplication app, NSDictionary options) { // Stamp the date this was installed (first run) StampInstallDate("CodeBucket"); var exceptionSubject = new Subject <Exception>(); RxApp.DefaultExceptionHandler = exceptionSubject; exceptionSubject.Subscribe(x => AlertDialogService.ShowAlert("Error", x.Message)); Window = new UIWindow(UIScreen.MainScreen.Bounds); Presenter = new IosViewPresenter(Window); new Setup(this, Presenter).Initialize(); // Setup theme Theme.Setup(); GoToStartupView(); Window.MakeKeyAndVisible(); return(true); }
void AddCommentTapped() { var composer = new MarkdownComposerViewController(); composer.PresentAsModal(this, async text => { var hud = composer.CreateHud(); using (UIApplication.SharedApplication.DisableInteraction()) using (NetworkActivity.ActivateNetwork()) using (hud.Activate("Commenting...")) { try { await ViewModel.AddComment(text); composer.DismissViewController(true, null); } catch (Exception e) { AlertDialogService.ShowAlert("Unable to post comment!", e.Message); } } }); }
private void ShowComposer(Func <string, Task> workFn) { var composer = new MarkdownComposerViewController(); composer.PresentAsModal(this, async text => { var hud = composer.CreateHud(); using (UIApplication.SharedApplication.DisableInteraction()) using (_networkActivityService.ActivateNetwork()) using (hud.Activate("Commenting...")) { try { await workFn(text); composer.DismissViewController(true, null); } catch (Exception e) { AlertDialogService.ShowAlert("Unable to Comment", e.Message); } } }); }
/// <summary> /// Finished the launching. /// </summary> /// <param name="app">The app.</param> /// <param name="options">The options.</param> /// <returns>True or false.</returns> public override bool FinishedLaunching(UIApplication app, NSDictionary options) { Crashlytics.Instance.Initialize(); Fabric.Instance.Initialize(); #if DEBUG Fabric.Instance.Debug = true; #endif Window = new UIWindow(UIScreen.MainScreen.Bounds); Presenter = new IosViewPresenter(this.Window); var setup = new Setup(this, Presenter); setup.Initialize(); var culture = new System.Globalization.CultureInfo("en"); System.Threading.Thread.CurrentThread.CurrentCulture = culture; System.Threading.Thread.CurrentThread.CurrentUICulture = culture; System.Globalization.CultureInfo.DefaultThreadCurrentCulture = culture; System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = culture; // Setup theme UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, true); Theme.Setup(); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <IApplicationService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <IAccountsService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <IAlertDialogService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <INetworkActivityService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <IMessageService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <IInAppPurchaseService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <IFeaturesService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <ILoginService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <IMarkdownService>()); Locator.CurrentMutable.RegisterConstant(Mvx.Resolve <IPushNotificationsService>()); Locator.CurrentMutable.RegisterLazySingleton( () => new ImgurService(), typeof(IImgurService)); var features = Mvx.Resolve <IFeaturesService>(); var purchaseService = Mvx.Resolve <IInAppPurchaseService>(); purchaseService.ThrownExceptions.Subscribe(ex => { var error = new Core.UserError("Error Purchasing", ex.Message); Core.Interactions.Errors.Handle(error).Subscribe(); }); Core.Interactions.Errors.RegisterHandler(interaction => { var error = interaction.Input; AlertDialogService.ShowAlert(error.Title, error.Message); interaction.SetOutput(System.Reactive.Unit.Default); }); #if DEBUG features.ActivateProDirect(); #endif //options = new NSDictionary (UIApplication.LaunchOptionsRemoteNotificationKey, //new NSDictionary ("r", "octokit/octokit.net", "i", "739", "u", "thedillonb")); if (options != null) { if (options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey)) { var remoteNotification = options[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary; if (remoteNotification != null) { HandleNotification(remoteNotification, true); } } } // Set the client constructor GitHubSharp.Client.ClientConstructor = () => new HttpClient(new CustomHttpMessageHandler()); if (!Core.Settings.HasSeenWelcome) { Core.Settings.HasSeenWelcome = true; var welcomeViewController = new ViewControllers.Walkthrough.WelcomePageViewController(); welcomeViewController.WantsToDimiss += GoToStartupView; TransitionToViewController(welcomeViewController); } else { GoToStartupView(); } Window.MakeKeyAndVisible(); // Notifications don't work on teh simulator so don't bother if (Runtime.Arch != Arch.SIMULATOR && features.IsProEnabled) { RegisterUserForNotifications(); } return(true); }