cloudinary / cloudinarydotnet Goto Github PK
View Code? Open in Web Editor NEWCloudinary DotNet library
License: MIT License
Cloudinary DotNet library
License: MIT License
I've installed latest package version 1.3.1.
ASP.NET Core 2.1 Project
I'd like to have UploadAsync(...) method. Instead I have Upload(...) only.
Please do not specify comments e.g: use Task.Run(...) etc.
Can you help me? I try to upload image through .Net using streams but I get error "empty image file". I'm sure that the stream is not empty. My code:
ImageUploadParams uploadParams = new ImageUploadParams()
{
File = new FileDescription(GetSizedFileName(size), stream),
PublicId = GetSizedFileName(size)
};
var cloudinary = CloundinaryFactory.CreateCloudinary();
ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
Is there any way we can get a https://
in the URL builds without having to specify the Secure()
function each time? Is there still a requirement for http://
only out there?
Support for SVGs together with responsive breakpoints in SDK
The following code has always worked for us, when uploading files to cloudinary:
`protected async Task SaveFileAsync(string filepath, Stream fileStream)
{
if (filepath == null) throw new ArgumentNullException(nameof(filepath));
if (fileStream == null) throw new ArgumentNullException(nameof(fileStream));
var filename = Guid.NewGuid().ToString();
fileStream.Position = 0;
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(filename, fileStream),
PublicId = $"{ServiceDomain}/{ServiceSubDomain}/{filepath.Trim('/')}/{filename}",
ResponsiveBreakpoints =
new List<ResponsiveBreakpoint> { new ResponsiveBreakpoint().CreateDerived(true).MaxWidth(2000) }
};
var uploadResult = await _cloudinary.UploadAsync(uploadParams);
var url = uploadResult.SecureUrl.ToString();
return new Uri(url.Replace("/upload/", "/upload/c_scale,w_auto/"));
}`
However, we have recently started using SVGs and are getting the following error, when trying to upload the SVG:
"Not encoding raster image to SVG, use e_vectorize as the last component in transformation"
Removing the responsive breakpoints lines stops this error. Is there any way we can have this working with SVGs? I looked into the SDK code, and saw no support for e_vectorize, so I dont know if its not a part of the .NET SDK.
Uploading SVGs and have them eagerly transformed to their various sizes.
Not more in depth than requested above
Hi!
Please, can you implement function 'ListResourcesWithoutTag'.
I need get all resources without tags.
I Try call 'result = Cloudinary.ListResourcesByTag(null, result.NextCursor);'
but I see resource with tag in 'result' variable.
We are using the SDK in a .NET Core 3.1 Azure Function project. On startup we get the following error message.
[2021-10-05T19:14:11.699Z] A host error has occurred during startup operation '929d6984-66be-444d-b0b2-d4645ccc7549'.
[2021-10-05T19:14:11.701Z] Function-ZipWhipEngine: Could not load file or assembly 'Microsoft.Extensions.Options, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
Value cannot be null. (Parameter 'provider')
In order to resolve the error we have to downgrade to version 1.14.0.
…
Simply upgrade the NuGet package and try to run the project. Error will occur during startup.
Hi,
I investigate a bit more the original issue bellow and I was able to prove that the code was originally working in .net core 1.0 but isn't in 1.1.
Create a simple project targetting 1.1 and launch
static void Main(string[] args)
{
var content = new MultipartFormDataContent("test");
var task1 = content.ReadAsStreamAsync();
task1.Wait();
Stream requestStream = task1.Result;
StreamWriter writer = new StreamWriter(requestStream);
}
_____ Original issue
I am using Cloudinary.NetCoreShared project in my .Net core 1.1 project.
I try to upload a file from a IFormFile as follow :
using (var stream = file.OpenReadStream())
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(file.FileName, stream)
};
cloudinary.Upload(uploadParams)
};
The upload is failing due to a "Stream not writable"
in the following line
StreamWriter writer = new StreamWriter(requestStream);
line 209 of https://github.com/cloudinary/CloudinaryDotNet/blob/master/Cloudinary/Shared/Coudinary.NetCoreShared/Api.cs
Any ideas ?
Thanks
I am attempting to use the new feature of generating archives for multiple resource types, but it does not seem to be working or I have misunderstood something. I admit I don't see how to do this in the documentation...I am just looking at the code for the PR that got merged and am going off of that. The PR is #166 .
Here is the basic test:
public string GenerateDownloadUrl(Collection<string> paths)
{
ArchiveParams archiveParams = new ArchiveParams();
archiveParams.FullyQualifiedPublicIds(paths.ToList());
archiveParams.FlattenFolders(true);
archiveParams.ResourceType("auto");
string downloadUrl = GetCloudinary().DownloadArchiveUrl(archiveParams);
return downloadUrl;
}
private Cloudinary GetCloudinary()
{
Account account = new Account(
ApplicationConfiguration.CloudinaryConfiguration.CloudName,
ApplicationConfiguration.CloudinaryConfiguration.ApiKey,
ApplicationConfiguration.CloudinaryConfiguration.ApiSecret);
return new Cloudinary(account);
}
Assuming a URL of https://res.cloudinary.com/twelve-stone-church/video/upload/v1551371287/FreeResources/4ThingsJesusKnew.mp3, I have tried as the public ID:
FreeResources/4ThingsJesusKnew
/FreeResources/4ThingsJesusKnew
FreeResources/4ThingsJesusKnew.mp3 (this is the one I THINK should work since the PR says it must be fully qualified).
/FreeResources/4ThingsJesusKnew.mp3
But, no matter what I try, I get the following response from the download link:
{"error":{"message":"Invalid value FreeResources for parameter resource_type"}}
I am not sure how to proceed and would appreciate some assistance.
I am having an issue saving an image from my back-end. I get the error "File is Empty" like if I had sent nothing at all. I get a file from a controller action, check that it indeed has the necessary data and send its stream as your FileDescription class can be instantiated by passing a file name and a stream but it does not work.
Code that calls the service (File is of type HttpPostedFileBase):
var result = CloudinaryService.UploadImage("pages/" + _page.UploadFolder, fileName, File.InputStream);
Service:
public static UploadResult UploadImage(string folderStructure, string fileName, Stream stream)
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(fileName, stream),
Folder = folderStructure,
};
var result = new Cloudinary(GetAccount()).Upload(uploadParams);
return new UploadResult {
uri = result.SecureUri,
error = result.Error != null ? result.Error.Message : string.Empty
};
}
Follow StackOverflow and code:
string[] files
= System.IO.Directory.GetFiles(@"C:\Users\Matheus Miranda\Pictures", "*.jpg");
foreach (var file in files)
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(file),
PublicId = "my_folder/images",
UseFilename = true,
EagerAsync = true
};
var uploadResult = cloudinary.Upload(uploadParams);
}
I'm trying to send multiple images to cloudinary, only 1 image is saved, any solution?
Hi,
Thank you for you API but ...
Should return a good error (Proxy authentication) or better : Allow passing proxy info in the API. Now, the exception is a JSON token error, not really helpful.
Thank you.
Hi,
I'm currently trying to list all my file from my CDN, however, I'm stuck, I just can't get my pictures.
I tried from HTTP Url with a HttpGet
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get....
I'm getting a 401, however, it's only from my app, Postman works...
I tried with the SDK -> var res = await cloudinary.GetUploadPresetAsync(preset);
but I'm getting an exception: Cannot send data when method is: GET
Do you have any idea why I'm getting theses problems?
Hi
We're integrating Cloudinary with our Dynamics 365 Online implementation, so we can upload pictures or files into Cloudinary. We have both client-side and server-side integration. In the process, we've found a couple of issues with CloudinaryDotNet on the server-side.
Note: We use the .Net Framework implementation of the CloudinaryDotNet library.
Run-time exception (line 20): The type initializer for 'CloudinaryDotNet.Api' threw an exception.
Stack Trace:
[System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
at System.Reflection.RuntimeAssembly.VerifyCodeBaseDiscovery(String codeBase)
at System.Reflection.RuntimeAssembly.GetName(Boolean copiedName)
at System.Reflection.Assembly.GetName()
at CloudinaryDotNet.Api..cctor()
You can actually reproduce this same error in https://dotnetfiddle.net/ and we found a sample code while researching this bug:
using System;
using CloudinaryDotNet;
using CloudinaryDotNet.Actions;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var archiveParams = new ArchiveParams();
var list = new List<string>();
list.Add("sample");
list.Add("couple");
archiveParams.PublicIds(list);
archiveParams.PublicIds();
archiveParams.Mode(ArchiveCallMode.Download);
string yourcloudinaryurl = ""; //put your cloudinaryurl here
var cloudinary = new Cloudinary(yourcloudinaryurl);
ArchiveResult result = cloudinary.CreateArchive(archiveParams);
if (result.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new System.ApplicationException(result.JsonObj.ToString());
}
Console.WriteLine(result.Url);
Console.WriteLine("Hello World");
}
}
We've managed to isolate this issue to the static constructor of the Api class:
static Api()
{
var version = Assembly.GetExecutingAssembly().GetName().Version;
var frameworkDisplayName = Assembly.GetExecutingAssembly().GetCustomAttributes(true).OfType<System.Runtime.Versioning.TargetFrameworkAttribute>().First().FrameworkDisplayName;
USER_AGENT = String.Format("CloudinaryDotNet/{0}.{1}.{2} ({3})", version.Major, version.Minor, version.Build, frameworkDisplayName);
}
Changing the code to this works
static Api()
{
Version version = new Version(1, 3, 1);
var frameworkDisplayName = ".Net 4.0";
USER_AGENT = String.Format("CloudinaryDotNet/{0}.{1}.{2} ({3})", version.Major, version.Minor, version.Build, frameworkDisplayName);
}
So clearly there's something about Assembly.GetExecutingAssembly()
that the sandbox environment doesn't like (we're not sure how you would go about fixing this, but probably having a default value, or checking if you can actually get assembly information could be a place to start).
RawUpload
.Error during cloudinary import: Error setting value to 'PublicId' on 'CloudinaryDotNet.Actions.RawUploadResult'. at Newtonsoft.Json.Serialization.ReflectionValueProvider.SetValue(Object target, Object value)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at CloudinaryDotNet.Api.Parse[T](Object response)
at CloudinaryDotNet.Api.CallAndParse[T](HttpMethod method, String url, SortedDictionary2 parameters, FileDescription file, Dictionary
2 extraHeaders)
at CloudinaryDotNet.ApiShared.CallApi[T](HttpMethod method, String url, BaseParams parameters, FileDescription file, Dictionary`2 extraHeaders)
at CloudinaryDotNet.Cloudinary.Upload(RawUploadParams parameters, String type)
This seems to take place here, on Api.cs, on the DeserializeObject
from the newtonsoft library:
internal static T Parse<T>(Object response) where T : BaseResult, new()
{
if (response == null)
throw new ArgumentNullException("response");
HttpWebResponse message = (HttpWebResponse)response;
T result;
using (Stream stream = message.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string s = reader.ReadToEnd();
result = JsonConvert.DeserializeObject<T>(s);
result.JsonObj = JToken.Parse(s);
}
if (message.Headers != null)
foreach (var header in message.Headers.AllKeys)
{
if (header.StartsWith("X-FeatureRateLimit"))
{
long l;
DateTime t;
if (header.EndsWith("Limit") && long.TryParse(message.Headers[header], out l))
result.Limit = l;
if (header.EndsWith("Remaining") && long.TryParse(message.Headers[header], out l))
result.Remaining = l;
if (header.EndsWith("Reset") && DateTime.TryParse(message.Headers[header], out t))
result.Reset = t;
}
}
result.StatusCode = message.StatusCode;
return result;
}
Now this is an odd one, because it's an access problem, and it only happens on Dynamics' sandbox. However, we found changing the protected modifier on the setters to public solved the problem for us. We had to change it for every property that gets deserialized using the Newtonsoft library though.
We get that you'd want to make the setters protected, so values returned by the cloudinary service don't get modified unless someone is really determined to do so, however, we would expect the Newtonsoft library to be unable to access the setters as well unless it's using reflection to bypass the access level. This seems to cause issues in our application.
A way around this may be to include a serialization / deserialization library in your own code, (such as LitJSON which is a public domain library) and change the access modifier to protected internal, to avoid any use of reflection for deserialization. Another option would be to have a public version for each response class (like the current one) and another private one. The private one has public setters, but is not exposed in the API, and you make a copy of it to the public version. You can probably think of a better way to do this, but those are what I could think of.
At the moment, we're using an internal build of CloudinaryDotNet to get around these problems, but we'd like to see them addressed in a future version.
Best regards
Before proceeding, please update to latest version and test if the issue persists
I used version 1.13.1
It seems you are missing a project reference.
[ ] Build - Can’t install or import the SDK
[ ] Performance - Performance issues
[X ] Behaviour - Functions aren’t working as expected (Such as generate URL)
[ ] Documentation - Inconsistency between the docs and behaviour
[ ] Other (Specify)
Just try to add a photo using UploadAsync method.
Version: 1.51.0 (user setup)
Commit: fcac248b077b55bae4ba5bab613fd6e9156c2f0c
Date: 2020-11-05T18:18:23.642Z
Electron: 9.3.3
Chrome: 83.0.4103.122
Node.js: 12.14.1
V8: 8.3.110.13-electron.0
OS: Windows_NT x64 10.0.19042
Cloudinary .NET SDK version 1.13.1
5.0.100-preview.8.20417.9
If possible, please provide a link to a reproducible repository that showcases the problem
It is private but I can share by giving access to someone.
Hi,
I'm busy implementing this library into one of our views, to view images and using this line of code to do it:
@Html.Raw(cloudinary.Api.ApiUrlImgUp.Transform(new Transformation()
.Width(480)
.Height(480))
.BuildImageTag(image.CloudinaryPulicId)
);
and it generates the following URL for the image https://api.cloudinary.com/some-company/image/upload/v1/products/DWagdjpg .
This URL returns a 404 but if i change it to https://res.xxxxxx it works, but with https://api.xxxxx it doesnt.
Is this a bug in the library or am i missing something.
Does Cloudinary support Xamarin mobile clients ? Xamarin uses the mono subset (4.5), not the full .net runtime.
I try to make the first call to the lib, I found some inconsistencies:
new ListResourcesParams(Type = "upload", Tags = true , Prefix = company) //Prefix not exist
cloudinary.ListResourcesByPrefix(company, "upload", "") // Can't apply others params
I find it weird how some calls allow this or that. I wonder why is just cloudinary.ListResources(params)
and if want make utility for params like ListResourcesParams.ByPrefix()
instead.
It is not possible to install the package with nuget in the last version of Visual Studio 2015 for a windows phone uwp project.
Is it possible for you to fix it ?
Cloudinary References NewtonSoft.Json 11.0.0 but that version does not exists (https://www.nuget.org/packages/Newtonsoft.Json/)
So nuget have to settle for 11.0.1 and causes warning NU1603.
The nuspec should be updated to point to an existing version.
I have just received the following exception when calling cloudinary.Upload(uploadParams). I have performed thousands of uploads (currently 28k+ images successfully uploaded) and have seen this occur twice.
A quick google suggests that the error occurs because instance members of HashAlgorithm cannot be guarnteed to be thread safe.
http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1%28v=vs.110%29.aspx
http://stackoverflow.com/questions/569683/hmacsha1-computehash-thread-safety-question
Cheers
Michael
Unhandled Exception: System.Security.Cryptography.CryptographicException: Hash n
ot valid for use in specified state.
at System.Security.Cryptography.CryptographicException.ThrowCryptogaphicExcep
tion(Int32 hr)
at System.Security.Cryptography.Utils._HashData(SafeHashHandle hHash, Byte[]
data, Int32 ibStart, Int32 cbSize)
at System.Security.Cryptography.HashAlgorithm.ComputeHash(Byte[] buffer)
at CloudinaryDotNet.Api.GetSign(IDictionary2 parameters) at CloudinaryDotNet.Api.FinalizeUploadParameters(IDictionary
2 parameters)
at CloudinaryDotNet.Api.Call(HttpMethod method, String url, SortedDictionary 2 parameters, FileDescription file) at CloudinaryDotNet.Cloudinary.Upload(ImageUploadParams parameters) at Netcars.Framework.Services.CloudinaryApi.CDNUploader.PerformUpload(FileDes cription file, String tags, String id) at Netcars.Framework.Services.CloudinaryApi.CDNUploader.ProcessImages(List
1
items)
at ImportProcessor.Models.CloudinaryTasks.CloudinaryUploadTask.DoThreadWork()
at Netcars.Framework.Core.Threading.AbstractTask`1.ThreadStart()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, C
ontextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Hi, hope you're doing well.
I have the Cloudinary .NET SDK integrated with a Unity project. I've placed the CloudinaryDotNet DLL, as well as all of its DLL dependencies, inside my project. I'm able to access all the Cloudinary namespaces/classes/etc. from my code, which is fantastic.
Unfortunately, when I attempt a simple implementation of Cloudinary.Upload
, I get a FormatException
. Here's the problem code:
public void UploadImage()
{
ImageUploadParams uploadParams = new ImageUploadParams
{
File = new FileDescription("https://www.fnordware.com/superpng/pnggrad16rgb.png"), // Just a simple gradient image for testing
};
cloudinary.Upload(uploadParams); // FormatException is traced back to this line
}
Before the above method is called in my program, I'm setting my configuration parameters as outlined in the documentation, like this (with my actual info substituted):
Account account = new Account(
"my_cloud_name",
"my_api_key",
"my_api_secret");
Cloudinary cloudinary = new Cloudinary(account);
Here are the package versions I'm using:
Below is the FormatException
that I'm getting:
FormatException: One of the identified items was in an invalid format.
System.Net.Http.Headers.HttpHeaders.AddInternal (System.String name, System.Collections.Generic.IEnumerable`1[T] values, System.Net.Http.Headers.HeaderInfo headerInfo, System.Boolean ignoreInvalid) (at <efff4cb93af94c0c950db61b78368b54>:0)
System.Net.Http.Headers.HttpHeaders.Add (System.String name, System.Collections.Generic.IEnumerable`1[T] values) (at <efff4cb93af94c0c950db61b78368b54>:0)
System.Net.Http.Headers.HttpHeaders.Add (System.String name, System.String value) (at <efff4cb93af94c0c950db61b78368b54>:0)
CloudinaryDotNet.ApiShared.PrePrepareRequestBody (System.Net.Http.HttpRequestMessage request, CloudinaryDotNet.HttpMethod method, System.Collections.Generic.Dictionary`2[TKey,TValue] extraHeaders) (at <0c3884533d824ad98e55170b6aba31df>:0)
CloudinaryDotNet.ApiShared+<PrepareRequestBodyAsync>d__75.MoveNext () (at <0c3884533d824ad98e55170b6aba31df>:0)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0)
CloudinaryDotNet.ApiShared+<CallAsync>d__58.MoveNext () (at <0c3884533d824ad98e55170b6aba31df>:0)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0)
CloudinaryDotNet.ApiShared+<CallAndParseAsync>d__56`1[T].MoveNext () (at <0c3884533d824ad98e55170b6aba31df>:0)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0)
CloudinaryDotNet.Cloudinary.Upload[T,TP] (TP parameters) (at <0c3884533d824ad98e55170b6aba31df>:0)
CloudinaryDotNet.Cloudinary.Upload (CloudinaryDotNet.Actions.ImageUploadParams parameters) (at <0c3884533d824ad98e55170b6aba31df>:0)
CloudinaryUploader.UploadImage () (at Assets/Scripts/_general/Cloudinary/CloudinaryUploader.cs:28)
I'm working on a Mac inside Unity 2021.1.3f1, which can use either .NET Standard 2.0 or .NET 4.x. Both APIs produce the above error.
Please let me know if there's any additional information I can provide.
Thank you so much. I would really appreciate any insight anyone might have.
All the best,
Galen
The Tag()
api call is locked to ResourceType.Image
(since it is using ApiUrlImgUpV
).
I had made a pull request to fix this for both the Rename and Tag functions (see #35 ).
The Rename function is now updated (thanks!), but the Tag function is not, and the request has been closed.
Is there any intent to add support for dnxcore50 for VNext applications? Perhaps in a prerelease branch? Please?
The following (hopefully simple and obvious) code works, but once in a while will glitch with an error. On retrying, the error has gone.
private string UploadImageToCloud(string path, string imageId, ImageUploadStatus imageUpload)
{
try
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(path),
Invalidate = imageUpload == ImageUploadStatus.Updated,
PublicId = imageId,
Overwrite = true,
};
var uploadResult = cloudinary.Upload(uploadParams);
if (uploadResult.StatusCode == System.Net.HttpStatusCode.OK)
{
return uploadResult.Version;
}
}
catch (Exception ex)
{
Log.Error(ex, "Unable to upload image.");
}
return string.Empty;
}
It seems that there is a connectivity issue or the backend throws an error and returns the web server HTML error page which causes the JSON parser to throw an error (I've come across the same problem with other code before).
The stack trace is;
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at CloudinaryDotNet.Api.Parse[T](Object response)
at CloudinaryDotNet.Api.CallAndParse[T](HttpMethod method, String url, SortedDictionary2 parameters, FileDescription file, Dictionary
2 extraHeaders)
at CloudinaryDotNet.Cloudinary.Upload(ImageUploadParams parameters)
at ImageSyncService.Logic.ImageSync.UploadImageToCloud(String path, String imageId, ImageUploadStatus imageUpload) in C:\inetpub\wwwroot\ImageSyncService\Logic\ImageSync.cs:line 221
I appreciate that the server should not be returning HTML when erroring (or it might be an intermediate gateway) and that's outside the scope of this client, but could the client be made to be more tolerant of this situation by returning a 'server is talking rubbish' message?
If so, do you want a pull request to handle this?
Regards
Ryan
Hi I'm new to Cloudinary, may I know as the code showing below, am I able to insert the HttpPostedFileBase to upload into Cloudinary?
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(@"c:\my_image.jpg")
};
var uploadResult = cloudinary.Upload(uploadParams);
Hi, I'm getting the error while trying to upload the image to cloudinary. The error message shows that it has the exception while parsing value. The back-end of my project is Asp.Net Core 2.
The total error messages:
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An unhandled exception has occurred: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at CloudinaryDotNet.Api.Parse[T](Object response)
at CloudinaryDotNet.Api.CallAndParse[T](HttpMethod method, String url, SortedDictionary`2 parameters, FileDescription file, Dictionary`2 extraHeaders)
at CloudinaryDotNet.Cloudinary.Upload(ImageUploadParams parameters)
at Dating.API.Controllers.PhotoController.<AddPhotoForUser>d__6.MoveNext() in D:\Practices\Udemy Courses\Dating.API\Controllers\PhotoController.cs:line 74
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
The method to upload file to cloudinary site:
[HttpPost]
public async Task<IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoDto)
{
var user = await _repo.GetUser(userId);
if (user == null)
return BadRequest("Could not find user");
var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
if (currentUserId != user.Id)
return Unauthorized();
var file = photoDto.File;
var uploadResult = new ImageUploadResult();
if (file.Length > 0)
{
using (var stream = file.OpenReadStream())
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(file.Name, stream)
};
uploadResult = _cloudinary.Upload(uploadParams); //This line cause the error
}
}
photoDto.Url = uploadResult.Uri.ToString();
photoDto.PublicId = uploadResult.PublicId;
var photo = _mapper.Map<Photo>(photoDto);
photo.User = user;
if (!user.Photos.Any(m => m.IsMain))
photo.IsMain = true;
user.Photos.Add(photo);
if (await _repo.SaveAll())
{
var photoToReturn = _mapper.Map<PhotoForReturnDto>(photo);
return CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn);
}
return BadRequest("Could not add the photo");
}
I use the Postman to test the upload method with this configuration:
P/S: I have already used the CloudinaryDotNet version of 1.1.0-rc1 and 1.1.1. Both of them throw the same error. Is anyone faced with the same problem? Is there any way to fix it? Any comment will be very appreciated.
Hello, I'm having a problem where the UploadResult returned from the method Upload in the Cloudinary class is completely empty, and this problem happens randomly.
The code:
public string Put(string imageUrl)
{
var fileDescription = new FileDescription(imageUrl);
var result = this.provider.Upload(new ImageUploadParams{ File = fileDescription });
return result.Uri.AbsoluteUri;
}
Hello, it seems that Cloudinary is currently not supporting .net standard 2. We currently migrate our solutions to .net core and the middle step is to target .net standard 2 so I would like to task if this is planned and when.
When performing ListResources operation a result of type ListResourceResult is returned containing single Resource object. The property JsonObj of result object contains JToken representing the full response, including resource, but property JsonObj of inner resource object is null, although other properties are set.
I have two video files (both mp4), can't get those from ListResources call. Is there any special method to get videos?
I'm trying to upload an image using .Net SDK, when I add MetadataFields
I get error with this message : Invalid value for parameter kind
but when I remove the MetadataFields
it works.
Here is the code:
var customMetadata = new StringDictionary()
{
{"MimeType","image/jpeg" }
};
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(@"Path\test.jpg"),
MetadataFields = customMetadata,
};
var result = await _cloudinary.UploadAsync(uploadParams);
The result give me the 400 bad request and in the result.error.message="Invalid value for parameter kind"
.
We have a shared C# library that encapsulates a good bit of business logic from a number of vendors...Cloudinary being one of them. We have been on the 1.0.x line with no issues. We are testing the 1.1.x line and are able to update to 1.1.0. But, in attempting to update to 1.1.1, NuGet is reporting that the package is incompatible with .NET Framework 4.7.1.
Is this intentional? We're not at a place where we can move strictly to .NET Standard. I could probably just create a .NET Standard library just to house Cloudinary if necessary, but it seems that a breaking change like that would have been noted in the changelog?
Any assistance would be greatly appreciated.
When uploading a video file the result contains playback_url
field which is currently not exposed in Cloudinary .NET SDK.
Add PlaybackUrl
field in VideoUploadResult
When try to upload a photo from the app (with dotnet run or dotnet watch run) i have Json Serialization Error: Foribbiden. However, when run from the VSCode debugger everything works fine.
[ ] Build - Can’t install or import the SDK
[ ] Performance - Performance issues
[X ] Behaviour - Functions aren’t working as expected (Such as generate URL)
[ ] Documentation - Inconsistency between the docs and behaviour
[ ] Other (Specify)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Exception: Failed to deserialize response with status code: Forbidden
---> Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.JsonReader.ReadAndMoveToContent()
at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at CloudinaryDotNet.ApiShared.CreateResultFromString[T](String s, HttpStatusCode statusCode)
--- End of inner exception stack trace ---
OS: Arch Linux
Cloudinary .NET SDK version: 1.10.0
.NET Core - 3.0.1
Provide interfaces
for the main CloudinaryDotNet classes.
Has anyone on the team considered adding any interfaces to the CloudinaryDotNet SDK, which would make it way easier for testing scenario's / projects?
If we wish to test some custom service which uses the CloudinaryDotNet SDK/nuget package, then we need to create instances of this class which means it will try and hit the real resources/endpoints.
Versus, if there are some interfaces
, then we can just provide that (vid DI/IoC) to any of our own code and when it comes to testings, it's soo much easier.
Currently, we need to create our own custom "wrapper" Cloudinary class + interface, which just has an internal instance of this cloudinary SDK inside it. Works? Sure.. a bit of a pain? yes :(
The main problem we have is that when we write our tests, we don't want to be hitting the real Cloudinary endpoints. This is bad. We just want to pretend we are hitting them and get back a good or bad pretend result and then see how our code deals with that.
Looking at the CloudinaryDotNet TESTS in this repo, I can see that there is a MockedCloudinary class which you folks have created to sorta deal with this. Basically, you're trying to hijack the low level HttpClient response and then let the rest of the code see how it handles. This is GREAT for testing your CloudinaryDotNet SDK because you need to test both the happy path and the bad paths, when bad things happen and to make sure the CloudinaryDotNet SDK can handles all the various scenario's. Great! But when it comes to consumers of your library, then should NOT KNOW of these low level details. I shouldn't be having to deal with faking the response of the HTTPClient. I should even KNOW what this SDK is doing behind the scenes!
We should just be dealing with the public methods and their results (good and bad).
Interfaces enable this -> easily!
Sure do!
Add interfaces
to the public classes :)
For example, with the class public class Cloudinary
, generate an interface for all of these public properties and methods.
Then we can have some nice code that looks like this:
public interface ICloudinary
{
Task<ImageUploadResult> UploadAsync(ImageUploadParams parameters, CancellationToken? cancellationToken = null);
}
public class Cloudinary: ICloudinary
{
// Ctor, all the same methods, etc.
public Task<ImageUploadResult> UploadAsync(ImageUploadParams parameters, CancellationToken? cancellationToken = null)
{ ... }
}
public class MyService : IMyService
{
private readonly ICloudinary _cloudinary;
public MyService(ICloudinary cloudinary)
{
_cloudinary = ICloudinary;
}
public async Task DoSomethingAsync()
{
// some stuff ...
await result = _cloudinary.UploadAsync(someImageUploadParams, cancellationToken);
// some more stuff ...
}
}
public class DoSomethingAsyncTests
{
[Fact]
public async Task GivenSomeImage_DoSomethingAsync_ShouldUploadTheImage()
{
// Arrange.
var imageUploadResult = new ImageUploadResult(); // Whatever result data goes in here.
var cloudinary = new Mock<ICloudinary>();
cloudinary
.Setup(x => x.UploadAsync(It.Is<ImageUploadParams>(iup => ....), It.IsAny<CancelltionToken>())
.ReturnsAsync(imageUploadResult);
var service = new MyService(cloudinary.Object);
// Act.
await service.DoSomethingAsync();
// Assert.
cloudinary.VerifyAll(); // Makes sure that our code did end up calling Cloudinary with the _specific_
}
}
It looks like the predominant parameter is missing from the GetResourceResult object.
There is no AccessMode property available in RawUploadParams structure, although it is possible to specify it via AddCustomParam method and server accepts it. This parameter is also not parsed into ListResourcesResult structure, although it is available in raw json object.
Hi,
At some screen, I'm uploading images while completing a form and then saving the returned Public Ids that the API return on the database.
On another method, I'm trying to retrieve the signed URL by providing the public id, for example, "dev/pynin7oskrstrzahhfwz" to the following method:
account.Api.UrlImgUp.Signed(true).BuildUrl("dev/pynin7oskrstrzahhfwz");
While this method doesn't throw any exception, the result returns a 404 error:
http://res.cloudinary.com/{cloudName}/image/upload/{signature}/v1/dev/{public id}
It seems that I need to provide the file extension after the public id in order to get this signed url working.
Changing this to
http://res.cloudinary.com/{cloudName}/image/upload/{signature}/v1/dev/{public id}.{fileExtension}
works.
Is there a way to get the signed image URL by only providing the id? There could be some scenario where I cannot know which file type I should ask for.
the following code is not working in cloudinary nuget package version -- 1.21.0. I am using .net core
AuthToken t = new AuthToken("MyKey").Expiration(1514764800);
string url = cloudinary.Api.Url
.AuthToken(t)
.Signed(true)
.Type("authenticated")
.BuildVideoTag("dog.mp4");
Type("authenticated") is not found in above code.
I am following https://cloudinary.com/documentation/control_access_to_media#delivering_token_based_authenticated_media_assets tutorial
Please also provide any sample for token based authentiv=cation .net core
Hi,
looking at the implementation of the Api.cs, there is no way to set global Url.Secure(true) flag:
public Url Url
{
get
{
return new Url(Account.Cloud, this)
.CSubDomain(CSubDomain)
.Shorten(ShortenUrl)
.PrivateCdn(UsePrivateCdn)
.Secure(UsePrivateCdn)
.SecureDistribution(PrivateCdn);
}
}
Can you please fix this by providing a way to set this flag globally without requirement to set UsePrivateCdn to true.
Thank you,
Michal
The CloudinaryDotNet.nuspec file is currently pointing to version 12.0 of Newtonsoft.Json, which does not exist. The correct version is 12.0.1.
This leads to the following warning when using the library:
CloudinaryDotNet 1.9.1 depends on Newtonsoft.Json (>= 12.0.0) but Newtonsoft.Json 12.0.0 was not found. An approximate best match of Newtonsoft.Json 12.0.1 was resolved.
This is a similar problem to #116
From documantion: Delivering token-based authenticated images
duration - the duration that the URL is valid in seconds
This property does not work, the Url is valid forever.
Before proceeding, please update to latest version and test if the issue persists
…
… if applicable
…
If possible, please provide a link to a reproducible repository that showcases the problem
Any plans to support .net core? My website is written in it and I was hoping to use this service but I can't use a NuGet package that does not target netstandards 1.x...
I've looked into the code but so far I couldn't find any means to set the text color (co_...
) of a TextLayer
with this library.
Not sure if this is a bug or rather a feature request.
Is there a metadata endpoint for videos? My use case Is I would like to know the aspect ratio of a video prior to streaming of a video from cloudinary. I have a custom video presenter I am working with.
Before proceeding, please update to latest version and test if the issue persists
When you try to upload a file larger then 2Gb (video) the SDk get an exception
Upload a video larger then 2Gb
Unhandled Exception: System.IO.IOException: An attempt was made to move the file pointer before the beginning of the file.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.SeekCore(Int64 offset, SeekOrigin origin)
at System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin)
at CloudinaryDotNet.ApiShared.SetStreamToStartAndCreateWriter(FileDescription file, Stream stream)
at CloudinaryDotNet.ApiShared.GetRangeFromFile(FileDescription file, Stream stream)
at CloudinaryDotNet.ApiShared.PrepareMultipartFormDataContent(SortedDictionary2 parameters, FileDescription file, Dictionary
2 extraHeaders)
at CloudinaryDotNet.ApiShared.PrepareRequestContent(HttpRequestMessage request, SortedDictionary2 parameters, FileDescription file, Dictionary
2 extraHeaders)
at CloudinaryDotNet.ApiShared.PrepareRequestBody(HttpRequestMessage request, HttpMethod method, SortedDictionary2 parameters, FileDescription file, Dictionary
2 extraHeaders)
at CloudinaryDotNet.ApiShared.Call(HttpMethod method, String url, SortedDictionary2 parameters, FileDescription file, Dictionary
2 extraHeaders)
at CloudinaryDotNet.ApiShared.CallAndParse[T](HttpMethod method, String url, SortedDictionary2 parameters, FileDescription file, Dictionary
2 extraHeaders)
at CloudinaryDotNet.ApiShared.CallApi[T](HttpMethod method, String url, BaseParams parameters, FileDescription file, Dictionary`2 extraHeaders)
at CloudinaryDotNet.Cloudinary.UploadLarge[T](BasicRawUploadParams parameters, Int32 bufferSize)
at CloudinaryDotNet.Cloudinary.UploadLarge(VideoUploadParams parameters, Int32 bufferSize)
If possible, please provide a link to a reproducible repository that showcases the problem
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.