I am saving several graphs that I have created with:
plotly_IMAGE(graph, format = "png", out_file = filename)
but:
Error in process.image(append_class(resp, "image")) :
Internal Server Error (HTTP 500).
I have provided user name and API KEY, so I don't know where my problem is. Furthermore, this code worked but suddenly it stopped working.
Related
I wonder if anyone can help, and if the issue is specific to Last.fm (perhaps not the greatest of APIs).
I've built an album search feature into my app that takes two parameters - album and artist. Now, this returns an album just fine if there's a result, but in the instances that there isn't a result - if just type gibberish into the fields - Rails breaks with a 404 error when trying to run URI.open(url).read.
What I don't quite understand (and I am fairly new at this), is that when I run the same API call url in my search engine, with the gibberish, I do get a JSON response:
// https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=xxxxxxx&artist=akjsdhkasd&album=hdkuahd&format=json
{
"message": "Album not found",
"error": 6
}
So, I don't understand why I'm getting a 404 error when it runs in my code.
Is there any way that I can rescue this, so that I can just render a 'no result', rather than crashing the entire site?
Not sure my code adds much to the picture, but this is where I run the URI:
def get_album(artist, album)
album = ERB::Util.url_encode(album)
artist = ERB::Util.url_encode(artist)
url = "https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=xxxx&artist=#{artist}&album=#{album}&format=json"
serialized = URI.open(url).read
JSON.parse(serialized, object_class: OpenStruct).album
end
Thanks for any pointers.
From what I understood, you are using open-uri to reach this service. If you want to rescue an exception in this process you can try something like this:
def get_album(artist, album)
album = ERB::Util.url_encode(album)
artist = ERB::Util.url_encode(artist)
url = "https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=xxxx&artist=#{artist}&album=#{album}&format=json"
serialized = URI.open(url).read
JSON.parse(serialized, object_class: OpenStruct).album
rescue OpenURI::HTTPError
"Error when trying to fetch album information"
end
*I'm returning just a string but you can implement an appropriate return that fits your purpose.
I'm not sure if it's possible to rescue specific 404 - Not Found errors using this strategy. But, you can take a look into 'net/http' or other HTTP Client Libraries (httparty, typhoeus, etc..) to try different approaches if you want..
I am trying to get a very simple c# snippet on predicting an image, but get following error (there is very little on the internet around this subject):
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models.CustomVisionErrorException HResult=0x80131500 Message=Operation returned an invalid status code 'NotFound'
var predictionClient = GetPredictionClient();
predictionClient.ClassifyImageUrl(Guid.Parse("5329678e-2a6b-46cf-ac11-fbd19ce89353"), "Iteration2", new ImageUrl("https://storageinfluencer.blob.core.windows.net/social-media-images/1e8bfef3-f070-44b9-9ae4-4b0d8a31316d.jpg"));
CustomVisionPredictionClient GetPredictionClient()
{
CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient()
{
ApiKey = "xxx",
Endpoint = "https://northeurope.api.cognitive.microsoft.com/customvision/v3.0/Prediction/"
};
return endpoint;
}
I got a little closer by using fiddler. EndPoint should be https://northeurope.api.cognitive.microsoft.com only even if portal says copy the other as end point. However now I get:
{"code":"BadRequest","message":"Invalid project type for operation."}
I have following POST in fiddler:
https://northeurope.api.cognitive.microsoft.com/customvision/v3.0/prediction/xx-xx-xx-xx-xx/classify/iterations/Iteration2/url HTTP/1.1
I think I finally found why you got this 404, thanks to... Intelligent Kiosk demo being open-source!
See how they pass the endpoint value in their code, here:
private const string SouthCentralUsEndpoint = "https://southcentralus.api.cognitive.microsoft.com";
As you can see, the Endpoint field is the value of the root, not the Custom Vision Prediction API root
So change your
Endpoint = "https://northeurope.api.cognitive.microsoft.com/customvision/v3.0/Prediction/"
to:
Endpoint = "https://northeurope.api.cognitive.microsoft.com"
And it should be fine. I made a test with WestEurope and some CustomVision projects that I already had, it is working fine.
I have a .NET MVC project and I'm trying to download a file from temporary folder. Here is my view code:
window.open('#Url.Action("DownloadDocument", "Controller")?fileName=' + fileName, '_blank');
And here is my controller code:
public FileResult DownloadDocument(string fileName)
{
string path = Web.Common.Properties.Settings.Default.TempDocPath + "OpenTable\\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return File(fileName, "application/xml", fileName + ".xml");
}
This code works on IIS and file is being downloaded. But I'm getting 500 error when trying to download it from remote server.
This site can’t be reached
The webpage at <...> might be temporarily down or it may have moved permanently to a new web address.
ERR_INVALID_RESPONSE
And the worst part is that there are some almost exact code snippets in the system which are working in both IIS and remote server.
Any suggestions what could be done?
UPDATE
Good news. When I tried postman it threw a file not found error with wrong path. It's an easy fix:
return File(Path.Combine(path, fileName), "application/xml", fileName + ".xml");
So it puzzles me... How and why it was working locally on IIS with wrong path?
You need to create your temp folder inside the root folder of your web app, for example ~/Temp, then use below code to access to that folder instead of Web.Common.Properties.Settings.Default.TempDocPath, I think this maybe just a constant.
System.Web.Hosting.HostingEnvironment.MapPath("~/Temp")
We implement Solr search in a document manager we use. When a user requests to search for all the documents in a given directory, we are forced to aggregate the docids of the user's selected documents into an array and send a
SolrQueryInList("docid", arrFileNames)
If the number of files in the user's directory is very large, so is the resulting http request. Ergo, we decided to use SolrPostConnection. In our site we implement the PostSolrConnection decorator within the Windsor container, as per M. Scheeffer's instructions:
public SolrSearchRepository(int caseID, string solrServer)
{
this.facility = new SolrNetFacility(solrServer);
this.facility.AddCore(caseID.ToString(), typeof(SolrDocument),
string.Format("{0}/{1}", solrServer, caseID));
this.container = new WindsorContainer();
this.container.Register(Component.For<ISolrConnection>()
.ImplementedBy<PostSolrConnection>()
.DependsOn(Parameter.ForKey("serverUrl").Eq(solrServer)));
this.container.AddFacility(this.facility);
solrOperation = this.container
.Resolve<ISolrOperations<SolrDocument>>(caseID.ToString());
}
However, we are still getting the following error:
{"Message":"An error has occurred.","ExceptionMessage":"The remote server returned an
error: (400) Bad Request.","ExceptionType":"System.Net.WebException","StackTrace":"
at System.Net.HttpWebRequest.GetResponse()\r\n at
HttpWebAdapters.Adapters.HttpWebRequestAdapter.GetResponse()\r\n at
SolrNet.Impl.SolrConnection.GetResponse(IHttpWebRequest request)\r\n at
SolrNet.Impl.SolrConnection.Get(String relativeUrl, IEnumerable`1 parameters)"}
We use Tomcat 7.0 server. The logs are pretty uniformative. Here's the pastebin of what seems to happen around the time I launch a search:
Solr Log
I noticed that the command never reaches the server. Is the PostSolrConnection not implementing post? Note that this query works perfectly with small number of files (i.e. docid's)
Following the tutorial found on ASP.NET, implemented a Web API controller method for doing asynchronous file uploads that looks like this:
public Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
Uploading a file via a standard multipart HTML form works perfectly. However, when another developer attempts to upload a file via multipart form constructed by Flex's FileReference class, an error is thrown:
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
I have no idea if the problem lies in Web API or Flex. I've found some sort of related fixes that had no affect (Multipart form POST using ASP.Net Web API), and more recently this one ("MIME multipart stream. MIME multipart message is not complete" error on webapi upload). If the second link holds true, does anyone know if it's out in the current release of Web API available via Nuget? The discussion was in May, the most recent release from Nuget was August, so I assume this fix was deployed already, and is not the root cause of my issue.
I had the same problem with MVC4, but Will is correct, add a name to your input.....
<input type="file" id="fileInput" name="fileInput"/>
and all the magic is back up and working!
I had the same problem with flex. And below is the code that solved it. Basically I used a custom stream to append the newline that asp.net web api is expecting.
Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
MemoryStream tempStream = new MemoryStream();
reqStream.CopyTo(tempStream);
tempStream.Seek(0, SeekOrigin.End);
StreamWriter writer = new StreamWriter(tempStream);
writer.WriteLine();
writer.Flush();
tempStream.Position = 0;
StreamContent streamContent = new StreamContent(tempStream);
foreach(var header in Request.Content.Headers)
{
streamContent.Headers.Add(header.Key, header.Value);
}
// Read the form data and return an async task.
await streamContent.ReadAsMultipartAsync(provider);
Hope this helps.
Reading through your existing research and following through to the codeplex issue reported it looks like someone else confirmed this issue to still exist in September.
They believe that MVC 4 fails to parse uploads without a terminating "\r\n".
The issue is really simple but extremely hard to fix. The problem is that Uploadify does > not add an "\r\n" at the end of the MultiPartForm message
http://aspnetwebstack.codeplex.com/discussions/354215
It may be worth checking that the Flex upload adds the "\r\n"
For those landing here googling:
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
Reading the request stream more than once will also cause this exception. I struggled with it for hours until I found a source explaining that the request stream only could be read once.
In my case, I combined trying to read the request stream using a MultipartMemoryStreamProvider and at the same time letting ASP.NET do some magic for me by specifying parameters (coming from the request body) for my api method.
Make sure the virtual directory ("~/App_Data" directory as below example) where the image files are first uploaded are physically existance. When you publish the project, it may not be in the output files.
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
I just removed my headers I was setting on my post method which ended up solving this issue.
The problem is this line:
string root = HttpContext.Current.Server.MapPath("~/App_Data");
It will only work in localhost, you can use HostingEnvironment.MapPath instead in any context where System.Web objects like HttpContext.Current are not available (e.g also from a static method).
var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/SomePath");
See also What is the difference between Server.MapPath and HostingEnvironment.MapPath?
Reference to this answer How to do a Server Map Path.