Esempio n. 1
0
        public async Task <IActionResult> OnGetFetchEditEventPartialAsync(CancellationToken cancellationToken)
        {
            //set this value to true as the partial page will include specific
            //elements in the modal based on this value
            EditEvent = true;

            var baseAPIUrl = $"api/events/{Id}";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithAuthorization()).GetAsync(baseAPIUrl,
                                                                                    HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                //return the same page with an error message if the user is trying to call the API too many times
                if (response.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(Partial("_CreateEditEventPartial", this));
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                eventForView = streamContent.ReadAndDeserializeFromJson <EventViewDto>();

                //if image name is not null, proceed. Otherwise user never uploaded an image
                if (eventForView.ImageName != null)
                {
                    //store the image names so that if user submits a new image, blob storage retains the same file name
                    TempData["ImageUrl"]     = eventForView.ImageName;
                    TempData["ThumbnailUrl"] = eventForView.ThumbnailName;
                }
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Partial("_CreateEditEventPartial", this));
            }

            //see startup in AddMvc for how this partial is fetched
            //this was an answer found at https://softdevpractice.com/blog/asp-net-core-mvc-ajax-modals/
            return(Partial("_CreateEditEventPartial", this));
        }
Esempio n. 2
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var baseAPIUrl = $"api/Events/GetCurrentEventDue";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithGETOnlyAccessAuthorization()).GetAsync(baseAPIUrl,
                                                                                                 HttpCompletionOption.ResponseHeadersRead);

                if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(View(new EventViewDto()));
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                EventForView = streamContent.ReadAndDeserializeFromJson <EventViewDto>();

                if (EventForView == null)
                {
                    return(View(new EventViewDto()));
                }

                //cut down the size of the message if its longer than 75 characters
                if (EventForView.Message.Length > 75)
                {
                    EventForView.Message = EventForView.Message.Substring(0, 75) + "...";
                }
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(View(new EventViewDto()));
            }


            return(View(EventForView));
        }
        private EventViewDto GetTestEventViewDto()
        {
            var events = new EventViewDto()
            {
                Id            = new Guid("e77551ba-78e2-4a36-8754-3ea5f12e1619"),
                Title         = "Test1",
                Message       = "Test1",
                ImageName     = "https://[email protected]",
                ThumbnailName = "abc",
                DaysOld       = 0,
                Created       = DateTime.Now,
                ScheduledTime = DateTime.Now,
                OwnerName     = "ABC",
                OwnerEmail    = "*****@*****.**"
            };

            return(events);
        }
Esempio n. 4
0
        public async Task <IActionResult> OnGetICALFile(CancellationToken cancellationToken)
        {
            var baseAPIUrl = $"api/events/{Id}";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var response = await(await _apiClient.WithGETOnlyAccessAuthorization()).GetAsync(baseAPIUrl,
                                                                                                 HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                //return the same page with an error message if the user is trying to call the API too many times
                if (response.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(RedirectToPage("/Index"));
                }

                //ensure success status code else throw an exception
                response.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await response.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                eventForView = streamContent.ReadAndDeserializeFromJson <EventViewDto>();
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(RedirectToPage("/Index"));
            }

            StringBuilder sb         = new StringBuilder();
            string        DateFormat = "yyyyMMddTHHmmssZ";
            string        now        = DateTime.Now.ToUniversalTime().ToString(DateFormat);

            sb.AppendLine("BEGIN:VCALENDAR");
            sb.AppendLine("PRODID:-//GENERIC HOA//EN");
            sb.AppendLine("VERSION:2.0");
            sb.AppendLine("METHOD:PUBLISH");

            DateTime dtStart = Convert.ToDateTime(eventForView.ScheduledTime);
            DateTime dtEnd   = Convert.ToDateTime(eventForView.ScheduledTime.AddHours(1));

            sb.AppendLine("BEGIN:VEVENT");
            sb.AppendLine("DTSTART:" + dtStart.ToUniversalTime().ToString(DateFormat));
            sb.AppendLine("DTEND:" + dtEnd.ToUniversalTime().ToString(DateFormat));
            sb.AppendLine("DTSTAMP:" + now);
            sb.AppendLine("UID:" + Guid.NewGuid());
            sb.AppendLine("CREATED:" + now);
            sb.AppendLine("X-ALT-DESC;FMTTYPE=text/html:" + "HOA Event");
            sb.AppendLine("DESCRIPTION:" + eventForView.Message);
            sb.AppendLine("LAST-MODIFIED:" + now);
            sb.AppendLine("LOCATION:" + "N/A");
            sb.AppendLine("SEQUENCE:0");
            sb.AppendLine("STATUS:CONFIRMED");
            sb.AppendLine("SUMMARY:" + eventForView.Title);
            sb.AppendLine("TRANSP:OPAQUE");
            sb.AppendLine("END:VEVENT");
            sb.AppendLine("END:VCALENDAR");

            byte[] calendarBytes = Encoding.UTF8.GetBytes(sb.ToString());

            return(File(calendarBytes, "text/calendar", "hoaevent.ics"));
        }
Esempio n. 5
0
        public async Task <IActionResult> OnPostDeleteEventAsync(CancellationToken cancellationToken)
        {
            var baseAPIUrl = $"api/events/{Id}";

            try
            {
                //call the api with a GET request
                //ensure to set the httpcompletion mode to response headers read
                //this allows the response to be read as soon as content starts arriving instead of having to wait
                //until the entire response is read
                //with this option, we can read the response content into a stream and deserialize it
                var responseForGet = await(await _apiClient.WithAuthorization()).GetAsync(baseAPIUrl,
                                                                                          HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                //return the same page with an error message if the user is trying to call the API too many times
                if (responseForGet.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(Content("Error"));
                }

                //ensure success status code else throw an exception
                responseForGet.EnsureSuccessStatusCode();

                //read the response content into a stream
                var streamContent = await responseForGet.Content.ReadAsStreamAsync();

                //deserialize the stream into an object (see StreamExtensions on how this is done)
                eventForView = streamContent.ReadAndDeserializeFromJson <EventViewDto>();

                //set the file name from the fetched meeting minute
                ImageName     = eventForView.ImageName;
                ThumbnailName = eventForView.ThumbnailName;

                //get the response with authorization as the API endpoint requires an authenticated user
                var responseForDelete = await(await _apiClient.WithAuthorization()).DeleteAsync(baseAPIUrl, cancellationToken);

                //return the same page with an error message if the user is trying to call the API too many times
                if (responseForDelete.StatusCode == HttpStatusCode.TooManyRequests)
                {
                    TempData["TooManyRequests"] = "Too many requests. Please slow down with your requests";
                    return(Content("Error"));
                }

                //ensure success status code else throw an exception
                responseForDelete.EnsureSuccessStatusCode();

                if (ImageName != null)
                {
                    //deleting was successful as we checked for a success status code
                    //delete the images from blob storage as well
                    var imageToDelete     = _azureBlob.GetAzureBlobFileReference(ImageName, AzureBlobFolder);
                    var thumbnailToDelete = _azureBlob.GetAzureBlobFileReference(ThumbnailName, AzureBlobFolder);

                    //we want to delete both blobs in parallel
                    //if we used await _azureblob.deletefile(image), it would block the program from executing
                    //the other await statement until the first finished
                    //------------------------
                    //don't do below as it will block the second method from executing until the first has completed
                    //await _azureBlob.DeleteAzureBlobFileAsync(imageToDelete);
                    //await _azureBlob.DeleteAzureBlobFileAsync(thumbnailToDelete);
                    //----------------------------
                    //we first initialize the tasks to immediately start executing by assining them to a variable
                    //this will return a task that can be awaited to ensure it completes before we return from this action
                    //this ensures both delete functions execute in parallel as we kicked them off first before awaiting
                    var   deleteImageTask     = _azureBlob.DeleteAzureBlobFileAsync(imageToDelete);
                    var   deleteThumbnailTask = _azureBlob.DeleteAzureBlobFileAsync(thumbnailToDelete);
                    await deleteImageTask;
                    await deleteThumbnailTask;
                }
            }
            catch (HttpRequestException ex)
            {
                _logger.LogError($"An error occured accessing the API. Url: {HttpContext.Request.GetDisplayUrl()}" +
                                 $" Error Message: {ex.Message}");

                //either the API is not running or an error occured on the server
                TempData["Error"] = "An error occured while processing your request. Please try again later.";
                return(Content("Error"));
            }

            return(Content("Success"));
        }