Beispiel #1
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            RequiresAuthorization(AuthorizationStrings.CreateImage);
            var image = new ImageEntity
            {
                Name             = txtImageName.Text,
                Os               = "",
                Environment      = ddlEnvironment.Text,
                Description      = txtImageDesc.Text,
                Protected        = chkProtected.Checked ? 1 : 0,
                IsVisible        = chkVisible.Checked ? 1 : 0,
                Enabled          = 1,
                ClassificationId = Convert.ToInt32(ddlClassification.SelectedValue)
            };

            image.Type    = ddlEnvironment.Text == "macOS" ? "Block" : ddlImageType.Text;
            image.Type    = ddlEnvironment.Text == "winpe" ? "File" : ddlImageType.Text;
            image.OsxType = ddlEnvironment.Text == "macOS" ? "thick" : "";

            var result = Call.ImageApi.Post(image);

            if (result.Success)
            {
                EndUserMessage = "Successfully Added Image";
                Response.Redirect("~/views/images/edit.aspx?imageid=" + result.Id);
            }
            else
            {
                EndUserMessage = result.ErrorMessage;
            }
        }
Beispiel #2
0
        private async void InitializeWindowData()
        {
            companyData = await companyDataServices.GetCompanyData();

            if (companyData != null)
            {
                TextBox_Address.Text        = companyData.address;
                TextBox_Email.Text          = companyData.email;
                TextBox_CompanyName.Text    = companyData.companyName;
                TextBox_PhoneNumber.Text    = companyData.phoneNumber;
                TextBox_WebPageAddress.Text = companyData.webPageAddress;
                TextBox_Username.Text       = companyData.emailUsername;
                TextBox_Password.Text       = companyData.emailPassword;

                List <ImageEntity> companyImages = await imageEntityServices.GetCompanyImageEntities();

                if (companyImages.Count > 0)
                {
                    companyImageInCloud = companyImages[0];
                    string companyImagePath = await imageEntityServices.downloadCompanyImage(companyImageInCloud, imageSavingPath);

                    Image image = Image.FromFile(companyImagePath);
                    addImageToPictureBox(image);
                }
            }
        }
Beispiel #3
0
        public void CreateItem(int buyOut, int userId, int expire, string[] tags, string title, string description, string[] images)
        {
            List <ImageEntity> newImages = new List <ImageEntity>();

            for (int i = 0; i < images.Length; i++)
            {
                ImageEntity item = new ImageEntity();
                item.ImageOfItem = images[i];
                newImages[i]     = item;
            }
            List <TagEntity> newTags = new List <TagEntity>();

            for (int i = 0; i < tags.Length; i++)
            {
                TagEntity tag = new TagEntity();
                tag.Type   = tags[i];
                newTags[i] = tag;
            }
            ItemEntity itemEntity = new ItemEntity()
            {
                BuyOutPrice       = buyOut,
                DateCreated       = DateTime.Now,
                ExpirationDate    = DateTime.Now.AddDays(expire),
                Title             = title,
                Images            = newImages,
                Tags              = newTags,
                DescriptionOfItem = description,
                UserIdSeller      = userId,
            };

            GenerateTags(itemEntity.Title, itemEntity.ItemId);
            db.Add(itemEntity);
            db.SaveChanges();
        }
Beispiel #4
0
        public int Add(ImageEntity entity)
        {
            string sql = @"INSERT INTO image (CategoryId, FilePath, CreateTime)
                        VALUES (@CategoryId, @FilePath, @CreateTime)";

            return(_connection.Execute(sql, entity));
        }
        public async Task<List<ImageEntity>> GetEntityImageEntities(string entityName,string entityId)
        {
            FirestoreDb db = FirestoreDb.Create(GetConstant.FIRESTORE_ID);

            List<ImageEntity> entityImages = new List<ImageEntity>();

            Query entityImagesQuery = db.Collection("Images").WhereEqualTo("EntityName", entityName).WhereEqualTo("EntityId",entityId);
            QuerySnapshot entityImagesQuerySnapshot = await entityImagesQuery.GetSnapshotAsync();
            foreach (DocumentSnapshot documentSnapshot in entityImagesQuerySnapshot.Documents)
            {
                Console.WriteLine("Document data for {0} document:", documentSnapshot.Id);
                Dictionary<string, object> imageValue = documentSnapshot.ToDictionary();
                ImageEntity imageEntity = new ImageEntity(
                    long.Parse(imageValue["Id"].ToString()),
                    imageValue["Link"].ToString(),
                    imageValue["EntityId"].ToString(),
                    imageValue["EntityName"].ToString(),
                    long.Parse(imageValue["ImageNumber"].ToString())

                    );

                entityImages.Add(imageEntity);
            }
            return entityImages;
        }
        /*****************
         * UPDATE
         */
        public IActionResult Edit(int galleryId, int imageId)
        {
            ImageEntity          entity    = imageRepository.FindById(imageId);
            ImageEditorViewModel viewModel = new ImageEditorViewModel(entity.Id, entity.Label, entity.Filename, entity.GalleryId);

            return(View("Editor", viewModel));
        }
Beispiel #7
0
        public async Task GetSubmissionWithEntries_GetsFromDb()
        {
            // Arrange
            ImageEntity imageEntity = EntitiesHelper.GetImage();

            var lCreatedEntity = await submissionRepository.Add(new Entities.SubmissionEntity {
                Notes   = "test", SalonYear = EntitiesHelper.GetSalonYear(), Person = EntitiesHelper.GetPerson(),
                Entries = new List <CompetitionEntryEntity>
                {
                    new CompetitionEntryEntity
                    {
                        Image      = imageEntity,
                        Section    = EntitiesHelper.GetSection(),
                        IsAccepted = true,
                        IsAwarded  = false,
                        Score      = 50
                    },
                    new CompetitionEntryEntity
                    {
                        Image   = imageEntity,
                        Section = EntitiesHelper.GetSection(),
                    }
                }
            });

            // Act
            var lResult = await submissionRepository.GetSubmissionWithEntries(lCreatedEntity.Id);

            // Assert
            Assert.IsNotNull(lResult);
            Assert.IsTrue(lResult.Id > 0);
            Assert.AreEqual("test", lResult.Notes);
            Assert.AreEqual(2, lResult.Entries.Count);
        }
Beispiel #8
0
        public async Task AddOrUpdate(ImageEntity imageEntity)
        {
            var existingEntity = imageGalleryContext.Image
                                 .Include(image => image.ImageTags)
                                 .FirstOrDefault(image => image.ExternalId.Equals(imageEntity.ExternalId));

            if (existingEntity == null)
            {
                imageGalleryContext.Image.Add(imageEntity);
            }
            else
            {
                existingEntity.Author         = imageEntity.Author;
                existingEntity.Camera         = imageEntity.Camera;
                existingEntity.CroppedPicture = imageEntity.CroppedPicture;
                existingEntity.FullPicture    = imageEntity.FullPicture;
                foreach (var imageTag in imageEntity.ImageTags)
                {
                    imageTag.ImageId = existingEntity.Id;
                }
                existingEntity.ImageTags = imageEntity.ImageTags;
            }

            await imageGalleryContext.SaveChangesAsync();
        }
        //הפונקציה מוסיפה שורה לטבלת התמונות, תמונה עם כל הפרטים עליה
        private static async Task <bool> InitImageDetailsAsync(string fileUrl, string fileName)
        {
            try
            {
                ImageEntity img = new ImageEntity();
                img.url  = fileUrl;
                img.name = fileName;
                var resClarifai = await GetResClarifai(fileUrl);

                var resFacePP = getResultFacePP(fileUrl);
                if (resClarifai == null || resFacePP == null)
                {
                    return(false);
                }
                img.isBlur      = IsBlur(resClarifai);
                img.isClosedEye = IsClosedEye(resFacePP);
                img.isGroom     = IsGroom(resFacePP);
                img.numPerson   = await NumPerson(fileUrl);

                if (img.numPerson == -1)
                {
                    return(false);
                }
                img.isIndoors   = IsIndoors(resClarifai);
                img.isOutdoors  = IsOutdoors(resClarifai);
                img.hasChildren = HasChildren(resClarifai);
                img.Add();
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Beispiel #10
0
        private async Task SaveFileToFolder(ImageEntity file, string pathToSave)
        {
            var fileExtension = Path.GetExtension(file.Title);

            if (IsValidFormat(fileExtension) == false)
            {
                throw new InvalidFileFormatException("The file contains the wrong format.");
            }

            var uniqueFileName = Convert.ToString(Guid.NewGuid());

            file.Title = DeleteSpaces(file);

            var newFileTitle = uniqueFileName + fileExtension;

            file.Title = pathToSave + "\\wwwroot\\userImages" + $@"\{newFileTitle}";

            using (FileStream fs = File.Create(file.Title))
            {
                await file.ImageFromForm.CopyToAsync(fs);

                await fs.FlushAsync();
            }

            file.Title = newFileTitle;
        }
Beispiel #11
0
        public void Post()
        {
            var httpRequest = HttpContext.Current.Request;

            foreach (string file in httpRequest.Files)
            {
                var    postedFile = httpRequest.Files[file];
                byte[] bytes;

                using (BinaryReader br = new BinaryReader(postedFile.InputStream))
                {
                    bytes = br.ReadBytes(postedFile.ContentLength);
                }

                var name  = httpRequest.Form["name"];
                var price = httpRequest.Form["price"];
                var pr    = Convert.ToInt32(price);

                ImageEntity image = new ImageEntity()
                {
                    Name = postedFile.FileName, ContentType = postedFile.ContentType, Data = bytes
                };
                HairItem hair = new HairItem()
                {
                    Name = name, Price = Convert.ToInt32(price), HairImage = image
                };
                context.Images.Add(image);
                context.HairItems.Add(hair);
                context.SaveChanges();
            }
        }
Beispiel #12
0
        /// <summary>
        /// 通过datatble获取实体集合
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private List <ImageEntity> GetEntityList(DataTable dt)
        {
            List <ImageEntity> list = new List <ImageEntity>();

            foreach (DataRow dr in dt.Rows)
            {
                ImageEntity entity = new ImageEntity();
                entity.ImageId    = dr["s_id"].ToString();
                entity.UserOpenId = dr["s_useropenid"].ToString();
                entity.FilePath   = dr["s_imgpath"].ToString();

                entity.Renom = dr["s_ornum"].ToString();
                string count = dr["cou"].ToString();
                if (count.Length == 0)
                {
                    entity.FabCount = "0";
                }
                else
                {
                    entity.FabCount = count;
                }
                list.Add(entity);
            }
            return(list);
        }
 public override byte[] ConvertToByte(ImageEntity entity)
 {
     if (entity.Compress == Compress.NONE)
     {
         return(base.ConvertToByte(entity));
     }
     using (var ms = new MemoryStream()) {
         var data  = entity.Picture.ToArray();
         var table = Album.CurrentTable;
         for (var i = 0; i < data.Length; i += 4)
         {
             var color = Color.FromArgb(data[i + 3], data[i + 2], data[i + 1], data[i]);
             if (!table.Contains(color))
             {
                 table.Add(color);
             }
             ms.WriteByte((byte)table.IndexOf(color));
         }
         data = ms.ToArray();
         if (data.Length < 2)
         {
             data = new byte[2];
         }
         return(data);
     }
 }
        public override Bitmap ConvertToBitmap(ImageEntity entity)
        {
            var data = entity.Data;
            var size = entity.Width * entity.Height;

            if (entity.Compress != Compress.ZLIB)
            {
                return(base.ConvertToBitmap(entity));
            }
            data = FreeImage.Uncompress(data, size);
            var table = Album.CurrentTable;

            if (table.Count > 0)
            {
                using (var os = new MemoryStream()) {
                    for (var i = 0; i < data.Length; i++)
                    {
                        var j = data[i] % table.Count;
                        os.WriteColor(table[j], ColorBits.ARGB_8888);
                    }
                    data = os.ToArray();
                }
            }
            return(Tools.FromArray(data, entity.Size));
        }
        public async Task <GeneralStatusEnum> InsertOrMergeEntityAsync(ImageEntity entity)
        {
            try
            {
                if (_table is null)
                {
                    await CreateTableAsync();
                }
                if (entity == null)
                {
                    throw new ArgumentNullException(nameof(entity));
                }
                // Create the InsertOrReplace table operation
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

                // Execute the operation.
                TableResult result = await _table.ExecuteAsync(insertOrMergeOperation);

                var insertedQuote = result.Result as ImageEntity;

                // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure CosmoS DB
                if (result.RequestCharge.HasValue)
                {
                    _log.LogInformation($"Request Charge of InsertOrMerge Operation:{ result.RequestCharge}");
                }

                return(GeneralStatusEnum.Ok);
            }
            catch (Exception e)
            {
                _log.LogInformation(e.Message);
                return(GeneralStatusEnum.ServerError);
            }
        }
Beispiel #16
0
 /// <summary>
 /// 写入单行
 /// </summary>
 /// <param name="entity"></param>
 private void WriteLine(LineEntity entity, Dictionary <string, object> dicSource)
 {
     if (!entity.ListContent.IsNullOrEmpty())
     {
         foreach (ContentEntity item in entity.ListContent)
         {
             if (item is StrLineEntity)
             {
                 StrLineEntity Content = item as StrLineEntity;
                 this.WriteLine(Content);
             }
             else if (item is TextEntity)
             {
                 TextEntity Content = item as TextEntity;
                 this.WriteText(Content, dicSource);
             }
             else if (item is ImageEntity)
             {
                 ImageEntity Content = item as ImageEntity;
                 this.WriteImage(Content, dicSource);
             }
             else if (item is QRCodeEntity)
             {
                 QRCodeEntity Content = item as QRCodeEntity;
                 this.WriteQRCode(Content, dicSource);
             }
             else if (item is BarCodeEntity)
             {
                 BarCodeEntity Content = item as BarCodeEntity;
                 this.WriteBarCode(Content, dicSource);
             }
         }
     }
     this.CurrentHeight += entity.Height;
 }
Beispiel #17
0
        public async Task DeleteImage_mine_and_it_exist()
        {
            // Arrange
            var controller = new ImageController(GalleryService.Object, ImageService.Object);

            controller.ControllerContext = APIControllerUtils.CreateApiControllerContext(UserEntities[0].Id.ToString());

            Guid        imageId     = Guid.NewGuid();
            ImageEntity imageEntity = new ImageEntity()
            {
                Id = imageId, fk_gallery = GalleryEntities[0].Id, gallery = GalleryEntities[0], Name = "Test1", Extension = ".jpg", SizeInBytes = 100
            };

            ImageEntities.Add(imageEntity);

            // Act
            ActionResult response = await controller.DeleteImage(GalleryEntities[0].Id, imageId);

            // Assert
            Assert.IsInstanceOfType(response, typeof(NoContentResult));
            var result = response as NoContentResult;

            Assert.AreEqual(204, result.StatusCode);
            ImageService.Verify(repo => repo.DeleteImageAsync(It.IsAny <Guid>()), Times.Once());
            ImageEntities.Remove(imageEntity);
        }
Beispiel #18
0
        public async Task <CreateImageResult> CreateImageAsync(CreateImageCommand command)
        {
            if (String.IsNullOrWhiteSpace(command.Name))
            {
                return(new CreateImageResult(new Error("Empty name", "Name can't be empty")));
            }

            var image = new ImageEntity()
            {
                Description = command.Description,
                Name        = command.Name,
                Data        = command.Data,
                ContentType = command.ContentType,
                FileName    = command.FileName
            };

            var result = await ImageStore.CreateImageAsync(image, CancellationToken);

            if (result.Succeeded)
            {
                return(new CreateImageResult(image.ImageId));
            }
            else
            {
                return(new CreateImageResult(result.Errors));
            }
        }
Beispiel #19
0
        public override void NewImage(int count, ColorBits type, int index)
        {
            if (count < 1)
            {
                return;
            }
            var array = new ImageEntity[count];

            array[0]       = new ImageEntity(Album);
            array[0].Index = index;
            if (type != ColorBits.LINK)
            {
                array[0].Type = type;
            }
            for (var i = 1; i < count; i++)
            {
                array[i]      = new ImageEntity(Album);
                array[i].Type = type;
                if (type == ColorBits.LINK)
                {
                    array[i].Target = array[0];
                }
                array[i].Index = index + i;
            }
            Album.List.InsertAt(index, array);
        }
 public async Task<bool> DeleteImageEntityFromDatabase(ImageEntity imageEntity)
 {
     FirestoreDb db = FirestoreDb.Create(GetConstant.FIRESTORE_ID);
     DocumentReference docRef = db.Collection("Images").Document(imageEntity.id.ToString());
     await docRef.DeleteAsync();
     return true;
 }
        public ActionResult DeleteImage(string imageName)
        {
            try
            {
                Repository <ImageEntity> imageRepository = new Repository <ImageEntity>();

                ImageEntity image = imageRepository.GetList().Where(img => img.Name.Substring(0, img.Name.IndexOf('.')) == imageName).FirstOrDefault();
                if (image != null)
                {
                    imageRepository.Delete(image.Id);
                    if (System.IO.File.Exists(Server.MapPath("~/Content/Images/Images/LargeImages/" + image.Name)))
                    {
                        System.IO.File.Delete(Server.MapPath("~/Content/Images/Images/LargeImages/" + image.Name));
                    }
                    if (System.IO.File.Exists(Server.MapPath("~/Content/Images/Images/MiddleImages/" + image.Name)))
                    {
                        System.IO.File.Delete(Server.MapPath("~/Content/Images/Images/MiddleImages/" + image.Name));
                    }
                    if (System.IO.File.Exists(Server.MapPath("~/Content/Images/Images/SmallImages/" + image.Name)))
                    {
                        System.IO.File.Delete(Server.MapPath("~/Content/Images/Images/SmallImages/" + image.Name));
                    }

                    return(Json(new { result = "Success" }, JsonRequestBehavior.AllowGet));
                }

                return(Json(new { result = "Fail" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(ProcessException(ex));
            }
        }
        private async Task <ImageEntity> AddImageDetailsToRDS(ImageModel imageModel, string imageKey)
        {
            try
            {
                var imageEntity = new ImageEntity
                {
                    Description = imageModel.Description,
                    FileSizeKb  = ((decimal)imageModel.ImageFile.Length) / 1024,
                    FileType    = imageModel.ImageFile.ContentType,
                    ImageKey    = imageKey,
                    createdDate = DateTime.Now
                };

                _amazonRDS.Images.Add(imageEntity);
                var itensAdded = await _amazonRDS.SaveChangesAsync();

                if (itensAdded == 1)
                {
                    return(imageEntity);
                }
                else
                {
                    throw new CustomException(System.Net.HttpStatusCode.InternalServerError, "An unexpected error occurred. Please try again.");
                }
            }
            catch
            {
                await _awsS3service.RemoveFileAsync(imageKey);

                throw new CustomException(System.Net.HttpStatusCode.InternalServerError, "An unexpected error occurred. Please try again.");
            }
        }
Beispiel #23
0
        public ActionResultDTO CheckApprovalAndChecksum(ImageEntity image, int userId)
        {
            var actionResult = new ActionResultDTO();

            if (image == null)
            {
                actionResult.Success      = false;
                actionResult.ErrorMessage = "Image Does Not Exist";
                return(actionResult);
            }

            if (image.Enabled == 0)
            {
                actionResult.Success      = false;
                actionResult.ErrorMessage = "Image Is Not Enabled";
                return(actionResult);
            }

            if (SettingServices.GetSettingValue(SettingStrings.RequireImageApproval).ToLower() == "true")
            {
                var user = _userServices.GetUser(userId);
                if (user.Membership != "Administrator") //administrators don't need image approval
                {
                    if (!Convert.ToBoolean(image.Approved))
                    {
                        actionResult.Success      = false;
                        actionResult.ErrorMessage = "Image Has Not Been Approved";
                        return(actionResult);
                    }
                }
            }

            actionResult.Success = true;
            return(actionResult);
        }
Beispiel #24
0
        public ActionResultDTO AddImage(ImageEntity image)
        {
            var validationResult = ValidateImage(image, true);
            var actionResult     = new ActionResultDTO();

            if (validationResult.Success)
            {
                _uow.ImageRepository.Insert(image);
                _uow.Save();
                actionResult.Id = image.Id;
                var defaultProfile = SeedDefaultImageProfile(image.Id);
                defaultProfile.ImageId = image.Id;
                new ImageProfileServices().AddProfile(defaultProfile);

                var dirCreateResult = new FilesystemServices().CreateNewImageFolders(image.Name);
                actionResult.Success = dirCreateResult;
            }
            else
            {
                actionResult.ErrorMessage = validationResult.ErrorMessage;
                return(actionResult);
            }

            return(actionResult);
        }
Beispiel #25
0
        public ActionResultDTO UpdateImage(ImageEntity image)
        {
            var originalImage = GetImage(image.Id);

            if (originalImage == null)
            {
                return new ActionResultDTO {
                           ErrorMessage = "Image Not Found", Id = 0
                }
            }
            ;
            var result = new ActionResultDTO();

            var updateFolderName = originalImage.Name != image.Name;
            var oldName          = originalImage.Name;
            var validationResult = ValidateImage(image, false);

            if (validationResult.Success)
            {
                _uow.ImageRepository.Update(image, image.Id);

                _uow.Save();
                result.Id = image.Id;
                if (updateFolderName)
                {
                    result.Success = new FilesystemServices().RenameImageFolder(oldName, image.Name);
                }
                else
                {
                    result.Success = true;
                }
            }
            return(result);
        }
Beispiel #26
0
        /// <summary>
        /// 读取图片的节点
        /// </summary>
        /// <param name="Node"></param>
        /// <returns></returns>
        private ImageEntity ReadImage(XElement Node)
        {
            ImageEntity Result = new ImageEntity();

            float  Left    = Node.Value <float>("Left");
            float  Top     = Node.Value <float>("Top");
            float  Width   = Node.Value <float>("Width");
            float  Heigth  = Node.Value <float>("Heigth");
            string Content = Node.Value;

            if (Content.Contains("{{") && Content.Contains("}}"))
            {
                Result.ContentType = 2;
            }
            else
            {
                Result.ContentType = 1;
            }
            Result.Content = Content;
            Result.Left    = Left;
            Result.Top     = Top;
            Result.Width   = Width;
            Result.Heigth  = Heigth;

            return(Result);
        }
Beispiel #27
0
        /// <summary>
        /// Gets Images for an event asynchronously.
        /// </summary>
        /// <param name="eventID">Identifier of the event which will have it's images retrieved.</param>
        /// <returns>
        /// List of Images for an event.
        /// </returns>
        public async Task <IEnumerable <IImage> > GetImagesAsync(Guid eventID)
        {
            log4net.GlobalContext.Properties["AppName"] = Assembly.GetExecutingAssembly().FullName;
            try
            {
                List <IImage> selectImages = new List <IImage>();
                using (var connection = Connection.CreateConnection())
                    using (NpgsqlCommand command = new NpgsqlCommand(ImageQueryHelper.GetSelectImagesQueryString(), connection))
                    {
                        command.Parameters.AddWithValue(QueryConstants.ParEventId, NpgsqlDbType.Uuid, eventID);

                        await connection.OpenAsync();

                        DbDataReader dr = await command.ExecuteReaderAsync();

                        while (dr.Read())
                        {
                            ImageEntity tmp = new ImageEntity
                            {
                                Id      = new Guid(dr[0].ToString()),
                                EventId = eventID
                            };
                            tmp.Content = (byte[])dr["Content"];
                            selectImages.Add(Mapper.Map <IImage>(tmp));
                        }
                    }
                return(Mapper.Map <IEnumerable <IImage> >(selectImages));
            }
            catch (Exception ex)
            {
                _log.Error(ex.StackTrace, ex);
                throw new Exception(ex.StackTrace);
            }
        }
Beispiel #28
0
        /// <summary>
        /// 读取行元素中的内容元素
        /// </summary>
        /// <param name="EL"></param>
        /// <returns></returns>
        private List <ContentEntity> ReadContent(XElement EL)
        {
            List <ContentEntity> listResult = new List <ContentEntity>();

            foreach (XElement Node in EL.Elements())
            {
                if (Node.Name == "Text")
                {
                    TextEntity Result = this.ReadText(Node);
                    listResult.Add(Result);
                }
                else if (Node.Name == "StrLine")
                {
                    StrLineEntity Result = this.ReadStrLine(Node);
                    listResult.Add(Result);
                }
                else if (Node.Name == "Image")
                {
                    ImageEntity Result = this.ReadImage(Node);
                    listResult.Add(Result);
                }
                else if (Node.Name == "QRCode")
                {
                    QRCodeEntity Result = this.ReadQRCode(Node);
                    listResult.Add(Result);
                }
                else if (Node.Name == "BarCode")
                {
                    BarCodeEntity Result = this.ReadBarCode(Node);
                    listResult.Add(Result);
                }
            }
            return(listResult);
        }
        public override void NewImage(int count, ColorBits type, int index)
        {
            var array = new ImageEntity[count];

            if (count < 1)
            {
                return;
            }
            array[0]       = new ImageEntity(Album);
            array[0].Index = index;
            if (type != ColorBits.LINK)
            {
                array[0].Type = type;
            }
            for (var i = 1; i < count; i++)
            {
                array[i]      = new ImageEntity(Album);
                array[i].Type = type;
                if (type == ColorBits.LINK)
                {
                    array[i].Target = array[0];
                }
                array[i].Index = index + i;
            }
            if (index < Album.List.Count && index > 0)
            {
                Album.List.InsertRange(index, array);
            }
            else
            {
                Album.List.AddRange(array);
            }
        }
Beispiel #30
0
        public async Task <ImageDTO> CreateImageAsync(Guid userId, Guid galleryId, ImageCreationDTO imageCreationDTO)
        {
            ImageEntity entity = imageCreationDTO.ToImageEntity();

            entity.fk_gallery = galleryId;

            ImageEntity addedEntity = await _imageRepository.PostImage(entity);

            if (_imageRepository.Save() == false)
            {
                throw new Exception();
            }

            IFormFile formFile = imageCreationDTO.FormFile;

            if (formFile.Length > 0)
            {
                string extension = Path.GetExtension(formFile.FileName);
                string filename  = addedEntity.Id.ToString();

                byte[] formfileBytes;
                using (Stream stream = formFile.OpenReadStream())
                {
                    formfileBytes = new byte[stream.Length];
                    await stream.ReadAsync(formfileBytes, 0, (int)stream.Length);
                }

                await _fileSystemRepository.SaveFile(formfileBytes, filename, extension);
            }

            return(addedEntity.ToImageDto());
        }
Beispiel #31
0
        public ActionResult Edit(int id, ImageEntity image, HttpPostedFileBase file)
        {
            string[] mediaExtensions = {
                ".PNG", ".JPG", ".JPEG", ".BMP", ".GIF"
            };

            if (image.ImageId > 0)
            {
                if (file == null)
                {
                    Service.ImageUpdate(image.ReportId, image.ImageId, image.Name, image.Description, image.Path);
                }
                else
                {
                    string path = Helpers.SaveFile(file, Server, "images/"+image.ReportId.ToString() + "/");
                    if (mediaExtensions.Contains(Path.GetExtension(path).ToUpperInvariant()))
                    {
                        Service.ImageUpdate(image.ReportId, image.ImageId, image.Name, image.Description, path);
                    }
                    else
                    {
                        TempData["error"] = "Please upload an image file of type PNG, JPG, or GIF";
                        return RedirectToAction("Edit", new { id = id, imageId = image.ImageId});
                    }
                }

            }
            else
            {
                string path = Helpers.SaveFile(file, Server, "images/" + image.ReportId.ToString() + "/");
                if (mediaExtensions.Contains(Path.GetExtension(path).ToUpperInvariant()))
                {
                    Service.ImageAdd(id, image.Name, image.Description, path);
                }
                else
                {
                    TempData["error"] = "Please upload an image file of type PNG, JPG, or GIF";
                    return RedirectToAction("Edit", new { id = id, imageId = image.ImageId });
                }
            }
            return RedirectToAction("Index");
        }
Beispiel #32
0
 public SelectFaceArgs(ImageEntity img, object tag)
     : this(img)
 {
     this.Tag = tag;
 }
Beispiel #33
0
 public SelectFaceArgs(ImageEntity img)
     : this()
 {
     this.Img = img;
 }
        public ActionResult JobPictureItem(string enterpriseJobKey, string itemKey, ImageEntity originalEntity)
        {
            bool isSuccessful = false;
            string displayMessage = string.Empty;
            ImageEntity targetEntity = null;
            if (GuidHelper.IsInvalidOrEmpty(itemKey) == true)
            {
                targetEntity = new ImageEntity();

                targetEntity.RelativeGuid = GuidHelper.TryConvert(enterpriseJobKey);
                targetEntity.ImageCategoryCode = "enterpriserJob";
                targetEntity.CreateTime = DateTime.Now;

                SetTargetJobImageEntityValue(originalEntity, ref  targetEntity);

                isSuccessful = ImageBLL.Instance.Create(targetEntity);
            }
            else
            {
                targetEntity = ImageBLL.Instance.Get(itemKey);
                originalEntity.CreateTime = targetEntity.CreateTime;
                originalEntity.ImageRelativePath = targetEntity.ImageRelativePath;
                originalEntity.ImageType = targetEntity.ImageType;

                SetTargetJobImageEntityValue(originalEntity, ref  targetEntity);
                isSuccessful = ImageBLL.Instance.Update(targetEntity);
            }

            if (isSuccessful == true)
            {
                displayMessage = "数据保存成功";
            }
            else
            {
                displayMessage = "数据保存失败";
            }

            return Json(new LogicStatusInfo(isSuccessful, displayMessage));
        }
        private void SetTargetJobImageEntityValue(ImageEntity originalEntity, ref ImageEntity targetEntity)
        {
            targetEntity.CanUsable = originalEntity.CanUsable;
            targetEntity.ImageStatus = originalEntity.CanUsable;
            targetEntity.ImageOrder = originalEntity.ImageOrder;
            targetEntity.ImageName = originalEntity.ImageName;

            HttpPostedFileBase fileInfo = Request.Files["fileInput"];
            if (fileInfo.HasFile())
            {
                string fileExtensionName = Path.GetExtension(fileInfo.FileName);
                string fileName = string.Format("{0}{1}", GuidHelper.NewGuidString(), fileExtensionName);
                string baseVirtualPath = PathHelper.CombineForVirtual(ImageEntity.ImageVirtualBasePath, "enterpriseJob");

                string nativeFullPath = IOHelper.EnsureDatePath(Request.MapPath(baseVirtualPath), DatePathFormaters.Y_MD);
                nativeFullPath = Path.Combine(nativeFullPath, fileName);
                string relativeVirtualPath = IOHelper.GetRelativeVirtualPath(nativeFullPath, ImageEntity.ImageVirtualBasePath);
                fileInfo.SaveAs(nativeFullPath);

                targetEntity.ImageRelativePath = relativeVirtualPath;
                targetEntity.ImageType = FileHelper.GeFileExtensionNameWithoutDot(fileExtensionName);
            }
        }
Beispiel #36
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="reportId"></param>
        /// <param name="filter"></param>
        /// <param name="recordsPerPage">eg: 10, 25</param>
        /// <param name="page">1 to x</param>
        /// <returns></returns>
        public IList<ImageEntity> ImageList(int reportId, string filter)
        {
            string sql = "Select Id, ReportId, Name, Description, Path from [Image] where reportId = @0";
            if (filter.Length>0) sql += " and (name like @1 OR description like @1)";
            sql += " ORDER BY Id DESC";
            DataTable dt = DB.GetDataTable(new SQLBuilder(sql, reportId.ToString(), "%" + filter + "%"));

            IList<ImageEntity> images = new List<ImageEntity>();
            foreach (DataRow dr in dt.Rows)
            {
                ImageEntity entity = new ImageEntity();
                entity.ImageId = Convert.ToInt32(dr["Id"]);
                entity.ReportId = Convert.ToInt32(dr["ReportId"]);
                entity.Name = dr["Name"].ToString();
                entity.Description = dr["Description"].ToString();
                entity.Path = dr["Path"].ToString();
                images.Add(entity);
            }
            return images;
        }
Beispiel #37
0
 public ImageEntity ImageGet(int reportId, int id)
 {
     ImageEntity entity = new ImageEntity();
     DataTable dt = DB.GetDataTable(new SQLBuilder("Select Id, ReportId, Name, Description, Path from [Image] where Id = @0", id.ToString()));
     if (dt.Rows.Count > 0)
     {
         DataRow dr = dt.Rows[0];
         entity.ImageId = Convert.ToInt32(dr["Id"]);
         entity.ReportId = Convert.ToInt32(dr["ReportId"]);
         entity.Name = dr["Name"].ToString();
         entity.Description = dr["Description"].ToString();
         entity.Path = dr["Path"].ToString();
     }
     return entity;
 }