Odata naming file return error message of the - asp.net

I have this custom Odata function to download pdf from download pdf database. I have some issues
1.with Pdf name does not name "reportname.pdf" it is named response.pdf as
2.return error message of reportBinary is null
[HttpGet]
[ODataRoute("GetDownloadReport(downloadId={downloadId})")]
public HttpResponseMessage GetDownloadReport(Guid downloadId)
var received = DateTime.UtcNow;
byte[] reportBinary = null;
string queryString = "SELECT report FROM downloads WHERE id = #downloadId ";
bool success = false;
using (SqlConnection conn = new SqlConnection(connectionString))
{
//get the binary from database
}
HttpResponseMessage response = null;
try
{
if (reportBinary == null)
return Request.CreateResponse(HttpStatusCode.Gone);
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(reportBinary);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = "PORTName.pdf"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
}

try to set filename manually:
String headerInfo = "attachment; filename=" + System.Web.HttpUtility.UrlPathEncode("PORTName.pdf");
response.Content.Headers.Add("Content-Disposition", headerInfo);
I'm not sure what do you want to do about error message, but if you mean setting string content, just set it ;)
response = Request.CreateResponse(HttpStatusCode.Gone);
response.Content = new StringContent(...);
return response;
Consider using NotFound instead of Gone status code (Gone has very specific meaning).

Related

How to read application/pdf type from web api and display the response in browser in asp.net c#?

I have a Web API which returns HttpResponseMessage of type application/pdf using HttpPost method. I want to display the file which is returning from the API in asp.net webforms but I am unable to do it even though I tried to return response directly. Can anyone help me. P.S:-When I pass parameters in body using Postman Post I am able to generate PDF.
Web API Code:-
public HttpResponseMessage o([FromBody] CPRSsubmit customers)
{
string path = "~/PayBill/" + customers.value + "/";
string sail_pl_no;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
using (OracleConnection con = new OracleConnection(ConnectionStr.Con("oracle")))
{
using (OracleCommand cmd = new OracleCommand(query, con))
{
cmd.Connection = con;
con.Open();
using (OracleDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
while (sdr.Read())
{
sail_pl_no = Convert.ToString(sdr[0]).Trim();
path += sail_pl_no;
}
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
}
con.Close();
}
}
path += "_E_" + customers.value + ".pdf";
string filePath = HttpContext.Current.Server.MapPath(path);
if (!File.Exists(filePath))
{
//Throw 404 (Not Found) exception if File not found.
response.StatusCode = HttpStatusCode.NotFound;
response.ReasonPhrase = string.Format("File not found");
throw new HttpResponseException(response);
}
byte[] bytes = File.ReadAllBytes(filePath);
response.Content = new ByteArrayContent(bytes);
response.Content.Headers.ContentLength = bytes.LongLength;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
response.Content.Headers.ContentDisposition.FileName = customers.value + ".pdf";
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(customers.value + ".pdf"));
return response;
}
Asp.net webform code:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
Model.CPRSPost cpr = new Model.CPRSPost();
cpr.pl_no = Convert.ToInt32(Session["LoginId"]);
cpr.value = ddlMonth.SelectedValue;
var url = "CPRSPayBill/O";
HttpResponseMessage response = client.PostAsJsonAsync(url,cpr).Result;
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
}
}

You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse

I tried to upload file on oracle cloud infrastructure iaas but getting the error.I am not sure whether the file that I attached in the body is in
correct format or not. ApI signing is correct and I am doubt only about
whether the code that I wrote is upto mark or not. The code snippet is mentioned below.
The code Snippet :
FileInfo f = new FileInfo(FileUpload1.FileName);
byte[] filebyte =FileUpload1.FileBytes;
var postdata = Encoding.UTF8.GetBytes(filebyte.ToString());
Console.Write(postdata.Length);
var tenancyId = ConfigurationManager.AppSettings["BMCTenancyId"];
var userId = ConfigurationManager.AppSettings["BMCUserId"];
var fingerprint = ConfigurationManager.AppSettings["BMCFingerprint"];
var privateKeyPath = ConfigurationManager.AppSettings["BMCPrivateKeyPath"];
var privateKeyPassphrase = ConfigurationManager.AppSettings["BMCPrivateKeyPassphrase"];
var signer = new RequestSigner(tenancyId, userId, fingerprint, privateKeyPath, privateKeyPassphrase);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
request.SendChunked = true;
request.ContentType = "text/plain";
request.ContentLength =postdata.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(postdata, 0, postdata.Length);
stream.Close();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
request.Headers["x-content-sha256"] = Convert.ToBase64String(SHA256.Create().ComputeHash(postdata));
signer.SignRequest(request);
Console.WriteLine($"Authorization header: {request.Headers["authorization"]}");
ExecuteRequest(request);
Console.WriteLine("The value of 'ContentLength' property after sending the data is {0}", request.ContentLength);
}
private static void ExecuteRequest(HttpWebRequest request)
{
try
{
var webResponse = (HttpWebResponse)request.GetResponse();
var response = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
Console.WriteLine($"Response: {response}");
}
catch (WebException e)
{
Console.WriteLine($"Exception occurred: {e.Message}");
Console.WriteLine($"Response: {new StreamReader(e.Response.GetResponseStream()).ReadToEnd()}");
}
}
For one thing, you'll need to update the URL to the following format:
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/n/{namespaceName}/b/{bucketName}/o/{objectName}");
Docs: https://docs.cloud.oracle.com/iaas/api/#/en/objectstorage/20160918/Object/PutObject
Also, can you please edit the question to include the complete error you are receiving, that will help with debugging.

HTTP POST receiving more than one HTTP Response

I have an http POST being actioned via a .NET System.Net.WebRequest as follows:
...
XXXUtilities.Log.WriteLog(string.Format("XXXHTTPPost PostToUri has uri={0}, body={1}", uri, messageBodyAsString));
System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(messageBodyAsString);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
try
{
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
string rs = sr.ReadToEnd().Trim();
sr.Close();
resp.Close();
XXXUtilities.Log.WriteLog(string.Format("XXXHTTPPost PostToUri has string response = {0}", rs));
MongoDB.Bson.BsonDocument doc2 = new BsonDocument();
doc2.Add("Response", rs);
return doc2;
}
}
catch (System.Net.WebException e)
{...
This all works fine most of the time. However, looking at the log files that this creates I spotted something strange. The suspect log entries look like this:
18:59:17.0608 HPSHTTPPost PostToUri has uri=https://salesforce.ringlead.com/cgi-bin/2848/3/dedup.pl, body=LastName=Doe&FirstName=Jon
18:59:17.5608 HPSHTTPPost PostToUri has string response = Success
18:59:18.0295 HPSHTTPPost PostToUri has string response = Success
It seems that the Http Response is being received twice. Is this even technically possible? i.e. is it possible for an Http POST to receive two Responses, one after the other? If so, is my code below then liable to be called twice, thus resulting in the observed log file entries? Many thanks.
Edit:
In response to the comment that the logging code may be broken, here is the logging code:
public class Log
{
public static void WriteLog(string commandText)
{
string clientDBName = "test";
string username = "test";
try
{
string filePath = "c:\\Data\\XXXLogs\\" + clientDBName + "logs\\";
string filename = System.DateTime.Now.ToString("yyyyMMdd_") + username + ".log";
DirectoryInfo dir = new DirectoryInfo(filePath);
if (!dir.Exists)
{
dir.Create();
}
System.IO.FileStream stream = new System.IO.FileStream(
filePath + filename
, System.IO.FileMode.Append); // Will create if not already exists
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(); // Writes a line terminator, thus separating entries by 1 blank line
writer.WriteLine(System.DateTime.Now.ToString("HH:mm:ss.ffff") + " " + commandText);
writer.Flush();
stream.Close();
}
catch { }
}
}

Mendeley Pagination

There are currently 1205 resources (citations) in the SciTS Mendeley group. However, no matter how we call the “getDocuments” method of the API, we only get the first 1000 resources. Is there a specific parameter we need to pass to get the full list of resources? Or is there a way to make a subsequent call that gets data pages not returned by the first call?
string grantType = "client_credentials";
string applicationID = "id";
string clientsecret = "XXXXXXX";
string redirecturi = "*******";
string url = "https://api-oauth2.mendeley.com/oauth/token";
string view = "all";
string group_id = "f7c0e437-f68b-34df-83c7-2877147ba8f9";
HttpWebResponse response = null;
try
{
// Create the data to send
StringBuilder data = new StringBuilder();
data.Append("client_id=" + Uri.EscapeDataString(applicationID));
data.Append("&client_secret=" + Uri.EscapeDataString(clientsecret));
data.Append("&redirect_uri=" + Uri.EscapeDataString(redirecturi));
data.Append("&grant_type=" + Uri.EscapeDataString(grantType));
data.Append("&response_type=" + Uri.EscapeDataString("code"));
data.Append("&scope=" + Uri.EscapeDataString("all"));
byte[] byteArray = Encoding.UTF8.GetBytes(data.ToString());
// Setup the Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
// Write data
Stream postStream = request.GetRequestStream();
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Send Request & Get Response
response = (HttpWebResponse)request.GetResponse();
string accessToken;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the Response Stream
string json = reader.ReadLine();
Console.WriteLine(json);
// Retrieve and Return the Access Token
JavaScriptSerializer ser = new JavaScriptSerializer();
Dictionary<string, object> x = (Dictionary<string, object>)ser.DeserializeObject(json);
accessToken = x["access_token"].ToString();
}
// Console.WriteLine("Access TOken"+ accessToken);
var apiUrl = "https://api-oauth2.mendeley.com/oapi/documents/groups/3556001/docs/?details=true&items=1250";
try
{
request = (HttpWebRequest)WebRequest.Create(apiUrl);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.Host = "api-oauth2.mendeley.com";
response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the Response Stream
string json = reader.ReadLine();
Console.WriteLine(json);
//need this to import documents
}
}
catch (WebException ex1)
{
Console.WriteLine("Access TOken exception" + ex1.Message);
}
}
catch (WebException e)
{
if (e.Response != null)
{
using (HttpWebResponse err = (HttpWebResponse)e.Response)
{
Console.WriteLine("The server returned '{0}' with the status code '{1} ({2:d})'.",
err.StatusDescription, err.StatusCode, err.StatusCode);
}
}
}
The default number of items returned is limited to 1000 per page. For a paginated response you should get some additional fields in the response; notably 'items_per_page','total_pages','total_results'.
I suspect you have will two pages and to get the next result you need to append 'page=1'.

Problems sending and receiving JSON between ASP.net web service and ASP.Net web client

You would think with all the posts here that this would be easy to figure out. :| Well here is what should be a simple example. NOTE The web service is VB and the client is c#. The wb service sends and receives fine when called from JQuery. From .NET There is a problem,
If the service asks for a parameter as show below then the client's getresponse method gets error 500 Internal server error
The Web Service
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
Public Function Test(WebInfo As GetUserID) As Person
Dim Someone As New Person
Someone.Name = "Bob"
Someone.FavoriteColor = "Green"
Someone.ID = WebInfo.WebUserID.ToString()
Return Someone
End Function
The Web Client (set up to be send and receive JSON)
public Person Test(int UserID, string url) {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + "test.asmx/Test");
webRequest.Method = "POST";
webRequest.ContentType = "application/json; charset=utf-8";
StreamWriter sw = new StreamWriter(webRequest.GetRequestStream());
sw.Write("{'WebInfo':{'WebUserID':1}}"); // this works from JQuery
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
Person someone = (Person)jsonSerializer.ReadObject(responseStream);
return someone;
}
Has anyone out there done this successfully?
Thanks
Here is a method that makes calls to a JSON web service, allowing the developer to both send and receive complext data types. The object passed in can be any data type or class. The result is a JSON string, and or any error message the methods type is shown below
public class WebServiceCallReturn {
public string JSONResponse { get; set; }
public string SimpleResponse { get; set; }
public string Error { get; set; }
}
public WebServiceCallReturn WebServiceJSONCall(string uri, string requestType, object postData = null) {
WebServiceCallReturn result = new WebServiceCallReturn();
// create request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.Method = requestType;
webRequest.Accept = "application/json; charset=utf-8";
// add json data object to send
if (requestType == "POST") {
string json = "{ }";
if (postData != null) {
try { // the serializer is fairly robust when used this way
DataContractJsonSerializer ser = new DataContractJsonSerializer(postData.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, postData);
json = Encoding.UTF8.GetString(ms.ToArray());
} catch {
result.Error = "Error serializing post";
}
}
webRequest.ContentLength = json.Length;
StreamWriter sw;
try {
sw = new StreamWriter(webRequest.GetRequestStream());
} catch (Exception ex) {
// the remote name could not be resolved
result.Error = ex.Message;
return result;
}
sw.Write(json);
sw.Close();
}
// read response
HttpWebResponse webResponse;
try {
webResponse = (HttpWebResponse)webRequest.GetResponse();
} catch (Exception ex) {
// The remote server returned an error...
// (400) Bad Request
// (403) Access forbidden (check the application pool)
// (404) Not Found
// (405) Method not allowed
// (415) ...not the expected type
// (500) Internal Server Error (problem with IIS or unhandled error in web service)
result.Error = ex.Message;
return result;
}
Stream responseStream = webResponse.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
string resultString = sr.ReadToEnd();
sr.Close();
responseStream.Close();
result.JSONResponse = resultString;
return result;
}
This method could be used as follows
public SomeCustomDataClass Getsomeinformation(int userID) {
UserInfoClass postData = new UserInfoClass();
postData.WebUserID = userID;
SomeCustomDataClass result = new SomeCustomDataClass();
string uri = URL + "SomeServices.svc/GetSomething";
WebServiceCallReturn webReturn = WebServiceJSONCall(uri, "POST", postData);
if (webReturn.Error == null) {
//resultString = CleanJSON(resultString);
JavaScriptSerializer serializer = new JavaScriptSerializer();
try {
result = serializer.Deserialize<SomeCustomDataClass>(webReturn.JSONResponse);
} catch {
result.Error = "Error deserializing";
}
} else {
result.Error = webReturn.Error;
}
return result;
}
Hope that helps someone

Resources