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

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

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.

ASP.NET Identity AllowOnlyAlphanumericUserNames

Can someone please help me how can i use special characters in ASP.Net identity?
The problem is that my users cannot register with special characters: č,ć,š,ž,đ.
When you try to enter this characters in registration, i get following error:
User name Krešo is invalid, can only contain letters or digits.
Where and how can i change this.
Here is the code:
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Pages_Account_Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPrijava_Click(object sender, EventArgs e)
{
UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
userStore.Context.Database.Connection.ConnectionString =
System.Configuration.ConfigurationManager.ConnectionStrings["SeminariConnectionString3"].ConnectionString;
UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
IdentityUser user = new IdentityUser();
user.UserName = txtKorisnickoIme.Text;
if(txtLozinka.Text == txtPotvrdaLozinke.Text)
{
try
{
IdentityResult result = manager.Create(user, txtLozinka.Text);
if(result.Succeeded)
{
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
Response.Redirect("Pocetna.aspx");
}
else
{
litStatus.Text = result.Errors.FirstOrDefault();
}
}
catch (Exception ex)
{
litStatus.Text = ex.ToString();
}
}
else
{
litStatus.Text = "Lozinke moraju biti identične.";
}
}
}
You should be able to change this behaviour as follows:
var manager = new UserManager<IdentityUser>(userStore); // existing code
var validator = manager.UserValidator as UserValidator<ApplicationUser>;
if (validator != null) validator.AllowOnlyAlphanumericUserNames = false;
Should validator turn out to be null, then debug a little to find the actual type used at runtime.

The remote server returned an error: (500) Internal Server Error. web service error soap request

I want to create a web service that responds to soap requests. and returns a soap response.now i want to send 2 parameters to the service namely invoiceno and orderno do something with it at the webservice and return the result. currently im just trying to retuen the values recieved as it is back to the client, but i keep getting this error "The remote server returned an error: (500) Internal Server Error." I am a total novice with soap web services. please tell me what i am doing wrong. or is this completely wrong.
namespace WebApplication7
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public XmlDocument savedata()
{
XmlDocument xmlSoapRequest = new XmlDocument();
Stream receiveStream = HttpContext.Current.Request.InputStream;
receiveStream.Position = 0;
string invoiceno2 = xmlSoapRequest.GetElementById("invoiceno").Value;
string orderno2 = xmlSoapRequest.GetElementById("orderno").Value;
string gg = #" <soap:Envelopexmlns:soap=""http://www.w3.org/2001/12/soap-envelope""soap:encodingStyle=""http://www.w3.org/2001/12/soap-encoding"">
<soap:Body xmlns:m=""http://www.example.org/stock"">
<m:savedata>
<m:invoiceno>" + invoiceno2 + #"</m:invoiceno>
<m:orderno>" + orderno2 + #"</m:orderno>
<m:haha>hahahahahahahha</m:haha>
</m:savedata>
</soap:Body>
</soap:Envelope>";
XmlDocument cv = new XmlDocument();
cv.LoadXml(gg);
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
// Load into XML document
xmlSoapRequest.Load(readStream);
}
// string gg = invoiceno + " hahahahaha " + orderno;
return cv;
}
}
}
and this is the client i created to consume it
namespace unicommerce_testing
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Execute());
}
public static string Execute()
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(CreateOrEditItemTypeRequestCreator("44", "2500313-125","Watch",20,20,20,56,"This is a test product","Red","Brillier","NA",45000));
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
return soapResult;
}
}
}
/// <summary>
/// Create a soap webrequest to [Url]
/// </summary>
/// <returns></returns>
public static HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(#"http://localhost:1234/test/WebService1.asmx/savedata");
webRequest.Headers.Add(#"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
public static string CreateOrEditItemTypeRequestCreator()
{
string request= #"<soap:Envelopexmlns:soap=""http://www.w3.org/2001/12/soap-envelope""soap:encodingStyle=""http://www.w3.org/2001/12/soap-encoding"">
<soap:Body xmlns:m=""http://www.example.org/stock"">
<m:savedata>
<m:invoiceno>inv1</m:invoiceno>
<m:orderno>od1</m:orderno>
</m:savedata>
</soap:Body>
</soap:Envelope>";
return request;
}
}
}

getting directed to ASP.NET home page on browser

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?

Compressing viewstate is adding another hidden field with same id as __VIEWSTATE

I am trying to compress viewstate in ASP.Net 4.0, so the page loads more quickly for heavily bloated viewstate pages.
However, when I view source of page in browser, I am finding 2 hidden fields with same name and id of '__VIEWSTATE'.
My code is as below. How can I compress the view state but let it be stored in its original hidden field without creating another duplicate hidden field?
protected override void SavePageStateToPersistenceMedium(object viewState)
{
byte[] viewStateArray;
using (MemoryStream memoryStream = new MemoryStream())
{
_objectStateFormatter.Serialize(memoryStream, viewState);
viewStateArray = memoryStream.ToArray();
}
ClientScript.RegisterHiddenField("__VIEWSTATE",
Convert.ToBase64String(GZip.Compress(viewStateArray)));
}
using System.IO;
using System.IO.Compression;
using System.Web.UI;
public class PageCompressed : System.Web.UI.Page
{
private ObjectStateFormatter _formatter = new ObjectStateFormatter();
protected override void SavePageStateToPersistenceMedium(object viewState)
{
MemoryStream ms = new MemoryStream();
_formatter.Serialize(ms, viewState);
byte[] viewStateArray = ms.ToArray();
ClientScript.RegisterHiddenField("__CVIEWSTATE", Convert.ToBase64String(_Compress(viewStateArray)));
}
protected override object LoadPageStateFromPersistenceMedium()
{
string vsString = Request.Form["__CVIEWSTATE"];
byte[] bytes = Convert.FromBase64String(vsString);
bytes = _DeCompress(bytes);
return _formatter.Deserialize(Convert.ToBase64String(bytes));
}
private byte[] _Compress(byte[] inputBytes)
{
MemoryStream m = new MemoryStream();
GZipStream zip = new GZipStream(m, CompressionMode.Compress, true);
zip.Write(inputBytes, 0, inputBytes.Length);
zip.Close();
return m.ToArray();
}
private byte[] _DeCompress(byte[] inputBytes)
{
MemoryStream m = new MemoryStream(inputBytes);
MemoryStream mout = new MemoryStream();
GZipStream zip = new GZipStream(m, CompressionMode.Decompress, true);
do
{
byte[] bBuffer = new byte[4097];
int iRead = zip.Read(bBuffer, 0, bBuffer.Length);
if (iRead > 0)
{
mout.Write(bBuffer, 0, iRead);
}
else
{
break;
}
} while (true);
zip.Close();
return mout.ToArray();
}
}
you can use this Interface Class to compress viewstate by inheriting from it like this in code behind for every page
public partial class Default : PageCompressed

Resources