public string GetScreenShot(Test test) { string path = ""; string picUrl = ""; try { path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{test.TestName}_{test.TestRunId}.jpg"); Screenshot ss = ((ITakesScreenshot)Driver).GetScreenshot(); string screenshot = ss.AsBase64EncodedString; byte[] screenshotAsByteArray = ss.AsByteArray; ss.SaveAsFile(path, ScreenshotImageFormat.Jpeg); Account account = new Account( "dpqroysdg", "233854257866176", "Uh3NWNHgTZEZz5IYF6rXkcIEx7c" ); Cloudinary cloudinary = new Cloudinary(account); var uploadeParameters = new ImageUploadParams() { File = new FileDescription(path) }; var uploadeResult = cloudinary.Upload(uploadeParameters); picUrl = uploadeResult.Uri.AbsoluteUri; } catch (Exception ex) { Exception e = ex; } return(picUrl); }
public async Task <ResponseNoteModel> UploadImage(IFormFile file, long UserID, long noteID) { var note = this.notesContext.Notes.Where(t => t.NoteId == noteID).SingleOrDefault(); var stream = file.OpenReadStream(); var name = file.FileName; Account account = new Account("devjs8e7v", "217619793785761", "t8nmfVwKgMJciXM8dP_B2C5UK90"); Cloudinary cloudinary = new Cloudinary(account); var uploadParams = new ImageUploadParams() { File = new FileDescription(name, stream) }; ImageUploadResult uploadResult = cloudinary.Upload(uploadParams); note.Image = uploadResult.Url.ToString(); try { ResponseNoteModel NewNote = new ResponseNoteModel { UserID = (long)note.UserId, NoteId = note.NoteId, Title = note.Title, Body = note.Body, Color = note.Color, Image = note.Image, Reminder = (DateTime)note.Reminder, isPin = (bool)note.IsPin, isArchieve = (bool)note.IsArchieve, isTrash = (bool)note.IsTrash, }; await notesContext.SaveChangesAsync(); return(NewNote); } catch (Exception) { throw; } }
public void Initialize() { m_account = new Account( Settings.Default.CloudName, Settings.Default.ApiKey, Settings.Default.ApiSecret); if (String.IsNullOrEmpty(m_account.Cloud)) Console.WriteLine("Cloud name must be specified in test configuration (app.config)!"); if (String.IsNullOrEmpty(m_account.ApiKey)) Console.WriteLine("Cloudinary API key must be specified in test configuration (app.config)!"); if (String.IsNullOrEmpty(m_account.ApiSecret)) Console.WriteLine("Cloudinary API secret must be specified in test configuration (app.config)!"); Assert.IsFalse(String.IsNullOrEmpty(m_account.Cloud)); Assert.IsFalse(String.IsNullOrEmpty(m_account.ApiKey)); Assert.IsFalse(String.IsNullOrEmpty(m_account.ApiSecret)); m_cloudinary = new Cloudinary(m_account); if (!String.IsNullOrWhiteSpace(Settings.Default.ApiBaseAddress)) m_cloudinary.Api.ApiBaseAddress = Settings.Default.ApiBaseAddress; m_testVideoPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "movie.mp4"); m_testImagePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestImage.jpg"); m_testPdfPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "multipage.pdf"); m_testIconPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "favicon.ico"); Resources.TestImage.Save(m_testImagePath); File.WriteAllBytes(m_testPdfPath, Resources.multipage); File.WriteAllBytes(m_testVideoPath, Resources.movie); using (Stream s = new FileStream(m_testIconPath, FileMode.Create, FileAccess.Write, FileShare.None)) { Resources.favicon.Save(s); } }
public async Task <IActionResult> UrunEkle(Urun entity, IEnumerable <IFormFile> file) { ViewBag.Kategoriler = new SelectList(kategoriRepo.GetAll(), "KategoriId", "KategoriAd"); if (ModelState.IsValid && file != null) { Account acc = new Account("naimmobilya", "742112311237693", "nqeO8i7tnQpNPnSAQyESOqImU-I"); Cloudinary cloudinary = new Cloudinary(acc); Urun urun = urunRepo.Add(entity); foreach (var item in file) { string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", item.FileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await item.CopyToAsync(stream); } UrunImage image = new UrunImage() { UrunId = urun.UrunId }; imageRepo.Add(image); var uploadParams = new ImageUploadParams() { File = new FileDescription(filePath), PublicId = "" + image.UrunImageId }; var uploadResult = cloudinary.Upload(uploadParams); image.ImageUrl = uploadResult.Uri.ToString(); imageRepo.Update(image); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } TempData["message"] = $"{entity.UrunId} id li ürün eklendi"; return(RedirectToAction("UrunList")); } return(View(entity)); }
public async Task <ActionResult> UploadAsync(IFormFile file) { // Check this content type against a set of allowed content types var contentType = file.ContentType.ToLower(); if (!VALID_CONTENT_TYPES.Contains(contentType)) { // Return a 400 Bad Request when the content type is not allowed return(BadRequest("Not Valid Image")); } // Create and configure a client object to be able to upload to Cloudinary var cloudinaryClient = new Cloudinary(new Account(CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET)); // Create an object describing the upload we are going to process. // We will provide the file name and the stream of the content itself. var uploadParams = new ImageUploadParams() { File = new FileDescription(file.FileName, file.OpenReadStream()) }; // Upload the file to the server ImageUploadResult result = await cloudinaryClient.UploadLargeAsync(uploadParams); // If the status code is a "OK" then the upload was accepted so we will return // the URL to the client if (result.StatusCode == HttpStatusCode.OK) { var urlOfUploadedFile = result.SecureUrl.AbsoluteUri; return(Ok(new { url = urlOfUploadedFile })); } else { // Otherwise there was some failure in uploading return(BadRequest("Upload failed")); } }
public ActionResult POSTEDIT(int id, HttpPostedFileBase file) { //Upload hinh Account account = new Account("tuantran4792", "768477423592365", "ZvwS4cVh6U_YKWk_QgvhphOpV-I"); Cloudinary cloudinary = new Cloudinary(account); var uploadParams = new ImageUploadParams() { File = new FileDescription(file.FileName, file.InputStream) }; var uploadResult = cloudinary.Upload(uploadParams); // cho nay no uphinh SYNC ko co async nên up xong nó cho cái link hinh ben dưới ViewData["Hinh"] = uploadResult.Uri.AbsoluteUri; // luu vao database <- đem cái String hinh nay lưu vào DB // ViewData["MaMonAn"] = id; WebClient client = new WebClient(); var json = client.DownloadString("http://cookapi.apphb.com/api/MonAn/LayMonAn/" + id.ToString()); json = System.Text.Encoding.Unicode.GetString(System.Text.Encoding.Convert(System.Text.Encoding.UTF8, System.Text.Encoding.Unicode, System.Text.Encoding.Default.GetBytes(json))); var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); dynamic model = serializer.Deserialize <dynamic>(json); ViewData["MaMonAn"] = model["MaMonAn"]; ViewData["TenMon"] = model["TenMon"]; ViewData["GioiThieu"] = model["GioiThieu"]; // ViewData["Hinh"] = model["Hinh"]; ViewData["ThoiGianChuanBi"] = model["ThoiGianChuanBi"]; ViewData["ThoiGianNau"] = model["ThoiGianNau"]; ViewData["NgayDang"] = model["NgayDang"]; ViewData["NguyenLieu"] = model["NguyenLieu"]; ViewData["CachLam"] = model["CachLam"]; ViewData["MaNguoiDung"] = model["MaNguoiDung"]; ViewData["MaMucDo"] = model["MaMucDo"]; ViewData["MaLoaiMon"] = model["MaLoaiMon"]; return(View("Edit")); }
public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext <MiraDesignContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <MiraDesignUser, IdentityRole>(options => { }) .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores <MiraDesignContext>() .AddDefaultTokenProviders(); Account cloudinaryCredentials = new Account( Configuration["Cloudinary:CloudName"], Configuration["Cloudinary:ApiKey"], Configuration["Cloudinary:ApiSecret"]); Cloudinary cloudinaryUtility = new Cloudinary(cloudinaryCredentials); services.AddSingleton(cloudinaryUtility); services.AddTransient <ICloudinaryService, CloudinaryService>(); services.AddMvc(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSingleton <IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get <EmailConfiguration>()); services.AddTransient <IEmailService, EmailService>(); services.AddScoped <IEmailMessage, EmailMessage>(); }
public string getImagenQR(string codigo) { QrCodeEncodingOptions options = new QrCodeEncodingOptions(); options = new QrCodeEncodingOptions { DisableECI = true, CharacterSet = "UTF-8", Width = 250, Height = 250, }; var writer = new BarcodeWriter(); writer.Format = BarcodeFormat.QR_CODE; writer.Options = options; var qr = new ZXing.BarcodeWriter(); qr.Options = options; qr.Format = ZXing.BarcodeFormat.QR_CODE; var bitm = new Bitmap(qr.Write(codigo)); bitm.Save(PATH + codigo + ".jpg", ImageFormat.Jpeg); //Guarda la imagen en local para despues poderla subira cloudinary //aqui utilizo el path de nuevo para agarrar la imagen y luego subirla Account account = new Account(CLOUD_NAME, API_KEY, API_SECRET); cloudinary = new Cloudinary(account); var uploadParams = new ImageUploadParams() { File = new FileDescription(PATH + codigo + ".jpg") }; var uploadResult = cloudinary.Upload(uploadParams); //y luego simplemente agarro el url y lo guardo en el atributo del objeto llave return(uploadResult.SecureUri.ToString()); }
public PostServiceTests() { this.imagesRepository = this.GetImageRepository(this.GetTestImagecList()).Object; this.usersRepository = this.GetUserRepository(this.GetTestUsercList()).Object; this.postsRepository = this.GetPostsRepository(this.GetTestPostsList()).Object; this.pageHeadersRepository = this.GetPageHeadersRepository(this.GetTestPageHeadersList()).Object; this.sectionRepository = this.GetSectionRepository(this.GetTestSectionsList()).Object; Account cloudinaryAcc = new Account( "dy78wnfy2", "857437556699719", "jj3uew_U5wJPCm8Xn_LWYbbHDf8"); Cloudinary cloudinaryUtility = new Cloudinary(cloudinaryAcc); this.cloudinaryService = new CloudinaryService(cloudinaryUtility); this.userService = new UsersService(this.usersRepository, this.imagesRepository, this.cloudinaryService); this.pageHeaderService = new PageHeaderService(this.pageHeadersRepository, this.cloudinaryService); this.sectionService = new SectionService(this.sectionRepository); this.postService = new PostService(this.postsRepository, this.userService, this.pageHeaderService, this.sectionService); }
public async Task <string> UploadFileToCloudinary(string name, Stream fileStream) { Account account = new Account { Cloud = this.configuration.GetSection("Cloudinary").GetSection("cloudName").Value, ApiKey = this.configuration.GetSection("Cloudinary").GetSection("apiKey").Value, ApiSecret = this.configuration.GetSection("Cloudinary").GetSection("apiSecret").Value, }; Cloudinary cloudinary = new Cloudinary(account); var index = name.LastIndexOf('.'); name = "file" + name.Substring(index); var uploadParams = new RawUploadParams() { File = new FileDescription(name, fileStream), }; var uploadResult = await cloudinary.UploadAsync(uploadParams); return(uploadResult.SecureUri.AbsoluteUri); }
public LotsController(IMapper mapper, ILotService lotService, ICategoryService categoryService, IAuthorizationService authorizationService, IUserService userService, IConfiguration configuration) { _mapper = mapper; _lotService = lotService; _categoryService = categoryService; _authorizationService = authorizationService; _userService = userService; var cloudinaryConfiguration = configuration.GetSection("Cloudinary"); var account = new Account( cloudinaryConfiguration.GetSection("cloud_name").Value, cloudinaryConfiguration.GetSection("api_key").Value, cloudinaryConfiguration.GetSection("api_secret").Value ); _cloudinary = new Cloudinary(account); }
public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Component.For <CloudinaryDotNet.Cloudinary>() .UsingFactoryMethod(() => { dynamic config = new Formo.Configuration(); return(Cloudinary.Create(new CloudinaryAccountCredentials { CloudName = config.CloudinaryAccountName, ApiKey = config.CloudinaryKey, ApiSecret = config.CloudinarySecret })); }) .LifestyleTransient()); container.Register(Component.For <IAssetService>() .ImplementedBy(typeof(CloudinaryService)) .DependsOn(new { cloudinaryInstance = container.Resolve <CloudinaryDotNet.Cloudinary>(), Salt = ConfigurationManager.AppSettings["CloudinarySalt"] }).LifestyleTransient()); }
public AdminController( IMissionControlRepository missionControlRepo, IAdminRepository adminRepo, IMapper mapper, DataContext context, UserManager <User> userManager, IOptions <CloudinarySettings> cloudinaryConfig) { _userManager = userManager; _cloudinaryConfig = cloudinaryConfig; _context = context; _missionControlRepo = missionControlRepo; _adminRepo = adminRepo; _mapper = mapper; Account acc = new Account( _cloudinaryConfig.Value.CloudName, _cloudinaryConfig.Value.ApiKey, _cloudinaryConfig.Value.ApiSecret ); _cloudinary = new Cloudinary(acc); }
public virtual void Initialize() { m_account = GetAccountInstance(); m_cloudinary = GetCloudinaryInstance(m_account); m_appveyor_job_id = Environment.GetEnvironmentVariable("APPVEYOR_JOB_ID"); m_suffix = String.IsNullOrEmpty(m_appveyor_job_id) ? new Random().Next(100000, 999999).ToString() : m_appveyor_job_id; m_test_tag += m_suffix; m_testVideoPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "movie.mp4"); m_testImagePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestImage.jpg"); m_testLargeImagePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestLargeImage.jpg"); m_testPdfPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "multipage.pdf"); m_testIconPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "favicon.ico"); Resources.TestImage.Save(m_testImagePath); Resources.TestLargeImage.Save(m_testLargeImagePath); File.WriteAllBytes(m_testPdfPath, Resources.multipage); File.WriteAllBytes(m_testVideoPath, Resources.movie); using (Stream s = new FileStream(m_testIconPath, FileMode.Create, FileAccess.Write, FileShare.None)) { Resources.favicon.Save(s); } }
public async Task <string> UploadAsync(Cloudinary cloudinary, IFormFile file) { byte[] destinationImage; using (var memoryStream = new MemoryStream()) { await file.CopyToAsync(memoryStream); destinationImage = memoryStream.ToArray(); } using (var destinationStream = new MemoryStream(destinationImage)) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.FileName, destinationStream), }; var result = await cloudinary.UploadAsync(uploadParams); return(result.Uri.AbsoluteUri); } }
private string UploadImg(string picPublicId) { byte[] imageBytes = Convert.FromBase64String(hdnImage.Value); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); Account account = new Account("dlyvxs7of", "634626974285569", "FtB_0jhcmFypFS7QTwCBKcPRGzE"); Cloudinary cloudinary = new Cloudinary(account); if (!string.IsNullOrEmpty(picPublicId)) { cloudinary.DeleteResources(new string[] { picPublicId }); } ImageUploadParams uploadParams = new ImageUploadParams() { File = new FileDescription("file", ms), }; ImageUploadResult result = cloudinary.Upload(uploadParams); return(result.PublicId); }
public string UpdateImageAndGetUrl(PaintingUpdateDTO image) { Account account = new Account( "paintingproject", //cloud name "373497354299735", //api key "6rt6J94a-ZylEscK5hZf5jLMyhM" //api secret ); var uploadParams = new ImageUploadParams() { File = new FileDescription(image.Image.FileName, image.Image.OpenReadStream()) }; var cloudinary = new Cloudinary(account); var uploadResult = cloudinary.Upload(uploadParams); var id = uploadResult.JsonObj; var data = JsonConvert.DeserializeObject <RawUploadResult>(id.ToString()); var result = data.SecureUri.ToString(); return(result); throw new NotImplementedException(); }
public PhotosController( UserManager <User> userManager, IOptions <CloudinarySettings> cloudinaryConfig, IPhotosRepository photosRepository, IUsersRepository usersRepository, IRepository repository, IMapper mapper) { this.userManager = userManager; this.repository = repository; this.photosRepository = photosRepository; this.usersRepository = usersRepository; this.mapper = mapper; this.cloudinaryConfig = cloudinaryConfig; var acc = new Account( cloudinaryConfig.Value.CloudName, cloudinaryConfig.Value.ApiKey, cloudinaryConfig.Value.ApiSecret ); cloudinary = new Cloudinary(acc); }
public PhotosController(IDatingRepository repo, IMapper mapper, // services.Configure<CloudinarySettings>(Configuration.GetSection("CloudinarySettings")); IOptions <CloudinarySettings> cloudinaryConfig) // type = <class from Helpers> { _repo = repo; _mapper = mapper; _cloudinaryConfig = cloudinaryConfig; // Bring in the Account class from Cloudinary library // Account acc = new Account( // 3 strings from api>appsetting.json // _cloudinaryConfig.Value.CloudName, _cloudinaryConfig.Value.ApiKey, _cloudinaryConfig.Value.ApiSecret ); // new instance of Cloudinary with acc details above // _cloudinary = new Cloudinary(acc); }
public async Task <Image> UploadProfilePictureAsync(string name, Stream stream, string publicIdToDelete) { // think a little how can make this method better var cloudinary = new Cloudinary(account); var uploadParams = new ImageUploadParams() { File = new FileDescription(name, stream) }; if (publicIdToDelete != "Facebook-no-profile-picture-icon-620x389_hwyvki") { await cloudinary.DeleteResourcesAsync(publicIdToDelete); } var img = await cloudinary.UploadAsync(uploadParams); var image = new Image { ProfilePictureUrl = img.Uri.ToString(), ProfilePicturePublicId = img.PublicId }; return(image); }
public ActionResult Delete(int id) { CustomerModel customer = db.Customers.SingleOrDefault(c => c.ID == id); if (customer == null) { return(HttpNotFound()); } if (!(customer.Image == "http://ssl.gstatic.com/accounts/ui/avatar_2x.png")) { var myAccount = new Account { ApiKey = "555682285552641", ApiSecret = "Id-vLH2JZBKc7x0wK3ZEZYCsGkA", Cloud = "dmrx96yqx" }; Cloudinary _cloudinary = new Cloudinary(myAccount); int pos = customer.Image.LastIndexOf("placeOfBueaty/Users/"); string delImg = customer.Image.Substring(pos, customer.Image.Length - pos - 4); _cloudinary.DeleteResources(delImg); } db.Customers.Remove(customer); db.SaveChanges(); return(RedirectToAction("CustomersList", "Customer")); }
private void resimYükleToolStripMenuItem_Click(object sender, EventArgs e) { this.resimyukledialog.ShowDialog(); if (this.resimyukledialog.FileName != "" || File.Exists(this.resimyukledialog.FileName)) { Cursor.Current = Cursors.WaitCursor; Account account = new Account("duj1m9euv", "366682913616939", "sIZ_S9Zs_C00uRgAdBrUmr_aHHE"); Cloudinary cloudinary = new Cloudinary(account); ImageUploadParams uploadParams = new ImageUploadParams() { File = new FileDescription(this.resimyukledialog.FileName) }; ImageUploadResult uploadResult = cloudinary.Upload(uploadParams); string url = cloudinary.Api.UrlImgUp.BuildUrl(String.Format("{0}.{1}", uploadResult.PublicId, uploadResult.Format)); Clipboard.SetText(url); MessageBox.Show("Link hafızaya kopyalandı. Ctrl + V yaparak kullanabilirsiniz.", "Resim Yükleme Tamam", MessageBoxButtons.OK, MessageBoxIcon.Information); Cursor.Current = Cursors.Default; } }
public static void GenQRCode(String message, String Code) { QRCodeGenerator qrGenerator = new QRCodeGenerator(); Cloudinary _cloudinary = new Cloudinary(new Account("dpciaiobf", "546941639243358", "-clBvD99twwKZUYzhb2eLQDt7SU")); QRCodeData qrCodeData = qrGenerator.CreateQrCode(message, QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData); Bitmap qrCodeImage = qrCode.GetGraphic(20); System.IO.MemoryStream stream = new MemoryStream(); qrCodeImage.Save(stream, ImageFormat.Png); var bytes = ((MemoryStream)stream).ToArray(); System.IO.Stream inputStream = new MemoryStream(bytes); ImageUploadParams a = new ImageUploadParams { File = new FileDescription(Guid.NewGuid().ToString(), inputStream), PublicId = Code }; _cloudinary.Upload(a); }
public ActionResult UploadToGallery(IEnumerable <HttpPostedFileBase> file) { var res = ""; //save file in App_Data for (int i = 0; i < Request.Files.Count; i++) { var file2 = Request.Files[i]; var fileName = Path.GetFileName(file2.FileName); var path = Path.Combine(Server.MapPath("~/Content/imgs/"), fileName); file2.SaveAs(path); //connect to cloudinary account var myAccount = new Account { ApiKey = "555682285552641", ApiSecret = "Id-vLH2JZBKc7x0wK3ZEZYCsGkA", Cloud = "dmrx96yqx" }; Cloudinary _cloudinary = new Cloudinary(myAccount); var uploadParams = new ImageUploadParams() { File = new FileDescription(path), Folder = "placeOfBueaty/Gallery", }; var uploadResult = _cloudinary.Upload(uploadParams); res = uploadResult.SecureUri.ToString(); //delete the image from App_Data FileInfo del = new FileInfo(path); del.Delete(); //send back url. Response.StatusCode = (int)HttpStatusCode.OK; } return(RedirectToAction("Gallery", "Home")); }
public void ConfigureServices(IServiceCollection services) { services.AddDbContext <StopifyDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <StopifyUser, IdentityRole>() .AddEntityFrameworkStores <StopifyDbContext>() .AddDefaultTokenProviders(); Account cloudinaryCredentials = new Account( this.Configuration["Cloudinary:CloudName"], this.Configuration["Cloudinary:ApiKey"], this.Configuration["Cloudinary:ApiSecret"]); Cloudinary cloudinaryUtility = new Cloudinary(cloudinaryCredentials); services.AddSingleton(cloudinaryUtility); services.Configure <IdentityOptions>(options => { // Password settings. options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 3; options.Password.RequiredUniqueChars = 0; options.User.RequireUniqueEmail = true; }); services.AddTransient <IProductService, ProductService>(); services.AddTransient <ICloudinaryService, CloudinaryService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services .AddEntityFrameworkSqlServer() .AddDbContext <QDetectDbContext>((serviceProvider, options) => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")) .UseInternalServiceProvider(serviceProvider)); Account cloudinaryCredentials = new Account( this.Configuration["Cloudinary:CloudName"], this.Configuration["Cloudinary:ApiKey"], this.Configuration["Cloudinary:ApiSecret"]); Cloudinary cloudinaryUtility = new Cloudinary(cloudinaryCredentials); services.AddSingleton(cloudinaryUtility); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); services.AddTransient <IImageReceiverService, ImageReceiverService>(); services.AddTransient <ICloudinaryService, CloudinaryService>(); services.AddTransient <IPeopleService, PeopleService>(); services.AddTransient <IReportService, ReportService>(); }
public void ScaleMode() { Cloudinary cloudinary = TestUtilities.GetCloudinary(); string scaleTag = cloudinary.Api.UrlImgUp.Transform( new Transformation().Width(100).Height(150).Crop("scale")) .BuildImageTag("sample.jpg"); /*Cloudinary's fit cropping mode (set Crop to fit) transforms the image * to fit in a given rectangle while retaining its original proportions.*/ string fitTag = cloudinary.Api.UrlImgUp.Transform( new Transformation().Width(100).Height(150).Crop("fit")) .BuildImageTag("sample.jpg"); /*Transform an image to fill specific dimensions completely while retaining its original * proportions by setting Crop to fill. Only part of the original image might be visible * if the required proportions are different than the original ones.*/ string fillTag = cloudinary.Api.UrlImgUp.Transform( new Transformation().Width(100).Height(150).Crop("fill")) .BuildImageTag("sample.jpg"); /*By default, fill keeps the center of the image centered while cropping * the image to fill the given dimensions. You can control this behavior by * specifying the Gravity parameter. In the following example, gravity is set to * South East.*/ string gravityTag = cloudinary.Api.UrlImgUp.Transform( new Transformation().Width(100).Height(150).Crop("fill").Gravity("south_east")) .BuildImageTag("sample.jpg"); // more examples // https://cloudinary.com/documentation/dotnet_image_manipulation#limit_mode // https://cloudinary.com/documentation/dotnet_image_manipulation#crop_mode // https://cloudinary.com/documentation/dotnet_image_manipulation#percentage_based_resizing TestUtilities.LogAndWrite(scaleTag, "ScaleMode.txt"); TestUtilities.LogAndWrite(fitTag, "FitMode.txt"); TestUtilities.LogAndWrite(fillTag, "FillMode.txt"); TestUtilities.LogAndWrite(gravityTag, "GravityMode.txt"); }
public void ConfigureServices(IServiceCollection services) { services.AddDbContext <KTasevaDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity <User>(options => options.SignIn.RequireConfirmedAccount = false) .AddRoles <IdentityRole>() .AddEntityFrameworkStores <KTasevaDbContext>(); services.AddControllersWithViews(); services.AddRazorPages(); services.AddSignalR(); services.Configure <IdentityOptions>(options => { options.Password.RequiredUniqueChars = 0; options.Password.RequireDigit = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; }); RegisterServiceLayer(services); services.Configure <SendGridOptions>(this.Configuration.GetSection("EmailSettings")); services.Configure <ReCAPTCHASettings>(Configuration.GetSection("GooglereCAPTCHA")); Account account = new Account( this.Configuration["Cloudinary:AppName"], this.Configuration["Cloudinary:AppKey"], this.Configuration["Cloudinary:AppSecret"]); Cloudinary cloudinary = new Cloudinary(account); services.AddSingleton(cloudinary); services.AddApplicationInsightsTelemetry(); }
public async Task <IActionResult> PostVideo([FromForm] UploadFile model) { var file = model.File; Account account = new Account( "dn2pht7no", "763416155661231", "Y8_D6HDCOUNJAUoPvi8wtVWhkmE"); Cloudinary cloudinary = new Cloudinary(account); if (file.Length > 0) { string path = Path.Combine(_hostingEnvironment.ContentRootPath, @"ClientApp\src\components", "uploadFiles"); using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create)) { await file.CopyToAsync(fs); } string path2 = Path.Combine(path, file.FileName); var uploadParams = new VideoUploadParams() { File = new FileDescription(path2) }; var uploadResult = cloudinary.Upload(uploadParams); model.source = $"/uploadFiles{file.FileName}"; Models.Video v = new Models.Video(); v.VideoName = file.FileName; v.VideoLink = uploadResult.Uri.ToString(); v.Format = Path.GetExtension(file.FileName).Substring(1).Trim(); _context.Video.Add(v); await _context.SaveChangesAsync(); return(CreatedAtAction("GetVideo", new { id = v.Id }, v)); } return(BadRequest()); }
public async Task <IActionResult> DeleteUserStory(int projectId, int userStoryId) { if (!IsCurrentUserInProject(projectId)) { return(Unauthorized()); } try { var userstory = await this.userStoryService.GetAsync(userStoryId); Account account = new Account( config["Cloudinary:CloudName"], config["Cloudinary:ApiKey"], config["Cloudinary:ApiSecret"] ); Cloudinary cloudinary = new Cloudinary(account); foreach (var mockup in userstory.Mockups) { if (!string.IsNullOrWhiteSpace(mockup.MockUpPath)) { // Get public name of the file. var deleteParams = new DeletionParams(mockup.MockUpPath.Split('/').Last().Split('.')[0]); var deleteresult = cloudinary.Destroy(deleteParams); } } await this.userStoryService.DeleteAsync(userStoryId); return(RedirectToAction(nameof(GetAll), new { projectId = projectId })); } catch { return(RedirectToAction("Error", "Error")); } }
public async Task <ImageUploadResult> CategoryImagesUpload(IFormFile file) { try { Account account = new Account(_cloudinaryConfig.Cloud, _cloudinaryConfig.ApiKey, _cloudinaryConfig.ApiSecret); Cloudinary cloudinary = new Cloudinary(account); // var path = Path.Combine(Directory.GetCurrentDirectory(), "TempFileUpload", file.FileName); var path = Path.Combine(_hostingEnvironment.WebRootPath, file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } //Uploads the Course Images to cloudinary var uploadParams = new ImageUploadParams() { File = new FileDescription(path), Transformation = new Transformation().Height(500).Width(500).Crop("scale"), PublicId = "Softlearn/course_category_Images/" + file.FileName + "", }; var uploadResult = cloudinary.Upload(uploadParams); //deletes the file from the "TempFileUplaod" directory if the status of upload result is okay if (uploadResult.StatusCode == System.Net.HttpStatusCode.OK) { System.IO.File.Delete(path); } return(uploadResult); } catch (Exception ex) { throw ex; } }
public void Initialize() { m_account = new Account( Settings.Default.CloudName, Settings.Default.ApiKey, Settings.Default.ApiSecret); if (String.IsNullOrEmpty(m_account.Cloud)) Console.WriteLine("Cloud name must be specified in test configuration (app.config)!"); if (String.IsNullOrEmpty(m_account.ApiKey)) Console.WriteLine("Cloudinary API key must be specified in test configuration (app.config)!"); if (String.IsNullOrEmpty(m_account.ApiSecret)) Console.WriteLine("Cloudinary API secret must be specified in test configuration (app.config)!"); Assert.IsFalse(String.IsNullOrEmpty(m_account.Cloud)); Assert.IsFalse(String.IsNullOrEmpty(m_account.ApiKey)); Assert.IsFalse(String.IsNullOrEmpty(m_account.ApiSecret)); m_cloudinary = new Cloudinary(m_account); m_testImagePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestImage.jpg"); m_testPdfPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "multipage.pdf"); Resources.TestImage.Save(m_testImagePath); File.WriteAllBytes(m_testPdfPath, Resources.multipage); }
public void TestInitFromEnvironmentVariable() { Environment.SetEnvironmentVariable("CLOUDINARY_URL", "cloudinary://*****:*****@test123"); Cloudinary cloudinary = new Cloudinary(); }
public void Initialize() { m_account = new Account( Settings.CloudName, Settings.ApiKey, Settings.ApiSecret); if (String.IsNullOrEmpty(m_account.Cloud)) Console.WriteLine("Cloud name must be specified in test configuration (app.config)!"); if (String.IsNullOrEmpty(m_account.ApiKey)) Console.WriteLine("Cloudinary API key must be specified in test configuration (app.config)!"); if (String.IsNullOrEmpty(m_account.ApiSecret)) Console.WriteLine("Cloudinary API secret must be specified in test configuration (app.config)!"); Assert.IsFalse(String.IsNullOrEmpty(m_account.Cloud)); Assert.IsFalse(String.IsNullOrEmpty(m_account.ApiKey)); Assert.IsFalse(String.IsNullOrEmpty(m_account.ApiSecret)); m_cloudinary = new Cloudinary(m_account); sourceImagePath = "/Users/terjetyl/Projects/CloudinaryMono/CloudinaryMono.Tests/Resources/TestImage.jpg"; sourcePdfPath = "/Users/terjetyl/Projects/CloudinaryMono/CloudinaryMono.Tests/Resources/multipage.pdf"; m_testImagePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "TestImage.jpg"); m_testPdfPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "multipage.pdf"); if(!File.Exists(m_testImagePath)) File.Copy(sourceImagePath, m_testImagePath); if(!File.Exists(m_testPdfPath)) File.Copy(sourcePdfPath, m_testPdfPath); }
public void TestSecureDistributionFromUrl() { // should take secure distribution from url if secure=TRUE Cloudinary cloudinary = new Cloudinary("cloudinary://*****:*****@test123/config.secure.distribution.com"); string url = cloudinary.Api.UrlImgUp.BuildUrl("test"); Assert.AreEqual("https://config.secure.distribution.com/image/upload/test", url); }
public void TestInitFromUri() { Cloudinary cloudinary = new Cloudinary("cloudinary://*****:*****@test123"); }
public void TestUnsignedUpload() { // should support unsigned uploading using presets var preset = m_cloudinary.CreateUploadPreset(new UploadPresetParams() { Folder = "upload_folder", Unsigned = true }); var acc = new Account(Settings.Default.CloudName); var cloudinary = new Cloudinary(acc); var upload = cloudinary.Upload(new ImageUploadParams() { File = new FileDescription(m_testImagePath), UploadPreset = preset.Name, Unsigned = true }); Assert.NotNull(upload.PublicId); Assert.True(upload.PublicId.StartsWith("upload_folder")); m_cloudinary.DeleteUploadPreset(preset.Name); }