Adding a network printer with C# - c#

I've been building a program to easily configure newly imaged computers (setting DNS servers, IP address, gateway, adding to AD, adding optional printers, etc). I had it working in PowerShell, but I've been trying to port it to C#, mainly to combine lots of small scripts in one, add a nice user interface, and as practice to get better at C#. It's been going well so far, but I've been having some trouble with adding a printer.
Here's the PowerShell script I was using to configure the network printer:
Add-PrinterPort -name ESDPRT500 -PrinterHostAddress $ReceiptPrinterIP
Set-Printer -Name "EPSON TM-T88IV Receipt" -PortName ESDPRT500
I've been looking at the following C# code, but it appears to only set a printer by TCP/IP port, whereas I believe my port is under "EPSON Port Handler"?
ManagementClass portClass = new ManagementClass("Win32_TCPIPPrinterPort");
ManagementObject portObject = portClass.CreateInstance();
portObject["Name"] = portName;
portObject["HostAddress"] = "174.30.164.15";
portObject["PortNumber"] = portNumber;
portObject["Protocol"] = 1;
portObject["SNMPCommunity"] = "public";
portObject["SNMPEnabled"] = true;
portObject["SNMPDevIndex"] = 1;
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOrCreate;
portObject.Put(options);
Could anyone point me in the right direction given how my printer is configured? I've found examples for installing drivers and adding printers via TCP/IP port #s, but haven't had much luck with this. Thanks!

Related

Virtual USB to COM adapter on Windows 10?

I have a C# application/windows service (and the source code) that is trying to an external USB device over serial and I want to replace the physical USB device with a virtual one made by me (another C# service/app). That would normally be straightforward as I have done that multiple times before using com0com to connect the COM port of my program with the COM port of another.
My problem is that the service uses WMI (Windows Management Instrumentation) to check for both the insertion of an USB device with a specific VID and PID (in the "PNPDeviceID"/"DeviceID") ...
this.USBInsertWatcher = new ManagementEventWatcher();
WqlEventQuery wqlEventQuery1 = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
this.USBInsertWatcher.EventArrived += new EventArrivedEventHandler(this.OnUSBDeviceInserted);
this.USBInsertWatcher.Query = (EventQuery) wqlEventQuery1;
this.USBInsertWatcher.Start();
... and for the associated COM port ("DeviceID") to connect to.
private string GetComPort()
{
using (ManagementObjectCollection instances = new ManagementClass("Win32_SerialPort").GetInstances())
{
foreach (ManagementBaseObject managementBaseObject in instances)
{
string str = managementBaseObject["PNPDeviceID"].ToString();
if (str.Contains(this.vendorIdStr) && str.Contains(this.productIdStr))
return managementBaseObject["DeviceID"].ToString();
}
return (string) null;
}
}
This means that I
can't choose the COM port the service connects to and
can't get the service to connect to anything in the first place :/
What I believe I need is some kind of driver that simulates a COM to USB adapter. I already have a virtual com port (opened by my other C# program)
I'm open to any kind of solution, but I should be usable on a non-virtualized Windows machine, also I can't recompile the binary because of (license/building) issues and the solution should be free.
Thank you!

Use a new ssh connection using another established connection with SSH.NET [duplicate]

I am doing SSH to a Linux machine and again from there want to SSH to another Linux machine to carry out few Perforce tasks.
using (SshClient ssh = new SshClient("ip address","username", "pwd"))
{
ssh.Connect();
command = ssh.CreateCommand("ssh hostname");
result = command.Execute();
Console.WriteLine(result);
}
Where the ssh hostname is a password less ssh. How can I control the second SSH session and pass commands to it?
Even explored the CreateShell function, but seems like it is not suggested for automation.
In general, trying to automate ssh command is a bad design.
You better use a port forwarding (aka SSH tunnel) to implement the "hop".
var firstClient =
new SshClient(firstHostName, firstUserName, firstPassword);
firstClient.Connect();
var port = new ForwardedPortLocal("127.0.0.1", secondHostName, 22);
firstClient.AddForwardedPort(port);
port.Start();
var secondClient =
new SshClient(port.BoundHost, (int)port.BoundPort, secondUserName, secondPassword);
secondClient.Connect();
var command = secondClient.CreateCommand("ls");
var result = command.Execute();
Console.WriteLine(result);
There are some cases, when automating the ssh is acceptable (while still not ideal). E.g. because there's an authentication to the second host set up on the first one. I.e. there might be private key in the .ssh folder and you are not allowed to transfer that key to your client machine.
Even then, try talking to the system Administrator to find a better solution. The private key is still accessible using the credentials contained in your application, so it's not protected any better, had the private key itself been contained directly in the application.
Anyway, ssh can accept a command on its command line, like:
command = ssh.CreateCommand("ssh hostname command");
result = command.Execute();
Console.WriteLine(result);

Accessing Honeywell-Box(HICC-P-2100X) IP Camera with c#?

Nowadays I am using Honeywell IP camera for image processing application.But unfortunately I couldn't manage to open it using opencvsharp in c# programming.
So, I would like to share some part of my code and I am using ethernet cable to connect it directly(cable from my notebook to Ip camera).I defined static ip to my laptop and I am able to connect it using default ip configuration via internet explorer.But I am not able to connect and open this camera using c# programming.
I tried all relevant links to make it work as below.Any help would be highly apreciated.
string v2 = #"http://192.168.0.101:5060/h264";
CvCapture camera = new CvCapture(v2)
string v2 = #"http://admin:admin#192.168.0.101:564/h264";
string v2 = #"rtsp://admin:admin#192.168.0.101:564/h264";
string v2 = #"http://192.168.0.101:564/img/video.mjpeg";
string v2 = #"http://admin:admin#192.168.0.101:564/img/video.mjpeg";
string v2 = #"http://192.168.0.101:564/img/video.mjpeg";
string v2 = #"http://192.168.0.101:564/img/video.asf";
string v2 = #"http://192.168.0.101:564/img/video.mjpeg";
All these methods are defined according to related link below(I tried almost all but I couldn be successful
http://www.camera-sdk.com/p_183-how-to-connect-to-your-honeywell-ip-camera-onvif.html``
related image
You can use http://www.aforgenet.com/framework/docs/html/dbf7400d-fbe9-e770-57aa-f63bc507c917.htm JPGStream to capture your video.
_videoSource = new JPEGStream(ConnectionString);
_videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
_videoSource.Start();
And after capture you can process you images with opencv.
you can use ONVIF DEVICE MANAGER
then you can find the url of your ip camera
like:
rtsp://192.168.1.188/media?stream=0

Reset Network Connections

What's the best way to reset network connections using C#/.NET?
My company has several machines out with customers that connect by various means (3G, wifi, ethernet cable) and sometimes (especially with 3G) are reporting to Windows that they're still connected when they're not. I have a way to check if the connection is really live, but I'm struggling to reset them. Here's one problem:
var searcher = new ManagementObjectSearcher("select * from Win32_NetworkAdapter");
var managementObject = searcher.Get();
foreach (ManagementObject obj in managementObject)
{
var name = obj.Properties["Name"].Value.ToString();
Console.WriteLine(name);
obj.InvokeMethod("Disable", null);
obj.InvokeMethod("Enable", null);
}
As you can see, that will go through ALL network adapters and reset them, which I don't want to do. Furthermore, some adapters won't accept the null parameter.
I can get the NetworkInterface objects I want with this:
var interfaces = NetworkInterface.GetAllNetworkInterfaces().Where(ni => ni.IsReceiveOnly == false &&
ni.OperationalStatus == OperationalStatus.Up && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback);
But the NetworkInterface class seems to have no Start(), Stop(), Reset() etc methods. Where do I go from here?
After some searching and experimentation, I found this blog post:
Disable/Enable Network Connections Under Vista
It is a much better approach.
The just of it, is to use a utility called mgmtclassgen.exe to generate a wrapper class around the WMI Win32_NetworkAdapter class. Use the following command in a developer command prompt at the folder of your choosing:
mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
After you've generated NetworkAdapter.cs you can import it into a new project, add System.Management.dll to your project references, and use the following code to disable or enable an adapter of your choosing:
SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "NetConnectionStatus=2");
ManagementObjectSearcher search = new ManagementObjectSearcher(query);
foreach(ManagementObject result in search.Get())
{
NetworkAdapter adapter = new NetworkAdapter(result);
// Identify the adapter you wish to disable here.
// In particular, check the AdapterType and
// Description properties.
// Here, we're selecting the LAN adapters.
if (adapter.AdapterType.Equals("Ethernet 802.3"))
{
adapter.Disable();
}
}
Also keep in mind, your program will have to be run as an administrator on any systems where UAC is enabled - to do this it is recommended to create an application manifest. You can do that by changing the requestedExecutionLevel entry in your manifest file to this:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Might be a bit simplistic, but could you call ipconfig /renew from a new process?
Process.Start("ipconfig", "/renew");
Alternatively, this similar question talks about using netsh, which I guess you could call from a process too How to disable (or reset) a network adapter programmatically in C#
You need Win32 API :
GetExtendedTcpTable : Get all exists tcp connection.
SetTcpEntry : Change tcp connection state.
Example code:
MIB_TCPROW row = new MIB_TCPROW();
row.dwState = TcpState.DeleteTcb;
row.dwLocalAddr = ...;
row.dwLocalPort = ...;
row.dwRemoteAddr = ...;
row.dwRemotePort = ...;
SetTcpEntry(ref row);

C# - Windows Mobile - Pairing with Zebra RW 420

Update: This may not be "Pairing". This may just need to have a service started and bound to a port. However, this code is not storing it either. I need the device to be stored even after the application is closed.
I am building a program specifically suited for Zebra RW 420's on a Windows Mobile 6 Handheld device. The application needs to allow a mobile device to pair with the printer on COM1. I believe I am very close to getting it, but I can't get the pair request to work.
I am able to communicate with the printer and even print by directly connecting and printing, but I can't get the mobile device to actually pair with it. I've tried a variation of pins to include null, "1", "0000", and "1234". No matter what, the method always returns false. Any suggestions or ideas why this might be failing? I can pair the device just find in the WM6 Bluetooth menu, but not in my application.
It might be important to note that the little light bulb icon on the printer comes on when the program says it is attempting to pair, but after about 5 to 10 seconds, it fails.
BluetoothSecurity.PairRequest(device, "1"))
Additional Information:
I've successfully paired with my Android phone using this code.
I then logged in and set a PIN on the Zebra printer. However, this code still fails to pair with the printer even when I know the pin is correct / set in the printer.
From https://km.zebra.com/kb/index?page=answeropen&type=open&searchid=1336682809706&answerid=16777216&iqaction=5&url=https%3A%2F%2Fkm.zebra.com%2Fkb%2Findex%3Fpage%3Dcontent%26id%3DSO8031%26actp%3Dsearch%26viewlocale%3Den_US&highlightinfo=6292341,26,43#
Zebra Bluetooth enabled mobile printers are 'slave' devices only. The printers will pair with any 'master' device that tries to make a valid connection. Since only a master device can initiate a connection, the printer does not store pairing data, that function is always done on the master device. The printer can only be connected to one master device at a time, but any number of master devices that have stored pairing information for the printer would be able to initiate a connection to the printer without having to rediscover it.
I'm guessing that this means the InTheHand.Net BluetoothSecurity.PairRequest might not work for this type of pairing?
In the Bluetooth section of the WM handheld, under the "Devices" tab, I can add the device. I need to essentially do that. I need to register the device in that list and then set it to use COM 1 in the "COM Ports" section. The application I am using doesn't actually print. It's sole purpose is to prepare the printer for other applications.
The quote from Zebra make it sounds as pairing is actually not required at all. Are you printing from your app? If so just connect to the SPP service and send the text.
BluetoothAddress addr = ...
Guid serviceClass;
serviceClass = BluetoothService.SerialPort;
var ep = new BluetoothEndPoint(addr, serviceClass);
var cli = new BluetoothClient();
cli.Connect(ep);
Stream peerStream = cli.GetStream();
peerStream.Write ...
(From General Bluetooth Data Connections)
The Zebra Mobile Printer needed to be properly configured before pairing with this method will work. Here is what I did:
First, I ran the following commands on the printer:
.
! U1 setvar "bluetooth.authentication" "setpin"
! U1 getvar "bluetooth.authentication"
! U1 getvar "bluetooth.enable"
! U1 getvar "bluetooth.discoverable"
! U1 setvar "bluetooth.bluetooth_pin" "0000"
! U1 getvar "bluetooth.bluetooth_pin"
Then, the application with this code ran successfully.
.
int pair_req = 0;
try
{
if (BluetoothSecurity.SetPin(device, "0000")) {
while (status == false && pair_req < 3)
{
++pair_req;
status_box.Text = status_box.Text + '\n' + "Attempt " + pair_req.ToString();
status_box.Update();
if (BluetoothSecurity.PairRequest(device, "0000"))
{
status = true;
client.Refresh();
status_box.Text = "Paired Successfully.";
status_box.Update();
Thread.Sleep(5000);
}
else
{
status = false;
}
}
}
}
catch (ArgumentNullException e)
{
status_box.Text = "Pair failed.";
status_box.Update();
Thread.Sleep(5000);
}
status_box.Update();
Thread.Sleep(400);

Categories