Artifactory REST Deploy screwing up upload - c#

I am trying to deploy artifacts to artifactory using their REST API, however all my files end up having
-------------------------------28947758029299 Content-Disposition: form-data; name="test.txt"; filename="new2.txt" Content-Type:
application/octet-stream
appended to the file. Here is my code (keep in mind this is only me testing the concept...the code will be cleaned after I get a success)
var uriString = "artifactoryuri";
var uri = new Uri(uriString);
var credentialCache = new CredentialCache{{uri, "Basic",new NetworkCredential("UN", "PW")}};
var restClient = new RestClient(uriString);
var restRequest = new RestRequest(Method.PUT){Credentials = credentialCache};
restRequest.AddFile("test.txt", #"pathto\new2.txt");
var restResponse = restClient.Execute(restRequest);
How can I fix this? Is it because it is a text file and artifactory tends to store executables and such? If so, I can live with that. This will be used to upload chm files currently.

This is caused by the AddFile method - RestSharp will create a multipart/form request by default. I could not find a good solution for preventing this behavior, although many people ask about it. You can take a look at Can RestSharp send binary data without using a multipart content type? and PUT method and send raw bytes

Related

Get file stream without load it into memory

How is it possible to get the file that the user is uploading without load it into memory?
This row make the memory go up var request = await httpContent.ReadAsMultipartAsync();
The client can only upload one file so is there a way to get the stream without go trough ReadAsMultipartAsync?
var request = await httpContent.ReadAsMultipartAsync();
var content = request.Contents.FirstOrDefault();
var stream = await content.ReadAsStreamAsync();
I only want the stream of the content. If I get the stream like this:
var stream = await httpContent.ReadAsStreamAsync();
Then it give a file that looks like this:
-----------------------------224143682423505141523038143258
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain
my dummy content
-----------------------------224143682423505141523038143258--
Uploading file to an asp.net webservice always bloats the memory because that's the way your request pipeline works. There is an alternative though, when you are using a cloud service for example. In that case you can use the valet key pattern to upload a file immediately to a storage solution. This prevents your service from having to deal with the payload.
If you do want your service to handle the request, there's no way of doing to without consuming memory.

How do you make a Post request with binary file in this situation?

i have System A (Web Interface for people to upload files) and System B (file archive system).
step 1) User submits a files via System A
step 2) System A receives the files ,and encrypt it
step 3) System A sends a Post request with the decrypted file by calling System B 's end point (http://127.0.0.1:8080/rest/bookstore/).
step 4) System B receives the POST request. then archive the file .
at this moment , i am stuck in step 3. i am abled to receive the files, but throw a exception when System A make a Post Request with the file
i am trying to post a csv file to http://127.0.0.1:8080/rest/bookstore/. However it return
RestSharp.RestClient.Execute returned "StatusCode: NotAcceptable, Content-Type: , Content-Length: 0)" RestSharp.RestResponse
Do you have any idea what wrong in below code?
string path = "THE PATH OF THE FILE";
byte[] file = System.IO.File.ReadAllBytes(path);
string filevalue = System.Convert.ToBase64String(file);
var client = new RestClient("http://127.0.0.1:8080/rest/bookstore/");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "text/csv");
request.AddParameter("text/csv", file , ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
You should not need to redirect, should simply be:
public class BookstoreController : ApiController
{
public void Get() => Download();
}
public static void Download()
{
var client = new RestClient("...");
var request = new RestRequest("...", Method.POST);
var response = client.Execute(request);
client.DownloadData(new RestRequest("/file", Method.GET)).SaveAs("filename.csv");
Console.WriteLine("Output: ");
Console.WriteLine(response.Content);
}
In essence, you could do the method content to download the file. But create the client and request, then execute the response but download the data from the request into the response. Then it should force the browser to download the file for the user.
Today i have checked the system Log . i found this message (which means my file is archived).
INFO 11:15:01.938 (FedoraLdp) GET resource 'bookstore/cc51bc52-e59a-4e29-801a-e7d979326197'
So that i try to submit Post Request and check if file is archived .
and finally found that the file is archived as showed in system log. even though ,In the Http Post response ,it said that my Request is not acceptable ...
So that i think that The API End point does not return my a correct message and not giving me a clear information about what is missing in Http Post Request i made.

Sharepoint online API returns: HTTP Error 400. A request header field is too long

I have a loop that will loop through records in my DB, pulling information i need and then creating 3 folders & upload a file.
This works OK for like 40 records but then it starts erroring out with the below response back from sharepoint: <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\">\r\n<HTML><HEAD><TITLE>Bad Request</TITLE>\r\n<META HTTP-EQUIV=\"Content-Type\" Content=\"text/html; charset=us-ascii\"></HEAD>\r\n<BODY><h2>Bad Request - Header Field Too Long</h2>\r\n<hr><p>HTTP Error 400. A request header field is too long.</p>\r\n</BODY></HTML>
I am not sure whats going on, i read online its todo with cookies but i am using HTTPClient to send the request so i dont know how that would effect it? I also seen onlne about changing the kestrel?
Can anybody shed some light on this for me? Provide me with an easy but working solution? I dont use CSOM for integrating to sharepoint online, i use HTTP Requests, below is a sample of how i interact with sharepoint.
It seems as if i get blocked or banned temporarily cause if i wait a good bit, i can then make the same request that failed previously, and it will work! So strange.
Sample code (Used to create a resource at Sharepoint):
//Set Endpoint
var sharePointEndpoint = $"https://{hostname}/sites/{site}/_api/web/folders";
//Set default headers
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sharePointToken); //Set token
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
//Pre-Body data setup
var metaData = new MetaDataModel();
metaData.type = "SP.Folder";
//Body data setup
var bodyModel = new ExpandoObject() as IDictionary<string, object>;
bodyModel.Add("__metadata", metaData);
bodyModel.Add("ServerRelativeUrl", location + "/" + directoryName + "/");
//Set content headers
HttpContent strContent = new StringContent(JsonConvert.SerializeObject(bodyModel));
strContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
strContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
// Send request, grab response
var response = await client.PostAsync(sharePointEndpoint, strContent);
//Return response message
return response;
It turns out I needed to use Content-Length header when sending the request, once done I was able to successfully communicate with sharepoint without encountering this error.
More information here: https://social.technet.microsoft.com/Forums/en-US/26459f1c-945d-4112-9200-69c5a33a37ff/sharepoint-online-rest-api-returns-http-error-400-a-request-header-field-is-too-long?forum=sharepointdevelopment
Thanks.

Read ashx jpg with .Net 4.5

My goal is to read a jpg file from a ashx Url. I would like to do this with Windows Phone 8 but I'm starting with .Net 4.5 because that might be more simple for me.
Here is an example url:
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=239959&type=card
If you go to this Url in IE 10 you'll see an image. How do I download the image in .Net 4.5? I have tried using:
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpg"));
string resourceAddress = "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=239959&type=card";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);
HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);
byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
and also using WebClient
string url = #"http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card";
byte[] imageData;
using (WebClient client = new WebClient())
{
imageData = client.DownloadData(new Uri(url));
}
both of these methods return no data. How do I get the data and format it into a jpg? I am pretty new to using ashx files. I see that they are used easily in Asp.Net web sites but have not been able to find anything that allows to simply download the file. The goal is to download the jpg file and display it in a windows phone 8 application.
Take a look at that URL. You've URL encoded the &, so indeed there's nothing returned from
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card
this
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card
however, worked just fine for me in Windows 8 using your first code sample.
By the way, I see you set an Accept header of image/jpg, the ASHX seems to set the Content-type to image/jpeg - it does work though.

Find extension of file from URL

I want to find what is the extension of file in current URL.
I have used
http://tol.imagingtech.com/eIL/cgi-bin/eIL.pl?ACTION=get_trans_doc&DOC=ALL&CAB_NAME=TOL_AP_2012&WHSE=18&PAYEE=23003655&INV=01235770
The extension of this file is (.pdf) how can i get this. Sometimes it will be (.doc,.txt,.jpeg) so i want the exact one.
Following is the code which i used to retrieve file extension
var extFile = Document.DocumentFilePath.Split('.');
return "Backup document." + extFile[extFile.Length-1].Trim().ToLower();
It works fine for normal local path but it fails to retrieve extension which DocumentFilePath is url.
I think that there is no way to get the file type without actually getting it.
You can get the information in the response header once your request is completed.
Content-Type: image/jpeg
You can do it in C# using WebClient
WebClient client = new WebClient();
var url = "http://tol.imagingtech.com/eIL/cgi-bin/eIL.pl?ACTION=get_trans_doc&DOC=ALL&CAB_NAME=TOL_AP_2012&WHSE=18&PAYEE=23003655&INV=01235770";
string data = client.DownloadString(url);
string contentType = client.Headers["Content-Type"];
Do a HEAD request to the URL and take a look at the Content-Disposition: attachment; filename=FILENAME header if that's being used.
To find the content type, take it from the Http response as follows:
byte[] myDataBuffer = webClient.DownloadData(fileAbsoluteUrl);
string contentType = webClient.ResponseHeaders["Content-Type"];

Categories

Resources