I'm developing an application for a windows CE 6.0 scanner device and I'm having an issue when I want to insert datas.
I'm using the OpenNETCF.ORM framework and SQLite.
The problem happens when I want to add a 3rd article to the database with the insert() method. It works well with the first 2 articles but when it comes to the 3rd one, it throws an exception which is "SQLiteConnection".
Did anyone have the same issue with this ORM framework and could help me pls?
Here is the code of DatabaseHelper.cs :
using System;
using System.Windows.Forms;
using OpenNETCF.ORM;
namespace OfflineWMS
{
public class DatabaseHelper
{
private Scanner _scannerManager = new Scanner();
private static DatabaseHelper _instance = null;
private static readonly object MyLock = new object();
private SQLiteDataStore _stockDatabase;
public SQLiteDataStore StockDatabase1
{
get { return _stockDatabase; }
set { _stockDatabase = value; }
}
private DatabaseHelper() {}
public static DatabaseHelper getInstance()
{
lock (MyLock)
{
if (_instance == null)
{
_instance = new DatabaseHelper();
_instance.InitDatabase();
}
return _instance;
}
}
//Create the Database
public void InitDatabase()
{
StockDatabase1 = new SQLiteDataStore(ConfigurationHelper.Settings["PathToTheApp"] + ConfigurationHelper.Settings["DatabaseFilename"]);
if (!StockDatabase1.StoreExists)
{
StockDatabase1.CreateStore();
}
InitializeDbStructure();
}
private void InitializeDbStructure()
{
StockDatabase1.AddType<Article>();
}
}
}`
The code in the Form.cs where I have the issue (at the end of the code) :
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using FileOperations.CsvImport;
using FileOperations.CsvImport.FluentInterface;
using OfflineWMS.Properties;
using OpenNETCF.ORM;
using Symbol.Barcode;
namespace OfflineWMS
{
public partial class Form1 : Form
{
private ReaderData TheReaderData;
private Scanner ScannerManager;
private bool IsReaderInitiated;
private DatabaseHelper db;
public Form1()
{
InitializeComponent();
}
protected override void OnClosing(CancelEventArgs e)
{
if (IsReaderInitiated)
ScannerManager.TermReader();
base.OnClosing(e);
}
private void ScannerManager_ReadNotify(object sender, EventArgs e)
{
TheReaderData = ScannerManager.Reader1.GetNextReaderData();
//action to do
ProcessData(TheReaderData);
ScannerManager.StopRead();
ScannerManager.StartRead(true);
}
private void ProcessData(ReaderData TheReaderData)
{
if (TheReaderData != null)
{
textBox1.Text = TheReaderData.Text;
}
else
{
MessageBox.Show(Resources.ReaderDataIsNull);
}
}
private void ScannerManager_StatusNotify(object sender, EventArgs e)
{
BarcodeStatus theStatus = ScannerManager.Reader1.GetNextStatus();
if (theStatus != null)
{
switch (theStatus.State)
{
case States.IDLE:
statusBar1.Text = Resources.IDLEStatus;
break;
case States.READY:
statusBar1.Text = Resources.ReadyStatus;
break;
case States.WAITING:
statusBar1.Text = Resources.WaitingStatus;
break;
default:
statusBar1.Text = Resources.DefaultStatus;
break;
}
}
else
{
//log error
}
}
protected override void OnLoad(EventArgs e)
{
// DatabaseHelper is instanciated only once here
db = DatabaseHelper.getInstance();
ScannerManager = new Scanner();
IsReaderInitiated = ScannerManager.InitReader();
textBox1.Focus();
// if not initialized, we quit the app
if (!IsReaderInitiated)
{
MessageBox.Show(Resources.InitiatingError);
Application.Exit();
}
else
{
ScannerManager.AttachStatusNotify(ScannerManager_StatusNotify);
ScannerManager.StartRead(true);
ScannerManager.AttachReadNotify(ScannerManager_ReadNotify);
}
//db.InitDatabase();
base.OnLoad(e);
}
private void buttonAddToDb_Click(object sender, EventArgs e)
{
if ((TheReaderData != null))
{
var article = new Article
{
ArticleName = "test",
ArticleCode = "321",
ArticleFeature = "true blue",
ArticlePrice = 33.22m,
ArticleQuantity = 15,
ArticleBarcode = TheReaderData.Text
};
var article2 = new Article
{
ArticleName = "test",
ArticleCode = "321",
ArticleFeature = "true blue",
ArticlePrice = 33.22m,
ArticleQuantity = 15,
ArticleBarcode = TheReaderData.Text
};
var article3 = new Article
{
ArticleName = "test",
ArticleCode = "321",
ArticleFeature = "true blue",
ArticlePrice = 33.22m,
ArticleQuantity = 15,
ArticleBarcode = TheReaderData.Text
};
// HERE
try
{
db.StockDatabase1.Insert(article);// article added
db.StockDatabase1.Insert(article2);// article2 added
db.StockDatabase1.Insert(article3);// throws the exception "SQLiteException"
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
ScannerManager.TermReader();
Application.Exit();
}
else
{
MessageBox.Show(Resources.ScanData);
}
}
}
}
And this is the stacktrace of this SQLiteException :
at System.Data.SQLite.SQLiteConnection.CheckDisposed()
at System.Data.SQLite.SQLiteConnection.get_State()
at OpenNETCF.ORM.SQLStoreBase`1.<GetPoolConnection>b__11(IDbConnection c)
at System.Linq.Enumerable.<WhereIterator>d__0`1.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at OpenNETCF.ORM.SQLStoreBase`1.GetPoolConnection()
at OpenNETCF.ORM.SQLStoreBase`1.GetConnection(Boolean maintenance, Boolean isRetry)
at OpenNETCF.ORM.SQLStoreBase`1.GetConnection(Boolean maintenance)
at OpenNETCF.ORM.SQLiteDataStore.OnInsert(Object item, Boolean insertReferences)
at OpenNETCF.ORM.DataStore`1.Insert(Object item, Boolean insertReferences, Boolean recoveryInsert)
at OpenNETCF.ORM.DataStore`1.Insert(Object item, Boolean insertReferences)
at OpenNETCF.ORM.DataStore`1.Insert(Object item)
at OfflineWMS.Form1.buttonAddToDb_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
at Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
at System.Windows.Forms.Application.Run(Form fm)
at OfflineWMS.Program.Main()
Related
I've made a Windows Form using C# and I'm trying to read serial DATA from RS232 serial port. But when I try to connect the device with PC through serial port. Device connected successfully but nothing is being received on the serial port through RS232.
Here is the main Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using WindowsFormsApp1;
using System.Data.SQLite;
using System.Windows.Forms.DataVisualization.Charting;
namespace Weight_Scale
{
public partial class FormWeightScale : Form
{
string weight;
string dbFile = "BundleInstances.db";
bundle bundle1 = new bundle();
int h = 0 , m = 0, s = 0 ;
public FormWeightScale()
{
InitializeComponent();
PageWeightScale();
if (!File.Exists(dbFile))
{
SQLiteConnection.CreateFile(dbFile);
}
//----------------- Queries ----------------------//
string createTable = "CREATE TABLE IF NOT EXISTS bundle" +
"(ID integer PrimaryKey AutoIncreament Unique Not Null," +
"Date VARCHAR, Time VARCHAR, Size VARCHAR, BarGrade VARCHAR," +
"Length VARCHAR, HeatNumber VARCHAR, WeightZeroLevel VARCHAR," +
"WeightReadingLevel VARCHAR, BundleMaxWeight VARCHAR, Weight integer)";
bundle1.setQueryCreateTable(createTable);
bundle.createTable();
setData();
displayData();
var ports = SerialPort.GetPortNames();
ComboBoxPort.DataSource= ports;
ProgressBarConnection.Value = 0;
}
void setData()
{
bundle1.setDateQuery(DateTimePickerWeight.Value.ToString("dd-MM-yyyy"));
}
void displayData()
{
dataGridWeightInstances.DataSource = bundle.readTable();
chartWeight.DataSource = bundle.readTable();
chartWeight.Series["Weight"].Points.Clear();
chartWeight.Series["Weight"].XValueMember = "Date";
chartWeight.Series["Weight"].XValueMember = "Time";
chartWeight.Series["Weight"].YValueMembers = "Weight";
labelPerDayProduction.Text = bundle.totalPerDayProduction.ToString("000.0");
}
private void BtnConnect_Click(object sender, EventArgs e)
{
if (ComboBoxPort.SelectedIndex > -1)
{
if(BtnConnect.Text == "Connect")
{
MessageBox.Show(String.Format("You selected port '{0}'", ComboBoxPort.SelectedItem), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Connection(ComboBoxPort.SelectedItem.ToString());
}
else
{
MessageBox.Show("Please select a port first");
}
}
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
serialPort1.Close();
ProgressBarConnection.Value=0;
Application.Exit();
}
private void ConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
{
PageConfiguration();
}
private void WeightScaleToolStripMenuItem_Click(object sender, EventArgs e)
{
PageWeightScale();
}
private void ComboBoxPort_TextChanged(object sender, EventArgs e)
{
string[] sport = SerialPort.GetPortNames();
toolStripComboBoxPort.Items.AddRange(sport);
}
private void FormWeightScale_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
}
//--------------------------- Function for Connecting to Serial Port ----------------------------//
private void Connection(string portName)
{
if (BtnConnect.Text == "Connect")
{
try
{
serialPort1.PortName = portName;
serialPort1.BaudRate = Convert.ToInt32(comboBoxBaudRate.Text);
serialPort1.DataBits = Convert.ToInt32(comboBoxDataBits.Text);
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBoxParity.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBoxStopBits.Text);
//serialPort1.RtsEnable= true;
//serialPort1.DtrEnable= true;
serialPort1.Open();
Console.WriteLine("Connection is open");
ProgressBarConnection.Value = 100;
BtnConnect.Text = "Disconnect";
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
serialPort1.Close();
BtnConnect.Text = "Connect";
ProgressBarConnection.Value = 0;
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
weight = serialPort1.ReadLine();
this.Invoke(new EventHandler(ShowData));
if(int.Parse(weight.ToString()) >= int.Parse(textBoxReadingLevel.Text))
{
this.Invoke(new EventHandler(setBundleData));
string insertQuery = "INSERT INTO bundle (ID , Date , Time , Size , BarGrade," +
"Length , HeatNumber , WeightZeroLevel , WeightReadingLevel ," +
"BundleMaxWeight , Weight )" +
"VALUES (#ID , #date ,#time , #barSize , #barGrade , #bundleLength , #bundleHeatNumber ," +
"#bundleWeightZeroLevel , #bundleWeightReadingLevel , #bundleMaxWeight , #bundleWeight)";
bundle1.setQueryInsertRow(insertQuery);
bundle.insertRow();
this.Invoke(new EventHandler(displayDataOnGridChart));
}
}
private void displayDataOnGridChart(object sender, EventArgs e)
{
labelPerDayProduction.Text = bundle.totalPerDayProduction.ToString("000.0");
dataGridWeightInstances.DataSource = bundle.readTable();
chartWeight.DataSource = bundle.readTable();
chartWeight.Series["Weight"].Points.Clear();
chartWeight.Series["Weight"].XValueMember = "Date";
chartWeight.Series["Weight"].XValueMember = "Time";
chartWeight.Series["Weight"].YValueMembers = "Weight";
}
private void setBundleData(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
bundle1.setDateQuery(DateTimePickerWeight.Value.ToString("dd-MM-yyyy"));
bundle1.setDate(dt.ToString("dd-MM-yyyy"));
bundle1.setTime(dt.ToString("HH:mm-tt"));
bundle1.setBarSize(ComboBoxBarSize.SelectedItem.ToString());
bundle1.setBarGrade(ComboBoxBarGrade.SelectedItem.ToString());
bundle1.setBundleLength(TextBoxCutLength.Text);
bundle1.setBundleHeatNumber(textBoxHeatNumber.Text);
bundle1.setBundleWeightZeroLevel(textBoxZeroLevel.Text);
bundle1.setBundleWeightReadingLevel(textBoxReadingLevel.Text);
bundle1.setBundleMaxWeight(textBoxMaxWeight.Text);
bundle1.setBundleWeight(int.Parse(weight.ToString()));
}
private void ShowData(object sender, EventArgs e)
{
TimerWeight.Stop();
h = 0; m = 0; s = 0;
LabelWeight.Text = weight.ToString();
TimerWeight.Interval = 1000;
TimerWeight.Start();
}
private void ComboBoxBarSize_MouseEnter(object sender, EventArgs e)
{
//ComboBoxBarSize.Text = "";
}
private void ComboBoxBarSize_MouseClick(object sender, MouseEventArgs e)
{
ComboBoxBarSize.Text = "";
}
private void ComboBoxBarSize_MouseLeave(object sender, EventArgs e)
{
ComboBoxBarSize.Text = "Bar Size";
}
private void ComboBoxPort_MouseHover(object sender, EventArgs e)
{
string[] sport = SerialPort.GetPortNames();
toolStripComboBoxPort.Items.AddRange(sport);
}
//------------------------ Functions for PAGES -------------------------//
private void PageConfiguration()
{
DateTimePickerWeight.Hide();
labelBarSize.Hide();
labelBarGrade.Hide();
labelBarCutLength.Hide();
labelHeatNumber.Hide();
labelZeroLevel.Hide();
labelReadingLevel.Hide();
labelMaxWeight.Hide();
LabelWeight.Hide();
labelStableWeightCounter.Hide();
labelPerDayProduction.Hide();
ComboBoxBarSize.Hide();
ComboBoxBarGrade.Hide();
TextBoxCutLength.Hide();
textBoxHeatNumber.Hide();
textBoxZeroLevel.Hide();
textBoxReadingLevel.Hide();
textBoxMaxWeight.Hide();
checkBoxBarSize.Hide();
checkBoxBarGrade.Hide();
checkBoxBarCutLength.Hide();
checkBoxHeatNumber.Hide();
comboBoxChartType.Hide();
chartWeight.Hide();
dataGridWeightInstances.Hide();
labelPort.Show();
labelBaudRate.Show();
labelParity.Show();
labelDataBits.Show();
labelStopBits.Show();
ComboBoxPort.Show();
comboBoxBaudRate.Show();
comboBoxParity.Show();
comboBoxDataBits.Show();
comboBoxStopBits.Show();
BtnConnect.Show();
}
private void PageWeightScale()
{
DateTimePickerWeight.Show();
labelBarSize.Show();
labelBarGrade.Show();
labelBarCutLength.Show();
labelHeatNumber.Show();
labelZeroLevel.Show();
labelReadingLevel.Show();
labelMaxWeight.Show();
LabelWeight.Show();
labelStableWeightCounter.Show();
labelPerDayProduction.Show();
ComboBoxBarSize.Show();
ComboBoxBarGrade.Show();
TextBoxCutLength.Show();
textBoxHeatNumber.Show();
textBoxZeroLevel.Show();
textBoxReadingLevel.Show();
textBoxMaxWeight.Show();
checkBoxBarSize.Show();
checkBoxBarGrade.Show();
checkBoxBarCutLength.Show();
checkBoxHeatNumber.Show();
comboBoxChartType.Show();
chartWeight.Show();
dataGridWeightInstances.Show();
labelPort.Hide();
labelBaudRate.Hide();
labelParity.Hide();
labelDataBits.Hide();
labelStopBits.Hide();
ComboBoxPort.Hide();
comboBoxBaudRate.Hide();
comboBoxParity.Hide();
comboBoxDataBits.Hide();
comboBoxStopBits.Hide();
BtnConnect.Hide();
if (ComboBoxBarSize.Text == "")
{
ComboBoxBarSize.Text = "Bar Size";
}
if (ComboBoxBarGrade.Text == "")
{
ComboBoxBarGrade.Text = "Bar Grade";
}
}
private void DateTimePickerWeight_ValueChanged(object sender, EventArgs e)
{
setData();
displayData();
}
private void DateTimePickerWeight_MouseDown(object sender, MouseEventArgs e)
{
setData();
displayData();
}
private void comboBoxChartType_SelectedValueChanged(object sender, EventArgs e)
{
chartWeight.Series["Weight"].ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), comboBoxChartType.Text);
}
private void TimerWeight_Tick(object sender, EventArgs e)
{
if (int.Parse(weight.ToString()) >= int.Parse(textBoxReadingLevel.Text))
{
s += 1;
if (s == 60)
{
s = 0;
m += 1;
if (m == 60)
{
h += 1;
}
}
labelStableWeightCounter.Text = string.Format("{0}:{1}:{2}", h.ToString().PadLeft(2, '0'), m.ToString().PadLeft(2, '0'), s.ToString().PadLeft(2, '0'));
}
}
}
}
Here is the Class of bundles
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Data;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
internal class bundle
{
// ------------------------- Variables for DATABASE DATA ---------------------//
public static int bundleID;
public static string date;
public static string time;
public static string barSize;
public static string barGrade;
public static string bundleLength;
public static string bundleHeatNumber;
public static string bundleWeightZeroLevel;
public static string bundleWeightReadingLevel;
public static string bundleMaxWeight;
public static int bundleWeight;
// ------------------------- Variables for Queries ---------------------//
public static double totalPerDayProduction;
public static string dateQuery;
public static string dbFile = "Data Source = BundleInstances.db; Version = 3";
public static string queryCreateTable;
public static string queryInsertRow;
public static string queryReadDataGrid;
public static SQLiteDataReader reader;
//---------------- Constructor ----------------//
public bundle() { }
//---------------- Set the Variable of the Class ----------------//
public string setDate(string dt)
{
date = dt;
return date;
}
public string setTime(string t)
{
time = t;
return time;
}
public int setbundleID(int bID)
{
bundleID = bID;
return bundleID;
}
public string setBarSize(string bSize)
{
barSize = bSize;
return barSize;
}
public string setBarGrade(string bGrade)
{
barGrade = bGrade;
return barGrade;
}
public string setBundleLength(string bLength)
{
bundleLength = bLength;
return bundleLength;
}
public string setBundleHeatNumber(string bHeatNumber)
{
bundleHeatNumber = bHeatNumber;
return bundleHeatNumber;
}
public string setBundleWeightZeroLevel(string bWeightZeroLevel)
{
bundleWeightZeroLevel = bWeightZeroLevel;
return bundleWeightZeroLevel;
}
public string setBundleWeightReadingLevel(string bWeightReadingLevel)
{
bundleWeightReadingLevel = bWeightReadingLevel;
return bundleWeightReadingLevel;
}
public string setBundleMaxWeight(string bMaxWeight)
{
bundleMaxWeight = bMaxWeight;
return bundleMaxWeight;
}
public int setBundleWeight(int bWeight)
{
bundleWeight = bWeight;
return bundleWeight;
}
public string setDateQuery(string dt)
{
dateQuery = dt;
return dateQuery;
}
//---------------- Set Query strings of Class ----------------//
public string setQueryCreateTable(string qCreateTable)
{
queryCreateTable = qCreateTable;
return queryCreateTable;
}
public string setQueryInsertRow(string qInsertRow)
{
queryInsertRow = qInsertRow;
return queryInsertRow;
}
public string setQueryReadDataGrid(string qReadDataGrid)
{
queryReadDataGrid = qReadDataGrid;
return queryReadDataGrid;
}
//---------------- Queries Section ----------------//
//---------------- Create Table ----------------//
public static void createTable()
{
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(queryCreateTable, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
//---------------- Insert Record ----------------//
public static void insertRow()
{
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand getIDcmd = new SQLiteCommand("SELECT MAX(ID) FROM bundle", dbConnection);
object maxID = getIDcmd.ExecuteScalar();
if (maxID.ToString() == "")
{
bundleID = 1;
}
else
{
bundleID = int.Parse(maxID.ToString());
bundleID++;
}
SQLiteCommand command = new SQLiteCommand(queryInsertRow, dbConnection);
command.Parameters.AddWithValue("#ID", bundleID++);
command.Parameters.AddWithValue("#date", date);
command.Parameters.AddWithValue("#time", time);
command.Parameters.AddWithValue("#barSize", barSize);
command.Parameters.AddWithValue("#barGrade", barGrade);
command.Parameters.AddWithValue("#bundleLength", bundleLength);
command.Parameters.AddWithValue("#bundleHeatNumber", bundleHeatNumber);
command.Parameters.AddWithValue("#bundleWeightZeroLevel", bundleWeightZeroLevel);
command.Parameters.AddWithValue("#bundleWeightReadingLevel", bundleWeightReadingLevel);
command.Parameters.AddWithValue("#bundleMaxWeight", bundleMaxWeight);
command.Parameters.AddWithValue("#bundleWeight", bundleWeight);
command.ExecuteNonQuery();
dbConnection.Close();
}
//---------------- Data Reader ----------------//
public static DataTable readTable()
{
DataTable dt = new DataTable();
string dbFile = "Data Source = BundleInstances.db; Version = 3";
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand getMaxWeightcmd = new SQLiteCommand("SELECT SUM(Weight) FROM bundle WHERE Date = #dateQuery", dbConnection);
getMaxWeightcmd.Parameters.AddWithValue("#dateQuery", dateQuery);
object weightSum = getMaxWeightcmd.ExecuteScalar();
if(weightSum.ToString() != "")
{
totalPerDayProduction = Convert.ToDouble(weightSum.ToString()) / 1000;
}
else
{
totalPerDayProduction = 0;
}
string readTable = "SELECT Date , Time , Size , Length, Weight FROM bundle WHERE Date = #dateQuery ORDER BY ID DESC";
SQLiteCommand command = new SQLiteCommand(readTable, dbConnection);
command.Parameters.AddWithValue("#dateQuery", dateQuery);
reader = command.ExecuteReader();
dt.Load(reader);
dbConnection.Close();
return dt;
}
}
}
Here is the picture of Form1.cs[Design]
Form1.cs[Design]
Here is Configuration Page:
Configuration
Weight Scale Page is:
Weight Scale
Picture of Connection of RS232 PC Side:
PC Side DB9 Connector
Picture of Connection of RS232 Device Side:
Device Side Connector Connection
The received value should be displayed on the LABEL. At present, 2080 is the TEXT Value.
The port setting is displayed here:
I try this code with arduino MEGA2560. This winform is receiving DATA serially when connected with Arduino.
I'm fairly new to C# and am trying to create a web browser for a specific function
I have Form1 (An invisible form) that calls Form2 (The browser) and monitor to make sure Form2 is always running and if it goes idle close and reopen Form2
I think I'm having an issue with threading, which I setup to run the timer (It's the only way I could work out)
I have determined that it only fails to launch Form2 when I try to call the function from inside the thread
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Browselite;
using System.Diagnostics;
using System.Threading;
namespace BrowseLite
{
public partial class Form1 : Form
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();
public static Boolean IdleTimeoutEnabled { get; private set; }
public static int IdleTimeout { get; private set; }
public static Boolean ClearRunning { get; private set; }
public Form2 Browser { get; private set; }
public static Boolean programmaticClose { get; set; }
public static Boolean Form2Open { get; set; }
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll")]
public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);
public struct tagLASTINPUTINFO
{
public uint cbSize;
public Int32 dwTime;
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
using (RegistryKey RootKey = Registry.CurrentUser.OpenSubKey("Software\\Policies\\BrowseLite"))
{
try
{
Form1.IdleTimeout = Int32.Parse(RootKey.GetValue("IdleTimeout", -1, RegistryValueOptions.None).ToString());
if (Form1.IdleTimeout <= 0)
{
Form1.IdleTimeoutEnabled = false;
}
else
{
Form1.IdleTimeoutEnabled = true;
}
}
catch
{
Form1.IdleTimeout = 0;
Form1.IdleTimeoutEnabled = false;
}
}
}
catch
{
Form1.IdleTimeout = 0;
Form1.IdleTimeoutEnabled = false;
}
Thread Timer = new Thread(new ThreadStart(MyTimer));
Browser = new Form2();
OpenBrowser();
Timer.Start();
}
private void MyTimer()
{
while (true)
{
FormCollection OpenForms = Application.OpenForms;
foreach (Form OpenForm in OpenForms)
{
if (OpenForm.Name.Contains("Form2"))
{
Form1.Form2Open = true;
}
}
if (!Form1.Form2Open)
{
Browser.ShowDialog();
Form1.Form2Open = true;
}
tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
Int32 IdleTime;
LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
LastInput.dwTime = 0;
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
int IdleTimeSet = IdleTimeout * 60 * 1000;
if (Form1.IdleTimeoutEnabled)
{
if (IdleTime >= IdleTimeSet)
{
if (Form1.ClearRunning == false)
{
CloseBrowser();
OpenBrowser();
}
}
else
{
Form1.ClearRunning = false;
}
}
}
Thread.Sleep(1000 * 30); //Time in seconds (30)
}
}
private void CloseBrowser()
{
Form1.programmaticClose = true;
Browser.Close();
}
private void OpenBrowser()
{
Form1.programmaticClose = false;
Form1.Form2Open = true;
Browser.ShowDialog();
}
}
}
Any help would be appreciated, but as I said... I'm not good with this.
For anyone else that stumbles onto this, I found the answer myself
If setting a variable in the thread. Instead of using
Form1.Running = true;
instead use
BeginInvoke(new Action(() => Form1.Running = true), null);
And if calling a function from within the thread use
BeginInvoke(new InvokeDelegate(FUNCTION));
This seems to have completely fixed my issue
I'm working on a C# UWP APP and I need to communicate with many devices using
an USB port as Serial Port. After that I will convert the communication to RS485 to communicate with the other devices. Until now, I have create a class that will make all comunications between my devices and I can sent a trama between my devices.
My problem at this point is that after sending some startup frames, the application changes the page and from that moment gives me the following exception in my ReadAsync method:
**
System.Exception occurred HResult=-2147023901 Message=The I/O
operation was canceled due to a module output or an application
request. (Exception from HRESULT: 0x800703E3) Source=mscorlib
StackTrace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at DrDeliver.CComm.d__31.MoveNext() InnerException:
**
Exception Picture
I already have this problem for a few days and I can't get over it.
I wonder if anyone can figure out where the problem is.
Another question I would like to ask is if anyone knows of any method that allows me to make this communication synchronously.
UPDATE 1
The entire class for communicatons:
public class CComm : IDisposable
{
EventLogDB _eldb = new EventLogDB();
ParameterDB _pdb = new ParameterDB();
cParameter _cParam = new cParameter();
DataReader _dataReaderObject = null;
private DispatcherTimer mTimer;
private int num;
public bool FlagComm { set; get; }
public static string InBuffer { set; get; }
public bool busyFlag = false;
public CancellationTokenSource _readCancellationTokenSource = new CancellationTokenSource();
private DeviceInformationCollection DeviceInformation { set; get; }
private static SerialDevice SerialPort { set; get; }
// Define a delegate
public delegate void CheckReadEventHandler(object source, EventArgs args);
// Define an event based on that delegate
public event CheckReadEventHandler CheckRead;
// Raise an event
protected virtual void OnChecRead()
{
CheckRead?.Invoke(this, EventArgs.Empty);
}
private async Task OpenComm()
{
try
{
busyFlag = true;
//_cParam = _pdb.getParameters();
string selectedPortId = null;
string aqs = SerialDevice.GetDeviceSelector();
DeviceInformation = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs);
foreach (var devInfo in DeviceInformation)
{
if (devInfo.Name == "USB-RS485 Cable")
{
selectedPortId = devInfo.Id;
}
}
if (selectedPortId != null)
{
SerialPort = await SerialDevice.FromIdAsync(selectedPortId);
if (SerialPort != null)
{
SerialPort.ReadTimeout = TimeSpan.FromMilliseconds(1500);
SerialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
SerialPort.BaudRate = 9600;
SerialPort.Parity = SerialParity.None;
SerialPort.StopBits = SerialStopBitCount.One;
SerialPort.DataBits = 8;
FlagComm = true;
}
else
{
var status = DeviceAccessInformation.CreateFromId(selectedPortId).CurrentStatus;
FlagComm = false;
_eldb.attachEvent("E1002", "Starting Comunication Failed: " + status);
//ContentDialog noSerialDevice = new ContentDialog()
//{
// Title = "No Serial Connection",
// Content = "Check connection and try again. App Closing.",
//};
//await noSerialDevice.ShowAsync();
//this.Dispose();
}
InitTool();
await ActivateListen();
busyFlag = false;
}
}
catch (Exception ex)
{
_eldb.attachEvent("E1cC", ex.Message);
}
}
private async Task Listen()
{
try
{
if (SerialPort != null)
{
busyFlag = true;
_dataReaderObject = new DataReader(SerialPort.InputStream);
await ReadAsync(_readCancellationTokenSource.Token);
busyFlag = false;
}
}
catch (Exception ex)
{
}
}
//using (var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000)))
//{
// await dataReaderObject.LoadAsync(1024).AsTask(cts.Token);
//}
private async Task ReadAsync(CancellationToken cancellationToken)
{
busyFlag = true;
const uint readBufferLength = 1024; // only when this buffer would be full next code would be executed
var loadAsyncTask = _dataReaderObject.LoadAsync(readBufferLength).AsTask(cancellationToken); // Create a task object
_dataReaderObject.InputStreamOptions = InputStreamOptions.ReadAhead;
var bytesRead = await loadAsyncTask; // Launch the task and wait until buffer would be full
if (bytesRead > 0)
{
InBuffer += _dataReaderObject.ReadString(bytesRead);
OnChecRead();
}
busyFlag = false;
}
private async void WriteComm(string str2Send)
{
using (var dataWriter = new DataWriter(SerialPort.OutputStream))
{
dataWriter.WriteString(str2Send);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
}
private async Task ActivateListen()
{
while (FlagComm)
{
await Listen();
}
}
private void dispatcherTimer_Tick(object sender, object e)
{
_eldb.attachEvent("SYSTEM", "Checking ADDR: " + num);
SendComm(num++, 5);
if (num == 5)
{
mTimer.Stop();
_eldb.attachEvent("SYSTEM", "Modules Checking Finished.");
busyFlag = false;
}
}
public void InitTool()
{
busyFlag = true;
_eldb.attachEvent("SYSTEM", "Setting Parameters.");
// Get Parameters
if (_pdb.GetParameters() == null)
{
// Set Default Parameters
_cParam.SetParam();
// Insert Default parameters in database
_pdb.Insert(_cParam);
// Update Parameters Object
_cParam = _pdb.GetParameters();
}
else
{
// Update Parameters Object
_cParam = _pdb.GetParameters();
}
// Check Addresses in Line
_eldb.attachEvent("SYSTEM", "Start Verifiyng.");
num = 0;
mTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(4000) };
mTimer.Tick += dispatcherTimer_Tick;
mTimer.Start();
}
public async void StartSerialComm()
{
try
{
await OpenComm();
}
catch (Exception ex)
{
_eldb.attachEvent("E7cC", ex.Message);
}
}
public void SendComm(params int[] list)
{
try
{
_cParam = _pdb.GetParameters();
string toSend = "";// = "A" + list[0] + "#";
switch (list[1])
{
case 0:
// Send Initialazation command
toSend = "##" + list[0] + "#" + list[1] + "##";
break;
case 1:
// List of parameters (minPower, maxPower, ramPercent, initSpeed)
toSend = "##" + list[0] + "#" + list[1] + "#" + _cParam.minPower + "#" +
_cParam.maxPower + "#" + _cParam.percRamp + "#" + _cParam.initSpeed + "##";
break;
case 2:
// Send Status Request
toSend = "##" + list[0] + "#" + list[1] + "##";
break;
case 3:
// Send a move Request
toSend = "##" + list[0] + "#" + list[1] + "#" + list[2] + "##";
break;
case 4:
// Send a Error Request
toSend = "##" + list[0] + "#" + list[1] + "##";
break;
case 5:
// Send a start check
toSend = "##" + list[0] + "#" + list[1] + "##";
break;
default:
_eldb.attachEvent("E1004", "Wrong Function Command.");
break;
}
if (toSend != "")
{
WriteComm(toSend);
}
else
{
_eldb.attachEvent("E1003", "Wrong String comunication.");
}
}
catch (Exception ex)
{
_eldb.attachEvent("E8cC", ex.Message);
}
}
public void Dispose()
{
try
{
if (SerialPort == null) return;
FlagComm = false;
SerialPort.Dispose();
SerialPort = null;
if (_dataReaderObject == null) return;
_readCancellationTokenSource.Cancel();
_readCancellationTokenSource.Dispose();
}
catch (Exception ex)
{
_eldb.attachEvent("E6cC", ex.Message);
}
}
}
Main Page:
public sealed partial class MainPage : Page
{
CComm _cC = new CComm();
EventLogDB _eldb = new EventLogDB();
procTrama _cProcTrama = new procTrama();
private DispatcherTimer mTimer;
public MainPage()
{
try
{
InitializeComponent();
// Get the application view title bar
ApplicationViewTitleBar appTitleBar = ApplicationView.GetForCurrentView().TitleBar;
// Make the title bar transparent
appTitleBar.BackgroundColor = Colors.Transparent;
// Get the core appication view title bar
CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
/*
ExtendViewIntoTitleBar
Gets or sets a value that specifies whether this title
bar should replace the default window title bar.
*/
// Extend the core application view into title bar
coreTitleBar.ExtendViewIntoTitleBar = true;
mTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(5000) };
mTimer.Tick += dispatcherTimer_Tick;
mTimer.Start();
_eldb.attachEvent("S1027", "Init Started...");
// Start comunication
_cC.StartSerialComm();
// Reference for CheckRead Event
_cC.CheckRead += OnCheckRead;
}
catch (Exception ex)
{
_eldb.attachEvent("MainP", ex.Message);
}
}
private void dispatcherTimer_Tick(object sender, object e)
{
if (!_cC.busyFlag)
{
Frame.Navigate(typeof(InitPage), null);
mTimer.Stop();
}
}
public void OnCheckRead(object source, EventArgs e)
{
try
{
if (CComm.InBuffer == null) return;
_cProcTrama.ProcessTrama(CComm.InBuffer);
CComm.InBuffer = "";
}
catch (Exception ex)
{
_eldb.attachEvent("OnCheckRead: ", ex.Message);
}
}
}
INIT Page:
public partial class InitPage : Page
{
CComm _cC = new CComm();
EventLogDB _eldb = new EventLogDB();
procTrama _cProcTrama = new procTrama();
public InitPage()
{
this.InitializeComponent();
_eldb.attachEvent("S1000", "System Started.");
// Reference for CheckRead Event
_cC.CheckRead += OnCheckRead;
}
private void button_Click(object sender, RoutedEventArgs e)
{
_eldb.attachEvent("S1001", "Login Activated.");
Frame.Navigate(typeof(Page1), null);
}
public void OnCheckRead(object source, EventArgs e)
{
if (CComm.InBuffer == null) return;
_eldb.attachEvent("OnCheckRead: ", CComm.InBuffer);
_cProcTrama.ProcessTrama(CComm.InBuffer);
}
}
Login Page where i more frequently the error occur:
public sealed partial class Page1 : Page
{
private CComm _cC = new CComm();
private procTrama _cProcTrama = new procTrama();
EventLogDB _eldb = new EventLogDB();
public Page1()
{
this.InitializeComponent();
// Reference for CheckRead Event
_cC.CheckRead += OnCheckRead;
user = null;
pass = null;
user_pass = 0;
}
private const int userLimit = 5;
private const int passLimit = 5;
private const char passChar = '*';
public string user
{
get; set;
}
public string pass
{
get; set;
}
public int user_pass
{
get; set;
}
private void execute(char val)
{
string aux = null;
if (user_pass == 1)
{
if (user == null)
user = val.ToString();
else
{
if (user.Length <= userLimit)
user = user + val;
}
userBtn.Content = user;
}
else
{
if (user_pass == 2)
{
if (pass == null)
pass = val.ToString();
else
{
if (pass.Length <= passLimit)
pass = pass + val;
}
for (int i = 0; i < pass.Length; i++)
aux = aux + passChar;
passBtn.Content = aux;
}
}
}
private void key1Btn_Click(object sender, RoutedEventArgs e)
{
execute('1');
}
private void key2Btn_Click(object sender, RoutedEventArgs e)
{
execute('2');
}
private void key3Btn_Click(object sender, RoutedEventArgs e)
{
execute('3');
}
private void key4Btn_Click(object sender, RoutedEventArgs e)
{
execute('4');
}
private void key5Btn_Click(object sender, RoutedEventArgs e)
{
execute('5');
}
private void key6Btn_Click(object sender, RoutedEventArgs e)
{
execute('6');
}
private void key7Btn_Click(object sender, RoutedEventArgs e)
{
execute('7');
}
private void key8Btn_Click(object sender, RoutedEventArgs e)
{
execute('8');
}
private void key9Btn_Click(object sender, RoutedEventArgs e)
{
execute('9');
}
private void key0Btn_Click(object sender, RoutedEventArgs e)
{
execute('0');
}
private void keyEntrarBtn_Click(object sender, RoutedEventArgs e)
{
if (pass == "123" && user == "123")
{
_eldb.attachEvent("S1002", "User Login: " + user);
Frame.Navigate(typeof(Page2), null);
}
user_pass = 0;
passBtn.Content = "Insirir Código";
userBtn.Content = "Inserir Utilizador";
}
private void keyApagarBtn_Click(object sender, RoutedEventArgs e)
{
pass = null;
user = null;
user_pass = 0;
passBtn.Content = "Inserir Código";
userBtn.Content = "Inserir Utilizador";
_eldb.attachEvent("S1003", " User data cleared.");
}
private void userBtn_Click(object sender, RoutedEventArgs e)
{
user_pass = 1;
userBtn.Content = "";
_eldb.attachEvent("S1004", "User button clicked.");
}
private void passBtn_Click(object sender, RoutedEventArgs e)
{
user_pass = 2;
passBtn.Content = "";
_eldb.attachEvent("S1005", "Pass button clicked.");
}
private void exitBtn_Click(object sender, RoutedEventArgs e)
{
_eldb.attachEvent("S1006", "Page1 exit button clicked.");
Frame.Navigate(typeof(InitPage), null);
}
public void OnCheckRead(object source, EventArgs e)
{
try
{
if (CComm.InBuffer == null) return;
_eldb.attachEvent("OnCheckRead: ", CComm.InBuffer);
_cProcTrama.ProcessTrama(CComm.InBuffer);
}
catch (Exception ex)
{
_eldb.attachEvent("OnCheckRead: ", ex.Message);
}
}
}
I am using tapi programming in order to communicate
with a device and send-receive calls. At this moment i am able
to make external calls, and "see" who is calling me when
i pick up the phone. For some reason i can't see the number
at the event < CALL_STATE.CS_OFFERING > (When your phone rings).
I post my code below (it is similar to one i found on the internet).
Any help will be appreciated!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TapiSample
{
public partial class Form1 : Form
{
static public IAsyncResult result;
public Form1()
{
InitializeComponent();
tapi = new TAPI3Lib.TAPIClass();
tapi.Initialize();
foreach (TAPI3Lib.ITAddress ad in (tapi.Addresses as TAPI3Lib.ITCollection))
{
cbLines.Items.Add(ad.AddressName);
}
tapi.EventFilter = (int)(TAPI3Lib.TAPI_EVENT.TE_CALLNOTIFICATION |
TAPI3Lib.TAPI_EVENT.TE_CALLINFOCHANGE |
TAPI3Lib.TAPI_EVENT.TE_DIGITEVENT |
TAPI3Lib.TAPI_EVENT.TE_PHONEEVENT |
TAPI3Lib.TAPI_EVENT.TE_CALLSTATE |
TAPI3Lib.TAPI_EVENT.TE_GENERATEEVENT |
TAPI3Lib.TAPI_EVENT.TE_GATHERDIGITS |
TAPI3Lib.TAPI_EVENT.TE_REQUEST);
tapi.ITTAPIEventNotification_Event_Event += new TAPI3Lib.ITTAPIEventNotification_EventEventHandler(tapi_ITTAPIEventNotification_Event_Event);
}
TAPI3Lib.TAPIClass tapi = null;
TAPI3Lib.ITAddress line = null;
int cn = 0;
private void button1_Click(object sender, EventArgs e)
{
if (line != null)
{
line = null;
if (cn != 0) tapi.UnregisterNotifications(cn);
}
foreach (TAPI3Lib.ITAddress ad in (tapi.Addresses as TAPI3Lib.ITCollection))
{
if (ad.AddressName == cbLines.Text)
{
line = ad;
break;
}
}
if (line != null)
{
cn = tapi.RegisterCallNotifications(line, true, true, TAPI3Lib.TapiConstants.TAPIMEDIATYPE_AUDIO, 2);
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (cn != 0) tapi.UnregisterNotifications(cn);
}
delegate void AddLogDelegate(string text);
private void AddLog(string text)
{
if (this.InvokeRequired)
{
result = this.BeginInvoke(new AddLogDelegate(AddLog), new object[] { text });
}
listBox1.Items.Insert(0, text);
}
private void tapi_ITTAPIEventNotification_Event_Event(TAPI3Lib.TAPI_EVENT TapiEvent, object pEvent)
{
try
{
switch (TapiEvent)
{
case TAPI3Lib.TAPI_EVENT.TE_CALLNOTIFICATION:
AddLog("call notification event has occured");
break;
case TAPI3Lib.TAPI_EVENT.TE_CALLSTATE:
TAPI3Lib.ITCallStateEvent tcallStateEvent = (TAPI3Lib.ITCallStateEvent)pEvent;
TAPI3Lib.ITCallInfo b = tcallStateEvent.Call;
switch (b.CallState)
{
case TAPI3Lib.CALL_STATE.CS_OFFERING:
string str2 = b.get_CallInfoString(TAPI3Lib.CALLINFO_STRING.CIS_CALLERIDNUMBER);
AddLog("Number Calling:" + str2); //Doesn't work
return;
case TAPI3Lib.CALL_STATE.CS_CONNECTED:
string str = b.get_CallInfoString(TAPI3Lib.CALLINFO_STRING.CIS_CALLERIDNUMBER);
AddLog("Communicating with: " + str);
return;
case TAPI3Lib.CALL_STATE.CS_DISCONNECTED:
this.EndInvoke(result);
AddLog("Call Disconnected");
return;
}
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (line == null) return;
TAPI3Lib.ITBasicCallControl bc = line.CreateCall(teNumber.Text, TAPI3Lib.TapiConstants.LINEADDRESSTYPE_PHONENUMBER, TAPI3Lib.TapiConstants.TAPIMEDIATYPE_AUDIO);
bc.Connect(false);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
For same kind of problem I used a managed C# wrapper for Tapi written by Julmar , You can download its dll,
By using this Sample you can also record incoming call in .wav format
TPhone tphone;
TTapi tobj;
TTerminal recordTerminal;
TCall CurrCall;
void InitializeTapi()
{
tobj = new TTapi();
tobj.Initialize();
tobj.TE_CALLNOTIFICATION += new System.EventHandler<JulMar.Tapi3.TapiCallNotificationEventArgs>(this.OnNewCall);
tobj.TE_CALLSTATE += new System.EventHandler<JulMar.Tapi3.TapiCallStateEventArgs>(this.OnCallState);
tobj.TE_CALLINFOCHANGE += tobj_TE_CALLINFOCHANGE;
foreach (TPhone tp in tobj.Phones)
{
tphone = tp;
tphone.Open(PHONE_PRIVILEGE.PP_OWNER);
}
foreach (TAddress addr in tobj.Addresses)
{
if (addr.QueryMediaType(TAPIMEDIATYPES.AUDIO))
{
try
{
addr.Open(TAPIMEDIATYPES.AUDIO);
}
catch (TapiException ex)
{
if (ex.ErrorCode == unchecked((int)0x80040004))
{
try
{
addr.Open(TAPIMEDIATYPES.DATAMODEM);
}
catch (Exception ex2)
{
}
}
}
}
}
}
void tobj_TE_CALLINFOCHANGE(object sender, TapiCallInfoChangeEventArgs e)
{
try
{
CurrCall = e.Call;
txtCallerId.Text = e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLERIDNUMBER).ToString();
objCallLog.CallerID = txtCallerId.Text;
Task.Factory.StartNew(() => AnswerCall());
}
catch (Exception ex)
{
}
}
void OnNewCall(object sender, TapiCallNotificationEventArgs e)
{
CurrCall = e.Call;
}
void OnCallState(object sender, EventArgs E)
{
try
{
TapiCallStateEventArgs e = E as TapiCallStateEventArgs;
CurrCall = e.Call;
TapiPhoneEventArgs ev = E as TapiPhoneEventArgs;
switch (e.State)
{
case CALL_STATE.CS_OFFERING:
break;
case CALL_STATE.CS_CONNECTED:
break;
case CALL_STATE.CS_DISCONNECTED:
try
{
if (recordTerminal != null)
recordTerminal.Stop();
recordTerminal = null;
CurrCall.Dispose();
}
catch (Exception ex)
{
}
finally
{
CurrCall = null;
}
break;
}
}
catch (Exception ex)
{
}
}
void OnCallChangeEvent(object sender, TapiCallInfoChangeEventArgs e)
{
CurrCall = e.Call;
}
private void AnswerCall()
{
try
{
lock (lockAnswer)
{
if (CallStat == CallState.Offering)
{
CurrCall.Answer();
RecordConversation();
}
else
{
}
}
}
catch (Exception ex)
{
}
}
void RecordConversation()
{
if (CurrCall != null)
{
try
{
recordTerminal = CurrCall.RequestTerminal(
TTerminal.FileRecordingTerminal,
TAPIMEDIATYPES.MULTITRACK, TERMINAL_DIRECTION.TD_RENDER);
if (recordTerminal != null)
{
recordTerminal.RecordFileName = "FileName.wav";
CurrCall.SelectTerminalOnCall(recordTerminal);
recordTerminal.Start();
}
else
{
MessageBox.Show("Error in recording file.");
}
}
catch (TapiException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Internally TAPI handles state and call information separately. So the calling number (a.k.a. CLIP) can be sent before or after the offering state itself. So you are not guaranteed to have the CLIP at the time of the offering state. It can come later in a a call info change event.
You are already requesting TAPI3Lib.TAPI_EVENT.TE_CALLINFOCHANGE in your filter but you are not handling it in your TapiEvent switch statement. So you will need to implement this.
Side note: it is possible for something calling you to not have a CLIP
I am new to c# and I don't know if I am doing this right. My problem is that I need to return the error from a class(.dll) but I don't know how.It only returns true or false. This is the code of my class:
namespace DigitalAssetConverter
{
public class ConvertImage
{
public Boolean ImagePath(string filePath)
{
try
{
MagickReadSettings settings = new MagickReadSettings();
settings.ColorSpace = ColorSpace.RGB;
using (MagickImage image = new MagickImage(filePath))
{
image.Read(filePath, settings);
image.Resize(500, 500);
image.Write(Path.ChangeExtension(filePath, ".jpg"));
return true;
}
}
catch
{
return false;
}
}
}
}
and I use it like this:
private void btnConvert_Click(object sender, EventArgs e)
{
ConvertImage ci = new ConvertImage();
if (ci.ImagePath(#"C:\tryConvert\LP_10078.eps"))
{
MessageBox.Show("Success!");
}
else
{
MessageBox.Show("Failed.");
}
}
Omit the try/catch block and make the return type void:
public void ImagePath(string filePath)
{
MagickReadSettings settings = new MagickReadSettings();
settings.ColorSpace = ColorSpace.RGB;
using (MagickImage image = new MagickImage(filePath))
{
image.Read(filePath, settings);
image.Resize(500, 500);
image.Write(Path.ChangeExtension(filePath, ".jpg"));
}
}
The exception (if any) will bubble up on its own, and you can place a try/catch block in the btnConvert_Click event to handle it instead:
private void btnConvert_Click(object sender, EventArgs e)
{
ConvertImage ci = new ConvertImage();
try
{
ci.ImagePath(#"C:\tryConvert\LP_10078.eps")
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}