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
Related
I have found some code HERE and modified the same to call a phone number using skype, play an audio file and then disconnect. However, there are two issues in this code.
Audio file which is being played can be heard on the local system
but NOT in the phone call (the person receiving the call is not able to hear the audio played).
The call is not getting disconnected after audio file finishes
playing.
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Device;
using Microsoft.Lync.Model.Extensibility;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
namespace LyncTest
{
public partial class frmCaller : Form
{
public frmCaller()
{
InitializeComponent();
}
private void btnCall_Click(object sender, EventArgs e)
{
//if this client is in UISuppressionMode...
if (client.InSuppressedMode && client.State == ClientState.Uninitialized)
{
//...need to initialize it
try
{
client.BeginInitialize(this.ClientInitialized, null);
}
catch (LyncClientException lyncClientException)
{
Console.WriteLine(lyncClientException);
}
catch (SystemException systemException)
{
if (LyncModelExceptionHelper.IsLyncException(systemException))
{
// Log the exception thrown by the Lync Model API.
Console.WriteLine("Error: " + systemException);
}
else
{
// Rethrow the SystemException which did not come from the Lync Model API.
throw;
}
}
}
else //not in UI Suppression, so the client was already initialized
{
//sign-in or contact selection
SignInToLync();
}
SendLyncCall("+6512345678", "Hello, I am calling regarding a pending change request");
}
LyncClient client = LyncClient.GetClient();
private void SignInToLync()
{
try
{
client.BeginSignIn("abc#contoso.com", "abc#contoso.com", "Pass#word99", HandleEndSignIn, null);
}
catch (LyncClientException lyncClientException)
{
Console.WriteLine(lyncClientException);
}
catch (SystemException systemException)
{
if (LyncModelExceptionHelper.IsLyncException(systemException))
{
// Log the exception thrown by the Lync Model API.
Console.WriteLine("Error: " + systemException);
}
else
{
// Rethrow the SystemException which did not come from the Lync Model API.
throw;
}
}
}
Automation _automation = LyncClient.GetAutomation();
ConversationWindow globalConv = null;
public void SendLyncCall(string numberToCall, string textToSpeech)
{
var targetContactUris = new List<string> { numberToCall }; //"tel:+4900000000"
_automation.BeginStartConversation(AutomationModalities.Audio, targetContactUris, null, StartConversationCallback, null);
while (this.globalConv == null)
{
Thread.Sleep(1);
}
if (globalConv != null)
{
//client.DeviceManager.EndPlayAudioFile(
// client.DeviceManager.BeginPlayAudioFile(#"C:\Temp\voice.wav", AudioPlayBackModes.AlertAndCommunication, false, AudioPlayed, null)
// );
}
}
private void StartConversationCallback(IAsyncResult asyncop)
{
// this is called once the dialing completes..
if (asyncop.IsCompleted == true)
{
ConversationWindow newConversationWindow = _automation.EndStartConversation(asyncop);
globalConv = newConversationWindow;
AVModality avModality = newConversationWindow.Conversation.Modalities[ModalityTypes.AudioVideo] as AVModality;
avModality.ModalityStateChanged += ConversationModalityStateChangedCallback;
}
}
/// <summary>
/// Called when the client in done initializing.
/// </summary>
/// <param name="result"></param>
private void ClientInitialized(IAsyncResult result)
{
//registers for conversation related events
//these events will occur when new conversations are created (incoming/outgoing) and removed
//client.ConversationManager.ConversationAdded += ConversationManager_ConversationAdded;
//client.ConversationManager.ConversationRemoved += ConversationManager_ConversationRemoved;
}
private void ConversationModalityStateChangedCallback(object sender, ModalityStateChangedEventArgs e)
{
AVModality avModality = sender as AVModality;
if (avModality != null)
{
switch (e.NewState)
{
case ModalityState.Disconnected:
avModality.ModalityStateChanged -= ConversationModalityStateChangedCallback;
break;
case ModalityState.Connected:
avModality.ModalityStateChanged -= ConversationModalityStateChangedCallback;
//foreach (char c in "SOS")
//{
// avModality.AudioChannel.BeginSendDtmf(c.ToString(), null, null);
// System.Threading.Thread.Sleep(500);
//}
client.DeviceManager.EndPlayAudioFile(client.DeviceManager.BeginPlayAudioFile(#"C:\Temp\voice.wav",
AudioPlayBackModes.Communication, false, AudioPlayed, null));
break;
case ModalityState.Invalid:
break;
case ModalityState.Notified:
break;
}
}
}
private void AudioPlayed(IAsyncResult audioPlayed)
{
if(audioPlayed.IsCompleted == true)
{
client.ConversationManager.Conversations[0].End();
}
}
private void HandleEndSignIn(IAsyncResult ar)
{
try
{
client.EndSignIn(ar);
}
catch (Exception e)
{
Console.Out.WriteLine(e);
}
}
private void frmCaller_FormClosing(object sender, FormClosingEventArgs e)
{
GC.Collect();
}
}
}
Any help would be appreciated. Thank you.
It was confirmed by Microsoft that this is not possible using client side code. I need to use UCMA and develop a server side solution for the same.
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 try to shutdown vbox before local shutdown/restart/logoff etc.
i try something but dont work.
My code is:
private void VMStarter_Load(object sender, EventArgs e)
{
...
...
ShutDownHandle.StopShutdown(this.Handle, "Virtual Box is shutting down...");
}
private void tmr_doWork_tick(object sender, EventArgs e)
{
tmr_doWork.Enabled = false;
Controller.closeVM(); //for
while (!ShutDownHandle.ResetShutdown(this.Handle))
{
Thread.Sleep(10);
}
ShutDownHandle.Shutdown();
this.Close();
}
//[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref Message m)
{
if (!systemShutdown)
if (m.Msg == (int)EnumClass.WindowsMessageCodes.SM_SHUTTINGDOWN ||
m.Msg == (int)EnumClass.WindowsMessageCodes.WM_ENDSESSION ||
m.Msg == (int)EnumClass.WindowsMessageCodes.WM_QUERYENDSESSION)
{
tmr_Check.Enabled = false;
//Message MyMsg = new Message();
//MyMsg.Msg = (int)EnumClass.WindowsMessageCodes.WM_CANCELMODE;
//base.WndProc(ref MyMsg);
systemShutdown = true;
tmr_doWork.Enabled = true;
return;
}
base.WndProc(ref m);
}
ShutDownHandle class: include StopShutdown and ResetShutdown methode. I use ShutdownBlockReasonCreate and ShutdownBlockReasonDestroy to stop closing window.
public static bool StopShutdown(IntPtr hWdn, string strMessage)
{
try
{
if (ShutdownBlockReasonCreate(hWdn, strMessage))
{
return true;
}
}
catch (Exception ex)
{
Writer.errorWrite(ex);
}
return false;
}
public static bool ResetShutdown(IntPtr hWdn)
{
try
{
return ShutdownBlockReasonDestroy(hWdn);
}
catch (Exception ex)
{
return false;
Writer.errorWrite(ex);
}
return false;
}
I click shutdown while app is running and get this
How can i do? what's wrong?
try this
in your method tmr_doWork_tick
put async like this
async void tmr_doWork_Tick(object sender, etc..)
{
// here is your thread.sleep();
// reemplace for await Task.delay(10);
}
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()
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);
}
}