public VideoUploadInBackgroundModel(int userId, VideoMetadata md, string imagePath, string videoPath)
 {
     this.LoggedInUserId = userId;
     this.Metadata = md;
     this.ImagePath = imagePath;
     this.VideoPath = videoPath;
 }
        private async void submit_videoBtn_Click_1(object sender, RoutedEventArgs e)
        {
            #region Variable declarations
            WebResponse response;                   // Response from createvideo URL 
            Stream responseStream;                  // Stream data from responding URL
            StreamReader reader;                    // Read data in stream 
            string responseJSON;                    // The JSON string returned to us by the Archive API 
            CreateVideoResponse API_response;       // A simple object with only one attribute: VideoId 
            HttpClient httpClient = new HttpClient();
            HttpMessageHandler handler = new HttpClientHandler();
            int SavedVideoId = -1;
            VideoMetadata md = null;
            #endregion 

            this.Frame.Navigate(typeof(GroupedItemsPage)); 


            #region Adjust some controls while the video is being uploaded
            //// Close the metadata popup 
            video_metadataPopup.IsOpen = false;
            //uploadingPopUp.Visibility = Visibility.Visible;
            //uploadingPopUp.IsOpen = true;
            //backButton.Visibility = Visibility.Collapsed;
            //ButtonsPanel.Visibility = Visibility.Collapsed;
            #endregion 

            #region Make sure the user is logged in
            // Serialize a simple UserId object and send it to the Archive API
            if (App.LoggedInUser == null)
            {
                var error_output = string.Format("You are not currently logged in.");
                Windows.UI.Popups.MessageDialog error_dialog = new Windows.UI.Popups.MessageDialog(error_output);
                await error_dialog.ShowAsync();
                return;
            }
            #endregion

            #region Upload video
            string UserID_JSON = JsonConvert.SerializeObject(new { UserId = App.LoggedInUser.UserId });

            progressTxtBlock.Text = "Uploading video..."; 

            try
            {

                var createVideoRequest = new ApiRequest("createvideo");
                createVideoRequest.Authenticated = true;
                await createVideoRequest.AddJsonContentAsync(new { UserId = App.LoggedInUser.UserId });
                var videoId = await createVideoRequest.ExecuteAsync<VideoIdModel>();
                SavedVideoId = videoId.VideoId;

                var videoUpload = new ApiChunkedVideoUpload(SavedVideoId, videoFile.Path);
                await videoUpload.Execute();

                var isVideoComplete = new ApiRequest("video/uploadchunked/iscomplete");
                isVideoComplete.Parameters.Add("videoId", SavedVideoId.ToString());
                var array = await isVideoComplete.ExecuteAsync(); 

                
            }
            catch (ApiException ex)
            {
                // api returned something other than 200
            }
            catch (Exception ex)
            {
                // something bad happened, hopefully not api related
            }
            #endregion


            #region Extract video metadata from metadata pop up 
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    string videoName = "Untitled";
                    string archive_videoName = videoName;
                    string videoDescription = descriptionTxtBox.Text;
                    DateTime dateCreated = DateTime.Now;
                    bool isPublic = false;

                    if (privacyComboBox.SelectedIndex == 0)
                        isPublic = false;
                    else if (privacyComboBox.SelectedIndex == 1)
                        isPublic = true;

                    if (titleTxtBox.Text != "")
                    {
                        archive_videoName = titleTxtBox.Text;
                        videoName = titleTxtBox.Text + ".mp4";
                    }

                    tags = new string[tagsList.Count];
                    int i = 0;

                    foreach (string t in tagsList)
                    {
                        tags[i] = t;
                        i++; 
                    }
            // Create a VideoMetadata object 
            md = new VideoMetadata(SavedVideoId, archive_videoName, videoDescription, location_string, dateCreated.ToUniversalTime(), isPublic, tags);

            // Serialize the VideoMetadata object into JSON string
            string video_metadata_JSON = JsonConvert.SerializeObject(md);
                });
            #endregion  

            #region Send metadata
            progressTxtBlock.Text = "Uploading video metadata..."; 
            try
            {
                var videoMetadataRequest = new ApiRequest("uploadvideometadata");
                videoMetadataRequest.Authenticated = true;
                videoMetadataRequest.Parameters.Add("VideoId", SavedVideoId.ToString());
                videoMetadataRequest.AddJsonContent(md);

                var result = await videoMetadataRequest.ExecuteAsync(); 

            }
            catch (ApiException ex)
            {
                // api returned something other than 200
            }
            catch (Exception ex)
            {
                // something bad happened, hopefully not api related
            }
            #endregion
            
            #region Get a thumbnail image from the video file and upload it
            // Get thumbnail of the video file 
            var thumb = await videoFile.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView, 1000, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);

            // Create a Buffer object to hold raw picture data
            var buffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(thumb.Size));

            // Read the raw picture data into the Buffer object 
            await thumb.ReadAsync(buffer, Convert.ToUInt32(thumb.Size), InputStreamOptions.None);

            // Open LocalFolder
            var folder = ApplicationData.Current.LocalFolder;

            // Create (or open if one exists) a folder called temp images
            folder = await folder.CreateFolderAsync("temp images", CreationCollisionOption.OpenIfExists);

            // Create a StorageFile 
            var thumbFile = await folder.CreateFileAsync(PHOTO_FILE_NAME, CreationCollisionOption.ReplaceExisting);

            // Write picture data to the file 
            await FileIO.WriteBufferAsync(thumbFile, buffer);

            // Preview the image
            var bmpimg = new BitmapImage();
            bmpimg.SetSource(thumb);
            PreviewImage.Source = bmpimg;

            try
            {

                var thumbnailUploadRequest = new ApiRequest("uploadvideoimage");
                thumbnailUploadRequest.Authenticated = true;
                thumbnailUploadRequest.Parameters.Add("VideoId", SavedVideoId.ToString());
                await thumbnailUploadRequest.AddFileContentAsync(thumbFile.Path);

                var result = await thumbnailUploadRequest.ExecuteAsync();

            }
            catch (ApiException ex)
            {
                // api returned something other than 200

            }
            catch (Exception ex)
            {
                // something bad happened, hopefully not api related
            }
            #endregion

            #region Upload complete, put the controls to normal
            uploadingPopUp.Visibility = Visibility.Collapsed;
            uploadingPopUp.IsOpen = false;
            //backButton.Visibility = Visibility.Visible; ;
            //ButtonsPanel.Visibility = Visibility.Visible;
            #endregion 

            #region Show success toast notification 
            //var notifier = ToastNotificationManager.CreateToastNotifier();
            //if (notifier.Setting == NotificationSetting.Enabled)
            //{
                
            //    var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

            //    var title = template.GetElementsByTagName("text")[0];
            //    title.AppendChild(template.CreateTextNode("Upload successful.")); 
            //    var message = template.GetElementsByTagName("text")[1];
            //    message.AppendChild(template.CreateTextNode("Your video " + archive_videoName + " has been uploaded successfully."));
                

            //    var toast = new ToastNotification(template);
            //    notifier.Show(toast);
            //}
            #endregion

            // Background task stuff
            //var VideoUploadObject = new VideoUploadInBackgroundModel(App.LoggedInUser.UserId, md, thumbFile.Path, videoFile.Path);

            //VideoUploadTask.RegisterVideoUpload(VideoUploadObject); 
            

            
        }