public async Task <ActionResult <Cabin> > CreateCabin(int portalId, [FromBody] CabinModel cabin) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Cabin newCabin = await _cabinRepository.CreateCabin(portalId, cabin); return(Ok(newCabin)); }
public async Task <IActionResult> ImportData(int portalId, [FromBody] ImportDataRequestModel model) { try { string storageConnectionString = _config["ConnectionStrings:AzureStorageConnection"]; // Check whether the connection string can be parsed. if (!CloudStorageAccount.TryParse(storageConnectionString, out CloudStorageAccount storageAccount)) { throw new Exception("Storage account connection issue."); } // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account. CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = cloudBlobClient.GetContainerReference(model.ContainerName); CloudBlob blob = container.GetBlobReference(model.Filename); Dictionary <int, string> headers = new Dictionary <int, string>(); Dictionary <int, string> errors = new Dictionary <int, string>(); int lineNumber = 0; await using (Stream stream = await blob.OpenReadAsync()) { using StreamReader reader = new StreamReader(stream); while (!reader.EndOfStream) { string line = reader.ReadLine(); if (line == null) { continue; } string[] cols = line.Split(','); if (lineNumber == 0) { // set headers for (int i = 0; i < cols.Length; i++) { headers.Add(i, cols[i]); } } else { try { // import data switch (model.ImportType) { case ImportType.Cabins: CabinModel cabinModel = new CabinModel { Name = GetColumnValue(model.Headers, headers, cols, "Name"), CreatedBy = model.CreatedBy, IsActive = true }; await _cabinRepository.CreateCabin(portalId, cabinModel); break; case ImportType.Coupons: string expirationDateValue = GetColumnValue(model.Headers, headers, cols, "ExpirationDate"); DateTimeOffset?expirationDate = null; if (expirationDateValue != null) { DateTimeOffset.TryParse(expirationDateValue, out DateTimeOffset actualExpirationDate); expirationDate = actualExpirationDate; } CouponModel couponModel = new CouponModel { Name = GetColumnValue(model.Headers, headers, cols, "Name"), Code = GetColumnValue(model.Headers, headers, cols, "Code"), ExpirationDate = expirationDate, CreatedBy = model.CreatedBy, IsActive = true }; await _couponRepository.CreateCoupon(portalId, couponModel); break; default: throw new ArgumentException("The import type is required."); } } catch (Exception ex) { errors.Add(lineNumber, ex.Message); } } lineNumber++; } } List <ImportError> importErrors = new List <ImportError>(); if (errors.Any()) { importErrors.AddRange(errors.Select(error => new ImportError { LineNumber = error.Key, Message = error.Value })); } else { await container.DeleteAsync(); } return(Ok(new ImportResponseModel { Errors = importErrors })); } catch (ArgumentException ex) { return(BadRequest(ex.Message)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }