how to use Management API in Windows Form / C# - but The remote server returned an error: (400) Bad Request - c#-4.0

I have a problem in API Management, I want to create images in item 1 item, but I still can not do it forever. I use c # language, I feel depressed
i want to create a resource in catchoom.
can you help me
byte[] buffer = null;
byte[] data = null;
byte[] data1 = null;
HttpWebRequest request = null;
int bytesRead = 0;
long length = 0;
string boundary = DateTime.Now.Ticks.ToString("x");
// string boundary = "AaB03x";
StringBuilder sb = null;
// Create the HttpWebRequest object
request = (HttpWebRequest)HttpWebRequest.Create("https://crs.catchoom.com/api/v0/image/?api_key=5aba12ba6974c04ebc95da45ba1597d27d75238f");
// Specify the ContentType
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
// Specify the Method
request.Method = "POST";
request.KeepAlive = false;
// Create the StringBuilder object
sb = new StringBuilder();
// Constrcut the POST header message
sb.AppendLine("");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: form-data; name=\"anh\"");
sb.AppendLine("");
sb.AppendLine("/api/v0/item/aee726ff67274fcb80f4c24f27861c1e/");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: file; name=\"anh\"; filename=\"anh\"");
sb.AppendLine("Content-Type: image/jpg");
sb.AppendLine("");
StringBuilder sb1 = new StringBuilder();
sb1.AppendLine("");
sb1.AppendLine("--" + boundary + "--");
// Convert the StringBuilder into a string
data = Encoding.UTF8.GetBytes(sb.ToString());
data1 = Encoding.UTF8.GetBytes(sb1.ToString());
//
using (FileStream fs = new FileStream(#"D:\17. NHATLINH\ToolKit_Catchoom\ToolKit_Catchoom\bin\Debug\aa.jpg", FileMode.Open, FileAccess.Read))
{
length = data.Length + fs.Length + data1.Length;
// đưa thông tin chiều dài của gói gửi đi vào
request.ContentLength = length;
//
using (Stream stream = request.GetRequestStream())
{
// ghi header vào gói gửi đi
stream.Write(data, 0, data.Length);
//
buffer = new Byte[checked((uint)Math.Min(4096, (int)fs.Length))];
// buffer = new Byte[fs.Length];
// Write the file contents
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
stream.Write(data1, 0, data1.Length);
//
try
{
Console.WriteLine(request.ContentType);
Console.WriteLine(sb.ToString() + sb1.ToString());
WebResponse responce = request.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
MessageBox.Show(sr.ReadToEnd());
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
}
}

Building a multipart-encoded request is an error-prone task ( it is normal if you feel frustrated trying ), I recommend you to use a library to handle this kind of things, no point in reinventing the wheel :)
If you are using the Microsoft .NET Framework >= 4.5, you may use the HttpClient class as this answer explains.
Hope this help you ;)

Related

Making HTTPS call in C# with the BouncyCastle library

Using C# 4.0, I need to make HTTPS call with the BouncyCastle library (Short story : Windows XP + TLS 1.2).
When using the following code, I get a "HTTP Error 400. The request verb is invalid."
Here is my code :
using (var client = new TcpClient("serverName", 443))
{
var sr = new SecureRandom();
var cl = new MyTlsClient();
var protocol = new TlsClientProtocol(client.GetStream(), sr);
protocol.Connect(new MyTlsClient());
using (var stream = protocol.Stream)
{
var hdr = new StringBuilder();
hdr.AppendLine("GET /Url/WebService.asmx?wsdl HTTP/1.1");
hdr.AppendLine("Host: serverName");
hdr.AppendLine("Content-Type: text/xml; charset=utf-8");
hdr.AppendLine("Connection: close");
hdr.AppendLine();
var dataToSend = Encoding.ASCII.GetBytes(hdr.ToString());
sr.NextBytes(dataToSend);
stream.Write(dataToSend, 0, dataToSend.Length);
int totalRead = 0;
string response = "";
byte[] buff = new byte[1000];
do
{
totalRead = stream.Read(buff, 0, buff.Length);
response += Encoding.ASCII.GetString(buff, 0, totalRead);
} while (totalRead == buff.Length);
}
}
class MyTlsClient : DefaultTlsClient
{
public override TlsAuthentication GetAuthentication()
{
return new MyTlsAuthentication();
}
}
class MyTlsAuthentication : TlsAuthentication
{
public TlsCredentials GetClientCredentials(CertificateRequest certificateRequest) { return null; }
public void NotifyServerCertificate(Certificate serverCertificate) { }
}
What I've already done :
Using WireShark to decrypt the ssl stream and inspect the request send => I've never succeeded to decrypt ssl stream
Using fiddler to decrypt the https stream => No detection by fiddler so I suspect something might be badly encrypted
Any ideas ?
Thanks to PeterDettman who gave me the solution :
I must not use the sr.NextBytes(instructions), so the code becomes :
using (var client = new TcpClient("serverName", 443))
{
var sr = new SecureRandom();
var cl = new MyTlsClient();
var protocol = new TlsClientProtocol(client.GetStream(), sr);
protocol.Connect(new MyTlsClient());
using (var stream = protocol.Stream)
{
var hdr = new StringBuilder();
hdr.AppendLine("GET /Url/WebService.asmx?wsdl HTTP/1.1");
hdr.AppendLine("Host: serverName");
hdr.AppendLine("Content-Type: text/xml; charset=utf-8");
hdr.AppendLine("Connection: close");
hdr.AppendLine();
var dataToSend = Encoding.ASCII.GetBytes(hdr.ToString());
stream.Write(dataToSend, 0, dataToSend.Length);
int totalRead = 0;
string response = "";
byte[] buff = new byte[1000];
do
{
totalRead = stream.Read(buff, 0, buff.Length);
response += Encoding.ASCII.GetString(buff, 0, totalRead);
} while (totalRead == buff.Length);
}
}

Writing a binary response (stream) directly to MIME in a Notes document

As I'm playing around with the Watson API I am using the Text2Speech service to get an audio stream (file) from the service. I already get the file with the code but my MIME doesn't contain anything later. I save the document after I call this method below. Any best pratices for streaming a byte content directly to a MIME would be appreciated.
public void getSpeechFromText(AveedoContext aveedoContext, Document doc, String fieldName, String text, String voiceName) {
try {
Session session = aveedoContext.getXspHelper().getSession();
session.setConvertMIME(false);
TextToSpeech service = new TextToSpeech();
String username = watsonSettings.getTextToSpeechUsername();
String password = watsonSettings.getTextToSpeechPassword();
if (username.isEmpty() || password.isEmpty()) {
throw new AveedoException("No credentials provided for service");
}
service.setUsernameAndPassword(username, password);
MIMEEntity mime = doc.getMIMEEntity(fieldName);
if (mime == null) {
mime = doc.createMIMEEntity(fieldName);
}
// local proxy?
if (!Util.isEmpty(customEndpoint)) {
// service.setEndPoint(customEndpoint + "/speech/");
}
Voice voice = Voice.getByName(voiceName);
AudioFormat audio = AudioFormat.WAV;
System.out.println("Fieldname: " + fieldName + "SPEECH: " + text + ", Voice: " + voice.getName() + ", Format: "
+ audio.toString());
InputStream stream = service.synthesize(text, voice, audio).execute();
InputStream in = WaveUtils.reWriteWaveHeader(stream);
Stream out = session.createStream();
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer);
}
mime.setContentFromBytes(out, "audio/wav", MIMEEntity.ENC_IDENTITY_BINARY);
out.close();
session.setConvertMIME(true);
in.close();
stream.close();
} catch (Throwable e) {
aveedoLogger.error("Error calling Watson service (text to speech)", e);
e.printStackTrace();
}
}
I believe that you need to create a child MIME entity. I use the following code in one of my apps to attach an image:
boolean convertMime = JSFUtil.getSessionAsSigner().isConvertMime();
if (convertMime) {
JSFUtil.getSessionAsSigner().setConvertMime(false);
}
final MIMEEntity body = doc.createMIMEEntity(getAttachmentFieldName());
// Add binary attachment
final MIMEEntity attachmentChild = body.createChildEntity();
final MIMEHeader bodyHeader = attachmentChild.createHeader("Content-Disposition");
bodyHeader.setHeaderVal("attachment; filename=" + incident.getPhoto().getName());
Stream imgStream = getPhoto(doc, incident.getPhoto());
attachmentChild.setContentFromBytes(imgStream, incident.getPhoto().getType(), MIMEEntity.ENC_IDENTITY_BINARY);
imgStream.close();
imgStream.recycle();
imgStream = null;
if (convertMime) {
JSFUtil.getSessionAsSigner().setConvertMime(true);
}

Azure server not letting me use a NuGet package

I have a website hosted by Azure that includes a Web API which I'm using to develop an android app. I'm trying to upload a media file to the server where it's encoded by a media encoder and saved to a path. The encoder library is called "Media Toolkit" which I found here : https://www.nuget.org/packages/MediaToolkit/1.0.0.3
My server side code looks like this:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/video"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/video");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
try
{
File.WriteAllBytes(tempFilePath, model.data);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname + ".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname + ".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname + "_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname + "_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
When the debugger hits the line using (var engine = new Engine()) I get 500 internal server error thrown. I don't get this error testing it on the iis server. Since it works fine on my local server and not on the azure hosted server, I figured it had to do with the Azure service rather than an error in my code. If so is the case then how would I be able to get around this issue? I don't want to use azure blob storage as it would require a lot of changes to my code. Does anyone have any idea what might be the issue.
Any helpful suggestions are appreciated.
Server.MapPath works differently on Azure WebApps - change to:
string pathToFiles = HttpContext.Current.Server.MapPath("~//video");
Also, see this SO post for another approach.

Convertapi Word2PDF in Java

I'm having problems reading the response from the server. If I use the StoreFile parameter and access via URL the PDF looks great, but serving it up through my own server always renders the pages blank. Possibly an encoding issue?
def convertPdf(document) {
File f = new File(document)
RestBuilder rest = new RestBuilder()
def resp = rest.post("https://do.convertapi.com/Word2Pdf") {
contentType "multipart/form-data"
ApiKey = "CONFIDENTIAL"
file = f
}
InputStream istream = new ByteArrayInputStream(resp.getBody().getBytes());
File file = new File("123123.pdf");
FileOutputStream ostream = new FileOutputStream(file);
byte[] b = new byte[1024];
int num = 0;
while ((num = istream.read(b)) != -1) {
ostream.write(b, 0, num);
}
istream.close();
ostream.flush();
ostream.close();
}
Fixed by using the method on "mashape" and using their Unirest library.
def downloadPdf() {
HttpResponse<InputStream> response = Unirest.post("https://do.convertapi.com/Word2Pdf")
.field("ApiKey", "CONFIDENTIAL")
.field("File", new File(params.document))
.field("OutputFormat", "pdf")
.field("Timeout", 300)
.field("OutputFileName", params.fileName)
.asBinary();
render(file: response.getBody(), contentType: "application/octet-stream", fileName: params.fileName+".pdf")
}

POI not sending xls file as attachment , sending as string

one of my junior code is not sending excel file as attachment . It is sending file like
------=_Part_0_2066339629.1374147892060
Content-Type: text/plain; name="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"
UEsDBBQACAAIANqJ8kIAAAAAAAAAAAAAAAARAAAAZG9jUHJvcHMvY29yZS54bWytkV1LwzAUhu/7
K0Lu2yTr1BHaDlEGguLADsW7kB7bYvNBEu3892bdrCheennyPu/D4aRY79WA3sH53ugSs4xiBFqa
ptdtiXf1Jl3hdZUkhTQOts5YcKEHj2JL+xJ3IVhOiJcdKOGzGOuYvBinRIija4kV8lW0QBaUnhMF
QTQiCHKwpXbW4aOPS/vvykbOSvvmhknQSAIDKNDBE5Yx8s0GcMr/WZiSmdz7fqbGcczGfOLiRow8
3d0+TMunvfZBaAm4ShAqTnYuHYgADYoOHj4slPgrecyvrusNrhaU5Sm9SNmqZowvl/yMPhfkV//k
function is following
public void sendSeviceabilityMail(List<OctpinSaveBean> datalist)
throws MessagingException {
Session session = null;
Map<String, String> utilsMap = ApplicationBean.utilsProperties;
if (utilsMap == null || utilsMap.size() == 0)
utilsMap = ApplicationBean.getUtilsPropertyFileValues();
smtpHost = utilsMap.get("SMTPHost");
to = utilsMap.get("To");
try {
if (smtpHost != null && to != null) {
Date date = new Date();
XSSFWorkbook updateDataBook =
updatedServiceabilityExcel(datalist);
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("To", to);
session = Session.getInstance(props, null);
String str = "strstr";
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(str, "text/html");
BodyPart messageBodyPart = new MimeBodyPart();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] bytes = baos.toByteArray();
DataSource ds = new ByteArrayDataSource(bytes,
"application/vnd.ms-excel");
DataHandler dh = new DataHandler(ds);
messageBodyPart.setDataHandler(dh);
String fileName = "Service_Change_Alert_" + date+".xlsx";
messageBodyPart.setFileName(fileName);
messageBodyPart.setHeader("Content-disposition", "attachment;
filename=\"" + fileName + "\"");
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart);
if (to != null && to.length() > 0) {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("tech_noida
<tech_noida#xyz.com>"));
String[] toArray = to.split(",");
InternetAddress[] address = new
InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
address[i] = new InternetAddress(toArray[i]);
}
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Updated Serviceability Alert!!!");
msg.setContent(multipart);
msg.setSentDate(date);
try {
Transport.send(msg);
logger.info("Mail has been sent about the updated serviceability alert to :" + to);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is not related to POI, but with JavaMail (plus the way different email clients handles the specs and malformed emails). Try this:
Multipart multipart = new MimeMultipart();
MimeBodyPart html = new MimeBodyPart();
// Use actual html not "strstr"
html.setContent("<html><body><h1>Hi</h1></body></html>", "text/html");
multipart.addBodyPart(html);
// ...
// Joop Eggen suggestion to avoid spaces in the file name
String fileName = "Service_Change_Alert_"
+ new SimpleDateFormat("yyyy-MM-dd_HH:mm").format(date) + ".xlsx";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] poiBytes = baos.toByteArray();
// Can be followed by the DataSource / DataHandler stuff if you really need it
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(filename);
attachment.setContent(poiBytes, "application/vnd.ms-excel");
//attachment.setDataHandler(dh);
attachment.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(attachment);
Update:
Also don't forget to call saveChanges to update the headers before sending the message.
msg.saveChanges();
See this answer for further details.

Resources