Showing IP cam feed in WinForms C# app - c#

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.

Related

How to run controller action after user clicks button in Jquery dialog, code must loop though all records so user can accept or reject

I am battling with some code in MVC, I managed to pass data form controller to a Jquery dialog widget, now i need to know how to return back to the controller depending on whether the user accepted or rejected the record. There is a list of records I upload as CSV onto MVC View, I then have a button called Validate Claims which calls a stored procedure to validate records, when validate claims is clicked a dialog pops up, with the response from the controller ViewBag passed, I want to then based on the validation response enable user to accept or reject record, when user accepts record it must save it to db then move to the next record. How can I do this in MVC JQuery, please assist.
Please see my code below:
Here is my View Code
#{
ViewBag.Title = "Home Page";
}
#*<link href="~/Content/jquery-ui.css" rel="stylesheet" />*#
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.js"></script>
<link href="~/Content/themes/base/dialog.css" rel="stylesheet" />
#*<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>*#
#using CSVSupplierClaims.Models
#model List<CSVSupplierClaims.Models.SupplierClaimsUploadDisplayList>
<input type="submit" id="validateClaims" value="Validate Claims" size="5" />
<input type="submit" value="Import Claims to CRM" size="5" />
<div id="dialog" title="Supplier Claims Validation">
Claims Upload Confirmation
<p>
<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
<table id="users" class="ui-widget ui-widget-content" height="100" width="100" border="1">
<thead>
<tr class="ui-widget-header ">
<th style="width:70%">ST Key</th>
<th style="width:70%">Supplier Claim</th>
<th style="width:70%">System Cost</th>
<th style="width:70%">Orig Inv</th>
</tr>
</thead>
<tbody>
<tr>
<td>#ViewBag.ST_Key</td>
<td>#ViewBag.SupplierClaim</td>
<td>#ViewBag.OrigInv</td>
<td>#ViewBag.Error</td>
<td>#ViewBag.SystemCost</td>
</tr>
</tbody>
</table>
</p>
</div>
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
autoOpen: false
});
$("#validateClaims").click(function () {
$("#dialog").dialog("open", "resizable");
$("#dialog").dialog({
resizable: true,
height: 300,
width:500,
modal: true,
closeOnEscape: true,
buttons: {
"Accept Claim Record": function (){
$(this).dialog("close");
$(this).empty();
},
"Reject Claim Record": function () {
$(this).dialog("close");
}
}
});
});
});
</script>
<table>
<tr>
<th>Action</th>
<th>LineNo</th>
<th>TotalClaim</th>
<th>ClaimReference</th>
<th>Currency</th>
</tr>
#if (Model != null)
{
foreach (var c in Model)
{
<tr>
<td>#c.Action</td>
<td>#c.LineNo</td>
<td>#c.TotalClaim</td>
<td>#c.ClaimReference</td>
<td>#c.Currency</td>
</tr>
}
}
</table>
#Html.ValidationMessage("Error")
<form action="" method="post" enctype="multipart/form-data">
<table style="margin-top:150px">
<tr>
<td>
<label for="file"> Filename</label>
</td>
<td>
<input type="file" name="file" id="file" />
</td>
<td>
<input type="submit" value="Upload" />
</td>
</tr>
</table>
Here is my Controller Code
using CsvHelper;
using CSVSupplierClaims.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Crm;
using System.Data.SqlClient;
using System.Data;
namespace CSVSupplierClaims.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(HttpPostedFileBase file)
{
string path = null;
List<SupplierClaimsUploadDisplayList> supplierClaimsData = new List<SupplierClaimsUploadDisplayList>();
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = AppDomain.CurrentDomain.BaseDirectory + "upload\\" + fileName;
file.SaveAs(path);
var csv = new CsvReader(new StreamReader(path));
var supplierList = csv.GetRecords<SupplierClaimsUpload>();
foreach (var supplier in supplierList)
{
SupplierClaimsUploadDisplayList supplierUploadDisplay = new SupplierClaimsUploadDisplayList();
supplierUploadDisplay.Action = supplier.Action;
supplierUploadDisplay.LineNo = supplier.LineNo;
supplierUploadDisplay.TotalClaim = supplier.TotalClaim;
supplierUploadDisplay.ClaimReference = supplier.ClaimReference;
supplierUploadDisplay.Currency = supplier.Currency;
supplierClaimsData.Add(supplierUploadDisplay);
}
}
}
catch
{
ViewData["error"] = "Uplaod failed";
}
Supplier_Claim_Upload_Result supplierClaimUplaod = new Supplier_Claim_Upload_Result();
var sqlConnection = "data source=WMVSQL02;initial catalog=Embrace;integrated security=True;";
using (SqlConnection conn = new SqlConnection(sqlConnection))
{
try
{
foreach (var claim in supplierClaimsData)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 60;
SqlDataReader reader;
cmd.CommandText = "CRM.Supplier_Claim_Upload";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Invoice", SqlDbType.NVarChar).Value = claim.LineNo;
cmd.Parameters.Add("#Amount", SqlDbType.NVarChar).Value = claim.TotalClaim;
cmd.Connection = conn;
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
supplierClaimUplaod.ST_Key = reader["ST_Key"].ToString();
if (supplierClaimUplaod.SupplierClaim != null)
{
supplierClaimUplaod.SupplierClaim = reader["Supplier_Claim"].ToString();
}
else if (supplierClaimUplaod.SupplierClaim == null && supplierClaimUplaod.OrigInv == null && supplierClaimUplaod.SystemCost == null)
{
if (supplierClaimUplaod.Error != null)
{
supplierClaimUplaod.Error = reader["Error"].ToString();
}
else if (supplierClaimUplaod.Error == null)
{
supplierClaimUplaod.SupplierClaim = "No value";
}
}
if (supplierClaimUplaod.OrigInv != null)
{
supplierClaimUplaod.OrigInv = reader["Orig_Inv"].ToString();
}
else if (supplierClaimUplaod.OrigInv == null)
{
if (supplierClaimUplaod.Error != null)
{
supplierClaimUplaod.Error = reader["Error"].ToString();
}
else if (supplierClaimUplaod.Error == null)
{
supplierClaimUplaod.OrigInv = "No value";
}
}
if (supplierClaimUplaod.SystemCost != null)
{
supplierClaimUplaod.SystemCost = reader["System_Cost"].ToString();
}
else if (supplierClaimUplaod.SystemCost == null)
{
if (supplierClaimUplaod.Error != null)
{
supplierClaimUplaod.Error = reader["Error"].ToString();
}
else if (supplierClaimUplaod.Error == null)
{
supplierClaimUplaod.SystemCost = "No Value";
}
}
}
if (supplierClaimUplaod != null)
{
ViewBag.ST_Key = supplierClaimUplaod.ST_Key;
ViewBag.SupplierClaim = supplierClaimUplaod.SupplierClaim;
ViewBag.OrigInv = supplierClaimUplaod.OrigInv;
ViewBag.Error = supplierClaimUplaod.Error;
ViewBag.SystemCost = supplierClaimUplaod.SystemCost;
ViewBag.Confirmation = supplierClaimUplaod.Error +
supplierClaimUplaod.OrigInv +
supplierClaimUplaod.ST_Key +
supplierClaimUplaod.SupplierClaim +
supplierClaimUplaod.SystemCost;
return View(supplierClaimsData);
}
conn.Close();
}
}
catch (Exception)
{
throw;
}
}
return View(supplierClaimsData);
}
}
}
I managed to pass the controller response to the dialog, I am struggling trigger the loop to go back to the controller and got through all the records. When a user click on Accept Record I want to go back to the controller, and maybe save the record somewhere(sql) and validate the next record and so on, I am basically asking how can I wire up the Jquery button click Accept or Reject to go back to the controller and run additional code based on what button the user selected.
You can do this with an ajax call to your controller action.
$.ajax({
url: "#Url.Action("YourAction", "YourController")",
data: some_parameters
type: "POST",
success: function(response){ },
error: function(jqXHR, textStatus, errorThrown) { }
});
Here for more details

Asyncupload control of AjaxControlToolkit

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.

mvc ajax form post null list issue

Here is my ajax form of my view:
#using (Ajax.BeginForm("SendIndoorRequest", "TestRequest", new AjaxOptions { OnBegin = "SendRequestBegin", OnComplete = "SendRequestComplete", OnFailure = "SendRequestFail", OnSuccess = "SendRequestSuccess" }, new { enctype = "multipart/form-data", id = "ImgUpload" }))
{
<input type="hidden" name="CliqPanelID" value="#ViewBag.OrgID" />
<input type="hidden" name="TypeOfRequest" value="I" />
<input type="hidden" name="patient_id" value="#ViewBag.PatientId" />
<input type="hidden" name="bed_no" value="#ViewBag.PatientBedNo" />
<input type="hidden" name="ward_no" value="#ViewBag.PatientWardNo" />
#*<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>*#
<div class="row" style="margin-top:5px;margin-bottom:5px;">
#*input fields*#
<div class="col-lg-8">
<div class="col-lg-4">
<div class="col-lg-12"><label>Request Type:</label></div>
<div class="col-lg-12">
#Html.DropDownList("RequestType", null, "Select Request Type", new { #style = "width:170px;", #id = "ddlRequestType" })
</div>
<div id="ddlRequestTypeValidate" style="margin-left:12px;color:red;display:none;">
Select Request Type
</div>
</div>
<div class="col-lg-4">
<div class="col-lg-12"><label>Reffering Doctor:</label></div>
<div class="col-lg-12">
#Html.DropDownList("CliqDoctorID", null, "Select Reffering Doctor", new { #style = "width:180px;", id = "ddlRefDoctors", #class = "chosen-select" })
</div>
<div id="ddlRefDoctorsValidate" style="margin-left:12px;color:red;display:none;">
Select Reffering Doctor
</div>
</div>
<div class="col-lg-4">
<div class="col-lg-12"><label>Doctor Name</label>
</div>
<div class="col-lg-12">
#Html.TextBoxFor(o => o.DoctorName, new { placeholder = "In case Doctor not in list" })
</div>
<div id="DoctorNameValidate" style="margin-left:12px;color:red;display:none;">
Enter Reffering Doctor
</div>
</div>
#Html.HiddenFor(o => o.BookedTestsIds, new { #id = "bookedTestsIds" })
#*#Html.HiddenFor(o => o.)*#
#*<input type="hidden" name="Tests[0].TestId" value="1" />
<input type="hidden" name="Tests[0].Charges" value="100" />*#
<div style"clear:both; margin-bottom:5px;"></div>
<div class="col-lg-4">
<div class="col-lg-12"><label>Authorization Code:</label></div>
<div class="col-lg-12">
#if (Session["AccountType"].ToString() == "panel")
{
#Html.TextBoxFor(o => o.AuthCode1, new { #disabled = "disabled" })
#Html.HiddenFor(o => o.AuthCode1)
}
else
{
#Html.TextBoxFor(o => o.AuthCode1)
}
</div>
<div id="AuthCode1Validate" style="margin-left:12px;color:red;display:none;">
Enter Authorization Code
</div>
</div>
#*<div class="col-lg-4">
<div class="col-lg-12"><label>Prescription Reference:</label></div>
<div class="col-lg-12">
<input type="file" id="uploadFile" name="files"><br>
<span id="uploadLoader" style="display:none;"><img id="searchLoader" src="#Url.Content("~/Images/loader.gif")" />Uploading Please Wait</span>
</div>
<div style="margin-left:12px;color:red;">
</div>
</div>*#
<div class="col-lg-4">
<div class="col-lg-12"><label>Prescription Reference:</label></div>
<div class="col-lg-12">
<div id="uploadControlContainer">
<input type="file" name="fileUpload" value="" id="uploadFile" />
<p>Upload Files</p>
</div>
</div>
<input type="hidden" name="FilePath" value="" id="UploadedFile" />
<div style="margin-left:12px;color:red;">
</div>
</div>
<div class="col-lg-3">
<div class="col-lg-12">
</div>
<div class="col-lg-12">
<input class="btn btn-primary" style="padding: 0 5px; !important;" id="btnSendRequest" type="submit" value="Send Request"/>
</div>
</div>
</div>
#*input fields portion end*#
#*card portion*#
<div class="col-lg-4" style="background:white; border-radius:4px;padding:4px; box-shadow: 2px 2px 2px 2px #888888; width:32.333% !important; margin-left:10px;">
<div class="col-lg-2" style="padding-left: 4px !important;padding-right: 2px; !important"><img id="PatientPic" src="" style=" width: 100%;" /></div>
<div class="col-lg-10" style="padding-left: 4px !important;padding-right: 2px; !important">
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Patient:</strong></div>
<div class="col-lg-9" id="EmpName" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">#ViewBag.PatientName </div>
<div style="clear:both;"></div>
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Ward/Room:</strong></div>
<div class="col-lg-9" id="DepName" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">#ViewBag.PatientWardNo </div>
<div style="clear:both;"></div>
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Bed No:</strong></div>
<div class="col-lg-9" id="Relation" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">#ViewBag.PatientBedNo </div>
</div>
</div>
#*card portion end*#
</div>
<div id="panelTestsContainer">
</div>
<div id="hiddenContainer">
<input type="hidden" id="delimCharges" />
<input type="hidden" id="delimTestId" />
<input type="hidden" id="delimTestName" />
</div>
<div id="BookedTestsContainer">
</div>
}
on my view there are checkboxes with test name on check box checked or unchecked event i sent an ajax call to maintain list on server side but if i only i check 1 test the list posted is null but when i check more than 1 then list is posted with right count and data, whats the issue i am not getting:
Here is my jquery code for checkbox event:
$("input.checkBoxTests").live('change', function () {
var TestID = this.id;
var charges = $('#sample-table-3').find('td.TestCharges#' + TestID).html();
var TestName = $('#sample-table-3').find('td.TestName#' + TestID).html()
if (this.checked) {
var AddUrl = '#Url.Action("AddTest","TestRequest")';
$.post(AddUrl,
{ TestId: TestID, Charges: charges, TestName: TestName },
function (response) {
$("div#BookedTestsContainer").html(response);
});
$("#selectedTestsTable").find('tbody')
.append($('<tr>')
.attr('id', TestID)
.attr('class', "bookedTest")
.append($('<td>')
.append($('#sample-table-3').find('td.TestName#' + TestID).html()
)
)
);
}
else {
var RemoveUrl = '#Url.Action("RemoveTest","TestRequest")';
$.post(RemoveUrl,
{ TestId: TestID, Charges: charges, TestName: TestName },
function (response) {
$("div#BookedTestsContainer").html(response);
});
$("#selectedTestsTable").find('tr#' + TestID).remove()
}
});
here is my ajax call server event when checkbox is checked:
[HttpPost]
public ActionResult AddTest(int TestId,long Charges, string TestName)
{
List<Test> bookedTests = new List<Test>();
if (Session["BookedTests"] != null)
{
bookedTests = (List<Test>)Session["BookedTests"];
}
Test objTest = new Test();
objTest.TestId = TestId;
objTest.Charges = Charges;
objTest.TestName = TestName;
bookedTests.Add(objTest);
Session["BookedTests"] = bookedTests;
return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml",bookedTests);
}
here is my ajax call server side event when checkbox is unchecked:
[HttpPost]
public ActionResult RemoveTest(int TestId)
{
List<Test> bookedTests = new List<Test>();
if (Session["BookedTests"] != null)
{
bookedTests = (List<Test>)Session["BookedTests"];
bookedTests.RemoveAll(key => key.TestId == TestId);
Session["BookedTests"] = bookedTests;
return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml", bookedTests);
}
else
{
return new EmptyResult();
}
}
Here is my form post method:
[HttpPost]
public string SendIndoorRequest(TestRequestViewModel form, IEnumerable<HttpPostedFileBase> files)
{
using (var db = new cloud_clinicEntities())
using (var scope = new TransactionScope())
{
org_requestm objRequestM = new org_requestm();
objRequestM.authcode1 = form.AuthCode1;
objRequestM.admission_no = form.admission_no;
objRequestM.bed_no = form.bed_no;
objRequestM.ward_no = form.ward_no;
objRequestM.patient_id = form.patient_id;
objRequestM.RequestType = form.TypeOfRequest;
if (form.DependentId == 0)
{
objRequestM.cliq_dependent_id = null;
}
else
{
objRequestM.cliq_dependent_id = form.DependentId;
}
if (form.CliqDoctorID != 0)
{
objRequestM.cliq_doctor_id = form.CliqDoctorID;
}
if (!string.IsNullOrEmpty(form.DoctorName))
{
objRequestM.doctor_name = form.DoctorName;
}
objRequestM.request_total_amount = 0;
for (int i = 0; i < form.BookedTests.Count; i++)
{
if (form.BookedTests[i].Charges != 0)
{
objRequestM.request_total_amount = objRequestM.request_total_amount + form.BookedTests[i].Charges;
}
}
objRequestM.cliq_panel_id = form.CliqPanelID;
if (Session["AccountType"].ToString() == "lab")
{
objRequestM.enteredby_clinicPersonId = int.Parse(Session["userId"].ToString());
}
else
{
objRequestM.enteredby_orgPersonId = int.Parse(Session["userId"].ToString());
}
objRequestM.enteredon = DateTime.Now;
objRequestM.org_request_type_id = form.RequestType;
if (Request.Files != null)
{
foreach (string requestFile in Request.Files)
{
HttpPostedFileBase file = Request.Files[requestFile];
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string directory = Server.MapPath("~/uploads/");
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string path = Path.Combine(directory, fileName);
file.SaveAs(path);
objRequestM.perscription_doc_path = "~/Uploads/" + file.FileName;
}
}
}
db.org_requestm.Add(objRequestM);
db.SaveChanges();
long RequestmId = db.org_requestm.Max(o => o.id);
for (int i = 0; i < form.BookedTests.Count; i++)
{
if (form.BookedTests[i].TestId != 0)
{
org_requestd objRequestd = new org_requestd();
objRequestd.amount = form.BookedTests[i].Charges;
objRequestd.lims_test_id = form.BookedTests[i].TestId;
objRequestd.lims_test_name = form.BookedTests[i].TestName;
objRequestd.Status = "P";
objRequestd.requestm_id = RequestmId;
db.org_requestd.Add(objRequestd);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
{
outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
outputLines.Add(string.Format(
"- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage));
}
}
System.IO.File.AppendAllLines(#"d:\EFerrors.txt", outputLines);
}
}
}
scope.Complete();
Session.Remove("BookedTests");
return "success";
}
}
here is my checkbox event:
$("input.checkBoxTests").live('change', function () {
var TestID = this.id;
var charges = $('#sample-table-3').find('td.TestCharges#' + TestID).html();
var TestName = $('#sample-table-3').find('td.TestName#' + TestID).html()
if (this.checked) {
var AddUrl = '#Url.Action("AddTest","TestRequest")';
//AddUrl = AddUrl + "?TestId=" + TestID + "&Charges=" + charges + "&TestName=" + TestName;
$.post(AddUrl,
{ TestId: TestID, Charges: charges, TestName: TestName },
function (response) {
$("div#BookedTestsContainer").html(response);
});
$("#selectedTestsTable").find('tbody')
.append($('<tr>')
.attr('id', TestID)
.attr('class', "bookedTest")
.append($('<td>')
.append($('#sample-table-3').find('td.TestName#' + TestID).html()
)
)
);
/*var TestIdIndex = $("input.iHiddenTestId").length;
var Mytest = $('input.MyTest').length;
alert('my' + Mytest);
$('form#ImgUpload input.iHiddenTestId').each(function (i) {
// do something
alert($(this).val());
});
var newTestId = $("<input id='" + this.id + "' type='hidden' value='" + this.id + "' class='iHiddenTestId' name='Tests[" + TestIdIndex + "].TestId' />");
$("form#ImgUpload").append(newTestId);
var Testing = $("<input id='" + this.id + "' type='hidden' value='" + this.id + "' class='MyTest' name='Tests[" + TestIdIndex + "].TestId' />");
$("form#ImgUpload").append(Testing);
var ChargesIndex = $("form#ImgUpload input.iHiddenCharges").length;
var newCharges = $("<input id='" + this.id + "' type='hidden' value='" + charges + "' class='iHiddenCharges' name='Tests[" + ChargesIndex + "].Charges' />");
$("form#ImgUpload").append(newCharges);
var TestNameIndex = $("form#ImgUpload input.iHiddenTestName").length;
var newTestName = $("<input id='" + this.id + "' type='hidden' value='" + TestName + "' class='iHiddenTestName' name='Tests[" + TestNameIndex + "].TestName' />");
$("form#ImgUpload").append(newTestName);*/
}
else {
var RemoveUrl = '#Url.Action("RemoveTest","TestRequest")';
$.post(RemoveUrl,
{ TestId: TestID, Charges: charges, TestName: TestName },
function (response) {
$("div#BookedTestsContainer").html(response);
});
$("#selectedTestsTable").find('tr#' + TestID).remove()
}
});
What i did after messing up with it that on list creating on Add Test i added a dummy empty entry on index 0 of the list and on retrieving while saving in db i am skipping the 0th index of the list, here is the code:
[HttpPost]
public ActionResult AddTest(int TestId,long Charges, string TestName)
{
List<Test> bookedTests = new List<Test>();
if (Session["BookedTests"] != null)
{
bookedTests = (List<Test>)Session["BookedTests"];
}
else
{
Test dummyTest = new Test();
dummyTest.TestId = 0;
dummyTest.Charges = 0;
dummyTest.TestName = "dummy";
bookedTests.Add(dummyTest);
}
Test objTest = new Test();
objTest.TestId = TestId;
objTest.Charges = Charges;
objTest.TestName = TestName;
bookedTests.Add(objTest);
Session["BookedTests"] = bookedTests;
return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml",bookedTests);
}
and here is the Saving in which i am skipping the first item of list:
[HttpPost]
public string SendIndoorRequest(TestRequestViewModel form, IEnumerable<HttpPostedFileBase> files)
{
using (var db = new cloud_clinicEntities())
using (var scope = new TransactionScope())
{
org_requestm objRequestM = new org_requestm();
objRequestM.authcode1 = form.AuthCode1;
objRequestM.admission_no = form.admission_no;
objRequestM.bed_no = form.bed_no;
objRequestM.ward_no = form.ward_no;
objRequestM.patient_id = form.patient_id;
objRequestM.RequestType = form.TypeOfRequest;
if (form.DependentId == 0)
{
objRequestM.cliq_dependent_id = null;
}
else
{
objRequestM.cliq_dependent_id = form.DependentId;
}
if (form.CliqDoctorID != 0)
{
objRequestM.cliq_doctor_id = form.CliqDoctorID;
}
if (!string.IsNullOrEmpty(form.DoctorName))
{
objRequestM.doctor_name = form.DoctorName;
}
objRequestM.request_total_amount = 0;
for (int i = 0; i < form.BookedTests.Count; i++)
{
if (form.BookedTests[i].Charges != 0)
{
objRequestM.request_total_amount = objRequestM.request_total_amount + form.BookedTests[i].Charges;
}
}
objRequestM.cliq_panel_id = form.CliqPanelID;
if (Session["AccountType"].ToString() == "lab")
{
objRequestM.enteredby_clinicPersonId = int.Parse(Session["userId"].ToString());
}
else
{
objRequestM.enteredby_orgPersonId = int.Parse(Session["userId"].ToString());
}
objRequestM.enteredon = DateTime.Now;
objRequestM.org_request_type_id = form.RequestType;
if (Request.Files != null)
{
foreach (string requestFile in Request.Files)
{
HttpPostedFileBase file = Request.Files[requestFile];
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string directory = Server.MapPath("~/uploads/");
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string path = Path.Combine(directory, fileName);
file.SaveAs(path);
objRequestM.perscription_doc_path = "~/Uploads/" + file.FileName;
}
}
}
db.org_requestm.Add(objRequestM);
db.SaveChanges();
long RequestmId = db.org_requestm.Max(o => o.id);
for (int i = 0; i < form.BookedTests.Count; i++)
{
if (form.BookedTests[i].TestId != 0)
{
org_requestd objRequestd = new org_requestd();
objRequestd.amount = form.BookedTests[i].Charges;
objRequestd.lims_test_id = form.BookedTests[i].TestId;
objRequestd.lims_test_name = form.BookedTests[i].TestName;
objRequestd.Status = "P";
objRequestd.requestm_id = RequestmId;
db.org_requestd.Add(objRequestd);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
{
outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
outputLines.Add(string.Format(
"- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage));
}
}
System.IO.File.AppendAllLines(#"d:\EFerrors.txt", outputLines);
}
}
}
scope.Complete();
Session.Remove("BookedTests");
return "success";
}
}

C# array to MVC view for Google Map markers

I am having such a rough time accomplishing this and all the research I'm doing is not turning out positive. In short, I need to send an array of markers from my code to my MVC view (through the model and setting it as a hidden field) so that the Google map can use this array to place markers on the map. I have tried building it as a List and then using JSON serialization to turn it to a string, but the format just won't turn out and won't be recognizable to the Google API. Has anyone done this before successfully??
Here is my updated code based on CodeMonkey's answer, but the markers still aren't placing. I think it's happening somewhere in the addMarker function...
var lat = $("#Latitude").val();
var lng = $("#Longitude").val();
var myOptions = {};
var map = null;
var marker = null;
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function map_initialize() {
var myLatlng = new google.maps.LatLng(lat, lng);
myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
#foreach (var item in Model.AllSearchResults)
{
<text>try
{
var lat = '#item.Latitude';
var lng = '#item.Longitude';
var name = '#item.Name';
var url = '#Url.Action("GetMarker", "Base")';
var model = { "Latitude": lat, "Longitude": lng, "Name": name };
$.ajax({
type: "POST",
data: model,
dataType: "json",
url: url,
success: function (data) {
geodata = data;
JSONString = JSON.stringify(geodata);
var valuesToPush = new Array();
valuesToPush[0] = data.Latitude;
valuesToPush[1] = data.Longitude;
valuesToPush[2] = data.Name;
markers.push(valuesToPush);
addMarker();
},
error: function () {
alert("fail");
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var name = markers[i][2];
var location = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + name + '</p></div>';
var marker = new google.maps.Marker({
position: location,
map: map,
title: name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', map_initialize);
I was able to do a combo server side/client side approach using the following link as a guide: http://mikehadlow.blogspot.com/2008/10/using-google-maps-with-mvc-framework.html
Thanks for Code Monkey's input!!
You can reference my front-end JS code at this URL: http://www.wallodex.com/WallodexAdmin/Map/10
This is how I use it on the VIEW:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CloudClaims Administration - Site Visits</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgJDbn0VP_AnX4HsXSjN3cIn0MoEJ4vOw&sensor=false"></script>
<script type="text/javascript" src="../../js/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../../js/json2.js"></script>
<script type='text/javascript'>
var DISPLAY_COUNT = 20;
var myOptions = {};
var markerArray = new Array();
var map = null;
//var geocoder = null;
var marker = null;
var g_ctr = 0;
var last_used_address = "";
var splitURLs = {};
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function initialize() {
myOptions = {
center: new google.maps.LatLng(38.5111, -96.8005),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//geocoder = new google.maps.Geocoder();
#foreach (var item in Model)
{
<text>try
{
var ip = '#item';
var url = 'http://api.ipinfodb.com/v3/ip-city/?format=json&key=6d0759103a4ec817ffda18dfba4eafe853125d6960dedffdcfa4a428774d871d&ip=' + ip + '&callback=?';
$.getJSON(url,
function (data) {
if (data['statusCode'] == 'OK') {
geodata = data;
JSONString = JSON.stringify(geodata);
//callback();
//alert(data.regionName);
var valuesToPush = new Array();
valuesToPush[0] = data.latitude;
valuesToPush[1] = data.longitude;
valuesToPush[2] = data.cityName + ', ' + data.regionName;
valuesToPush[3] = data.ipAddress;
markers.push(valuesToPush);
addMarker();
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var cityState = markers[i][2];
var ipAddress = markers[i][3];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + cityState + '<br/>' + ipAddress + '</p></div>';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " \n Location: " + cityState
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".fadeInbox").hide().fadeIn(4000);
$("#map_canvas").hide().fadeIn(4000);
$(".subscriberList").hide().fadeIn(8000);
});
$(window).load(function () {
$("#loading").css('visibility', 'hidden');
});
</script>
<style type="text/css">
.infowindow
{
background-color: Yellow;
text-align: left;
padding: 0px, 0px, 0px, 0px;
margin: 0px, 0px, 0px, 0px;
}
.fadeOutbox, .fadeInbox, .fadeTobox
{
padding: 10px;
margin: 4px;
border: 1px solid blue;
width: 250px;
height: 50px;
background-color: #000000;
color: white;
font: georgia;
}
.clear
{
clear: both;
}
</style>
</head>
<body onload="initialize();">
<form id="form1" runat="server">
<asp:panel id="Panel1" runat="server" style="height: 600px;">
<asp:Literal ID="js" runat="server"></asp:Literal>
<table width="100%" align="center" border="1">
<tr bgcolor="#1569C7" align="center">
<td colspan="2">
<font color="white">CloudClaims™ - Site visitors - Last X days</font>
</td>
</tr>
<tr align="center">
<td width="80%">
<div id="map_canvas" style="width: 100%; height: 620px; margin-bottom: 0.5px;"></div>
</td>
<td align="center" valign="bottom" bgcolor="#FFBD82">
<asp:Label runat="server" id="errors"/>
<div>
#{Html.RenderAction("Subscribers");}
</div>
<div align="center" class="fadeInbox">
<b>DEBUGGING</b><br />
<asp:Label runat="server" id="ajaxtest"/>
</div>
</td>
</tr>
</table>
</asp:panel>
</form>
</body>
</html>
And this is my CONTROLLER (I convert IP ADDRESSES to gMap objects on the front-end but you get the idea...):
public ActionResult Map(int id)
{
try
{
using (var db = new CloudClaimsEntities())
{
DateTime dateFrom = (id != null && id > 1) ? DateTime.Now.AddDays(-id) : DateTime.Now.AddDays(-1);
List<string> IPAddresses = new List<string>();
IPAddresses = db.IPLogs
.Where(i => i.timeStamp <= DateTime.Now)
.Where(i => i.timeStamp >= dateFrom)
.Select(i => i.IPAddress)
.ToList();
return View(IPAddresses);
}
}
catch
{
return View();
}
}

Running Batch files & Reading LAST Line of Output after a Pause

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

Categories