コード例 #1
0
        public async Task <ActionResult <Ad> > PostAd([FromForm] AdDTO adDTO)
        {
            if (!UserExists(adDTO.User))
            {
                return(NotFound());
            }

            var maxAds = _options.PublishOptions.MaxAdsByUser;

            if (await _context.Users.Where(user => user.Id == adDTO.User).CountAsync() >= maxAds)
            {
                return(BadRequest());
            }

            var maxNumber = 0;

            if (await _context.Ads.CountAsync() > 0)
            {
                maxNumber = _context.Ads.Max(x => x.Number);
            }

            var adId     = Guid.NewGuid();
            var imageUrl = "";

            if (adDTO.Image != null)
            {
                IImageFileManager imageManager = new ImageFileManager(_options, _cacheController);
                imageUrl = imageManager.GenerateURL(adId.ToString(), adDTO.Image.FileName);
                try
                {
                    await imageManager.UploadImageAsync(adDTO.Image, imageUrl);
                }
                catch (Exception)
                {
                    return(Problem("Возникла ошибка при загрузке изображения", null,
                                   StatusCodes.Status500InternalServerError, "Ошибка загрузки изображения"));
                }
            }

            var ad = new Ad
            {
                Id       = adId,
                Created  = DateTime.Now,
                Number   = maxNumber + 1,
                Rating   = new Random().Next(-5, 10),
                User     = adDTO.User,
                Subject  = adDTO.Subject,
                Content  = adDTO.Content ?? adDTO.Subject,
                ImageURL = imageUrl
            };

            await _context.Ads.AddAsync(ad);

            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetAd), new { id = ad.Id }, ad));
        }
コード例 #2
0
        public async Task <IActionResult> DeleteBannerImage(int id)
        {
            var     fileManager = new ImageFileManager(_context, _hostingEnvironment.WebRootPath, Path.Combine("usercontent", "bannerimages"));
            Project project     = await _context.Projects.Include(p => p.BannerImage).FirstAsync(p => p.Id == id);

            fileManager.DeleteImageFileIfExists(project.BannerImage);
            project.BannerImageFileId = null;
            await _context.SaveChangesAsync();

            return(RedirectToAction("ManageProject", new { id = id }));
        }
コード例 #3
0
 private void CheckFileType(string extension)
 {
     if (extension == ".pdf")
     {
         PdfFileManager pdfRecognizer = new PdfFileManager();
         CreateMainViewer(pdfRecognizer);
     }
     else if (extension == ".txt")
     {
         TextFileManager txtRecognizer = new TextFileManager();
         CreateMainViewer(txtRecognizer);
     }
     else if (extension == ".jpg" || extension == ".jpeg" || extension == ".bmp" || extension == ".png")
     {
         ImageFileManager imageRecognizer = new ImageFileManager();
         CreateMainViewer(imageRecognizer);
     }
     else
     {
         MessageBox.Show("Неизвестный файл");
     }
 }
コード例 #4
0
        /// <summary>
        /// Sets Clipboard text and returns the content
        /// </summary>
        /// <returns></returns>
        public static string SetClipboardText(WorkerTask task, bool showDialog)
        {
            string clipboardText = "";

            switch (task.JobCategory)
            {
                case JobCategoryType.PICTURES:
                case JobCategoryType.SCREENSHOTS:
                case JobCategoryType.BINARY:
                    ScreenshotsHistory = task.LinkManager;
                    if (GraphicsMgr.IsValidImage(task.LocalFilePath))
                    {
                        if (Engine.conf.ShowClipboardModeChooser || showDialog)
                        {
                            ClipboardOptions cmp = new ClipboardOptions(task);
                            cmp.Icon = Resources.zss_main;
                            if (showDialog) { cmp.ShowDialog(); } else { cmp.Show(); }
                        }

                        if (task.MyImageUploader == ImageDestType.FILE)
                        {
                            clipboardText = task.LocalFilePath;
                        }
                        else
                        {
                            clipboardText = ScreenshotsHistory.GetUrlByType(Engine.conf.ClipboardUriMode).ToString().Trim();
                            if (task.MakeTinyURL)
                            {
                                string tinyUrl = ScreenshotsHistory.GetUrlByType(ClipboardUriType.FULL_TINYURL);
                                if (!string.IsNullOrEmpty(tinyUrl))
                                {
                                    clipboardText = tinyUrl.Trim();
                                }
                            }
                        }
                    }
                    break;
                case JobCategoryType.TEXT:
                    switch (task.Job)
                    {
                        case WorkerTask.Jobs.LANGUAGE_TRANSLATOR:
                            if (null != task.TranslationInfo)
                            {
                                clipboardText = task.TranslationInfo.Result.TranslatedText;
                            }
                            break;
                        default:
                            if (!string.IsNullOrEmpty(task.RemoteFilePath))
                            {
                                clipboardText = task.RemoteFilePath;
                            }
                            else if (null != task.MyText)
                            {
                                clipboardText = task.MyText.LocalString;
                            }
                            else
                            {
                                clipboardText = task.LocalFilePath;
                            }
                            break;
                    }
                    break;
            }

            // after all this the clipboard text can be null

            if (!string.IsNullOrEmpty(clipboardText))
            {
                Engine.ClipboardUnhook();
                FileSystem.AppendDebug("Setting Clipboard with URL: " + clipboardText);
                Clipboard.SetText(clipboardText);

                // optional deletion link
                string linkdel = ScreenshotsHistory.GetDeletionLink();
                if (!string.IsNullOrEmpty(linkdel))
                {
                    FileSystem.AppendDebug("Deletion Link: " + linkdel);
                }

                Engine.zClipboardText = clipboardText;
                Engine.ClipboardHook();
            }
            return clipboardText;
        }
コード例 #5
0
        public async Task <IActionResult> Create(CreateProjectViewModel model)
        {
            // Make sure the project name is unique.
            if (await _context.Projects.AnyAsync(p => p.Name == model.Name))
            {
                ModelState.AddModelError("Name", _localizer["A project with the same name already exists."]);
            }

            // If there are image descriptions without corresponding image uploads, warn the user.
            if (model.BannerImageUpload == null && !string.IsNullOrWhiteSpace(model.BannerImageDescription))
            {
                ModelState.AddModelError("BannerImageDescription", _localizer["You can only provide a 'Banner Image Description' if you upload a 'Banner Image'."]);
            }
            if (model.DescriptiveImageUpload == null && !string.IsNullOrWhiteSpace(model.DescriptiveImageDescription))
            {
                ModelState.AddModelError("DescriptiveImageDescription", _localizer["You can only provide a 'DescriptiveImage Description' if you upload a 'DescriptiveImage'."]);
            }

            if (!ModelState.IsValid)
            {
                model.Categories = new SelectList(await _context.Categories.ToListAsync(), "Id", "Description");
                return(View(model));
            }

            var project = new Project
            {
                OwnerId         = (await _userManager.GetUserAsync(User)).Id,
                Name            = model.Name,
                Description     = model.Description,
                Goal            = model.Goal,
                Proposal        = model.Proposal,
                CreatorComments = model.CreatorComments,
                CategoryId      = model.CategoryId,
                LocationId      = model.LocationId,
                Target          = model.Target,
                Start           = model.Start,
                End             = model.End.Date.AddHours(23).AddMinutes(59).AddSeconds(59),
                BannerImage     = null
            };

            var bannerImageManager = new ImageFileManager(_context, _hostingEnvironment.WebRootPath, Path.Combine("usercontent", "bannerimages"));

            project.BannerImage = await bannerImageManager.CreateOrReplaceImageFileIfNeeded(project.BannerImage, model.BannerImageUpload, model.BannerImageDescription);

            var descriptiveImageManager = new ImageFileManager(_context, _hostingEnvironment.WebRootPath, Path.Combine("usercontent", "descriptiveimages"));

            project.DescriptiveImage = await descriptiveImageManager.CreateOrReplaceImageFileIfNeeded(project.DescriptiveImage, model.DescriptiveImageUpload, model.DescriptiveImageDescription);

            _context.Add(project);
            await _context.SaveChangesAsync();

            project.SetDescriptionVideoLink(_context, model.DescriptionVideoLink);

            // Only call this once we have a valid Project.Id
            await project.SetTags(_context, model.Hashtag?.Split(';') ?? new string[0]);

            // Notify admins and creator through e-mail
            string confirmationEmail =
                "Hi!<br>" +
                "<br>" +
                "Thanks for submitting a project on www.collaction.org!<br>" +
                "The CollAction Team will review your project as soon as possible – if it meets all the criteria we’ll publish the project on the website and will let you know, so you can start promoting it! If we have any additional questions or comments, we’ll reach out to you by email.<br>" +
                "<br>" +
                "Thanks so much for driving the CollAction / crowdacting movement!<br>" +
                "<br>" +
                "Warm regards,<br>" +
                "The CollAction team";
            string subject = $"Confirmation email - start project {project.Name}";

            ApplicationUser user = await _userManager.GetUserAsync(User);

            await _emailSender.SendEmailAsync(user.Email, subject, confirmationEmail);

            string confirmationEmailAdmin =
                "Hi!<br>" +
                "<br>" +
                $"There's a new project waiting for approval: {project.Name}<br>" +
                "Warm regards,<br>" +
                "The CollAction team";

            var administrators = await _userManager.GetUsersInRoleAsync("admin");

            foreach (var admin in administrators)
            {
                await _emailSender.SendEmailAsync(admin.Email, subject, confirmationEmailAdmin);
            }

            return(View("ThankYouCreate", new ThankYouCreateProjectViewModel()
            {
                Name = project.Name
            }));
        }
コード例 #6
0
        private static void Main()
        {
            Console.WriteLine(sad);
            var sqlEngine = new SqlDbEngine(SqlConnectionString);

            //Task 1
            WriteLine("1.Write a program that retrieves from the Northwind sample database in MS SQL Server the number of rows in the Categories table.");
            var categoryCount = sqlEngine.GetNumberOfRowsFor("Categories");

            WriteLine("Total categories: " + categoryCount);
            Divide();

            //Task 2
            WriteLine("2.Write a program that retrieves the name and description of all categories in the Northwind DB.");
            var categoryNamesAndDescriptions = sqlEngine.GetCategoryNamesAndDescriptions();

            foreach (var category in categoryNamesAndDescriptions)
            {
                WriteLine(string.Format(ResultFormat, category.CategoryName, category.Description));
            }

            Divide();

            //Task 3
            WriteLine("3.Write a program that retrieves from the Northwind database all product categories and the names of the products in each category.");
            var categoryWithProducts = sqlEngine.GetProductsGroupedByCategory();

            foreach (var category in categoryWithProducts)
            {
                WriteLine(string.Format(ResultFormat, category.CategoryName, category.Products));
            }

            Divide();

            //Task 4
            sqlEngine.InsertProduct("Pesho", 2, 3, "Many peshos per unit", 1050000.3m, 5000);

            //Task 5
            WriteLine("5.Write a program that retrieves the images for all categories in the Northwind database and stores them as JPG files in the file system.");
            var images      = sqlEngine.GetAllCategoryImages();
            var fileManager = new ImageFileManager();

            for (var i = 0; i < images.Count; i++)
            {
                fileManager.WriteToDisk($"..\\..\\..\\..\\CategoryImages\\image-{i + 1}.jpg", images[i].Picture);
            }

            WriteLine("Downloaded and saved category images to ..\\..\\..\\..\\CategoryImages\\");
            Divide();

            //Task 6
            WriteLine("6.Write a program that reads your MS Excel file through the OLE DB data provider and displays the name and score row by row.");
            var oleDbEngine = new OleDbEngine(OledbConnectionString);
            var scores      = oleDbEngine.GetPersonScores();

            foreach (var personScore in scores)
            {
                WriteLine(string.Format(ResultFormat, personScore.Name, personScore.Score));
            }

            Divide();

            //Task 7
            oleDbEngine.InsertPerson("Tosho", 50);

            //Task 8
            WriteLine("8.Write a program that reads a string from the console and finds all products that contain this string.");

            var pattern      = GetUserInput("product");
            var searchResult = sqlEngine.SearchProductsByName(pattern);

            foreach (var product in searchResult)
            {
                WriteLine(product.ProductName);
            }

            Divide();

            //Task 9
            WriteLine("9.Write methods for listing all books, finding a book by name and adding a book from a MySql Database.");

            var mySqlDb  = new MySqlDbEngine(MySqlConnectionString);
            var allBooks = mySqlDb.ListAllBooks();

            foreach (var book in allBooks)
            {
                WriteLine(string.Format(ResultFormat, book.Author, book.Name));
            }

            Divide();

            //Task 9.1
            var bookSearchPattern = GetUserInput("book");
            var bookSearchResult  = mySqlDb.SearchForBooksByName(bookSearchPattern);

            foreach (var book in bookSearchResult)
            {
                WriteLine(string.Format(ResultFormat, book.Author, book.Name));
            }
            Divide();

            //Task 9.2
            mySqlDb.AddBook("The Art of War", "Sun Tzu", "56453-5654-4512", DateTime.Now);

            var sqlLiteDb = new SqLiteDbEngine(SqLiteConnectionString);

            //Task 10.2
            sqlLiteDb.AddBook("The Art of Unit Testing", "Roy Osherove", "9781933988276", DateTime.Now);

            //Task 10
            WriteLine("Re-implement the previous task with SQLite embedded DB.");
            var result = sqlLiteDb.ListAllBooks();

            foreach (var book in result)
            {
                WriteLine(string.Format(ResultFormat, book.Author, book.Name));
            }

            Divide();

            //Task 10.1
            var bookSearchPatternLite = GetUserInput("book");
            var bookSearchLiteResult  = sqlLiteDb.SearchForBooksByName(bookSearchPatternLite);

            foreach (var book in bookSearchLiteResult)
            {
                WriteLine(string.Format(ResultFormat, book.Author, book.Name));
            }

            Divide();
        }
コード例 #7
0
        public async Task <IActionResult> ManageProject(ManageProjectViewModel model)
        {
            Project project = await _context.Projects
                              .Where(p => p.Id == model.Id)
                              .Include(p => p.Owner)
                              .Include(p => p.Tags)
                              .ThenInclude(t => t.Tag)
                              .Include(p => p.DescriptionVideoLink)
                              .Include(p => p.BannerImage)
                              .Include(p => p.DescriptiveImage)
                              .FirstAsync();

            // If the project name changed make sure it is still unique.
            if (project.Name != model.Name && await _context.Projects.AnyAsync(p => p.Name == model.Name))
            {
                ModelState.AddModelError("Name", _localizer["A project with the same name already exists."]);
            }

            // If there are image descriptions without corresponding image uploads, warn the user.
            if (project.BannerImage == null && model.BannerImageUpload == null && !string.IsNullOrWhiteSpace(model.BannerImageDescription))
            {
                ModelState.AddModelError("BannerImageDescription", _localizer["You can only provide a 'Banner Image Description' if you upload a 'Banner Image'."]);
            }
            if (project.DescriptiveImage == null && model.DescriptiveImageUpload == null && !string.IsNullOrWhiteSpace(model.DescriptiveImageDescription))
            {
                ModelState.AddModelError("DescriptiveImageDescription", _localizer["You can only provide a 'DescriptiveImage Description' if you upload a 'DescriptiveImage'."]);
            }

            if (ModelState.IsValid)
            {
                bool approved    = model.Status == ProjectStatus.Running && project.Status == ProjectStatus.Hidden;
                bool successfull = model.Status == ProjectStatus.Successful && project.Status == ProjectStatus.Running;
                bool failed      = model.Status == ProjectStatus.Failed && project.Status == ProjectStatus.Running;

                if (approved)
                {
                    string approvalEmail =
                        "Hi!<br>" +
                        "<br>" +
                        "The CollAction Team has reviewed your project proposal and is very happy to share that your project has been approved and now live on www.collaction.org!<br>" +
                        "<br>" +
                        "So feel very welcome to start promoting it! If you have any further questions, feel free to contact the CollAction Team at [email protected]. And don’t forget to tag CollAction in your messages on social media so we can help you spread the word(FB: @collaction.org, Twitter: @collaction_org)!<br>" +
                        "<br>" +
                        "Thanks again for driving the CollAction / crowdacting movement!<br>" +
                        "<br>" +
                        "Warm regards,<br>" +
                        "The CollAction team<br>";

                    string subject = $"Approval - {project.Name}";

                    await _emailSender.SendEmailAsync(project.Owner.Email, subject, approvalEmail);
                }
                else if (successfull)
                {
                    string successEmail =
                        "Hi!<br>" +
                        "<br>" +
                        "The deadline of the project you have started on www.collaction.org has passed. We're very happy to see that the target you have set has been reached! Congratulations! Now it's time to act collectively!<br>" +
                        "<br>" +
                        "The CollAction Team might reach out to you with more specifics (this is an automated message). If you have any further questions yourself, feel free to contact the CollAction Team at [email protected]. And don’t forget to tag CollAction in your messages on social media so we can help you spread the word on your achievement (FB: @collaction.org, Twitter: @collaction_org)!<br>" +
                        "<br>" +
                        "Thanks again for driving the CollAction / crowdacting movement!<br>" +
                        "<br>" +
                        "Warm regards,<br>" +
                        "The CollAction team<br>";

                    string subject = $"Success - {project.Name}";

                    await _emailSender.SendEmailAsync(project.Owner.Email, subject, successEmail);
                }
                else if (failed)
                {
                    string failedEmail =
                        "Hi!<br>" +
                        "<br>" +
                        "The deadline of the project you have started on www.collaction.org has passed. Unfortunately the target that you have set has not been reached. Great effort though!<br>" +
                        "<br>" +
                        "The CollAction Team might reach out to you with more specifics (this is an automated message). If you have any further questions yourself, feel free to contact the CollAction Team at [email protected].<br>" +
                        "<br>" +
                        "Thanks again for driving the CollAction / crowdacting movement and better luck next time!<br>" +
                        "<br>" +
                        "Warm regards,<br>" +
                        "The CollAction team<br>";

                    string subject = $"Failed - {project.Name}";

                    await _emailSender.SendEmailAsync(project.Owner.Email, subject, failedEmail);
                }

                project.Name            = model.Name;
                project.Description     = model.Description;
                project.Goal            = model.Goal;
                project.Proposal        = model.Proposal;
                project.CreatorComments = model.CreatorComments;
                project.CategoryId      = model.CategoryId;
                project.Target          = model.Target;
                project.Start           = model.Start;
                project.End             = model.End.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
                project.Status          = model.Status;
                project.OwnerId         = model.OwnerId;
                project.DisplayPriority = model.DisplayPriority;

                var bannerImageManager = new ImageFileManager(_context, _hostingEnvironment.WebRootPath, Path.Combine("usercontent", "bannerimages"));
                project.BannerImage = await bannerImageManager.CreateOrReplaceImageFileIfNeeded(project.BannerImage, model.BannerImageUpload, model.BannerImageDescription);

                var descriptiveImageManager = new ImageFileManager(_context, _hostingEnvironment.WebRootPath, Path.Combine("usercontent", "descriptiveimages"));
                project.DescriptiveImage = await descriptiveImageManager.CreateOrReplaceImageFileIfNeeded(project.DescriptiveImage, model.DescriptiveImageUpload, model.DescriptiveImageDescription);

                await project.SetTags(_context, model.Hashtag?.Split(';') ?? new string[0]);

                project.SetDescriptionVideoLink(_context, model.DescriptionVideoLink);

                await _context.SaveChangesAsync();

                return(RedirectToAction("ManageProjectsIndex"));
            }
            else
            {
                model.UserList             = new SelectList(await _context.Users.ToListAsync(), "Id", "UserName", null);
                model.CategoryList         = new SelectList(await _context.Categories.ToListAsync(), "Id", "Name", null);
                model.DisplayPriorityList  = new SelectList(Enum.GetValues(typeof(ProjectDisplayPriority)));
                model.StatusList           = new SelectList(Enum.GetValues(typeof(ProjectStatus)));
                model.BannerImageFile      = project.BannerImage;
                model.DescriptiveImageFile = project.DescriptiveImage;
                return(View(model));
            }
        }
コード例 #8
0
ファイル: ImagesController.cs プロジェクト: mapleFU/ECBackend
        public HttpResponseMessage PostImage()
        {
            Dictionary <string, object> dict = new Dictionary <string, object>();
            List <object> imageUrls          = new List <object>();

            try
            {
                var httpRequest = HttpContext.Current.Request;
                System.Diagnostics.Debug.WriteLine("Image enter");
                IList <string> AllowedFileExtensions = new List <string> {
                    ".jpg", ".gif", ".png"
                };
                System.Diagnostics.Debug.WriteLine(httpRequest.Files.Count);
                foreach (string file in httpRequest.Files)
                {
                    System.Diagnostics.Debug.WriteLine("Image is" + file);
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

                    var postedFile = httpRequest.Files[file];
                    if (postedFile != null && postedFile.ContentLength > 0)
                    {
                        int MaxContentLength = 1024 * 1024 * 5; //Size = 1 MB


                        var ext       = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                        var extension = ext.ToLower();
                        if (!AllowedFileExtensions.Contains(extension))
                        {
                            var message = string.Format("Please Upload image of type .jpg,.gif,.png.");

                            dict.Add("error", message);
                            return(Request.CreateResponse(HttpStatusCode.BadRequest, dict));
                        }
                        else if (postedFile.ContentLength > MaxContentLength)
                        {
                            var message = string.Format("Please Upload a file upto 5 mb.");

                            dict.Add("error", message);
                            return(Request.CreateResponse(HttpStatusCode.BadRequest, dict));
                        }
                        else
                        {
                            KeyValuePair <string, string> pair = ImageFileManager.Upload(postedFile);
                            string fileUrl  = pair.Key;
                            string filePath = pair.Value;
                            System.Diagnostics.Debug.WriteLine("Image is" + fileUrl);
                            var obj = new
                            {
                                fileUrl  = fileUrl,
                                filePath = filePath
                            };
                            imageUrls.Add(obj);
                            System.Diagnostics.Debug.WriteLine(fileUrl, filePath);
                            //YourModelProperty.imageurl = userInfo.email_id + extension;
                            ////  where you want to attach your imageurl

                            ////if needed write the code to update the table

                            //var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + userInfo.email_id + extension);
                            ////Userimage myfolder name where i want to save my image
                            //postedFile.SaveAs(filePath);
                        }
                    }
                }
                if (imageUrls.Count == httpRequest.Files.Count)
                {
                    var message1 = string.Format("Image Updated Successfully.");
                    dict.Add("images", imageUrls);
                    return(Request.CreateResponse(HttpStatusCode.Created, dict));
                }
                var res = string.Format("Please Upload a image.");
                dict.Add("error", res);

                return(Request.CreateResponse(HttpStatusCode.NotFound, dict));
            }
            catch (Exception ex)
            {
                var res = string.Format("some Message");
                dict.Add("error", res);
                return(Request.CreateResponse(HttpStatusCode.NotFound, dict));
            }
        }
コード例 #9
0
        public async Task <IActionResult> Upload(PostUploadViewModel model)
        {
            ViewBag.SubsectionPages = _subsectionPages;
            ViewBag.ActiveSubpage   = _subsectionPages[2];
            if (ModelState.IsValid)
            {
                if (!_signInManager.IsSignedIn(User))
                {
                    ModelState.AddModelError(string.Empty, "You have to be logged in to upload an art!");
                    return(Redirect("/posts/upload"));
                }

                // Check if the artist exists
                Artist artist = null;
                if (model.Author != null)
                {
                    artist = await _db.Artists
                             .FirstOrDefaultAsync(a => a.ArtistName.Equals(model.Author));

                    if (artist == null)
                    {
                        // TODO: Ask if u can make a link to the artist registration form in here
                        ModelState.AddModelError(string.Empty, $"Could not find artist named {model.Author}." +
                                                 " Please consider adding a new artist <a href=\"#\">here</a>");
                        return(View());
                    }
                }

                // Save the files and manage get the necessary data
                string large, normal, thumbnail, hash;
                (int, int)dims;
                long size;
                try
                {
                    using (ImageFileManager ifm = new ImageFileManager("wwwroot/img/posts/", model.File.OpenReadStream(),
                                                                       ImageUtils.ImgExtensionFromContentType(model.File.ContentType)))
                    {
                        large = await ifm.SaveLarge();

                        normal = await ifm.SaveNormal();

                        thumbnail = await ifm.SaveThumbnail(0, 0);
                    }
                    hash = ImageUtils.HashFromFile(large);
                    dims = ImageUtils.DimensionsOfImage(large);
                    size = model.File.Length;

                    large     = large.Remove(0, 7);
                    normal    = normal.Remove(0, 7);
                    thumbnail = thumbnail.Remove(0, 7);
                }
                catch (InvalidArtDimensionsException exception)
                {
                    ModelState.AddModelError(string.Empty, "Invalid art size - the art should be at least 300 x 300px");
                    return(View());
                }

                // Get the user data and register unregistered tags
                var usr = await _userManager.GetUserAsync(User);

                List <string> rawTags = model.TagString.Split(' ').ToList();
                List <Tag>    tags    = new List <Tag>();
                foreach (string rawTag in rawTags)
                {
                    var tag = _db.Tags.FirstOrDefault(t => t.TagString.Equals(rawTag));
                    if (tag == null)
                    {
                        Tag newTag = new Tag {
                            Id = Guid.NewGuid(), Creator = usr, TagString = rawTag, AddedAt = DateTime.Now
                        };
                        await _db.Tags.AddAsync(newTag);

                        tags.Add(newTag);
                    }
                    else
                    {
                        tags.Add(tag);
                    }
                }
                await _db.SaveChangesAsync();

                // Create an art
                Art art = new Art()
                {
                    Id             = Guid.NewGuid(),
                    Uploader       = usr,
                    Name           = model.Name,
                    Source         = model.Source,
                    Rating         = model.Rating,
                    Author         = artist,
                    LargeFileUrl   = large,
                    FileUrl        = normal,
                    PreviewFileUrl = thumbnail,
                    Md5Hash        = hash,
                    Height         = dims.Item2,
                    Width          = dims.Item1,
                    FileSize       = (int)size,
                    Stars          = 0,
                    CreatedAt      = DateTime.Now,
                };

                // Register tag occurrences in the join table and the art
                List <TagOccurrence> occurrences = new List <TagOccurrence>();
                foreach (var tag in tags)
                {
                    occurrences.Add(new TagOccurrence()
                    {
                        Art   = art,
                        ArtId = art.Id,
                        Tag   = tag,
                        TagId = tag.Id
                    });
                }
                art.Tags = occurrences;

                await _db.Arts.AddAsync(art);

                await _db.SaveChangesAsync();

                return(Redirect("/Posts/List"));
            }
            return(View());
        }
コード例 #10
0
        /// <summary>
        /// Sets Clipboard text and returns the content
        /// </summary>
        /// <returns></returns>
        public static string SetClipboardText(WorkerTask task, bool showDialog)
        {
            string clipboardText = "";

            switch (task.JobCategory)
            {
            case JobCategoryType.PICTURES:
            case JobCategoryType.SCREENSHOTS:
            case JobCategoryType.BINARY:
                ScreenshotsHistory = task.LinkManager;
                if (GraphicsMgr.IsValidImage(task.LocalFilePath))
                {
                    if (Engine.conf.ShowClipboardModeChooser || showDialog)
                    {
                        ClipboardOptions cmp = new ClipboardOptions(task);
                        cmp.Icon = Resources.zss_main;
                        if (showDialog)
                        {
                            cmp.ShowDialog();
                        }
                        else
                        {
                            cmp.Show();
                        }
                    }

                    if (task.MyImageUploader == ImageDestType.FILE)
                    {
                        clipboardText = task.LocalFilePath;
                    }
                    else
                    {
                        clipboardText = ScreenshotsHistory.GetUrlByType(Engine.conf.ClipboardUriMode).ToString().Trim();
                        if (task.MakeTinyURL)
                        {
                            string tinyUrl = ScreenshotsHistory.GetUrlByType(ClipboardUriType.FULL_TINYURL);
                            if (!string.IsNullOrEmpty(tinyUrl))
                            {
                                clipboardText = tinyUrl.Trim();
                            }
                        }
                    }
                }
                break;

            case JobCategoryType.TEXT:
                switch (task.Job)
                {
                case WorkerTask.Jobs.LANGUAGE_TRANSLATOR:
                    if (null != task.TranslationInfo)
                    {
                        clipboardText = task.TranslationInfo.Result.TranslatedText;
                    }
                    break;

                default:
                    if (!string.IsNullOrEmpty(task.RemoteFilePath))
                    {
                        clipboardText = task.RemoteFilePath;
                    }
                    else if (null != task.MyText)
                    {
                        clipboardText = task.MyText.LocalString;
                    }
                    else
                    {
                        clipboardText = task.LocalFilePath;
                    }
                    break;
                }
                break;
            }

            // after all this the clipboard text can be null

            if (!string.IsNullOrEmpty(clipboardText))
            {
                Engine.ClipboardUnhook();
                FileSystem.AppendDebug("Setting Clipboard with URL: " + clipboardText);
                Clipboard.SetText(clipboardText);

                // optional deletion link
                string linkdel = ScreenshotsHistory.GetDeletionLink();
                if (!string.IsNullOrEmpty(linkdel))
                {
                    FileSystem.AppendDebug("Deletion Link: " + linkdel);
                }

                Engine.zClipboardText = clipboardText;
                Engine.ClipboardHook();
            }
            return(clipboardText);
        }
コード例 #11
0
        public async Task <IActionResult> Register(ArtistRegistrationViewModel model)
        {
            ViewBag.SubsectionPages = _subsectionPages;
            ViewBag.ActiveSubpage   = _subsectionPages[1];

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

            if (!_signInManager.IsSignedIn(User))
            {
                ModelState.AddModelError(string.Empty,
                                         "You have to be logged in to register an artist!");
                return(View());
            }

            Guid id = Guid.NewGuid();

            ImageFileManager ifmPfp = null, ifmBg = null;
            string           pfp, bg = null;

            try
            {
                // Load images
                ifmPfp = new ImageFileManager("wwwroot/img/profiles/pfps/", model.Pfp.OpenReadStream(),
                                              ImageUtils.ImgExtensionFromContentType(model.Pfp.ContentType));
                if (model.BackgroundImage != null)
                {
                    ifmBg = new ImageFileManager("wwwroot/img/profiles/bgs/",
                                                 model.BackgroundImage.OpenReadStream(),
                                                 ImageUtils.ImgExtensionFromContentType(model.BackgroundImage.ContentType));
                }

                // Save images
                pfp = await ifmPfp.SavePfp(id);

                pfp = pfp.Remove(0, 7);
                if (ifmBg != null)
                {
                    bg = await ifmBg.SaveBg(id);

                    bg = bg.Remove(0, 7);
                }
            }
            catch (InvalidArtDimensionsException e)
            {
                ModelState.AddModelError(string.Empty, "Invalid profile picture or background size! " +
                                         "Profile picture must be at least 400px by 400px and in 1:1 ratio " +
                                         "and background must be at least 1590px by 540px");
                return(View());
            }


            Artist artist = new Artist()
            {
                Id                 = id,
                ArtistName         = model.Name,
                RegisteredAt       = DateTime.Now,
                RegisteredBy       = await _userManager.GetUserAsync(User),
                ProfileViews       = 0,
                BackgroundImageUrl = bg,
                PfpUrl             = pfp,
                Country            = model.Country,
                FacebookProfileUrl = model.FacebookProfileUrl,
                TwitterProfileUrl  = model.TwitterProfileUrl,
                MailAddress        = model.MailAddress,
                Gender             = model.Gender,
            };

            await _db.Artists.AddAsync(artist);

            await _db.SaveChangesAsync();

            return(Redirect("/Artists/List"));
        }
コード例 #12
0
        public async Task <IActionResult> PutAd(Guid id, [FromForm] AdDTO adDTO)
        {
            var ad = await _context.Ads.FindAsync(id);

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

            if (adDTO.User != Guid.Empty)
            {
                if (!UserExists(adDTO.User))
                {
                    return(NotFound());
                }
                ad.User = adDTO.User;
            }

            if (!string.IsNullOrEmpty(adDTO.Subject))
            {
                ad.Subject = adDTO.Subject;
            }
            if (!string.IsNullOrEmpty(adDTO.Content))
            {
                ad.Content = adDTO.Content;
            }

            if (adDTO.Image != null)
            {
                IImageFileManager imageManager = new ImageFileManager(_options, _cacheController);
                var imageUrl = imageManager.GenerateURL(ad.Id.ToString(), adDTO.Image.FileName);
                try
                {
                    await imageManager.UploadImageAsync(adDTO.Image, imageUrl);
                }
                catch (Exception)
                {
                    return(Problem("Возникла ошибка при загрузке изображения", null,
                                   StatusCodes.Status500InternalServerError, "Ошибка загрузки изображения"));
                }
            }

            _context.Entry(ad).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AdExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok());
        }
コード例 #13
0
        public async Task <IActionResult> Update(ProfileUpdateViewModel puvm)
        {
            if (!ModelState.IsValid)
            {
                return(Redirect("/Profile/Settings"));
            }

            if (!_signInManager.IsSignedIn(User))
            {
                ModelState.AddModelError(string.Empty,
                                         "You have to be logged in to change your settings!");
                return(Redirect("/Profile/Settings"));
            }

            NeobooruUser usr = await _userManager.GetUserAsync(User);

            usr.Gender             = puvm.Gender;
            usr.UserName           = puvm.Username;
            usr.ProfileDescription = puvm.ProfileDescription;

            if (puvm.PfpImage != null)
            {
                Guid id = Guid.NewGuid();

                ImageFileManager ifmPfp = null;
                try
                {
                    ifmPfp = new ImageFileManager("wwwroot/img/profiles/pfps/",
                                                  puvm.PfpImage.OpenReadStream(), ImageUtils.ImgExtensionFromContentType(puvm.PfpImage.ContentType));
                }
                catch (InvalidArtDimensionsException e)
                {
                    ModelState.AddModelError(string.Empty, "Invalid profile picture or background size! " +
                                             "Profile picture must be at least 400px by 400px");
                    return(Redirect("/Profile/Settings"));
                }

                usr.PfpUrl = await ifmPfp.SavePfp(id);

                usr.PfpUrl = usr.PfpUrl.Remove(0, 7);
            }

            if (puvm.BgImage != null)
            {
                Guid id = Guid.NewGuid();

                ImageFileManager ifmPfp = null;
                try
                {
                    ifmPfp = new ImageFileManager("wwwroot/img/profiles/bgs/",
                                                  puvm.BgImage.OpenReadStream(), ImageUtils.ImgExtensionFromContentType(puvm.BgImage.ContentType));
                }
                catch (InvalidArtDimensionsException e)
                {
                    ModelState.AddModelError(string.Empty, "Invalid profile picture or background size! " +
                                             "Background must be at least 1590px by 540px");
                    return(Redirect("/Profile/Settings"));
                }

                usr.BgUrl = await ifmPfp.SaveBg(id);

                usr.BgUrl = usr.BgUrl.Remove(0, 7);
            }

            await _db.SaveChangesAsync();

            return(Redirect("/Profile/Profile"));
        }