Example #1
0
        public static async Task <HNAnswerResult> EditComment(int answerID, int questionID, HNAnswerResult answer)
        {
            string     query = _host + "questions/" + questionID + "/answers/" + answerID;
            HttpClient http  = new HttpClient();
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

            http.DefaultRequestHeaders.Add("Authorization", "Token token=\"" + localSettings.Values["API_Token"] + "\"");

            string postBody = JsonConvert.SerializeObject(answer,
                                                          Formatting.None,
                                                          new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            StringContent payload = new StringContent(postBody, System.Text.Encoding.UTF8, "application/json");

            var response = await http.PatchAsync(new Uri(query), payload);

            if (!response.IsSuccessStatusCode)
            {
                Debug.WriteLine("Error updating answer. Error code: " + response.StatusCode);
            }
            var jsonMessage = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <HNAnswerResult>(jsonMessage);

            Debug.WriteLine("Updated answer: " + answerID);
            return(result);
        }
        private void InitializeCommands()
        {
            GoToProfileCommand = new RelayCommand <TappedRoutedEventArgs>(args =>
            {
                LastClickedProfilePic = args.OriginalSource as Ellipse;
                var parentGrid        = LastClickedProfilePic.Parent as Grid;
                LastClickedUsername   = parentGrid.FindName("lblAnswerUsername") as TextBlock;
                var dc = LastClickedProfilePic.DataContext as HNAnswer;
                App.ViewModelLocator.Profile.LoadUser((int)dc.user.id);
                App.ViewModelLocator.Profile.ProfilePicture = dc.user.profile_image;
                App.ViewModelLocator.Profile.UserName       = dc.user.name;
                if (ApiInformation.IsTypePresent("Windows.UI.Xaml.Media.Animation.ConnectedAnimationService"))
                {
                    ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ProfilePicture", LastClickedProfilePic);
                    ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("Username", LastClickedUsername);
                }
                _navigationService.NavigateTo(typeof(ProfilePage));
            });

            GoToOPProfileCommand = new RelayCommand <TappedRoutedEventArgs>(args =>
            {
                LastClickedProfilePic = args.OriginalSource as Ellipse;
                var parentGrid        = (LastClickedProfilePic.Parent as Border).Parent as Grid;
                LastClickedUsername   = parentGrid.FindName("lblUsername") as TextBlock;
                App.ViewModelLocator.Profile.LoadUser((int)CurrentQuestion.user.id);
                App.ViewModelLocator.Profile.ProfilePicture = CurrentQuestion.user.profile_image;
                App.ViewModelLocator.Profile.UserName       = CurrentQuestion.user.name;
                if (ApiInformation.IsTypePresent("Windows.UI.Xaml.Media.Animation.ConnectedAnimationService"))
                {
                    ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ProfilePicture", LastClickedProfilePic);
                    ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("Username", LastClickedUsername);
                }
                _navigationService.NavigateTo(typeof(ProfilePage));
            });

            ReplyCommand = new RelayCommand <HNAnswer>(args =>
            {
                var atTag = string.Format("@{0} ", args.user.name);

                if (string.IsNullOrWhiteSpace(AnswerText))
                {
                    AnswerText = atTag;
                }
                else if (!AnswerText.Contains(atTag))
                {
                    AnswerText = AnswerText + " " + atTag;
                }
            });

            SubmitAnswerCommand = new RelayCommand(async() =>
            {
                if (!string.IsNullOrWhiteSpace(AnswerText))
                {
                    CanSendAnswer = false;
                    InCall        = true;

                    HNAnswerResult answer = new HNAnswerResult
                    {
                        answer = new HNAnswer
                        {
                            content = AnswerText,
                            quick   = false
                        }
                    };

                    #region Attachments
                    if (UploadImages.Count > 0)
                    {
                        try
                        {
                            var file     = await StorageFile.GetFileFromPathAsync(UploadImages[0].UriSource.AbsolutePath);
                            var response = await DataService.UploadAttachment(file, true, false);
                            answer.image = new HNImage {
                                id = response.image.id
                            };
                        }
                        catch (Exception)
                        {
                            await new MessageDialog("We're having trouble uploading that attachment").ShowAsync();
                            LoggerService.LogEvent("Attachment_upload_failed");
                        }
                    }
                    #endregion

                    try
                    {
                        HNAnswerResult result = await DataService.PostAnswer(answer.answer, (int)CurrentQuestion.id);
                        LoggerService.LogEvent("Answer_posted");
                        UploadImages.Clear();
                        AnswerText = "";
                        Answers.Add(result.answer);
                        InCall        = false;
                        CanSendAnswer = true;
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        LoggerService.LogEvent("Posting_answer_failed");
                    }
                }
                else
                {
                    await new MessageDialog("The answer box is empty").ShowAsync();
                }
            });

            SelectOption = new RelayCommand <ItemClickEventArgs>(args =>
            {
                var lst = args.OriginalSource as ListView;
                int i   = lst.IndexFromContainer(args.ClickedItem as Grid);
            });

            #region Attachments

            SelectPhotoCommand = new RelayCommand(async() =>
            {
                var picker      = new FileOpenPicker();
                picker.ViewMode = PickerViewMode.Thumbnail;
                picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                picker.FileTypeFilter.Add(".jpg");
                picker.FileTypeFilter.Add(".jpeg");
                picker.FileTypeFilter.Add(".png");

                var imageFile = await picker.PickSingleFileAsync();
                if (imageFile != null)
                {
                    // Application now has read/write access to the picked file
                    Debug.WriteLine("Picked photo: " + imageFile.Name);
                    var uploadImage = new BitmapImage();
                    FileRandomAccessStream stream = (FileRandomAccessStream)await imageFile.OpenAsync(FileAccessMode.Read);
                    uploadImage.SetSource(stream);
                    UploadImages.Add(uploadImage);
                }
                else
                {
                    Debug.WriteLine("Operation cancelled.");
                }
            });
            TakePhotoCommand = new RelayCommand(async() =>
            {
                CameraCaptureUI captureUI      = new CameraCaptureUI();
                captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;

                var imageFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

                if (imageFile == null)
                {
                    return;
                }

                IRandomAccessStream stream = await imageFile.OpenAsync(FileAccessMode.Read);

                BitmapImage image = new BitmapImage();
                await image.SetSourceAsync(stream);
                UploadImages.Clear();
                UploadImages.Add(image);
            });
            RecordAudioCommand = new RelayCommand(() =>
            {
            });
            #endregion
        }