download doc file in MVC - asp.net-web-api2

I have applicaiton which is the combination of MVC 4 + Web Api + SQL server.
I am trying to download the doc file to MVC but i have tried the below step.
I have Web API where i have written the below code. when i send the rowid it has the value stored in the DB as varbinary. file format can be any thing like .doc,pdf etc ... but however I am looking for the first doc or PDF file format.
When I call the Web api it will create the PDF file and download it , but the file is completely corrupted.
[ResponseType(typeof(MandateExceptionDO))]
[HttpGet]
[Route("api/DealingMandate/GetExceptionDoc/{rowId}")]
public HttpResponseMessage GetExceptionDoc(int rowId)
{
IDealingMandates repository = new DealingMandatesRepository();
List<MandateExceptionDO> mandateexceptiondoc =new List<MandateExceptionDO>();
mandateexceptiondoc = repository.GetExceptionDoc(rowId);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
//response.Content = new ByteArrayContent(mandateexceptiondoc[0].Content);
//response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
//byte[] fileBytes = System.IO.File.ReadAllBytes(mandateexceptiondoc[0].Content);
response.Content = new ByteArrayContent(mandateexceptiondoc[0].Content);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "testing.pdf";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
//return Ok(mandateexceptiondoc);
return response;
}

I am able to fix this issue on the web api i made the byte as string as show below
String doc = Convert.ToBase64String(customermandate.Content);
and for the MVC side i converted back to byte from the string
var doc = restClient.Execute(request);
var response = doc.Content.Substring(1, doc.Content.Length - 2).Replace(#"\/", "/");
byte[] docBytes = Convert.FromBase64String(response);
if (doc.Content != null && doc.Content.Length > 0 && !string.IsNullOrEmpty(doc.Content))
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
Response.BinaryWrite(docBytes);
Response.End();
}

Related

ASP WebAPI 2 _pdf HTTPResponseMessage_couldnt open

Used the below code to read a pdf file and return as response from WebAPI 2.
When I used a text file here and also changed the response FileName="new.txt", then it works fine. Running the WEBAPI in swagger, could download file in the response and the file opens too.
But if its a pdf file, the downloaded file couldnt be opened. Also tried zip and xl files....File is corrupted and couldnt be opened.
[HttpGet]
[Route("GetPDF")]
public IHttpActionResult GetABCPDF()
{
var bytes = System.IO.File.ReadAllBytes(bookPath_Pdf);
var dataStream = new MemoryStream(bytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(dataStream)
};
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "new.pdf"
};
httpResponseMessage.Content.Headers.ContentLength = dataStream.Length;
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
return responseMessageResult;
}

Attaching files to Azure DevOps work item

I am trying to attach files (screenshots) to an Azure DevOps work item via a C# desktop app. I have managed to attach files, but they're not valid image files, which leads me to believe that I'm doing something wrong in uploading them.
From the documentation DevOps Create Attachment below is the section on the Request body of the API call, which is rather vague.
From a GitHub discussion this answer seems to suggest that I just upload the binary content directly, which is what I'm doing.
My code is as follows
var img = File.ReadAllBytes(fname);
string query = #"/_apis/wit/attachments?fileName=" + fname + #"&api-version=6.0"
string response = AzureUtils.AttachFile(query, img, "POST", false, "application/octet-stream");
Is it correct that I literally pass in the byte array which is read from the file (variable img) as the body?
Why is it not a valid file when I look at it in DevOps?
The code for AttachFile is
public static string AttachFile(string query, byte[] data = null, string method = "GET",
bool dontUseBaseURL = false, string contentType = "application/json-patch+json")
{
try
{
HttpWebRequest request = WebRequest.Create(query) as HttpWebRequest;
request.ContentType = contentType;
request.Method = method;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", ["AzurePAT"]))));
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
request = null;
response = null;
return result;
}

Send Image to the API using image path that stored in local database

I am trying to send image to the API, I have multiple local storage image path which is stored in local
database sqlite and I have to upload these image on one click. in the
local database. replace _mediaFile = await CrossMedia.Current.TakePhotoAsync
with _mediaFile = Image_Path_From_Database
The datatobesync it contain multiple local storage image path from local dat
conn = await DependencyService.Get().GetConnection();
List datatobesync = new List();
datatobesync = (from c in conn.Table<CDCInfo>()
where c.SyncStatus == 0 && c.UserName == Settings.Username
select new CDCInfo
{
PhotoPath = c.PhotoPath,
}
I have a string image path but I am not sure about how
to use this
Using MediaPlugin for opening a gallery or camera. After selecting the
picture I set that picture to _mediafile and added to the content and send it to the API.
Detail Here
these lines of code gets image from the gallery or camra (using MediaPlugin) in a
mediaFile and send it to the API
private MediaFile _mediaFile;
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.
StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
AllowCropping = true,
PhotoSize = PhotoSize.Medium
});
var content = new MultipartFormDataContent();
content.Add(new StreamContent(_mediaFile.GetStream()),"\"Files\"", $"\"{_mediaFile.path}\"");
var httpClnt = new HttpClient();
result = await httpClnt.PostAsync(Urle, content);
How can I add image to the content using database path and send it to the API without using MediaPlugin.
I am trying to do something like
foreach (var item in datatobesync)
{
try
{
HttpClient client = new HttpClient();
MultipartFormDataContent content = new
MultipartFormDataContent();
content.Add(new
StreamContent("Here I want to user item.PhotoPath Image path from the database".GetStream()),"\"Files\"",
$"\"{item.PhotoPath}\"");
var httpClnt = new HttpClient();
result = await httpClnt.PostAsync(Urle, content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I dont know how to use image path at this line
content.Add(new StreamContent(How_to_User_ImagePath_Her.GetStream()),"\"Files\"",
$"\"{item.PhotoPath}\"");
How to get GetStram() of image path

HttpWebRequest does not retrieve the url I have set for

I am trying to download
"https://www.google.com/search?sclient=psy-ab&biw=1472&bih=740&espv=2&tbm=vid&btnG=Search&q=%25%25%25#q=iran&tbm=nws";
by the following code:
string url = "https://www.google.com/search?sclient=psy-ab&biw=1472&bih=740&espv=2&tbm=vid&btnG=Search&q=%25%25%25#q=iran&tbm=nws";
try
{
string htmlPage = "";
//http request preparing
CookieContainer CC = new CookieContainer();
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = 60000;
objRequest.Proxy = null;
objRequest.UseDefaultCredentials = true;
objRequest.KeepAlive = false; //THIS DOES THE TRICK
objRequest.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK
objRequest.CookieContainer = CC;
//http request sending
using (HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse())
{
using (Stream strm = objResponse.GetResponseStream())
{
using (StreamReader objStreamReader = new StreamReader(strm))
{
htmlPage = objStreamReader.ReadToEnd();
}
}
};
if (htmlPage.Contains("No results found for") || htmlPage.Contains("(without quotes):") || htmlPage.Contains("Make sure all words are spelled correctly."))
{
return dtResult;
}
else
{
Regex objEgEx = new Regex(#"[\r\n][ ]+\.[\r\n][ ]+");
htmlPage = objEgEx.Replace(htmlPage, string.Empty);
int startIndex = htmlPage.IndexOf("<div class =\"g\">");
if (startIndex == -1)
{ Console.Write("problem in parsing"); }
but HttpWebRequest download the first page of the google instead of the url I hd saved for it which is the address of the video search service of Google results' page.
what should I change so that it download the url I want?
You are downloading the page, not the query. Due that the search of google doesn't load a new page but updates a page. Maybe have a look into google search api

calling Amazon S3 from WCF service

I try to upload an image from my WCF service to Amazon S3 web server. I have the Amazon S3 code that is working in a web project and my image upload method that is uploading image in Uploded\test.jpg in WCF service. I am not sure how I can use Amazon S3 code working with WCF service. 1st I don't know how to put Amazon credential in the web confing when I add these line of code inside the it is not uploading:
<appSettings>
<add key="AWSAccessKey" value="myaccessKey"/>
<add key="AWSSecretKey" value="MySecretKey"/>
</appSettings>
and this is my method to upload to the WCF server I guess I have to add AWS code when I said //AWS here:
[WebInvoke(UriTemplate = "UploadImage", Method = "POST")]
Stream UploadImage(Stream request)
{
Stream requestTest = request;
StreamWriter sw = null;
string logpath = HttpContext.Current.Server.MapPath("Uploded\\logtest.txt");
logpath = logpath.Replace("SSGTrnService\\", "");
HttpMultipartParser parser = new HttpMultipartParser(request, "file");
string filePath = "";
string passed = parser._content;
string sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
sw = new StreamWriter(logpath);
sw.Flush();
if (parser.Success)
{
// Save the file somewhere
//File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
// Save the file
//SaveFile( mtp.Filename, mtp.ContentType, mtp.FileContents);
FileStream fileStream = null;
BinaryWriter writer = null;
try
{
filePath = HttpContext.Current.Server.MapPath("Uploded\\test.jpg"); // BuildFilePath(strFileName, true);
filePath = filePath.Replace("SSGTrnService\\", "");
fileStream = new FileStream(filePath, FileMode.Create);
fileStream.Write(parser.FileContents, 0, parser.FileContents.Length);
// return filePath;
}
catch (Exception ex)
{
return "Error: " + ex.Message;
}
finally
{
if (fileStream != null)
fileStream.Close();
if (writer != null)
writer.Close();
//AWS Code
}
}
//
// returning text for html DOM
//
string text = "Image uploaded: " + parser.Filename + " / " + parser.ContentType + filePath + passed;
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
MemoryStream ms = new MemoryStream(encoding.GetBytes(text));
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return ms;
}
Any Guide in calling Amazon S3 from WCF service would be great.
There is a amazon dll that you would need to reference (AWSSDK.dll) and then use the below lines of code:
var transferUtility = new TransferUtility(accessKey, secretKey);
var bucketName = "Files";
transferUtility.Upload(filePath, bucketName, Guid.NewGuid().ToString());
NOTE: Please make sure that the Amazon S3 bucket "Files" exists. Else you need to check if the bucket exists and then perform the upload method call. Hope that helps.