I am using asyncupload control of AjaxControlToolkit and I want to check the file to be uploding is already exists or
not on server.
How we can do this?
Please help me out.
<!-- Client side code for control-->
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
<!-- Control Code in aspx-->
<tr>
<td></td>
<td>
<cc1:AsyncFileUpload ID="FileUpload2" Width="265px" runat="server"
OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red"
ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../../images/indicator.gif" align="absmiddle" alt="loading" />
</asp:Label>
<asp:HiddenField ID="hdnField" runat="server" value=""/>
</td>
</tr>
//.CS Code for ayncupload control
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath="C:\Documents\temp.txt"
if(File.Exists(filePath))
{
hdnField.value="1";//Not able to access this value
}
}
Thanks!!
you just need to set your hidden field value at client side script.
See I have made little changes in your server side code:
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath = "C:\\Documents\\temp.txt";
string hiddenValue = "0";
if (File.Exists(filePath))
{
hiddenValue = "1";
}
//This script will set required value for hidden field.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SetHiddenField", String.Format("top.$get('{0}').value = '{1}'", hdnField.ClientID, hiddenValue), true);
}
Make changes in your script location as follow:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
Check if the file exists using the following:-
File.Exists
You can compare based on the filename.
Related
can you help me with something i struggle for 4 days, button event doesn't fire :( In the MasterPage i use this to add control
<Login:UserLogin runat="server" ID="UserLogin" EnableViewState="false" > </Login:UserLogin>
and the control is this
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserLogin.ascx.cs" Inherits="BookApartmentsPortal.controls.UserLogin" %>
<%# Register TagPrefix="MultiLanguage" Namespace="MultiLanguage.multilanguage" %>
<%--
<script type="text/javascript">
function DeleteKartItems() {
var inputEmail = $("#ctl00_UserLogin_txtEmailVal").val();
var user = {
email: "s.krastanov",
password: "1"
};
$.ajax({
type: "POST",
url: 'PublicDefault.aspx/Getvalues',
data: JSON.stringify({ person: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
$("#ctl00_PublicDefault_buttonLog").Click();
}
</script>--%>
<h3>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral13" runat="server" Resource="669" />
</h3>
<form action="/" method="POST" id="formasd">
<div class="">
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral14" runat="server" Resource="858" />
<%--user name input field--%>
<input type="text" class="modal-input" runat="server" size="20" id="txtEmailVal"
name="txtEmail" />
<%-- <asp:TextBox runat="server" CssClass="modal-input" ID="txtEmailVal" ></asp:TextBox> --%>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral21" runat="server" Resource="205" />
<%--password input field--%>
<%--<input type="password" class="modal-input" runat="server" size="1" maxlength="20" id="txtPassword" />--%>
<asp:TextBox runat="server" CssClass="modal-input" TextMode="Password" ID="txtPassword"
MaxLength="20" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label1" runat="server">
</asp:Label>
<asp:Panel ID="panelLogin" runat="server" DefaultButton="btnLogon">
<asp:Button runat="server" ID="btnLogon" Text="Click" CssClass="login-btn" OnClick="btnLogon_Click"></asp:Button>
</asp:Panel>
<%-- <button class="login-btn" runat="server" id="btnLogon" name="btnLogon" onclick="DeleteKartItems()">
<i class="fa fa-paper-plane"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
</button>--%>
<div id="divResult">
</div>
</div>
</form>
<asp:HyperLink ID="LoginFB" Target="_blank" runat="server" CssClass="btn btn-block btn-social btn-facebook fb-login">
<i class="fa fa-facebook"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral27" runat="server" Resource="1306" /></asp:HyperLink>
<a href="#lost-pass" class="button-modal various-login"><i class="fa fa-lock"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral22" runat="server" Resource="164" /></a>
<a href="#reg" class="button-modal reg"><i class="fa fa-user"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral23" runat="server" Resource="1271" /></a>
Backend is this:
public partial class UserLogin : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
Response.Write("you click");
}
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
LoginFB.NavigateUrl = "https://www.facebook.com/v2.0/dialog/oauth/?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&redirect_uri=http://" + ConfigurationManager.AppSettings["URL"].ToString() + "/Publish/UserFB.aspx&response_type=code&state=1";
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
//btnLogon.ServerClick += new EventHandler(btnLogon_Click);
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
//btnLogon.ServerClick += new CommandEventHandler(btnLogonClick);
// btnLogon.Command += btnLogon_Click;
}
public void btnLogon_Click(object sender, EventArgs e)
{
Label1.Text = "submit button is press";
// if (LoginSet == false )
// {
string Name = txtPassword.Text;
string Dev = txtEmailVal.Value;
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal.Value.Trim(), txtPassword.Text.Trim(), true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now;
FormsAuthentication.RedirectFromLoginPage(txtEmailVal.Value.Trim(), false);
Session["LoginUserName"] = txtEmailVal.Value.Trim();
// _loginSet = true;
}
else
{
// _loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
// _loginSet = false;
}
//}
}
}
This control is for login form and i just cant get the values from input boxes because event don't trigger. One idea was to make AJAX post to static method but after that i cant make new session with this variables.
I try everything and this button just doesn't fire the event. I don't know what to do next, can you help me.
Ok after one more day of struggle, i manage to make a little walk around path:
In the first step i made a Button to fire event (javascript function) and make cookie, after that i make click event for actual asp:Button :
<script type="text/javascript">
function LoginClicked() {
var inputEmail = $("#txtEmail").val();
var inputPass = $("#txtPassword").val();
if(inputEmail != "" && inputPass != ""){
var userSet = inputEmail + "&" + inputPass;
setCookie("UserSettings", userSet, 1);
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
$("#ctl00_UserLogin_btnLogon").click();
}
}
</script>
And here is the buttons:
<asp:Panel runat="server" ID="panekl">
<asp:Button runat="server" ID="btnLogon" UseSubmitBehavior="false" CssClass="no-display" ></asp:Button>
</asp:Panel>
<button class="login-btn" id="btnLogon1" name="btnLogon1" onclick="LoginClicked()">
<i class="fa fa-paper-plane"></i><MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
And in the back end, i get the cookie, split it, and check for validation:
public void btnLogon_Click()
{
if (LoginSet == false )
{
string[] txtSome = Request.Cookies["UserSettings"].Value.Split('&');
if (Request.Cookies["UserSettings"] != null && txtEmailVal != "" && txtPassword != "")
{
txtEmailVal = txtSome[0].Trim();
txtPassword = txtSome[1].Trim();
}
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal, txtPassword, true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Session["IdUserLogin"] = txtEmailVal;
_loginSet = true;
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Label1.Text = "submit button is press";
}
else
{
_loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
_loginSet = false;
}
}
}
This was the only way i figured out to get values from the control.
I have a page SendResults.aspx that holds a button and a ListView with ItemTemplate set to a user control (3 labels and 2 textboxes) that gets it's data from a matching object.
On Page_Load I fill the List with data (this works well).
When the button is clicked I want to take the user input in the user-control's textboxes and do something with it.
However I always get the initial value and not the updated one.
Here is the code:
The user-control "MatchControl.ascx"
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MatchControl.ascx.cs" Inherits="TotoMondeal.Controls.MatchControl" %>
<div>
<asp:Image ID="Team1FlagImage" runat="server" />
<asp:Label ID="Team1Label" runat="server" Width="150px"></asp:Label>
<asp:TextBox ID="Team1TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px" AutoPostBack="true" OnTextChanged="Team1TextBox_TextChanged"></asp:TextBox>
<asp:Label ID="Colon" runat="server" Font-Size="XX-Large" Text=":"></asp:Label>
<asp:TextBox ID="Team2TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px"></asp:TextBox>
<asp:Label ID="Team2Label" runat="server" Width="150px"></asp:Label>
<asp:Image ID="Team2FlagImage" runat="server" />
</div>
The user-control code-behind:
public partial class MatchControl : System.Web.UI.UserControl
{
public Match Match
{
get
{
object obj = ViewState["Match"];
return (obj == null) ? new Match() : (Match)obj;
}
set
{
ViewState["Match"] = value;
}
}
public string Team1Score
{
get { return Team1TextBox.Text; }
set { Team1TextBox.Text = value; }
}
public string Team2Score
{
get { return Team2TextBox.Text; }
set { Team2TextBox.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
Team1Label.Text = Match.Team1Name;
Team2Label.Text = Match.Team2Name;
Team1TextBox.Text = Match.Team1Score.ToString();
Team2TextBox.Text = Match.Team2Score.ToString();
Team1TextBox.Enabled = Match.EnableTextBox;
Team2TextBox.Enabled = Match.EnableTextBox;
Team1FlagImage.ImageUrl = #"~/FlagImages/" +Match.Team1Name + ".png";
Team2FlagImage.ImageUrl = #"~/FlagImages/" + Match.Team2Name + ".png";
}
protected void Team1TextBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
try
{
Match updatedMatch = new Match()
{
MatchId = Match.MatchId,
MatchDate = Match.MatchDate,
Result = Match.Result,
Team1Name = Match.Team1Name,
Team1Score = Convert.ToInt32(textBox.Text),
Team2Name = Match.Team2Name,
Team2Score = Match.Team2Score,
EnableTextBox = Match.EnableTextBox
};
Match = updatedMatch;
}
catch (Exception ex)
{
throw ex;
}
}
}
The SendResults.aspx:
<%# Page Title="שלח תוצאות" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SendResults.aspx.cs" Inherits="TotoMondeal.SendResults" %>
<%# Register TagPrefix="TOTO" TagName="MatchControl" Src="~/Controls/MatchControl.ascx" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2>
<div class="jumbotron">
<asp:ListView ID="TodayMatchesList" runat="server">
<ItemTemplate>
<TOTO:MatchControl ID="MatchControl" Match="<%# Container.DataItem %>" runat="server" />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</asp:Content>
the SendResults code-behind:
public partial class SendResults : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
foreach (Match match in matches)
{
match.EnableTextBox = true;
}
this.TodayMatchesList.DataSource = matches;
this.TodayMatchesList.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < TodayMatchesList.Items.Count; i++)
{
MatchControl match = (MatchControl)TodayMatchesList.Items[i].FindControl("MatchControl");
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
}
}
}
The problem is that in this line:
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
I always get the initial value from the database, and not the user updated input.
Please help I'm new at this.
Your List is getting overwritten every time you post back. Add this in Page_Load for SendResults
if ( !Page.IsPostBack )
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
...etc...
}
In addition to checking IsPostBack you need to handle saving your control properties in the ViewState. As suggested here: User control (ascx) and properties
Example from post:
public string Title {
get { return Convert.ToString(ViewState["Title"]); }
set { ViewState["Title"] = value; }
}
You would do this in your control class.
I'm am trying to show video from IP cam in my C# WinForms app. I need to show only video, not camera menu and such. I was thinking of using WebBrowser control and somehow change parameters. If you have any suggestions for this approach or any other please help. I don't know where to start.
This is default IP cam page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<title>IP CAMERA</title>
<link href="style/css.css" rel="stylesheet" type="text/css">
<SCRIPT language="JavaScript" src="js/localization.js"></SCRIPT>
<SCRIPT language="JavaScript" src="js/commfunc.js"></SCRIPT>
<SCRIPT language="JavaScript" src="js/axobjdef.js"></SCRIPT>
<script language="JavaScript" src="js/slider.js"></script>
<SCRIPT language="JavaScript" src="js/vlc.js"></SCRIPT>
<SCRIPT language="Javascript" src="js/plugin_detect.js"></SCRIPT>
<style type="text/css">
.statusBarL{
background-image:url("./style/image/vlc/img_Liveview_L.png");
background-repeat:no-repeat;
height:25px;
width:7px;
}
.statusBarM{
background-image:url("./style/image/vlc/img_Liveview_M.png");
background-repeat: repeat-x;
height:25px;
overflow:hidden;
}
.statusBarR{
background-image:url("./style/image/vlc/img_Liveview_R.png");
background-repeat:no-repeat;
height:25px;
width:7px;
}
.live_btn{
display:block;
float:left;
}
</style>
<script type="text/JavaScript">
<!--
var PLUGIN_LANG=0;
//var INITMODE = "Player";
var VIEW_SIZE = getViewSize();
var PROTOCOL_TYPE=getProtocol();
var INITMODE = "none";
var CAPTEXT = "Live View";
var STATUSBAR = 1;
var TOOLBAR = 1;
var CONTEXTMENU = 0;
var AUTOSTART=1;
var TOOLBARCONF = "stream+rec+mic+zoom+time";
var CheckMac = (navigator.platform.toLowerCase().indexOf("mac") < 0) ? false : true;
GetDeviceInfo_A('view','General.Network.RTSP.Enabled&group=General.Network.RTP.R0.Multicast');
var RTSPEnabled = GetQueryVariable('General.Network.RTSP.Enabled');
var TypeIndex = getCookies("TypeIdx");
if(TypeIndex == null)
{
if(getOs().indexOf("IE") >= 0)
{
TypeIndex = "ocx";
}else{
if(CheckMac)
{
TypeIndex = "quicktime";
}else{
TypeIndex = "vlc";
}
}
}
GetDeviceInfo_A('view','Image');
switch(getVideoFmt())
{
default:
case '1':
CHANNEL = 1;
break;
case '2':
if(RTSPEnabled == "1")
{
CHANNEL = 1;
setVideoFmt(1);
}else{
CHANNEL = 2;
}
break;
}
if(CheckMac && TypeIndex != "jpg")
{
TypeIndex = "quicktime";
}
function mouseOver(index)
{
if(index=="Liveview_Play" || index=="Liveview_Sound" ||
index=="Liveview_Talk" || index=="Liveview_Record")
{
EID(index).src = eval("'./style/image/vlc/btn_Liveview_"+EID(index).title+"_h.png'");
}else{
EID(index).src = eval("'./style/image/vlc/btn_"+index+"_h.png'");
}
}
function mouseOut(index)
{
if(index=="Liveview_Play" || index=="Liveview_Sound" ||
index=="Liveview_Talk" || index=="Liveview_Record")
{
EID(index).src = eval("'./style/image/vlc/btn_Liveview_"+EID(index).title+"_e.png'");
}else{
EID(index).src = eval("'./style/image/vlc/btn_"+index+"_e.png'");
}
}
function mouseDown(index)
{
if(index=="Liveview_Play" || index=="Liveview_Sound" ||
index=="Liveview_Talk" || index=="Liveview_Record")
{
EID(index).src = eval("'./style/image/vlc/btn_Liveview_"+EID(index).title+"_p.png'");
}else{
EID(index).src = eval("'./style/image/vlc/btn_"+index+"_p.png'");
}
}
function mouseUp(index)
{
switch(index)
{
case 'Play':
EID("Liveview_Play").title = "Pause";
mouseOver("Liveview_Play");
break;
case 'Pause':
EID("Liveview_Play").title = "Play";
mouseOver("Liveview_Play");
break;
case 'Stop':
mouseOver("Liveview_Stop");
EID("Liveview_Play").title = "Play";
mouseOut("Liveview_Play");
break;
case 'Sound':
EID("Liveview_Sound").title = "SoundMute";
mouseOver("Liveview_Sound");
break;
case 'SoundMute':
EID("Liveview_Sound").title = "Sound";
mouseOver("Liveview_Sound");
break;
case 'Talk':
EID("Liveview_Talk").title = "TalkMute";
break;
case 'TalkMute':
EID("Liveview_Talk").title = "Talk";
break;
default:
}
}
function changeVolume(value)
{
if(value != 0 && EID("Liveview_Sound").title != "Sound")
{
EID("Liveview_Sound").title = "Sound";
VLC_DoAct("Sound");
mouseOut("Liveview_Sound");
}
A_SLIDERS[0].f_setValue(value);
VLC_DoUpdateVolume(value);
}
var VLC_Version = PluginDetect.getVersion("vlc");
var VLC_Polling_Timer = null;
function onLoad()
{
if( TypeIndex == "vlc" && navigator.platform.toLowerCase().indexOf("mac") < 0 )
{
if(VLC_Version != null)
{
EShow("vlc_control","");
var i=0;
while(EID("statusBor"+i))
{
EID("statusBor"+i).style.borderRight = "1px solid #000";
i++;
}
EShow("table1","");
EShow("table2","none");
VLC_Polling_Timer = setTimeout("CheckVlcPlaying()",5000);
}else{
EShow("table1","none");
EShow("table2","");
}
}else{
EShow("table1","");
EShow("table2","none");
if( TypeIndex == "ocx")
{
AxMediaControl.Play(1);
}
}
}
function CheckVlcPlaying()
{
if(VLC_Polling_Timer != null)
{
clearTimeout(VLC_Polling_Timer);
}
var vlc = getVLC("vlc");
if( vlc )
{
if(VLC_Pause_Flag == false && EID("Liveview_Play").title == "Pause")
{
if(!vlc.playlist.isPlaying)
{
window.location.reload(true);
}
}
}
VLC_Polling_Timer = setTimeout("CheckVlcPlaying()",5000);
}
function onUnload()
{
if(TypeIndex == "ocx")
{
onAxobjUnload();
}else if(TypeIndex == "vlc"){
if(VLC_Version != null)
{
VLC_DoStop();
}
}
}
//-->
</script>
</head>
<body leftmargin="0" topmargin="0" onLoad="onLoad()" onUnload="onUnload()">
<table id="table1" width="640" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
</td>
</tr>
<tr>
<td height="450"> </td>
<td align="center" valign="top">
<script type="text/JavaScript">
<!--
GetDeviceInfo_A('view','Image');
var Codec;
if(CHANNEL == 3) CHANNEL = 1;
switch(CHANNEL)
{
default:
case 1:
Codec = "MPEG4";
break;
case 2:
Codec = "MJPEG";
break;
}
var VideoPath;
if(Codec == "MPEG4")
{
VideoPath = "video.mp4";
}else if(Codec == "MJPEG"){
VideoPath = "video.mjpg";
}
if(CheckMac)
{
if(TypeIndex == "quicktime")
{
var normalSize = VIEW_SIZE;
if(normalSize == null)
{
normalSize = "Medium";
setViewSize(normalSize);
}
if(normalSize == "Medium")
{
normalSize = "320x240";
}else if(normalSize == "Large"){
normalSize = "640x480";
}
if(normalSize.indexOf("x")>=0)
{
resolutionW=normalSize.slice(0,normalSize.indexOf("x"));
resolutionH=normalSize.slice(normalSize.indexOf("x")+1,normalSize.length);
}
document.open();
document.write("<embed SCALE=\"ToFit\" width=\"" + resolutionW + "\" height=\"" + resolutionH + "\"" +
" type=\"video/quicktime\" qtsrc=\"rtsp://" + location.hostname + "/" + VideoPath + "\"" +
" qtsrcdontusebrowser src=\"quicktime.mov\" autoplay=\"true\" controller=\"true\"\>");
document.close();
}else{
CHANNEL = 3;
Viewer();
}
}else{
if(TypeIndex != "vlc")
{
if(TypeIndex == "jpg")
{
CHANNEL = 3;
}
Viewer();
}else{
if(VLC_Version != null)
{
VLC_Viewer(VideoPath);
}
}
}
//-->
</script>
<br>
<script FOR="AxMediaControl" EVENT="OnConnectStateNotify(id, msg)">
if(navigator.appName.toLowerCase().indexOf("microsoft internet explorer") >= 0)
{
if(msg=="video lost")
{
window.top.leftFrame.location.reload();
window.top.mainFrame.location.reload();
}
else if(msg=="full connect")
{
alert(loadLangString("L_Warn_FullConnection",false));
}
else if(msg=="mic occupy")
{
alert(loadLangString("L_MicOccupy",false));
}
}
</script>
</div>
</td>
</tr>
<tr style="height:10px;"></tr>
<tr id="vlc_control" style="display:none;">
<td></td>
<td align="center">
<table cellSpacing="0" cellPadding="0" border="0" bordercolor="#000" style="table-layout:fixed;">
<tr id="statusBar">
<td class="statusBarL"></td>
<td id="statusBor0" class="statusBarM" style="width:80px;">
<div class="live_btn" style="padding:2px 7px 0px 7px;" id="statusBar0">
<img id="Liveview_Play" src="./style/image/vlc/btn_Liveview_Pause_e.png" title="Pause"
style="cursor:pointer"
onMouseOver="mouseOver(this.id)"
onMouseOut="mouseOut(this.id)"
onMouseDown="mouseDown(this.id)"
onMouseUp="mouseUp(this.title)"
onClick="VLC_DoAct(this.title)">
</div>
<div class="live_btn" style="padding:2px 14px 0px 7px;" id="statusBar1">
<img id="Liveview_Stop" src="./style/image/vlc/btn_Liveview_Stop_e.png" title="Stop"
style="cursor:pointer"
onMouseOver="mouseOver(this.id)"
onMouseOut="mouseOut(this.id)"
onMouseDown="mouseDown(this.id)"
onMouseUp="mouseUp(this.title)"
onClick="VLC_DoAct(this.title)">
</div>
</td>
<td id="statusBor1" class="statusBarM" style="width:43px;"> <!-- 87 -->
<!--
<div class="live_btn" style="padding:2px 7px 0px 14px;" id="statusBar2">
<img id="Liveview_Record" src="./style/image/vlc/btn_Liveview_Record_e.png" title="Record"
style="cursor:pointer"
onMouseOver="mouseOver(this.id)"
onMouseOut="mouseOut(this.id)"
onMouseDown="mouseDown(this.id)"
onMouseUp="mouseOver(this.id)"
onClick="VLC_DoAct(this.title)">
</div>
-->
<div class="live_btn" style="padding:2px 14px 0px 14px;" id="statusBar3"> <!-- 2 14 0 7 -->
<img id="Liveview_Snapshot" src="./style/image/vlc/btn_Liveview_Snapshot_e.png" title="Snapshot"
style="cursor:pointer"
onMouseOver="mouseOver(this.id)"
onMouseOut="mouseOut(this.id)"
onMouseDown="mouseDown(this.id)"
onMouseUp="mouseOver(this.id)"
onClick="VLC_DoAct(this.title)">
</div>
</td>
<form name="form1">
<td class="statusBarM" style="width:150px;"> <!-- 234 -->
<div class="live_btn" style="padding:1px 0px 0px 14px;" id="statusBar5"> <!-- 1 7 0 14 -->
<img id="Liveview_Sound" src="./style/image/vlc/btn_Liveview_Sound_e.png" title="Sound"
style="cursor:pointer;"
onMouseOver="mouseOver(this.id)"
onMouseOut="mouseOut(this.id)"
onMouseDown="mouseDown(this.id)"
onMouseUp="mouseUp(this.title)"
onClick="VLC_DoAct(this.title)">
</div>
<div id="soundSlider" class="divStyle" style="padding-top:5px;margin-left:40px;">
<script style="text/javascript">
<!--
var A_TPL1h = {
'b_vertical' : false,'b_watch': true,'n_controlWidth': 105,'n_controlHeight': 10,
'n_sliderWidth': 5,'n_sliderHeight': 12,'n_pathLeft' : 0,'n_pathTop' : 1,'n_pathLength' : 100,
's_imgControl': 'style/image/blueh_bg.gif','s_imgSlider': 'style/image/blueh_sl.gif','s_imgAlt': '','n_zIndex': 1
}
var A_INIT1h = {
's_form' : 0,'s_name': 'sliderValue1h','n_minValue' : 0,'n_maxValue' : 100,'n_value' : 30,'n_step' : 1
}
new slider(A_INIT1h, A_TPL1h, changeVolume);
//-->
</script>
<input type="hidden" name="soundSlider" id="sliderValue1h" size="2" readonly>
</div>
<!--
<div class="live_btn" style="padding:1px 7px 0px 14px;" id="statusBar6">
<img id="Liveview_Talk" src="./style/image/vlc/btn_Liveview_TalkMute_e.png" title="TalkMute"
style="cursor:pointer"
onMouseOver="mouseOver(this.id)"
onMouseOut="mouseOut(this.id)"
onMouseDown="mouseDown(this.id)"
onMouseUp="mouseUp(this.title)"
onClick="VLC_DoAct(this.title)">
</div>
<div id="talkSlider" class="divStyle" style=""></div>
-->
</td>
</form>
<!--
<td class="statusBarM" style="width:44px">
<div class="live_btn" style="padding:2px 7px 0px 14px;" id="statusBar7">
<img id="Liveview_Fullscreen"
src="./style/image/vlc/btn_Liveview_Fullscreen_e.png" title="Fullscreen"
style="cursor:pointer"
onMouseOver="mouseOver(this.id)"
onMouseOut="mouseOut(this.id)"
onMouseDown="mouseDown(this.id)"
onMouseUp="mouseOver(this.id)"
onClick="VLC_DoAct(this.title)">
</div>
</td>
-->
<td class="statusBarR"></td>
</tr>
</table>
</td>
</tr>
</table>
<table id="table2" style="display:none;" height="100%" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td>
<u><a id="vlc_plugin_help" href="./vlc_help.htm" target="blank" style="color:#00000;">Install VLC plugin to watch streaming.</a></u>
</td>
</tr>
</table>
</body>
<script type="text/JavaScript">
<!--
StyleCustomize("main");
//-->
</script>
</html>
And here is .NET 3.5 solution from my friend.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;
namespace kamera
{
public partial class Form1 : Form
{
//private static String imageUrl = "http://10.10.10.1/now.jpg";
private static String imageUrl=null;
private static Thread t ;
private static Image webImage;
private static List<String> kamere;
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
private static int intervalOsvezevanja=3000; //3 sekunde osveževanja
public Form1()
{
InitializeComponent();
////timer k pokliče funkcijo vsake 3 sekunde
//AutoResetEvent autoEvent = new AutoResetEvent(false);
//TimerCallback tcb = updatePicture;
//System.Threading.Timer stateTimer = new System.Threading.Timer(tcb, autoEvent, 0, 200);
t = new Thread(updatePicture);
t.IsBackground = true;
t.Start();
timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
timer.Interval = (intervalOsvezevanja) ; // Timer will tick every 0.05 seconds
timer.Enabled = true; // Enable the timer
timer.Start(); // Start the timer
//skrijemo formo za dodajanje kamer
panelDodajKamero.Hide();
//inicializacija
kamere = new List<String>();
tbNaslovKamere.Text = "cam-kk-";
preberiDatoteko();
}
void timer_Tick(object sender, EventArgs e)
{
pictureBox1.Image = webImage;
}
~Form1() {
//t.Join();
t.Abort();
timer.Stop();
timer.Dispose();
}
private void updatePicture(object stateInfo)
{
while (true)
{
if (imageUrl != null)
{
try
{
WebRequest requestPic = WebRequest.Create(imageUrl);
WebResponse responsePic = requestPic.GetResponse();
webImage = Image.FromStream(responsePic.GetResponseStream());
//webImage.Save("C:\\Users\\Public\\kamera\\kamera" + fileName + ".jpg");
}
catch{}
}
Thread.Sleep(intervalOsvezevanja);
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (menuStrip1.Visible)
{
menuStrip1.Hide();
}
else
{
menuStrip1.Show();
}
}
private void menjajKamero(String camAddr)
{
if (camAddr.Contains("http"))
{
imageUrl = camAddr;
}
else
{
imageUrl = "http://" + camAddr + "/now.jpg"; //link to http://10.10.10.1now.jpg camera live image.
}
}
private void btDodajKamero_Click(object sender, EventArgs e)
{
String webAddres;
if (tbNaslovKamere.Text.Contains("http"))
{
webAddres = tbNaslovKamere.Text;
}
else
{
webAddres = "http://" + tbNaslovKamere.Text + "/now.jpg";
}
if (RemoteFileExists(webAddres))
{
if (!kamere.Contains(tbNaslovKamere.Text) && !kamere.Contains(webAddres))
{
kamere.Add(tbNaslovKamere.Text);
//kamere.Add(webAddres);
}
menjajKamero(tbNaslovKamere.Text);
//menjajKamero(webAddres);
panelDodajKamero.Hide();
izpisKamer();
tbNaslovKamere.Text = "cam-kk-";
}
else
{
MessageBox.Show("Ne najdem Kamere");
}
}
private void dodajKameroToolStripMenuItem_Click(object sender, EventArgs e)
{
panelDodajKamero.Show();
}
private void izpisKamer()
{
//zanka ki odstrani vse prej dodane kamere
textBox1.Text = kamereToolStripMenuItem.DropDownItems.Count.ToString();
foreach (String kamera in kamere)
{
kamereToolStripMenuItem.DropDownItems.RemoveByKey(kamera);
}
System.IO.StreamWriter file = new System.IO.StreamWriter(System.Environment.CurrentDirectory + "\\kamere.txt");
foreach (String kamera in kamere)
{
ToolStripDropDownButton btTemp = new ToolStripDropDownButton(kamera, null, kameraOnClick, kamera);
file.WriteLine(kamera);
//dodamo trenutno kamero, ki je v kamerah.txt
kamereToolStripMenuItem.DropDownItems.Add(btTemp);
}
file.Dispose();
file.Close();
}
private void kameraOnClick(object sender, EventArgs e)
{
//tbNaslovKamere.Text+=sender.ToString();
imageUrl = "http://" + sender.ToString() + "/now.jpg";
}
private void izhodToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void preberiDatoteko()
{
String vrstica;
// Read the file as one string.
if (File.Exists(System.Environment.CurrentDirectory + "\\kamere.txt"))
{
kamere = new List<String>();
StreamReader myFile = new StreamReader(System.Environment.CurrentDirectory + "\\kamere.txt");
while ((vrstica = myFile.ReadLine()) != null)
{
//zapis v list
kamere.Add(vrstica);
//doda v meni
ToolStripDropDownButton btTemp = new ToolStripDropDownButton(vrstica, null, kameraOnClick, vrstica);
kamereToolStripMenuItem.DropDownItems.Add(btTemp);
}
myFile.Close();
}
}
private void menuPobrisiKamere()
{
foreach (String kamera in kamere)
{
kamereToolStripMenuItem.DropDownItems.RemoveByKey(kamera);
}
kamere = new List<String>();
}
private void odpriToolStripMenuItem_Click(object sender, EventArgs e)
{
// Create an instance of the open file dialog box.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// Set filter options and filter index.
openFileDialog1.Filter = "Text Files (.txt)|*.txt";
openFileDialog1.FilterIndex = 1;
//openFileDialog1.Multiselect = true;
// Call the ShowDialog method to show the dialog box.
DialogResult userClickedOK = openFileDialog1.ShowDialog();
//tbNaslovKamere.Text = userClickedOK.ToString();
// Process input if the user clicked OK.
if (userClickedOK.ToString().Equals("OK"))
{
menuPobrisiKamere();
String vrstica;
// Open the selected file to read.
System.IO.Stream fileStream = openFileDialog1.OpenFile();
kamere = new List<String>();
StreamReader myFile = new StreamReader(fileStream);
while ((vrstica = myFile.ReadLine()) != null)
{
//zapis v list
kamere.Add(vrstica);
//doda v meni
ToolStripDropDownButton btTemp = new ToolStripDropDownButton(vrstica, null, kameraOnClick, vrstica);
kamereToolStripMenuItem.DropDownItems.Add(btTemp);
}
myFile.Dispose();
myFile.Close();
fileStream.Dispose();
fileStream.Close();
myFile.Close();
fileStream.Close();
}
}
private void pobrišiKamereToolStripMenuItem_Click(object sender, EventArgs e)
{
menuPobrisiKamere();
}
private void zbrišiShranjeneKamereToolStripMenuItem_Click(object sender, EventArgs e)
{
menuPobrisiKamere();
System.IO.StreamWriter file = new System.IO.StreamWriter(System.Environment.CurrentDirectory + "\\kamere.txt");
file.Dispose();
file.Close();
}
private void pictureBox1_DoubleClick(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.Size = new Size(100, frm1.Size.Height);
}
private bool RemoteFileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TRUE if the Status code == 200
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
}
}
Have you any Code from your C# Application?
First of all i would look at this Part of your Code:
document.open();
document.write("<embed SCALE=\"ToFit\" width=\"" + resolutionW + "\" height=\"" + resolutionH + "\"" +
" type=\"video/quicktime\" qtsrc=\"rtsp://" + location.hostname + "/" + VideoPath + "\"" +
" qtsrcdontusebrowser src=\"quicktime.mov\" autoplay=\"true\" controller=\"true\"\>");
document.close();
There you get Location Path and Type, after many IF-Cases. Maybe you want them in your C# Code too. Then set the URI Path of the WebBrowser Control and see what happens...
webBrowser1.Url = new Uri(myIPCamStringPath);
Normally you can every IP-Cam direct with a standard Browser.
I have a Repeater control, that I have now reduced to just changing text in a text box when clicking the associated button.
However, this is not happening.
Here is my code so far:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Repeater ID="rptPdfList" runat="server" OnItemCommand="rptPdfList_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<td>File Name</td>
<td></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblName" runat="server" Text=<%#Eval("FileName") %>></asp:Label>
</td>
<td>
<asp:Button ID="btnLoad" runat="server" Text="Load" CommandName="LoadDoc"/>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnLoad" runat="server" Text="Load" OnClick="btnLoad_Click" /><br />
<iframe runat="server" id="pdfHolder"></iframe>
<br />
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
private void GetFiles()
{
rptPdfList.DataSource = Pdf();
rptPdfList.DataBind();
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}
public static List<PdfList> Pdf()
{
string pdfDir = HostingEnvironment.MapPath("~") + #"PDF\";
DirectoryInfo directory = new DirectoryInfo(pdfDir);
FileInfo[] pdfFiles = directory.GetFiles("*.pdf", SearchOption.AllDirectories);
List<PdfList> pdfLists = pdfFiles.Select(pdfFile => new PdfList
{
FileName = pdfFile.Name
}).ToList();
return pdfLists;
}
}
public class PdfList
{
public string FileName { get; set; }
}
Ca anyone see where I went wrong?
Edit, added all the code
Change this:
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
to this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetFiles();
}
You are calling the GetFiles() each time so it is always returning to the initial state.
I am binding your repeater like this and it works fine for me, Just place your binding function in
if (!Page.IsPostBack)
condition :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var v = (from s in dc.t_employees select s).ToList();
rptPdfList.DataSource = v;
rptPdfList.DataBind();
}
}
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}
I've got a web application that has a page full of batch files which the user can run, view the output, and send input. My problem occurs when the process hits something which causes it to pause, such as a pause, or a question that requires the user to press Y or N to continue. We'll go with pause for the purposes of this question.
This is my batch file:
pause
When run in windows, I get the output displayed on my screen "Press any key to continue...", I press enter, and it exits. But when my app runs this batch file, I dont get any output, but I know what it's waiting for so I press enter, and only then do I see the output "Press any key to continue...".
I've created a simplified version of my code in a console app, and the same thing happens, I get a blank screen, I press enter, and then I see "Press any key to continue..."
Any idea how I go about getting this line of output BEFORE I am required to press the key?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace BatchCaller
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = #"C:\Projects\BatchCaller\BatchCaller\Test2.bat",
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
Process proc = new Process();
proc.StartInfo = psi;
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.BeginOutputReadLine();
// Problem is not here, ignore this, just my temporary input method.
// Problem still occurs when these two lines are removed.
string inputText = Console.ReadLine();
proc.StandardInput.WriteLine(inputText);
proc.WaitForExit();
}
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
// This method doesnt get called for output: "Press any key to continue..."
// Why?
if (e.Data != null)
Console.WriteLine(e.Data);
}
}
}
Just checked and I noticed that pause doesn't return to the next line of text until you press the key. That's probably why it's not displaying, since your code is looking for a line return.
Rather than using ReadLine(), try seeing if there's one that will show all the characters as they're printed.
(^that should solve your problem by giving you a more real-time view of what's going on inside)
I'd have thought you'd need to move your:
string inputText = Console.ReadLine();
proc.StandardInput.WriteLine(inputText);
into the OutputDataReceived handler.
Then in your main, call proc.WaitForExit() and with a bit of luck (I haven't tested this) the following should happen:
proc's output buffer is flushed
your OutputDataReceived handler is executed
Console.Write with proc's stdout
Console.Read and send input to proc's stdin
proc exits
I realised it wasn't reading the last line because the data received event was only being triggered after there was a whole line of output, but when it pauses or asks a question, the cursor is still on the same line. A new thread that continuously checked the output stream was the solution to this small problem.
I also managed to solve my whole problem so that now what I've got when I run a script close ly resembles a command prompt window.
Here's a very basic summary of how it works:
I start a new process that runs a batch file. At the same time I start a new thread that continuously loops asking the process for more output, and storing that output in a queue. My .NET timer continuously checks the queue for text, and outputs it into my ajax panel. I use a text box and ajax to input text into the process input and into my ajax panel. I also needed a lot of javascript and I had to use session variables to make it run smoothly.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Scripts.aspx.cs" Inherits="MITool.Scripts" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" language="javascript">
var script = '';
function ShowScriptModal() {
$('#overlay').css({ width: $(document).width(), height: $(document).height(), 'display': 'block' }).animate({ opacity: 0.85 }, 0, function () { $('#scriptModal').show(); });
}
function ScriptInputKeypress(e) {
if (e.keyCode == 13) {
ScriptInput();
}
}
function ScriptInput() {
var txtInput = document.getElementById("txtInput");
var input = txtInput.value;
var hiddenInput = document.getElementById("hiddenInput");
if (input == '')
return;
hiddenInput.value = input;
txtInput.value = '';
}
function CheckForNewOutput() {
var outputUpdatePanel = document.getElementById("OutputUpdatePanel");
var pageScript = outputUpdatePanel.innerHTML;
if (script != pageScript) {
script = pageScript;
ScrollToBottom();
}
setTimeout("CheckForNewOutput()", 100);
}
function ScrollToBottom() {
$('#OutputPanel').scrollTop($('#OutputUpdatePanel').height());
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true" LoadScriptsBeforeUI="true" />
<div id="scriptModal">
<div id="ScriptInputOutput">
<asp:Panel ID="OutputPanel" runat="server" Width="700" Height="250" ScrollBars="Vertical"
Style="margin: 10px auto; border: 1px solid #CCC; padding: 5px;" ClientIDMode="Static">
<controls:ScriptOutput ID="ScriptOutputControl" runat="server" />
</asp:Panel>
<asp:Panel ID="InputPanel" runat="server" DefaultButton="btnScriptInput" >
<asp:TextBox ID="txtInput" runat="server" ClientIDMode="Static" onkeypress="ScriptInputKeypress(event)" />
<asp:HiddenField ID="hiddenInput" runat="server" ClientIDMode="Static" />
<asp:Button ID="btnScriptInput" runat="server" Text="Script Input" ClientIDMode="Static" OnClick="btnScriptInput_Click" style="display:none" />
<asp:Button ID="btnExit" runat="server" CssClass="floatRight" Text="Exit" OnClick="btnExit_Click" />
</asp:Panel>
</div>
</div>
<asp:Literal ID="litScript" runat="server" />
<ul id="breadcrumb">
<li>Main page ></li>
<li class="current">Scripts</li>
</ul>
<div class="content">
<h2>
<asp:Label ID="lblHeader" runat="server" Text="Scripts" /></h2>
<div class="clear">
</div>
<div class="table-content">
<asp:Label ID="lblMessage" runat="server" CssClass="redMessage" />
<asp:Repeater ID="rptScripts" runat="server" OnItemCommand="rptScripts_ItemCommand">
<HeaderTemplate>
<table class="table" cellpadding="0" cellspacing="0">
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Location
</th>
<th>
</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("ScriptId") %>
</td>
<td>
<%# Eval("Name") %>
</td>
<td>
<%# Eval("Path") %>
</td>
<td>
<asp:LinkButton ID="btnRunScript" runat="server" Text="Run" CommandName="Run" CommandArgument='<%# Eval("ScriptId") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<div>
</div>
</div>
</div>
<script type="text/javascript" language="javascript">
CheckForNewOutput();
</script>
</asp:Content>
// ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MITool.Data.ScriptManager;
using System.Diagnostics;
using System.IO;
using System.Web.Security;
using System.Web.Services;
using System.Collections.Concurrent;
using System.Threading;
namespace MITool
{
public partial class Scripts : System.Web.UI.Page
{
ConcurrentQueue<char> ScriptOutputQueue
{
get
{
return (ConcurrentQueue<char>)Session["ScriptOutputQueue"];
}
set
{
Session["ScriptOutputQueue"] = value;
}
}
Process CurrentProcess
{
get
{
return (Process)Session["CurrentProcess"];
}
set
{
Session["CurrentProcess"] = value;
}
}
bool ScriptRunning
{
get
{
if (CurrentProcess == null)
return false;
if (!CurrentProcess.HasExited || !CurrentProcess.StandardOutput.EndOfStream)
return true;
return false;
}
}
bool OutputProcessing
{
get
{
if (ScriptOutputQueue != null && ScriptOutputQueue.Count != 0)
return true;
return false;
}
}
Thread OutputThread;
void Reset()
{
ScriptOutputControl.SetTimerEnabled(false);
ScriptOutputControl.ClearOutputText();
if (CurrentProcess != null && !CurrentProcess.HasExited)
CurrentProcess.Kill();
if (OutputThread != null && OutputThread.IsAlive)
OutputThread.Abort();
ScriptOutputQueue = new ConcurrentQueue<char>();
litScript.Text = string.Empty;
txtInput.Text = string.Empty;
}
void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
Reset();
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
string role = id.Ticket.UserData;
ScriptData data = new ScriptData();
List<Script> scripts = data.GetScriptsByRole(role);
rptScripts.DataSource = scripts;
rptScripts.DataBind();
}
protected void rptScripts_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "Run": StartScript(Int32.Parse(e.CommandArgument.ToString()));
break;
}
}
void StartScript(int id)
{
if (ScriptRunning || OutputProcessing)
return;
Reset();
ScriptData data = new ScriptData();
History history = new History()
{
UserName = HttpContext.Current.User.Identity.Name,
BatchFileId = id,
DateRun = DateTime.Now
};
data.CreateHistory(history);
Script script = data.GetScript(id);
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = script.Path,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
CurrentProcess = new Process();
CurrentProcess.StartInfo = psi;
OutputThread = new Thread(Output);
CurrentProcess.Start();
OutputThread.Start();
ScriptOutputControl.SetTimerEnabled(true);
litScript.Text = "<script type=\"text/javascript\" language=\"javascript\">ShowScriptModal();</script>";
SetFocus("txtInput");
}
void Output()
{
while (ScriptRunning)
{
var x = CurrentProcess.StandardOutput.Read();
if (x != -1)
ScriptOutputQueue.Enqueue((char)x);
}
}
public void btnScriptInput_Click(object sender, EventArgs e)
{
string input = hiddenInput.Value.ToString();
ScriptOutputControl.Input(input);
foreach (char x in input.ToArray())
{
if (CurrentProcess != null && !CurrentProcess.HasExited)
{
CurrentProcess.StandardInput.Write(x);
}
Thread.Sleep(1);
}
}
protected void btnExit_Click(object sender, EventArgs e)
{
Reset();
}
}
}
// ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ScriptOutput.ascx.cs"
Inherits="MITool.Controls.ScriptOutput" %>
<asp:Label ID="lblStats" runat="server" Style="color: Red" />
<br />
<asp:UpdatePanel ID="OutputUpdatePanel" runat="server" ClientIDMode="Static">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
<asp:AsyncPostBackTrigger ControlID="btnScriptInput" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Literal ID="litOutput" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Timer ID="UpdateTimer" Interval="100" runat="server" OnTick="UpdateTimer_Tick" Enabled="false" />
// ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace MITool.Controls
{
public partial class ScriptOutput : System.Web.UI.UserControl
{
string Output
{
get
{
if (Session["Output"] != null)
return Session["Output"].ToString();
return string.Empty;
}
set
{
Session["Output"] = value;
}
}
ConcurrentQueue<char> ScriptOutputQueue
{
get
{
return (ConcurrentQueue<char>)Session["ScriptOutputQueue"];
}
set
{
Session["ScriptOutputQueue"] = value;
}
}
Process CurrentProcess
{
get
{
return (Process)Session["CurrentProcess"];
}
set
{
Session["CurrentProcess"] = value;
}
}
bool ScriptRunning
{
get
{
if (CurrentProcess == null)
return false;
if (!CurrentProcess.HasExited || CurrentProcess.StandardOutput.Peek() != -1)
return true;
return false;
}
}
bool OutputProcessing
{
get
{
if (ScriptOutputQueue != null && ScriptOutputQueue.Count != 0)
return true;
return false;
}
}
public void SetTimerEnabled(bool enabled)
{
UpdateTimer.Enabled = enabled;
}
public void ClearOutputText()
{
Output = string.Empty;
litOutput.Text = Output;
}
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
ProcessOutput();
if (!ScriptRunning && !OutputProcessing)
{
UpdateTimer.Enabled = false;
Output += "<br />// SCRIPT END //<br />";
litOutput.Text = Output;
}
}
public void Input(string s)
{
Output += "<br />// " + s + "<br />";
}
void ProcessOutput()
{
string s = string.Empty;
while (ScriptOutputQueue != null && ScriptOutputQueue.Any())
{
char x;
if (ScriptOutputQueue.TryDequeue(out x))
{
s += x;
}
}
if (s != string.Empty)
{
s = Server.HtmlEncode(s);
s = s.Replace("\r\n", "<br />");
Output += s;
}
litOutput.Text = Output;
}
}
}