I'm trying binding image from ASP.NET Web Api service there i have contorller
public class ImageController : ApiController
{
public HttpResponseMessage GetImage()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(new FileStream("FileAddress", FileMode.Open));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
}
client side is Windows 8 universal app there are next code
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri datauri = new Uri("http://localhost:63606/Api/Image");
var client = new HttpClient();
var datafil = await client.GetAsync(datauri);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, datauri);
HttpResponseMessage response = await client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
}
I don't know what to do , I couldn't get image for example in BitmapImage file.
inYou can do the following
public class ImageController : ApiController
{
public HttpResponseMessage GetImage()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(new FileStream("FileAddress", FileMode.Open));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
}
and in the WinRt app write following code
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri datauri = new Uri("Api Uri");
BitmapImage image= new BitmapImage(datauri);
// if you want show result in XAML Controls
Image1.Sourse=image;
}
in XAML
<Image x:Name="Image1" HorizontalAlignment="Left" Height="292" Margin="48,413,0,0" VerticalAlignment="Top" Width="310"/>
Second way if you want get many photo is that you can create new folder in API folder and named it for example PhotoRepository add photo in this folder and get photo via it URI
private void Button_Click(object sender, RoutedEventArgs e)
{
Uri datauri = new Uri("http://localhost:63606/PhotoReposytory/"photo name".jpg");
//jpg or other format
BitmapImage foto = new BitmapImage(datauri);
Image1.Source = foto;
}
Related
I'm trying to log API request payload and response data to Azure Application Insight. Using trace I can able to log. but I want to know what is the best way to log request and response data to application insight. Because data is huge, no.of API calls will be more. I can't just trace hundreds of thousands of request and response data using tracing. I tried some of the blogs like using ITelemetryInitializer/ httpcontext.feature,get, but no luck.
I want to log from c# .Net framework, Web API, not .NET Core.
Sample code which I tried.
public class AzureRequestResponseInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
var requestTelemetry = telemetry as RequestTelemetry;
if (requestTelemetry != null && (HttpContext.Current.Request.HttpMethod == HttpMethod.Post.ToString() || HttpContext.Current.Request.HttpMethod == HttpMethod.Get.ToString()))
{
using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
string requestBody = reader.ReadToEnd();
requestTelemetry.Properties.Add("body", requestBody);
}
}
You can achieve it by implementing IHttpModule that using Application Insight's TelemtryClient, see the following code:
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Contoso.Services.Logging.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Contoso.Services.Logging.Modules
{
public class CaptureTrafficModule : IHttpModule
{
public TelemetryClient Telemetry { get; set; }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
context.EndRequest += new EventHandler(context_EndRequest);
Telemetry = new TelemetryClient();
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
HttpResponse response = HttpContext.Current.Response;
OutputFilterStream filter = new OutputFilterStream(response.Filter);
response.Filter = filter;
app.Context.Items["Filter"] = filter;
StringBuilder request = new StringBuilder();
// Write All The Headers too :
//foreach (string key in app.Request.Headers.Keys)
//{
// request.Append(key);
// request.Append(": ");
// request.Append(app.Request.Headers[key]);
// request.Append("\n");
//}
//request.Append("\n");
byte[] bytes = app.Request.BinaryRead(app.Request.ContentLength);
if (bytes.Count() > 0)
request.Append(Encoding.ASCII.GetString(bytes));
app.Request.InputStream.Position = 0;
string operationName = $"{app.Request.HttpMethod} {app.Request.FilePath}";
string activityId = System.Diagnostics.Activity.Current.RootId;
app.Context.Items["OperationName"] = operationName;
app.Context.Items["ActivityId"] = activityId;
using (var logRequest = Telemetry.StartOperation<RequestTelemetry>(operationName, System.Diagnostics.Activity.Current.RootId, System.Diagnostics.Activity.Current.RootId))
{
try
{
//logRequest.Telemetry.Id = $"10-{activityId}";
logRequest.Telemetry.Url = app.Request.Url;
logRequest.Telemetry.Properties["RequestBody"] = request.ToString();
}
catch (Exception ex)
{
logRequest.Telemetry.Success = false;
Telemetry.TrackException(ex);
//throw;
}
}
}
void context_EndRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
OutputFilterStream filter = null;
string operationName = "", activityId = Guid.Empty.ToString(), responseStr = "NONE";
if (app.Context.Items.Contains("OperationName"))
operationName = app.Context.Items["OperationName"].ToString();
if (app.Context.Items.Contains("ActivityId"))
activityId = app.Context.Items["ActivityId"].ToString();
if (app.Context.Items.Contains("Filter"))
{
filter = (OutputFilterStream)app.Context.Items["Filter"];
responseStr = filter.ReadStream();
}
using (var logResponse = Telemetry.StartOperation<RequestTelemetry>(operationName, activityId, activityId))
{
try
{
//logResponse.Telemetry.Id = $"20-{activityId}";
logResponse.Telemetry.Url = app.Request.Url;
logResponse.Telemetry.Properties["ResponseBody"] = responseStr.ToString();
}
catch (Exception ex)
{
logResponse.Telemetry.Success = false;
Telemetry.TrackException(ex);
//throw;
}
}
}
public void Dispose()
{
//Does nothing
}
}
}
This question is answered in https://thirum.wordpress.com/2019/08/19/logging-the-http-response-body-in-application-insights/
Please take a look.
I am new to xamarin forms. I implement a simple program where the image is capture from the camera and convert into base64 string and send it to the server like below.
private async void AddNewPhoto(object sender, EventArgs e)
{
MemoryStream memoryStream = new MemoryStream();
img.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.GetStream().CopyTo(memoryStream);
return stream;
});
paths.Enqueue(filePath);
imgPaths.Add(file);
val.Add(img.Source);
// Set StackLayout in XAML to the class field
parent = headerStack1;
parent.Children.Add(img);
}
async void btnSubmitClicked(object sender, EventArgs args)
{
if (paths.Count > 0)
{
string URL1 = "";
string basicDomain1 = AppConstant.ComplaintsUploadImageURL + PhoneNo + "~secretcode-" +
secretCode;
MultipartFormDataContent form1 = new MultipartFormDataContent();
DependencyService.Get<IHudService>().ShowHud("Loading");
List<string> pathItems = new List<string>();
for each (MediaFile ph in imgPaths)
{
var fileName = filePath.Split('\\').LastOrDefault().Split('/').LastOrDefault();
var file = ph;
var upfilebytes = File.ReadAllBytes(file.Path);
var base64 = Convert.ToBase64String(upfilebytes);
var content = new StringContent(base64);
form1.Add(content, "image_64string");
Dictionary<string, string> UploadJson = new Dictionary<string, string>();
UploadJson.Add("image_txt", imgText);
form1.Add(new StringContent(UploadJson["image_txt"]), "image_txt");
form1.Add(new StringContent("jpg"), "image_extension");
var response_ = await this.apiService.PostImageRequest(form1, URL1, basicDomain1);
if (!response_.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert("Error", response_.Message, "Network Problem!!");
return;
}
}
}
}
But it shows the error "Can not access the closed stream." How to fix this error?
I am trying to make a simple xamarin.forms app for picking an image from the phone gallery and uploading i to the azure storage service.
This is what I have done, but unfortunately I got the error message
"{Microsoft.WindowsAzure.Storage.StorageException: Server failed to authenticate the request."
The pick image from galley code:
private MediaFile mediaFile;
public ImageUpload ()
{
InitializeComponent ();
}
private async void Button_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if(CrossMedia.Current.IsPickPhotoSupported==false)
{
await DisplayAlert("No Pick", "No Available", "ok");
return;
}
this.mediaFile = await CrossMedia.Current.PickPhotoAsync();
if (this.mediaFile == null)
return;
//Show The path in the Xaml
LocalImagPath.Text = this.mediaFile.Path;
//Show the image in the Xaml
MyImageFile.Source = ImageSource.FromStream(this.mediaFile.GetStream);
}//end btnClikcked
private async void uploadPhoto_Clicked(object sender, EventArgs e)
{
try
{
var imageName = await ImageManager.UploadImage(this.mediaFile);
}
catch(Exception ex)
{
ex.StackTrace.ToString();
}
}//end uploadPhoto_Clicked
This is the ImageManger Class:
class ImageManager
{
private static Random random = new Random();
// Uploads a new image to a blob container.
public static async Task<string> UploadImage(MediaFile image)
{
CloudBlobContainer container = GetContainer();
// Creates the container if it does not exist
//await container.CreateIfNotExistsAsync();
// Uses a random name for the new images
var name = Guid.NewGuid().ToString();
// Uploads the image the blob storage
CloudBlockBlob imageBlob = container.GetBlockBlobReference(name);
imageBlob.Properties.ContentType = "image/jpeg";
await imageBlob.UploadFromFileAsync(image.Path);
return name;
}
// Gets a reference to the container for storing the images
private static CloudBlobContainer GetContainer()
{
// Parses the connection string for the WindowS Azure Storage Account
CloudStorageAccount account = CloudStorageAccount.Parse(Configuration.StorageConnectionString);
CloudBlobClient client = account.CreateCloudBlobClient();
// Gets a reference to the images container
CloudBlobContainer container = client.GetContainerReference("bepartphoto");
//Set The Permissions
BlobContainerPermissions blopPerm = new BlobContainerPermissions();
blopPerm.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissionsAsync(blopPerm);
return container;
}//end GetContainer
}//end class
My Phonegap application can receive notifications from pushwoosh panel. I want to integrate it in my DOT NET Application with help of remote api.
You can find example at http://docs.pushwoosh.com/docs/createmessage
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string pwAuth = "YOUR_AUTH_TOKEN";
string pwApplication = "PW_APPLICATION_CODE";
JObject json = new JObject(
new JProperty("application", pwApplication),
new JProperty("auth", pwAuth),
new JProperty("notifications",
new JArray(
new JObject(
new JProperty("send_date", "now"),
new JProperty("content", "test"),
new JProperty("wp_type", "Toast"),
new JProperty("wp_count", 3),
new JProperty("data",
new JObject(
new JProperty("custom", "json data"))),
new JProperty("link", "http://pushwoosh.com/"),
new JProperty("conditions",
new JArray(
(object)new JArray("Color", "EQ", "black")))))));
PWCall("createMessage", json);
}
private void PWCall(string action, JObject data)
{
Uri url = new Uri("https://cp.pushwoosh.com/json/1.3/" + action);
JObject json = new JObject(new JProperty("request", data));
DoPostRequest(url, json);
}
private void DoPostRequest(Uri url, JObject data)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.ContentType = "text/json";
req.Method = "POST";
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(data.ToString());
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
throw new Exception(string.Format("Problem with {0}, {1}", url, exc.Message));
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Page.Response.Write(responseText);
}
}
}
}
I am trying to run the following HTTP POST API Call using ASP.NET on Visual studio 2013. I created a new web application project as mentioned here
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateNewAPICall("test api abc");
}
private object CreateNewAPICall(string apiDesc)
{
object result = null;
var accessKey = "myaccesskey";
var secretKey = "mysecretkey";
var uRLapiList = "http://myurl.com";
byte[] bytes = Encoding.UTF8.GetBytes("apiListDesc=" + apiDesc);
var method = "POST";
var timeString = DateTime.UtcNow.GetDateTimeFormats()[104];
var signature = GetSignature(secretKey, method, timeString);
var authorization = accessKey + ":" + signature;
HttpWebRequest request = CreateWebRequest(uRLapiList, "POST", bytes.Length, timeString, authorization);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
var responseReader = new StreamReader(request.GetResponse().GetResponseStream());
// Return List api Data
result = responseReader.ReadToEnd();
}
}
return result;
}
private HttpWebRequest CreateWebRequest(string endPoint, string method, Int32 contentLength, string timeString, string authorization)
{
// Some code here
}
private string GetSignature(string secretKey, string method, string timeString)
{
// Some code here
}
private byte[] HMAC_SHA1(string signKey, string signMessage)
{
// Some code here
}
private string CreateSignature(string stringIn, string scretKey)
{
// Some code here
}
}
Right now, I am confused as to where to put this file in the "Solution Explorer" in order to
run the file and get the output on my browser?
Right now I have this code inside "Models-->Class1.cs" directory as shown in the image below:
So, when I press F-5 key, I am getting directed to the home page of the ASP.NET with the URL http://localhost:4439/
Do I need to make any changes here?