Application_BeginRequest not firing (NOT URL rewrite) - asp.net

I would like to write out incoming requests for a SOAP web service. Turns out that my Application_BeginRequest event is not firing. It is running on IIS6 & Windows 2003, so the config change recommended elsewhere doesn't have any effect.
protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
byte[] inputBytes = new byte[HttpContext.Current.Request.ContentLength];
HttpContext.Current.Request.InputStream.Position = 0;
HttpContext.Current.Request.InputStream.Read(inputBytes, 0, inputBytes.Length);
string requestString = ASCIIEncoding.ASCII.GetString(inputBytes);
Logger.Write("input: " + Convert.ToString(inputBytes.Length), Global.LOGGER_EVENT_SOURCE, 0, 0, TraceEventType.Warning);
using (var writer = new StreamWriter(#"c:\inetpub\wwwroot\requests\testfile - " + DateTime.Now.ToString("MMddYYYYhhmmssffff") + ".xml"))
{
writer.Write(requestString);
writer.Close();
}
// Reset stream pointer to beginning.
HttpContext.Current.Request.InputStream.Position = 0;
}
catch (Exception ex)
{
// Error handling; omitted here.
}
}
The code 'almost' works if I just put it inside of the web service method being called; the file is created but the request has a content length of '0'.
Thanks for any advice.

The most likely reason for this issue is that the site is not set as an Application.

Related

Microsoft Custom Speech Service issue when using web socket url

so recently for a work project I've been playing around with speech to text models and in particular custom speech to text models. With a bit of mixing and matching examples I've managed to get a test application to talk to the normal Bing speech to text API. But when I attempt to use it with a custom speech instance only the HTTPS URL works. When I use any of the available long form web socket URLS the error An unhandled exception of type 'System.NullReferenceException' occurred in SpeechClient.dll occurs. This is a bit of a problem as that endpoint only supports 2 minutes of transcription, where as the websocket endpoint supports up to 10 minutes.
This https://learn.microsoft.com/en-us/azure/cognitive-services/custom-speech-service/customspeech-how-to-topics/cognitive-services-custom-speech-use-endpoint page here is what I'm going off of. It says that I should use a web socket url when creating the service, but that leads to the error above.
Here my test bed code for trying it out:
using System;
using Microsoft.CognitiveServices.SpeechRecognition;
using System.IO;
namespace ConsoleApp1
{
class Program
{
DataRecognitionClient dataClient;
static void Main(string[] args)
{
Program p = new Program();
p.Run(args);
}
void Run(string[] args)
{
try
{
// Works
//this.dataClient = SpeechRecognitionServiceFactory.CreateDataClient(SpeechRecognitionMode.LongDictation, "en-US", "Key");
// Works
//this.dataClient = SpeechRecognitionServiceFactory.CreateDataClient(SpeechRecognitionMode.LongDictation, "en-US",
// "Key", "Key",
// "https://Id.api.cris.ai/ws/cris/speech/recognize/continuous");
// Doesn't work
this.dataClient = SpeechRecognitionServiceFactory.CreateDataClient(SpeechRecognitionMode.LongDictation, "en-US",
"Key", "Key",
"wss://Id.api.cris.ai/ws/cris/speech/recognize/continuous");
this.dataClient.AuthenticationUri = "https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken";
this.dataClient.OnResponseReceived += this.ResponseHandler;
this.dataClient.OnConversationError += this.ErrorHandler;
this.dataClient.OnPartialResponseReceived += this.PartialHandler;
Console.WriteLine("Starting Transcription");
this.SendAudioHelper("Audio file path");
(new System.Threading.ManualResetEvent(false)).WaitOne();
} catch(Exception e)
{
Console.WriteLine(e);
}
}
private void SendAudioHelper(string wavFileName)
{
using (FileStream fileStream = new FileStream(wavFileName, FileMode.Open, FileAccess.Read))
{
// Note for wave files, we can just send data from the file right to the server.
// In the case you are not an audio file in wave format, and instead you have just
// raw data (for example audio coming over bluetooth), then before sending up any
// audio data, you must first send up an SpeechAudioFormat descriptor to describe
// the layout and format of your raw audio data via DataRecognitionClient's sendAudioFormat() method.
int bytesRead = 0;
byte[] buffer = new byte[1024];
try
{
do
{
// Get more Audio data to send into byte buffer.
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
// Send of audio data to service.
this.dataClient.SendAudio(buffer, bytesRead);
}
while (bytesRead > 0);
}
finally
{
// We are done sending audio. Final recognition results will arrive in OnResponseReceived event call.
this.dataClient.EndAudio();
}
}
}
void ErrorHandler(object sender, SpeechErrorEventArgs e)
{
Console.WriteLine(e.SpeechErrorText);
}
void ResponseHandler(object sender, SpeechResponseEventArgs e)
{
if(e.PhraseResponse.RecognitionStatus == RecognitionStatus.EndOfDictation || e.PhraseResponse.RecognitionStatus == RecognitionStatus.DictationEndSilenceTimeout)
{
Console.WriteLine("Trnascription Over");
Console.ReadKey();
Environment.Exit(0);
}
for(int i = 0; i < e.PhraseResponse.Results.Length; i++)
{
Console.Write(e.PhraseResponse.Results[i].DisplayText);
}
Console.WriteLine();
}
void PartialHandler(object sender, PartialSpeechResponseEventArgs e)
{
}
}
}
Thanks in advance for any help.
so you are probably ok with using https ...
we are revisiting the SDKs right now (restructuring/reorganizing). I expect updates in the next couple of months.
Wolfgang
The new speech service SDK supports Custom Speech Service out-of-box. Please also check the samples RecognitionUsingCustomizedModelAsync() here for details.

Push Sharp Within Asp.Net Web Service

This is more of a general Asp.Net / .Net lifecycle question.
I'm looking at using PushSharp within a Asp.Net Web Service to send notifications using APNS.
Given the nature of PushSharp using a queue to async send messages and then event callbacks to notify of 'OnNotificationSent' / 'OnServiceException' etc.. how would this work within Asp.net?
The Web Service exposes a method that instantiates PushSharp, registers for the various callback events and queues Notification Messages.
The consumer calls the web service
Once The Web service method returns, does that method continue to receive the event callbacks or is it disposed and the events will not be called?
Thanks
for your help.
Not highly recommended in Asp.net, due to application pool interfering in the process (PushSharp author says notifications in the queue but not get sent). I have implemented this though in an Asp.net website and it works.
I have moved this to a Windows service since.
Global.asax.cs file:
using PushSharp;
using PushSharp.Core;
public class Global : System.Web.HttpApplication
{
private static PushBroker myPushBroker;
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
myPushBroker = new PushBroker();
myPushBroker.OnNotificationSent += NotificationSent;
myPushBroker.OnChannelException += ChannelException;
myPushBroker.OnServiceException += ServiceException;
myPushBroker.OnNotificationFailed += NotificationFailed;
myPushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
myPushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
myPushBroker.OnChannelCreated += ChannelCreated;
myPushBroker.OnChannelDestroyed += ChannelDestroyed;
HttpContext.Current.Application["MyPushBroker"] = myPushBroker;
}
//IMPLEMENT PUSHBROKER DELEGATES HERE
}
aspx.cs file (example Notifications.aspx.cs):
using PushSharp;
using PushSharp.Apple;
using PushSharp.Core;
public partial class Notifications : System.Web.UI.Page {
private PushBroker myPushBroker = HttpContext.Current.Application["MyPushBroker"] as PushBroker;
//SO I CAN SWITCH FROM DEVELOPMENT TO PRODUCTION EASILY I SET THIS IN THE DATABASE
private string pushCertificate = "";
private string certPass = "";
private bool isProduction = false;
protected void btnSendNotification_Click(object sender, EventArgs e)
{
bool hasError = false;
lblError.Text = "";
if (!string.IsNullOrEmpty(txtMessage.Text))
{
try
{
GetCertificate();
//GET DEVICE TOKENS TO SEND MESSAGES TO
//NOT THE BEST WAY TO SEND MESSAGES IF YOU HAVE HUNDREDS IF NOT THOUSANDS OF TOKENS. THAT'S WHY A WINDOWS SERVICE IS RECOMMENDED.
string storedProcUser = "sp_Token_GetAll";
string userTableName = "User_Table";
DataSet dsUser = new DataSet();
UserID = new Guid(ID.Text);
dsUser = srvData.GetDeviceToken(UserID, storedProcUser, userTableName, dataConn);
DataTable userTable = new DataTable();
userTable = dsUser.Tables[0];
if (userTable.Rows.Count != 0)
{
string p12FileName = Server.MapPath(pushCertificate); //SET IN THE GET CERTIFICATE
var appleCert = File.ReadAllBytes(p12FileName);
string p12Password = certPass;
//REGISTER SERVICE
myPushBroker.RegisterAppleService(new ApplePushChannelSettings(isProduction, appleCert, p12Password));
DataRow[] drDataRow;
drDataRow = userTable.Select();
string savedDeviceToken = "";
for (int i = 0; i < userTable.Rows.Count; i++)
{
if (drDataRow[i]["DeviceToken"] is DBNull == false)
{
savedDeviceToken = drDataRow[i]["DeviceToken"].ToString();
myPushBroker.QueueNotification(new AppleNotification()
.ForDeviceToken(savedDeviceToken)
.WithAlert(txtMessage.Text)
.WithBadge(1)
.WithSound("sound.caf"));
//NOTHING TO DO ANYMORE. CAPTURE IN THE PUSH NOTIFICATION DELEGATE OF GLOBAL ASCX FILE WHAT HAPPENED TO THE SENT MESSAGE.
}
}
}
}
catch(Exception ex)
{
}
finally
{
}
}
}
}
Check out EasyServices it allows you to easily push notifications to various push servers using PushSharp without having to take care of un-received notifications even when using ASP.NET
var _pushNotificationService = EngineContext.Current.Resolve<IPushNotificationService>();
_pushNotificationService.InsertNotification(NotificationType type, string title, string message, int subscriberId, PushPriority Priority = PushPriority.Normal);
https://easyservices.codeplex.com

Rewrite url for video

I am newbie with asp.net. I have a url of video http://localhost/video/file.mp4 , but i want to serve url like http://localhost/34567fghft/file.mp4 to make timeout for url, is there some solution to my question? Sr for my english, im stuct around with this, waiting for your answers, thanks
You can on Global.asax, and on Application_BeginRequest to get the requested path, split it, see if has expired or not, manipulate the string and send him ether to an error page, ether rewrite it to the real path:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
if (cTheFile.EndsWith("/file.mp4", StringComparison.InvariantCultureIgnoreCase))
{
// manipulate your string to see if is expired...
string[] keys = HttpContext.Current.Request.Path.Split('/');
// get the 34567fghft part
if (IfExpired(keys[keys.Length - 1]))
{
HttpContext.Current.Response.Redirect("ExpiredMessage.aspx", true);
return ;
}
else
{
HttpContext.Current.RewritePath("http://localhost/video/file.mp4", false);
}
}
}
Please note this code is the idea on how you do it. Is need some better string manipulation and error check.

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

Any ideas why on some links that I try to access using HttpWebRequest I am getting "The remote server returned an error: (304) Not Modified." in the code?
The code I'm using is from Jeff's post here (the page seems to have disappeared, see an archive copy at the Wayback Machine).
Note the concept of the code is a simple proxy server, so I'm pointing my browser at this locally running piece of code, which gets my browsers request, and then proxies it on by creating a new HttpWebRequest, as you'll see in the code. It works great for most sites/links, but for some this error comes up. You will see one key bit in the code is where it seems to copy the http header settings from the browser request to it's request out to the site, and it copies in the header attributes. Not sure if the issue is something to do with how it mimics this aspect of the request and then what happens as the result comes back?
case "If-Modified-Since":
request.IfModifiedSince = DateTime.Parse(listenerContext.Request.Headers[key]);
break;
I get the issue for example from http://en.wikipedia.org/wiki/Main_Page
PS. UPDATE HERE
Still can't work this out. Basically I can identify 1 link which has an issue, and it seems to work fine, 2nd time it gets the error, 3rd time OK, 4th time gets the error, 5th time OK etc. As if there is some state not getting cleared or something in the code. I've tried to clean up the code a bit using "using" type statements etc.
Here's the code. If anyone can spot why every 2nd time I browse to a link like http://newsimg.bbc.co.uk/css/screen/1_0_16/nol/v4/story.css (starting at the 2nd time, not the first) via this proxy code I get the error I'd love to hear.
class Program
{
static void Main(string[] args)
{
Proxy p = new Proxy(8080);
Thread proxythread = new Thread(new ThreadStart(p.Start));
proxythread.Start();
Console.WriteLine("Proxy Started. Press Any Key To Stop...");
Console.ReadKey();
p.Stop();
}
}
public class Proxy
{
private HttpListener _listener;
private int _port;
public Proxy(int port)
{
int defaultport = 8080;
// Setup Thread Pool
System.Threading.ThreadPool.SetMaxThreads(50, 1000);
System.Threading.ThreadPool.SetMinThreads(50, 50);
// Sanitize Port Number
if (port < 1024 || port > 65535)
port = defaultport;
// Create HttpListener Prefix
string prefix = string.Format("http://*:{0}/", port);
_port = port;
// Create HttpListener
_listener = new HttpListener();
_listener.Prefixes.Add(prefix);
}
public void Start()
{
_listener.Start();
while (true)
{
HttpListenerContext request = null;
try
{
request = _listener.GetContext();
// Statistics (by Greg)
int availThreads = -1;
int compPortThreads = -1;
ThreadPool.GetAvailableThreads(out availThreads, out compPortThreads);
log("INFO", request.Request.Url.ToString(), "START - [" + availThreads + "]");
ThreadPool.QueueUserWorkItem(ProcessRequest, request);
}
catch (HttpListenerException ex)
{
log("ERROR", "NA", "INFO: HttpListenerException - " + ex.Message);
break;
}
catch (InvalidOperationException ex)
{
log("ERROR", "NA", "INFO: InvalidOperationException - " + ex.Message);
break;
}
}
}
public void Stop()
{
_listener.Stop();
}
private void log(string sev, string uri, string message)
{
Console.Out.WriteLine(Process.GetCurrentProcess().Id + " - " + sev + " (" + uri + "): " + message);
}
private void ProcessRequest(object _listenerContext)
{
#region local variables
HttpWebRequest psRequest; // Request to send to remote web server
HttpWebResponse psResponse; // Response from remote web server
List<byte> requestBody = new List<byte>(); // Byte array to hold the request's body
List<byte> responseBody = new List<byte>(); // Byte array to hold the response's body
byte[] buffer;
string uri = "";
#endregion
var listenerContext = (HttpListenerContext)_listenerContext;
uri = listenerContext.Request.Url.ToString().Replace(string.Format(":{0}", _port), "");
// Create Interent Request
HttpWebRequest internetRequest = (HttpWebRequest)WebRequest.Create(uri);
#region Build Request Up
internetRequest.Method = listenerContext.Request.HttpMethod;
internetRequest.ProtocolVersion = listenerContext.Request.ProtocolVersion;
internetRequest.UserAgent = listenerContext.Request.UserAgent;
foreach (string key in listenerContext.Request.Headers.AllKeys)
{
try
{
switch (key)
{
case "Proxy-Connection":
case "Connection":
internetRequest.KeepAlive = (listenerContext.Request.Headers[key].ToLower() == "keep-alive") ? true : false;
break;
case "Content-Length":
internetRequest.ContentLength = listenerContext.Request.ContentLength64;
break;
case "Content-Type":
internetRequest.ContentType = listenerContext.Request.ContentType;
break;
case "Accept":
internetRequest.Accept = listenerContext.Request.Headers[key];
break;
case "Host":
break;
case "Referer":
internetRequest.Referer = listenerContext.Request.Headers[key];
break;
case "If-Modified-Since":
internetRequest.IfModifiedSince = DateTime.Parse(listenerContext.Request.Headers[key]);
break;
default:
internetRequest.Headers.Add(key, listenerContext.Request.Headers[key]);
break;
}
}
catch (Exception ex)
{
Console.WriteLine("Error settup up psRequest object. Error = " + ex.Message + "\n" + ex.StackTrace);
}
}
#endregion
#region Copy content into request
buffer = new byte[1024];
using (Stream instream = listenerContext.Request.InputStream)
{
int incount = instream.Read(buffer, 0, buffer.Length);
while (incount > 0)
{
internetRequest.GetRequestStream().Write(buffer, 0, incount);
incount = instream.Read(buffer, 0, buffer.Length);
}
}
#endregion
// Get Internet Response
HttpWebResponse internetResponse = null;
try
{
using (internetResponse = (HttpWebResponse)internetRequest.GetResponse())
{
#region Configure Local Response Header Keys
foreach (string key in internetResponse.Headers.Keys)
{
try
{
switch (key)
{
case "Transfer-Encoding":
listenerContext.Response.SendChunked = (internetResponse.Headers[key].ToLower() == "chunked") ? true : false;
break;
case "Content-Length":
listenerContext.Response.ContentLength64 = internetResponse.ContentLength;
break;
case "Content-Type":
listenerContext.Response.ContentType = internetResponse.Headers[key];
break;
case "Keep-Alive":
listenerContext.Response.KeepAlive = true;
break;
default:
listenerContext.Response.Headers.Add(key, internetResponse.Headers[key]);
break;
}
}
catch (Exception ex)
{
log("ERROR", uri, "Error settup up listenerContext.Response objects. Error = " + ex.Message + "\n" + ex.StackTrace);
}
}
#endregion
try
{
// Transfer the body data from Internet Response to Internal Response
buffer = new byte[1024];
using (Stream inputStream = internetResponse.GetResponseStream())
{
int outcount = inputStream.Read(buffer, 0, buffer.Length);
while (outcount > 0)
{
listenerContext.Response.OutputStream.Write(buffer, 0, outcount);
outcount = inputStream.Read(buffer, 0, buffer.Length);
}
}
}
catch (Exception ex)
{
log("ERROR", uri, "Could not obtain response from URI: " + ex.Message);
}
finally
{
listenerContext.Response.OutputStream.Close();
}
}
}
catch (Exception ex)
{
//if (ex is InvalidOperationException ||
// ex is ProtocolViolationException ||
// ex is WebException)
//{
// log(uri, "Could not successfully get response: " + ex.GetType() + " - " + ex.Message);
// listenerContext.Response.Close();
// return;
//}
//else { throw; }
log("ERROR", uri, "Could not successfully get response: " + ex.GetType() + " - " + ex.Message);
listenerContext.Response.Close();
}
}
}
And here is an example of what I see - first hit is good, 2nd has error...
Proxy Started. Press Any Key To Stop...
2080 - INFO (http://newsimg.bbc.co.uk:8080/css/screen/1_0_16/nol/v4/story.css): START - [50]
2080 - INFO (http://newsimg.bbc.co.uk:8080/css/screen/1_0_16/nol/v4/story.css): START - [50]
2080 - ERROR (http://newsimg.bbc.co.uk/css/screen/1_0_16/nol/v4/story.css): Could not successfully get response: System.Net.WebException - The remote server returned an error: (304) Not Modified.
First, this is not an error. The 3xx denotes a redirection. The real errors are 4xx (client error) and 5xx (server error).
If a client gets a 304 Not Modified, then it's the client's responsibility to display the resouce in question from its own cache. In general, the proxy shouldn't worry about this. It's just the messenger.
This is intended behavior.
When you make an HTTP request, the server normally returns code 200 OK. If you set If-Modified-Since, the server may return 304 Not modified (and the response will not have the content). This is supposed to be your cue that the page has not been modified.
The authors of the class have foolishly decided that 304 should be treated as an error and throw an exception. Now you have to clean up after them by catching the exception every time you try to use If-Modified-Since.
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ? at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
It is not an issue it is because of caching...
To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').
After timestamp it should be axios.get(/api/products?${Date.now()}.
It will resolve your 304 status code.
I think you have not installed these features. see below in picture.
I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.
Install Process:
go to android studio
Tools
Android
SDK Manager
Appearance & Behavior
Android SDK

Asp.net Webform Display Alert and redirect

I'm currently stuck. I have a webform with a button that registers or saves a record.
What i'd like to is have it display a javascript alert and then redirect to a page.
Here is the code i am using
protected void Save(..)
{
// Do save stuff
DisplayAlert("The changes were saved Successfully");
Response.Redirect("Default.aspx");
}
This code just redirects without giving the prompt Saved Successfully.
Here is my DisplayAlert Code
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');", message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true
);
}
Can anyone help me find a solution to this?
Thanks
You can't do a Response.Redirect because your javascript alert will never get displayed. Better to have your javascript code actually do a windows.location.href='default.aspx' to do the redirection after the alert is displayed. Something like this:
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');window.location.href = 'default.aspx'",
message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true);
}
The DisplayAlert method adds the client script to the currently executing page request. When you call Response.Redirect, ASP.NET issues a HTTP 301 redirect to the browser, therefore starting a new page request where the registered client script no longer exists.
Since your code is executing on the server-side, there is no way to display the alert client-side and perform the redirect.
Also, displaying a JavaScript alert box can be confusing to a user's mental workflow, an inline message would be much more preferable. Perhaps you could add the message to the Session and display this on the Default.aspx page request.
protected void Save(..)
{
// Do save stuff
Session["StatusMessage"] = "The changes were saved Successfully";
Response.Redirect("Default.aspx");
}
Then in Default.aspx.cs code behind (or a common base page class so this can happen on any page, or even the master page):
protected void Page_Load(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty((string)Session["StatusMessage"]))
{
string message = (string)Session["StatusMessage"];
// Clear the session variable
Session["StatusMessage"] = null;
// Enable some control to display the message (control is likely on the master page)
Label messageLabel = (Label)FindControl("MessageLabel");
messageLabel.Visible = true;
messageLabel.Text = message;
}
}
The code isn't tested but should point you in the right direction
This works perfect:
string url = "home.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Saved Sucessfully.');window.location.href = '" + url + "';",true);
protected void Save(..)
{
// Do save stuff
ShowMessageBox();
}
private void ShowMessageBox()
{
string sJavaScript = "<script language=javascript>\n";
sJavaScript += "var agree;\n";
sJavaScript += "agree = confirm('Do you want to continue?.');\n";
sJavaScript += "if(agree)\n";
sJavaScript += "window.location = \"http://google.com\";\n";
sJavaScript += "</script>";
Response.Write(sJavaScript);
}

Resources