Asp.net change hourglass cursor back without post back - c#

I created an asp.net site for downloading documents. I handle this with Page.Response.
try {
...
EndpointAddress endPoint = new EndpointAddress("xxxxx.svc");
FileServiceClient fileServiceProxy = new FileServiceClient(binding, endPoint);
// WCF WebService call
Stream stream = fileServiceProxy.GetFileStream(filePath);
Page.Response.ContentType = "application/pdf";
Page.Response.AddHeader("Content-Disposition",string.Format ("attachment; fileName=\"{0}\"", Path.GetFileName(filePath)));
Page.Response.AddHeader("Accept-Ranges", "bytes");
if (buffer != null){
Page.Response.BinaryWrite(buffer);
}
Page.Response.Flush();
}
catch (Exception e)
{
Page.Response.Clear();
Page.Response.ClearContent();
Page.Response.ClearHeaders();
}
finally
{
Page.Response.End();
}
And while the file is loading from a webservice I want to display a hourglass cursor. Showing loading cursor is working.
protected void Page_Load(object sender, EventArgs e)
{
btnDownload.Attributes.Add("onclick", "document.body.style.cursor = 'wait';");
}
But I can't change it back to normal cursor. I think because I don't fire a post back or don't reload the site.
What can I do to set default cursor if buttonClick event is over without site reload!?
Update: Updated the code with the wcf webservice call. I call the webservice with file path and get a stream back which I write to Page.Response.BinaryWriter

# Frédéric Hamidi THX for the link. I change my approach and display a jquery waiting dialog until file transfer is finished.
File download dialog

Related

How to capture video stream via http with an IP camera using emgucv in c#

I'm having the hardest time trying to find a solution for something I think would be very simple. The Capture Constructor (String) in Emgu.CV should "Create a capture from file or a video stream."
However, I cannot capture anything with my code in C# despite my IP camera (Axis) allowing a video stream as follows:
Request a Motion JPEG video stream ->
http://myserver/axis-cgi/mjpg/video.cgi
(By the way, according to the manufacturer, "A successful request returns a continuous flow of JPEG images. The content type is multipart/x-mixed-replace and each image ends with a boundary string .")
FYI, the camera server does require a username and password login, which I haven't been able to figure out how to include with Capture yet, either...
Am I supposed to make a HTTPWebRequest first and then do Capture, or am I supposed to do something much more complicated? Not sure if login may be an issue since I didn't get a specific error on this, but suspect a webrequest may be necessay, which I don't know how to include...
Stripped down code in my form.cs:
Capture _capture = null; //Camera
string sourceURL = "http://192.168.0.90/axis-cgi/mjpg/video.cgi";
_capture = new Capture(sourceURL);
Image<Bgr, Byte> imgOriginal = new Image<Bgr, byte>(_capture.RetrieveBgrFrame().ToBitmap());
Then I try to display imgOriginal in an ImageBox. However, at the last step above, it already generates an error that says "unable to create capture..." or something like this.
Shouldn't this be very simple with emguCV or am I mistaken? If someone can help me figure out how to capture the image, I can take it from there with processing my images. Thank you in advance!
Might be too late for this post , but hopefully it'll help someone else in the future.
For MJPEG video codec use ==>
http://root:pass#172.16.10.38/axis-cgi/mjpg/video.cgi?x.mjpeg
For H.264 codec use ==>
rtsp://root:pass#172.16.10.38/axis-media/media.amp?videocodec=h264&resolution=640x480
Please note that these URIs apply only to AXIS brand IP Cameras . For other IP camera brands , I'd suggest you to check the below website , as each manufacturer has a different HTTP or RTSP URI
http://www.soleratec.com/support/rtsp/rtsp_listing
As for the implementation code, here is a headstart :
private static Capture _cameraCapture;
//Windows form button to start the video stream
private void btn_play_Click(object sender, EventArgs e)
{
Run();
}
private void Run()
{
if (rdbWebcam.Checked == true) //radio button
{
_cameraCapture = new Capture(0); //use local webcam
}
else
{
_cameraCapture = new Capture(txtrtsp.Text); //use rtsp or http uri you typed into a textbox
}
Application.Idle += ProcessFrame;
}
private void ProcessFrame(object sender, EventArgs e)
{
try
{
Mat frame = _cameraCapture.QueryFrame();
imageBox1.Image = frame; //imagebox to show live video
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.Exit();
}
}
//Windows Form FormClosing event
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (_cameraCapture != null)
{
_cameraCapture.Stop();
_cameraCapture.Dispose();
}
}
There are a few things that you might want to try.
First you can use something like fiddler(its a proxy to monitor your web traffic) to check that when application is making the request to the server what response is coming back.
Second if the server requires authentication its very likely its using HTTP Basic authentication you might want to try to call the url something like
string sourceURL = "http://username:password#192.168.0.90/axis-cgi/mjpg/video.cgi";
_capture = new Capture(sourceURL);
or else you will have to send the parameters in Authorization Header
You can use the native cvInvoke function to check that if it helps.The code will be something like this.
Capture _Capture = new Emgu.CV.CvInvoke.cvCreateFileCapture("http://username:password#192.168.0.90/axis-cgi/mjpg/video.cgi");
Please refer to this SO answer more info

Code executes even after Response.End()

I have to reload my page after I write some html, script to my page using Response.Write. After using Response.Write I am using Response.Flush(), followed by Response.End(). The code works properly in one server and when I deploy it to another server it is not working.
As far as I know the code execution must stop once it executes the Response.End, but it is now behaving in the desired way.
Response.ClearContent();
Response.Write("Write some html, script content here");
Response.Flush();
Response.End();
Using Respose.Redirect(Request.RawUrl) will not work and will throw an exception stating that the redirection cannot happen once the headers are posted...
Can some one tell me, why the code execution is not stopped by Response.End() ??
EDIT: Actual Code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["localTime"] == null && String.IsNullOrEmpty(Request.Params["localTime"]))
{
// then clear the content and write some html, a javascript code which submits the local time
Response.ClearContent();
Response.Write(#"<form id='local' method='post' name='local'>
<input type='hidden' id='localTime' name='localTime' />
<script type='text/javascript'>
document.getElementById('localTime').value = new Date();
document.getElementById('local').submit();
</script>
</form>");
//
Response.Flush();
// end the response so PageLoad, PagePreRender etc won't be executed
Response.End();//Page must reload after this line.
}
else
{
// if the request contains the localtime, then save it in Session
if (Request.Params["localTime"] != null)
{
Session["localTime"] = Request.Params["localTime"];
Response.Write(Request.Params["localTime"] + " ~2");
// and redirect back to the original url
Response.Redirect(Request.RawUrl);
}
}
}

Using try-catch and if-else statement to open new browser window

Using: C# and .net
I want to use a try catch to display an image of the product in a new window window. Everything works unless the image does not exist meaning a (HTTP Error 404 - File or directory not found) page. If that happens the button just simply does nothing when clicked.
What I want to happen is when you click the button and the file does not exist that the user is taken to a "Image does not exist" page. I have tried to do that in the following code. It does not work. Thanks for any advice!
bool ImageExists = true;
try
{
webResponse = webRequest.GetResponse();
}
catch
{
ImageExists = false;
}
if (ImageExists == true)
{
ClientScript.RegisterStartupScript(this.GetType(), "openFoundImage", "window.open('" + PathToFolder + "');", true);
}
else
{
System.Diagnostics.Process.Start("http://www.companysite.com/noimage.jpg");
}
Edit: Changed to bool.
Try Catch won't trigger in this. See the link below
How to: Request Data Using the WebRequest Class
4.. You can access the properties of the WebResponse or cast the WebResponse to a protocol-specific instance to read protocol-specific
properties. For example, to access the HTTP-specific properties of
HttpWebResponse, cast the WebResponse to a HttpWebResponse reference.
The following code example shows how to display the status information
sent with a response.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
Add logic around the status return.

Cancel webclient Async request

Hopefully an easy question for you all but I'm really struggling.
I've only recently started programming and have just had an app certified to the WP7 app store but noticed a bug myself that i would like to fix before making the app public.
Basically I have a search box where the user enters a chemical name and a webservice returns an image and its molecular weight. What i would like to do is cancel the webclient if the user navigates away from the page before the download is completed or if a new search is made before the previous is completed (this currently crashes the app as I believe you can only have one request at a time??)
private void searchCactus()
{
WebClient imgClient = new WebClient();
imgClient.OpenReadCompleted += new OpenReadCompletedEventHandler(imgClient_OpenReadCompleted);
WebClient mwClient = new WebClient();
mwClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mwClient_DownloadStringCompleted);
if (DeviceNetworkInformation.IsNetworkAvailable == false)
{
MessageBox.Show("No network found, please check network availability and try again");
}
else if (compoundSearchBox.Text.Contains("?"))
{
MessageBox.Show("\"?\" Not Permitted");
return;
}
else if (compoundSearchBox.Text != "")
{
progBar1.IsIndeterminate = true;
string imageuri = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/image?format=png&width=300&height=300";
string mwURI = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/mw";
imgClient.OpenReadAsync(new Uri(#imageuri), imgClient);
mwClient.DownloadStringAsync(new Uri(#mwURI), mwClient);
// //lower keyboard
this.Focus();
}
else MessageBox.Show("Enter Search Query");
}
I tried implementing the following button but it does not work
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
imgClient.CancelAsync();
mwClient.CancelAsync();
}
as "the name 'mwClient' does not exist in the current context"
I would be very grateful if anybody could provide some guidance
Just put the two clients into fields in your class.

How to post data from a webform page to an HTTPHandler.ashx file?

I have a web application project to support file transfer operations to vendor product backend. It's composed of 2 HTTPHandler files compiled into a website on a Win2003 server with IIS 6.0:
UploadHandler.ashx
DownloadHandler.ashx
These files get "POSTed to" from a ColdFusion website that exposes the user interface. In a way, my job is done because these handlers work and have to be called from ColdFusion.
Yet, I am very frustrated with my inability to get my own "test UI" (default.aspx) to use in my testing/refinement independent of ColdFusion.
<asp:Button ID="DownloadButton" PostBackUrl="~/DownloadHandler.ashx" runat="server" Text="Download"/>
Using a PostBackUrl for Download works nicely - when the DownloadHandler.ashx is entered, it finds its key input value in context.Request.Form["txtRecordNumber"];
But I cannot use this technique for Upload because I have to do some processing (somehow read the bytes from the chosen fileupload1.postedfile into a FORM variable so my UploadHandler.ashx file can obtain its input from Request.Form as with Download).
My first approach tried using HTTPWebRequest which seemed overly complex and I could never get to work. Symptoms began with a HTTP 401 status code and then morphed into a 302 status code so I researched other ideas.
Here is my latest code snippet from my default.aspx:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
BuildFormData();
//Server.Transfer("UploadHandler.ashx", true);
Response.Redirect("~/UploadHandler.ashx");
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
protected void BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
b64fileName.Text = FileUpload1.PostedFile.FileName;
// create arbitrary MetaData in a string
strMetaData.Text = "recAuthorLoc=anyname1~udf:OPEAnalyst=anyname2~udf:Grant Number=0102030405";
}
Attempts to use Server.Transfer (above) to my .ashx file result in an error:
error executing child request for UploadHandler.ashx
Attempts to use Response.Redirect (above) to my .ashx file result in GET (not POST) and Trace.axd of course shows nothing in the Form collection so that seems wrong too.
I even tried clone-ing my .ashx file and created UploadPage.aspx (a webform with no HTML elements) and then tried:
Server.Transfer("UploadPage.aspx", true);
//Response.Redirect("~/UploadPage.aspx");
Neither of those allow me to see the form data I need to see in Request.Form within my code that processes the Upload request. I am clearly missing something here...thanks in advance for helping.
EDIT-UPDATE:
I think I can clarify my problem. When the UploadHandler.ashx is posted from ColdFusion, all of the input it needs is available in the FORM collection (e.g. Request.Form["fileData"] etc.)
But when I use this control it generates a postback to my launching web page (i.e. default.aspx). This enables me to refer to the content by means of FileUpload1.PostedFile as in:
protected void BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
b64fileName.Text = FileUpload1.PostedFile.FileName;
}
Yet I am not using the FileUpload1.PostedFile.SaveAs method to save the file somewhere on my web server. I need to somehow - forgive the language here - "re-post" this data to an entirely different file - namely, my UploadHandler.ashx handler. All the goofy techniques I've tried above fail to accomplish what I need.
EDIT-UPDATE (20 Aug 2009) - my final SOLUTION using Javascript:
protected void UploadHandlerButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
ctlForm.Text = BuildFormData();
String strJS = InjectJS("_xclick");
ctlPostScript.Text = strJS;
}
catch (Exception someError)
{
LogText("FAILURE: " + someError.Message);
}
}
}
private String InjectJS(String strFormId)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var ctlForm1 = document.forms.namedItem('{0}');");
strScript.Append("ctlForm1.submit();");
strScript.Append("</script>");
return String.Format(strScript.ToString(), strFormId);
}
protected string BuildFormData()
{
BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
int numBytes = FileUpload1.PostedFile.ContentLength;
byte[] fileContent = b.ReadBytes(numBytes);
// Convert the binary input into Base64 UUEncoded output.
string base64String;
base64String =
System.Convert.ToBase64String(fileContent,
0,
fileContent.Length);
objBinaryData.Text = base64String;
b64fileName.Text = FileUpload1.PostedFile.FileName;
// create arbitrary MetaData in a string
strMetaData.Text = "recAuthorLoc=Patterson, Fred~udf:OPEAnalyst=Tiger Woods~udf:Grant Number=0102030405";
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"_xclick\" name=\"_xclick\" target=\"_self\" action=\"http://localhost/HTTPHandleTRIM/UploadHandler.ashx\" method=\"post\">");
strForm.Append("<input type=\"hidden\" name=\"strTrimURL\" value=\"{0}\" />");
strForm.Append("<input type=\"hidden\" name=\"objBinaryData\" value=\"{1}\" />");
strForm.Append("<input type=\"hidden\" name=\"b64fileName\" value=\"{2}\" />");
strForm.Append("<input type=\"hidden\" name=\"strDocument\" value=\"{3}\" />");
strForm.Append("<input type=\"hidden\" name=\"strMetaData\" value=\"{4}\" />");
strForm.Append("</form>");
return String.Format(strForm.ToString()
, txtTrimURL.Text
, objBinaryData.Text
, b64fileName.Text
, txtTrimRecordType.Text
, strMetaData.Text);
}
Sorry if I'm missing something, but can't you simply use a plain HTML form to upload files to your handler:
<form action="UploadHandler.ashx" method="post" enctype="multipart/form-data">
Choose file to upload:
<input name="file" type="file" size="50">
</form>
What worked for me was to inject a new FORM and some Javascript to submit the FORM to the UploadHandler.ashx. This (for me) was easier to grasp than the HTTPWebRequest technique.
John Galt,
The only way to do what you want is using HttpWebRequest.
Here is good example of a Class that do what you want. I've made to send image and form values to picassa serve sometime ago (I know I could use Picassa API, but I did it for fun).
You only need to pay attention to the 'SendPhoto' function to get hints on what you have to do to make HttpWebRequest to do the work.

Categories