Run code on periodic timer after services registered - asp.net-boilerplate

I have a class which I'd like to run a method on periodically. I'd prefer to do this with a timer method, so built the class with a method: StartPolling() which would then call my DoSomething() method every 60 seconds.
I tried to start the polling from the Main method in Program.cs:
public static void Main(string[] args)
{
var webHost = BuildWebHost(args);
ConfigureApp();
var cam = IocManager.Instance.Resolve<CameraManager>();
webHost.Run();
}
But when I try resolve an instance (CamerManager) I get an error that other things that CameraManager depends on haven't been registered, e.g. repositories.
What's the best way to do this...and I do not want to use the ABP background jobs as ASP.NET may "go to sleep" so my tasks wouldn't get run on time.
Thanks
Chris

Related

How to create a custom events in C#

I'm trying to develop an application using C# wiforms. I want to execute void sendEmail(){} function in a class only when internet connection is up. The method that I used is bool checkConnection(){} function infinitely loops a while loop and sending ping requests to google.com. if the ping is successful, sendEmail(){} function is called by the checkConnection() function.
But i know this is not the best practice of doing this. I'm very confusing about custom events in C#. how to use custom events to accomplish this task. expecting an answer with simple explanation.
Thanks in advance
I understand that you are trying to build a scheduler task like functionality in c#. Based on my understanding, a windows service would do the task for you like listening for the availability of internet and then performing the mail sending operation when the application goes online.
W.R.To Events, you can build your own event engine that the one that raises the application events when the app runs and then there will be database entries that lists the pending tasks. There will be a background job like a windows service that reads the database and based on the availability of internet or on some condition executes the job.
If you can be more clear on the exact use-case and what you have tried so far the community can help you better.
Sample
class Observable
{
public event ImageUploadeventHandler InternetcOnnected;
public void DoSomething()
{
ImageUploadeventHandler handler = InternetcOnnected;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
class Observer
{
public void HandleEvent(object sender, EventArgs args)
{
// upload the image to the online service
}
}

can I build javafx without start function

I want to develop a javafx application which should not have a start function why?
When I am developing a swing application with JFrame I usually comment the
public static void main(String[] args)
function and build the jar. This ensures me if someone double clicks the jar file will not execute unless proper method. I use this .jar file into another java program which will call this jar and execute it.
I want same functionality in javafx application.
When I comment public void start(Stage primaryStage) function in FX it gives error.
How should I do this.
Thanks in advance
Yogesh.
You could make use of the launch parameters of JavaFX (which is just a beefed up version of the main method parameters).
Lets say we add a new mandatory parameter named launch to our application. You can check if someone (your code) has passed this parameter to the application and start or if the parameter is missing quit the application.
You can access the parameters anywhere in your Application class, but in your case init() seems to be a good place:
public class MyFXClient extends Application {
#Override
public void init() throws Exception
{
Map<String, String> mainParams = getParameters().getNamed();
// TODO check if parameter "launch" is present..
}
public static void main(String[] args) {
launch(MyFXClient.class, args);
}
}
Now you can call the main method from outside and pass along the parameter with --launch=test.
I am using Eclipse
There I can export a project as "Runnable Jar-File" and "Jar-File".
If you want, that nobody double clicks the jar file, maybe you can use the "Jar-File" witch are not runnable
The difference between the two kinds of jar files are the "Runnable Jar-File" contains a Main-Class, and the other not.

A background running feature in Orchard

So what I'm trying to do is an Orchard Feature that if enabled, runs a separate thread (service) that queries IRepository<> of some PartRecord.
About Starting the service:
I tried starting the service on IFeatureEventHandler.Enabled(), but this gets executed only on enabling the feature, not when Orchard is started.
So i looked in the Orchard framework for anything that i can use and i found IOrchardShellEvents.Activated().
So I basicly did this:
public class MyService : IOrchardShellEvents {
...More stuff...
public void Activated() {
running = true;
//Run DoWork() in separate thread
}
public void Terminating() {
running = false;
}
private void DoWork(){
//do service work while running = true
}
}
This happened to work, but I'm not sure if this is the common practice for starting a custom defined thread when Orchard starts. So please correct me if it's not done like this..
About Repository querying problem:
The repository gets injected and at first it queries the table just fine. After a while tho, it throws an exception saying that: "Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.".
It seems extremely bizzare, that a query that get executed a couple of times crashes after a while;
Here's the code for the shows how i use the repository:
public MyService(ServiceManager manager, IRepository<SomePartRecord> repo) {
this.manager = manager;
//The manager of the service uses the repository to get a single column(ExpectaId, not a PK) out of each row
manager.LoadIds = () =>
repo.Table.ToList().Select(record => record.ExpectaId);
}
Note: The Func<> manager.LoadIds is called once per 10 seconds
Note: I'm using MySql Server 5.5
OK, so the answer to any question beginning with "how do I spin a separate thread in order to..." is "don't". Seriously. See for example http://ayende.com/blog/158945/thou-shall-not-do-threading-unless-you-know-what-you-are-doing
Fortunately, Orchard provides a way to run tasks in the background without having to spin your own threads: How to run scheduled tasks in Orchard?

How to perform repetitive actions in PureMVC flex application?

Currently working on a flex AIR project based on PureMVC framework. There was a new requirement to the project, an operation is to be performed repetitively at regular interval which has some business logic. As per PureMVC this should be placed in the command, but then command would get garbage collected the moment its executed.
Given the scenario there are few doubts/confusions/clarifications...
Creating a command with business logic would be one solution ... but then who would trigger it at specific interval? (shouldn't this be done by a command as per PureMVC)
Placing the command trigger in a mediator or placing the logic in a mediator (this would make pureMVC a bit impure :) )
How do I find a solution for this kind of scenario?
You need to pull apart the async process you want to run and the repetitive triggering of said process. My advice is to create a Proxy for the async process and a separate Proxy that's a wrapper for a Timer which simply sends a notification upon timeout. The notification is coupled to a command, which in turn calls the async proxy's methods. That way you can add logic to the command for instance what to do if the process is still busy.
The benefits of creating two proxies: you adhere to SRP. You can easily swap/modify/remove the timing proxy w/o touching the async proxy. Everything is nicely separated.
depends on what the Command should do - if it updates the Model put a Timer in one of your Proxy class and send a Notification every xx seconds which is mapped to a Command that does whatever it is you want it to do.
If it should just update the View you could add the Timer to the corresponding Mediator but then you wouldn't need a Command at all.
**
Don't create more Singletons than you need. ApplicationFacade is already one - try and keep it that way.
**
If you have to do any async calls to the backend, just make sure to add the EventListener without weakReference set to true - then everything should be ok...
Try this:
Create a Singleton class - singleton class in Flex
Have a function in this class (eg. called start) that when called starts a timer, the callback function of which sends a notification, that triggers a command that does your business logic.
When you are ready to start your regular actions simply call the get instance method on your singleton, to create the singleton and then call it's start() function.
*Optionally have a stop function that cancels the timer and stops the regular notifications being sent.
package
{
import flash.events.TimerEvent;
import flash.utils.Timer;
public final class RepititiveSingleton
{
private var timer:Timer;
private static var instance:RepititiveSingleton= new RepititiveSingleton();
public function RepititiveSingleton() {
if( RepititiveSingleton.instance ) {
throw new Error(
"ReptitiveSingleton can only be accessed through Singleton.getInstance()" );
}
}
public static function getInstance():RepititiveSingleton{
return RepititiveSingleton.instance;
}
public function start(interval:Number = 1000):void {
timer = new Timer(interval);
timer.addEventListener(TimerEvent.TIMER, onTimer);
}
private function onTimer(e:TimerEvent):void {
ApplicationFacade.getInstance().sendNotification(Constants.REPTITIVE_ACTION_NOTIFICATION));
}
}
}
This code assumes that you have your Concrete facade named ApplicationFacade, and have registered a notification using a String constant that is referenced from a class called constants.
Then in an appropriate place (maybe in your startup command) you can add:
RepetitiveSingleton.getInstance().start();
Hope this helps you.
IMO, the timer belongs in a mediator. Let it- well, mediate the asynch process messaging. It will be a little state machine to make sure everything is running smoothly. Commands still do the heavy lifting, it just sits around like a 911 operator.

e.getWindow().dispose() is not working?

I have a main program which calls a JFrame to get User information, If a user press submit I am storing the information in POJO and getting it into Main program.
If User clicks on Exit, I want to dispose the JFrame and want to exit the main program as well after executing one logging statement in main method.
If I use -
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
and
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
e.getWindow().dispose();
}
});
all the Threads exit immediately and I am not able to execute logging statments in main method.
If I use-
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
e.getWindow().dispose();
}
});
My main method execute those logging statments but it never exit, It stay silent after executing all the statements.
If I use this -
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
Thread.currentThread.interrupt();
}
});
Everything works fine. But is it the correct way of doing this?
In theory, if you dispose all top-level windows, the JVM should terminate cleanly.
However, there are a few details to make sure, which are detailed on this page:
Therefore, a stand-alone AWT
application that wishes to exit
cleanly without calling System.exit
must:
Make sure that all AWT or Swing components are made undisplayable when
the application finishes. This can be
done by calling Window.dispose on all
top-level Windows. See
Frame.getFrames.
Make sure that no method of AWT event listeners registered by the
application with any AWT or Swing
component can run into an infinite
loop or hang indefinitely. For
example, an AWT listener method
triggered by some AWT event can post a
new AWT event of the same type to the
EventQueue. The argument is that
methods of AWT event listeners are
typically executed on helper threads.
If you don't manage to find what keeps the program alive, there can be another way:
-Use the first method you described, with the EXIT_ON_CLOSE
-Add a ShutdownHook to the runtime, to execute your last logging statements:
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
//logging statements
});
Dispose method only releases system resources.
To actually close the window you have to call setVisible(false)