A background running feature in Orchard - mysql

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?

Related

Run code on periodic timer after services registered

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

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
}
}

xUnit test deadlock

When I run my xUnit unit tests I sometimes get an error message like "Transaction (Process ID 58) was deadlocked on lock resources with another process and has been chosen as the deadlock victim" on one or more of the tests, seemingly randomly. If I re-run any failing test on its own it passes.
What should I do to prevent this? Is there an option to run the tests one-after-another instead of all at once?
(N.B. I'm running the tests over the API methods in my ASP.Net 5 MVC controllers under Visual Studio 2015)
Here's an example of one of my occasionally failing tests:
[Fact]
private void TestREAD()
{
Linq2SQLTestHelpers.SQLCommands.AddCollections(TestCollections.Select(collection => Convert.Collection2DB(collection)).ToList(), TestSettings.LocalConnectionString);
foreach (var testCollection in TestCollections)
{
var testCollectionFromDB = CollectionsController.Get(testCollection.Id);
Assert.Equal(testCollection.Description, testCollectionFromDB.Description);
Assert.Equal(testCollection.Id, testCollectionFromDB.Id);
Assert.Equal(testCollection.IsPublic, testCollectionFromDB.IsPublic);
Assert.Equal(testCollection.LayoutSettings, testCollectionFromDB.LayoutSettings);
Assert.Equal(testCollection.Name, testCollectionFromDB.Name);
Assert.Equal(testCollection.UserId, testCollectionFromDB.UserId);
}
}
There are two methods the test calls, here's the controller method:
[HttpGet("{id}")]
public Collection Get(Guid id)
{
var sql = #"SELECT * FROM Collections WHERE id = #id";
using (var connection = new SqlConnection(ConnectionString))
{
var collection = connection.Query<Collection>(sql, new { id = id }).First();
return collection;
}
}
and here's the helper method:
public static void AddCollections(List<Collection> collections, string connectionString)
{
using (var db = new DataClassesDataContext(connectionString))
{
db.Collections.InsertAllOnSubmit(collections);
db.SubmitChanges();
}
}
(Note that I'm using Dapper as the micro-ORM in the controller method and so, to avoid potentially duplicating errors in the test, I'm using LINQ to SQL instead in the test to set-up and clean-up test data.)
There are also database calls in the unit test's class's constructor and Dispose method. I can add them to the post if needed.
OK, so looks like a plain vanilla case of deadlocks in your app and the need to handle that - what is your plan on the app side?
The tests and their data rigging can potentially fall prey to the same thing. xUnit doesnt have anything to address this and I'd strongly argue it shouldnt.
So in both the test and the app, you need failure/retry management.
For a web app, you have a fire them a picture of a whale and let them try again pattern but ultimately you want a real solution.
For a test, you don't want whales and definitely want to handle it, i.e. not be brittle.
I'd be using Poly to wrap retry decoration around anything in either the app or the tests that's prone to significant failures -- your exercise is to figure out what are the significant failures in your context.
Under normal circumstances a database with a single reader/writer operating synchronously shouldn't deadlock. Analysing why it happens is a matter of doing the analysis on the DB side. The tools that side would also likely quickly reveal to you if e.g. you have some aspect of your overall System Under Test which is resulting in competing work.
(Obviously your snippets are incomplete as there is a disconnect between CollectionsController.Get(testCollection.Id) and the fact that the controller method is not static - the point of this discussion should not be down at that level IMO though)

swing uncaughtexceptionhandler

I am trying to build a general exception handler for a swing application as described here: http://www.javaspecialists.eu/archive/Issue081.html
I work in jython (python syntax getting compiled to java and executed). My code looks roughly like this (updated):
def launcher(func):
class launcherThread(Runnable):
def __init__(self):
super(launcherThread, self).__init__()
def run(self):
func()
#trying to get the name which can be used to instantiate this in java
cls = ExceptionGroup().getClass()
fullName = cls.__module__ + '.' + cls.__name__
System.setProperty("sun.awt.exception.handler", fullName)
Thread(ExceptionGroup(), launcherThread(), 'Cross ExceptionHandlerThread').start()
class ExceptionGroup(ThreadGroup):
def __init__(self):
super(ExceptionGroup, self).__init__("HardenedGroup")
def uncaughtException(self, thread, exception):
#make a fancy dialog displaying str(exception)
If I test it it works fine however in the production enviornment it failes.
For testing I launch my program in Eclipse (PyDev), the production enviornment is a third party application written in Java, that has a Jython console build in. The application supports adding of custom menu entries, and putting jython scripts on these.
The main difference I see between testing and production enviornment is that in the production enviornment the swing threads are allready started (the third party application utilitizes swing). Does this cause my ThreadGroup setting to fail, or is there another reason why this is not working?
How can I get the Involved threads (exceptions ar thrown as a result of buttonActions) to check their defaultException handlers? If (as I am afraid) it should turn out that the third party installed its own handler (all exceptions are written to a log file) how can I make a new swing worker thread? (I don't want to catch the exceptions created by the host application after all)
Question recap:
1. How can I check which threads are started for the function func passed into the launcher function and see thier uncaught exception handler?
2. Can I enforce a seperate swing dispatcher for my gui part and the main applications gui part? (If I exitOnClos on a frame of my add in, the third party application closes)?
Update:
Considering the anwser from lbalazscs I am trying to use the sun.awt.exception.handler property, but it has no effect, the exceptions still end up in the log file (applications dfeault behaviour). Am I using it right? (p.s.: I am on Java 1.6)
If you have Java 5 or higher, you can also use Thread.setDefaultUncaughtExceptionHandler(), which is also described in a newer "Java Specialists' Newsletter":
http://www.javaspecialists.eu/archive/Issue089.html
And here is the newest Java 7 version:
http://www.javaspecialists.eu/archive/Issue196.html
Also see this:
Why bother with setting the "sun.awt.exception.handler" property?
EDIT: This is how I use Thread.setDefaultUncaughtExceptionHandler (in Java...):
public static void setupGlobalExceptionHandling() {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
handleException(e);
}
});
}

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.