コード例 #1
0
        public async Task <IActionResult> UploadImage([FromForm(Name = "imageupload")] IFormFile file)
        {
            // validate image extension
            var extension = Path.GetExtension(file.FileName);

            if (string.IsNullOrEmpty(extension))
            {
                return(BadRequest($"No file extension specified"));
            }

            extension = extension.Replace(".", "");
            var isSupported = Regex.IsMatch(extension, "gif|png|jpe?g", RegexOptions.IgnoreCase);

            if (!isSupported)
            {
                return(BadRequest($"{extension} is not supported"));
            }

            using (var memstream = new MemoryStream())
            {
                await file.CopyToAsync(memstream);

                var result = await _repository.Add(file.FileName, memstream.ToArray());

                await _service.NotifyImageCreated(result.Item1);

                return(Created(result.Item2, null));
            }
        }
コード例 #2
0
        public ActionResult AddDeclaration(DeclarationModel declaration)
        {
            ViewBag.Directory = DirectoryTypes.Home;
            InitDropDownItems(CategoryRepository.GetCategoryIdBySubCategoryId(declaration.SubCategoryId), RegionRepository.GetRegionIdByCityyId(declaration.CityId));
            if (ModelState.IsValid)
            {
                var newDeclaration = new Declaration
                {
                    Name          = declaration.NameD,
                    Description   = declaration.Description,
                    SubCategoryId = declaration.SubCategoryId,
                    Type          = DeclarationTypes.OnModeration,
                    UserId        = UserId,
                    CityId        = declaration.CityId,
                };

                DeclarationRepository.Add(newDeclaration);

                foreach (var img in declaration.Images)
                {
                    if (!string.IsNullOrEmpty(img))
                    {
                        ImageRepository.Add(new Image
                        {
                            Name          = img,
                            DeclarationId = newDeclaration.Id,
                        });
                    }
                }
                return(RedirectToAction("Index", "Home"));
            }

            return(View(declaration));
        }
コード例 #3
0
        public async void CreateNewArticle_Created()
        {
            using var db = GetDbContext();

            new DefaultData().InitDbDefault(db);
            ImageRepository imgRepo    = new ImageRepository(db);
            var             newArticle = new Article()
            {
                Body  = "body1",
                Title = "title1",
            };

            db.Articles.Add(newArticle);
            db.SaveChanges();

            var imgForAdd = new CustomImage()
            {
                Path      = "10",
                ArticleId = newArticle.Id,
            };

            await imgRepo.Add(imgForAdd);

            var addedImg = db.Images.FirstOrDefault(x => x.Id == imgForAdd.Id);

            Assert.NotNull(addedImg);
            Assert.Equal(imgForAdd.Path, addedImg.Path);
            Assert.Equal(imgForAdd.ArticleId, addedImg.ArticleId);
        }
コード例 #4
0
        public void ProcessRequest(HttpContext context)
        {
            string   filename     = context.Request.QueryString["filename"].ToString();
            int      Mag_ID       = int.Parse(context.Request.QueryString["Mag_id"].ToString());
            string   Mag_Issue    = context.Request.QueryString["Mag_Issue"].ToString();
            string   Shoot        = context.Request.QueryString["Shoot"].ToString();
            DateTime ShootDate    = DateTime.Parse(context.Request.QueryString["ShootDate"].ToString());
            string   keywords     = context.Request.QueryString["keywords"].ToString();
            string   description  = context.Request.QueryString["description"].ToString();
            string   photographer = context.Request.QueryString["photographer"].ToString();

            using (FileStream fs = File.Create(HttpContext.Current.Server.MapPath("~/photos/" + filename)))
            {
                SaveFile(context.Request.InputStream, fs);
            }

            IImageRepository db       = new ImageRepository();
            IUserRepository  userdb   = new UserRepository();
            tbl_Image        newImage = new tbl_Image();

            newImage.date_uploaded     = DateTime.Now;
            newImage.magazine_id       = Mag_ID;
            newImage.magazine_issue    = Mag_Issue;
            newImage.shoot_description = Shoot;
            newImage.shoot_date        = ShootDate;
            newImage.keywords          = keywords;
            newImage.description       = description;
            newImage.photographer      = userdb.getUserbyUsername(photographer).id;
            newImage.date_updated      = DateTime.Now;


            db.Add(newImage);
            db.Save();
        }
コード例 #5
0
        public ActionResult Upload(Image image, HttpPostedFileBase imageFile)
        {
            string fileName = Guid.NewGuid().ToString() + Path.GetExtension(imageFile.FileName);

            imageFile.SaveAs(Server.MapPath("~/UploadedImages/") + fileName);
            image.FileName = fileName;
            var repo = new ImageRepository(Properties.Settings.Default.ConStr);

            repo.Add(image);
            return(Redirect("/home/index"));
        }
コード例 #6
0
        public async void CreateNewArticles_Created()
        {
            using var db = GetDbContext();

            new DefaultData().InitDbDefault(db);
            ImageRepository imgRepo = new ImageRepository(db);

            var articlesForAdd = new List <Article>()
            {
                new Article()
                {
                    Body  = "body1",
                    Title = "title1",
                },
                new Article()
                {
                    Body  = "body2",
                    Title = "title2",
                },
            };


            db.Articles.AddRange(articlesForAdd);
            db.SaveChanges();

            var imagesForAdd = new List <CustomImage>()
            {
                new CustomImage()
                {
                    Path      = "10",
                    ArticleId = articlesForAdd[0].Id,
                },
                new CustomImage()
                {
                    Path      = "11",
                    ArticleId = articlesForAdd[1].Id,
                },
            };

            await imgRepo.Add(imagesForAdd);

            var addedImg1 = db.Images.FirstOrDefault(x => x.Id == imagesForAdd[0].Id);
            var addedImg2 = db.Images.FirstOrDefault(x => x.Id == imagesForAdd[1].Id);

            Assert.NotNull(addedImg1);
            Assert.Equal(addedImg1.Path, imagesForAdd[0].Path);
            Assert.Equal(addedImg1.ArticleId, imagesForAdd[0].ArticleId);

            Assert.NotNull(addedImg2);
            Assert.Equal(addedImg2.Path, imagesForAdd[1].Path);
            Assert.Equal(addedImg2.ArticleId, imagesForAdd[1].ArticleId);
        }
コード例 #7
0
        public override void Handle(HttpRequest request, HttpResponse response)
        {
            if (string.IsNullOrEmpty(request.Headers["key"]))
            {
                response.Drop("no key given");
                return;
            }

            var key = KeysRepository.Find(request.Headers["key"]);

            if (key == null)
            {
                response.Drop("no key found");
                return;
            }

            if (!new[] { AccessLevel.Admin, AccessLevel.Moderator }.ToList().Contains(key.Level))
            {
                response.Drop("no access");
                return;
            }

            if (request.Files["grekan"] == null)
            {
                response.Drop("no grekan given");
                return;
            }

            var file = request.Files["grekan"];

            using (var image = Image.FromStream(file.InputStream))
            {
                if (image.Width != 960 && image.Height != 960)
                {
                    response.Drop("image is not 960x960");
                    return;
                }

                var ms = new MemoryStream();
                image.Save(ms, ImageFormat.Jpeg);

                ImageRepository.Add(ms.ToArray());

                Logger.Info($"User noted as '{key.Note}' just added a new image.");
                Logger.Info($"http://backend.grekan.tk/get_image?id={ImageRepository.LastId()}");

                ImageRepository.ResetInternalPointer();

                response.WriteLine("s u c c");
            }
        }
コード例 #8
0
        public ActionResult AddOrganization(Organization entity)
        {
            if (Request.Files.Count <= 0)
            {
                ModelState.AddModelError("ImageValidation", "Image seçilmedi");
            }
            if (Request.Files[0].ContentLength <= 0)
            {
                ModelState.AddModelError("ImageValidation", "Image seçilmedir");
            }


            if (!ModelState.IsValid)
            {
                return(View(entity));
            }



            Image image = new Image();

            image.ImageUrl = Request.Files[0].FileName;
            imagerep.Add(image);

            var imagePath = ConfigurationManager.AppSettings["ImagePath"] + "/" + image.Id + "_" + image.ImageUrl;

            Request.Files[0].SaveAs(imagePath);

            entity.ImageId = image.Id;


            orgrep.Add(entity);


            return(RedirectToAction("ListOrgs"));
        }
コード例 #9
0
        public IActionResult PostImage([FromBody] ImageViewModel imageViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var image = imageRepository.Add(imageViewModel, User.GetId());

            if (image == null)
            {
                return(BadRequest());
            }

            return(CreatedAtRoute("GetImage", new { id = image.Id }, image));
        }
コード例 #10
0
        public ActionResult UploadIcon(HttpPostedFileBase file)
        {
            if (!file.ContentType.Contains("image"))
            {
                ModelState.AddModelError("CustomError", @"Wgrywany plik nie jest plikiem graficznym."); //error += "\nWgrywany plik nie jest plikiem graficznym.";
            }
            else
            {
                System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream, true, true);
                if (img.Width > 150 || img.Height > 150)
                {
                    ModelState.AddModelError("CustomError", @"Maksymalny rozmiar ikony to 150x150px.");                                     //error += "Maksymalny rozmiar ikony to 150x150px.";
                }
                if (img.Width < 50 || img.Height < 50)
                {
                    ModelState.AddModelError("CustomError", @"Minimalny rozmiar ikony to 50x50px.");                                    //error += "\nMinimalny rozmiar ikony to 50x50px.";
                }
            }

            file.InputStream.Seek(0, SeekOrigin.Begin);

            if (file.ContentLength > 0 && ModelState.IsValid)
            {
                Guid guid = Guid.NewGuid();

                Image image = new Image()
                {
                    FileName  = file.FileName,
                    ImageType = ImageType.Icon,
                    Favorite  = false,
                    Guid      = guid.ToString()
                };
                BlobConnector.UploadIcon(file, image);
                _repository.Add(image);

                return(RedirectToAction("IconsManagement"));
            }
            else
            {
                ModelState.AddModelError("CustomError", @"Błąd wgrywania pliku.");  //error += "\nBłąd wgrywania pliku";
            }
            return(View("IconsManagement", _repository.GetAll()));
        }
コード例 #11
0
        public ActionResult Index(ImageViewModel model, HttpPostedFileBase fileupload)
        {
            var destination = Server.MapPath("~/images/");

            Directory.CreateDirectory(destination);

            fileupload.SaveAs(Path.Combine(destination, fileupload.FileName));

            ImageViewModel newImage = new ImageViewModel()
            {
                Id       = Guid.NewGuid(),
                Filename = fileupload.FileName,
                Name     = model.Name
            };

            ImageRepository.Add(newImage);

            return(PartialView("_Image"));
        }
コード例 #12
0
        // This function will get triggered/executed when a new message is written
        // on an Azure Queue called queue.
        public static void ProcessQueueMessage([ServiceBusTrigger("thumbnails")] BrokeredMessage message, TextWriter log)
        {
            var imgOriginalId = (Guid)message.Properties["imageId"];
            //var imgOriginalId = Newtonsoft.Json.JsonConvert.DeserializeObject<Guid>(b);

            IRepository <Epam.AzureWorkShop.Entities.Image> imgRepo = new ImageRepository();
            var currentImg = imgRepo.GetById(imgOriginalId);

            using (var image = Image.Load(currentImg.Data))
            {
                image.Mutate(i => i.Resize(150, 150));
                using (var outputMemory = new MemoryStream())
                {
                    image.Save(outputMemory, new PngEncoder());

                    var id = imgRepo.Add(new Epam.AzureWorkShop.Entities.Image
                    {
                        Data = outputMemory.ToArray(),
                    }).Id;

                    var metRep  = new MetadataRepository();
                    var metData = metRep.GetByImageId(imgOriginalId);
                    metData.ThumbnailId = id;
                    metRep.Update(metData);

                    using (var httpClient = new HttpClient())
                    {
                        httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["LogicAppUri"]);

                        var content = new FormUrlEncodedContent(new[]
                        {
                            new KeyValuePair <string, string>(nameof(ImageMetadata.FileName), metData.FileName),
                            new KeyValuePair <string, string>(nameof(ImageMetadata.ImageId), metData.ImageId.ToString()),
                            new KeyValuePair <string, string>(nameof(ImageMetadata.ThumbnailId), metData.ThumbnailId.ToString()),
                        });
                        httpClient.PostAsync(ConfigurationManager.AppSettings["LogicAppUri"], content).Wait();
                    }
                }
            }
        }
コード例 #13
0
        public ActionResult Upload(string Name, string AlternateText, int id)
        {
            try
            {
                PhotoViewModel     photoVM = new PhotoViewModel();
                HttpPostedFileBase file    = Request.Files["OriginalLocation"];
                photoVM.Name          = Name;
                photoVM.AlternateText = AlternateText;

                photoVM.ContentType = file.ContentType;

                Int32  length  = file.ContentLength;
                byte[] tempImg = new byte[length];
                file.InputStream.Read(tempImg, 0, length);
                photoVM.Image = tempImg;
                Image image = new Image();
                image.ImageName   = photoVM.Name;
                image.ImageAlt    = photoVM.AlternateText;
                image.ContentType = photoVM.ContentType;
                image.ImageData   = photoVM.Image;
                imageRepository.Add(image);
                imageRepository.Save();

                ImageSamochod imageSamochod = new ImageSamochod();
                imageSamochod.Opis       = photoVM.AlternateText;
                imageSamochod.ImageId    = image.ImageId;
                imageSamochod.SamochodId = id;
                imageSamochodRepository.Add(imageSamochod);
                imageSamochodRepository.Save();

                return(RedirectToAction("DisplayZdjecia", "Samochod", new { samId = id }));
            }catch (Exception e)
            {
                TempData["errorMessage"] = "Nie udało się dodać zdjęcia!\n" + e;
                return(RedirectToAction("DisplayZdjecia", "Samochod", new { samId = id }));
            }
        }
コード例 #14
0
        /// <summary>
        /// 抓取出租信息
        /// </summary>
        /// <param name="area"></param>
        public void CrawlDataCz(Area area)
        {
            string url = string.Empty;

            try
            {
                Crawler crawler = new Crawler();
                url = area.Url + ConstVar.出租 + "0/";
                string          html      = crawler.Crawl(url, Encoding.UTF8);
                var             htmlParse = new HtmlParser();
                IHtmlDocument   docuement = htmlParse.Parse(html);
                List <IElement> eles      = docuement.QuerySelectorAll("div").ToList().Where(p => p.ClassName == "pager")
                                            .ToList();
                if (eles.Count > 0)
                {
                    IHtmlDocument   htmlA    = htmlParse.Parse(eles[0].InnerHtml);
                    List <IElement> spanEles = htmlA.QuerySelectorAll("span").ToList();


                    int page = 0;
                    if (spanEles.Count > 2)
                    {
                        IElement el = spanEles[spanEles.Count - 2];
                        page = int.Parse(el.InnerHtml);
                    }
                    else
                    {
                        page = 1;
                    }

                    for (int i = 1; i < page + 1; i++)
                    {
                        string str = string.Empty;
                        try
                        {
                            str = url + "pn" + i + "/";
                            Crawler crawlerA = new Crawler();
                            string  htmlB    = crawlerA.Crawl(str, Encoding.UTF8);

                            IDocument docuemnt = htmlParse.Parse(htmlB);
                            IElement  eleist   = docuemnt.QuerySelectorAll("ul")
                                                 .Where(p => p.ClassName == "house-list-wrap").ToList().FirstOrDefault();


                            IDocument       docuementC = htmlParse.Parse(eleist.InnerHtml);
                            List <IElement> eliss      = docuementC.QuerySelectorAll("div").Where(p => p.ClassName == "pic")
                                                         .ToList();
                            Parallel.ForEach(eliss, p =>
                            {
                                string urlA = string.Empty;
                                try
                                {
                                    IDocument documentD = htmlParse.Parse(p.InnerHtml);

                                    IElement eloo = documentD.QuerySelector("a");
                                    urlA          = eloo.GetAttribute("href").ToString();
                                    var htmlE     = crawler.Crawl(eloo.GetAttribute("href").ToString(), Encoding.UTF8);


                                    IDocument documentE = htmlParse.Parse(htmlE);
                                    IElement ele        = documentE.QuerySelectorAll("span")
                                                          .Where(o => o.InnerHtml.StartsWith("更新于")).FirstOrDefault();
                                    DateTime time = ParseTool.StringToDateTime(ele.InnerHtml.Replace("更新于", ""));
                                    if (time > DateTime.Now.AddMonths(-2))
                                    {
                                        IElement InfoTitleElee = documentE.QuerySelectorAll("h1")
                                                                 .FirstOrDefault(o => o.ClassName == "c_000 f20");

                                        IElement money = documentE.QuerySelectorAll("span")
                                                         .FirstOrDefault(o => o.ClassName == "house_basic_title_money_num");
                                        var InfoContent = documentE.QuerySelectorAll("div")
                                                          .Where(o => o.ClassName == "general-item-wrap").FirstOrDefault(u =>
                                                                                                                         u.ParentElement.ClassName == "general-item general-miaoshu");
                                        var Customer = documentE.QuerySelectorAll("span")
                                                       .FirstOrDefault(o => o.ClassName == "f14 c_333 jjrsay");
                                        var phone = documentE.QuerySelectorAll("p")
                                                    .FirstOrDefault(o => o.ClassName == "phone-num");


                                        var InfoEles = htmlParse.Parse(documentE.QuerySelectorAll("ul")
                                                                       .FirstOrDefault(o => o.ClassName == "house_basic_title_content")
                                                                       ?.InnerHtml).QuerySelectorAll("li").ToList();
                                        //面积
                                        IElement areasize = htmlParse.Parse(InfoEles[0].InnerHtml)
                                                            .QuerySelectorAll("span")
                                                            .FirstOrDefault(o => o.ClassName == "house_basic_title_content_item2");
                                        //行业名字
                                        IElement IndustryName = htmlParse.Parse(InfoEles[2].InnerHtml)
                                                                .QuerySelectorAll("span")
                                                                .FirstOrDefault(o => o.ClassName == "house_basic_title_content_item3");
                                        IElement address = htmlParse.Parse(InfoEles[5].InnerHtml).QuerySelectorAll("a")
                                                           .FirstOrDefault(o =>
                                                                           o.ClassName == "house_basic_title_content_item3 blue-link");
                                        IElement addressDetail = htmlParse.Parse(InfoEles[5].InnerHtml)
                                                                 .QuerySelectorAll("span")
                                                                 .FirstOrDefault(o =>
                                                                                 o.ClassName == "house_basic_title_content_item3 xxdz-des");

                                        var shoptransfer = new ShopRentOrTransfer()
                                        {
                                            Id            = Guid.NewGuid(),
                                            ShopArea      = areasize == null ? "" : areasize.InnerHtml,
                                            InfoTitle     = InfoTitleElee == null ? "" : InfoTitleElee.InnerHtml,
                                            TransFerMoney = money == null ? "" : money.InnerHtml,
                                            Address       = address == null ? "" : string.Join("", address.InnerHtml),
                                            DetailAddress = addressDetail == null ? "" : addressDetail.InnerHtml,
                                            InfoContent   = InfoContent == null ? "" : InfoContent.InnerHtml,
                                            InfoType      = Model.BaseModel.InfoType.出租,
                                            IndustryName  = IndustryName == null ? "" : IndustryName.InnerHtml,
                                            Customer      = Customer == null ? "" : Customer.InnerHtml,
                                            Phone         = phone == null ? "" : phone.InnerHtml,
                                            AreaId        = area.Id.ToString(),
                                            UpdateTime    = time
                                        };
                                        var imgUl = documentE.QuerySelectorAll("ul")
                                                    .FirstOrDefault(o => o.ClassName == "general-pic-list");

                                        object obj    = shoprepo.Add(shoptransfer);
                                        bool resultId = (bool)obj;


                                        Console.WriteLine(area.Name + "添加一条出租信息");
                                        if (imgUl != null && resultId)
                                        {
                                            IDocument documentf = htmlParse.Parse(imgUl.InnerHtml);
                                            var tem             = documentf.QuerySelectorAll("img")
                                                                  .Select(o => o.GetAttribute("data-src"));
                                            if (tem != null && tem.Count() > 0)
                                            {
                                                foreach (var o in tem)
                                                {
                                                    if (o != null)
                                                    {
                                                        Bitmap img = crawler.CrawlPic(o);
                                                        if (img != null)
                                                        {
                                                            string path =
                                                                AppDomain.CurrentDomain.BaseDirectory + "Imgs/" +
                                                                shoptransfer.Id + "/";
                                                            if (!Directory.Exists(path))
                                                            {
                                                                Directory.CreateDirectory(path);
                                                            }

                                                            string fullPath =
                                                                path + Guid.NewGuid().ToString().Replace("-", "") +
                                                                ".png";
                                                            img.Save(fullPath);
                                                            string savePath = fullPath.Replace(
                                                                AppDomain.CurrentDomain.BaseDirectory,
                                                                "");
                                                            imgrepo.Add(new Model.Image()
                                                            {
                                                                FkId     = shoptransfer.Id,
                                                                ImageUrl = savePath,
                                                                InfoType = TableType.ShopRentOrTransfer,
                                                            });
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    errorUrlrepsitory.Add(new ErrorUrl()
                                    {
                                        UrlType = UrlType.Item, Url = urlA
                                    });
                                    log.Error(e.ToString());
                                }
                            });
                        }
                        catch (Exception e)
                        {
                            errorUrlrepsitory.Add(new ErrorUrl()
                            {
                                UrlType = UrlType.Page, Url = str
                            });
                            log.Error(e.ToString());
                        }
                    }
                }

                Console.WriteLine(area.Name + "出租信息抓取完成");
            }
            catch (Exception e)
            {
                errorUrlrepsitory.Add(new ErrorUrl()
                {
                    UrlType = UrlType.All, Url = url
                });
                log.Error(e.ToString());
            }
        }
コード例 #15
0
        public ActionResult Upload(string Name, string AlternateText, int id, string mode)
        {
            try
            {
                PhotoViewModel     photoVM = new PhotoViewModel();
                HttpPostedFileBase file    = Request.Files["OriginalLocation"];
                photoVM.Name          = Name;
                photoVM.AlternateText = AlternateText;

                photoVM.ContentType = file.ContentType;

                Int32  length  = file.ContentLength;
                byte[] tempImg = new byte[length];
                file.InputStream.Read(tempImg, 0, length);
                photoVM.Image = tempImg;
                Image image = new Image();
                image.ImageName   = photoVM.Name;
                image.ImageAlt    = photoVM.AlternateText;
                image.ContentType = photoVM.ContentType;
                image.ImageData   = photoVM.Image;
                imageRepository.Add(image);
                imageRepository.Save();

                switch (mode)
                {
                case "1":
                    ImageDowodOsobisty imageDowodOsobisty = new ImageDowodOsobisty();
                    DowodOsobisty      dowod = new DowodOsobisty();
                    dowod.NrDowodu       = "tbd";
                    dowod.TerminWaznosci = DateTime.Now;
                    dowod.PESEL          = 00000000000;
                    dowod.OsobaId        = id;
                    dowodOsobistyRepository.Add(dowod);
                    dowodOsobistyRepository.Save();

                    imageDowodOsobisty.Opis            = photoVM.AlternateText;
                    imageDowodOsobisty.ImageId         = image.ImageId;
                    imageDowodOsobisty.DowodOsobistyId = dowod.DowodOsobistyId;
                    imageDowodOsobistyRepository.Add(imageDowodOsobisty);
                    imageDowodOsobistyRepository.Save();

                    break;

                case "2":
                    ImagePaszport imagePaszport = new ImagePaszport();
                    Paszport      paszport      = new Paszport();
                    paszport.NrPaszportu    = "tbd";
                    paszport.TerminWaznosci = DateTime.Now;
                    paszport.OsobaId        = id;
                    paszportRepository.Add(paszport);
                    paszportRepository.Save();

                    imagePaszport.Opis       = photoVM.AlternateText;
                    imagePaszport.ImageId    = image.ImageId;
                    imagePaszport.PaszportId = paszport.PaszportId;
                    imagePaszportRepository.Add(imagePaszport);
                    imagePaszportRepository.Save();
                    break;

                default:
                    break;
                }

                return(RedirectToAction("DisplayZdjecia", "Osoba", new { OsobaId = id }));
            }
            catch (Exception e)
            {
                TempData["errorMessage"] = "Nie udało się dodać zdjęcia!\n" + e;
                return(RedirectToAction("Details", "Osoba", id));
            }
        }