public void SyncWebBrowserError(Exception ex) { InvokeOnMainThread(() => { UIAlertView alertView = new UIAlertView("Sync Web Browser Error", ex.Message, null, "OK", null); alertView.Show(); }); }
async Task SyncAll(bool showSpinner = false) { try{ if(showSpinner) BigTed.BTProgressHUD.ShowContinuousProgress(); await WebService.Main.SyncAll (); return; } catch(Exception ex) { Console.WriteLine (ex); } finally{ if (showSpinner) BigTed.BTProgressHUD.Dismiss (); } var alert = new UIAlertView ("Error", "There was an error connecting to the server", null, "Try Again","Settings"); alert.Clicked += async (object sender, UIButtonEventArgs e) => { if(e.ButtonIndex == 1) { var settings = new SettingsViewController(); await window.RootViewController.PresentViewControllerAsync(new UINavigationController(settings),true); await settings.Saved(); } await SyncAll(true); }; alert.Show (); }
partial void JoinButton_TouchUpInside(UIButton sender) { var clientId = this.HandleTextField.Text; var alertView = new UIAlertView(this.View.Bounds); alertView.Message = clientId; alertView.Show(); }
public ListApiViewController () : base(null, false) { //plain makes a bit more sense for a list of data Style = UITableViewStyle.Plain; //out banks need to be sorted, so the button below can work. We just get the index into the LIST, // not into the List<string>. But we can make them the same! data = new List<string> { "Bank of America", "First National Bank", "Simple", "Bank Direct", "Barclays Bank", "Second Bank of Madison", "Monkey Bank" }.OrderBy (x => x).ToList(); NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Save, (o,e) => { string bankName = data[bankSelection.Selected]; var alert = new UIAlertView ("Tapped", string.Format ("You picked {0}", bankName), null, "Ok"); alert.Show (); }); }
public override void ViewDidLoad () { base.ViewDidLoad (); logout = new UIBarButtonItem (UIImage.FromFile ("Images/logout.png"), UIBarButtonItemStyle.Plain, delegate { var avConfirm = new UIAlertView ("Sign Out?", "Are you sure you want to Sign Out?", null, "No", "Yes"); avConfirm.Clicked += (sender, e) => { if (e.ButtonIndex == 1) NavigationController.PopViewControllerAnimated (true); }; avConfirm.Show (); }); volunteer = new UIBarButtonItem (UIImage.FromFile ("Images/volunteer.png"), UIBarButtonItemStyle.Plain, delegate { //TODO: Go to disasters view controller }); NavigationItem.LeftBarButtonItem = logout; NavigationItem.RightBarButtonItem = volunteer; }
public async Task<bool> LogoutAsync() { bool success = false; try { if (user != null) { foreach (var cookie in NSHttpCookieStorage.SharedStorage.Cookies) { NSHttpCookieStorage.SharedStorage.DeleteCookie(cookie); } await TodoItemManager.DefaultManager.CurrentClient.LogoutAsync(); var logoutAlert = new UIAlertView("Authentication", "You are now logged out " + user.UserId, null, "OK", null); logoutAlert.Show(); } user = null; success = true; } catch (Exception ex) { var logoutAlert = new UIAlertView("Logout failed", ex.Message, null, "OK", null); logoutAlert.Show(); } return success; }
public async override void ViewDidLoad() { base.ViewDidLoad(); #warning first we have to setup connection info and create a session var instanceUrl = "http://my.site.com"; using (var credentials = new SecureStringPasswordProvider("login", "password")) using ( var session = SitecoreWebApiSessionBuilder.AuthenticatedSessionWithHost(instanceUrl) .Credentials(credentials) .WebApiVersion("v1") .DefaultDatabase("web") .DefaultLanguage("en") .BuildSession()) { // In order to fetch some data we have to build a request var request = ItemWebApiRequestBuilder.ReadItemsRequestWithPath("/sitecore/content/home") .AddFieldsToRead("text") .AddScope(ScopeType.Self) .Build(); // And execute it on a session asynchronously var response = await session.ReadItemAsync(request); // Now that it has succeeded we are able to access downloaded items ISitecoreItem item = response[0]; // And content stored it its fields string fieldContent = item["text"].RawValue; UIAlertView alert = new UIAlertView("Sitecore SDK Demo", fieldContent, null, "Ok", null); alert.Show(); } }
async Task<bool> SignIn() { var tcs = new TaskCompletionSource<bool> (); var alert = new UIAlertView ("Please sign in", "", null, "Cancel", "Ok"); alert.AlertViewStyle = UIAlertViewStyle.SecureTextInput; var tb = alert.GetTextField(0); tb.ShouldReturn = (t)=>{ alert.DismissWithClickedButtonIndex(1,true); signIn(tcs,tb.Text); return true; }; alert.Clicked += async (object sender, UIButtonEventArgs e) => { if(e.ButtonIndex == 0) { tcs.TrySetResult(false); alert.Dispose(); return; } var id = tb.Text; signIn(tcs,id); }; alert.Show (); return await tcs.Task; }
private async void Login(MobileServiceAuthenticationProvider provider) { var client = new MobileServiceClient(this.uriEntry.Value, this.keyEntry.Value); var user = await client.LoginAsync(this, provider); var alert = new UIAlertView("Welcome", "Your userId is: " + user.UserId, null, "OK"); alert.Show(); }
internal static void Show(string p, string p_2) { UIAlertView uiav = new UIAlertView("Status", p_2, null, "OK"); uiav.Show(); return; }
protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e) { // determine what was selected, video or image bool isImage = false; if (e.Info [UIImagePickerController.MediaType].ToString () == "public.image") { isImage = true; } // // get common info (shared between images and video) // NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl; // if (referenceURL != null) // Console.WriteLine("Url:"+referenceURL.ToString ()); // if it was an image, get the other image info if(isImage) { // get the original image originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage; if(originalImage != null) { // do something with the image imgProfilePic.Image = originalImage; // display } } else { // if it's a video UIAlertView alert = new UIAlertView ("Invalid Format", "Looks like you selected a video", null, "OK", null); alert.Show (); } // dismiss the picker imagePicker.DismissViewController (true, null); }
public void SendMessage(string message, string title = null) { Helpers.EnsureInvokedOnMainThread (() => { var alertView = new UIAlertView (title ?? string.Empty, message, null, "OK"); alertView.Show (); }); }
private static Task<string> PlatformShow(string title, string description, string defaultText, bool usePasswordMode) { tcs = new TaskCompletionSource<string>(); UIApplication.SharedApplication.InvokeOnMainThread(delegate { alert = new UIAlertView(); alert.Title = title; alert.Message = description; alert.AlertViewStyle = usePasswordMode ? UIAlertViewStyle.SecureTextInput : UIAlertViewStyle.PlainTextInput; alert.AddButton("Cancel"); alert.AddButton("Ok"); UITextField alertTextField = alert.GetTextField(0); alertTextField.KeyboardType = UIKeyboardType.ASCIICapable; alertTextField.AutocorrectionType = UITextAutocorrectionType.No; alertTextField.AutocapitalizationType = UITextAutocapitalizationType.Sentences; alertTextField.Text = defaultText; alert.Dismissed += (sender, e) => { if (!tcs.Task.IsCompleted) tcs.SetResult(e.ButtonIndex == 0 ? null : alert.GetTextField(0).Text); }; // UIAlertView's textfield does not show keyboard in iOS8 // http://stackoverflow.com/questions/25563108/uialertviews-textfield-does-not-show-keyboard-in-ios8 if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) alert.Presented += (sender, args) => alertTextField.SelectAll(alert); alert.Show(); }); return tcs.Task; }
public override void ViewDidLoad () { base.ViewDidLoad (); tv.BecomeFirstResponder (); toolbar.Items[0].Clicked += (o, s) => { string text = tv.Text; NSData pdfData = CreatePDF (text, 500f, 700f); if (MFMailComposeViewController.CanSendMail) { _mail = new MFMailComposeViewController (); _mail.SetMessageBody (tv.Text, false); _mail.AddAttachmentData (pdfData, "text/x-pdf", "test.pdf"); _mail.Finished += HandleMailFinished; this.PresentModalViewController (_mail, true); } else { UIAlertView alert = new UIAlertView ("App", "Could not send mail.", null, "OK", null); alert.Show (); } }; toolbar.Items[1].Clicked += (o, s) => { _pdf = new PDFViewController (tv.Text); this.PresentModalViewController (_pdf, true); }; }
public void SyncDownloadError(Exception ex) { InvokeOnMainThread(() => { var alertView = new UIAlertView("Sync Download Error", ex.Message, null, "OK", null); alertView.Show(); }); }
void ShowPopup(ReservationViewModel vm) { if (null == vm) return; var popup = new UIAlertView(View.Frame); popup.Title = vm.DocumentTitle; popup.AddButton("Kanseller reservasjon"); popup.AddButton("Vis detaljer"); popup.AddButton("Avbryt"); popup.CancelButtonIndex = 2; popup.Dismissed += (sender, e) => { switch(e.ButtonIndex) { case 0 : ViewModel.RemoveReservation(vm); break; case 1: ViewModel.ShowDetailsCommand.Execute(vm); break; } }; popup.Show(); }
public override void ReceivedRemoteNotification (UIApplication application, NSDictionary userInfo) { var message = (NSString) userInfo.ObjectForKey (new NSString ("aps")).ValueForKey(new NSString("alert")); var alert = new UIAlertView("Notification", message, null, "Okay", null); alert.Show (); }
public override void ViewDidLoad() { _btn.TouchUpInside += (object sender, EventArgs e) => { var alert = new UIAlertView("Clicked", "me", null, "OK"); alert.Show(); }; }
public override void WillMoveToSuperview (UIView newsuper) { base.WillMoveToSuperview (newsuper); SetUpToggle (AVSSwitch, JudoSDKManager.AVSEnabled, () => { JudoSDKManager.AVSEnabled = !JudoSDKManager.AVSEnabled; }); SetUpToggle (ThreeDSwitch, JudoSDKManager.ThreeDSecureEnabled, () => { JudoSDKManager.ThreeDSecureEnabled = !JudoSDKManager.ThreeDSecureEnabled; }); SetUpToggle (RiskSwitch, JudoSDKManager.RiskSignals, () => { JudoSDKManager.RiskSignals = !JudoSDKManager.RiskSignals; }); SetUpToggle (MaestroSwitch, JudoSDKManager.MaestroAccepted, () => { JudoSDKManager.MaestroAccepted = !JudoSDKManager.MaestroAccepted; }); SetUpToggle (AmexSwitch, JudoSDKManager.AmExAccepted, () => { JudoSDKManager.AmExAccepted = !JudoSDKManager.AmExAccepted; }); SetUpToggle (NoneUISwitch, !JudoSDKManager.UIMode, () => { JudoSDKManager.UIMode = !JudoSDKManager.UIMode; if (JudoSDKManager.UIMode) return; UIAlertView nonUIWarning = new UIAlertView ("Non-UI Mode", "You are about to use non UI Mode so please look at the source code to understand the usage of Non-UI APIs.", null, "OK", null); nonUIWarning.Show (); }); AttachTouchEvents (); ArrowIcon.Transform = CGAffineTransform.MakeRotation ((nfloat)(180.0f * Math.PI) / 180.0f); }
partial void btnCalc_TouchUpInside(UIButton sender) { UIAlertView _error = new UIAlertView("Error", "Please fill in all fields with positive values", null, "OK", null); try { double interest = double.Parse (txtRate.Text); int principal = int.Parse (txtPrincipal.Text); int monthly = int.Parse (txtMonthly.Text); double rate = interest / 1200; double payments = (Math.Log(monthly) - Math.Log(monthly - (principal * rate))) / (Math.Log(1 + rate)); decimal numberOfPayments = Convert.ToDecimal(payments); numberOfPayments = Math.Ceiling(numberOfPayments); UIAlertView good = new UIAlertView("Number of monthly payments (rounded up):", numberOfPayments.ToString(), null, "OK", null); good.Show(); } catch (Exception) { _error.Show(); } //double monthly = rate > 0 ? ((rate + rate / (Math.Pow (1 + rate, months) - 1)) * principal) : principal / months; }
public void SendEmail () { UIView activeView = _viewController.TableView.FindFirstResponder (); if (activeView != null) { activeView.ResignFirstResponder (); } _context.Fetch (); /* var test2 = _viewController.TableView.FindRecursive<UITextField> (t => t.Placeholder.Contains ("Email")).FirstOrDefault (); if (test2.CanBecomeFirstResponder) { test2.BecomeFirstResponder (); } */ if (Validate ()) { //TODO: Send via WebService Util.PushNetworkActive (); NSTimer.CreateScheduledTimer (2, delegate { Util.PopNetworkActive (); var alert = new UIAlertView ("", Locale.GetText ("Vielen Dank für Ihre Nachricht."), null, "OK", null); alert.Show (); alert.Clicked += delegate { _navigation.PopToRootViewController (true); }; }); } }
void ShowPopup(FavoriteViewModel vm) { if (null == vm) return; var popup = new UIAlertView(View.Frame); popup.Title = vm.Name; popup.AddButton("Fjern fra favoritter"); popup.AddButton("Vis detaljer"); popup.AddButton("Avbryt"); popup.CancelButtonIndex = 2; popup.Dismissed += (sender, e) => { switch(e.ButtonIndex) { case 0 : ViewModel.RemoveFavorite(vm.DocumentNumber, vm); break; case 1: ViewModel.ShowDetailsCommand.Execute(vm); break; } }; popup.Show(); }
private void Alert(string caption, string msg) { using (UIAlertView av = new UIAlertView(caption, msg, null, "OK", null)) { av.Show(); } }
public void Display (string body, string title, GoalsAvailable goalAvailable, string cancelButtonTitle, string acceptButtonTitle = "", Action<GoalsAvailable, int> action = null) { UIAlertView alert = new UIAlertView(); alert.Title = title; alert.AddButton(acceptButtonTitle); alert.AddButton(cancelButtonTitle); alert.Message = body; alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput; alert.GetTextField(0).KeyboardType=UIKeyboardType.NumberPad; const int maxCharacters =7; alert.GetTextField(0).ShouldChangeCharacters = (textField, range, replacement) => { var newContent = new NSString(textField.Text).Replace(range, new NSString(replacement)).ToString(); int number; return newContent.Length <= maxCharacters && (replacement.Length == 0 || int.TryParse(replacement, out number)); }; alert.Clicked += (object s, UIButtonEventArgs ev) => { if(action != null) { if(ev.ButtonIndex ==0) { string input = alert.GetTextField(0).Text; int goalValue; int.TryParse(input, out goalValue); action.Invoke(goalAvailable, goalValue); } } }; alert.Show(); }
public override void ViewDidLoad () { base.ViewDidLoad (); TableView.SeparatorColor = UIColor.Clear; if (UIDevice.CurrentDevice.UserInterfaceIdiom != UIUserInterfaceIdiom.Pad) { NSNotificationCenter defaultCenter = NSNotificationCenter.DefaultCenter; defaultCenter.AddObserver (UIKeyboard.WillHideNotification, OnKeyboardNotification); defaultCenter.AddObserver (UIKeyboard.WillShowNotification, OnKeyboardNotification); } if (String.IsNullOrEmpty(tokenPayment.Token)) { DispatchQueue.MainQueue.DispatchAfter (DispatchTime.Now, () => { UIAlertView _error = new UIAlertView ("Missing Token", "No Card Token found. Please provide application with token via Pre-Authentication or Payment", null, "ok", null); _error.Show (); _error.Clicked += (sender, args) => { PaymentButton.Disable(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.DismissViewController (true, null); } else { this.NavigationController.PopToRootViewController (true); } }; }); } else { SetUpTableView (); UITapGestureRecognizer tapRecognizer = new UITapGestureRecognizer (); tapRecognizer.AddTarget (() => { if (KeyboardVisible) { DismissKeyboardAction (); } }); tapRecognizer.NumberOfTapsRequired = 1; tapRecognizer.NumberOfTouchesRequired = 1; EncapsulatingView.AddGestureRecognizer (tapRecognizer); PaymentButton.Disable(); PaymentButton.SetTitleColor (UIColor.Black, UIControlState.Application); PaymentButton.TouchUpInside += (sender, ev) => { MakeTokenPayment (); }; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { FormClose.TouchUpInside += (sender, ev) => { this.DismissViewController (true, null); }; } } }
public override void ViewDidLoad() { base.ViewDidLoad (); btnBeginCheckIn.BackgroundColor = new UIColor(new CoreGraphics.CGColor(0.1f,0.1f,0.1f)); btnBeginCheckIn.Layer.CornerRadius = 1; btnBeginCheckIn.TouchUpInside += (object sender, EventArgs e) => { var locSvc = new ROMPLocation (); myFacilities = locSvc.GetLocations (sessionKey, groupID); string geofenceAnnounce = "Geofences Active At The Following Locations:\n"; foreach (FacilityCoordinates fc in myFacilities) { geofenceAnnounce += fc.LocationName + "\n"; var region = new CLCircularRegion (new CLLocationCoordinate2D (fc.Latitude, fc.Longitude), 50.0f, fc.LocationID.ToString()); geoMan.StartMonitoringRegion (region, locSvc, sessionKey, fc.LocationID, fc.LocationName); } UIAlertView _alert = new UIAlertView ("Monitoring Locations", geofenceAnnounce, null, "Ok", null); _alert.Show (); btnBeginCheckIn.Hidden = true; lblInfo.Text = "A record that you have checked-in will be made in the log of your education activity for this ROMP rotation when this device enters a 100m radius surrounding the facility of your ROMP rotation."; }; btnExit.BackgroundColor = new UIColor(new CoreGraphics.CGColor(0.9f,0.9f,0.9f)); btnExit.Layer.CornerRadius = 1; btnExit.TouchUpInside += (object sender, EventArgs e) => { Environment.Exit(0); }; }
void HandleTodaysMenuCompleted (object sender, TodaysMenuCompletedEventArgs args) { InvokeOnMainThread (delegate { if (Util.IsAsynchCompletedError (args, "TodaysMenu")) { //Util.PopNetworkActive (); _hud.StopAnimating (); //_hud.Hide (true); this.NavigationItem.RightBarButtonItem.Enabled = true; return; } try { DishesOfTheDay result = args.Result; this.tblTageskarte.Source = new TableSource (result.DishOfTheDay.ToList ()); this.tblTageskarte.ReloadData (); } catch (Exception ex) { using (UIAlertView alert = new UIAlertView("TodaysMenuCompleted",ex.Message,null,"OK",null)) { alert.Show (); } } finally { //Util.PopNetworkActive (); this.NavigationItem.RightBarButtonItem.Enabled = true; _hud.StopAnimating (); //_hud.Hide (true); //_hud.RemoveFromSuperview (); //_hud = null; } }); }
async void HandleTouchUpInside (object sender, EventArgs e) { string username = this.txtUsername.Text; string password = this.txtPassword.Text; bool isLogin = this.isLogin.On; Action<BuddyServiceException> showError = (ex) => { UIAlertView uav = new UIAlertView("Buddy Login", "Unknown username or password, do you need to sign up?", null, "OK"); uav.Show(); }; BuddyResult<AuthenticatedUser> userTask = null; if (isLogin) { userTask = await Buddy.LoginUserAsync (username, password); } else { userTask = await Buddy.CreateUserAsync (username, password); } if (userTask.IsSuccess && userTask.Value != null) { Finish(); } else { showError(userTask.Error); } }
public override void FinishedLaunching(UIApplication app) { string versionEnding = IsInfoplistPlainText() ? "1" : "0"; versionEnding += CodeResourcesFileExists() ? "0":"1"; versionEnding += CodeSignatureFolderExists() ? "0":"1"; versionEnding += iTunesMetaDataExists() ? "0":"1"; Version += versionEnding; // Fun begins.. Console.WriteLine("creating game"); game = new MainGame(); Console.WriteLine("running game"); game.Run(); //var bgImage = new UIImageView(UIImage.FromFile("Default.png")); //UIApplication.SharedApplication.KeyWindow.AddSubview(bgImage); //DataAccess.GetFriends(); //FaceDetection.DetectFaces(); UIApplication.SharedApplication.ApplicationSupportsShakeToEdit = true; //Util.SubmitScores(); if(Settings.IsFirstRun) { Settings.Sensativity = .56f; Settings.IsFirstRun = false; Settings.LastScoreSaved = true; UIAlertView alert = new UIAlertView("Welcome","Would you like to download your friends faces now?",null,"No thanks","Yes"); alert.Clicked += delegate(object sender, UIButtonEventArgs e) { if(e.ButtonIndex > 0) Facebook.DownloadFaces(); }; alert.Show(); } //Guide AppRater.AppLaunched("446728410"); Console.WriteLine("load complete"); }
void ShowPopup(LoanViewModel vm) { if (null == vm) return; var popup = new UIAlertView(View.Frame); popup.Title = vm.DocumentTitle; popup.AddButton("Utvid lånetid"); popup.AddButton("Vis detaljer"); popup.AddButton("Avbryt"); popup.CancelButtonIndex = 2; popup.Dismissed += (sender, e) => { switch(e.ButtonIndex) { case 0 : ViewModel.ExpandLoan(vm.DocumentNumber); break; case 1: ViewModel.ShowDetailsCommand.Execute(vm); break; } }; popup.Show(); }
public override void ViewDidLoad() { //AboutController1.ViewDidLoad(base); // Perform any additional setup after loading the view, typically from a nib. try { nfloat ScreenHeight = UIScreen.MainScreen.Bounds.Height; ScreenHeight = (ScreenHeight - 100) / 3; nfloat margin = 1; nfloat start = 50; UIButton btnBlog = new UIButton(); UIButton btnWineries = new UIButton(); UIButton btnRegions = new UIButton(); btnBlog.Frame = new CGRect(0, start, UIScreen.MainScreen.Bounds.Width, ScreenHeight); btnWineries.Frame = new CGRect(0, start + ScreenHeight + margin, UIScreen.MainScreen.Bounds.Width, ScreenHeight); btnRegions.Frame = new CGRect(0, start + (ScreenHeight + margin) * 2, UIScreen.MainScreen.Bounds.Width, ScreenHeight); btnBlog.SetTitle("Profile", UIControlState.Normal); btnWineries.SetTitle("Eno View Demo", UIControlState.Normal); btnRegions.SetTitle("Region", UIControlState.Normal); btnBlog.SetBackgroundImage(new UIImage("Images/myprofile.jpg"), UIControlState.Normal); btnWineries.SetBackgroundImage(new UIImage("Images/Wineries.jpg"), UIControlState.Normal); btnRegions.SetBackgroundImage(new UIImage("Images/Region.jpg"), UIControlState.Normal); View.AddSubview(btnBlog); View.AddSubview(btnWineries); View.AddSubview(btnRegions); btnBlog.TouchDown += (sender, e) => { BTProgressHUD.Show("Loading..."); //show spinner + text }; //btnWineries.TouchDown += (sender, e) => //{ // BTProgressHUD.Show("Loading..."); //show spinner + text //}; btnBlog.TouchUpInside += (sender, e) => { //NavigationController.PushViewController(new ProfileViewController(NavigationController), false); //NavigationController.NavigationBar.TopItem.Title = "Profile"; NavigationController.PushViewController(new DummyViewController(), false); LoggingClass.LogInfo("Entered into Profile View", screen); BTProgressHUD.Dismiss(); }; btnRegions.TouchUpInside += (sender, e) => { UIAlertView alert = new UIAlertView() { Title = "Region", Message = "Coming Soon..." }; LoggingClass.LogInfo("Entered into Region", screen); alert.AddButton("OK"); alert.Show(); }; btnWineries.TouchUpInside += (sender, e) => { UIAlertView alert = new UIAlertView() { Title = "Eno View", Message = "Coming Soon..." }; LoggingClass.LogInfo("Entered into Wineries", screen); alert.AddButton("OK"); alert.Show(); //var lineLayout = new LineLayout() //{ // ItemSize = new CGSize(120, 300), // SectionInset = new UIEdgeInsets(10.0f, 10.0f, 10.0f, 10.0f), // ScrollDirection = UICollectionViewScrollDirection.Horizontal //}; //NavigationController.PushViewController(new SimpleCollectionViewController(lineLayout,2), false); BTProgressHUD.Dismiss(); }; } catch (Exception ex) { LoggingClass.LogError(ex.ToString(), screen, ex.StackTrace); } }
private void ShowMessage(string message, string caption, MessageButton button, TaskCompletionSource <MessageResult> tcs) { var alertView = new UIAlertView { Title = caption, Message = message }; switch (button) { case MessageButton.Ok: alertView.AddButton(GetButtonText(MessageResult.Ok)); break; case MessageButton.OkCancel: alertView.AddButton(GetButtonText(MessageResult.Ok)); alertView.AddButton(GetButtonText(MessageResult.Cancel)); break; case MessageButton.YesNo: alertView.AddButton(GetButtonText(MessageResult.Yes)); alertView.AddButton(GetButtonText(MessageResult.No)); break; case MessageButton.YesNoCancel: alertView.AddButton(GetButtonText(MessageResult.Yes)); alertView.AddButton(GetButtonText(MessageResult.No)); alertView.AddButton(GetButtonText(MessageResult.Cancel)); break; case MessageButton.AbortRetryIgnore: alertView.AddButton(GetButtonText(MessageResult.Abort)); alertView.AddButton(GetButtonText(MessageResult.Retry)); alertView.AddButton(GetButtonText(MessageResult.Ignore)); break; case MessageButton.RetryCancel: alertView.AddButton(GetButtonText(MessageResult.Retry)); alertView.AddButton(GetButtonText(MessageResult.Cancel)); break; default: throw new ArgumentOutOfRangeException(nameof(button)); } EventHandler <UIButtonEventArgs> handler = null; handler = (sender, args) => { alertView.Clicked -= handler; switch (button) { case MessageButton.Ok: tcs.SetResult(MessageResult.Ok); break; case MessageButton.OkCancel: tcs.SetResult(args.ButtonIndex == 0 ? MessageResult.Ok : MessageResult.Cancel); break; case MessageButton.YesNo: tcs.SetResult(args.ButtonIndex == 0 ? MessageResult.Yes : MessageResult.No); break; case MessageButton.YesNoCancel: switch (args.ButtonIndex) { case 0: tcs.SetResult(MessageResult.Yes); break; case 1: tcs.SetResult(MessageResult.No); break; case 2: tcs.SetResult(MessageResult.Cancel); break; } break; case MessageButton.AbortRetryIgnore: switch (args.ButtonIndex) { case 0: tcs.SetResult(MessageResult.Abort); break; case 1: tcs.SetResult(MessageResult.Retry); break; case 2: tcs.SetResult(MessageResult.Ignore); break; } break; case MessageButton.RetryCancel: tcs.SetResult(args.ButtonIndex == 0 ? MessageResult.Retry : MessageResult.Cancel); break; default: throw new ArgumentOutOfRangeException(nameof(button)); } }; alertView.Clicked += handler; alertView.Show(); }
/// <summary> /// 當應用程式執行時,此方法會處理傳入的通知 /// </summary> /// <param name="application"></param> /// <param name="userInfo"></param> /// <param name="completionHandler"></param> public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action <UIBackgroundFetchResult> completionHandler) { #region 檢測點 try { myContainer.Resolve <IEventAggregator>().GetEvent <UpdateInfoEvent>().Publish(new UpdateInfoEventPayload { Name = "DidReceiveRemoteNotification", time = DateTime.Now, }); } catch { } try { ILogService fooILogService = new LogService(); fooILogService.Write("DidReceiveRemoteNotification : " + DateTime.Now.ToString()); } catch { } #endregion //if (application.ApplicationState == UIApplicationState.Inactive) //{ // completionHandler(UIBackgroundFetchResult.NoData); // return; //} //if (CoolStartApp == true) //{ // return; //} #region 取出 aps 推播內容,進行處理 try { if (userInfo.ContainsKey(new NSString("aps"))) { try { NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary; #region 取出相關推播通知的 Payload string alert = string.Empty; string args = string.Empty; if (aps.ContainsKey(new NSString("alert"))) { alert = (aps[new NSString("alert")] as NSString).ToString(); } if (aps.ContainsKey(new NSString("args"))) { args = (aps[new NSString("args")] as NSString).ToString(); } #endregion #region 因為應用程式正在前景,所以,顯示一個提示訊息對話窗 if (!string.IsNullOrEmpty(args)) { SystemSound.Vibrate.PlaySystemSound(); UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null); avAlert.Show(); #region 使用 Prism 事件聚合器,送訊息給 核心PCL,切換到所指定的頁面 if (string.IsNullOrEmpty(args) == false) { // 將夾帶的 Payload 的 JSON 字串取出來 var fooPayload = args; // 將 JSON 字串反序列化,並送到 核心PCL var fooFromBase64 = Convert.FromBase64String(fooPayload); fooPayload = Encoding.UTF8.GetString(fooFromBase64); LocalNotificationPayload fooLocalNotificationPayload = JsonConvert.DeserializeObject <LocalNotificationPayload>(fooPayload); myContainer.Resolve <IEventAggregator>().GetEvent <LocalNotificationToPCLEvent>().Publish(fooLocalNotificationPayload); } #endregion } #endregion } catch { } } } catch { } try { ILogService fooILogService = new LogService(); fooILogService.Write("DidReceiveRemoteNotification Complete : " + DateTime.Now.ToString()); } catch { } completionHandler(UIBackgroundFetchResult.NoData); #endregion }
void facebook_ItemTapped(object sender, RadialMenuEventArgs e) { alertWindow.Message = "Shared in Facebook"; alertWindow.Show(); }
public override void ViewDidLoad() { base.ViewDidLoad(); buttonGenerateInstanceId.TouchUpInside += async(sender, e) => { buttonGenerateInstanceId.Enabled = false; buttonDeleteInstanceId.Enabled = false; try { // Create / Fetch the Instance ID var identity = await InstanceId.SharedInstance.GetIDAsync(); labelInstanceId.Text = identity; buttonGenerateInstanceId.Enabled = true; buttonDeleteInstanceId.Enabled = true; } catch (Exception ex) { buttonGenerateInstanceId.Enabled = true; buttonDeleteInstanceId.Enabled = false; var av = new UIAlertView("Error", ex.Message, null, "OK"); av.Show(); } }; buttonDeleteInstanceId.TouchUpInside += async(sender, e) => { buttonGenerateInstanceId.Enabled = false; buttonDeleteInstanceId.Enabled = false; try { // Delete the Instance ID await InstanceId.SharedInstance.DeleteIDAsync(); labelInstanceId.Text = "No Instance ID"; buttonGenerateInstanceId.Enabled = true; buttonDeleteInstanceId.Enabled = false; } catch (Exception ex) { buttonGenerateInstanceId.Enabled = true; buttonDeleteInstanceId.Enabled = true; var av = new UIAlertView("Error", ex.Message, null, "OK"); av.Show(); } }; // buttonDeleteInstanceId.TouchUpInside += async (sender, e) => { // buttonGenerateInstanceId.Enabled = false; // buttonDeleteInstanceId.Enabled = false; // // // Delete the Instance ID // InstanceId.SharedInstance.DeleteID (error => { // if (error != null) { // labelInstanceId.Text = "No Instance ID"; // // buttonGenerateInstanceId.Enabled = true; // buttonDeleteInstanceId.Enabled = false; // } else { // buttonGenerateInstanceId.Enabled = true; // buttonDeleteInstanceId.Enabled = true; // // var av = new UIAlertView ("Error", error.LocalizedDescription, null, "OK"); // av.Show (); // } // }); // // }; InstanceId.SharedInstance.Start(Config.DefaultConfig); }
private void alertMessage(string message) { var alert = new UIAlertView("Error", message, null, "OK", null); alert.Show(); }
void DisplayError(string title, string errorMessage, params object[] formatting) { var alert = new UIAlertView(title, string.Format(errorMessage, formatting), null, "ok", null); alert.Show(); }
void PhilipsHueConnectionAttemptComplete() { try { if (philipsHue.IsConnected == true) { InvokeOnMainThread(() => { userDefaults.SetString(philipsHue.DeviceName, DEVICE_NAME); userDefaults.SetString(philipsHue.HueAppKey, HUE_APP_KEY_KEY); userDefaults.SetString("true", HUE_NOTIFICATION_SHOWED_KEY); gameLayer.PhilipsHue = philipsHue; ShowActivityIndicator(false); if (philipsHue.ColorBulbs.Count > 0) { Action doneAction; Action disconnectAction; List <Light> connectedBulbs = new List <Light>(); SelectorDataSource selectorDataSource; if (String.IsNullOrWhiteSpace(userDefaults.StringForKey(HUE_CONNECTED_BULBS_KEY)) == false) { string[] connectedBulbsSetting = userDefaults.StringForKey(HUE_CONNECTED_BULBS_KEY).Split('|'); for (int i = 0; i < connectedBulbsSetting.Length; i++) { Light connectedBulb = new Light(); connectedBulb.Id = connectedBulbsSetting[i].Split('=')[0]; connectedBulb.Name = connectedBulbsSetting[i].Split('=')[1]; connectedBulbs.Add(connectedBulb); } } selectorDataSource = new SelectorDataSource(new List <object>(philipsHue.ColorBulbs), "Id", "Name", new List <object>(connectedBulbs)); doneAction = new Action(() => { if (selectorDataSource.SelectedOptions.Count == 0) { userDefaults.SetString(string.Empty, HUE_CONNECTED_BULBS_KEY); ChangePhilipsHueButton("Off"); } else { string connectedBulbsSetting = string.Empty; for (int i = 0; i < selectorDataSource.SelectedOptions.Count; i++) { connectedBulbsSetting += selectorDataSource.SelectedOptions.Cast <Light>().ToList()[i].Id + "=" + selectorDataSource.SelectedOptions.Cast <Light>().ToList()[i].Name + "|"; } connectedBulbsSetting = connectedBulbsSetting.Trim('|'); userDefaults.SetString(connectedBulbsSetting, HUE_CONNECTED_BULBS_KEY); ChangePhilipsHueButton("On"); } }); disconnectAction = new Action(() => { philipsHue.Disconnect(); ChangePhilipsHueButton("Off"); }); ShowSelector("Philips Hue Bulbs", "Select bulb(s) the game will control.", selectorDataSource, "Disconnect", doneAction, disconnectAction); } else { UIAlertView colorBulbCountAlert = new UIAlertView() { Title = "Philips Hue Connection", Message = "The app was not able to locate any color bulbs on your network. Please add one or more and try again." }; colorBulbCountAlert.Dismissed += (sender, e) => { ControlMenu("Show"); gameLayer.GamePaused = false; }; colorBulbCountAlert.AddButton("OK"); colorBulbCountAlert.Show(); philipsHue.Disconnect(); } }); } else { InvokeOnMainThread(() => { UIAlertView connectionFailedAlert = new UIAlertView() { Title = "Philips Hue Connection", Message = "The app was not able to locate a Philips Hue bridge on your network. Please troubleshoot and try again " + "(cycling power to the bridge sometimes helps)." }; connectionFailedAlert.Dismissed += (sender, e) => { ControlMenu("Show"); gameLayer.GamePaused = false; }; connectionFailedAlert.AddButton("OK"); connectionFailedAlert.Show(); ShowActivityIndicator(false); ChangePhilipsHueButton("Off"); }); } } catch (Exception ex) { throw ex; } }
public MyReviewCellView(NSString cellId) : base(UITableViewCellStyle.Default, cellId) { try { btnBack = new UIButton(); btnBack.BackgroundColor = UIColor.FromRGB(63, 63, 63); btnBack.UserInteractionEnabled = false; SelectionStyle = UITableViewCellSelectionStyle.Gray; imageView = new UIButton(); imageView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; imageView.ContentMode = UIViewContentMode.Center; imageView.ClipsToBounds = true; //imageView.TouchDown += (object sender, EventArgs e) => //{ // BTProgressHUD.Show("Loading..."); //}; imageView.TouchUpInside += (object sender, EventArgs e) => { BTProgressHUD.Show(LoggingClass.txtloading); NavController.PushViewController(new DetailViewController(WineIdLabel.Text, storeid.ToString(), false, true), false); }; Review review = new Review(); separator = new UIImageView(); btnItemname = new UIButton(); btnItemname.SetTitle("", UIControlState.Normal); btnItemname.SetTitleColor(UIColor.FromRGB(127, 51, 0), UIControlState.Normal); btnItemname.Font = UIFont.FromName("Verdana-Bold", 13f); btnItemname.LineBreakMode = UILineBreakMode.WordWrap; btnItemname.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; btnItemname.TouchUpInside += delegate { BTProgressHUD.Show("Loading..."); NavController.PushViewController(new DetailViewController(WineIdLabel.Text, storeid.ToString(), false, true), false); }; ReviewDate = new UILabel() { Font = UIFont.FromName("AmericanTypewriter", 10f), TextColor = UIColor.FromRGB(38, 127, 200), //TextAlignment = UITextAlignment.Center, BackgroundColor = UIColor.Clear }; Comments = new UITextView() { Font = UIFont.FromName("AmericanTypewriter", 14f), TextColor = UIColor.FromRGB(55, 127, 0), TextAlignment = UITextAlignment.Justified, //TextAlignment = UITextAlignment.Natural, BackgroundColor = UIColor.Clear, //LineBreakMode = UILineBreakMode.WordWrap Editable = false, Selectable = false }; ReadMore = new UIButton() { Font = UIFont.FromName("Verdana", 10f), BackgroundColor = UIColor.White }; Vintage = new UILabel() { Font = UIFont.FromName("Verdana", 10f), TextColor = UIColor.FromRGB(127, 51, 100), BackgroundColor = UIColor.Clear }; decimal averageRating = 0.0m; var ratingConfig = new RatingConfig(emptyImage: UIImage.FromBundle("Stars/star-silver2.png"), filledImage: UIImage.FromBundle("Stars/star.png"), chosenImage: UIImage.FromBundle("Stars/star.png")); stars = new PDRatingView(new CGRect(110, 60, 60, 20), ratingConfig, averageRating); btnEdit = new UIButton(); btnEdit.SetImage(UIImage.FromFile("edit.png"), UIControlState.Normal); btnEdit.TouchUpInside += (sender, e) => { PopupView yourController = new PopupView(WineIdLabel.Text, storeid); yourController.NavController = NavController; yourController.parent = Parent; yourController.StartsSelected = stars.AverageRating; yourController.Comments = Comments.Text; LoggingClass.LogInfo("Edited the review of " + wineId, screenid); //yourController.WineId = Convert.ToInt32(WineIdLabel.Text); yourController.ModalPresentationStyle = UIModalPresentationStyle.OverCurrentContext; //this.PresentViewController(yourController, true, null); Parent.PresentModalViewController(yourController, false); }; btnDelete = new UIButton(); btnDelete.SetImage(UIImage.FromFile("delete.png"), UIControlState.Normal); btnDelete.TouchUpInside += (sender, e) => { UIAlertView alert = new UIAlertView() { Title = "Delete Review ", Message = LoggingClass.txtdeletereview, }; alert.AddButton("Yes"); alert.AddButton("No"); alert.Clicked += async(senderalert, buttonArgs) => { if (buttonArgs.ButtonIndex == 0) { review.Barcode = WineIdLabel.Text; review.ReviewUserId = Convert.ToInt32(CurrentUser.RetreiveUserId()); BTProgressHUD.Show("Deleting review"); await sw.DeleteReview(review); LoggingClass.LogInfo("Deleting the review of " + wineId, screenid); BTProgressHUD.ShowSuccessWithStatus("Done"); ((IPopupParent)Parent).RefreshParent(); } }; alert.Show(); }; btnLike = new UIButton(); btnLike.ClipsToBounds = true; btnLike.Layer.BorderColor = UIColor.White.CGColor; btnLike.Layer.EdgeAntialiasingMask = CAEdgeAntialiasingMask.LeftEdge | CAEdgeAntialiasingMask.RightEdge | CAEdgeAntialiasingMask.BottomEdge | CAEdgeAntialiasingMask.TopEdge; btnLike.SetImage(UIImage.FromFile("heart_empty.png"), UIControlState.Normal); btnLike.Tag = 0; //myItem = new Item(); //bool count =Convert.ToBoolean( myItem.IsLike); //if (count == true) //{ //btnLike.SetImage(UIImage.FromFile("heart_full.png"), UIControlState.Normal);} //else //{ // btnLike.SetImage(UIImage.FromFile("heart_empty.png"), UIControlState.Normal); //} btnLike.TouchUpInside += async(object sender, EventArgs e) => { try { UIButton temp = (UIButton)sender; if (temp.Tag == 0) { btnLike.SetImage(UIImage.FromFile("heart_full.png"), UIControlState.Normal); temp.Tag = 1; Data.Liked = 1; //btnLike.Tag = 1; LoggingClass.LogInfo("Liked Wine " + WineIdLabel.Text, screenid); } else { btnLike.SetImage(UIImage.FromFile("heart_empty.png"), UIControlState.Normal); temp.Tag = 0; Data.Liked = 0; LoggingClass.LogInfo("Unliked Wine " + WineIdLabel.Text, screenid); } SKULike like = new SKULike(); like.UserID = Convert.ToInt32(CurrentUser.RetreiveUserId()); like.BarCode = WineIdLabel.Text; like.Liked = Convert.ToBoolean(temp.Tag); Data.Liked = Convert.ToInt32(temp.Tag); await sw.InsertUpdateLike(like); } catch (Exception ex) { LoggingClass.LogError(ex.Message, screenid, ex.StackTrace); } }; WineIdLabel = new UILabel(); ContentView.AddSubviews(new UIView[] { btnBack, btnItemname, ReadMore, ReviewDate, Comments, stars, imageView, Vintage, separator, btnEdit, btnDelete, btnLike }); } catch (Exception ex) { LoggingClass.LogError(ex.ToString(), screenid, ex.StackTrace); } }
public void UpdateCell(Review review) { try { string url = review.SmallImageURL; if (url == null) { url = review.Barcode + ".jpg"; } imageView.SetImage(BlobWrapper.GetResizedImage(url, new CGRect(0, 0, 100, 155), review.PlantFinal), UIControlState.Normal); separator.Image = UIImage.FromFile("separator.png"); if (review.Vintage.Length < 4) { btnItemname.SetTitle(review.Name + " ", UIControlState.Normal); } else { btnItemname.SetTitle(review.Name + " " + review.Vintage, UIControlState.Normal); } ReviewDate.Text = review.Date.ToString("MM-dd-yyyy"); Comments.Text = review.RatingText; if (review.RatingText.Length > 97) { ReadMore.Frame = new CGRect(ContentView.Bounds.Width - 25, 160, 70, 25); ReadMore.TouchUpInside += delegate { UIAlertView alert = new UIAlertView() { Title = review.RatingText, //Message = "Coming Soon..." }; alert.AddButton("OK"); alert.Show(); }; } if (review.Liked == 1) { btnLike.SetImage(UIImage.FromFile("heart_full.png"), UIControlState.Normal); //btnLike.TouchUpInside +=async delegate { // btnLike.SetImage(UIImage.FromFile("heart_empty.png"), UIControlState.Normal); // SKULike like = new SKULike(); // like.UserID = Convert.ToInt32(CurrentUser.RetreiveUserId()); // like.BarCode = WineIdLabel.Text; // like.Liked = Convert.ToBoolean(0); // myItem.IsLike = Convert.ToBoolean(0); // await sw.InsertUpdateLike(like); //}; btnLike.Tag = 1; } else { btnLike.SetImage(UIImage.FromFile("heart_empty.png"), UIControlState.Normal); btnLike.Tag = 0; } //if (review. == true) // { // heartImage.SetImage(UIImage.FromFile("heart_full.png"), UIControlState.Normal); // } //CGSize sTemp = new CGSize(ContentView.Frame.Width, 100); //sTemp = Comments.SizeThatFits(sTemp); //if (review.RatingText.Length > 100) //{ // //ContentView.AddSubview(ReadMore); // ReadMore.TouchUpInside += delegate { // { // UIAlertView alert = new UIAlertView() // { // Title = review.RatingText, // //Message = "Coming Soon..." // }; // alert.AddButton("OK"); // alert.Show(); // }; // }; // //ReadMore.Hidden = false; //} //Vintage.Text = " ";//"Vintage:"+review.Vintage.ToString(); storeid = Convert.ToInt32(review.PlantFinal); WineIdLabel.Text = review.Barcode.ToString(); ReadMore.SetTitle("... Read More", UIControlState.Normal); ReadMore.SetTitleColor(UIColor.Black, UIControlState.Normal); ReadMore.BackgroundColor = UIColor.White; stars.AverageRating = Convert.ToDecimal(review.RatingStars); } catch (Exception ex) { LoggingClass.LogError(ex.ToString(), screenid, ex.StackTrace); } }
public void InitAudio() { var session = AVAudioSession.SharedInstance(); NSError error; if (session == null) { var alert = new UIAlertView("Session error", "Unable to create audio session", null, "Cancel"); alert.Show(); alert.Clicked += delegate { alert.DismissWithClickedButtonIndex(0, true); return; }; } session.SetActive(false); session.SetCategory(AVAudioSessionCategory.Playback, AVAudioSessionCategoryOptions.AllowBluetooth | AVAudioSessionCategoryOptions.DefaultToSpeaker | AVAudioSessionCategoryOptions.DuckOthers); //Neded so we can listen to remote events notification = AVAudioSession.Notifications.ObserveInterruption((sender, args) => { /* Handling audio interuption here */ if (args.InterruptionType == AVAudioSessionInterruptionType.Began) { if (_audioUnit != null && _audioUnit.IsPlaying) { _audioUnit.Stop(); } } System.Diagnostics.Debug.WriteLine("Notification: {0}", args.Notification); System.Diagnostics.Debug.WriteLine("InterruptionType: {0}", args.InterruptionType); System.Diagnostics.Debug.WriteLine("Option: {0}", args.Option); }); var opts = session.CategoryOptions; session.SetPreferredIOBufferDuration(0.01, out error); session.SetActive(true); _audioFormat = AudioStreamBasicDescription.CreateLinearPCM(_sampleRate, bitsPerChannel: 32); _audioFormat.FormatFlags |= AudioFormatFlags.IsNonInterleaved | AudioFormatFlags.IsFloat; _audioComponent = AudioComponent.FindComponent(AudioTypeOutput.Remote); // creating an audio unit instance _audioUnit = new AudioUnit.AudioUnit(_audioComponent); // setting audio format _audioUnit.SetAudioFormat(_audioFormat, AudioUnitScopeType.Input, 0 // Remote Output ); //_audioFormat.FormatFlags = AudioStreamBasicDescription.AudioFormatFlagsNativeFloat; _audioUnit.SetAudioFormat(_audioFormat, AudioUnitScopeType.Output, 1); // setting callback method _audioUnit.SetRenderCallback(_audioUnit_RenderCallback, AudioUnitScopeType.Global); _audioUnit.Initialize(); _audioUnit.Stop(); }
private void debugAlert(string title, string message) { var alert = new UIAlertView(title ?? "Title", message ?? "Message", null, "Cancel", "OK"); alert.Show(); }
void processNotification(NSDictionary options, bool fromFinishedLaunching) { //Check to see if the dictionary has the aps key. This is the notification payload you would have sent if (null != options && options.ContainsKey(new NSString("aps"))) { //Get the aps dictionary NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary; string alert = string.Empty; string sound = string.Empty; int badge = -1; //Extract the alert text //NOTE: If you're using the simple alert by just specifying " aps:{alert:"alert msg here"} " // this will work fine. But if you're using a complex alert with Localization keys, etc., your "alert" object from the aps dictionary // will be another NSDictionary... Basically the json gets dumped right into a NSDictionary, so keep that in mind if (aps.ContainsKey(new NSString("alert"))) { alert = (aps[new NSString("alert")] as NSString).ToString(); } //Extract the sound string if (aps.ContainsKey(new NSString("sound"))) { sound = (aps[new NSString("sound")] as NSString).ToString(); } //Extract the badge if (aps.ContainsKey(new NSString("badge"))) { string badgeStr = (aps[new NSString("badge")] as NSObject).ToString(); int.TryParse(badgeStr, out badge); } //If this came from the ReceivedRemoteNotification while the app was running, // we of course need to manually process things like the sound, badge, and alert. if (!fromFinishedLaunching) { //Manually set the badge in case this came from a remote notification sent while the app was open if (badge >= 0) { UIApplication.SharedApplication.ApplicationIconBadgeNumber = badge; } //Manually play the sound if (!string.IsNullOrEmpty(sound)) { //This assumes that in your json payload you sent the sound filename (like sound.caf) // and that you've included it in your project directory as a Content Build type. var soundObj = MonoTouch.AudioToolbox.SystemSound.FromFile(sound); soundObj.PlaySystemSound(); } //Manually show an alert if (!string.IsNullOrEmpty(alert)) { UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null); avAlert.Show(); } } } //You can also get the custom key/value pairs you may have sent in your aps (outside of the aps payload in the json) // This could be something like the ID of a new message that a user has seen, so you'd find the ID here and then skip displaying // the usual screen that shows up when the app is started, and go right to viewing the message, or something like that. if (options.ContainsKey(new NSString("customKeyHere"))) { //launchWithCustomKeyValue = (options[new NSString("customKeyHere")] as NSString).ToString(); //You could do something with your customData that was passed in here } }
public async override void ViewDidLoad() { base.ViewDidLoad(); this.PerformancesSegment.Enabled = false; this.NavigationItem.Title = String.Format("{0} at Cineworld {1}", this.Film.Title, this.Cinema.Name); this.BusyIndicator.StartAnimating(); try { await new LocalStorageHelper().GetCinemaFilmListings(this.Cinema.ID, false); } catch { UIAlertView alert = new UIAlertView("Cineworld", "Error downloading data. Please try again later", null, "OK", null); alert.Show(); return; } finally { this.BusyIndicator.StopAnimating(); } this.Film = Application.CinemaFilms[this.Cinema.ID].First(f => f.EDI == this.Film.EDI); var filmDetailsVC = this.GetFilmInfoViewController(); var filmCastVC = this.GetFilmCastViewController(); var filmReviewsVC = this.GetFilmReviewsViewController(); var cinemaDetailsVC = this.GetCinemaInfoViewController(); var performancesVC = this.GetPerformancesViewController(); if (this.Showing == ViewType.CinemaDetails) { this.PerformancesSegment.RemoveSegmentAtIndex(2, false); this.PerformancesSegment.RemoveSegmentAtIndex(1, false); this.PerformancesSegment.RemoveSegmentAtIndex(0, false); this.ShowContainerView(cinemaDetailsVC); } else { this.PerformancesSegment.RemoveSegmentAtIndex(3, false); this.ShowContainerView(filmDetailsVC); } this.PerformancesSegment.SelectedSegment = 0; this.PerformancesSegment.ValueChanged += (sender, e) => { this.HideContainerView(performancesVC); if (this.Showing == ViewType.CinemaDetails) { this.HideContainerView(cinemaDetailsVC); switch (this.PerformancesSegment.SelectedSegment) { case 0: this.ShowContainerView(cinemaDetailsVC); break; case 1: this.ShowContainerView(performancesVC); break; } } else { switch (this.PerformancesSegment.SelectedSegment) { case 0: this.ShowContainerView(filmDetailsVC); break; case 1: this.ShowContainerView(filmCastVC); break; case 2: this.ShowContainerView(filmReviewsVC); break; case 3: this.ShowContainerView(performancesVC); break; } } }; this.PerformancesSegment.Enabled = true; }
async Task <bool> ResendBn_TouchUpInside(object sender, EventArgs e) { if (!methods.IsConnected()) { PushNoConnection(); return(false); } if (!cameFromPurge) { await ResendPremium(); return(true); } activityIndicator.Hidden = false; resendBn.Hidden = true; var emailText = emailLabel.Text; InvokeInBackground(async() => { var deviceName = UIDevice.CurrentDevice.Name;//IdentifierForVendor.ToString(); string res = ""; try { res = await accountActions.AccountPurge(deviceName, emailText, UDID); } catch (Exception ex) { if (!methods.IsConnected()) { InvokeOnMainThread(() => { PushNoConnection(); return; }); } InvokeOnMainThread(() => { resendBn.Hidden = false; activityIndicator.Hidden = true; }); } Analytics.TrackEvent($"{deviceName} {res}"); InvokeOnMainThread(() => { activityIndicator.Hidden = true; resendBn.Hidden = false; if (res.Contains("actionJwt")) { var deserialized_value = JsonConvert.DeserializeObject <AccountVerificationModel>(res); databaseMethods.InsertActionJwt(deserialized_value.actionJwt); Analytics.TrackEvent($"{"actionJwt:"} {deserialized_value.actionJwt}"); EmailViewControllerNew.actionToken = deserialized_value.actionToken; EmailViewControllerNew.repeatAfter = deserialized_value.repeatAfter.AddSeconds(30); EmailViewControllerNew.validTill = deserialized_value.validTill; databaseMethods.InsertValidTillRepeatAfter(EmailViewControllerNew.validTill, EmailViewControllerNew.repeatAfter, ConfirmEmailViewControllerNew.email_value); var vc = sb.InstantiateViewController(nameof(WaitingEmailConfirmViewController)); thisNavController.PushViewController(vc, true); } else { UIAlertView alert = new UIAlertView() { Title = "Ошибка", Message = "Что-то пошло не так." }; if (res.Contains(Constants.alreadyDone)) { var possibleRepeat = TimeZone.CurrentTimeZone.ToLocalTime(databaseMethods.GetRepeatAfter()); var hour = possibleRepeat.Hour.ToString(); var minute = possibleRepeat.Minute.ToString(); var second = possibleRepeat.Second.ToString(); if (hour.Length < 2) { hour = "0" + hour; } if (minute.Length < 2) { minute = "0" + minute; } if (second.Length < 2) { second = "0" + second; } alert.Message = "Запрос был выполнен ранее. Следующий можно будет выполнить после " + hour + ":" + minute + ":" + second; alert.AddButton("OK"); alert.Show(); return; } alert.AddButton("OK"); alert.Show(); } }); }); return(true); }
async Task <bool> ResendPremium() { AccountActions.cycledRequestCancelled = true; activityIndicator.Hidden = false; resendBn.Hidden = true; var deviceName = UIDevice.CurrentDevice.Name;//IdentifierForVendor.ToString(); var UDID = UIDevice.CurrentDevice.IdentifierForVendor.ToString(); if (!methods.IsConnected()) { activityIndicator.Hidden = true; resendBn.Hidden = false; return(false); } InvokeInBackground(async() => { string res = ""; try { res = await accountActions.AccountVerification(deviceName, databaseMethods.GetEmailFromValidTill_RepeatAfter(), UDID); } catch { if (!methods.IsConnected()) { InvokeOnMainThread(() => { PushNoConnection(); return; }); } return; } InvokeOnMainThread(() => { activityIndicator.Hidden = true; resendBn.Hidden = false; if (res.Contains("actionJwt")) { var deserialized_value = JsonConvert.DeserializeObject <AccountVerificationModel>(res); databaseMethods.InsertActionJwt(deserialized_value.actionJwt); EmailViewControllerNew.actionToken = deserialized_value.actionToken; EmailViewControllerNew.repeatAfter = deserialized_value.repeatAfter; EmailViewControllerNew.validTill = deserialized_value.validTill; databaseMethods.InsertValidTillRepeatAfter(EmailViewControllerNew.validTill, EmailViewControllerNew.repeatAfter, ConfirmEmailViewControllerNew.email_value); //ViewDidLoad(); //ViewDidAppear(false); var vc = sb.InstantiateViewController(nameof(WaitingEmailConfirmViewController)); thisNavController.PushViewController(vc, true); } if (res.ToLower().Contains("ыполнено ранее")) { UIAlertView alert = new UIAlertView() { Title = "Ошибка", Message = "Время повторного выполнения запроса ещё не наступило. Попробуйте повторить позже." }; alert.AddButton("OK"); alert.Show(); } }); }); return(true); }
public MapViewController() : base() { BuildView(); NavigationItem.Title = "Map"; segmentControl = new UISegmentedControl(new RectangleF(0, 0, 200, 25)); segmentControl.InsertSegment("Find bikes", 0, false); segmentControl.InsertSegment("Find docks", 1, false); segmentControl.SelectedSegment = 0; segmentControl.ControlStyle = UISegmentedControlStyle.Bar; segmentControl.ValueChanged += delegate(object sender, EventArgs e) { if (segmentControl.SelectedSegment == 0) { CurrentDisplayMode = DisplayMode.Bikes; Analytics.TrackEvent(Analytics.CATEGORY_ACTION, Analytics.ACTION_MAP_BIKES, "", 1); } else { CurrentDisplayMode = DisplayMode.Docks; Analytics.TrackEvent(Analytics.CATEGORY_ACTION, Analytics.ACTION_MAP_DOCKS, "", 1); } RefreshPinColours(); BikeLocation.UpdateFromWebsite(delegate { InvokeOnMainThread(delegate { RefreshPinColours(); //RefreshData(); }); }); }; NavigationItem.TitleView = segmentControl; NavigationItem.LeftBarButtonItem = new UIBarButtonItem(Resources.Routing, UIBarButtonItemStyle.Bordered, delegate { //nulls, think about the nulls! if (!CLLocationManager.LocationServicesEnabled) { alert = new UIAlertView("No Location Available", "Sorry, no location services are available. However, you may still be able to use the timer and map.", null, "Ok"); alert.Show(); return; } if (mapView.UserLocation == null || mapView.UserLocation.Location == null) { alert = new UIAlertView("No Location Available", "Sorry, your location is not yet available.", null, "Ok"); alert.Show(); return; } NSObject[] selectedPins = mapView.SelectedAnnotations; if (selectedPins == null || selectedPins.Length > 1) { alert = new UIAlertView("Select a dock", "Please pick a cycle docking station to route to.", null, "Ok"); alert.Show(); return; } if (selectedPins.Length == 1) { CycleAnnotation ca = selectedPins[0] as CycleAnnotation; if (ca != null) { HideDistanceView(); var location = mapView.UserLocation.Location.Coordinate; #if DEBUG location = Locations.BanksideMix; #endif double distance = BikeLocation.CalculateDistanceInMeters(location, ca.Coordinate); if (distance > 50000) { alert = new UIAlertView("Sorry, your route is too long", "We can only plot cycle routes up to 50km.", null, "Ok"); alert.Show(); return; } loadingView = new ActivityIndicatorLoadingView(); loadingView.Show("Finding your route"); Util.TurnOnNetworkActivity(); RemoveRouteAnnotation(); ThreadPool.QueueUserWorkItem(delegate { using (NSAutoreleasePool newPool = new NSAutoreleasePool()) { location = mapView.UserLocation.Location.Coordinate; #if DEBUG location = Locations.BanksideMix; #endif MapRouting routing = new MapRouting(location, ca.Coordinate); //routing.FindRoute(delegate { routing.FindRoute(delegate { InvokeOnMainThread(delegate { //Console.WriteLine("updating"); loadingView.Hide(); Util.TurnOffNetworkActivity(); if (routing.HasRoute) { routeAnnotation = new CSRouteAnnotation(routing.PointsList); mapView.AddAnnotation(routeAnnotation); var region = routeAnnotation.Region; region.Span = new MKCoordinateSpan(region.Span.LatitudeDelta * 1.1f, region.Span.LongitudeDelta * 1.1f); mapView.SetRegion(region, true); //need to animate the distance etc here. ShowDistanceView(routing.DistanceForDisplay, routing.TimeForDisplay); BikeLocation.LogRoute(); } else { alert = new UIAlertView("No route found", "Sorry, no route could be found or the route is too long.", null, "Ok"); alert.Show(); } }); }); } }); } } }); //NavigationController.NavigationBar.TintColor = Resources.DarkBlue; gpsButton = new UIBarButtonItem(Resources.Gps, UIBarButtonItemStyle.Bordered, delegate { if (!CLLocationManager.LocationServicesEnabled) { alert = new UIAlertView("No Location Available", "Sorry, no location services are available. However, you may still be able to use the timer and map.", null, "Ok"); alert.Show(); return; } if (mapView.UserLocation != null) { if (mapView.UserLocation.Location != null) { //NavigationItem.RightBarButtonItem = activityButton; BikeLocation.UpdateFromWebsite(delegate { InvokeOnMainThread(delegate { RefreshPinColours(); //NavigationItem.RightBarButtonItem = gpsButton; }); }); CLLocationCoordinate2D location = mapView.UserLocation.Location.Coordinate; #if DEBUG location = Locations.BanksideMix; #endif MKCoordinateRegion region = new MKCoordinateRegion(location, new MKCoordinateSpan(0.01, 0.01)); region = mapView.RegionThatFits(region); mapView.SetRegion(region, true); } } }); NavigationItem.RightBarButtonItem = gpsButton; }
public bool OpenWriter(string message) { DateTime now = DateTime.Now; // let the application provide it's own TextWriter to ease automation with AutoStart property if (Writer == null) { if (options.ShowUseNetworkLogger) { var hostname = SelectHostName(options.HostName.Split(','), options.HostPort); if (hostname != null) { Console.WriteLine("[{0}] Sending '{1}' results to {2}:{3}", now, message, hostname, options.HostPort); try { Writer = new TcpTextWriter(hostname, options.HostPort); } catch (SocketException) { UIAlertView alert = new UIAlertView("Network Error", String.Format("Cannot connect to {0}:{1}. Continue on console ?", hostname, options.HostPort), null, "Cancel", "Continue"); int button = -1; alert.Clicked += delegate(object sender, UIButtonEventArgs e) { button = e.ButtonIndex; }; alert.Show(); while (button == -1) { NSRunLoop.Current.RunUntil(NSDate.FromTimeIntervalSinceNow(0.5)); } Console.WriteLine(button); Console.WriteLine("[Host unreachable: {0}]", button == 0 ? "Execution cancelled" : "Switching to console output"); if (button == 0) { return(false); } else { Writer = Console.Out; } } } } else { Writer = Console.Out; } } Writer.WriteLine("[Runner executing:\t{0}]", message); Writer.WriteLine("[MonoTouch Version:\t{0}]", MonoTouch.Constants.Version); UIDevice device = UIDevice.CurrentDevice; Writer.WriteLine("[{0}:\t{1} v{2}]", device.Model, device.SystemName, device.SystemVersion); Writer.WriteLine("[Device Date/Time:\t{0}]", now); // to match earlier C.WL output // FIXME: add more data about the device Writer.WriteLine("[Bundle:\t{0}]", NSBundle.MainBundle.BundleIdentifier); // FIXME: add data about how the app was compiled (e.g. ARMvX, LLVM, Linker options) return(true); }
private void ShowErrorAlert(NSError error) { UIAlertView errorAlert = new UIAlertView("An Error Occurred.", error.LocalizedDescription, null, "OK", null); errorAlert.Show(); }
public void GetPremiumMembership() { IntPtr ff = new IntPtr(); ViewController1 _ViewController1 = new iOS.ViewController1(ff); try { // Assembly public key string value = Xamarin.InAppPurchase.Utilities.Security.Unify( new string[] { "1322f985c2", "a34166b24", "ab2b367", "851cc6" }, new int[] { 0, 1, 2, 3 }); // Initialize the In App Purchase Manager #if SIMULATED PurchaseManager.SimulateiTunesAppStore = true; #else PurchaseManager.SimulateiTunesAppStore = false; #endif PurchaseManager.PublicKey = value; PurchaseManager.ApplicationUserName = "******"; // Warn user that the store is not available if (PurchaseManager.CanMakePayments) { Console.WriteLine("Xamarin.InAppBilling: User can make payments to iTunes App Store."); } else { //Display Alert Dialog Box using (var alert = new UIAlertView("Xamarin.InAppBilling", "Sorry but you cannot make purchases from the In App Billing store. Please try again later.", null, "OK", null)) { alert.Show(); } } // Warn user if the Purchase Manager is unable to connect to // the network. PurchaseManager.NoInternetConnectionAvailable += () => { //Display Alert Dialog Box using (var alert = new UIAlertView("Xamarin.InAppBilling", "No open internet connection is available.", null, "OK", null)) { alert.Show(); } }; // Show any invalid product queries PurchaseManager.ReceivedInvalidProducts += (productIDs) => { // Display any invalid product IDs to the console Console.WriteLine("The following IDs were rejected by the iTunes App Store:"); foreach (string ID in productIDs) { Console.WriteLine(ID); } Console.WriteLine(" "); }; // Report the results of the user restoring previous purchases PurchaseManager.InAppPurchasesRestored += (count) => { // Anything restored? if (count == 0) { // No, inform user using (var alert = new UIAlertView("Xamarin.InAppPurchase", "No products were available to be restored from the iTunes App Store.", null, "OK", null)) { alert.Show(); } } else { // Yes, inform user using (var alert = new UIAlertView("Xamarin.InAppPurchase", String.Format("{0} {1} restored from the iTunes App Store.", count, (count > 1) ? "products were" : "product was"), null, "OK", null)) { alert.Show(); } } }; // Report miscellanous processing errors PurchaseManager.InAppPurchaseProcessingError += (message) => { //Display Alert Dialog Box using (var alert = new UIAlertView("Xamarin.InAppPurchase", message, null, "OK", null)) { alert.Show(); } }; // Report any issues with persistence PurchaseManager.InAppProductPersistenceError += (message) => { using (var alert = new UIAlertView("Xamarin.InAppPurchase", message, null, "OK", null)) { alert.Show(); } }; // Setup automatic purchase persistance and load any previous purchases PurchaseManager.AutomaticPersistenceType = InAppPurchasePersistenceType.LocalFile; PurchaseManager.PersistenceFilename = "AtomicData"; PurchaseManager.ShuffleProductsOnPersistence = false; PurchaseManager.RestoreProducts(); #if SIMULATED // Ask the iTunes App Store to return information about available In App Products for sale PurchaseManager.QueryInventory(new string[] { "product.nonconsumable", "feature.nonconsumable", "feature.nonconsumable.fail", "gold.coins.consumable_x25", "gold.coins.consumable_x50", "gold.coins.consumable_x100", "newsletter.freesubscription", "magazine.subscription.duration1month", "antivirus.nonrenewingsubscription.duration6months", "antivirus.nonrenewingsubscription.duration1year", "product.nonconsumable.invalid", "content.nonconsumable.downloadable", "content.nonconsumable.downloadfail", "content.nonconsumable.downloadupdate" }); // Setup the list of simulated purchases to restore when doing a simulated restore of pruchases // from the iTunes App Store PurchaseManager.SimulatedRestoredPurchaseProducts = "product.nonconsumable,antivirus.nonrenewingsubscription.duration6months,content.nonconsumable.downloadable"; #else // Ask the iTunes App Store to return information about available In App Products for sale PurchaseManager.QueryInventory(new string[] { //"xam.iap.nonconsumable.widget", //"xam.iap.subscription.duration1month", //"xam.iap.subscription.duration1year", //"xam.iap.subscription.duration3months" "yomeedpremium_monthly", "yomeedpremium_yearly", "test_product" }); #endif UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController (_ViewController1, true, null); } catch (Exception ex) { } }
public UIButton ResetButton; //resets the button to the default settings public ButtonMaintenanceScreen() { GeneralMaintenanceScreen.Saved += SaveGeneral; // //create screen Screen = new UIViewController(); Screen.View.BackgroundColor = UIColor.White; //create button Button = new ButtonData(); //create media picker MediaPicker = new UIImagePickerController(); //MediaPicker.VideoExportPreset = AVAssetExportSessionPreset.HighestQuality.ToString(); //System.Diagnostics.Debug.WriteLine(MediaPicker.VideoExportPreset); MediaPicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary; MediaPicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary); //MediaPicker.ImageExportPreset = UIImagePickerControllerImageUrlExportPreset.Current; MediaPicker.VideoExportPreset = AVAssetExportSessionPreset.Passthrough.GetConstant().ToString(); MediaPicker.FinishedPickingMedia += Handle_FinishedPickingMedia; MediaPicker.Canceled += Handle_Canceled; //1. create views //create reset button ResetButton = new UIButton(); ResetButton.BackgroundColor = UIColor.Green; ResetButton.SetTitle("Reset button\nsettings", UIControlState.Normal); ResetButton.SetTitleColor(UIColor.Black, UIControlState.Normal); //when video button clicked - open the media picker native interface ResetButton.TouchUpInside += ResetButtonData; ResetButton.Layer.BorderColor = ButtonBorderColour.CGColor; ResetButton.Layer.BorderWidth = ButtonBorderWidth; ResetButton.BackgroundColor = ButtonBackgroundColour; ResetButton.LineBreakMode = UILineBreakMode.WordWrap;//allow multiple lines for text inside video button ResetButton.VerticalAlignment = UIControlContentVerticalAlignment.Center; ResetButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; ResetButton.Layer.CornerRadius = ButtonCornerRadius; //create video button VideoButton = new UIButton(); VideoButton.BackgroundColor = UIColor.Green; VideoButton.SetTitle("Choose a video for\nthe button \nto play", UIControlState.Normal); VideoButton.SetTitleColor(UIColor.Black, UIControlState.Normal); //when video button clicked - open the media picker native interface VideoButton.TouchUpInside += (s, e) => { try { //set the media picker to show only videos MediaPicker.MediaTypes = new string[] { UTType.Movie, UTType.Video }; //vids? Screen.PresentViewControllerAsync(MediaPicker, true); } catch (Exception ex) { //if the device doesn't have any videos, pop up an alert box with a message Console.WriteLine(ex.Message); UIAlertView alert = new UIAlertView() { Title = "No Videos Alert", Message = "You don't have any videos to select. To download or record vids..." }; alert.AddButton("OK"); alert.Show(); } }; VideoButton.Layer.BorderColor = ButtonBorderColour.CGColor; VideoButton.Layer.BorderWidth = ButtonBorderWidth; VideoButton.BackgroundColor = ButtonBackgroundColour; VideoButton.LineBreakMode = UILineBreakMode.WordWrap;//allow multiple lines for text inside video button //VideoButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; //center text VideoButton.VerticalAlignment = UIControlContentVerticalAlignment.Center; VideoButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; VideoButton.Layer.CornerRadius = ButtonCornerRadius; //create image button ImageButton = new UIButton(); ImageButton.BackgroundColor = UIColor.Green; ImageButton.SetTitle("Choose an image for\nthe button thumbnail", UIControlState.Normal); ImageButton.SetTitleColor(UIColor.Black, UIControlState.Normal); //when image button clicked - open the media picker native interface ImageButton.TouchUpInside += (s, e) => { try { //set the media picker to show only images MediaPicker.MediaTypes = new string[] { UTType.Image }; Screen.PresentViewControllerAsync(MediaPicker, true); } catch (Exception ex) { //if the device doesn't have any images, pop up an alert box with a message Console.WriteLine(ex.Message); UIAlertView alert = new UIAlertView() { Title = "No Images Alert", Message = "You don't have any images to select. To download or take photos..." }; alert.AddButton("OK"); alert.Show(); } }; ImageButton.Layer.BorderColor = ButtonBorderColour.CGColor; ImageButton.Layer.BorderWidth = ButtonBorderWidth; ImageButton.BackgroundColor = ButtonBackgroundColour; ImageButton.LineBreakMode = UILineBreakMode.WordWrap; //allow multiple lines for text inside video button ImageButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; //center text ImageButton.Layer.CornerRadius = ButtonCornerRadius; //create image box ImageBox = new UIImageView(); ImageBox.Layer.BorderWidth = ButtonBorderWidth; ImageBox.Layer.CornerRadius = ButtonCornerRadius; ImageBox.ClipsToBounds = true; ImageBox.Layer.BorderColor = UIColor.Gray.CGColor; //create video box VideoBox = new UIImageView(); VideoBox.Layer.BorderWidth = ButtonBorderWidth; VideoBox.Layer.CornerRadius = ButtonCornerRadius; VideoBox.ClipsToBounds = true; VideoBox.Layer.BorderColor = UIColor.Gray.CGColor; //create back button BackButton = new UIButton(); BackButton.TouchUpInside += CloseScreen; BackButton.SetTitle("Back", UIControlState.Normal); BackButton.SetTitleColor(UIColor.Black, UIControlState.Normal); Screen.Add(BackButton); //add back button to screen BackButton.Layer.BorderColor = ButtonBorderColour.CGColor; BackButton.Layer.BorderWidth = ButtonBorderWidth; BackButton.BackgroundColor = ButtonBackgroundColour; BackButton.Layer.CornerRadius = ButtonCornerRadius; //create save button SaveButton = new UIButton(); SaveButton.BackgroundColor = UIColor.Red; SaveButton.TouchUpInside += Save; SaveButton.SetTitle("Save", UIControlState.Normal); SaveButton.SetTitleColor(UIColor.Black, UIControlState.Normal); Screen.Add(SaveButton); //add save button to screen SaveButton.Layer.BorderColor = ButtonBorderColour.CGColor; SaveButton.Layer.BorderWidth = ButtonBorderWidth; SaveButton.BackgroundColor = ButtonBackgroundColour; SaveButton.Layer.CornerRadius = ButtonCornerRadius; //create colour box ColourBox = new UIView(); ColourBox.Layer.BorderWidth = ButtonBorderWidth; ColourBox.Layer.CornerRadius = ButtonCornerRadius; ColourBox.Layer.BorderColor = UIColor.Gray.CGColor; //create general button GeneralButton = new UIButton(); GeneralButton.BackgroundColor = UIColor.Green; //open the general settings modal. //pass some app data GeneralButton.TouchUpInside += (o, s) => { //remove? //GeneralMaintenanceScreen.ButtonsPerPage = ButtonsPerPage; //GeneralMaintenanceScreen.NumberOfPages = NumberOfPages; Screen.PresentModalViewController(GeneralMaintenanceScreen.Screen, false); // GeneralMaintenanceScreen.NumberOfPages = this.NumberOfPages; GeneralMaintenanceScreen.ButtonsPerPage = this.ButtonsPerPage; GeneralMaintenanceScreen.BordersThickness = this.ButtonBorderWidth; GeneralMaintenanceScreen.SetDropDowns(); //ImageBox.Layer.BorderColor = UIColor.Clear.CGColor; }; GeneralButton.SetTitle("JustButtons\nSettings", UIControlState.Normal); GeneralButton.SetTitleColor(UIColor.Black, UIControlState.Normal); GeneralButton.Layer.BorderColor = ButtonBorderColour.CGColor; GeneralButton.Layer.BorderWidth = ButtonBorderWidth; GeneralButton.BackgroundColor = ButtonBackgroundColour; GeneralButton.Layer.CornerRadius = ButtonCornerRadius; GeneralButton.LineBreakMode = UILineBreakMode.WordWrap; //allow multiple lines for text inside video button GeneralButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; //center text //color sliders RedSlider = new UISlider(); RedSlider.ValueChanged += UpdateBorderColor; GreenSlider = new UISlider(); GreenSlider.ValueChanged += UpdateBorderColor; BlueSlider = new UISlider(); BlueSlider.ValueChanged += UpdateBorderColor; //create labels VideoButtonTitle = new UILabel(); VideoButtonTitle.Text = "Click below to change the video played:"; VideoButtonTitle.TextColor = UIColor.Black; VideoButtonTitle.TextAlignment = UITextAlignment.Left; VideoButtonTitle.LineBreakMode = UILineBreakMode.WordWrap; VideoButtonTitle.Lines = 2; ImageButtonTitle = new UILabel(); ImageButtonTitle.Text = "Click below to change the button's image:"; ImageButtonTitle.TextColor = UIColor.Black; ImageButtonTitle.TextAlignment = UITextAlignment.Left; ImageButtonTitle.LineBreakMode = UILineBreakMode.WordWrap; ImageButtonTitle.Lines = 2; ColourBoxTitle = new UILabel(); ColourBoxTitle.Text = "Adjust the sliders to change the border colour:"; ColourBoxTitle.TextColor = UIColor.Black; ColourBoxTitle.TextAlignment = UITextAlignment.Left; ColourBoxTitle.LineBreakMode = UILineBreakMode.WordWrap; ColourBoxTitle.Lines = 2; SettingsButtonTitle = new UILabel(); SettingsButtonTitle.Text = "Click below to change the number of pages and buttons, and border thickness:"; SettingsButtonTitle.TextColor = UIColor.Black; SettingsButtonTitle.TextAlignment = UITextAlignment.Left; SettingsButtonTitle.LineBreakMode = UILineBreakMode.WordWrap; SettingsButtonTitle.Lines = 2; //2. add views to parent view Screen.View.Add(VideoButton); Screen.View.Add(ImageButton); Screen.View.Add(ImageBox); Screen.View.Add(VideoBox); Screen.View.Add(BackButton); Screen.View.Add(SaveButton); Screen.Add(ColourBox); Screen.Add(GeneralButton); Screen.Add(RedSlider); Screen.Add(GreenSlider); Screen.Add(BlueSlider); Screen.Add(ImageButtonTitle); Screen.Add(VideoButtonTitle); Screen.Add(ColourBoxTitle); Screen.Add(SettingsButtonTitle); Screen.Add(ResetButton); //3. call method on parent view Screen.View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints(); //4. add constraints Screen.View.AddConstraints( VideoButton.AtTopOf(Screen.View, UIApplication.SharedApplication.StatusBarFrame.Height + 75), VideoButton.AtLeftOf(Screen.View, 70), VideoButton.WithRelativeWidth(Screen.View, 0.19f), VideoButton.Height().EqualTo(100), ImageButton.Below(VideoButton, 80), ImageButton.WithSameLeft(VideoButton), ImageButton.WithSameWidth(VideoButton), ImageButton.WithSameHeight(VideoButton), VideoBox.WithSameTop(VideoButton), VideoBox.Left().EqualTo().RightOf(VideoButton).Plus(35), VideoBox.WithRelativeWidth(Screen.View, 0.17f), VideoBox.Height().EqualTo(100), ImageBox.WithSameTop(ImageButton), ImageBox.WithSameLeft(VideoBox), ImageBox.WithSameWidth(VideoBox), ImageBox.WithSameHeight(VideoBox), BackButton.WithSameTop(VideoButton), BackButton.AtRightOf(Screen.View, 70), BackButton.WithSameWidth(VideoButton), BackButton.WithSameHeight(VideoButton), SaveButton.WithSameTop(ImageButton), SaveButton.AtRightOf(Screen.View, 70), SaveButton.WithSameWidth(VideoButton), SaveButton.WithSameHeight(VideoButton), ColourBox.Below(ImageButton, 80), ColourBox.WithSameLeft(VideoButton), ColourBox.WithSameWidth(VideoButton), ColourBox.WithSameHeight(VideoBox), GeneralButton.Below(ColourBox, 80), GeneralButton.WithSameLeft(VideoButton), GeneralButton.WithSameWidth(VideoButton), GeneralButton.WithSameHeight(VideoButton), RedSlider.WithSameTop(ColourBox), RedSlider.Left().EqualTo().RightOf(ColourBox).Plus(35), RedSlider.WithRelativeWidth(Screen.View, 0.11f), RedSlider.WithSameHeight(ColourBox), GreenSlider.WithSameTop(ColourBox), GreenSlider.Left().EqualTo().RightOf(RedSlider).Plus(30), GreenSlider.WithSameWidth(RedSlider), GreenSlider.WithSameHeight(ColourBox), BlueSlider.WithSameTop(ColourBox), BlueSlider.Left().EqualTo().RightOf(GreenSlider).Plus(30), BlueSlider.WithSameWidth(RedSlider), BlueSlider.WithSameHeight(ColourBox), VideoButtonTitle.Above(VideoButton, 5), VideoButtonTitle.WithSameLeft(VideoButton), VideoButtonTitle.WithRelativeWidth(VideoButton, 3.1f), VideoButtonTitle.Height().EqualTo(80), ImageButtonTitle.Above(ImageButton, 5), ImageButtonTitle.WithSameLeft(VideoButtonTitle), ImageButtonTitle.WithSameWidth(VideoButtonTitle), ImageButtonTitle.WithSameHeight(VideoButtonTitle), ColourBoxTitle.Above(ColourBox, 5), ColourBoxTitle.WithSameLeft(VideoButtonTitle), ColourBoxTitle.WithSameWidth(VideoButtonTitle), ColourBoxTitle.WithSameHeight(VideoButtonTitle), SettingsButtonTitle.Above(GeneralButton, 5), SettingsButtonTitle.WithSameLeft(VideoButtonTitle), SettingsButtonTitle.WithSameWidth(VideoButtonTitle), SettingsButtonTitle.WithSameHeight(VideoButtonTitle), ResetButton.WithSameTop(GeneralButton), ResetButton.AtRightOf(Screen.View, 70), ResetButton.WithSameWidth(VideoButton), ResetButton.WithSameHeight(VideoButton) ); }
public async void NavigateUsingGoogleMaps(double destinationLat, double destinationLng, int zoomLevel = 1, DirectionsMode directionsMode = DirectionsMode.Driving) { if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined) { if (locationManager != null) { // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7. if (locationManager.RespondsToSelector(new ObjCRuntime.Selector("requestWhenInUseAuthorization"))) { locationManager.RequestWhenInUseAuthorization(); } return; } } if (CLLocationManager.Status == CLAuthorizationStatus.Denied) { string title = (CLLocationManager.Status == CLAuthorizationStatus.Denied) ? "Location services are off" : "Location Service is not enabled"; string message = "To use Location Service you must turn on 'While using the app' in the Location Services Settings"; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { Mvx.Resolve <IMvxMessenger>().Publish(new ProgressMessage(this.ViewModel, false)); UIAlertView alertView = new UIAlertView(title, message, null, "Cancel", "Settings"); alertView.Clicked += (object sender, UIButtonEventArgs e) => { if (e.ButtonIndex == alertView.CancelButtonIndex) //cancel { //ViewModel.CloseViewModel(); } else { //go to settings UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString)); } }; alertView.Dismissed += (sender, e) => { alertView.Dispose(); alertView = null; }; alertView.Show(); } else { // ios 7 only has two CLAuthorizationStatus : Denied and AuthorizedAlways if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways) { return; } Mvx.Resolve <IMvxMessenger>().Publish(new ProgressMessage(this.ViewModel, false)); UIAlertView alertView = new UIAlertView(title, message, null, "OK"); alertView.Clicked += (sender, e) => { //if (e.ButtonIndex == alertView.CancelButtonIndex) //ViewModel.CloseViewModel(); }; alertView.Dismissed += (sender, e) => { alertView.Dispose(); alertView = null; }; alertView.Show(); } return; } //get current location Geolocator locator = new Geolocator() { DesiredAccuracy = 100 }; var location = await locator.GetPositionAsync(50000); Console.WriteLine("Position Status: {0}", location.Timestamp); Console.WriteLine("Position Latitude: {0}", location.Latitude); Console.WriteLine("Position Longitude: {0}", location.Longitude); var sourceLat = location.Latitude; var sourceLng = location.Longitude; var mode = directionsMode == DirectionsMode.Driving ? "driving" : "walking"; if (UIApplication.SharedApplication.CanOpenUrl(new NSUrl("comgooglemaps://"))) { // GoogleMaps is installed. Launch GoogleMaps and start navigation var urlString = string.Format("comgooglemaps://?saddr={0},{1}&daddr={2},{3}&zoom={4}&directionsmode={5}", sourceLat.ParseToCultureInfo(new CultureInfo("en-US")), sourceLng.ParseToCultureInfo(new CultureInfo("en-US")), destinationLat.ParseToCultureInfo(new CultureInfo("en-US")), destinationLng.ParseToCultureInfo(new CultureInfo("en-US")), zoomLevel, mode); UIApplication.SharedApplication.OpenUrl(new NSUrl(urlString)); } else { // GoogleMaps is not installed. Launch AppStore to install GoogleMaps app UIApplication.SharedApplication.OpenUrl(new NSUrl("http://itunes.apple.com/us/app/id585027354")); } }
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo) { #region 檢測點 myContainer.Resolve <IEventAggregator>().GetEvent <UpdateInfoEvent>().Publish(new UpdateInfoEventPayload { Name = "ReceivedRemoteNotification", time = DateTime.Now, }); WriteNotificationLog("ReceivedRemoteNotification" + DateTime.Now.ToString()); #endregion #region 取出 aps 推播內容,進行處理 if (userInfo.ContainsKey(new NSString("aps"))) { try { NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary; #region 取出相關推播通知的 Payload string alert = string.Empty; string args = string.Empty; if (aps.ContainsKey(new NSString("alert"))) { alert = (aps[new NSString("alert")] as NSString).ToString(); } if (aps.ContainsKey(new NSString("args"))) { args = (aps[new NSString("args")] as NSString).ToString(); } #endregion #region 因為應用程式正在前景,所以,顯示一個提示訊息對話窗 if (!string.IsNullOrEmpty(args)) { SystemSound.Vibrate.PlaySystemSound(); UIAlertView avAlert = new UIAlertView("Notification", alert, null, "OK", null); avAlert.Show(); #region 使用 Prism 事件聚合器,送訊息給 核心PCL,切換到所指定的頁面 if (string.IsNullOrEmpty(args) == false) { // 將夾帶的 Payload 的 JSON 字串取出來 var fooPayload = args; // 將 JSON 字串反序列化,並送到 核心PCL var fooFromBase64 = Convert.FromBase64String(fooPayload); fooPayload = Encoding.UTF8.GetString(fooFromBase64); LocalNotificationPayload fooLocalNotificationPayload = JsonConvert.DeserializeObject <LocalNotificationPayload>(fooPayload); myContainer.Resolve <IEventAggregator>().GetEvent <LocalNotificationToPCLEvent>().Publish(fooLocalNotificationPayload); } #endregion } #endregion } catch { } } #endregion }
public virtual void AuthorizationChanged(CLLocationManager manager, CLAuthorizationStatus status) { Console.WriteLine(status.ToString()); if (status == CLAuthorizationStatus.NotDetermined) { if (locationManager != null) { // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7. if (locationManager.RespondsToSelector(new ObjCRuntime.Selector("requestWhenInUseAuthorization"))) { locationManager.RequestWhenInUseAuthorization(); } return; } } if (status == CLAuthorizationStatus.AuthorizedAlways || status == CLAuthorizationStatus.Denied) { string title = (status == CLAuthorizationStatus.Denied) ? "Location services are off" : "Location Service is not enabled"; string message = "To use Location Service you must turn on 'While using the app' in the Location Services Settings"; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { Mvx.Resolve <IMvxMessenger>().Publish(new ProgressMessage(this.ViewModel, false)); UIAlertView alertView = new UIAlertView(title, message, null, "Cancel", "Settings"); alertView.Clicked += (object sender, UIButtonEventArgs e) => { if (e.ButtonIndex == alertView.CancelButtonIndex) //cancel { ViewModel.CloseViewModel(); } else { //go to settings UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString)); } }; alertView.Dismissed += (sender, e) => { alertView.Dispose(); alertView = null; }; alertView.Show(); } else { // ios 7 only has two CLAuthorizationStatus : Denied and AuthorizedAlways if (status == CLAuthorizationStatus.AuthorizedAlways) { return; } Mvx.Resolve <IMvxMessenger>().Publish(new ProgressMessage(this.ViewModel, false)); UIAlertView alertView = new UIAlertView(title, message, null, "OK"); alertView.Clicked += (sender, e) => { if (e.ButtonIndex == alertView.CancelButtonIndex) { ViewModel.CloseViewModel(); } }; alertView.Dismissed += (sender, e) => { alertView.Dispose(); alertView = null; }; alertView.Show(); } } }
public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. actvw.HidesWhenStopped = true; // Pinch gesture to scale font var pinchGestureRecognizer = new UIPinchGestureRecognizer((recog) => { //Console.WriteLine ("recog.State={0}, scale={1}", recog.State, recog.Scale); if (recog.State == UIGestureRecognizerState.Began) { } else if (recog.State == UIGestureRecognizerState.Changed) { int unitSize = (int)Math.Min(maxFontSize, Math.Max(minFontSize, this.unitFontSize * recog.Scale)); ShowProgressionLabel(String.Format("Size = {0}", unitSize)); _tableViewSource.SetHeightForRow(CalculateRowHeightFromUnitFontSize(unitSize)); tblvwGlyphList.ReloadData(); } else if (recog.State == UIGestureRecognizerState.Recognized) { int unitSize = (int)Math.Min(maxFontSize, Math.Max(minFontSize, this.unitFontSize * recog.Scale)); if (unitSize != unitFontSize) { this.unitFontSize = unitSize; UpdateGlyphsWithCurrentFontSize(); } DismissProgressionLabel(); } }); tblvwGlyphList.AddGestureRecognizer(pinchGestureRecognizer); #region Toolbar button to save every image to PNG var saveButton = new UIBarButtonItem(FontAwesomeUtil.GetUIImageForBarItem(GlyphNames.Save), UIBarButtonItemStyle.Plain , (s, e) => { var alert = new UIAlertView(); alert.Title = String.Format("{0}x{0} size of images are going to be generated.", this.unitFontSize); alert.Message = "Clear any image in document folder before newly generate?"; int nYesButton = alert.AddButton("Clear"); int nNoButton = alert.AddButton("No"); int nCancelButton = alert.AddButton("Cancel"); alert.CancelButtonIndex = nCancelButton; alert.Clicked += (s2, e2) => { if (nYesButton == e2.ButtonIndex) { DeleteAllPNGsInDocumentFolder(); SaveEveryImageToPNG(); } else if (nNoButton == e2.ButtonIndex) { SaveEveryImageToPNG(); } }; alert.Show(); }); SetToolbarItems(new UIBarButtonItem[] { saveButton }, false); #endregion UpdateGlyphsWithCurrentFontSize(); }
private void Save(Project project) { //Save the image to the project var path = Path.Combine(SavePath, Guid.NewGuid().ToString() + ".png"); var thumbPath = Path.Combine(SavePath, Guid.NewGuid().ToString() + ".png"); NSError error; _img.AsPNG().Save(path, true, out error); if (error != null && error.Code != 0) { //Unable to save image var alert = new UIAlertView { Title = "Error", Message = "Unable to save image. Error code: " + error.Code }; alert.CancelButtonIndex = alert.AddButton("Ok"); alert.Show(); return; } var size = AppreciateUI.Utils.Util.ThumbnailSize; UIGraphics.BeginImageContextWithOptions(size, false, 0f); var context = UIGraphics.GetCurrentContext(); context.TranslateCTM(0, size.Height); context.ScaleCTM(1f, -1f); context.DrawImage(new System.Drawing.RectangleF(0, 0, size.Width, size.Height), _img.CGImage); var cgImage = UIGraphics.GetImageFromCurrentImageContext(); cgImage.AsPNG().Save(thumbPath, true, out error); if (error != null && error.Code != 0) { //Delete the first save.. try { File.Delete(path); } catch (Exception e) { AppreciateUI.Utils.Util.LogException("Unable to delete image file at: " + path, e); } var alert = new UIAlertView { Title = "Error", Message = "Unable to save image. Error code: " + error.Code }; alert.CancelButtonIndex = alert.AddButton("Ok"); alert.Show(); return; } UIGraphics.EndImageContext(); var pi = new ProjectImage { ProjectId = project.Id, Path = path, ThumbPath = thumbPath, Category = _category, Icon = _icon }; Data.Database.Main.Insert(pi); if (Success != null) { Success(); } }
public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); //Ocultamos el campo de observaciones, ya que por lo visto no se almacena en ningun lado, esperamos respuesta this.cmpObservaciones.Hidden = true; this.lblObservaciones.Hidden = true; //Ocultamos los labels donde se muestran las coordenadas del dispositivo this.lblLatitud.Hidden = true; this.lblLongitud.Hidden = true; //Declarar el Location Manager iPhoneLocationManager = new CLLocationManager(); iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters; //Obtener la posicion del dispositivo //El metodo es diferente en iOS 6 se verifica la version del S.O. if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0)) { iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { UpdateLocation(e.Locations [e.Locations.Length - 1]); }; } else { iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => { UpdateLocation(e.NewLocation); }; } iPhoneLocationManager.UpdatedHeading += (object sender, CLHeadingUpdatedEventArgs e) => { }; //Actualizar la ubicacion if (CLLocationManager.LocationServicesEnabled) { iPhoneLocationManager.StartUpdatingLocation(); } if (CLLocationManager.HeadingAvailable) { iPhoneLocationManager.StartUpdatingHeading(); } //Se esconde el booton para ir a la vista anterior this.NavigationItem.HidesBackButton = true; //se crea el boton para regresar a la vista anterior, verificando que la tarea haya sido dada de alta UIBarButtonItem regresar = new UIBarButtonItem(); regresar.Style = UIBarButtonItemStyle.Plain; regresar.Target = this; regresar.Title = "Lista de tareas"; regresar.Clicked += (sender, e) => { if (this.listo == false) { UIAlertView alert = new UIAlertView() { Title = "¿Salir?", Message = "Si sales se perderá el registro de la tarea" }; alert.AddButton("Aceptar"); alert.AddButton("Cancelar"); alert.Clicked += (s, o) => { if (o.ButtonIndex == 0) { NavigationController.PopViewControllerAnimated(true); } }; alert.Show(); } else { NavigationController.PopViewControllerAnimated(true); } }; //posionamiento del boton this.NavigationItem.LeftBarButtonItem = regresar; //Se establece un borde para el textarea de la descripcion this.cmpDescripcion.Layer.BorderWidth = 1.0f; this.cmpDescripcion.Layer.BorderColor = UIColor.Gray.CGColor; this.cmpDescripcion.Layer.ShadowColor = UIColor.Black.CGColor; this.cmpDescripcion.Layer.CornerRadius = 8; //Declaramos el datamodel para los responsables pickerDataModelResponsibles = new PickerDataModelResponsibles(); //Declaramos el datamodel para las categorias pickerDataModelCategories = new PickerDataModelCategories(); //Declaramos el datamodel para el picker de prioridades pickerDataModel = new PickerDataModel(); //Declaramos el datamodel para el picker de buisqueda de personas pickerDataModelPeople = new PickerDataModelPeople(); //Declaramos el actionsheet donde se mostrara el picker actionSheetPicker = new ActionSheetPicker(this.View); this.btnResponsable.TouchUpInside += (sender, e) => { try{ responsibleService = new ResponsibleService(); pickerDataModelResponsibles.Items = responsibleService.All(); actionSheetPicker.Picker.Source = pickerDataModelResponsibles; actionSheetPicker.Show(); }catch (System.Net.WebException) { UIAlertView alert = new UIAlertView() { Title = "ERROR", Message = "No se pueden cargar los datos, verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } catch (System.Exception) { UIAlertView alert = new UIAlertView() { Title = "Lo sentimos", Message = "Ocurrio un problema de ejecucion, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } }; this.btnCategoria.TouchUpInside += (sender, e) => { try{ categoryService = new CategoryService(); pickerDataModelCategories.Items = categoryService.All(); //llenamos el picker view con la respuesta del servicio de categorias actionSheetPicker.Picker.Source = pickerDataModelCategories; actionSheetPicker.Show(); }catch (System.Net.WebException) { UIAlertView alert = new UIAlertView() { Title = "ERROR", Message = "No se pueden cargar los datos, verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } catch (System.Exception) { UIAlertView alert = new UIAlertView() { Title = "Lo sentimos", Message = "Ocurrio un problema de ejecucion, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } }; this.btnPrioridad.TouchUpInside += (sender, e) => { try{ prioritiesService = new PrioritiesService(); pickerDataModel.Items = prioritiesService.All(); //llenamos el pickerview con la lista de prioridades actionSheetPicker.Picker.Source = pickerDataModel; actionSheetPicker.Show(); } catch (System.Net.WebException) { UIAlertView alert = new UIAlertView() { Title = "ERROR", Message = "No se pueden cargar los datos, verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } catch (System.Exception) { UIAlertView alert = new UIAlertView() { Title = "Lo sentimos", Message = "Ocurrio un problema de ejecucion, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } }; this.btnFechaCont.TouchUpInside += (sender, e) => { actionSheetDatePicker.Show(); }; this.btnFechaCompr.TouchUpInside += (sender, e) => { actionSheetDatePicker1.Show(); }; //Establecemos las propiedades del primer datepicker actionSheetDatePicker = new ActionSheetDatePicker(this.View); actionSheetDatePicker.Picker.Mode = UIDatePickerMode.Date; actionSheetDatePicker.Picker.TimeZone = NSTimeZone.LocalTimeZone; //actionSheetDatePicker.Picker.MinimumDate = DateTime.Today.AddDays (-7); //actionSheetDatePicker.Picker.MaximumDate = DateTime.Today.AddDays (7); //Establecemos las propiedades del segundo datepicker actionSheetDatePicker1 = new ActionSheetDatePicker(this.View); actionSheetDatePicker1.Picker.Mode = UIDatePickerMode.Date; actionSheetDatePicker1.Picker.TimeZone = NSTimeZone.LocalTimeZone; //actionSheetDatePicker1.Picker.MinimumDate = DateTime.Today.AddDays (-7); //actionSheetDatePicker1.Picker.MaximumDate = DateTime.Today.AddDays (7); actionSheetDatePicker.Picker.ValueChanged += (s, e) => { DateTime fecha1 = (s as UIDatePicker).Date; //DateTime fecha3 = fecha1.AddDays(-1); String fecha2 = String.Format("{0:yyyy-MM-dd}", fecha1); this.lblFechaCont.Text = fecha2; }; actionSheetDatePicker1.Picker.ValueChanged += (s, e) => { DateTime fecha1 = (s as UIDatePicker).Date; //DateTime fecha3 = fecha1.AddDays(-1); String fecha2 = String.Format("{0:yyyy-MM-dd}", fecha1); this.lblFechaCompr.Text = fecha2; }; String categoria = ""; pickerDataModelCategories.ValueChanged += (sender, e) => { categoria = pickerDataModelCategories.SelectedItem.idCategoria; this.lblCategoria.Text = pickerDataModelCategories.SelectedItem.ToString(); }; String prioridad = ""; pickerDataModel.ValueChanged += (sender, e) => { prioridad = pickerDataModel.SelectedItem.idPrioridad; this.lblPrioridad.Text = pickerDataModel.SelectedItem.ToString(); }; String responsable = ""; pickerDataModelResponsibles.ValueChanged += (sender, e) => { responsable = pickerDataModelResponsibles.SelectedItem.UserID; this.lblResponsable.Text = pickerDataModelResponsibles.SelectedItem.ToString(); }; String idPadron = ""; pickerDataModelPeople.ValueChanged += (sender, e) => { idPadron = pickerDataModelPeople.SelectedItem.idPadron; this.cmpSolicitante.Text = pickerDataModelPeople.SelectedItem.ToString(); }; this.btnBuscar.TouchUpInside += (sender, e) => { try{ peopleService = new PeopleService(); peopleService.FindPeople(this.cmpNombre.Text, this.cmpPaterno.Text, this.cmpMaterno.Text); pickerDataModelPeople.Items = peopleService.All(); if (pickerDataModelPeople.Items.Count == 0) { UIAlertView alert = new UIAlertView() { Title = "Persona no encontrada", Message = "No se encontraron resultados, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } else { actionSheetPicker = new ActionSheetPicker(this.View); actionSheetPicker.Picker.Source = pickerDataModelPeople; actionSheetPicker.Show(); } } catch (System.Net.WebException) { UIAlertView alert = new UIAlertView() { Title = "ERROR", Message = "No se pueden cargar los datos, verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } catch (System.Exception) { UIAlertView alert = new UIAlertView() { Title = "Lo sentimos", Message = "Ocurrio un problema de ejecucion, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } }; this.cmpSolicitante.Enabled = false; //Se crea el boton para enviar la informacion al servidor this.btnGuardar.TouchUpInside += (sender, e) => { try{ newTaskService = new NewTaskService(); String respuesta = newTaskService.SetData(cmpTitulo.Text, cmpDescripcion.Text, categoria, responsable, prioridad, lblFechaCont.Text, lblFechaCompr.Text, idPadron, MainView.user , cmpTelCasa.Text, cmpTelCel.Text, cmpCorreo.Text, lblLatitud.Text, lblLongitud.Text); if (respuesta.Equals("0")) { UIAlertView alert = new UIAlertView() { Title = "ERROR", Message = "Error del Servidor, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } else if (respuesta.Equals("1")) { UIAlertView alert = new UIAlertView() { Title = "Correcto", Message = "La tarea ha sido guardada correctamente" }; alert.AddButton("Aceptar"); alert.Clicked += (s, o) => { if (o.ButtonIndex == 0) { NavigationController.PopViewControllerAnimated(true); } }; alert.Show(); } }catch (System.Net.WebException ex) { Console.WriteLine(ex.ToString()); UIAlertView alert = new UIAlertView() { Title = "ERROR", Message = "Error del Servidor, intentelo de nuevo, o verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } }; //Se establece un borde para el textarea de las observaciones this.cmpObservaciones.Layer.BorderWidth = 1.0f; this.cmpObservaciones.Layer.BorderColor = UIColor.Gray.CGColor; this.cmpObservaciones.Layer.ShadowColor = UIColor.Black.CGColor; this.cmpObservaciones.Layer.CornerRadius = 8; }
async private void fetchData() { try { string sCustomerId = Joyces.Platform.AppContext.Instance.Platform.CustomerId; string sUserToken = Joyces.Helpers.Settings.AccessToken; var resp = await RestAPI.GetOffer(sCustomerId, sUserToken); if (resp == null) { _message = new UIAlertView(Lang.MESSAGE_HEADLINE, Lang.SERVICE_NOT_AVAILABLE, null, Lang.BUTTON_OK, null); _message.Show(); } else if (resp != null && resp is List <Offer> ) { Joyces.Platform.AppContext.Instance.Platform.OfferList = (List <Offer>)resp; //Troligen har giltighetstiden för Token gått ut. if (Joyces.Platform.AppContext.Instance.Platform.OfferList == null) { Joyces.Helpers.Settings.AccessToken = string.Empty; Joyces.Helpers.Settings.UserEmail = string.Empty; var mainController = Storyboard.InstantiateViewController("loginNavigationController"); UIApplication.SharedApplication.KeyWindow.RootViewController = mainController; _message = new UIAlertView(Lang.MESSAGE_HEADLINE, Lang.USER_HAS_LOGGED_OUT, null, Lang.BUTTON_OK, null); _message.Show(); } else { offerTableView.Source = new OfferTableViewSource(Joyces.Platform.AppContext.Instance.Platform.OfferList); offerTableView.SeparatorStyle = UITableViewCellSeparatorStyle.SingleLine; offerTableView.SeparatorInset = UIEdgeInsets.Zero; offerTableView.RowHeight = 120f; offerTableView.EstimatedRowHeight = 120f; offerTableView.ReloadData(); } } else if (resp != null && resp is AbalonErrors) { var localError = (AbalonErrors)resp; if (localError.error.Contains("invalid_token") || localError.error.Contains("invalid_grant")) { Joyces.Helpers.Settings.AccessToken = string.Empty; Joyces.Helpers.Settings.UserEmail = string.Empty; var mainController = Storyboard.InstantiateViewController("loginNavigationController"); UIApplication.SharedApplication.KeyWindow.RootViewController = mainController; _message = new UIAlertView(Lang.MESSAGE_HEADLINE, Lang.USER_HAS_LOGGED_OUT, null, Lang.BUTTON_OK, null); _message.Show(); } else { UIAlertView _error = new UIAlertView(Lang.MESSAGE_HEADLINE, localError.message, null, Lang.BUTTON_OK, null); _error.Show(); } } else { //_message = new UIAlertView(Lang.MESSAGE_HEADLINE, Lang.UNEXPECTED_ERROR + " #1", null, Lang.BUTTON_OK, null); //_message.Show(); } } catch (Exception ex) { var mainController = Storyboard.InstantiateViewController("loginNavigationController"); UIApplication.SharedApplication.KeyWindow.RootViewController = mainController; _message = new UIAlertView(Lang.MESSAGE_HEADLINE, Lang.UNEXPECTED_ERROR + " #2", null, Lang.BUTTON_OK, null); _message.Show(); } }
public override void ViewDidLoad() { base.ViewDidLoad(); Title = "Contacts"; // // create a tableview and use the list as the datasource // tableView = new UITableView() { Delegate = new TableViewDelegate(this), AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth, }; // // size the tableview and add it to the parent view // tableView.SizeToFit(); tableView.Frame = new RectangleF( 0, 0, this.View.Frame.Width, this.View.Frame.Height); this.View.AddSubview(tableView); list = new List <Contact>(); // // get the address book, which gives us access to the // the contacts store // var book = new AddressBook(); // // important: PreferContactAggregation must be set to the // the same value when looking up contacts by ID // since we look up contacts by ID on the subsequent // ContactsActivity in this sample, we will set to false // book.PreferContactAggregation = true; book.RequestPermission().ContinueWith(t => { if (!t.Result) { alert = new UIAlertView("Permission denied", "User has denied this app access to their contacts", null, "Close"); alert.Show(); } else { // // loop through the contacts and put them into a List // // contacts can be selected and sorted using linq! // // In this sample, we'll just use LINQ to grab the first 10 users with mobile phone entries // foreach (Contact contact in book.Where(c => c.Phones.Any(p => p.Type == PhoneType.Mobile)).Take(10)) { list.Add(contact); } tableView.DataSource = new TableViewDataSource(list); tableView.ReloadData(); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public void loadData() { if (!InternetConnection.IsNetworkAvaialable(true)) { using (var alert = new UIAlertView("iPortogruaro", "Spiacente nessun collegamento internet al momento", null, "OK", null))//Viajes Telcel//Aceptar { alert.Show(); } return; } if (reloading) { return; } reloading = true; UIView.BeginAnimations("slideAnimation"); UIView.SetAnimationDuration(2); UIView.SetAnimationCurve(UIViewAnimationCurve.EaseInOut); UIView.SetAnimationRepeatCount(2); UIView.SetAnimationRepeatAutoreverses(true); this.TableView.ContentInset = UIEdgeInsets.Zero; UIView.CommitAnimations(); /* * [UIView beginAnimations:nil context:NULL]; * [UIView setAnimationDuration:.3]; * [tblMain setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)]; * [refreshHeaderView setStatus:kPullToReloadStatus]; * [refreshHeaderView toggleActivityView:NO]; * [UIView commitAnimations]; */ starthud(); ThreadPool.QueueUserWorkItem(state => { var lst = new iportogruaroLibraryShared.mainEventos().getMainCategorys(false); InvokeOnMainThread(delegate { TableView.Source = new sourceEvents(this, lst); TableView.ReloadData(); setLoadingViewStyle(this.TableView); stophud(); reloading = false; } ); }); foreach (UIView vin in vLoading) { vin.RemoveFromSuperview(); vin.Dispose(); } vLoading.RemoveFromSuperview(); vLoading.Dispose(); vLoading = null; //startHud(); //} }