public override void CommitCurrentUserChanges()
        {
            // Make copy to ensure password and avatar are null

            User userToSend;

            lock (_currentUserLock)
            {
                userToSend = new User () {
                    UserName = _currentUser.UserName,
                    FullName = _currentUser.FullName,
                    City = _currentUser.City,
                    Company = _currentUser.Company,
                    Title = _currentUser.Title,
                    Email = _currentUser.Email,
                    Phone = _currentUser.Phone,
                };
            }

            Func <int> func = delegate {
                lock (_clientWrapper.ClientLock)
                {
                    _clientWrapper.Client.Post<XamarinEvolveSSLibrary.UserResponse>("User", userToSend);
                    return 0;
                }
            };
            func.BeginInvoke (null, null);
        }
        public override void DeleteUser()
        {
            User userToDelete;

            lock (_currentUserLock)
            {
                userToDelete = _currentUser;
            }

            _currentUser = new User ();

            Engine.Instance.ImageCache.TouchUser (userToDelete);

            Func <int> func = delegate {
                lock (_clientWrapper.ClientLock)
                {
                    string uri = string.Format ("User/{0}", userToDelete.UserName);
                    _clientWrapper.Client.Delete<XamarinEvolveSSLibrary.UserResponse>(uri);
                }

                SendLogoutAuth ();

                return 0;
            };
            func.BeginInvoke (null, null);
        }
        public byte[] GetAvararForUser(User user, int size, Action<GetAvatarResult> onComplete)
        {
            Func <int> func = delegate {
                try
                {
                    byte [] data = GetAvararForUser (user, size);

                    if (onComplete != null)
                    {
                        onComplete (new GetAvatarResult (){
                            Data = data,
                        });
                    }
                }
                catch (Exception exp)
                {
                    if (onComplete != null)
                    {
                        onComplete (new GetAvatarResult (){
                            Exceptin = exp,
                        });
                    }
                }

                return 0;
            };
            func.BeginInvoke (null, null);

            return _defaultImage;
        }
        public void UpdateUser(User user)
        {
            SetupAndCall((dbCmd, ev) =>
            {
                List<string> updateStrs = new List<string>();
                if (user.FullName != null)
                    updateStrs.Add("FullName");
                if (user.City != null)
                    updateStrs.Add("City");
                if (user.Email != null)
                    updateStrs.Add("Email");
                if (user.Phone != null)
                    updateStrs.Add("Phone");
                if (user.Password != null)
                    updateStrs.Add("Password");
                if (user.Avatar != null)
                    updateStrs.Add("Avatar");
                if (user.Company != null)
                    updateStrs.Add("Company");
                if (user.Title != null)
                    updateStrs.Add("Title");

                if (updateStrs.Count == 0)
                    return;

                ev.Where(rn => user.UserName == rn.UserName).UpdateFields = updateStrs;
                dbCmd.UpdateOnly(user, ev);
            });

            return;
        }
 void AddUsers(JsonServiceClient client, string[] users)
 {
     foreach (string userName in users)
     {
         User user = new User { UserName = userName, Password = MD5Helper.CalculateMD5Hash("password123") };
         UserResponse response = client.Put<XamarinEvolveSSLibrary.UserResponse>("User", user);
     }
 }
 public void TouchUser(User user)
 {
     lock (_cacheLock)
     {
         foreach (KeyValuePair <ImageCacheItem, ImageCacheItem> iter in _cache)
         {
             if (iter.Key.UserName.Equals (user.UserName))
                 iter.Key.Time = _ancient;
         }
     }
 }
        public byte[] GetAvararForUser(User user, int size)
        {
            byte [] data = InternalGetAvararForUser (user, size);
            if (data != null && data.Length > 0)
                return data;

            data = GravatarHelper.GetGravatarImage (user, size);
            if (data != null && data.Length > 0)
                return data;

            return _defaultImage;
        }
        void Test10(JsonServiceClient client)
        {
            Console.WriteLine("~~~~~ AddUser (newuser3) ~~~~~~~~~");

            User user = new User()
            {
                UserName = "******"
            };

            UserResponse response = client.Put<XamarinEvolveSSLibrary.UserResponse>("User", user);
            Console.WriteLine();
        }
        public override void DeleteUser()
        {
            User userToDelete = _currentUser;

            _currentUser = new User ();

            CheckInAccessLocalTest localCheckIn = Engine.Instance.CheckInAccess as CheckInAccessLocalTest;

            localCheckIn.DeleteCheckinsForUser (userToDelete);

            CachedUserList.Delete (userToDelete);
        }
        public int AddUser(User user)
        {
            int result = 0;

            SetupAndCall((dbCmd, ev) =>
            {
                dbCmd.Insert(user);
                result = (int)dbCmd.GetLastInsertId();
            });

            return result;
        }
        void Test1(JsonServiceClient client)
        {
            Console.WriteLine("~~~~~ AddUser (newuser2) ~~~~~~~~~");

            User user = new User()
            {
                UserName = "******",
                FullName = "Awesome guy",
                City = "funkytown",
                Email = "*****@*****.**",
                Phone = "8675309",
                Password = "******",
                Avatar = "avatar.jpg",
                Title = "the man",
                Company = "three's",
            };

            UserResponse response = client.Put<XamarinEvolveSSLibrary.UserResponse>("User", user);
            Console.WriteLine();
        }
        public byte[] FindAny(User user)
        {
            byte [] data = new byte[0];
            int bestSize = 0;

            lock (_cacheLock)
            {
                foreach (KeyValuePair <ImageCacheItem, ImageCacheItem> iter in _cache)
                {
                    if (iter.Key.UserName.Equals (user.UserName))
                    {
                        if (iter.Key.Size > bestSize)
                        {
                            bestSize = iter.Key.Size;
                            data = iter.Key.Data;
                        }
                    }
                }
            }

            return data;
        }
        public static byte[] GetGravatarImage(User user, int size)
        {
            if (string.IsNullOrEmpty (user.Email))
                return null;

            string urlString = GetGravatarURL (user.Email, size);
            try
            {
                using (WebClient client = new WebClient ())
                {
                    byte [] data = client.DownloadData (urlString);
                    if (data != null && data.Length > 1)
                        return data;
                }
            }
            catch
            {

            }

            return null;
        }
        public byte[] FindOrLoad(User user, int size, Action<AvatarAccess.GetAvatarResult> onComplete)
        {
            ImageCacheItem item;
            ImageCacheItem newItem = new ImageCacheItem {
                UserName = user.UserName, Size = size};

            if (!string.IsNullOrEmpty(user.UserName))
            {
                lock (_cacheLock)
                {
                    if(_cache.TryGetValue(newItem, out item))
                    {
                        if (item.Time > (DateTime.UtcNow - _timeSpan))
                            return item.Data;
                    }
                }
            }

            return Engine.Instance.AvatarAccess.GetAvararForUser (user, size, (result) => {
                AddImage (newItem, result, onComplete);
            });
        }
        protected override byte[] InternalGetAvararForUser(User user, int size)
        {
            lock (_clientWrapper.ClientLock)
            {
                string uri = string.Format ("{0}/UserAvatar/{1}/{2}",
                                            _clientWrapper.Client.BaseUri, user.UserName, size);
                try
                {
                    using (System.Net.WebClient webClient = new System.Net.WebClient ())
                    {
                        byte [] ret = webClient.DownloadData(uri);
                        if (ret != null && ret.Length > 0)
                            return ret;
                    }
                }
                catch (Exception)
                {

                }
            }

            return null;
        }
        protected override byte[] InternalGetAvararForUser(User user, int size)
        {
            Debug.SimulateNetworkWait (1000);

            string fullName = user.Avatar;

            if (string.IsNullOrEmpty (fullName))
                return null;

            if (fullName.StartsWith ("file:///"))
                fullName = fullName.Remove (0, "file://".Length);

            try
            {
                return File.ReadAllBytes (fullName);

            }
            catch (Exception)
            {

            }

            return null;
        }
 public void Delete(User userToDelete)
 {
     _list.Remove (_list.Find (e=> e.UserName == userToDelete.UserName));
 }
 public User Add(User newUser)
 {
     _list.Add (newUser);
     return newUser;
 }
        private void StartOnAddContactAction(UINavigationController navigationController, User user)
        {
            AddressBook book = new AddressBook ();
            book.RequestPermission ().ContinueWith (task => {
                navigationController.BeginInvokeOnMainThread (delegate {
                    if (task.IsFaulted || task.IsCanceled || !task.Result)
                    {
                        ShowNoContactAccess ();
                    }

                    else
                    {
                        _canAccessAddress = true;
                        CheckForExistingAndContinue (navigationController, user, false);
                    }
                });

            },TaskScheduler.FromCurrentSynchronizationContext());
        }
        private void CheckForExistingAndContinue(UINavigationController navigationController, 
		                                          User user, bool mainThreadRequired)
        {
            KeyValuePair <string, string> namePair = GetFirstAndLastName (user);

            string firstName = namePair.Key;
            string lastName = namePair.Value;

            AddressBook book = new AddressBook ();

            foreach (Contact contact in book)
            {
                if (contact.FirstName == firstName &&
                    contact.LastName == lastName)
                {
                    if (!mainThreadRequired)
                        AskShouldAddDuplicateAndContinue (navigationController, user);
                    else
                    {
                        navigationController.BeginInvokeOnMainThread (delegate {
                            AskShouldAddDuplicateAndContinue (navigationController, user);
                        });
                    }
                    return;
                }
            }

            if (!mainThreadRequired)
                ShowAddContactController (navigationController, user);
            else
            {
                navigationController.BeginInvokeOnMainThread (delegate {
                    ShowAddContactController (navigationController, user);
                });
            }
        }
        public void ShowAddContactController(UINavigationController navigationController, User user)
        {
            ABNewPersonViewController abController = new ABNewPersonViewController ();

            ABPerson person = new ABPerson ();

            KeyValuePair <string, string> namePair = GetFirstAndLastName (user);

            person.FirstName = namePair.Key;
            person.LastName = namePair.Value;

            if (!string.IsNullOrEmpty (user.Company))
            {
                person.Organization = user.Company;
            }

            if (!string.IsNullOrEmpty (user.Phone))
            {
                ABMutableMultiValue<string> phones = new ABMutableStringMultiValue();
                phones.Add(user.Phone, ABPersonPhoneLabel.Main);
                person.SetPhones(phones);
            }

            if (!string.IsNullOrEmpty (user.Email))
            {
                ABMutableMultiValue<string> emails = new ABMutableStringMultiValue();
                emails.Add(user.Email, null);
                person.SetEmails(emails);
            }

            // Get any image from cache
            byte [] data = Engine.Instance.ImageCache.FindAny (user);

            if (data != null && data.Length > 0)
            {
                person.Image = NSData.FromArray(data);
            }

            abController.DisplayedPerson  = person;

            abController.NewPersonComplete += delegate {
                navigationController.PopViewControllerAnimated (true);
            };

            navigationController.PushViewController (abController, true);

            if (OnAddContactCompleted != null)
                OnAddContactCompleted ();
        }
 public override void Logout()
 {
     _currentUser = new User ();
 }
        protected override User UserLogin(string username, string password)
        {
            Debug.SimulateNetworkWait ();

            UserList list = CachedUserList;

            User ret = list[username];
            if (ret == null)
                throw new UserAuthenticationException (string.Format ("Could not login {0}", username));

            return _currentUser = ret;
        }
        public override void Logout()
        {
            lock (_currentUserLock)
            {
                _currentUser = new User ();
            }

            Func <int> func = delegate {
                SendLogoutAuth ();

                return 0;
            };
            func.BeginInvoke (null, null);
        }
        public UserProfileHeaderCell(User userProfile)
        {
            _userProfile = userProfile;

            this.BackgroundColor = UIColor.Clear;
            this.Frame = new RectangleF (0, 0, 200, 100);

            ImageView = new UIImageView (new RectangleF (10, 10, 80, 80));
            UITapGestureRecognizer imageTap =
                new UITapGestureRecognizer (() => {
                    if (_editing && OnImageChangeRequest != null)
                    {
                        OnImageChangeRequest(ImageView.Image);
                    }
            });

            ImageView.AddGestureRecognizer (imageTap);
            ImageView.UserInteractionEnabled = _editing;

            this.Add (ImageView);

            int labelXPos = 100;
            FullNameLabel = new UILabel (new RectangleF (
                labelXPos, 10,  this.Frame.Width-(labelXPos+10), 30));
            FullNameLabel.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            FullNameLabel.BackgroundColor = UIColor.Clear;
            FullNameLabel.Font = UIFont.BoldSystemFontOfSize (22);
            FullNameLabel.AdjustsFontSizeToFitWidth = true;
            FullNameLabel.Text = _userProfile.FullName;
            this.Add (FullNameLabel);

            FullNameTextView = new UITextField (new RectangleF (
                labelXPos, 12,  this.Frame.Width-(labelXPos+10), 30));
            FullNameTextView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            FullNameTextView.BackgroundColor = UIColor.Clear;
            FullNameTextView.Font = UIFont.BoldSystemFontOfSize (22);
            FullNameTextView.AdjustsFontSizeToFitWidth = true;
            FullNameTextView.Text = _userProfile.FullName;
            FullNameTextView.ClearButtonMode = UITextFieldViewMode.Always;
            FullNameTextView.AutocapitalizationType = UITextAutocapitalizationType.Words;
            FullNameTextView.AutocorrectionType = UITextAutocorrectionType.No;
            FullNameTextView.Placeholder = "Full Name";
            FullNameTextView.ReturnKeyType = UIReturnKeyType.Done;
            FullNameTextView.ShouldReturn = delegate {
                FullNameTextView.ResignFirstResponder ();
                return true;
            };
            FullNameTextView.EditingDidEnd += delegate {
                if (_userProfile != null)
                    _userProfile.FullName = FullNameTextView.Text;
            };
            this.Add (FullNameTextView);

            CityLabel = new UILabel (new RectangleF (
                labelXPos, 50,  this.Frame.Width-(labelXPos+10), 24));
            CityLabel.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            CityLabel.BackgroundColor = UIColor.Clear;
            CityLabel.Font = UIFont.BoldSystemFontOfSize (17);
            CityLabel.AdjustsFontSizeToFitWidth = true;
            CityLabel.Text = _userProfile.City;
            this.Add (CityLabel);

            CityTextView = new UITextField (new RectangleF (
                labelXPos, 52,  this.Frame.Width-(labelXPos+10), 24));
            CityTextView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            CityTextView.BackgroundColor = UIColor.Clear;
            CityTextView.Font = UIFont.BoldSystemFontOfSize (17);
            CityTextView.AdjustsFontSizeToFitWidth = true;
            CityTextView.Text = _userProfile.City;
            CityTextView.Placeholder = "City";
            CityTextView.ReturnKeyType = UIReturnKeyType.Done;
            CityTextView.ClearButtonMode = UITextFieldViewMode.Always;
            CityTextView.AutocapitalizationType = UITextAutocapitalizationType.Words;
            CityTextView.ShouldReturn = delegate {
                CityTextView.ResignFirstResponder ();
                return true;
            };
            CityTextView.EditingDidEnd += delegate {
                if (_userProfile != null)
                    _userProfile.City = CityTextView.Text;
            };
            this.Add (CityTextView);

            ImageEditTip = new UILabel (new RectangleF (
                10, 75,  80, 15));
            ImageEditTip.AutoresizingMask = UIViewAutoresizing.None;
            ImageEditTip.BackgroundColor = UIColor.Clear;
            ImageEditTip.Font = UIFont.SystemFontOfSize (13);
            ImageEditTip.AdjustsFontSizeToFitWidth = true;
            ImageEditTip.Text = "Tap to edit";
            ImageEditTip.Hidden = true;
            ImageEditTip.TextAlignment = UITextAlignment.Center;
            this.Add (ImageEditTip);

            RefreshImageFromData ();
        }
        private bool AskShouldAddDuplicateAndContinue(UINavigationController navigationController, User user)
        {
            string message = string.Format
                ("You have a contact with the name {0}.  Do you still want to add?",
                 user.FullName);

            UIAlertView view = new UIAlertView ("Duplicate Found", message,
                                                null, null, new string [] {"Yes", "No"});
            view.CancelButtonIndex = 1;

            view.Clicked += (object sender, UIButtonEventArgs e) => {
                if (e.ButtonIndex == 0)
                {
                    ShowAddContactController (navigationController, user);
                }
                else
                {
                    if (OnAddContactCompleted != null)
                        OnAddContactCompleted ();
                }
            };

            view.Show ();

            return false;
        }
        public static KeyValuePair<string, string> GetFirstAndLastName(User user)
        {
            string firstName = string.Empty;
            string lastName = string.Empty;
            if (!string.IsNullOrEmpty (user.FullName))
            {
                string [] names = user.FullName.Split ();

                if (names.Length > 0)
                    firstName = names[0];

                if (names.Length > 1)
                    lastName = user.FullName.Substring (firstName.Length);
                lastName = lastName.Trim ();
            }

            return new KeyValuePair<string, string> (firstName, lastName);
        }
 public void AddContact(UINavigationController navigationController, User user)
 {
     if (!_canAccessAddress)
         StartOnAddContactAction (navigationController, user);
     else
     {
         new Func<int> (delegate {
             CheckForExistingAndContinue (navigationController, user, true);
             return 0;
         }).BeginInvoke (null,null);
     }
 }
        protected override User CreateNewUser(string username, string password)
        {
            Debug.SimulateNetworkWait ();

            UserList list = CachedUserList;

            User ret = list[username];

            if (ret != null)
                throw new DuplicateUserException (string.Format ("username {0} already exists", username) );

            return _currentUser = _userListForTesting.Add (new User (){
                UserName = username,
            });
        }
        public void RunTests()
        {
            string username = "******";
            string passHash = MD5Helper.CalculateMD5Hash("password");

            JsonServiceClient client = new JsonServiceClient(SystemConstants.WebServiceBaseURL);
            Login(client, username, passHash);

            client.Get<XamarinEvolveSSLibrary.UserResponse>("User");

            Logout(client);

            client.Get<XamarinEvolveSSLibrary.UserResponse>("User");

            Login(client, username, passHash);

            User user = new User()
            {
                UserName = username,
                City = "changedtown",
                Email = "*****@*****.**"
            };

            client.Post<XamarinEvolveSSLibrary.UserResponse>("User", user);

            Logout(client);

            client.Post<XamarinEvolveSSLibrary.UserResponse>("User", user);
        }