Using Static Wrapper Class - c#

In my search for a WebSockets library, I came across this website that provides Delphi and C# versions in download section. It grabbed my attention especially because the client-side of my application is developed using Delphi, and I'm trying to develop the server-side using C#.
Looking at the Chat sample for C#, I realized that it uses a wrapper class (sgcWebSocketLib) around the unmanaged DLL written in Delphi. Here is an excerpt from sgcWebSocketLib.cs:
public sealed class sgcWebSocketLib
{
private static volatile sgcWebSocketLib instance;
private static object syncRoot = new Object();
private sgcWebSocketLib()
{
}
public static sgcWebSocketLib Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new sgcWebSocketLib();
}
}
return instance;
}
}
... //the rest is omitted
}
and the code from Start button in Chat server (a typical WinForms application):
private void btnStart_Click(object sender, EventArgs e)
{
string vOptions = "";
... //setting options according to UI values
sgcWebSocketLib.Instance.Server_LoadOptions(vOptions);
sgcWebSocketLib.Instance.Server_Start();
}
Now, here is the actual question: this Chat server uses a static property of sgcWebSocketLib class, and starts sending/receiving WebSocket stuff. Can I use the same approach in an ASP.Net application (WebForms or MVC)? Can I write the Chat server in ASP.Net using this wrapper class?
PS: I know there is SignalR and maybe others. But it has some limitations (IIS 8, Windows Server 2012 requirement for WebSocket) beside the unanswered communication problem with a Delphi VCL client.

Yes you can.
You will just have to pay attention to the Idle Time-out settings for your worker process (defaults to 20 minutes) as well as your Recycling settings (default is once every 29 hours). You may want to disable both settings if you want your application to never be recycled / go idle regardless of other parameters.
Recycling / idling will cause the worker process to shutdown, thus you'll lose any static variable and they'll have to be re instantiated when the process starts back up.
Check this answer for more info.

In IIS < 8 you won't be able of bind the WebSocket port to the same port than the web application (that is exactly what IIS8 can do)
Even with IIS8, the AppDomain is unable to recycle if there are WebSockets connected. So using the info that #Xeaz provided may be good idea. Usually I keep them in separate applications, since there is no point in mixing a connection oriented app (WebSockets), with a request-response one (regular HTTP). The only favorable point in doing that with IIS8 is the fact that both can share the port, but that is not really an issue aside of open/map an additional TCP port in the network, since cookies do not mind the port and WebSocket is not even affected by the SOP.
If the client is using the WebSocket protocol RFC6455 correctly, it should not matter which implementation is connecting to. I develop a websocket server for .NET/Mono 4.5 that works on Windows 7, take it a look if you go with the .NET server option.

Related

Xamarin Android - VpnService is blocking all apps

An app I'm designing uses the VpnService, along with the VpnService.Builder, classes to generate a VPN in order to block traffic from specific apps. According to the documentation over at developer.android.com, all apps should be allowed through the VPN until Builder.AddAllowedApplication or Builder.AddDisallowedApplication is called.
When my VPN service starts up, for some reason, all apps are being disallowed which is strange. As soon as I disconnect from the VPN, all apps become available again. I need to to allow all, unless otherwise specified (which is what the documentation says should be happening). I start the VPN by calling the following:
private string _sTag = typeof(VpnService).Name;
private VpnServiceBinder _objBinder;
private ParcelFileDescriptor _objVpnInterface = null;
private PendingIntent _objPendingIntent = null;
...
if (_objVpnInterface == null)
{
Builder objVpnBuilder = new Builder(this);
objVpnBuilder.AddAddress("10.0.0.2", 32);
objVpnBuilder.AddRoute("0.0.0.0", 0);
// Form the interface
_objVpnInterface = objVpnBuilder.SetSession("Squelch").SetConfigureIntent(_objPendingIntent).Establish();
// Disallow instagram as a test
objVpnBuilder.AddDisallowedApplication("com.instagram.android");
// Set flag
_bVpnIsRunning = true;
}
So in the above instance, instagram should be the only blocked app, but all traffic appears to be blocked (can't use the chrome app, facebook, etc). Is there something I am missing in regards to this? Should I be specifying something before/after establishing the interface? Any help or direction would be greatly appreciated!
Note: In case it matters, I am targeting android 6.0 and higher. I can provide more source if required.
addDisallowedApplication:
By default, all applications are allowed access, except for those denied through this method. Denied applications will use networking as if the VPN wasn't running.
AddDisallowedApplication excludes the application from your VPNService and allows it to continue to use the "non-VPN" networking stack.
addAllowedApplication:
Adds an application that's allowed to access the VPN connection
Note: You can use an allowed or disallowed list, but not both at the same time.
So lets say we want to "block" any Chrome package from accessing the normal networking stack and redirect any Chrome apps from accessing the network via our "blocking" VPN, we can add all Chrome app package names to our VPNService implementation.
Note: there are 4(?) different Chrome apps, alpha, beta, etc.... so lets just block any package that has the name chrome in it, not really ideal, but for an example it works.
using (var pm = Application.Context.PackageManager)
{
var packageList = pm.GetInstalledPackages(0);
foreach (var package in packageList)
{
if (package.PackageName.Contains("chrome"))
{
Log.Debug(TAG, package.PackageName);
builder.AddAllowedApplication(package.PackageName);
}
}
}
After you .Establish() the VPN connection, all Chrome applications networking will be redirected to your VPNService and thus blocked.

Transfer data from Windows Service to Console Application repeatedly

Here is my scenario, I have a windows service that runs a task every 20 minutes, the task is: requesting updates from an API hosted by a remote website.
The response is a list of JSON objects, When the Service receives the list, it carries out a set of operations then appends more JSON objects, finally the service must push the list to a running console application.
My very specific question is: how to transfer this data from the windows service to the console App both directly and professionally
By directly I mean without intermediate solution like writing in a temp file or saving in SQL table ... etc.
By professionally I mean the best optimal solution especially without p/Invoke from the service to the console App.
You would definitely need a medium to communicate between these two processes. The communication can be done in a lot of ways on the same system.
With your explanation in Question it looks like one way communication. May be you can go for Inter-process communication via sockets(raw level) or Use a messaging framework for communication(WCF/SignalR) or you can even use a Message Queue system(MSMQ/RabbitMQ) etc.
You can get a specific answer if you can narrow down your question.
A nice, clean, 'modern' way of doing this, would be to host a Web API directly in the console application, and accept JSON input.
This is relatively easy to set up, and very easy to test and use.
Other methods include .NET remoting (which is not very modern any more), some other kind of service, like WCF, or any of the multitude of windows IPC methods.
I wrote an answer here that has some applicable code. Basically, the OP there wanted to send strings from a Windows Forms application to a console application and have the console application print the strings.
My recommendation is to use a Message Queue.
A few quick notes: first, you may have to enable the feature in Windows if you've never done so. Also, I guess under certain configurations of Windows you can't create the Message Queue directly from C#; if that's the case for you, you can create it manually (or there's probably a way to do it as part of an install script or something).
Here's the Windows Forms code:
private void button1_Click(object sender, EventArgs e)
{
// Or whatever name you end up calling it if you created the queue manually
const string myQueue = ".\\myQueue";
// It's possible that this won't work on certain computers
// If not, you'll have to create the queue manually
// You'll also need to turn the Message Queueing feature on in Windows
// See the following for instructions (for Windows 7 and 8): https://technet.microsoft.com/en-us/library/cc730960(v=ws.11).aspx
if (!MessageQueue.Exists(myQueue))
{
MessageQueue.Create(myQueue);
}
using (MessageQueue queue = new MessageQueue(myQueue))
{
queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
queue.Send("Test");
}
}
Console application:
static void Main(string[] args)
{
// Or whatever name you use
const string myQueue = ".\\myQueue";
// See my comment on the corresponding line in the Windows Forms application
if (!MessageQueue.Exists(myQueue))
{
MessageQueue.Create(myQueue);
}
MessageQueue queue = new MessageQueue(myQueue);
queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
while (true)
{
Message message = queue.Receive();
string messageText = message.Body.ToString();
// Close if we received a message to do so
if (messageText.Trim().ToLower() == "exit")
{
break;
}
else
{
Console.WriteLine(messageText);
}
}
}

C# windows service subscribed to webserver

I'm working on an intranet website.
All users should get desktop popups from the webserver whenever something new is posted on the website.
I was looking to make my own windows service that would subscribe to the server ( Making use of something like SignalR ) and then this service would show a simple popup notifying the user whenever the server sends out a message.
But instead of building this myself i was wondering if something like this isn't already out there. I've been looking around a bit but couldn't find anything.
I'm mainly a web developer and have never built a windows service or C# desktop application so i would prefer using some existing code.
Does anyone know of such a thing ?
For building a Windows Service try Top Shelf: http://docs.topshelf-project.com/en/latest/
In general it is easy as one, two, three...
public class TownCrier
{
readonly Timer _timer;
public TownCrier()
{
_timer = new Timer(1000) {AutoReset = true};
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
public class Program
{
public static void Main()
{
HostFactory.Run(x =>
{
x.Service<TownCrier>(s =>
{
s.ConstructUsing(name=> new TownCrier());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("Stuff");
x.SetServiceName("Stuff");
});
}
}
I'm working on an intranet website. All users should get desktop
popups from the webserver whenever something new is posted on the
website.
using timer is not a good technique over here as updates are not guaranteed in particular interval or session .but you can take that as an option based on the need.
I was looking to make my own windows service that would subscribe to
the server ( Making use of something like SignalR ) and then this
service would show a simple popup notifying the user whenever the
server sends out a message.
Yes exactly like a chat application that would frequently have messages and users get a pop up.ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.
But instead of building this myself i was wondering if something like
this isn't already out there. I've been looking around a bit but
couldn't find anything.
References for SignalR Link1,Link2,Link3
I'm mainly a web developer and have never built a windows service or
C# desktop application so i would prefer using some existing code.
Making C# desktop or windows service is not a big deal as you already are a programmer.Some existing codes for updations pop up is here.
for the signalr Server side, I would suggest you use a C# winform.
for the client side, you can use JavaScript inside any html file to 'receive' the message from the signalr Server, then you can popup an alert message or whatever you want, however, in this case you have to make sure the users are browsing that html file in a browser, otherwise the message won't be received.
there's no ready code since signalr support different types of servers as well as different types of clients, I believe you need to write your own code. Actually Signalr is quite easy to use, write your own code may be faster than using the others.
This question: SignalR Chat App in WinForm With Remote Clients looks like it might point you inthe right direction. Specifically this article:
https://damienbod.wordpress.com/2013/11/01/signalr-messaging-with-console-server-and-client-web-client-wpf-client/
you could probably use DesktopToast: https://github.com/emoacht/DesktopToast
or Growl: http://www.growlforwindows.com/

.NET Remoting - How can the Server update the client?

Right now, I am in prototyping phase. So I am just getting started.
Situation:
Server - Will be run tests and publish progress to Client, must be low impact, no webserver, possibly running xp embedded or xp home.
Client - Initiate tests and receive progress report. running xp pro.
The two machines are connected via ethernet. I would like to use .NET remoting to communicate between the two machines, and I would like to use events to update the client with new results from the server, but I've read that events are unreliable in these conditions. How should I do this? Could the Server connect to the client and use remoting to publish the events? Would that work okay?
I once deployed a system wich used remoting, and where the server launched some events to which the client could subscribe to.
In order to make it possible, you have to set the typeFilterLevel to full, and, you also have to create an 'intermediate' object that is known on the client and on the server in order to be able to handle your events.
For instance:
This is the class that is known on the server & on the client side.
public abstract class MyDelegateObject : MarshalByRefObject
{
public void EventHandlerCallback( object sender, EventArgs e )
{
EventHandlerCallbackCore(sender, e);
}
protected abstract void EventHandlerCallbackCore(object sender, EventArgs e );
public override object InitializeLifetimeService() { return null; }
}
At the client-side, you create another class which inherits from the above class, and implements the actual logic that must be performed when the event is raised.
public class MyConcreteHandler : MyDelegateObject
{
protected override EventHandlerCallbackCore(object sender, EventArgs e)
{
// do some stuff
}
}
You simply attach the eventhandler to the event of the remote object like this:
MyConcreteHandler handler = new MyConcreteHandler();
myRemoteObject.MyEventOccured += new EventHandler(handler.EventHandlerCallback);
Offcourse, if you update Winform controls in your EventHandler class, that class should also implement ISynchronizeInvoke.
Since you're still in the prototyping stage, you might want to consider using Windows Communication Foundation (WCF) rather than remoting. WCF has built-in support for publish-subscribe scenarios, and already contains all the functionality of .NET remoting and web services (from what I understand).
By the Server connecting to the client, you are actually inverting the model and causing the server to become the client and vice versa.
You are better off having the client initiate tests, and poll the server for status updates.
Your choice of remoting is not really a big deal (and makes no impact on the opinion I offered), but you may want to investigate its replacement (WCF) instead of spending time on a 'replaced but still supported' technology.

How to create a simple c# http monitor/blocker?

I was reading that question (How to create a simple proxy in C#?) that is near of my wishes.
I simply want develop a c# app that, by example, monitors Firefox, IE, etc and logs all navigated pages. Depending of the visited page, I want to block the site (like a parental filter).
Code snippets/samples are good, but if you can just tell me some direction of that classes to use I will be grateful. :-)
I’ll answer appropriate for a parent: ala "Parental Controls"
You can start out with a proxy server when the kids are less than about 10 years old. After that, they will figure out how to get around the proxy (or run their own client applications that bypass the proxy). In the early teen years, you can use raw sockets.
Type this program into Visual Studio (C#).
class Program
{
static void Main(string[] args)
{
try
{
byte[] input = BitConverter.GetBytes(1);
byte[] buffer = new byte[4096];
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
s.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.91"), 0));
s.IOControl(IOControlCode.ReceiveAll, input, null);
int bytes = 0;
do
{
bytes = s.Receive(buffer);
if (bytes > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
}
} while (bytes > 0);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Note that this is just a “snippet”, lacking appropriate design and error checking. [Please do not use 'as-is' - you did request just a head start] Change the IP address to your machine. Run the program AS Administrator (use “runas” on the command line, or right-click “Run as Administrator”). Only administrators can create and use raw sockets on modern versions of windows. Sit back and watch the show.
All network traffic is delivered to your code (displayed on the screen, which will not look nice, with this program).
Your next step is to create some protocol filters. Learn about the various internet application protocols (assuming you don't already know), modify the program to examine the packets. Look for HTTP protocol, and save the appropriate data (like GET requests).
I personally have setup filters for AIM (AOL Instant Messenger), HTTP, MSN messenger (Windows Live Messenger), POP, and SMTP. Today, HTTP gets just about everything since the kids prefer the facebook wall to AIM nowadays.
As the kids reach their early-to-mid teenage years, you will want to back-off on the monitoring. Some say this is to enable the kids to “grow up”, but the real reason is that “you don’t wanna know”. I backed off to just collecting URLs of get requests, and username/passwords (for emergency situations) that are in clear text (pop, basic auth, etc.).
I don't know what happens in late teen years; I cannot image things getting much worse, but I am told that "I have not seen anything yet".
Like someone earlier said, this only works when run on the target machine (I run a copy on all of the machines in the house). Otherwise, for simple monitoring check your router - mine has some nice logging features.
My final comment is that this application should be written in C/C++ against the Win32 API directly, and installed as a service running with administrative rights on the machine. I don't think this type of code is appropriate for managed c#. You can attach a UI in C# for monitoring and control. You have to engineer the code so as to have zero noticeable effect on the system.
Your approach will depend on whether or not you are installing this application on the same box you are using to browse or on a separate proxy server.
If you are doing this on a separate server it will be easier to accomplish this in C# / managed code, as you will be simply writing a C# proxy server that client pc's will have point to. System.Net.Sockets namespace TcpListener and TcpClient will be your friend.
If, however, you are installing this on the same machine then take a look WinPcap and and SharpPCap and perhaps Fiddler for some ideas.
Hope that helps.

Categories