Пример #1
0
        public async Task <IActionResult> PostProperty([FromBody] AddProperty addProperty)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var    userCp   = HttpContext.User;
            string landlord = TokenVerifier.GetLandlord(userCp);

            //Generate property
            Property property = _mapper.Map <AddProperty, Property>(addProperty);

            property.PropertyStatus = Property.VerificationStatus.Pending;
            property.AppUserRef     = landlord;

            //Validate property
            if (!TryValidateModel(property))
            {
                return(BadRequest());
            }

            List <BasicImage> images = new List <BasicImage>();

            int imgCount = 0;

            foreach (string imageStr in addProperty.Images)
            {
                BasicImage bi = WriteImage(imageStr, imgCount);

                if (bi != null)
                {
                    images.Add(bi);
                    imgCount++;
                }
                else
                {
                    CleanImages(images);
                    return(BadRequest());
                }
            }

            //All Images are valid and added
            _context.Property.Add(property);
            foreach (BasicImage bi in images)
            {
                bi.PropertyRef = property.ID;
                Image im = _mapper.Map <BasicImage, Image>(bi);
                _context.Image.Add(im);
            }

            await _context.SaveChangesAsync();

            return(Ok());
        }
Пример #2
0
        // Update specified image
        // Update for an image would just be a combination of insert/delete
        // Process:
        //     Extract first half method of Insert to reuse (where system file name / bytes are formed)
        //     Use that to convert image and upload to drive
        //     Having passed previous system file name, use that to delete the old image from drive
        //     Update systemFileName in model and send that to update with update stored proc
        // When creating this service, do not forget to add the same method signature to the interface

        // Delete specified image
        public void Delete(BasicImage model)
        {
            // Deletes image from drive
            DeleteFromDrive(model.SystemFileName);
            // Deletes image from database
            this.DataProvider.ExecuteNonQuery(
                "ImageFiles_Delete",
                inputParamMapper : delegate(SqlParameterCollection paramCol)
            {
                paramCol.AddWithValue("@id", model.Id);
            }
                );
        }
Пример #3
0
        private static BasicImage BasicImageMapper(IDataReader reader)
        {
            BasicImage model = new BasicImage();
            int        index = 0;

            model.Id             = reader.GetSafeInt32(index++);
            model.ImageFileName  = reader.GetSafeString(index++);
            model.SystemFileName = reader.GetSafeString(index++);
            model.ImageFileType  = reader.GetSafeInt32(index++);
            model.Location       = reader.GetSafeString(index++);
            model.CreatedDate    = reader.GetSafeDateTime(index++);
            model.ModifiedDate   = reader.GetSafeDateTime(index++);
            model.ModifiedBy     = reader.GetSafeString(index++);
            return(model);
        }
Пример #4
0
        // Selecting all images
        public List <BasicImage> SelectAll()
        {
            List <BasicImage> result = new List <BasicImage>();

            this.DataProvider.ExecuteCmd(
                "ImageFiles_SelectAll",
                inputParamMapper : null,
                singleRecordMapper : delegate(IDataReader reader, short set)
            {
                BasicImage model = BasicImageMapper(reader);
                result.Add(model);
            }
                );

            return(result);
        }
Пример #5
0
        // Select image by id
        public BasicImage SelectById(int id)
        {
            BasicImage model = new BasicImage();

            this.DataProvider.ExecuteCmd(
                "ImageFiles_SelectById",
                inputParamMapper : delegate(SqlParameterCollection paramCol)
            {
                paramCol.AddWithValue("@id", id);
            },
                singleRecordMapper : delegate(IDataReader reader, short set)
            {
                model = BasicImageMapper(reader);
            }
                );
            return(model);
        }
Пример #6
0
        private static BasicImage WriteImage(string imageStr, int imgCount)
        {
            //Block injection attempt
            if (imageStr.IndexOf("data:image/") != 0)
            {
                return(null);
            }

            int    pStart = imageStr.IndexOf("data:image/") + "data:image/".Length;
            int    pEnd   = imageStr.IndexOf(";");
            string mime   = imageStr.Substring(pStart, pEnd - pStart);

            //Only allowing these types of files to be uploaded
            //otherwise completely reject
            //image/jpeg
            //image/png

            if (mime == "jpeg" || mime == "png")
            {
                string b64Content = imageStr.Substring(pStart + mime.Length + ";base64,".Length);
                byte[] imageBytes = Convert.FromBase64String(b64Content);
                string fileext    = "." + mime;
                string guid       = Guid.NewGuid().ToString();
                string pathUID    = guid + fileext;

                System.IO.File.WriteAllBytes("c:\\temp\\" + pathUID, imageBytes);

                BasicImage bi = new BasicImage
                {
                    //Initialise as -1 prior to autogeneration of PropertyID image is bound to
                    PropertyRef = -1,
                    Position    = ++imgCount,
                    Path        = pathUID
                };

                return(bi);
            }
            else
            {
                return(null);
            }
        }
Пример #7
0
 static async Task SendImage(Stream stream, BasicImage image, int size)
 {
     stream.WriteByte(Core.Code.Success);
     await stream.WriteAsync(image.Data, 0, size);
 }
Пример #8
0
        public static async Task <(FormValueProvider fvp, List <BasicImage> bi)> StreamFile(this HttpRequest request)
        {
            if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType))
            {
                throw new Exception($"Expected a multipart request, but got {request.ContentType}");
            }

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var formAccumulator = new KeyValueAccumulator();
            int positionCounter = 1;

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, request.Body);
            List <BasicImage> images = new List <BasicImage>();

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        string fileext = System.IO.Path.GetExtension(contentDisposition.FileName.ToString());
                        string guid    = Guid.NewGuid().ToString();
                        string pathUID = guid + fileext;
                        using (var stream = System.IO.File.Create("c:\\temp\\" + pathUID))
                        {
                            await section.Body.CopyToAsync(stream);

                            BasicImage bi = new BasicImage
                            {
                                //Initialise as -1 prior to autogeneration of PropertyID image is bound to
                                PropertyRef = -1,
                                Position    = positionCounter++,
                                Path        = pathUID
                            };
                            images.Add(bi);
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // Content-Disposition: form-data; name="key"
                        //
                        // value

                        // Do not limit the key name length here because the
                        // multipart headers length limit is already in effect.
                        var key      = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                        var encoding = GetEncoding(section);
                        using (var streamReader = new System.IO.StreamReader(
                                   section.Body,
                                   encoding,
                                   detectEncodingFromByteOrderMarks: true,
                                   bufferSize: 1024,
                                   leaveOpen: true))
                        {
                            // The value length limit is enforced by MultipartBodyLengthLimit
                            var value = await streamReader.ReadToEndAsync();

                            if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = String.Empty;
                            }
                            formAccumulator.Append(key.Value, value); // For .NET Core <2.0 remove ".Value" from key

                            if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                            {
                                throw new System.IO.InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                            }
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to a model
            var formValueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);

            return(formValueProvider, images);
        }
Пример #9
0
        public async Task <IActionResult> UpdateProperty([FromRoute] int id, [FromBody] AddProperty addProperty)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var    userCp   = HttpContext.User;
            string landlord = TokenVerifier.GetLandlord(userCp);

            Property currentProperty = await _context.Property.FindAsync(id);

            if (currentProperty == null)
            {
                return(NotFound());
            }

            if (landlord == null || landlord != currentProperty.AppUserRef)
            {
                return(Unauthorized());
            }

            //Generate property
            Property newproperty = _mapper.Map <AddProperty, Property>(addProperty);

            newproperty.PropertyStatus = Property.VerificationStatus.Pending;
            newproperty.AppUserRef     = landlord;

            //Validate new property
            if (!TryValidateModel(newproperty))
            {
                return(BadRequest());
            }

            List <BasicImage> images = new List <BasicImage>();

            int imgCount = 0;

            foreach (string imageStr in addProperty.Images)
            {
                BasicImage bi = WriteImage(imageStr, imgCount);

                if (bi != null)
                {
                    images.Add(bi);
                    imgCount++;
                }
                else
                {
                    CleanImages(images);
                    return(BadRequest());
                }
            }

            List <Image>      oldImages      = _context.Image.Where(i => i.PropertyRef == id).ToList();
            List <BasicImage> oldBasicImages = _mapper.Map <List <Image>, List <BasicImage> >(oldImages);

            //From DB
            foreach (Image i in oldImages)
            {
                _context.Image.Remove(i);
            }

            //From disk
            CleanImages(oldBasicImages);

            currentProperty.AddressLine1        = addProperty.AddressLine1;
            currentProperty.AddressLine2        = addProperty.AddressLine2;
            currentProperty.City                = addProperty.City;
            currentProperty.County              = addProperty.County;
            currentProperty.Postcode            = addProperty.Postcode;
            currentProperty.Longitude           = addProperty.Longitude;
            currentProperty.Latitude            = addProperty.Latitude;
            currentProperty.PropertyDescription = addProperty.PropertyDescription;
            currentProperty.PropertyStatus      = Property.VerificationStatus.Pending;

            foreach (BasicImage bi in images)
            {
                bi.PropertyRef = currentProperty.ID;
                Image im = _mapper.Map <BasicImage, Image>(bi);
                _context.Image.Add(im);
            }

            await _context.SaveChangesAsync();

            return(Ok());
        }