read sms message from modem using AT command in c# - c#

I'm trying to show sms messages in modem (I use my phone as modem),
Port connect successfully by using AT commands
and I can Import the number and date but the body of message show as number.
this is my code :
port.Write("AT" + System.Environment.NewLine);
Thread.Sleep(1000);
port.WriteLine("AT+CMGF=1" + System.Environment.NewLine);
Thread.Sleep(1000);
port.WriteLine("AT+CMGL=\"ALL\"\r" + System.Environment.NewLine); //("AT+CMGL=\"REC UNREAD\"\r");
Thread.Sleep(3000);
MessageBox.Show(port.ReadExisting());

Related

C# Client can't parse an ip addres

so I am writing a C# client, where the user needs to type which IPv4 address to listen to an incoming connection from. However, though the program compliles, when typing any ip address, it comes back saying the IP was invalid. This is for any IP typed. I am wondering how to correctly parse the IP address typed in to RecieveIP.Text so it will read correctly? Thanks.
try
{
InitializeComponent();
string listenporttext = listenPort.ToString();
IPAddress RIP = IPAddress.Parse(RecieveIP.Text);
client = new Client(RIP, listenporttext);
Console.WriteLine("Recieving information from lead computer " + RIP + " on port: " + listenPort);
recv = client.Receive(data);
string recc1 = recv.ToString();
string data_recieved = recc1;
Console.WriteLine("Recieved Command " + data_recieved);
if (data_recieved == "g")

Receiving carriage return through Serial Port

So I am developing a console application which is able to read and write to/from Arduino through Serial Port. At the moment I got a switch statement to read incoming data from Arduino and depending on the incoming data I will write to the Arduino a couple of messages.
string incoming = port.ReadExisting();
string questionMark = "?";
string carriageReturn = "\r";
string text = string.Empty;
switch (incoming)
{
case "#r\r":
port.Write(questionMark+ "*" + carriageReturn);
break;
case "#{":
port.Write("#" + text);
break;
default:
Console.WriteLine("Unknown command sent by the Arduino\n Command: " + incoming);
break;
}
Now, I am testing out the application with another application to read and write it and when I send to the console application the "#r\r" it will give
Unknown command sent by the Arduino\n Command: "#r\r".
I've found the problem and it comes from the carriage return or \r.
Do you have any idea how could I solve this problem? I want to receive the carriage return because it is the end of it.

Send/receive file over LAN with C# to/from Python

I'm pretty new to Python development and need some help.
I have a Raspberry Pi B+, and I'm planning on using it as a controller for household things (such as turning on a pool pump at a set time). I am pretty familiar with C# and was wondering if there was a way I could write a C# user interface to run on a laptop and send data in the form of a XML file to the Raspberry Pi over a LAN to tell the Pi what to do. I have written some code in C# and some code in Python to try to send and receive a file, but so far my tests have been unsuccessful.
I have some rudimentary code written in Python on the Raspberry Pi for controlling some GPIO pins and was wondering if a connection like this is even feasible of if I should rewrite my Python code into C# also.
Here is my C# send file function
public void SendFile(string fileName)
{
try
{
string IpAddressString = piIP;
IPEndPoint ipEnd_client = new IPEndPoint(IPAddress.Parse(IpAddressString), portnumber);
Socket clientSock_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string filePath = "";
fileName = fileName.Replace("\\", "/");
Console.WriteLine(fileName);
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName);
if (fileNameByte.Length > 5000 * 1024)
{
Console.WriteLine("File size is more than 5Mb, please try with small file.");
return;
}
Console.WriteLine("Buffering ...");
string fullPath = filePath + fileName;
byte[] fileData = File.ReadAllBytes(fullPath);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
Console.WriteLine("Connection to server...");
clientSock_client.Connect(ipEnd_client);
Console.WriteLine("File sending...");
clientSock_client.Send(clientData, 0, clientData.Length, 0);
Console.WriteLine("Disconnecting...");
clientSock_client.Close();
Console.WriteLine("File [" + fullPath + "] transferred.");
}
catch (Exception ex)
{
if (ex.Message == "No connection could be made because the target machine actively refused it")
Console.WriteLine("File Sending fail. Because server not running.");
else
Console.WriteLine("File Sending fail. " + ex.Message);
return;
}
connected = true;
return;
}
Here is my Python receive file function
import socket
import sys
s = socket.socket()
s.bind((socket.gethostname(), 8080))
s.listen(3)
while True:
#Accept connections from the outside
(clientsocket, address) = s.accept()
print(address)
i = 1
f = open('file_' + str(i) + ".xml", 'wb')
i = i + 1
while True:
l = clientsocket.recv(1024)
while l:
f.write(1)
l.clientsocket.recv(1024)
f.close()
sc.close()
s.close()
Again, so far, I am unable to even set up a connection between the two devices. Should I start over on the Pi and try C# instead of Python? Or am I missing something? I've given both devices a static IP address and hardcoded the IP addresses on both machine for now.
EDIT:
Here is the Console and stacktrace I get from C#:
Buffering ...
Connection to server...
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
File Sending fail. No connection could be made because the target machine actively refused it 10.51.21.199:8080
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at App1.Stuffs.SendFile(String fileName) in
...Projects\App1\App1\Stuffs.cs:line 308
The thread '<No Name>' (0x1684) has exited with code 0 (0x0).
Try to use
s.bind(('', 8080))
to force the Raspberry Pi to listen on all available interfaces, as the socket.gethostname() might not be the interface you are actually expecting.
UPDATE:
Try this on the Raspberry Pi side:
import socket
import sys
s = socket.socket()
s.bind(('', 8080))
s.listen(3)
i = 0
while True:
#Accept connections from the outside
(clientsocket, address) = s.accept()
print(address)
i = i + 1
with open('file_' + str(i) + ".xml", 'wb') as f:
while True:
l = clientsocket.recv(1024)
if not l:
break
f.write(l)
clientsocket.close()
s.close()
I have two ways of accessing my Raspberry Pi from a Windows PC. The first is after installing Putty connection manager on the PC, where entering the RPi IP address produces a Terminal window on the PC, from where I can execute RPi programs.
The RPi is connected to a Windows Workgroup, mapped as drive T:, in my case. My C programs can use this to create files on the RPi for writing or reading.

Multiple color fonts in one html email

mailItem.HTMLBody = "Dear IT Dept. You have received a new "+ comboBox3.Text + " priority task to complete from " + textBox1.Text + ". Please save the attached file and fit the task in to your schedule. Once completed please contact the " + textBox2.Text + " for comfirmation the task is completed to thier expectations. The Task is as follows: " + richTextBox1.Text + " Kind Regards, " + textBox1.Text + "";
I basically want to highlight the text/combo boxes or at least change their font color. Annoyingly you can't see the html code I used but it should be pretty obvious but I tried using the font color...with no luck. can't see where I'm going wrong
I can see that you try to put value of textBox2.txt. Your mistake is that wrote textBox2.txt as a string content. So you can achive this with using string.Format method.
You should to change it with this:
mailItem.HTMLBody = string.Format("<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from ({0}) Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>", textBox2.Text);
Notice that textBox2.Text and {0} element.
Note: You also wrong with syntax of TextBox.Text property.
You need to have:
mailItem.HTMLBody = "<html><body>... from " + textBox2.Text + " Please ...";
instead of
mailItem.HTMLBody = "<html><body>... from (textBox2.txt) Please ...";
There is no HTMLBody property on the MailMessage class (assuming this is what you're using?).
It's just Body.
You would do something like this:
mailItem.Body = string.Format("<html><body><p>Dear {0}.</p>", comboBox3.Text);
Etc...
var mailItem= new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp server addess");
mailItem.From = new MailAddress("your_email_address#xyz.com");
mailItem.To.Add("it-department#???.co.uk");
mailItem.Subject = string.Format("You have a new task from {0}", comboBox3.Text);
mailItem.To = "";
mailItem.Body =string.Format("<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from {0} Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to their expectations.</p>",textBox2.txt);
attachment = new System.Net.Mail.Attachment(#"\\??-filesvr\shares\Shared\+++++Web Projects+++++\????\IssueReport.txt");
mailItem.Attachments.Add(#"\\??-filesvr\shares\Shared\+++++Web Projects+++++\??\IssueReport.txt");
mailItem.IsBodyHtml = true;
// Optional Items based on your smtp server.
/* SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;*/
SmtpServer.Send(mailItem);
MessageBox.Show("mail Send");
Did you mean :
mailItem.HTMLBody = "<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from " + textBox2.Text + " Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>";
?
In your version, "textbox2.txt" will be manipulated as a string, it won't be "parsed".
In mine it's a control on your form and we put its text content in the mail.
Edit : you asked how to emphase the variable, here is a example :
Try something like
mailItem.HTMLBody = "<html><body><p>Dear IT Dept.</p> <p>You have received a new task to complete from <strong>" + textBox2.Text + "</strong> Please check the attached file and fit the task in to your schedule.</p><p> Once completed please contact the provided contactee for comfirmation the task is completed to thier expectations.</p>";
The "strong" tag around your variable will put the name in bold.

Errors scheduling a C# console app that sends faxes via FAXCOMEXLib

I have a console app written in C# that uses MS Fax (FAXCOMEXLib) to send faxes. If I run the application manually or from a command prompt it works as expected. If I schedule the application with Task Scheduler or try to run from a service with a timer, it fails when calling the ConnectedSubmit2 on the FaxDocument object. The application runs as expected, gets the data, creates the pdf, connects to Fax Service, fills the FaxDocument properties, but bombs on ConnectedSubmit2. It feels like a security issue. The windows account the TaskScheduler runs under belongs to the administrator group.
This same application has worked on another Server 2008 (not R2) computer without issue with Task Scheduler.
The server in question is running Microsoft Server 2008 R2.
Recap: The application will work if run manually, fails if run from another process like Task Scheduler.
Any suggestions would be most appreciated. Thank you.
C# Code:
FAXCOMEXLib.FaxServer faxServer = new FAXCOMEXLib.FaxServer();
FAXCOMEXLib.FaxDocument faxDocument = new FAXCOMEXLib.FaxDocument();
ArrayList al = new ArrayList();
al.Add(orderPdfFilePath);
if (facesheetPdfFilePath != "")
al.Add(facesheetPdfFilePath);
if (write) Console.WriteLine("Preparing to Connect to Fax Server...");
sbLog.Append("Preparing to Connect to Fax Server...\r\n");
faxServer.Connect("");
if (write) Console.WriteLine("Connected.");
sbLog.Append("Connected.\r\n");
// Add Sender Information to outgoing fax
faxDocument.Sender.Name = dr2["FacilityName"].ToString();
faxDocument.Sender.Department = dr2["TSID"].ToString();
faxDocument.Sender.TSID = Truncate(dr2["TSID"].ToString(), 20);
faxDocument.Recipients.Add(dr2["FaxNumber"].ToString(), dr2["Pharmacy"].ToString());
faxDocument.Bodies = al.ToArray(typeof(string));
faxDocument.Subject = order;
if (write) Console.WriteLine("Attempting submit to fax server...");
sbLog.Append("Attempting submit to fax server...\r\n");
// attempt send...
try
{
object o;
faxDocument.ConnectedSubmit2(faxServer, out o);
if (write) Console.WriteLine("Fax sent successfully " + DateTime.Now.ToString());
sbLog.Append("Fax sent successfully " + DateTime.Now.ToString() + ".\r\n");
}
catch (Exception ex)
{
if (write) Console.WriteLine("SEND FAILED! " + order + " " + DateTime.Now.ToString() + " " + ex.Message);
sbLog.Append("SEND FAILED! " + order + " " + DateTime.Now.ToString() + ".\r\n" + ex.Message + "\r\n" + ex.InnerException + "\r\n");
error = true;
}
Errors in Event Log:
System.Runtime.InteropServices.COMException (0x80070102): Operation failed.
at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit2(IFaxServer pFaxServer, Object& pvFaxOutgoingJobIDs)
System.UnauthorizedAccessException: Access denied. at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit2(IFaxServer pFaxServer, Object& pvFaxOutgoingJobIDs) at ElementsTransmission.Program.Main(String[] args)
See
http://blogs.msdn.com/b/dougste/archive/2011/08/30/system-runtime-interopservices-comexception-0x80070102-operation-failed-trying-to-send-a-fax-from-and-asp-net-application.aspx
Bill

Categories

Resources