Transferring from one form to another - c#

So I'm trying to find out and breaking each method while running my codes, and I still can't find why setTempID is always 0, I already assigned a value to it.
Here is my 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.Data.Sql;
using System.Data.SqlClient;
//imports
using DHELTASSys.DataAccess;
using DHELTASSys.Modules;
using DHELTASSys.AuditTrail;
namespace Enrollment
{
public partial class HRLogin : Form
{
HRModuleBL obj = new HRModuleBL();
DHELTASSysAuditTrail audit = new DHELTASSysAuditTrail();
public HRLogin()
{
InitializeComponent();
}
private void txtLogin_Click(object sender, EventArgs e)
{
obj.Emp_id = int.Parse(txtEmpID.Text);
audit.Emp_id = int.Parse(txtEmpID.Text);
obj.Password = txtPassword.Text;
if (obj.AccountEnrollmentLogin().Rows.Count == 0)
{
MessageBox.Show("Username and Password is incorrect!");
}
else if (obj.CheckIfHRManager().Rows.Count == 0)
{
MessageBox.Show("You are not allowed to access this system!");
}
else
{
CreateAccount frm = new CreateAccount();
frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);
audit.AddAuditTrail("Has logged in into the Fingerprint Enrollment System.");
frm.setEmpID = int.Parse(txtEmpID.Text);
frm.Show();
this.Hide();
}
}
void frm_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
and here is the other form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
//imports
using DHELTASSys.AuditTrail;
using DHELTASSys.Modules;
namespace Enrollment
{
delegate void Function(); // a simple delegate for marshalling calls from event handlers to the GUI thread
public partial class CreateAccount : Form
{
HRModuleBL obj = new HRModuleBL();
DHELTASSysAuditTrail audit = new DHELTASSysAuditTrail();
private int emp_id;
public int setEmpID
{
set { emp_id = value;}
}
public CreateAccount()
{
InitializeComponent();
}
private void CloseButton_Click(object sender, EventArgs e)
{
Close();
}
private void OnTemplate(DPFP.Template template)
{
this.Invoke(new Function(delegate()
{
Template = template;
VerifyButton.Enabled = SaveButton.Enabled = (Template != null);
if (Template != null)
MessageBox.Show("The fingerprint template is ready for verification and saving", "Fingerprint Enrollment");
else
MessageBox.Show("The fingerprint template is not valid. Repeat fingerprint enrollment.", "Fingerprint Enrollment");
}));
}
private DPFP.Template Template;
private void EnrollButton_Click(object sender, EventArgs e)
{
EnrollmentForm Enroller = new EnrollmentForm();
Enroller.OnTemplate += this.OnTemplate;
Enroller.ShowDialog();
}
private void SaveButton_Click(object sender, EventArgs e)
{
obj.Last_name = txtLastname.Text;
obj.First_name = txtFirstName.Text;
obj.Middle_name = txtMiddleName.Text;
obj.Position_name = cmbPosition.Text;
obj.Company_name = cmbCompany.Text;
obj.Password = txtTempPassword.Text;
obj.Department_name = cmbDepartment.Text;
if (obj.Last_name == string.Empty) //Validation for empty texts
{
MessageBox.Show("Last name can't be empty!");
} else if (obj.First_name == string.Empty)
{
MessageBox.Show("First name can't be empty!");
}
else if (obj.Middle_name == string.Empty)
{
MessageBox.Show("Middle name can't be empty!");
}
else if (obj.Position_name == string.Empty)
{
MessageBox.Show("Position name can't be empty!");
}
else if (obj.Department_name == string.Empty)
{
MessageBox.Show("Deparment can't be empty!");
}
else if (obj.Company_name == string.Empty)
{
MessageBox.Show("Company name can't be empty!");
}
else if (obj.Password == string.Empty)
{
MessageBox.Show("Password can't be empty!");
}
else if (txtConfirmTempPassword.Text == string.Empty)
{
MessageBox.Show("Please verify your input password!");
}
else
{
if (txtTempPassword.Text != txtConfirmTempPassword.Text)
{
MessageBox.Show("Password does not match", "Password Mismatch",
MessageBoxButtons.OK);
}
else
{
MemoryStream fingerprintData = new MemoryStream();
Template.Serialize(fingerprintData);
fingerprintData.Position = 0;
BinaryReader br = new BinaryReader(fingerprintData);
Byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length);
audit.Emp_id = emp_id;
obj.Biometric_code = bytes;
obj.AddAccountSetTempPassword();
}
}
}
private void VerifyButton_Click(object sender, EventArgs e)
{
VerificationForm Verifier = new VerificationForm();
Verifier.Verify(Template);
}
}
}
I'm setting it to frm.setEmpID so that I could get it from another form.
Thanks for the help man.

Perhaps in your SaveButton_Click event in the CreateAccount form you need to set also the Emp_Id variable of the obj instance defined inside that form (as you have done in the instance of the HRModuleBL defined in the first form).
private void SaveButton_Click(object sender, EventArgs e)
{
.....
audit.Emp_id = emp_id;
obj.Emp_id = emp_id;
obj.Biometric_code = bytes;
obj.AddAccountSetTempPassword();
.....
}

Related

Losing \n when sent to other form c#

I am working on a project where im supposed to send a list of titles to a "central computer".
My problem is that when I send them with the button sendAll I lose a couple och linebreaks.
Anyone got some advice on how to get this to work?
Since this is a school assignment I cant access the "central computer". I can only work with my own program.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Avdelningsrapport
{
public partial class KlientForm : Form
{
TcpClient client = new TcpClient();
int port = 12345;
FileLoader fileLoader = new FileLoader();
List<Book> ListOfBooks = FileLoader.BookIndex;
public KlientForm()
{
InitializeComponent();
client.NoDelay = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnImportData_Click(object sender, EventArgs e)
{
foreach (Book item in ListOfBooks)
{
listBoxObj.Items.Add(item);
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (!client.Connected) StartConnection();
if (client.Connected)
{
btnConnect.BackColor = Color.Green;
}
}
public async void StartConnection()
{
try
{
IPAddress adress = IPAddress.Parse("127.0.0.1");
await client.ConnectAsync(adress, port);
}
catch (Exception error) { MessageBox.Show(error.Message, Text); return;}
btnConnect.Enabled = false;
btnSendAll.Enabled = true;
btnSendMarked.Enabled = true;
}
private void btnSendAll_Click(object sender, EventArgs e)
{
if (!client.Connected)
{
MessageBox.Show("Du måste ansluta till servern.");
}
else
{
if (listBoxObj.Items.Count == 0)
{
MessageBox.Show("Det finns inga böcker att skicka.");
}
else
{
foreach (Book item in listBoxObj.Items)
{
StartSend(item.ToString());
}
ListOfBooks.Clear();
listBoxObj.Items.Clear();
}
}
}
private void btnSendMarked_Click(object sender, EventArgs e)
{
if (!client.Connected)
{
MessageBox.Show("Du måste ansluta till servern.");
}
else
{
if (listBoxObj.SelectedIndex == -1)
{
MessageBox.Show("Du måste välja en bok du vill skicka.");
}
else
{
StartSend(listBoxObj.SelectedItem.ToString());
ListOfBooks.RemoveAt(listBoxObj.SelectedIndex);
listBoxObj.Items.RemoveAt(listBoxObj.SelectedIndex);
}
}
}
public async void StartSend(string SendingBook)
{
byte[] outData = Encoding.Unicode.GetBytes(SendingBook);
try
{
await client.GetStream().WriteAsync(outData, 0, outData.Length);
}
catch (Exception error) { MessageBox.Show(error.Message, Text); return; }
}
}
}

C# WPF Checkbox with null value?

I am currently making a GUI in WPF, and am working on a page intended to create and configure message rooms but the following code below
else if (Password_Enabled.IsChecked == true && Password.Text.Length == 0)
{
return false;
}
appears with an error of
Password_Enabled.IsChecked 'Password_Enabled.IsChecked' threw an exception of type 'System.NullReferenceException'
My Xaml for the CheckBox appears as follows
<CheckBox x:Name="Password_Enabled" IsChecked="False" Content="Password Enabled" HorizontalAlignment="Left" VerticalAlignment="Top" Checked="Password_Enabled_Checked" Unchecked="Password_Disabled_Checked" Margin="10,5,0,0" Grid.RowSpan="2"/>
I've searched online, but with errors like these it's standardised, I know it means that the checkbox is being treated as null. But while searching through my code haven't found anything stating why, any help on this would be much appreciated, thank you.
Edit
My FullCode for the Page C# is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ChatRoom
{
/// <summary>
/// Interaction logic for New_Server.xaml
/// </summary>
public partial class New_Server : Page
{
public New_Server()
{
InitializeComponent();
Owner.Text = Global_Class.GetUsername(Environment.UserName);
}
public static string ChosenAddress = "";
private bool CheckValidCredentials()
{
List<string> IllegalCharacters = new List<string>() { ",", "|", "\\", "/", ".", "?", "\"", "<", ">", ":" };
bool Illegal = false;
if (ServerName.Text.Length == 0)
{
return false;
}
foreach (string Check in IllegalCharacters)
{
if (ServerName.Text.Contains(Check))
{
Illegal = true;
break;
}
}
if (Illegal)
{
return false;
}
else if (Password_Enabled.IsChecked == true && Password.Text.Length == 0)
{
return false;
}
else if (ChosenAddress == "")
{
return false;
}
else
{
return true;
}
}
public void SetMakeServer()
{
if (CheckValidCredentials())
{
MakeServer.IsEnabled = true;
}
else
{
MakeServer.IsEnabled = false;
}
}
private void Public_Server_Checked(object sender, RoutedEventArgs e)
{
MessageBox.Show("This Server Will Be Open to everyone in the College, Please Untick if you wish to change this.");
CheckValidCredentials();
}
private void Password_Enabled_Checked(object sender, RoutedEventArgs e)
{
Password.IsEnabled = true;
OneTimePass.IsEnabled = true;
SetMakeServer();
}
private void Password_Disabled_Checked(object sender, RoutedEventArgs e)
{
Password.IsEnabled = false;
OneTimePass.IsEnabled = false;
SetMakeServer();
}
private void Back_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Server_Selection());
}
private void ServerDirectorySet_Click(object sender, RoutedEventArgs e)
{
using (var fbd = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = fbd.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
ChosenAddress = fbd.SelectedPath;
ServerDirectoryDisplay.Content = "Location: " + ChosenAddress;
}
else
{
ChosenAddress = "";
SetMakeServer();
}
}
}
private void ServerName_TextChanged(object sender, TextChangedEventArgs e)
{
SetMakeServer();
}
private void Password_TextChanged(object sender, TextChangedEventArgs e)
{
SetMakeServer();
}
}
}
InitializeComponent has to finish before you interact with anything on the UI. If you try to access visual elements in your code before WPF has finished initializing them you'll get the null errors.

Passing user login data from form1 to form2 listview using access database

I have created a program that needs to pass the employee number login data (Log_in) to the 2nd form (form1). I already created the database that consist of 3 tables: Employee_Information, SN_Incoming, and Duplicate. I want the employee number found in the Employee Information move over to the SN_Incoming table. That data will then be displayed in a listview.
Login Form 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.Data.OleDb;
namespace Serial_Number_Checker
{
public partial class Log_In : Form
{
public Log_In()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Please enter your employee #!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox1.Focus();
return;
}
try
{
Duplicate_Serial_Number_CheckerDataSetTableAdapters.Employee_InformationTableAdapter Employee_Number = new Duplicate_Serial_Number_CheckerDataSetTableAdapters.Employee_InformationTableAdapter();
Duplicate_Serial_Number_CheckerDataSet.Employee_InformationDataTable dt = Employee_Number.GetDataByEmployee_Number(textBox1.Text);
if (dt.Rows.Count > 0)
{
MessageBox.Show("You have been successfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); // Process your login here
this.Hide();
Form1 form1 = new Form1();
if (form1.ShowDialog() != DialogResult.OK)
Application.Exit();
}
else
{
MessageBox.Show("Your Employee # is not registered. Please contact your Supervisor to be registered.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
button1.PerformClick();
}
}
}
Form1 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.Configuration;
using System.Data.OleDb;
namespace Serial_Number_Checker
{
public partial class Form1 : Form
{
static string conString= "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=";
OleDbConnection con = new OleDbConnection(conString);
OleDbCommand cmd;
OleDbDataAdapter adapter;
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
listView1.SelectedIndexChanged += new EventHandler (listView1_SelectedIndexChanged); // Adding columns to listView1
// list view properities
listView1.View = View.Details;
listView1.FullRowSelect = true;
// Add Columns
listView1.Columns.Add("Employee #", 150);
listView1.Columns.Add("Serial Number", 150);
listView1.Columns.Add("Date/Time", 150);
}
// Add Row
private void InsertSerialNumber(string sn)
{
using (OleDbCommand odc = new OleDbCommand("INSERT INTO SN_Incoming (SN) VALUES(#SN)", con))
{
odc.Parameters.AddWithValue("#SN", sn);
try
{
con.Open();
odc.ExecuteNonQuery();
}
catch (Exception e) { MessageBox.Show(e.Message);
}
finally { con.Close();
}
}
}
// Add To ListView1
private void populate(String employeeid, String sn, String timestamp)
{
// Row
String[] row = { employeeid, sn, timestamp };
ListViewItem item = new ListViewItem(row);
listView1.Items.Add(item);
}
private void clearTxts()
{
textBox1.Text = "";
}
// Retrieve Check In
private void LoadSerialNumbers() {
listView1.Items.Clear();
DataTable dt = new DataTable();
using (OleDbCommand odc = new OleDbCommand("SELECT * FROM SN_Incoming", con)) {
try {
con.Open();
using (OleDbDataAdapter oda = new OleDbDataAdapter(odc))
oda.Fill(dt);
} catch (Exception e) { MessageBox.Show(e.Message); } finally { con.Close(); }
}
List<ListViewItem> items = new List<ListViewItem>();
foreach (DataRow row in dt.Rows) {
ListViewItem lvi = items.SingleOrDefault(s => s.Tag == row[1].ToString());
if (lvi != null)
continue;
lvi = new ListViewItem(new string[] { row[0].ToString(), row[1].ToString(), row[2].ToString() });
lvi.Tag = row[1].ToString();
items.Add(lvi);
}
listView1.Items.AddRange(items.ToArray());
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
{
foreach (ListViewItem lvi in listView1.SelectedItems)
listView1.Items.Remove(lvi);
if (string.IsNullOrWhiteSpace(textBox1.Text))
MessageBox.Show("Please enter a serial number!", "Input");
else
InsertSerialNumber(textBox1.Text);
textBox1.Text = string.Empty;
textBox1.Focus();
textBox1.SelectionStart = textBox1.Text.Length == 0 ? 0 : textBox1.Text.Length - 1;
textBox1.SelectionLength = 0;
LoadSerialNumbers();
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void listView1_SelectedIndexChanged_1(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
}
// If enter is pressed down during input, it will automatically submit
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(this, new EventArgs());
}
}
}
}
I have already set my primary key to Employee_Number. I need to learn how to pass that information to the next table. So I can retrieve and put in my listview. Your help is greatly appreciated. Thanks
Just add a parameter to the constructor of Form1:
public Form1(string id)
{
InitializeComponent();
//Do whatever you like with the passed-in id:
MessageBox.Show($"you passed me Id {id}");
}
To Use:
Form1 form1 = new Form1(TextBox1.Text);
if (form1.ShowDialog() != DialogResult.OK)
Application.Exit();
Though Generally, I'd advise moving all the DB stuff and 'Who's currently logged in' code to separate repository/service classes which are commonly available everywhere.

Usercontrol event firing multiple times asp.net c#

I've got the following code: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Testing.Event_Delegate
{
public partial class WebForm1 : System.Web.UI.Page
{
WebUserControl2 QT2;
WebUserControl3 QT3;
DataTable dtQuestionSet;
protected void Page_Init(object sender, EventArgs e)
{
dtQuestionSet = (DataTable)Session["DataTableW"];
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
Session["Counter"] = 0;
Session["QuestionCount"] = 0;
Session["CompletedInsp"] = false;
}
//check to see if the inspection process is complete and display pass\fail and log. Else carry on.
if (Convert.ToBoolean(Session["CompletedInsp"]) == true)
{
//Response.Write("Failed");
ModalPopupExtender2.Show();
return;
}
// all controls need to be rendered every page postback otherwise the rest of the code loses scope.
QT2 = (WebUserControl2)this.LoadControl("WebUserControl2.ascx");
UC2BtnClickEvent.MyEvent2 += new UC2BtnClickEvent.OnMyEvent2(ChecKResult);
QT3 = (WebUserControl3)this.LoadControl("WebUserControl3.ascx");
UC2BtnClickEvent.MyEvent3 += new UC2BtnClickEvent.OnMyEvent3(ChecKResult);
PlaceHolder2.Controls.Add(QT2);
PlaceHolder2.Controls.Add(QT3);
QT2.Visible = false;
QT3.Visible = false;
if (IsPostBack == false)
{
dtQuestionSet = new DataTable();
MakeDataTabledtQuestionSet();
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
}
Session["DataTableW"] = dtQuestionSet;
}
void ChecKResult(object sender, EventArgs e, string strTextBox, string strMyDescription)
{
Label1.Text = "You Answered: - " + strMyDescription;
if (Convert.ToInt32(Session["Counter"]) > Convert.ToInt32(Session["QuestionCount"]))
{
Session["CompletedInsp"] = true;
}
else
{
//carry on with inspection
Session["Counter"] = Convert.ToInt32(Session["Counter"]) + 1;
dtQuestionSet = (DataTable)Session["DataTableW"];
RunInspection();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
protected void cmdStartInspection_Click(object sender, EventArgs e)
{
Session["Counter"] = 0;
GetQuestions();
}
protected void GetQuestions()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PromptedInspConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("test.GetQuestions", conn);
SqlDataReader dr = null;
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.Add(new SqlParameter("#Block1", cmbBlock1.Text));
dr = cmd.ExecuteReader();
while (dr.Read())
{
DataRow drQuestions = dtQuestionSet.NewRow();
drQuestions["QuestionText"] = dr[1].ToString();
drQuestions["ExpectedResponse"] = dr[2].ToString();
drQuestions["QuestionType"] = dr[3].ToString();
dtQuestionSet.Rows.Add(drQuestions);
}
Session["DataTableW"] = dtQuestionSet;
Session["QuestionCount"] = dtQuestionSet.Rows.Count;
conn.Close();
RunInspection();
}
protected void RunInspection()
{
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.QuestionText = dtQuestionSet.Rows[0][0].ToString();//"I'm asking a question 1";
QT2.Visible = true;
break;
case "2":
QT3.QuestionText = dtQuestionSet.Rows[0][0].ToString();//"I'm asking a question 2";
QT3.Visible = true;
break;
}
}
private void MakeDataTabledtQuestionSet()
{
dtQuestionSet.Columns.Add("QuestionText");
dtQuestionSet.Columns.Add("ExpectedResponse");
dtQuestionSet.Columns.Add("QuestionType");
}
}
}
When I click on the button on a usercontrol with the code: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Testing.Event_Delegate
{
public partial class WebUserControl2 : System.Web.UI.UserControl
{
string questionAsked;
public string QuestionText
{
set { questionAsked = value; }
get { return questionAsked; }
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = QuestionText;
TextBox1.Focus();
}
protected void Button1_Click(object sender, EventArgs e)
{
UC2BtnClickEvent bEvent = new UC2BtnClickEvent();
bEvent.onRefresh2Event3(sender, e, TextBox1.Text, TextBox1.Text );
TextBox1.Text = "";
}
}
}
It runs the procedure CheckResults 3 times on the aspx page when I only need it to run once.
UC2BtnClickEvent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Testing.Event_Delegate
{
public class UC2BtnClickEvent
{
public delegate void OnMyEvent2(object sender, EventArgs e, string strTextBox, string strMyDescription);
public static event OnMyEvent2 MyEvent2;
public virtual void onRefresh2Event2(object sender, EventArgs e, string strTextBox, string strMyDescription)
{
if (MyEvent2 != null)
{
MyEvent2(sender, e, strTextBox, strMyDescription);
}
}
public delegate void OnMyEvent3(object sender, EventArgs e, string strTextBox, string strMyDescription);
public static event OnMyEvent3 MyEvent3;
public virtual void onRefresh2Event3(object sender, EventArgs e, string strTextBox, string strMyDescription)
{
if (MyEvent3 != null)
{
MyEvent3(sender, e, strTextBox, strMyDescription);
}
}
}
}
What have I done wrong to make this happen please as it should only run once.

TAPI3LIB C#.NET - BasicCallControll.Connect crash

I have a sample code from the MS site, about a TAPI application which creates a call.
The code works. I can actually make a call as well.
Then when I hang up and try again, it crashed on the "connect statement" though I create the object the line before (as per sample code from MS)
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 {
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) {
this.Invoke(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:
TAPI3Lib.ITCallNotificationEvent cn = pEvent as TAPI3Lib.ITCallNotificationEvent;
if (cn.Call.CallState == TAPI3Lib.CALL_STATE.CS_OFFERING) {
string c = cn.Call.get_CallInfoString(TAPI3Lib.CALLINFO_STRING.CIS_CALLERIDNUMBER);
AddLog("Call Offering: " + c + " -> " + cn.Call.Address.DialableAddress);
}
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); // <!------ CRASH HERE ON 2ND TRY
}
}
}

Categories