How to retain Serial Port State after postback ASP.net - asp.net

I am trying to send the data to serial port in ASP.net. After connecting to serial port Before postback data is being sent. But after postback i get exception while sending data.
'System.InvalidOperationException: The port is closed.'
I tried everything by connecting to port on pageload: ispostback, and disconnecting and connecting again. Still it shows same exception. Is there any way to retain the state of serial port..
here's my code. Please Help me Out...
public partial class _Default : System.Web.UI.Page
{
string indata;
public SerialPort sp = new SerialPort();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
openPort("COM10");
disconnect();
connect();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//disconnect();
openPort("COM10");
connect();
check(TextBox1.Text); //Data Sending Successful but after postback even it doesnt work too.
}
public void connect()
{
try { sp.Open(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
public void disconnect()
{
try { sp.Close(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
public void openPort(string p)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
indata = sp.ReadExisting();
Debug.WriteLine(" Data Received:");
Debug.Write(" " + indata);
}
protected void Button4_Click(object sender, EventArgs e)
{
check("" + (char)26); //Exception in sending
}
protected void Button3_Click(object sender, EventArgs e)
{
check("\r\n"); //exception in sending
}
protected void Button2_Click(object sender, EventArgs e)
{
check(TextBox1.Text); // exception in sending
}
void check(string ss)
{
//sp.Dispose();
//openPort("COM10"); connect();
if (sp.IsOpen)
sp.Write(ss);
else
{
disconnect(); openPort("COM10"); connect();
sp.Write(ss);
}
}
}

I would simplify your code, so the port is configured on page load and the one handler deals with resetting your port. The disconnect, connect, I see is complicating it. Here I have given an example of using the button click event.
Please note the missing brace below.
public partial class _Default : System.Web.UI.Page
{
string indata;
public SerialPort sp = new SerialPort();
protected void Page_Load(object sender, EventArgs e)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
if (!Page.IsPostBack)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
protected void Button1_Click(object sender, EventArgs e)
if sp.IsOpen = False then
{
try { sp.Open(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
else
{
try { sp.Close(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
void check(string ss)
{
//sp.Dispose();
//openPort("COM10"); connect();
if (sp.IsOpen)
{//missing brace
sp.Write(ss);
}//missing brace
else
{
sp.Open();
sp.Write(ss);
}
}
}
Edit 2:
As I mentioned in the comments the code will only run once.
The following examples are provided from the link below.
Have you tried writing some codes under the !IsPostBack code block to
check if the codes hits there when it postbacks? try this below for
testing
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("First load");
}
else
{
Response.Write("Postback occurs");
}
}
OR
I will refer the code you want to run as One Time Code. For what you
are attempting to achieve, following should work. Please note that
sessions also expire. So after about 20 minutes (default value) of
inactivity, if the user comes back to the site/hits refresh, the One
Time Code will run again. If you want something more persistent than
20 minutes you can try using cookies, but if user clears their cookies
your One Time Code with run again.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["firsttimeuser"] == null)
{
//put code here for One Time Code;
Session["firsttimeuser"] = true;
}
}
Please see this link:
There is lengthy discussion about this.
http://forums.asp.net/t/1314918.aspx/1
You should be able to create a solution from this, please advise.
Edit 1
Please see MSDN for Get Port Names:
Use the GetPortNames method to query the current computer for a list
of valid serial port names. For example, you can use this method to
determine whether COM1 and COM2 are valid serial ports for the current
computer.
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames.aspx
And SerialPort.Open
_serialPort.PortName = SetPortName(_serialPort.PortName)
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx
Edit 3
Try:
if (!IsPostBack) or
if(!Page.IsPostBack)
Please see:
Implementation of IsPostBack in page load
What is a postback?
and:
http://msdn.microsoft.com/en-us/library/ms178472.aspx

Related

session timeout not working properly in global.asax

In my asp.net project I have an event in global.asax as session end which fires when the session is timeout and in this event, I am calling one stored procedure that updates logout time and flag in the table. But when the user is log in and after some work user close browser and on next day when he tries to log in at first attempt message shows that user is already login but when he tried to log in again he is able to log in.
please help its production issue.
<%# Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
}
void Application_End(object sender, EventArgs e)
{
Admin.User_Role objUserRole = new Admin.User_Role();
objUserRole.SchemaName =
(string)CBase.TripleDESDecode(Application["SchemaName"].ToString(),
CBase.EncryptionKey);
if (Session["UserId"] != null)
objUserRole.UserId = (string)Session["UserId"];
objUserRole.ModifiedDate = Convert.ToDateTime(CBase.GetServerDateTime());
try
{
objUserRole.funcUpdateLoggedIn();
}
catch (Exception ex)
{
//Response.Redirect(HttpUtility.UrlEncode("Logout.aspx"), false);
}
}
void Application_Error(object sender, EventArgs e)
{
Exception ex = this.Server.GetLastError().GetBaseException();
}
public HttpSessionState GetSession()
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Session;
}
else
{
return this.Session;
}
}
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
Admin.User_Role objUserRole = new Admin.User_Role();
string userid = Convert.ToString(GetSession()["UserId"]);
objUserRole.UserId = (string)CBase.TripleDESDecode(userid,
CBase.EncryptionKey);
objUserRole.ModifiedDate = Convert.ToDateTime(CBase.GetServerDateTime());
// objUserRole.funcUpdateLoggedIn();
try
{
objUserRole.funcUpdateLoggedIn();
}
catch (Exception ex)
{
//Response.Redirect(HttpUtility.UrlEncode("Logout.aspx"), false);
}
finally
{
Session.Abandon();
Session.Clear();
}
}
</script>

DateEdit value change

I would like to add minute (which is entered from a calcEdit) to starting date then it wil be set as end date.
Also when I enter the end date the subtract of start time will be set as minute .
I tried dateEdit's EditValueChanged ,Validating events and I tried both for calcedit but got wrong values.
I use g mask for dateEdits
Please help me thank you.
Here are my codes :
`private void calcEditMinute_Validating(object sender, CancelEventArgs e)
{
try
{
dtBitisZamani = Convert.ToDateTime(dateEditBas.EditValue).AddMinutes(Convert.ToDouble(calcEditMinute.Text));
dateEditBit.EditValue = dtBitisZamani;
}
catch (Exception)
{
}
}
private void dateEditBit_EditValueChanged(object sender, EventArgs e)
{
TimeSpan span = Convert.ToDateTime(dateEditBit.EditValue).Subtract(Convert.ToDateTime(dateEditBas.EditValue));
calcEditMinute.Text = string.Format(" {0} ",
span.Minutes); span.TotalMinutes.ToString();
}`
Try this:
private void calcEdit1_EditValueChanged(object sender, EventArgs e)
{
dateEditEnd.DateTime = dateEditStart.DateTime.AddMinutes(Convert.ToDouble(calcEdit1.Value));
}
private void dateEditEnd_EditValueChanged(object sender, EventArgs e)
{
dateEditStart.DateTime = dateEditEnd.DateTime.AddMinutes(Convert.ToDouble(calcEdit1.Value) * -1);
}

PageIndexChanging Event in search button in asp.net?

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grid();
}
}
protected void btnsearch_Click(object sender, EventArgs e)
{
objRetailPL.ZoneName = ddlzone.SelectedValue;
//IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
//String datetime = txtdate.Text.ToString();
//DateTime dt = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
//objRetailPL.date =dt;
DataTable dtsearch = new DataTable();
dtsearch = objRetailBAL.searchzone(objRetailPL);
GVRate.DataSource = dtsearch;
GVRate.DataBind();
}
protected void GVRate_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GVRate.PageIndex = e.NewPageIndex;
grid();
}
catch (Exception ex)
{
}
}
I have this code for searching records.And for that grid i added page index,but it is not coming properly.When click on search button it is showing more n of records at that time page index is not working. It is calling First grid before clicking search button..How can I change my code please help me.....
Try this ...
private void grid()
{
if(!string.IsNullOrEmpty(yourSearchTextBox.Text)
{
// Then call search method. Make sure you bind the Grid in that method.
}
else
{
// Normally Bind the Grid as you are already doing in this method.
}
}
you have to check whether there is any search Text or not in that grid() method like...

Selenium-RC loading empty frame

As stated above, I am running out an automated test on a website.
I am use selenium RC to do that but I'm just not sure why I am unable to open the website (actually i did open it), but its content is not showing.
There are just a few empty frame boxes.
This originally had too much code so I'm adding some more.
Anyone know why? Thank you.
Here is my code (unrelated code removed):
private ISelenium selenium;
private StringBuilder verificationErrors;
private Process worKer = new Process();
private string
serverHost = "localhost",
browserString = #"*iexploreproxy",
startUpURL = "";
private int
portNumber = 4444;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "CNY")
{
startUpURL = "http://malaysia.yahoo.com/";
}
}
private void btnStartServer_Click(object sender, EventArgs e)
{
worKer.StartInfo.FileName = #"C:\LjT\SeleniumServer.bat";
worKer.Start();
}
private void WakeUpSElenium()
{
selenium = new DefaultSelenium(serverHost, portNumber, browserString, startUpURL);
selenium.Start();
verificationErrors = new StringBuilder();
}
private void ToDoList()
{
selenium.Open("/");
//selenium.SelectFrame("iframe_content");
selenium.Type("id=txtFirstName", "1");
selenium.Click("id=rbtnGender_0");
}
private void btnTest_Click(object sender, EventArgs e)
{
try
{
WakeUpSElenium();
ToDoList();
}
catch
{}
}
You are not navigating anywhere, i.e this code here, will not navigate to any page at all:
selenium.Open("/");
I assume you meant to make it this:
selenium.Open(startUpURL); // this is the value from the combobox.

Passing DataKeys between pages

Using a GridView on the default page and want to show details of the row selected on another page. The code for capturing and sending the datakey is -
protected void SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
Response.Redirect("InvoicePage.aspx? EntityID= " + GridView1.DataKeys[index].Value.ToString());
}
And the code for retrieving the value is -
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["EntityID"];
}
My problem is that the id variable is a null on the receiving page. What am I missing?
Your URL should look something like this: InvoicePage.aspx?EntityID=", No space before or after EntityID
By The way Remove the white space : aspx?<>*EntityID<>*=
protected void SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
string id = GridView1.DataKeys[index].Value.ToString();
Response.Redirect("InvoicePage.aspx?EntityID="+id);
}
Try to add :
private string _EntityId;
//To check if value pass on query string
//but this is not really required if you want
public string EntityId
{
get
{
if (Request.QueryString["EntityID"] != null)
{
try
{
_EntityId = Convert.ToString(Request.QueryString["EntityID"].ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
else
{
_EntityId="0";
}
return _EntityId;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Request.QueryString["EntityID"].ToString();
string id = EntityId;
}
Regads

Resources