Exemple #1
0
        UIViewController MakeLogin()
        {
            var login = new EntryElement("Login", "Type 'Root'", "");
            var pass  = new EntryElement("Password", "Type 'Root'", "");

            var loginButton = new StringElement("Login", delegate {
                login.FetchValue();
                pass.FetchValue();
                if (login.Value == "Root" && pass.Value == "Root")
                {
                    NSUserDefaults.StandardUserDefaults.SetBool(true, "loggedIn");

                    window.RootViewController.PresentViewController(MakeOptions(), true, delegate {});
                }
            });

            return(new DialogViewController(new RootElement("Login")
            {
                new Section("Enter login and password")
                {
                    login, pass,
                },
                new Section()
                {
                    loginButton
                }
            }));
        }
Exemple #2
0
                void Save()
                {
                    userElement.FetchValue();
                    passwordElement.FetchValue();

                    hud = new ProgressHud(Locale.GetText("Authenticating"), Locale.GetText("Cancel"));
                    hud.ButtonPressed += delegate { DestroyHud(); };
                    dvc.View.AddSubview(hud);

                    // Send an incomplete request with login/password, if this returns 403, we got the wrong password
                    ThreadPool.QueueUserWorkItem((x) => {
                        bool ok = false;
                        try {
                            ok = ValidateCredentials();
                        } catch (Exception e) {
                            Util.ReportError(this, e, Locale.GetText("While validating credentials"));
                        }
                        BeginInvokeOnMainThread(delegate {
                            DestroyHud();
                            if (ok)
                            {
                                Close(true);
                            }
                        });
                    });
                }
Exemple #3
0
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            // create a new window instance based on the screen size
            window       = new UIWindow(UIScreen.MainScreen.Bounds);
            entryElement = new EntryElement("", "Type the text to speak here.", "");
            spearkBtn    = new StringElement("Speak", delegate {
                entryElement.FetchValue();
                Flite.Flite.ConvertTextToWav(entryElement.Value, "test.wav", 0);
            });
            window.RootViewController = new DialogViewController(new RootElement("")
            {
                new Section()
                {
                    entryElement,
                    spearkBtn
                }
            });
            // If you have defined a view, add it here:
            // window.AddSubview (navigationController.View);

            // make the window visible
            window.MakeKeyAndVisible();

            return(true);
        }
Exemple #4
0
        async void Login()
        {
            int port;

            hostEntry.FetchValue();
            portEntry.FetchValue();
            userEntry.FetchValue();
            passwordEntry.FetchValue();

            int.TryParse(portEntry.Value, out port);

            try {
                if (Mail.Client.IsConnected)
                {
                    await Mail.Client.DisconnectAsync(true);
                }

                // Connect to server
                await Mail.Client.ConnectAsync(hostEntry.Value, port, sslCheckbox.Value);

                // Note: For the purposes of this demo, since we have not implemented support for
                // obtaining the user's OAuth2.0 auth_token, we'll have to disable XOAUTH2.
                //
                // OAuth2 is the authentication mechanism that services like GMail are pushing.
                // If you get an exception when trying to log in to your GMail account using this
                // demo, then you probably have not enabled "less secure apps" in your GMail
                // settings. Do not be fooled by Google's labeling of this checkbox, the claim
                // is really only true if the user logs in w/o using SSL (which they enforce).
                Mail.Client.AuthenticationMechanisms.Remove("XOAUTH2");

                try {
                    // Authenticate now that we're connected
                    await Mail.Client.AuthenticateAsync(userEntry.Value, passwordEntry.Value);

                    // Show the folders view controller
                    NavigationController.PushViewController(foldersViewController, true);
                } catch (Exception aex) {
                    Console.WriteLine(aex);
                    Mail.MessageBox("Authentication Error",
                                    "Failed to Authenticate to server. If you are using GMail, then you probably " +
                                    "need to go into your GMail settings to enable \"less secure apps\" in order " +
                                    "to get this demo to work.\n\n" +
                                    "For a real Mail application, you'll want to add support for obtaining the " +
                                    "user's OAuth2 credentials to prevent the need for user's to enable this, but " +
                                    "that is beyond the scope of this demo."
                                    );
                }
            } catch (Exception ex) {
                Console.WriteLine(ex);
                Mail.MessageBox("Connection Error", "Failed to connect to server.");
            }
        }
        protected void AttemptAuth(object sender, EventArgs e)
        {
            _clientIdEntry.FetchValue();
            ClientId = _clientIdEntry.Value;
            _clientSecretEntry.FetchValue();
            ClientSecret = _clientSecretEntry.Value;
            _requestUriEntry.FetchValue();
            RequestUri = _requestUriEntry.Value;

            if ((string.IsNullOrEmpty(ClientId)) || (string.IsNullOrEmpty(ClientSecret)) || (string.IsNullOrEmpty(RequestUri)))
            {
                UIAlertView firstPageValidationAlert = new UIAlertView("Whoops!", "Please provide a Client Id, Client Secret and Request Uri.", null, "Okay");
                firstPageValidationAlert.Show();
            }
            else
            {
                //Elements for Second Page - authorization
                var secondPage = new UIViewController();
                secondPage.Title = "Authorize";
                var authorizeWebView = new UIWebView(secondPage.View.Frame);
                secondPage.View.AddSubview(authorizeWebView);
                viewController.VisibleViewController.NavigationController.PushViewController(secondPage, true);
                authorizeWebView.LoadFinished += delegate(object s, EventArgs ev) {
                    string       currentUrl     = authorizeWebView.Request.Url.AbsoluteString;
                    const string CodeIdentifier = "code=";
                    if (currentUrl.Contains(CodeIdentifier))
                    {
                        //We've received an authorization code - initialize the token manager to get a create a token
                        Code         = currentUrl.Substring(currentUrl.IndexOf(CodeIdentifier) + CodeIdentifier.Length);
                        TokenManager = new AccessTokenManager(ClientId, ClientSecret, RequestUri);
                        InvokeOnMainThread(() => {
                            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
                        });
                        TokenManager.InitAccessToken(Code);
                        var userRequest = new UsersEndpoint(TokenManager);
                        User = userRequest.GetUser();
                        var profileRequest = new ProfileEndpoint(TokenManager, User);
                        Profile = profileRequest.GetProfile();
                        InvokeOnMainThread(() => {
                            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
                        });
                        ShowUserAndProfile();
                    }
                };
                authorizeWebView.LoadRequest(new NSUrlRequest(new NSUrl(HealthGraphAuthorizeEndpoint + "?client_id=" + ClientId + "&redirect_uri=" + HttpUtility.UrlEncode(RequestUri) + "&response_type=code")));
            }
        }
        async void Login()
        {
            int port;

            hostEntry.FetchValue();
            portEntry.FetchValue();
            userEntry.FetchValue();
            passwordEntry.FetchValue();

            int.TryParse(portEntry.Value, out port);

            try {
                if (Mail.Client.IsConnected)
                {
                    await Mail.Client.DisconnectAsync(true);
                }

                // Note: for demo purposes, we're ignoring SSL validation errors (don't do this in production code)
                Mail.Client.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

                // Connect to server
                await Mail.Client.ConnectAsync(hostEntry.Value, port, sslCheckbox.Value);

                try {
                    // Authenticate now that we're connected
                    await Mail.Client.AuthenticateAsync(userEntry.Value, passwordEntry.Value);

                    // Show the folders view controller
                    NavigationController.PushViewController(foldersViewController, true);
                } catch (Exception aex) {
                    Console.WriteLine(aex);
                    Mail.MessageBox("Authentication Error",
                                    "Failed to Authenticate to server. If you are using GMail, then you probably " +
                                    "need to go into your GMail settings to enable \"less secure apps\" in order " +
                                    "to get this demo to work.\n\n" +
                                    "For a real Mail application, you'll want to add support for obtaining the " +
                                    "user's OAuth2 credentials to prevent the need for user's to enable this, but " +
                                    "that is beyond the scope of this demo."
                                    );
                }
            } catch (Exception ex) {
                Console.WriteLine(ex);
                Mail.MessageBox("Connection Error", "Failed to connect to server.");
            }
        }
        void submitScore()
        {
            nameElement.FetchValue();
            scoreElement.FetchValue();
            var gameScore = new GameScore()
            {
                Player    = nameElement.Value,
                Score     = int.Parse(scoreElement.Value),
                Dificulty = (GameDificulty)dificultyGroup.Selected,
            };
            var pfobj = gameScore.ToPfObject();

            Console.WriteLine(pfobj);

            pfobj.SaveAsync((success, error) => {
                UIAlertView alert = new UIAlertView(pfobj.ClassName, string.Format("Success: {0}", success), null, "Ok");
                alert.Show();
            });
        }
Exemple #8
0
        async void Login()
        {
            int port;

            hostEntry.FetchValue();
            portEntry.FetchValue();
            userEntry.FetchValue();
            passwordEntry.FetchValue();

            int.TryParse(portEntry.Value, out port);

            try {
                if (Mail.Client.IsConnected)
                {
                    await Mail.Client.DisconnectAsync(true);
                }

                // Connect to server
                await Mail.Client.ConnectAsync(hostEntry.Value, port, sslCheckbox.Value);

                // Remove this auth mechanism since we don't have an oauth token
                Mail.Client.AuthenticationMechanisms.Remove("XOAUTH2");

                try {
                    // Authenticate now that we're connected
                    await Mail.Client.AuthenticateAsync(userEntry.Value, passwordEntry.Value);

                    // Show the folders view controller
                    NavigationController.PushViewController(foldersViewController, true);
                } catch (Exception aex) {
                    Console.WriteLine(aex);
                    Mail.MessageBox("Authentication Error", "Failed to Authenticate to server.");
                }
            } catch (Exception ex) {
                Console.WriteLine(ex);
                Mail.MessageBox("Connection Error", "Failed to connect to server.");
            }
        }
Exemple #9
0
        void Save()
        {
            name.FetchValue();
            song.Name = name.Value;

            artist.FetchValue();
            song.TrackData.Artist = artist.Value;

            album.FetchValue();

            song.TrackData.Album = album.Value;

            albumArtist.FetchValue();
            song.TrackData.AlbumArtist = albumArtist.Value;

            genre.FetchValue();
            song.TrackData.Genre = genre.Value;

            trackNumber.FetchValue();
            int i;

            if (int.TryParse(trackNumber.Value, out i))
            {
                song.TrackData.Track = i;
            }

            disc.FetchValue();
            if (int.TryParse(disc.Value, out i))
            {
                song.TrackData.Disc = i;
            }

            year.FetchValue();
            if (int.TryParse(year.Value, out i))
            {
                song.TrackData.Year = i;
            }
        }
        public SetupDialogController()
            : base(UITableViewStyle.Grouped, null)
        {
            var nickname = new EntryElement(null, "Nickname", null);

            Root = new RootElement("Gablarski")
            {
                new Section {
                    nickname
                },

                new Section {
                    new StringElement("Continue", async() => {
                        nickname.FetchValue();
                        Settings.Nickname = nickname.Value;
                        await Settings.SaveAsync();
                        AppDelegate.StartSetup();

                        PresentViewController(new MainViewController(), true, null);
                    })
                }
            };
        }
Exemple #11
0
        // Creates the login dialog using Xauth, this is a nicer
        // user experience, but requires Twitter to approve your
        // app
        void NewAccountXAuth(DialogViewController parent, NSAction callback)
        {
            var login    = new EntryElement(Locale.GetText("Username"), Locale.GetText("Your twitter username"), "");
            var password = new EntryElement(Locale.GetText("Password"), Locale.GetText("Your password"), "", true);
            var root     = new RootElement(Locale.GetText("Login"))
            {
                new Section()
                {
                    login,
                    password
                },
                new Section()
                {
                    new LoadMoreElement(Locale.GetText("Login to Twitter"), Locale.GetText("Contacting twitter"), delegate {
                        login.FetchValue();
                        password.FetchValue();
                        StartXauthLogin(login.Value.Trim(), password.Value.Trim(), callback);
                    }, UIFont.BoldSystemFontOfSize(16), UIColor.Black)
                }
            };

            MakeLoginDialog(parent, root);
        }
Exemple #12
0
        void submitScore()
        {
            try {
                nameElement.FetchValue();
                scoreElement.FetchValue();
                var gameScore = new GameScore()
                {
                    Player    = nameElement.Value,
                    Score     = int.Parse(scoreElement.Value),
                    Dificulty = (GameDificulty)difficultyGroup.Selected,
                };

                var pfobj = gameScore.ToPfObject();
                Console.WriteLine(pfobj);

                pfobj.SaveAsync((success, error) => {
                    UIAlertView alert = new UIAlertView(pfobj.ClassName, string.Format("Success: {0}", success), null, "Ok");
                    alert.Show();
                });
            } catch (Exception ex) {
                (new UIAlertView("Error", "Please make sure all inputs are valid", null, "Ok")).Show();
            }
        }
Exemple #13
0
        public void DebugPage()
        {
            TraceHelper.AddMessage("Debug: constructor");

            // render URL and status
            var serviceUrl = new EntryElement("URL", "URL to connect to", WebServiceHelper.BaseUrl);
            var service    = new Section("Service")
            {
                serviceUrl,
                new StringElement("Store New Service URL", delegate
                {
                    serviceUrl.FetchValue();
                    // validate that this is a good URL before storing it (a bad URL can hose the phone client)
                    Uri uri = null;
                    if (Uri.TryCreate(serviceUrl.Value, UriKind.RelativeOrAbsolute, out uri) &&
                        (uri.Scheme == "http" || uri.Scheme == "https"))
                    {
                        WebServiceHelper.BaseUrl = serviceUrl.Value;
                    }
                    else
                    {
                        serviceUrl.Value = WebServiceHelper.BaseUrl;
                    }
                }),
                new StringElement("Connected", App.ViewModel.LastNetworkOperationStatus.ToString()),
            };

            // render user queue
            var userQueue = new Section("User Queue");

            userQueue.Add(new StringElement(
                              "Clear Queue",
                              delegate
            {
                RequestQueue.DeleteQueue(RequestQueue.UserQueue);
                userQueue.Clear();
            }));

            List <RequestQueue.RequestRecord> requests = RequestQueue.GetAllRequestRecords(RequestQueue.UserQueue);

            if (requests != null)
            {
                foreach (var req in requests)
                {
                    string typename;
                    string reqtype;
                    string id;
                    string name;
                    RequestQueue.RetrieveRequestInfo(req, out typename, out reqtype, out id, out name);
                    var sse = new StyledStringElement(String.Format("  {0} {1} {2} (id {3})", reqtype, typename, name, id))
                    {
                        Font = UIFont.FromName("Helvetica", UIFont.SmallSystemFontSize),
                    };
                    userQueue.Add(sse);
                }
            }

            // render system queue
            var systemQueue = new Section("System Queue");

            systemQueue.Add(new StringElement(
                                "Clear Queue",
                                delegate
            {
                RequestQueue.DeleteQueue(RequestQueue.SystemQueue);
                systemQueue.Clear();
            }));

            requests = RequestQueue.GetAllRequestRecords(RequestQueue.SystemQueue);
            if (requests != null)
            {
                foreach (var req in requests)
                {
                    string typename;
                    string reqtype;
                    string id;
                    string name;
                    RequestQueue.RetrieveRequestInfo(req, out typename, out reqtype, out id, out name);
                    var sse = new StyledStringElement(String.Format("  {0} {1} {2} (id {3})", reqtype, typename, name, id))
                    {
                        Font = UIFont.FromName("Helvetica", UIFont.SmallSystemFontSize),
                    };
                    systemQueue.Add(sse);
                }
            }

            var traceMessages = new Section("Trace Messages");

            traceMessages.Add(new StringElement(
                                  "Clear Trace",
                                  delegate
            {
                TraceHelper.ClearMessages();
                traceMessages.Clear();
            }));
            traceMessages.Add(new StringElement(
                                  "Send Trace",
                                  delegate
            {
                TraceHelper.SendMessages(App.ViewModel.User);
            }));
            foreach (var m in TraceHelper.GetMessages().Split('\n'))
            {
                // skip empty messages
                if (m == "")
                {
                    continue;
                }

                // create a new (small) string element with a detail indicator which
                // brings up a message box with the entire message
                var sse = new StyledStringElement(m)
                {
                    Accessory = UITableViewCellAccessory.DetailDisclosureButton,
                    Font      = UIFont.FromName("Helvetica", UIFont.SmallSystemFontSize),
                };
                string msg = m;                  // make a copy for the closure below
                sse.AccessoryTapped += delegate
                {
                    var alert = new UIAlertView("Detail", msg, null, "Ok");
                    alert.Show();
                };
                traceMessages.Add(sse);
            }
            ;

            var root = new RootElement("Debug")
            {
                service,
                userQueue,
                systemQueue,
                traceMessages,
            };

            var dvc = new DialogViewController(root, true);

            dvc.TableView.BackgroundColor = UIColorHelper.FromString(App.ViewModel.Theme.PageBackground);
            this.PushViewController(dvc, true);
            //this.NavigationController.PushViewController (dvc, true);
        }
            public VisitDetailsView(VisitDetailsViewController parent)
            {
                Parent          = parent;
                BackgroundColor = UIColor.FromRGB(239, 239, 244);

                addVisitor = new UIButton
                {
                    Frame     = new RectangleF(0, 0, 150, 150),
                    TintColor = UIColor.White,
                    Layer     =
                    {
                        CornerRadius  =   75,
                        MasksToBounds = true,
                    }
                };
                addVisitor.SetTitle("Add a visitor", UIControlState.Normal);
                addVisitor.ImageView.ContentMode = UIViewContentMode.ScaleAspectFill;;
                addVisitor.SetImage(Theme.UserImageDefaultLight.Value, UIControlState.Normal);
                addVisitor.TouchUpInside += (sender, args) => { if (Parent.PickVisitor != null)
                                                                {
                                                                    Parent.PickVisitor();
                                                                }
                };
                AddSubview(addVisitor);

                addEmployee = new UIButton
                {
                    Frame     = new RectangleF(0, 0, 150, 150),
                    TintColor = UIColor.White,
                    Layer     =
                    {
                        CornerRadius  =   75,
                        MasksToBounds = true,
                    }
                };
                addEmployee.SetTitle("Add an employee", UIControlState.Normal);
                addEmployee.ImageView.ContentMode = UIViewContentMode.ScaleAspectFill;;
                addEmployee.SetImage(Theme.UserImageDefaultLight.Value, UIControlState.Normal);
                addEmployee.TouchUpInside += (sender, args) => { if (Parent.PickEmployee != null)
                                                                 {
                                                                     Parent.PickEmployee();
                                                                 }
                };
                AddSubview(addEmployee);

                editButton = new UIButton(new RectangleF(0, 0, 40, 40));
                editButton.SetBackgroundImage(UIImage.FromBundle("edit"), UIControlState.Normal);
                editButton.TouchUpInside += (sender, args) =>
                {
                    var vc = new EditVisitorViewController
                    {
                        Visitor = new VMVisitor {
                            Visitor = visit.Visitor
                        }
                    };
                    this.Parent.NavigationController.PushViewController(vc, true);
                };

                visitorLabel = new UILabel {
                    Text = "Visitor", Font = UIFont.FromName(font2, 30), TextAlignment = UITextAlignment.Center, AdjustsFontSizeToFitWidth = true,
                };

                visitorLabel.SizeToFit();
                AddSubview(visitorLabel);

                employeeLabel = new UILabel {
                    Text = "Employee", Font = UIFont.FromName(font2, 30), TextAlignment = UITextAlignment.Center, AdjustsFontSizeToFitWidth = true,
                };
                employeeLabel.SizeToFit();
                AddSubview(employeeLabel);

                date             = new DateTimeElement("Date", DateTime.Now);
                comment          = new EntryElement("Reason: ", "Reason", "");
                comment.Changed += (sender, args) =>
                {
                    Console.WriteLine("Comment");
                };
                vehicle               = new BooleanElement("Vehicle", false);
                licensePlate          = new EntryElement("Lic Plate: ", "License Plate", "");
                licensePlate.Changed += (sender, args) =>
                {
                    Console.WriteLine("licensePlate");
                };
                vehicle.ValueChanged += (sender, args) =>
                {
                    if (vehicle.Value)
                    {
                        if (!section.Elements.Contains(licensePlate))
                        {
                            section.Add(licensePlate);
                        }
                        datadvc.ReloadData();
                    }
                    else
                    {
                        licensePlate.FetchValue();
                        section.Remove(licensePlate);
                    }
                };


                datadvc = new DialogViewController(new RootElement("visit")
                {
                    (section = new Section
                    {
                        date,
                        comment,
                        vehicle,
                        licensePlate
                    })
                });
                datadvc.TableView.SectionHeaderHeight = 0;
                datadvc.TableView.TableHeaderView     = null;
                datadvc.View.BackgroundColor          = UIColor.White;
                datadvc.View.Layer.CornerRadius       = 5f;
                var height = Enumerable.Range(0, datadvc.TableView.Source.RowsInSection(datadvc.TableView, 0)).Sum(x => datadvc.TableView.Source.GetHeightForRow(datadvc.TableView, NSIndexPath.FromRowSection(x, 0)));

                datadvc.View.Frame = new RectangleF(0, 0, 100, height);
                AddSubview(datadvc.View);
                this.Parent.AddChildViewController(datadvc);
            }
Exemple #15
0
        public SignInViewController() :
            base(UITableViewStyle.Grouped, new RootElement("Crisis Checkin"), false)
        {
            webService = WebServiceFactory.Create();

            username = new EntryElement("Email", "*****@*****.**", "")
            {
                KeyboardType       = UIKeyboardType.EmailAddress,
                AutocorrectionType = UITextAutocorrectionType.No
            };
            password = new EntryElement("Password", "password", "", true)
            {
                AutocorrectionType = UITextAutocorrectionType.No
            };


            Root = new RootElement("Crisis Checkin")
            {
                new Section("Already have an account?")
                {
                    username,
                    password,
                    new StyledStringElement("Sign In", async() => {
                        username.ResignFirstResponder(true);
                        password.ResignFirstResponder(true);

                        //TODO: Show progress HUD
                        ProgressHud.Show("Signing In");

                        // You have to fetch values first from MonoTouch.Dialog elements
                        username.FetchValue();
                        password.FetchValue();

                        // Actually sign in
                        var r = await webService.SignInAsync(new SignInRequest {
                            Username = username.Value,
                            Password = password.Value
                        });

                        if (!r.Succeeded)
                        {
                            // Show failure message
                            Utility.ShowError("Sign In Failed", "Invalid Username or Password");
                            return;
                        }

                        // Store our credentials for future web service calls
                        AppDelegate.Settings.SignedInUsername = username.Value;
                        AppDelegate.Settings.SignedInPassword = password.Value;

                        //TODO: Hide progress hud
                        ProgressHud.Dismiss();

                        // Navigate to commitments after successfuly login
                        commitmentsViewController = new CommitmentsViewController();
                        NavigationController.PushViewController(commitmentsViewController, true);
                    })
                    {
                        Alignment = UITextAlignment.Center
                    }
                },
                new Section("Don't have an account yet?")
                {
                    new StyledStringElement("Create an Account", () => {
                        // Navigate to registration controller
                        registerViewController = new RegisterViewController();
                        NavigationController.PushViewController(registerViewController, true);
                    })
                    {
                        Alignment = UITextAlignment.Center
                    }
                }
            };
        }