getting directed to ASP.NET home page on browser - asp.net

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?

Related

Logging Request and response to Application Insight

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.

Created a Soap Webservice and calling it in asp.net uisng code and getting error of The remote name could not be resolved

I had developed one web service in SOAP format and trying to access service in asp.net using the below mentioned code.
public static void CallWebService()
{
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _url = "https://test.in/ModelDetail/Service.asmx";
var _action = "https://test.in/ModelDetail/GetWarrantyDetails";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
//using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (HttpWebResponse webResponse= (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch(Exception ex) { throw ex; }
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='https://ndb.bmw.in/'><soapenv:Header/><soapenv:Body><tem:GetWarrantyDetails><tem:IP><demono>WBA3Y37070D45</demono></tem:IP></tem:GetWarrantyDetails></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
but when i call this code i get error of The remote name could not be resolved.
Tried all method but get this error only.
What is missing or wrong i am doing?

Pushwoosh Remote API DOT NET Example

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);
}
}
}
}

Windows 8 universal app ASP.Net web Api

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;
}

IISHandler error does not implement interface member 'System.Web.IHttpHandler.IsReusable',

How do i fix this error
Error 3 'FMMadminModule.IISHandler1' does not implement interface member 'System.Web.IHttpHandler.IsReusable',
Error 4 'FMMadminModule.IISHandler1' does not implement interface member 'System.Web.IHttpHandler.ProcessRequest(System.Web.HttpContext)'
Here is my handler
`using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.SessionState;
namespace FMMadminModule
{
public class IISHandler1 : IHttpHandler
{
/// <summary>
/// You will need to configure this handler in the web.config file of your
/// web and register it with IIS before being able to use it. For more information
/// see the following link: http://go.microsoft.com/?linkid=8101007
DataTable dt;
int key;
byte[] imageOut;
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
key = Convert.ToInt32(request.QueryString["Ind"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
}
You've declared a class twice. Remove the IISHandler1 class at the top, resulting in this:
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.SessionState;
namespace FMMadminModule
{
/// <summary>
/// You will need to configure this handler in the web.config file of your
/// web and register it with IIS before being able to use it. For more information
/// see the following link: http://go.microsoft.com/?linkid=8101007
public class imageHandler : IHttpHandler, IReadOnlySessionState
{
DataTable dt;
int key;
byte[] imageOut;
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
key = Convert.ToInt32(request.QueryString["Ind"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You have nested two classes. Try removing one of the nestings:
public class imageHandler : IHttpHandler, IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
int key = Convert.ToInt32(request.QueryString["Ind"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
DataTable dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
byte[] imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

Resources