private void UpdatedAuthenticationForUser(User user)
 {
     if (!String.IsNullOrWhiteSpace(user.Username) && !String.IsNullOrWhiteSpace(user.Password))
     {
         LoggedInUser = user;
         _client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(user.Username, user.Password);
     }            
 }
	    private async void AddUser()
	    {
	        User newUser = new User()
	        {
	            Fullname = FullName,
                Username = Username,
                Password = Password,
                Properties = Properties,
                Company = _propertyTrackerService.LoggedInUser.Company,
	        };

	        object response = null;
			object imageResponse = null;
			bool uploadedImage = false;
			using (_dialogService.Loading ("Adding user...")) {
				response = await _propertyTrackerService.AddUser (newUser);
				if(response is User && PhotoDataBytes != null && PhotoDataBytes.Length > 0) {
					imageResponse = await _propertyTrackerService.UploadUserPhoto ((response as User).Id, PhotoDataBytes);
					uploadedImage = true;
				}
			}

	        if (response is User)
	        {
				bool alertDisplayed = false;
				if(uploadedImage) {
					if(imageResponse is ErrorResult) {
						_dialogService.Alert ((imageResponse as ErrorResult).Message, "Photo Upload Failed (User Add Successful)", "OK", AddUserSuccess);
						alertDisplayed = true;
					}
					else if(imageResponse == null) {
						_dialogService.Alert ("Photo Upload Failed (User was added successfully)", "Request Failed", "OK", AddUserSuccess);
						alertDisplayed = true;
					}
				}
					
				if(alertDisplayed == false)
	            	_dialogService.Alert("User added successfully", null, "OK", AddUserSuccess);

				var message = new UsersUpdatedMessage(this) {
					User = response as User
				};
				_messenger.Publish(message);
	        }
	        else
	        {
	            var msg = response is ErrorResult ? (response as ErrorResult).Message : "Failed to add new user";
                _dialogService.Alert(msg, "Request Error", "OK", AddUserFailed);	            	            
	        }                          
	    }
        public async Task<object> Login(string username, string password)
        {
            LoggedIn = false;
            LoggedInUser = null;

            // Setup Authorization header - 
            _client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(username, password);
            
            //
            // Yes, I know - we are duplicating credentials within payload - in future if we want to get away from basic auth, we can do so here.
            // 
            // #future we may want to tack in more information within login request
            //
			var loginRequest = new LoginRequest {
				Username = username,
				Password = password
			};

		    // #reference: For async style: var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));
		    var payload = new StringContent (JsonConvert.SerializeObject (loginRequest), Encoding.UTF8, "application/json");

            using (var response = await _client.PostAsync(LoginRequestUrl, payload))
            {
                var content = response.Content != null ? await response.Content.ReadAsStringAsync() : null;
                if (response.IsSuccessStatusCode == false)
                {
                    var errorResult = content != null ? JsonConvert.DeserializeObject<ErrorResult>(content) : null;
                    Debug.WriteLine("Request failed: " + response.ToString());
                    _client.DefaultRequestHeaders.Authorization = null;
                    return errorResult;
                }
                
                var parsedObject = JsonConvert.DeserializeObject<LoginResponse>(content);
                if (parsedObject != null)
                {
                    LoggedIn = true;
                    LoggedInUser = parsedObject.User;
                }
                else
                {
                    Debug.WriteLine("Could not deserialize json(" + content + ") to login response");                  
                }
                LoggedIn = parsedObject != null;
                return parsedObject;
            }
        }
	    private async void SaveUser()
	    {
	        User savedUser = new User()
	        {
				Id = UserId,
	            Fullname = FullName,
                Username = Username,
				Password = String.IsNullOrWhiteSpace(Password) ? null : Password,
                Properties = Properties,
                Company = _propertyTrackerService.LoggedInUser.Company,
	        };


	        object response = null;
			object imageResponse = null;
			bool uploadedImage = false;
			using (_dialogService.Loading ("Saving user...")) {
				response = await _propertyTrackerService.UpdateUser (savedUser);

				if(response is bool && (bool)response && _newPicture && PhotoDataBytes != null && PhotoDataBytes.Length > 0) {
					imageResponse = await _propertyTrackerService.UploadUserPhoto (_user.Id, PhotoDataBytes);
					uploadedImage = true;
				}
			}

			if (response is bool && (bool)response)
			{
				bool alertDisplayed = false;
				if(uploadedImage) {
					if(imageResponse is ErrorResult) {
						_dialogService.Alert ((imageResponse as ErrorResult).Message, "Photo Upload Failed (User Save Successful)", "OK", SaveUserSuccess);
						alertDisplayed = true;
					}
					else if(imageResponse == null) {
						_dialogService.Alert ("Photo Upload Failed (User was saved successfully)", "Request Failed", "OK", SaveUserSuccess);
						alertDisplayed = true;
					}
				}

				if(alertDisplayed == false)
					_dialogService.Alert("User saved successfully", null, "OK", SaveUserSuccess);
					
				UserUpdated (savedUser);
			}
			else
			{
				var msg = response is ErrorResult ? (response as ErrorResult).Message : "Failed to save user";
				_dialogService.Alert(msg, "Request Error", "OK", SaveUserFailed);	            	            
			}                                
	    }
		public void Init(string jsonUser)
		{
			User = JsonConvert.DeserializeObject<User> (jsonUser);
		}
		private void UserUpdated(User savedUser)
		{
			// Photo url does not change if photo is updated, it is a fixed path to photo resource for user
			savedUser.PhotoUrl = _user.PhotoUrl;
			_user = savedUser;
		  
			var message = new UsersUpdatedMessage(this) {
				User = _user
			};
			_messenger.Publish(message);

			LastPhotoDataBytes = null;
			_newPicture = false;
		}
		public async Task<object> DownloadUserPhoto (User user)
		{
			if (!LoggedIn)
			{
				Debug.WriteLine("Not logged in");
				return null;
			}
				
			using (var response = await _client.GetAsync(user.PhotoUrl))
			{
				var content = response.Content != null ? await response.Content.ReadAsByteArrayAsync () : null;
				if (response.IsSuccessStatusCode == false)
				{
					var errorString = System.Text.Encoding.UTF8.GetString (content, 0, content.Length);
					var errorResult = content != null ? JsonConvert.DeserializeObject<ErrorResult>(errorString) : null;
					Debug.WriteLine("Request failed: " + response.ToString());
					return errorResult;
				}

				return content;
			}
		}
        public async Task<object> UpdateUser(User user)
        {
            if (!LoggedIn)
            {
                Debug.WriteLine("Not logged in");
                return null;
            }
            var payload = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
            using (var response = await _client.PutAsync(string.Format("{0}/{1}", UsersRequestUrl, user.Id),payload))
            {
                var content = response.Content != null ? await response.Content.ReadAsStringAsync() : null;
                if (response.IsSuccessStatusCode == false)
                {
                    var errorResult = content != null ? JsonConvert.DeserializeObject<ErrorResult>(content) : null;
                    Debug.WriteLine("Request failed: " + response.ToString());
                    return errorResult;
                }
                if (!String.IsNullOrWhiteSpace(user.Password) && user.Id == LoggedInUser.Id)
                {
                    // Logged in user changed his password - since server has already stored the password, we can simply update
                    // service authentication so further service calls don't fail.
                    UpdatedAuthenticationForUser(user);
                }

                return true;
            }
        }
 public async Task<object> AddUser(User user)
 {
     if (!LoggedIn)
     {
         Debug.WriteLine("Not logged in");
         return null;
     }
     var payload = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
     using (var response = await _client.PostAsync(UsersRequestUrl, payload))
     {
         var content = response.Content != null ? await response.Content.ReadAsStringAsync() : null;
         if (response.IsSuccessStatusCode == false)
         {
             var errorResult = content != null ? JsonConvert.DeserializeObject<ErrorResult>(content) : null;
             Debug.WriteLine("Request failed: " + response.ToString());
             return errorResult;
         }                
         var parsedObject = JsonConvert.DeserializeObject<User>(content);
         if (parsedObject == null)
         {
             Debug.WriteLine("Could not deserialize json(" + content + ") to user response");
         }
         return parsedObject;
     }
 }
 public void Logout()
 {
     LoggedIn = false;
     LoggedInUser = null;
     _client.DefaultRequestHeaders.Authorization = null;
 }