I want to send SMS from my Application that is under developing on Windows Forms Application, The trouble to achieving this task is getting Port Number, I'm suffering by this issue over a week, kindly guide me, I'm sending uploading my code, one thing more is that I'm using Android OS on my cell phone where I have installed SIM card, and device vendor is HUAWEI. thanks a lot in advance......
private void button1_Click(object sender, EventArgs e)
{
GsmCommMain comm;
int portn = 0;
System.IO.Ports.SerialPort _srp = new System.IO.Ports.SerialPort();
try
{
Cursor.Current = Cursors.Cross;
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort");
Cursor = Cursors.WaitCursor;
foreach (System.Management.ManagementObject queryObj in searcher.Get())
{
Cursor = Cursors.Hand;
StatusLabel.Text = "Just Enterd in foreach Block...";
if (queryObj != null)
{
Cursor = Cursors.UpArrow;
object captionObj = queryObj["DESCRIPTION"];//Model Name
object capdeviceid = queryObj["DEVICEID"];//Comm port
object MaxBaudRate = queryObj["MAXBAUDRATE"];
object connstatus = queryObj["STATUS"];
object ct = queryObj.ToString();
int timeoutsec = 300;
StatusLabel.Text = "USB Modem Condition Main Enter Na Ho Saki...";
if (captionObj.ToString().Contains("USB Modem"))
{
_srp.PortName = capdeviceid.ToString();
portn = Convert.ToInt32(capdeviceid.ToString().Substring(3));
label1.Text = _srp.PortName + " ,,, " + portn;
comm = new GsmComm.GsmCommunication.GsmCommMain(portn, Convert.ToInt32(MaxBaudRate), timeoutsec);
StatusLabel.Text = "USB Modem Condition Main Entry...";
comm.Open();
if (comm.IsOpen())
btnSMSConnect.BackColor = Color.Green;
MessageBox.Show("Not Opening..." );
StatusLabel.Text = "Not Opening...";
}
}
}
}
catch (Exception e15)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e15.Message);
btnSMSConnect.BackColor = Color.Transparent;
//comm.Close();
_srp.Close();
}
}
}
}
Related
In my winforms C# project I have a NFC device which is connected to pc and works properly.I have this part of code in Timer_Tick
private void timer1_Tick(object sender, EventArgs e)
{
try
{
if (NFC.Connect())
//label6.Text = "دستگاه متصل میباشد";
label6.Text = "device is connected";
label6.Invalidate();
label6.Update();
Application.DoEvents();
}
catch (Exception exception)
{
label6.Text = "device is not connected";
//label6.Text = "دستگاه متصل نمی باشد";
label6.Invalidate();
label6.ForeColor = Color.Red;
label6.Update();
Application.DoEvents();
}
}
I want to show the device is connected or not but the problem is that label6.text does not update.
Can anyone help please?
If you're using this library; https://github.com/h4kbas/nfc-reader/blob/master/NFCReader.cs
Then perhaps you should have a code like:
try
{
if (NFC.Connect())
label6.Text = "device is connected " + DateTime.Now;
else
label6.Text = "device didn't connect " + DateTime.Now;
label6.ForeColor = Color.Black;
}
catch (Exception e)
{
label6.Text = "device error " + e.Message;
label6.ForeColor = Color.Red;
}
I'd suggest also renaming label6 to something more apt, like statusLabel. Always rename your controls
Re your comment, here is the code of Connect()
ublic bool Connect()
{
string readerName = GetReadersList()[0];
connActive = true;
retCode = Card.SCardConnect(hContext, readerName, Card.SCARD_SHARE_SHARED,
Card.SCARD_PROTOCOL_T0 | Card.SCARD_PROTOCOL_T1, ref hCard, ref Protocol);
if (retCode != Card.SCARD_S_SUCCESS)
{
connActive = false;
return false;
}
else
return true;
}
You claim "it's connected but Caius code says it's not" -> Caius' code only goes off whether the library says it is connected or not. If Caius' code says it is not connected when it is, it's not Caius' code fault.. Library is open source; go fix the code of it for others to benefit
I am developing a program that uses a hardware (I am using Arduino) to collect data and then store the data in the database. As there is no way to get assured that the serialport is receiving the data, I am trying to implement some code snippet to declare hardware removal and then check if there is my desired device still connected or otherwise inform the user.
What I have come to up to now is:
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case WM_DEVICECHANGE:
switch ((int)m.WParam)
{
case DBT_DEVICEARRIVAL:
listBox1.Items.Add("New Device Arrived");
int devType = Marshal.ReadInt32(m.LParam, 4);
if (devType == DBT_DEVTYP_PORT)
{
string portName = Marshal.PtrToStringAuto((IntPtr)((long)m.LParam + 12));
listBox1.Items.Add("the name of the port is " + portName);
}
break;
case DBT_DEVICEREMOVECOMPLETE:
{
listBox1.Items.Add("Device Removed");
}
break;
}
break;
}
}
which informs me if any changes in device connection to the PC has happened. Also the following code tells me about existence of the arduino in the list of connected devices:
ManagementScope connectionScope = new ManagementScope();
SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);
try
{
foreach (ManagementObject item in searcher.Get())
{
string desc = item["Description"].ToString();
string deviceId = item["DeviceID"].ToString();
if (!desc.Contains("Arduino"))
{
// Inform the user about the disconnection of the arduino
}
}
}
catch //(ManagementException e)
{
/* Do Nothing */
}
How ever, when I mix the codes to inform me when arduino is unplugged, they do not comply with each other and throw the error of:
Transition into COM context 0x8ff990 for this RuntimeCallableWrapper failed with the following error: An outgoing call cannot be made since the application is dispatching an input-synchronous call. (Exception from HRESULT: 0x8001010D (RPC_E_CANTCALLOUT_ININPUTSYNCCALL)). This is typically because the COM context 0x8ff990 where this RuntimeCallableWrapper was created has been disconnected or it is busy doing something else and cannot process the context transition. No proxy will be used to service the request on the COM component and calls will be made to the COM component directly. This may cause corruption or data loss. To avoid this problem, please ensure that all COM contexts/apartments/threads stay alive and are available for context transition, until the application is completely done with the RuntimeCallableWrappers that represents COM components that live inside them.
Any Help is appreciated, Thanks in advance.
PS: For your further information, the whole coded is:
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case WM_DEVICECHANGE:
switch ((int)m.WParam)
{
case DBT_DEVICEARRIVAL:
listBox1.Items.Add("New Device Arrived");
int devType = Marshal.ReadInt32(m.LParam, 4);
if (devType == DBT_DEVTYP_PORT)
{
string portName = Marshal.PtrToStringAuto((IntPtr)((long)m.LParam + 12));
listBox1.Items.Add("the name of the port is " + portName);
}
break;
case DBT_DEVICEREMOVECOMPLETE:
{
listBox1.Items.Add("Device Removed");
ManagementScope connectionScope = new ManagementScope();
SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);
try
{
foreach (ManagementObject item in searcher.Get())
{
string desc = item["Description"].ToString();
string deviceId = item["DeviceID"].ToString();
if (desc.Contains("Arduino"))
{
MessageBox.Show(deviceId);
}
}
}
catch //(ManagementException e)
{
/* Do Nothing */
}
}
break;
}
break;
}
}
public partial class Form1 : Form
{
ManagementEventWatcher watcher;
// Not all arduinos have 'Arduino' in their serialport driver 'Description', So check for a Com port Number.
private static string MustHavePort = "COM3"; //Port to check for.
public Form1()
{
InitializeComponent();
watcher = new ManagementEventWatcher("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3");
watcher.EventArrived += new EventArrivedEventHandler(USBChangedEvent);
watcher.Start();
}
public void USBChangedEvent(object sender, EventArrivedEventArgs e)
{
(sender as ManagementEventWatcher).Stop();
this.Invoke((MethodInvoker)delegate
{
ManagementObjectSearcher deviceList = new ManagementObjectSearcher("Select Name, Description, DeviceID from Win32_SerialPort");
// List to store available USB serial devices plugged in. (Arduino(s)/Cell phone(s)).
List<String> ComPortList = new List <String>();
listBox1.Items.Clear();
textBox1.Text = "";
// Any results? There should be!
if (deviceList != null)
{
// Enumerate the devices
foreach (ManagementObject device in deviceList.Get())
{
string SerialPortNumber = device["DeviceID"].ToString();
string serialName = device["Name"].ToString();
string SerialDescription = device["Description"].ToString();
ComPortList.Add(SerialPortNumber);
listBox1.Items.Add(SerialPortNumber);
listBox1.Items.Add(serialName);
listBox1.Items.Add(SerialDescription);
}
}
else
{
listBox1.Items.Add("NO SerialPorts AVAILABLE!");
// Inform the user about the disconnection of the arduino ON PORT 3 etc...
SendAlarm();
}
if (!ComPortList.Contains(MustHavePort))
{
// Inform the user about the disconnection of the arduino ON PORT 3 etc...
SendAlarm();
}
});
(sender as ManagementEventWatcher).Start();
}
private void SendAlarm()
{
textBox1.Text = "Alarm..." + MustHavePort + "Port Missing...";
MessageBox.Show("Error " + MustHavePort + " Port Missing!!!", "Serial Port Error.");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
watcher.Stop();
}
}
I am trying to make an agsXMPP jabber chat client in window app. but the OnLogin event is not firing at all. In console app its working fine. but windows or web its not working.
Here is the code:
JID_Sender = jid.Text;
password = pword.Text;
MessageBox.Show("The jid is:" + JID_Sender);
MessageBox.Show("The password is:" + password);
Jid jidSender = new Jid(JID_Sender);
XmppClientConnection xmpp = new XmppClientConnection(jidSender.Server);
try
{
xmpp.Open(jidSender.User, password);
xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);
}
catch (Exception k)
{
MessageBox.Show(k.Message);
}
MessageBox.Show("waiting for login...1");
info.Text = "Wait for Login ";
MessageBox.Show("waiting for login...2");
int i = 0;
_wait = true;
do
{
info.Text += ".";
i++;
if (i == 10)
_wait = false;
Thread.Sleep(500);
} while (_wait);
info.Clear();
Please help me.
I use BackgroundTransferRequest class to download mp3 files in my wp8 app. Some of my files are over 100mb, so because of that I set transferRequest.TransferPreferences = TransferPreferences.None;. However, transferstatus method still returns me external power message.
If you look at line 12 in code you can see that i set TransferPreferences as None
Here is my code to download mp3 file:
private void download_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (transferFileName != null)
{
Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
transferRequest.TransferPreferences = TransferPreferences.None;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch (InvalidOperationException ex)
{
// TBD - update when exceptions are finalized
MessageBox.Show("Unable to add background transfer request. " + ex.Message);
}
catch (Exception e2)
{
MessageBox.Show("Unable to add background transfer request."+e2.ToString());
}
transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
transferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
}
else
MessageBox.Show("select an mp3 file to download");
}
private void ProcessTransfer(BackgroundTransferRequest transfer)
{
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
RemoveTransferRequest(transfer.RequestId);
processresult.Text = "";
download.Visibility = Visibility.Visible;
lnk = new linkname();
URLListBox.ItemsSource = lnk.obj();
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
string filename = transfer.Tag;
if (isoStore.FileExists(filename))
{
isoStore.DeleteFile(filename);
}
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename);
}
}
else
{
RemoveTransferRequest(transfer.RequestId);
if (transfer.TransferError != null)
{
MessageBox.Show(transfer.TransferError.ToString());
}
}
break;
case TransferStatus.WaitingForExternalPower:
WaitingForExternalPower = true;
processresult.Text = "Waiting For External Power";
break;
case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
WaitingForExternalPowerDueToBatterySaverMode = true;
processresult.Text = "Waiting For External Power Due To Battery Saver Mode";
break;
case TransferStatus.WaitingForNonVoiceBlockingNetwork:
WaitingForNonVoiceBlockingNetwork = true;
processresult.Text = "Waiting For Non Voice Blocking Network";
break;
case TransferStatus.WaitingForWiFi:
WaitingForWiFi = true;
processresult.Text = "Waiting For WiFi";
break;
}
}
private void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
ProcessTransfer(e.Request);
}
From the Documentation
If the file to be transferred is larger than 100 MB, set the TransferPreferences property of the transfer to None. If you do not, the system will automatically change the transfer settings to this value, meaning that the transfer will only proceed when the phone is connected to external power and has a Wi-Fi connection.
hope someone can help me with this issue. I have been trying different things for a while and I have tried a few solutions that I found on here and other site to no avail but as I am a novice, I think I have probably missed something. Here goes.
I am writing an application and I want to add in the ability for users to send messages to each other and have them pop on the screen. This is fine, the message is delivered and the form pops but if the user sends another message, it creates a new instance of the class. It doesn't appear to be finding the open form. I have tried a few things to search through open forms:
//Receive message is started by the OpenListeningSocket function
//ProcessingThread = new Thread(() => ReceiveMessage());
private void ReceiveMessage()
{
Socket newSocket = tempServerSocket;
NetworkStream netStream = new NetworkStream(newSocket);
BinaryReader br = new BinaryReader(netStream);
BinaryWriter bw = new BinaryWriter(netStream);
String message;
String sender;
try
{
do
{
message = br.ReadString();
sender = br.ReadString();
} while (br.PeekChar() > 0);
/*
//FormCollection fc = Application.OpenForms;
for(int i = 0; i <= Application.OpenForms.Count; i++)
//foreach (Form frm in Application.OpenForms)
{
if(Application.OpenForms[i].Text == sender)
//if (frm is Message)
{
Message liveMessage = (Message)Application.OpenForms[i];
if (liveMessage.Text == sender)
{
MessageBox.Show("liveMessage Message detected");
liveMessage.lbMain.Items.Add(sender + ": " + message);
liveMessage.cbUsers.Text = sender;
liveMessage.cbUsers.Enabled = false;
liveMessage.TopMost = true;
liveMessage.TopMost = false;
liveMessage.ShowDialog();
//liveMessage.Visible = true;
}
}
else if(Application.OpenForms[i] is Message)
{
newMsg = new Message();
newMsg.Text = sender;
newMsg.userName = userName;
newMsg.cbUsers.Text = sender;
newMsg.cbUsers.Enabled = false;
newMsg.lbMain.Items.Add(sender + ": " + message);
//msgList.Add(newMsg);
newMsg.ShowDialog();
}
}
*/
if (msgList.Count < 1)
{
Message newMsg = new Message();
newMsg.Text = sender;
newMsg.userName = userName;
newMsg.cbUsers.Text = sender;
newMsg.cbUsers.Enabled = false;
newMsg.lbMain.Items.Add(sender + ": " + message);
msgList.Add(newMsg);
newMsg.Visible = true;
}
else
{
foreach (Message msg in msgList)
{
if (msg.Text == sender)
{
//Message msg = (Message)frm;
msg.lbMain.Items.Add(sender + ": " + message);
msg.cbUsers.Text = sender;
msg.cbUsers.Enabled = false;
newMsg.Visible = true;
//msg.Visible = true;
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I have tried looking through all the open forms in the Form Collection and if the form is of the Message class, cast it to Message. I couldn't get this to work. I tried adding all new Message instances to a Generic List of type Message and then iterating through them but this didn't work, maybe being disposed by the ProcessingThread?
I have tried looking at some instant messaging application examples but I haven't come across how they send the new message to the existing form.
If anyone has any helpful hints or could point me in the right direction, it would be greatly appreciated. Thanks, Cameron.