Windows 8 Socket communication with Background Task - windows-8

I have a Background Task written in C# in a Windows 8 App, and I'm having trouble connecting it to my UI task. I've tried opening a StreamSocketListener on my background task and a StreamSocket to connect to it on my UI task, as well as the other way around. If I have both the listener and the connector in the UI task, or the background task, everything works fine. However, there seems to be some kind of isolation enforced between the two of them.
I can also connect out to external services on both of them, so I thought it might have something to do with needing a loopback exemption, but that doesn't seem to be the case either, as opening up the AppContainer Loopback Exemption Utility shows all apps as having loopback access.
Is there something else I need to enable to get network communication between these two parts of my app working properly? I have enabled the Private Networks (Client and Server) capabilities in my package manifest, (the other client/server pairs don't help, so i'm just using that one)

You could use the completion event of your background task and run it repeatedly in your UI. Using LocalSettings to pass data.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx
private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
var settings = ApplicationData.Current.LocalSettings;
var key = task.TaskId.ToString();
var message = settings.Values[key].ToString();
UpdateUIExampleMethod(message);
}

Related

Is it a best practice to make setInterval every some seconds to re update axios request to update displayed data in vue project? [duplicate]

hi
I want to build a control panel for a web art application that needs to run in fullscreen, so all this panel, that controls stuff like colors and speed values, have to be located at a different window.
My idea is to have a database storing all these values and when I make a change in the control panel window the corresponding variable in the application window gets updated too. So, it's basically a real-time update that I could do with AJAX setting a interval to keep checking for changes BUT my problem is: I can't wait 30 seconds or so for the update to happen and I guess a every-1-second AJAX request would be impossible.
Final question: is there a way to create a sort of a listener to changes in the database and fire the update event in the main application only immediately after I change some value in the control panel? Does Angular or another framework have this capability?
(Sorry for the long explanation, but I hope my question is clearer by offering the context [: )
A web socket powered application would have this benefit. This carries a bit more complexity on the back end, but has the benefit of making your application as close to real-time as can be reasonably expected.
The Mozilla Development Network has some good documentation on websockets.
On the front end, the WebSocket object should work for you on most modern browsers.
I'm not sure what your back end is written in, but Socket.IO for Node.js and Tornado for Python will make your applications web-socket capable
If one window is opening the other windows via JavaScript, you can keep the reference to the opened window and use otherWindow.postMessage to pass messages across
"Parent" window looks like
// set up to receive messages
window.addEventListener('message', function (e) {
if (e.origin !== 'http://my.url')
return; // ignore unknown source
console.log(e.message);
});
// set up to send messages
var otherWindow = window.open('/foo', '_blank');
otherWindow.postMessage('hello world', 'http://my.url');
"Child" windows look similar
// same setup to recieve
// ...
// set up to send
var otherWindow = window.opener;
// ... same as before
For the realtime I would recommend using a library like socket.io or using a database like firebase.
For the fullscreen I would recommend using a library like angular-screenfull
i use https://pushjs.io/, had exactly the same problem and this is a really simple solution for your problem. It is capable of sending and listening to events without any database interference.

Posting a Task to the Web Consoles Execution(Management) Context

In the apache brooklyn web interface we would like to display some content for the sytsem managers. The content is too long to be served as a simple sensor value.
Our idea was to create a task and write the content into the output stream of the task, and then offer the REST based URL to the managers like this:
/v1/activities/{task}/stream/stdout (Of course the link masked with some nice text)
The stream and task is created like this:
LOG.info("{} Creating Activity for ClusterReport Feed", this);
activity = Tasks.builder().
displayName("clusterReportFeed").
description("Output for the Cluster Report Feed").
body(new Runnable() {
#Override
public void run() {
//DO NOTHING
}
}).
parallel(true).
build();
LOG.info("{} Task Created with Id: " + activity.getId(), this);
Entities.submit(server, activity).getUnchecked();
The task seems to be created and the interraction works perfectly fine.
However when I want to access the tasks output stream from my browser using a prepared URL I get the error that the task does not exist.
Our idea is that we are not in the right Management/Execution Context. The Web page is running in an other context compared to the entities and their sensors. How can we put a task so that it's visible for the web consoles context also.
Is it possible to write the content into a file and then offer it for download via Jetty(brooklyns web server)? That would be a much simpler way.
Many tasks in Brooklyn default to being transient - i.e. they are deleted shortly after they complete (things like effector invocations are by default non-transient).
You can mark your task as non-transient using the code below in your use of the task builder:
.tag(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG)
However, note that (as of Brooklyn version 0.9.0) tasks are kept in-memory using soft references. This means the stdout of the task will likely be lost at some point in the future, when that memory is needed for other in-memory objects.
For your use-case, would it make sense to have this as an effector result perhaps?
Or could you write to an object store such as S3 instead? The S3-approach would seem best to me.
For writing it to a file, care must be taken when used with Brooklyn high-availability. Would you write to a shared volume?
If you do write to a file, then you'd need to provide a web-extension so that people can access the contents of that file. As of Brooklyn 0.9.0, you can add your own WARs in code when calling BrooklynLauncher (which calls BrooklynWebServer).

`StreamSocketListener`-based server in Universal App

It is known that Windows 8.1 and Windows Phone 8.1 put lots of constraints on background activities of third-party app. For instance, it is impossible to develop server-like capability (e.g. BitTorrent) in Store App without having to keep the screen always-on using DisplayRequest.
From the latest documentation, I have a feeling that one can utilize the method EnableTransferOwnership of StreamSocketListener to delegate the usual request processing code to a background task. The problem is that I don't know how IBackgroundTask should work in this case. Normally, they are activated by some conditions/triggers such as "Internet becomes available". The only sensible trigger in this case seems to be ControlChannelTrigger but apparently, the documentation implies that it cannot be used with StreamSocketListener since the app needs to be the one who creates and register a StreamSocket, not waiting for the socket to be created by some connecting client.
Is it possible now to implement a StreamSocketListener-based server in Windows 10 Universal app platform? If it is, how can I do that?
Use it to activate a background task on socket activity such as receiving data when the app is not active, e.g.:
var socketTaskBuilder = new BackgroundTaskBuilder();
socketTaskBuilder.Name = "SocketActivityBackgroundTask";
socketTaskBuilder.TaskEntryPoint = "SocketActivityBackgroundTask.SocketActivityTask";
var trigger = new SocketActivityTrigger();
socketTaskBuilder.SetTrigger(trigger);
var task = socketTaskBuilder.Register();
socket = new StreamSocket();
socket.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.Wake);
For a complete example, look at the Socket Activity sample or the documentation.

Best way to run scheduled tasks in ASP.NET CORE [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Today we have built a console application for running the scheduled tasks for our ASP.NET website. But I think this approach is a bit error prone and difficult to maintain. How do you execute your scheduled task (in an windows/IIS/ASP.NET environment)
Update:
Examples of tasks:
Sending email from an email-queue in the database
Removing outdated objects from the database
Retrieving stats from Google AdWords and fill a table in the database.
This technique by Jeff Atwood for Stackoverflow is the simplest method I've come across. It relies on the "cache item removed" callback mechanism build into ASP.NET's cache system
Update: Stackoverflow has outgrown this method. It only works while the website is running but it's a very simple technique that is useful for many people.
Also check out Quartz.NET
All of my tasks (which need to be scheduled) for a website are kept within the website and called from a special page. I then wrote a simple Windows service which calls this page every so often. Once the page runs it returns a value. If I know there is more work to be done, I run the page again, right away, otherwise I run it in a little while. This has worked really well for me and keeps all my task logic with the web code. Before writing the simple Windows service, I used Windows scheduler to call the page every x minutes.
Another convenient way to run this is to use a monitoring service like Pingdom. Point their http check to the page which runs your service code. Have the page return results which then can be used to trigger Pingdom to send alert messages when something isn't right.
Create a custom Windows Service.
I had some mission-critical tasks set up as scheduled console apps and found them difficult to maintain. I created a Windows Service with a 'heartbeat' that would check a schedule in my DB every couple of minutes. It's worked out really well.
Having said that, I still use scheduled console apps for most of my non-critical maintenance tasks. If it ain't broke, don't fix it.
I've found this to be easy for all involved:
Create a webservice method such as DoSuchAndSuchProcess
Create a console app that calls this webmethod.
Schedule the console app in the task scheduler.
Using this methodology all of the business logic is contained in your web app, but you have the reliability of the windows task manager, or any other commercial task manager to kick it off and record any return information such as an execution report. Using a web service instead of posting to a page has a bit of an advantage because it's easier to get return data from a webservice.
Why reinvent the wheel, use the Threading and the Timer class.
protected void Application_Start()
{
Thread thread = new Thread(new ThreadStart(ThreadFunc));
thread.IsBackground = true;
thread.Name = "ThreadFunc";
thread.Start();
}
protected void ThreadFunc()
{
System.Timers.Timer t = new System.Timers.Timer();
t.Elapsed += new System.Timers.ElapsedEventHandler(TimerWorker);
t.Interval = 10000;
t.Enabled = true;
t.AutoReset = true;
t.Start();
}
protected void TimerWorker(object sender, System.Timers.ElapsedEventArgs e)
{
//work args
}
Use Windows Scheduler to run a web page.
To prevent malicous user or search engine spiders to run it, when you setup the scheduled task, simply call the web page with a querystring, ie : mypage.aspx?from=scheduledtask
Then in the page load, simply use a condition :
if (Request.Querystring["from"] == "scheduledtask")
{
//executetask
}
This way no search engine spider or malicious user will be able to execute your scheduled task.
This library works like a charm
http://www.codeproject.com/KB/cs/tsnewlib.aspx
It allows you to manage Windows scheduled tasks directly through your .NET code.
Additionally, if your application uses SQL SERVER you can use the SQL Agent to schedule your tasks. This is where we commonly put re-occurring code that is data driven (email reminders, scheduled maintenance, purges, etc...). A great feature that is built in with the SQL Agent is failure notification options, which can alert you if a critical task fails.
I'm not sure what kind of scheduled tasks you mean. If you mean stuff like "every hour, refresh foo.xml" type tasks, then use the Windows Scheduled Tasks system. (The "at" command, or via the controller.) Have it either run a console app or request a special page that kicks off the process.
Edit: I should add, this is an OK way to get your IIS app running at scheduled points too. So suppose you want to check your DB every 30 minutes and email reminders to users about some data, you can use scheduled tasks to request this page and hence get IIS processing things.
If your needs are more complex, you might consider creating a Windows Service and having it run a loop to do whatever processing you need. This also has the benefit of separating out the code for scaling or management purposes. On the downside, you need to deal with Windows services.
If you own the server you should use the windows task scheduler. Use AT /? from the command line to see the options.
Otherwise, from a web based environment, you might have to do something nasty like set up a different machine to make requests to a certain page on a timed interval.
I've used Abidar successfully in an ASP.NET project (here's some background information).
The only problem with this method is that the tasks won't run if the ASP.NET web application is unloaded from memory (ie. due to low usage). One thing I tried is creating a task to hit the web application every 5 minutes, keeping it alive, but this didn't seem to work reliably, so now I'm using the Windows scheduler and basic console application to do this instead.
The ideal solution is creating a Windows service, though this might not be possible (ie. if you're using a shared hosting environment). It also makes things a little easier from a maintenance perspective to keep things within the web application.
Here's another way:
1) Create a "heartbeat" web script that is responsible for launching the tasks if they are DUE or overdue to be launched.
2) Create a scheduled process somewhere (preferrably on the same web server) that hits the webscript and forces it to run at a regular interval. (e.g. windows schedule task that quietly launches the heatbeat script using IE or whathaveyou)
The fact that the task code is contained within a web script is purely for the sake of keeping the code within the web application code-base (the assumption is that both are dependent on each other), which would be easier for web developers to manage.
The alternate approach is to create an executable server script / program that does all the schedule work itself and run the executable itself as a scheduled task. This can allow for fundamental decoupling between the web application and the scheduled task. Hence if you need your scheduled tasks to run even in the even that the web app / database might be down or inaccessible, you should go with this approach.
You can easily create a Windows Service that runs code on interval using the 'ThreadPool.RegisterWaitForSingleObject' method. It is really slick and quite easy to get set up. This method is a more streamlined approach then to use any of the Timers in the Framework.
Have a look at the link below for more information:
Running a Periodic Process in .NET using a Windows Service:
http://allen-conway-dotnet.blogspot.com/2009/12/running-periodic-process-in-net-using.html
We use console applications also. If you use logging tools like Log4net you can properly monitor their execution. Also, I'm not sure how they are more difficult to maintain than a web page, given you may be sharing some of the same code libraries between the two if it is designed properly.
If you are against having those tasks run on a timed basis, you could have a web page in your administrative section of your website that acts as a queue. User puts in a request to run the task, it in turn inserts a blank datestamp record on MyProcessQueue table and your scheduled task is checking every X minutes for a new record in MyProcessQueue. That way, it only runs when the customer wants it to run.
Hope those suggestions help.
One option would be to set up a windows service and get that to call your scheduled task.
In winforms I've used Timers put don't think this would work well in ASP.NET
A New Task Scheduler Class Library for .NET
Note: Since this library was created, Microsoft has introduced a new task scheduler (Task Scheduler 2.0) for Windows Vista. This library is a wrapper for the Task Scheduler 1.0 interface, which is still available in Vista and is compatible with Windows XP, Windows Server 2003 and Windows 2000.
http://www.codeproject.com/KB/cs/tsnewlib.aspx

Help with sending text thou TCP/IP or LAN

Hey all i am trying to send a text message from a virtual machine (VMWARE) to my local machine so that i can hit a button in the VM and have it do something on the local.
Is there anyway to send a text through an IP, TCP/IP, LAN using VB6 or VB.net? I was looking at the net send to send something but it doesn't seem to work for me (as well as it seems to pop up a dialog box for every text you send). I've already tried this out:
http://www.codeproject.com/KB/vb/CfSimpleSendComp.aspx
But it doesn't seem to work at all on my computer? I've tried both the IP of the machine and also the computer's name. Maybe .NET Remoting in VB?
Could anyone let me know if there are other ways to do what i would like to do?
Thanks!
David
You also can consider to use Eneter Messaging Framework.
It is lightweight and very easy to use.
I am sorry, I am not familiar with VB syntax, but in C# the whole implementation
is here: (You can copy paste the code into your project, include Eneter.Messaging.Framework.dll and change the IP to yours.)
The server listening to string messages.
using System;
using Eneter.Messaging.EndPoints.StringMessages;
using Eneter.Messaging.MessagingSystems.MessagingSystemBase;
using Eneter.Messaging.MessagingSystems.TcpMessagingSystem;
namespace StringReceiver
{
class Program
{
static void Main(string[] args)
{
// Create Tcp based messaging.
IMessagingSystemFactory aTcpMessaging = new TcpMessagingSystemFactory();
IInputChannel anInputChannel = aTcpMessaging.CreateInputChannel("127.0.0.1:7091");
// Create string message receiver
// Note: it is possible to receiver typed messages too.
IStringMessagesFactory aStringMessagesFactory = new StringMessagesFactory();
IStringMessageReceiver aStringMessageReceiver = aStringMessagesFactory.CreateStringMessageReceiver();
aStringMessageReceiver.MessageReceived += StringMessageReceived;
// Attach the input channel to the string message receiver
// and start listening.
Console.WriteLine("String sercer is listening.");
aStringMessageReceiver.AttachInputChannel(anInputChannel);
}
// Processing messages.
static void StringMessageReceived(object sender, StringMessageEventArgs e)
{
Console.WriteLine("Received message: " + e.Message);
}
}
}
The client sending the string messages:
using Eneter.Messaging.EndPoints.StringMessages;
using Eneter.Messaging.MessagingSystems.MessagingSystemBase;
using Eneter.Messaging.MessagingSystems.TcpMessagingSystem;
namespace StringMessageSender
{
class Program
{
static void Main(string[] args)
{
// Create Tcp based messaging.
IMessagingSystemFactory aTcpMessaging = new TcpMessagingSystemFactory();
IOutputChannel anOutputChannel = aTcpMessaging.CreateOutputChannel("127.0.0.1:7091");
// Create string message receiver
// Note: it is possible to receiver typed messages too.
IStringMessagesFactory aStringMessagesFactory = new StringMessagesFactory();
IStringMessageSender aStringMessageSender = aStringMessagesFactory.CreateStringMessageSender();
// Attach the output channel to the string message sender
// so that we can send messages via Tcp to desired Ip address.
aStringMessageSender.AttachOutputChannel(anOutputChannel);
// Send message.
aStringMessageSender.SendMessage("Hello world.");
}
}
}
Eneter Messaging Framework can be downloaded at www.eneter.net.
If you would like to get more technical info: www.eneter.net/OnlineHelp/EneterMessagingFramework/Index.html
More examples: eneter.blogspot.com
You need a client and a server, one of them at each end. These could communicate over TCPIP (TCP or UDP), Microsoft Networking (named Pipes, Mailslots), or whatever you have. Some options depend on what OS the two machines are running, but since you mentioned NET SEND we can probably assume some flavor of Windows.
The Messenger Service is gone in later versions of Windows NT (Vista, Windows 7) so it's not the best option. There are other Mailslots messengers though as well as lots of UDP messengers.
The real question is what action you want to perform "at the push of a button." Heck, you could easily run Telnet if that gave you what you were after.
Don't forget you may have to open firewalls for any of these to work though.
.Net Remoting isn't available in VB, you must mean VB.Net. That's a remote object invokation technology though and probably not what you want.
You'd probably get to a result more quickly picking one development tool set and using whatever it offers for TCP or UDP sockets.
There are several ways. The best way depends on how you define 'text message'.
If you literally just need to hit a button and run a command on a remote machine, I would run PsExec in Process object. Cheesy but effective. Something like:
Using p as new Process()
p.StartInfo.FileName = "c:\path\to\PsExec.exe"
p.StartInfo.Arguments = "\\RemoteComputerName RemoteCommand.exe"
p.Start()
End Using
If you need bi-directional communication with a custom protocol, I would use WCF or the TCPListener and TCPClient classes to create your own socket server and client.
I would stay away from remoting.