What is the best option to send text to the default printer?
The printer is a Zebra, and the text is a string of ZPL.
Many examples out there are with font size, graphics, points (x,y). Very confusing.
But I need to send the string and the printer does its work.
You can open the port directly using a p/invoke to OpenFile if you are connected using LPT or COM ports, but otherwise you will need to use the print ticket APIs to create a RAW formatted job. See http://support.microsoft.com/?kbid=322091 for a helper class which calls the appropriate platform functions to allows RAW print jobs from C#.
Is your Zebra printer on a network?
If so, this will work-
// Printer IP Address and communication port
string ipAddress = "10.3.14.42";
int port = 9100;
// ZPL Command(s)
string ZPLString =
"^XA" +
"^FO50,50" +
"^A0N50,50" +
"^FDHello, World!^FS" +
"^XZ";
try
{
// Open connection
using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
{
client.Connect(ipAddress, port);
// Write ZPL String to connection
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()))
{
writer.Write(ZPLString);
writer.Flush();
}
}
}
catch (Exception ex)
{
// Catch Exception
}
I've used this library successfully as well for USB.
Related
I have to check remote IP and Port is available or not.If its is available it will move to next form.If not available it should come to the initial state.I tried using this
while (true)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
-------
-------
-------
}
I am showing the example coding.it was checking local IP and port and moving to next form.it will check local port and IP is available.if port and IP not available it will come to the initial stage and it was working fine.same thing i have to check in remote Port and IP.
Use the Ping class of .NET to find out if the system is up and connected, the use the PortScanner to check if the port is open. check these links for further reading and exploring.
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping%28v=vs.110%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/8e4410bd-307f-4264-9575-cd9882653945/help-with-portscanner-in-c?forum=csharpgeneral
OR
public static bool PingHost(string hostUri, int portNumber)
{
try
{
using (var client = new TcpClient(hostUri, portNumber))
return true;
}
catch (SocketException ex)
{
MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'");
return false;
}
}
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.
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.
I have a small program (C# Windows Form) that will access the printer services and print a barcode label. This program only works when I install it and run it on the clients server. When I try running it from my PC I get an error.
Here is what I have:
public static bool PrintBin(string trans, string qty)
{
string m1 = string.Format("{0}|{1}|{2}|{3}", trans, qty, PrinterName, ConnString);
string m2 = string.Empty;
bool status = true;
try
{
TcpClient tcpSocket = new TcpClient(PrinterServer, 65000);
NetworkStream streamToServer = tcpSocket.GetStream();
// create a streamWriter and use it to write a string to the server
System.IO.StreamWriter writer =
new System.IO.StreamWriter(streamToServer);
writer.WriteLine(m1);
writer.Flush();
// Read response
System.IO.StreamReader reader =
new System.IO.StreamReader(streamToServer);
m2 = reader.ReadLine();
streamToServer.Close();
}
catch
{
m2 = "Can not find scanner printing service.";
status = false;
}
It gets stuck and errors out on the TcpClient line.
Thank you
* UPDATE *
Here is the error message i get:
"A connection attemp failed because the connected party did not properly respond after a period of time, or established connection failed because a connected host has failed to respond 172.18.10.22:65000 at System.Net.Sockets.TcpClient (String hostname, Int32 port)"
Thanks
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Listening to Port 5060
I am developing a SIP client.And I have a question.
I want listen 5060 port for catch the SIP Server Message.For this,I coding something.(Also I take admin rights in program)
But I get SocketException: "An attempt was made to access a socket in a way forbidden by its access permissions" (Native error code: 10013)...
My Code:
private void ListenPort() {
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
TcpListener server = null;
Int32 port = 5060;
IPAddress localAddr = IPAddress.Parse("192.168.1.33");
server = new TcpListener(localAddr, port);
Byte[] bytes = new Byte[1000];
String data = null;
while (hasAdministrativeRight == true)
{
server.Start();
int i = 0;
while (1==1)
{
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
data = null;
i = stream.Read(bytes, 0, bytes.Length);
data += System.Text.Encoding.ASCII.GetString(bytes, 0, i);
label3.Text += data;
this.Refresh();
Thread.Sleep(500);
}
}
}
Where do you think the problem?
Have you checked that no other program is already using port 5060? That's what this error can mean.
See this discussion on the matter: http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/d23d471c-002a-4958-829e-eb221c8a4b76/
You need to call server.Start() outside the while loop and before the first AcceptTcpClient call.
Also try using IPAddress.Any instead of IPAddress.Parse("192.168.1.33") for your listener ip
Make sure any other SIP Server program not installed as a Windows service which has using according port.
Type in netstat -an and it will show you the “listening” ports or try to googling port check softwares.
And check your SIP Server configuration for is it running over TCP or UDP.