How to show a message on process end in website? - c#

I want to start a process when i clicked the start button on webpage (asp.net site) now i want to set the label text to process started. and i want to set the label text to "Process Completed " when the process is ended. how to do this in asp.net and C#.
Thanks in advance.

You might want to consider using ASP.NET SignalR. Here's a summary of what it does:
ASP.NET SignalR is a new library for ASP.NET developers that makes it
incredibly simple to add real-time web functionality to your
applications. What is "real-time web" functionality? It's the
ability to have your server-side code push content to the connected
clients as it happens, in real-time.
The following is an example of simple web page with a button which starts Notepad.exe. Once the process is started, a label on the page shows process started. When the process exits (Notepad is closed), the label's updates to process exited.
So, first create an ASP.NET empty web application project (let's name it MyWebApplication) and get the Microsoft ASP.NET SignalR NuGet package. Add a web form to the project and name it Test. Add the following code to the Test.aspx file:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="Test.aspx.cs" Inherits="MyWebApplication.Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"
type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.1.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message) {
$('#label').text(message);
};
// Start the connection
$.connection.hub.start();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="Start Notepad.exe"
ID="button" OnClick="button_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="button" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<span id="label"></span>
</div>
</form>
</body>
</html>
Add a new class file to your project and name it Chat. In Chat.cs you will have:
using Microsoft.AspNet.SignalR;
namespace MyWebApplication
{
public class Chat : Hub
{
public void Send(string message)
{
//Call the addMessage method on all clients
var c = GlobalHost.ConnectionManager.GetHubContext("Chat");
c.Clients.All.addMessage(message);
}
}
}
Add the following to the Test.aspx.cs file:
using System;
using System.Diagnostics;
using Microsoft.AspNet.SignalR;
namespace MyWebApplication
{
public partial class Test : System.Web.UI.Page
{
Chat chat = new Chat();
protected void Page_Load(object sender, EventArgs e)
{
}
void MyProcess_Exited(object sender, EventArgs e)
{
chat.Send("process exited");
}
protected void button_Click(object sender, EventArgs e)
{
Process MyProcess = new Process();
MyProcess.StartInfo = new ProcessStartInfo("notepad.exe");
MyProcess.EnableRaisingEvents = true;
MyProcess.Exited += MyProcess_Exited;
MyProcess.Start();
chat.Send("process started");
}
}
}
Add the Global.asax file:
using System;
using System.Web.Routing;
namespace MyWebApplication
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs();
}
}
}
Some things I haven't covered:
The label is updated on all connections.
I'm not verifying if the process is already running or not (but that shouldn't be very difficult to check).

Use javascript to do the callback. And on each stage; Initiated, Completed or Error; update a label in your html. This should be fairly simple if you look for some samples with jQuery AJAX.
jQuery AJAX POST example

If you dont want to use javascript...what you can do is to change label text first when button click event is fired.
lblLabel.text="process started"
and last line in button_click event should be like:
lblLable.text="process completed";

Add this in CodeBehind:
ScriptManager.RegisterStartupScript(this, GetType(), "Records Inserted Successfuly", "Showalert();", true);
JAVASCRIPT add this in source code (aspx):
function Showalert() {
alert('Records inserted Successfully!');
}
And do add using System.Web.UI;
OR
You can simply add a Label to the webform like this in aspx..
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
and in codebehind aspx.cs add ..
Labelname.Text = "whatever msg you wanna display."

Related

ASP.NET: Update ListView from CodeBehind

So there's a ListView element on my ASP.NET page that I need to be able to update from the code behind. To my understanding, Microsoft has prepared UpdatePanels and DataBindung for exactly such purpose, allowing me to "bind" the ListView's content to a property member in the code behind and promising to take care of updating the browser's view automatically (?) when the property changes.
However, only the initial load of items via GetStuff() works; I can see in the debug console that my timer keeps adding new elements to the List, but those never arrive in the browser's view. What am I missing?
In Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="myLittleProject.Default" %>
<%# Register Src="~/StuffListItemControl.ascx" TagPrefix="stf" TagName="StuffListItem" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<!-- some irrelevant stuff -->
</head>
<bod>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<!-- some irrelevant stuff -->
<asp:UpdatePanel runat="server" ID="StuffUpdatePanel" UpdateMode="Always">
<ContentTemplate>
<ul>
<asp:ListView ID="StuffBoundContent" runat="server">
<ItemTemplate>
<stf:StuffListItem runat="server" ID="StuffListItemControl" />
</ItemTemplate>
</asp:ListView>
</ul>
</ContentTemplate>
</asp:UpdatePanel>
<!-- some more irrelevant stuff -->
</form>
</body>
</html>
And in Default.aspx.cs:
using System.Collections.Generic;
namespace myLittleProject
{
public partial class Default : System.Web.UI.Page
{
public static List<Stuff> StuffContent;
protected void Page_Load(object sender, EventArgs e)
{
StuffContent = Stuff.GetStuff(); // returns a list of three elements from the database
System.Timers.Timer t = new System.Timers.Timer();
t.Interval = 3000;
t.Elapsed += T_Tick;
t.Enabled = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
StuffBoundContent.DataSource = StuffContent;
StuffBoundContent.DataBind();
}
private void T_Tick(object sender, EventArgs e)
{
StuffContent.Add(new Stuff(StuffContent.Count + 1, DateTime.Now.ToShortDateString(), new string[] { "what", "ever" }));
System.Diagnostics.Debug.WriteLine("[TIMER EVENT] StuffContent.Count = " + StuffContent.Count.ToString());
}
}
}
System.Timers.Timer does not work with a webpage. The reason that t is disposed after the page is sent to the client. Use a Timer control if you really want to use one.
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick"></asp:Timer>
And then you can update the ListView in Timer1_Tick.
protected void Timer1_Tick(object sender, EventArgs e)
{
//update the ListView
}
Place the Timer Control inside the UPdatePanel if you do not want a full postback when the timer is triggered.
Another thing to remember is that although you use an UpdatePanel, a complete page life cycle is triggered. So all other code you use in Page Load (and PrerRender) is executed even when only the ListView update is visible to the user. This could put a huge load on the server when an updatepanel is triggered every few seconds. Maybe better use Ajax.
PS you don't need to use Page_PreRender to bind data.

Dynamically change label text in aspx page without postback or page-load

I am currently in the process of creating an asp.net webforms site in c#.
My goal with this website is to be able to receive mqtt messages from a mqtt broker that I currently have running, and disply them on a simple website.
I currently have the communication up and running and can subscribe and receive messages just as I wish, but my problem is that after receiving the messages in my code-behind, I am not able to dynamically display them in my aspx! I am currently trying to display a value in an asp:label, and every time I receive a new value I would like to update the label-text to reflect this.
Again my code-behind is working as intended, but my problem seems to be that the messages from my mqtt broker is not causing a page-load or postback, which means that my aspx are not getting refreshed. I have tried to solve this using JavaScript, but this doesn't seem to work! Here is a simplified version of my code:
Aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="proof_of_concept.WebForm1" %>
<head runat="server">
<script type="text/javascript">
var jsVariable1;
function GetValues(){
var someVar1 = "<%=Variable1 %>";
if(someVar1 != null && someVar1 != jsVariable1){
jsVariable1 == someVar1;
$('#Label1').innerHTML = "Variable 1 =<br/>" + jsVariable1;
}
setTimeout(GetValues, 5000);
}
GetValues();
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container" id="container">
<img src="/Images/TestImage.jpg" style="width:100%;" />
<div class="position1">
<asp:Label ID="Label1" runat="server" Text="Var1: <br/> Value"></asp:Label>
</div>
</div>
</form>
</body>
.cs:
namespace proof_of_concept
{
public partial class WebForm1 : System.Web.UI.Page
{
private static MqttClient myClient;
public String Variable1 = "No data yet";
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
if (!IsPostBack)
{
//Initialize connection to the mqtt broker (with a hardcoded URL)
myClient = new MqttClient("myBrokerurl", 1883, false, null, null, 0, null, null);
//Connect to the broker with an autogenerated User-ID
myClient.Connect(Guid.NewGuid().ToString());
//Check if the connection was established
Debug.WriteLine("Client connected: " + myClient.IsConnected);
//Subscribe to a topic at the broker (Again in this example the topic has been hardcoded)
myClient.Subscribe(new string[] { "mySubscribedTopic/#" },
new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
//Sets up an eventhandler for received messages to the subscribed topic(s)
myClient.MqttMsgPublishReceived += myClient_MqttMsgPublishReceived;
}
}
protected void myClient_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
//Check if a message was received
Debug.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
variableSelector(e.Topic, Encoding.UTF8.GetString(e.Message));
}
protected void variableSelector(String topicString, String messageString)
{
if (topicString.Contains("var1") == true)
{
Variable1 = messageString;
//Databinding here was a test that didnt seem to do anything
Page.DataBind();
}
}
}
I am not sure if my JavaScript is relevant, but I wrote it as an attempted workaround to my problem (which is that the label-text is not getting updated when I receive new messages from my broker).
It seems to me that the Broker is sending messages to the server of device A and the client of your page is on machine B and you are trying to synchronize, if this is the case, update a database on the server and use something similar with my example.
In my example i will focus on "I have tried to solve this using javascript, but this doesnt seem to work!".
Either way, you have chosen the wrong technology to do this, WebForms will give you a lot of headache.
Use Asp.Net MVC ... will be much easier.
Page
<form id="form1" runat="server">
<asp:ScriptManager ID="MyScriptManager" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="MyUpdatePanel" runat="server">
<ContentTemplate>
<asp:Label ID="MyLabel" runat="server"> Postback number <%= Counter %></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Code-Behind
public partial class MyPage: System.Web.UI.Page
{
protected int Counter { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// MyUpdatePanel will perform a async post-back every 1000 milliseconds
int _newCounter;
var newCount = Request.Form["__EVENTARGUMENT"];
if (newCount != null)
{
if (int.TryParse(newCount, out _newCounter))
{
Counter = _newCounter;
}
}
return;
}
// Loading javascript that will trigger the postback
var _pageType = this.GetType();
var script =
string.Concat(
"var counter = 0;",
"setInterval(function() { ",
"__doPostBack('", MyUpdatePanel.UniqueID, "', counter);",
"counter++; }, 1000);");
ClientScript.RegisterStartupScript(_pageType, "AutoPostBackScript", script, true);
}
}

System.Web.UI.Timer Refreshes Page when Enabled

During the page_load, I disable the timer. When I pressed Button1, I enable the timer, but the page refreshes. Therefore, it never reaches the timer_tick1. I need to show a popup after a certain amount of time a button is clicked. How do I prevent the refresh from happening?
Alerts Class
public static class Alert
{
public static void Show(string message, Page page)
{
// replaces the quotations to follow the script syntax
// quotations are interpretated as \\' in script code
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
// Gets the executing web page
Page tempPage = page;
// Checks if the handler is a Page and that the script isn't already on the page
if (tempPage != null & !tempPage.ClientScript.IsClientScriptBlockRegistered("alert"))
{
tempPage.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); // this isn't working, but it works on a button click event.
}
}
}
Page Class
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{ // i added a breakpoint here. It doesn't even pass through.
Alert.Show("hehehehe", this); //PopUp Shows up.
Timer1.Enabled = false; //Cancels Timer
Label1.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if update panel reloads
}
protected void Button1_Click1(object sender, EventArgs e)
{
Timer1.Enabled = true; //Starts Timer. It seems to refresh the page.
}
}
script
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" %>
<%# Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function delayer() {
setTimeout (function () {ShowPopUp()}, 15000);
}
delayer();
</script>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000" Enabled="true">
</asp:Timer>
<asp:Label ID="Label1" runat="server" Text="PanelNotRefreshedYet"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="ShowPopUp();" />
</form>
</body>
</html>
I think you're confused. Timer1 is a server side control. So it will fire on the server side, if you're still processing the page, that is, and will have no effect on the client side. By the time it fires in your code, the page has likely already rendered so you'll see no effect from that Timer1 object's Timer1_Tick event. Since the page has completed rendering, you can't inject new JavaScript, modify the page, or anything like that. Remember that web development is a disconnected thing. You send a request, you get a response. There are no events by nature of the web. There are libraries out there for triggering events and such but I think that's way beyond what you're trying to achieve.
For client side "timer" you need to use JavaScript setTimeout method, which you have verified as working and is the proper way for you to achieve the delay you're looking to implement.
setTimeout (function () {ShowPopUp()}, 15000);
If you still want to do it in your Alert class, then get rid of Timer1 and have your Alert class inject the timeout in JavaScript:
protected void Button1_Click1(object sender, EventArgs e)
{
Alert.Show("He heee", this);
}
And in Alert, change your script to:
string script = "<script type=\"text/javascript\">setTimeout(function() {alert('" + cleanMessage + "');}, 15000);</script>";
Your button is doing a postback, so yes the page will be refreshed and your Page_Load function will run again. You should test for this using the IsPostback property.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
You might want to look at showing the alert using JavaScript on the page rather than running it server side tho.
<script type="text/javascript">
function showPopup()
{
alert("Hey, click something already");
}
function delayer() {
setTimeout (showPopUp, 15000);
}
delayer();
</script>
Just put your message like this. Probably easier if your logic is simple.

Simple chat application signal r

I am trying to modify a simply chat application for learning purposes. The only change i made was to change a button to a serverside control. The problem i have is that the first time i broadcast a message, it works, and the Clients.addNotification(msg) is called. Yet the second time, although the javascript works, at its final step, the javascript undos all the changes and the Clients.addNotification(..) is never called :/ It only works for the first time! I have to rebuild my project to see it working again (a page refresh won't work)
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.addNotification(message);
}
}
My aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Client1.aspx.cs" Inherits="WebApplication1.WorkingWithHubs.Client1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="../Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addNotification = function (message) {
$('#messages').append('<li>' + message + '</li>');
var labelValue = $('#total').val();
$('#total').val(parseInt(labelValue, 10) + 1);
};
$("#btn").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server" />
<div>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<input type="text" id="msg" runat="server" />
<asp:Button ID="btn" runat="server" Text="BroadCast" OnClick="btn_click" ClientIDMode="static" />
<input type="text" id="total" value="0" />
<ul id="messages">
</ul>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
My code behind:
public partial class Client1 : System.Web.UI.Page
{
public List<String> list = new List<String>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_click(object sender, EventArgs e)
{
list.Add(msg.Value);
}
}
Once this example work I will shift the code to another application I am working on so that notifications can be immediately pushed to all clients.
I am a very beginner and I would appreciate all your help! Thanks a lot guys!
EDIT:
when checking out the network tab (on my chrome), for the first click I get a 'send' (signalR) and Client1.aspx and all works fine, for the second click onwards, I only get Client1.aspx, and no send whatsoever :/
for a quick and dirty solution, just place the update panel ONLY around the button, and remove
$("#btn").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
and instead, insert the following in the beginning
$('#form1').delegate('#btn', 'click', function () {
chat.send($('#msg').val());
});
Thanks to my friends shifty and red_square :)

clear FileUpload object on c#

i"m using asp.net FileUpload , after user input file he click on save button
in the c# i have this function
protected void btnUploadImages_Click(object sender, EventArgs e)
{
SaveImages(FileUpload1, "", returnAlbumId, out returnPhotoId);
}
this function save the image from the FileUpload1 so far all work as it"s should
but after the postback when i push the refresh button on the page i"m go to this function again , SaveImages function save the same image again .
the FileUpload1 didn't clear after the postback
thanks
Even i got the Same Problem I have resolved like Below.
After uploading the File If you Redirect to same page or some other page in your project. After Redirection Response will not be there once you redirected.
In My ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm.aspx.cs" Inherits="WebApplication.WebForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
In My Code Behind
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("~");
path = path + FileUpload1.FileName;
FileUpload1.SaveAs(path);
Response.Redirect("WebForm.aspx"); // Responce will be cleared. This Redirection will do the Trick
//Put the debugger and check it will work
}
}
Here, to show the success and error messages try to use sessions.

Categories

Resources