Best Practices: Adding a CLI to Existing Windows Service in .NET / Core - c#

I'm wondering if anyone has any recommendations for the best way to implement a command line interface to an existing Windows service.
Ideally, the following requirements can be met:
Supports .Net Core and works cross platform
Is self hosted (ie not a separate executable)
Is registered globally and available in any terminal (ie. > myApp doThis -please --prettyplease)
Can be piped through to a web interface for remote terminal access via existing web app
Is available via terminals on other local network devices
The big requirement is that this works cross platform and is not tied to Windows. Any recommendations are very much appreciated!!!

Questions that feature the phrase "what is the best" typically aren't a good fit for stackoverflow as they're subjective - there may be no right answer to your query, but maybe there will be some good ones.
One option that I've employed several times in the past is to implement something like a simple shell/command prompt, accessed via telnet. You simply open a listening socket (TcpListener) and accept text commands sent to it/write text to it, something like your first day's of programming, with console in and out stream printing. There are bucketloads of examples on the web of simple tcp servers so I won't provide any code here. In terms of your points:
Supports .Net Core and works cross platform
It's tcp based, this is intrinsic
Is self hosted (ie not a separate executable)
Starts when the app starts, hosted by the app, doesn't need any complex IPc
Is registered globally and available in any terminal (ie. > myApp doThis -please --prettyplease)
The firewall is probably the only thing stopping your remote device communicating
Call be piped through to a web interface for remote terminal access via existing web app
html5/web based implementations of telnet exist. Could also make a simple web interface out of it (treat the browser like telnet; Here's little difference between them, they both read and write tcp sockets, just the browser adds more text from the http protocol. You can filter that out and just get the interesting bit the user can vary (the URL))
Is available via terminals on other local network devices
Covered above
The last time I implemented this was on a server that was used by credit card terminals. It already had a listening socket and clients followed a strict protocol, so it was easy to detect when a message didn't match protocol and treat it as a command instead. The system grew to the point where the server was full remotely configurable via a simple telnet interface, new credit card ranges and routings could be added,debug printouts could be enabled and all traffic would be sent to the telnet client, certain card terminals could be monitored etc; it was nothin more than compsci101 stuff of command = streamreader.ReadLine(), if(command == "debug") Global.DebugLoggingStream = tcpWriterStream
It had a web interface too, based on HttpListener, that just provided a nicely formatted list of the most recent errors, some config settings etc.. some stuff is better on a web page in a table than in an 80char column format. Eventually I upgraded this to be more like the terminal; the user could end the URL with a command, the command would be carried out and the result put in an array. Each time the page was served he array was dumped, so it became a sort of command shell in itself, not requiring telnet. I kept the telnet interface because it was good for realtime debugging, watching messages as they happened etc but if you wanted to get really fancy, websockets exists today for that sort of thing.
Another thought struck me; perhaps most of this hard work has been done for you, if you can find a c# implementation of an irc server, paired with a web based irc client, it would provide a way to "chat" with your service (which is pretty much all a command shell is; a human having a text chat with a program)

Related

How to connect multiple clients to multiple servers and send alerts from servers based on certain events?

Background
I have multiple servers that I currently connect to remotely to run a number of different commands/scripts to obtain information about the servers and/or applications running on the servers.
I'd like to automate running the commands/scripts (or the code contained in the scripts converted to C#/.NET) and have the server send alerts/notifications/messages to a client (basically a Windows Form) running on multiple workstations, but need some guidance.
For reference, I have limited experience creating Windows Services, but feel fairly confident in being able to create them on the server to handle to command/script automation, which I'm assuming would be the best way to go about handling the command/script automation on the server (since the commands/scripts would need to be run all the time or at set intervals).
Question
How can I connect multiple servers to multiple clients so that the server sends alerts/notifications/messages to the client when a command/script or even an event occurs on the server?
For instance, if an application on the server has a built-in command that can be run to determine the status of the application (up, down, limbo, etc.), I would like the Windows Form on the client to receive an alert from the server when the command returns "down" or "limbo" when it is run, presumably from a Windows Service. The alerts would be displayed on the Windows Form that would be setup basically as a dashboard for the servers that the client can connect to.
An even better outcome would be that the client runs as a background application and a notification appears similar to how Microsoft Outlook displays a notification when new email messages arrive (although these notifications would likely require user interaction to close instead of fading out like the Outlook notifications).
I would also like for the client to use a configuration file that has the connection information for the servers in it so that the servers being used can be changed quickly new servers are added or existing servers are decommissioned.
Research (so far)
I've read about WCF and duplex contracts, and how WCF can be hosted in Windows Services. From what I've read, this seems promising. However, I'm not quite sure how I would set this up so that the client can connect to a WCF service on multiple servers.
One thing that I'm concerned about with WCF is that in all of the WCF examples (which implement a calculator-type service) I've seen the client has to initiate the communication with the server in order to receive a message through a callback. In the calculator service examples, the client sends numbers to the service and the result is provided in the callback. I've also seen an asynchronous example, but in that example the client initiated a single, long running request and the callback returned a single response when it was finished processing.
And, just so I'm clear about bindings in WCF, it is possible to create and use bindings for multiple servers using a configuration file without having to use SvcUtil.exe to generate the code, correct? The reason I ask is because the servers that will be configured will likely be change for different users, so the client needs to be flexible when connecting to the services.
I've just now started looking at Sockets, but I'm not familiar enough with them to know if this would be the better option to achieve my objective.
Summary
I'm just looking for guidance, so if you can help direct me to some resources that will help me achieve my objective, I would appreciate it. I've searched extensively, but the majority of my searching either doesn't apply to my scenario, it is limited to a single server/client interaction, or it is limited to a single server with multiple clients.
Since I'm not sure what direction to go in, I don't have any code examples, although I have implemented the examples in the following Microsoft article: Windows Communication Foundation - Getting Started Tutorial
So you want to build a system of
multiple servers which execute commands on the computer they are running on
multiple clients which will receive the status of the commands executed on server or such information from the server
This would be my advice
Servers can be implemented as windows service. You will be able to administrate them easily this way using the services console or the scm. Checkout this link for a creating a simple C# service How do you write and use a Windows Service in C#?
Also, you can set the service to run as an in-built service user with different levels of permissions in addition to regular user accounts.
I have not used WCF, but usually clients connect to the server; this is a pretty common model, and hence all samples are such. Initiating connection from server is not a big deal (at least in a socket program), but just a bad model. You have to ask yourself, if no client is connected to your servers, how can they relay a status to the end user. You have to think clearly about the communication model. I would suggest a central repository of messages. It can be a file on a shared file system or a database or any such entity which can act as a data repository. This way all servers can convey there messages without caring if a client is connected or not. You can use Sockets to achieve what you want to do. Check the asychronous socket server sample from MSDN to understand how to do it.
Making the client run in the background and just have a notification area icon is also easy in c#. You can use NotifyIcon Class for that. This CodeProject article (Formless System Tray Application) demonstrates its usage. To show notification a la outlook style, you can refer to the following post: How to create form popup from from system tray on windows application (not web) with c#. Look at not only the accepted answer but other answers too; there are lot of useful links in it.
So far we have windows service talking over sockets, storing messages in a central repository and capable of handling multiple clients with toast style pops for client side notification.
You need a far richer client side GUI so the end users can take actions on the messages sent from the server. You can maintain a list of servers in app.config for the client that the client connects on startup. You should to provide a GUI for users to manage all servers and their connections.
Lat but not least, by building such a client server model, you are effectively building a security loophole in your systems. You should implement a good authorization mechanism. Checkout the following post: Authenticate user in WinForms (Nothing to do with ASP.Net)
EDIT:
You can also implement your server to accept "custom command" when you implement it as a service. This way, your client server communication will be standardized by using ServiceController to pass the command. This post might help: How to send a custom command to a .NET windows Service from .NET code?.
Don't get confused in the "command" terminology here. ServiceController issues standard commands to a service for start, stop, pause, resume and restart the service. These are the same items you see on the context menu when you right click a service in the services.msc snap-in. The same way a service can respond to custom commands. In your case the custom command maybe a request to execute a process.
Note that some mechanisms I have described are geared towards an intranet setup while others scale fine on both intranet and internet

Is it possible that we could communicate C++ program in linux to a C# program acting as server using Remote Method Invocation?

Is it possible to implement client/server communication between a C++ program (client program) running in linux OS with a C# program(server program) running in Windows using RMI implementation?Can anyone suggest any possible way...Any kind of helpful reference is welcome
You would need to go along the lines of Google Protobuf. It is available with C++ and C# as well.
A similar answer from MSDN
It does not matter if you send data from java,c++ or c#, when it goes
over the network it's just 1s and 0s. It's a matter of what you do
with it on the client/server side. So, be sure that the data that you
receive corresponds with the structure that you have (that you want to
deserialize to).
Sometimes you need to manually put the bits and bytes together to get
it all working out. However, there is something called "Protobuff"
that can help you get a common structure of the data that you send,
google it and read all about it.
You can implement client server with sockets and serialize/deserialize it using protobuf.
(MSDN link might help in solution)
I think message passing libraries would fit best in to this. Take a look at ZMQ for instance; they have binding for many languages found here
so you may have your event dispatcher in one language and listener in the other language. Also take a look at apache thrift
CORBA is one IPC mechanism that will provide the RPC mechanism that you are looking for.
Here is a link describing communication between C# server and JAVA client.
http://iiop-net.sourceforge.net/dnAdderRmiClient.html
At one of the companies I worked previously, it was used for communication between c++ and java programs in a client/server model.
They used a combination of ACE/TAO libraries.
http://www.cs.wustl.edu/~schmidt/TAO.html
I would recommend that you do not use remote method invocation for communication between a client and a server. In the nineteen-nineties we used to believe that RMI is a good idea, but since then we have realized that there are much better ways for communication between computers.
The most popular way is by using Web Services, and the easiest flavor of Web Services is RESTful Web Services. (Look them up.) This has the benefit of not caring at all whether the runtime environment of the client looks anything like the runtime environment of the server, as the case is with your setup, where your client is C++ on Linux and your server is C# on Windows.
Mozilla's XPCOM might be your bridge. There is also PyXPCOM. Realistically though the easiest way is to have an intermediate VBox. So you run a VBox instance (running Windows) on the linux machine and then use VBox API (from C++) to issue commands within VBox. So you end up with
Linux <--xpCom--> VBox <--COM--> Windows
When working over network it's protocol what matters, not the client/server.
In telecommunications, a communications protocol is a system of rules that allow two or more entities of a communications system to transmit information via any kind of variation of a physical quantity. These are the rules or standard that defines the syntax, semantics and synchronization of communication and possible error recovery methods.
Source Emphasis is mine.
So, in order to communicate your C++ client and C# server you need to choose or define protocol that will be used for communication.
Your protocol can be build above another protocol. For example, you can use HTTP for transportation purposes and define your protocol describing what syntax should be used for messages in HTTP requests and responses bodies. This will help you, because there're many ready-to-use solutions for HTTP communication.
Actually you will build your protocol based on another anyway. HTTP itself build above TCP. You'll need to choose whether it would be low level or high level protocols. They all have their pros and cons.
But you will have to deal with messaging between your client and server yourself.
As an alternative you can use some Remote Procedure Call(or RPC) solution:
Remote procedure call (RPC) is an inter-process communication that allows a computer program to cause a subroutine or procedure to execute in another address space (commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction.
So that means that you only have to follow guidelines how to build your client and server and all communication will be hidden and will look like as just calling object's method.
Source
Here's short list of possible RPC solutions:
Component Object Model with DCOM. Wiki: COM,DCOM. MSDN: COM, DCOM.
Simple Object Access Protocol. Wiki.
Windows Communication Foundation. Wiki. MSDN. SO(credits to Sanju for link).
To wrap it up:
It's not a problem that your client and server are in different environments and are developed using different platforms. You only have to build communications between them using either your own messaging system based on some protocol, or some RPC system.
We could just write a C# program to listen messages from a particular port and write another C++ client program to write message to that port.As thus we could communicate both application.

What technology should I use to allow my Windows Service or Web Service (written in C#) publish it's progress and status?

The requirement:
My [windows/web] service in C# 3.5 periodically has something to say about its state. It could be a progress status, log entry, error or warning, or signal of data availability.
Client applications are on the same network, and they would like to learn about some of these messages.
Clients start and stop randomly, largely outside of my control.
Clients are written in C#, C++ and even Delphi.
Database connection that can support storing my service's messages may not be available.
I would like my service to publish its messages (text-based protocol) for subscribers to be able to see and react to. I don't want to bother with how many clients are connected, or are there clients at all.
I was looking into named pipes, regular TCP/IP, semaphores, but I cannot seem to find anything that fits the bill.
Currently I'm forced to store a file on the network that is being currently updated, but it's not clean, and requires clients to have access to a network share.
Looks like you need to use WCF for this.
WCF can handle named pipes, TCP/IP and it can do windows and Web services.
You can have a look here:
http://msdn.microsoft.com/en-us/library/ms731082.aspx
Hope this helps!
Check out the OWIN project and the Kayak implementation.
It will allow you to run your own in-process web server.

Do I want to use Remoting or just a Socket connection

I'm writing code for a project that was initially written in VB6 and my partner and I are trying to slowly migrate it to .NET. In the mean time I need some feedback on how I should go about doing the following:
My users can run several instances the same program to help split several specific Messages sent to a server; a server that will IP Ban you if you send to many messages at one time. What I want to do is share these messages sent between the programs so that we can build a distributed messaging system to prevent an IP Ban - these programs are running on the same machine at the present. I'm trying to get my feet wet, so I've done several (no joke...) days worth of research and I came to the conclusion that I could write a DLL in C# .NET, incorporate the needed Interop to support COM, and have that DLL store commonly used Functions, Arrays, Etc. The function would also raise events on the VB6 program to send its messages which then the client program would send to the server its connected to.
My partner says I'm going about this the wrong way and that I should to create a Sever application that loads when the first stances of my program starts and distribute messages between my clients via Socket. This process seems like a lot of work.
I'm finding it all the more difficult because samples I've found on MSDN won't compile. If you know of a great example I'd really appreciate you posting it.
Don't use Remoting for new development. It has been deprecated in favor of WCF.
Use WCF instead. You can host a WCF service in any application, and it can communicate quite quickly and efficiently using binary over TCP/IP.

Server Push vs Client Pull for Agent-Server Topology

I need to create a system comprising of 2 components:
A single server that process and stores data. It also periodically sends out updates to the agents
Multiple agents that are installed at remote endpoints. These collect data in (often, but not always) long-running operations, and this data needs to get to the server
I'm using C# .NET, and ideally I want to use a standards compliant communications method (i.e. one that could theoritically work with Java too, as we may well also use Java agents in the future). Are there any alternatives to web services? What are my options?
The way I see it I have 3 options using web services, and have made the following observations:
Client pull
No open port required at the agent, as it acts like a client
Would need to poll the server for updates
Server push
Open port at the agent, as it acts like a server
Server must poll agents for results
Hybrid
Open port at the agent, as it acts like both a client and a server
No polling; server pushes out updates when required, client sends results when they are available
The 'hybrid' (where agents are both client and server seems the obvious choice - but this application will typically be installed in enterprise and government environments, and I'm concerned they may have an issue with opening a port at the agent. Am I dwelling too much on this?
Are there any other pros and cons I've missed out?
Our friends at http://www.infrastructures.org swear by pull-based mechanisms: http://www.infrastructures.org/papers/bootstrap/bootstrap.html
A major reason why they prefer client-pull over server-push is that clients may be down, and clients must (in general) apply all the operations pushed by servers. If this criteria isn't important in your case, perhaps their conclusion won't be your conclusion, but I do think it is worth reading the "Push vs Pull" section of their paper to determine for yourself.
I would say that in this day and age you can seriously consider only pull technologies. The problem with push is that clients often are hidden behind Network Address Traversal devices (NAT) like wireless routers, broadband modems or company firewalls and they are, more often than not, unreachable from the server.
Making outbound connections ('phone-home'), specially on well known ports like HTTP/HTTPS can basically be assumed as 'possible' even under most constricted networks.
If you use some kind of messaging server (JMS for Java, not sure for C#) then your messaging server is the only server that needs to open a port and you can have two way communication from your agent to the messaging server and from the server to the messaging server. This would allow you to accomplish the hybrid model without needing to open a port on the agent server.
IMHO, I find your best option is the pull option.. that can satisfy your main system requirements as follow:
The first part: Data needs to get to the server, that's obviously can be done through invoking a web method that send that data as a parameter
2nd part:(Server periodically sends out updates to the agents): You can still do that that thru client (regular) pulls by some sort of a web service method that "asks" for the updates since its last pull (some sort of s time stamp to get the updates it missed)
The hybrid method seems a bit weird to me given that I think of an agent as a part of the system that probably might go "offline" quite often, what will the server then do if that failed? it's usually a tough question/decision, specially if you're not sure if this an intended "going offline" or a system/network failure.. etc

Categories

Resources