Store Image to table field returned by HTTP GET Response - axapta

I'm trying to get Image from Azure Storage Container by HTTP GET request.
I want to then save the image returned by the GET Response into Table field and then populate into SSRS report.
Need some inputs on how to handle the response to extract the image and then store it in table field.
Here's my incomplete code:
class Class1
{
public static void main(Args _args)
{
xml response = "";
System.Net.HttpWebRequest httpRequest = null;
System.Net.HttpWebResponse httpResponse = null;
CLRObject clro = null;
System.IO.Stream stream = null;
System.IO.StreamReader streamReader = null;
System.Byte[] bytes = null;
System.Text.Encoding encoding = null;
try
{
new InteropPermission(InteropKind::ClrInterop).assert();
httpRequest = System.Net.WebRequest::Create("https://storage.blob.core.windows.net/productimages/Products/10101001_000_001.jpg");
httpResponse = httpRequest.GetResponse();
stream = httpResponse.GetResponseStream();
streamReader = new System.IO.StreamReader(stream);
response = streamReader.ReadToEnd();
CodeAccessPermission::revertAssert();
}
catch(Exception::CLRError)
{
throw error(AifUtil::getClrErrorMessage());
}
}
}
Edit1:
Instead of troubleshooting the code I ended up following this, simply paste the URL in SSRS report image box, it fetches the image from the URL on its own.
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5dc6cf93-34cb-4e52-a95c-d478e143dce7/ssrs-fetching-image-from-url?forum=sqlreportingservices#:~:text=Generally%2C%20in%20SSRS%2C%20we%20are,%3EExternal%2D%3Eadd%20URL.&text=Hope%20this%20helps.&text=Please%20remember%20to%20click%20%22Mark,Unmark%20as%20Answer%22%20if%20not.

Related

How to pass array to php url from c#? [duplicate]

Is it possible to pass parameters with an HTTP get request? If so, how should I then do it? I have found an HTTP post requst (link). In that example the string postData is sent to a webserver. I would like to do the same using get instead. Google found this example on HTTP get here. However no parameters are sent to the web server.
My preferred way is this. It handles the escaping and parsing for you.
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
First WebClient is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
In a GET request, you pass parameters as part of the query string.
string url = "http://somesite.com?var=12345";
The WebRequest object seems like too much work for me. I prefer to use the WebClient control.
To use this function you just need to create two NameValueCollections holding your parameters and request headers.
Consider the following function:
private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
{
string ResponseText = null;
using (WebClient client = new WebClient())
{
try
{
if (RequestHeaders != null)
{
if (RequestHeaders.Count > 0)
{
foreach (string header in RequestHeaders.AllKeys)
client.Headers.Add(header, RequestHeaders[header]);
}
}
if (QueryStringParameters != null)
{
if (QueryStringParameters.Count > 0)
{
foreach (string parm in QueryStringParameters.AllKeys)
client.QueryString.Add(parm, QueryStringParameters[parm]);
}
}
byte[] ResponseBytes = client.DownloadData(URL);
ResponseText = Encoding.UTF8.GetString(ResponseBytes);
}
catch (WebException exception)
{
if (exception.Response != null)
{
var responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
Response.Write(reader.ReadToEnd());
}
}
}
}
}
return ResponseText;
}
Add your querystring parameters (if required) as a NameValueCollection like so.
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
Add your http headers (if required) as a NameValueCollection like so.
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
GET request with multiple params:
curl --request GET --url
http://localhost:8080/todos/?limit=10&offset=2 --header
'content-type:application/json'
You can also pass value directly via URL.
If you want to call method
public static void calling(string name){....}
then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya);
webrequest.Method = "GET";
webrequest.ContentType = "application/text";
Just make sure you are using ?Object = value in URL

How do I use response from an web api returning an image?

I have two web asp.net mvc based projects.
The first one has an image preview api, is implemented somewhat like this...
private async Task <HttpResponseMessage> GetImage(int id)
{
string filePath = "abstractedforsimplicity.png";
using(var file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
{
byte[] buff = new byte[file.Length];
await file.ReadAsync(buff, 0, (int) file.Length);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(buff)
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
}
this works, I am able to show a preview with the following url - domain/api/image/3
Now I am a different application where I want to again make use of the same preview. I do not want to expose this api directly, so will be making a proxy api which will be making the call internally.
public HttpResponseMessage GetImage(int id)
{
string tempalteUrl = string.Format("{0}/{1}", ConfigurationManager.AppSettings["rmgpubadmin:template-base-url"], id);
WebClient client = new WebClient();
byte[] bytes = client.DownloadData(tempalteUrl);
// not very sure what should i do here ??
return null;
}
I tried to converting the bytes to an object, but if fails with errors - System.Runtime.Serialization.SerializationException.
The input stream is not a valid binary format. The starting contents (in bytes) are: 89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49-48-44-52-00 ...
What should i be doing here?

Passing an image from a Wep Api service to another Web Api service

For security reasons, I am building two Web Api services. The first Web Api app will have access to an image generating service, and will act as a security proxy. The second Web Api app will call the first app from the internet and retrieve the image.
However, I can't seem to get to negotiate passage of the image correctly. My thought was to have the security proxy Web API to get the image, and then pass it as a byte array my other service which would allow a user to download the image. However, when my browser attempts to open the image, it is always corrupted.
Here is the security proxy getting the image, which I know is successful:
public byte[] Get(string invoice, string Customer)
{
object image;
try
{
image = _repo.GetImage(invoice, Customer);
}
catch (ApplicationException exc)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No Image with Invoice Number = {0}", invoice.ToString())),
ReasonPhrase = "Image Not Found"
};
throw new HttpResponseException(resp);
}
catch (Exception exc)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
return (byte[])image;
}
This returns an array with a length of 40133.
The calling Web API service looks like this:
public HttpResponseMessage Get(string invoice, string Customer)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
byte[] img = client.GetByteArrayAsync("http://localhost:1363/api/Image/" + invoice + "/" + Customer).Result;
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ByteArrayContent(img);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/tiff");
var disposition = new ContentDispositionHeaderValue("attachment");
disposition.FileName = "ImageDocument.tif";
response.Content.Headers.ContentDisposition = disposition;
return response;
}
However, the length of the img byte array is 53514.
When the browser tries to open the image, it tells me it is corrupt. If I open the TIFF in notepad, I get :
"SUkqAAgAAAASAP4ABAABAAAAAAAAAAABBAABAAAAsAYAAAEBBAABAAAAvgQAAAIBAwABAAAAAQAAAAMBAwABAAAABAAAAAYBAwABAAAAAAAAAAcBAwABAAAAAQAAABEBBAABAAAAAAMAABIBAwABAAAAAQAAABUBAwABAAAAAQAAABYBBAABAAAAvgQAABcBBAABAAAAxZkAABoBBQABAAAA+AIAABsBBQABAAAA8AIAACgBAwABAAAAAgAAADEBAgA4AAAAuAIAADIBAgAUAAAApAIAAOiAAwABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADIwMTI6MTA6MDMgMDc6Mjc6MTkAS29mYXggc3RhbmRhcmQgTXVsdGktUGFnZSBUSUZGIFN0b3JhZ2UgRmlsdGVyIHYzLjAzLjAwMADIAAAAAQAAAMgAAAABAAAALcMjAGC+cBQRwhOKcIuzqZDzrHoxF8k+VAOR2cAgjhC5lQEI+VYoiIiIiIiIiJXLAazgaZvMBqEcNI0BoJwaTMGsjgqGA1yOGaUA0Hg0igC5qZ6I1GSsNMuGqeBrI+bBoNYQrfNIiMREWdl4zVWRERkQzVECBpNcRyMCz6PhQgZwQGQLjpCIWwgxERGLLYAx//zLWLx4IeDnBnxSGFMRgIeZ4zcaR+KuPM4KeZ6MBTqKcj8YjAQ4IejDoQ4eE07WGnra3p9w07Xhw1s7NHu+0/v+/SQf6/9+cjwp0Z0Z8KeCm4p4IGQwhoz4cwCFBZN8u8s5duXeXTLva7pN6J56l45sf8u8u
SNIP*
Anyone know what I am doing wrong?
Thanks!
Chris
Solved
If anyone is interested in the calling code that leverages the solution identified, here it is:
public HttpResponseMessage Get(string invoice, string Customer)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/tiff"));
byte[] img = client.GetByteArrayAsync("http://localhost:1363/api/Image/" + invoice + "/" + Customer).Result;
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ByteArrayContent(img);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/tiff");
var disposition = new ContentDispositionHeaderValue("attachment");
disposition.FileName = "ImageDocument.tif";
response.Content.Headers.ContentDisposition = disposition;
return response;
}
With your above current return type (byte[]) of action, formatters of web api are probably handling them and hence you are seeing unexpected response.
can you try sending the image as a ByteArrayContent instead?(you need to have HttpResponseMessage as a return type here)
Example:
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(..your byte array here...);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
return response;

Retrieve XML from HTTP POST Request Payload

I have an ActiveX that POSTs to the server (HTTP Handler) with a payload of a certain XML document.
Is there a better way to retrieve the payload into XML than the below?
private static byte[] RequestPayload()
{
int bytesToRead = HttpContext.Current.Request.TotalBytes;
return (HttpContext.Current.Request.BinaryRead(bytesToRead));
}
using (var mem = new MemoryStream(RequestPayload()))
{
var docu = XDocument.Load(mem);
}
Once I have the "docu" I can query using LINQ to XML.
Thanks
Simply load the XML from the InputStream of the Request e.g.
XDocument doc;
using (Stream input = HttpContext.Current.Request.InputStream)
{
doc = XDocument.Load(input);
}
there is no need for a MemoryStream in my view.

ASP.net: Getting HTTPS data server-side?

I previously asked on StackOverflow how to parse XML downloaded programmatically by my ASP.net application. By this, I mean that the user visits https://www.example.com/page1.aspx. The code-behind for page1.aspx is supposed to somehow download and parse an xml file located at https://www.example.com/foo.xml.
I received good answers about how to parse the XML. However, I've been out of luck with being able to retrieve XML from my secure HTTPS server.
I am looking at a situation where https://www.example.com/foo.xml authenticates requests with a cookie. (third party system, not Forms Authentication). The answer I received to my question about how to download and parse XML suggested that I use the System.Net.WebClient class. I read that the WebClient class must be customized to work with cookies. Therefore, I wrote the following code:
public class WebClientWithCookies : WebClient
{
private CookieContainer m_container = new CookieContainer();
public CookieContainer CookieContainer
{
get { return m_container; }
set { m_container = value; }
}
public void addCookie(Cookie cookie)
{
m_container.Add(cookie);
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if ( request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
} // end class
However, when the request is received at https://www.example.com/foo.xml, there are no cookies in the request, and so it doesn't work.
How can I work around this problem?
Where are you creating the cookie? That seems to be a missing part from the code you are displaying. There is an "HttpCookie" class as part of the System.Web name space that may be useful.
Here's the code that I eventually wrote that solved the problem:
private XmlDocument getXmlData(string url)
{
System.Net.HttpWebRequest rq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.CookieContainer container = new System.Net.CookieContainer();
for (int i = 0; i < System.Web.HttpContext.Current.Request.Cookies.Count; i++)
{
System.Web.HttpCookie httpcookie = System.Web.HttpContext.Current.Request.Cookies[i];
string name = httpcookie.Name;
string value = httpcookie.Value;
string path = httpcookie.Path;
string domain = "my.domain";
System.Net.Cookie cookie = new System.Net.Cookie(name, value, path, domain);
container.Add(cookie);
}
rq.CookieContainer = container;
rq.Timeout = 10000;
rq.UserAgent = "Asset Tracker Server Side Code";
System.Net.HttpWebResponse rs = (System.Net.HttpWebResponse)rq.GetResponse();
System.Text.Encoding enc = System.Text.Encoding.GetEncoding(1252);
System.IO.StreamReader reader = new System.IO.StreamReader(rs.GetResponseStream());
System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
xml.Load(rs.GetResponseStream());
return xml;
}

Resources