Ok so I have an area where people can create OpenHouse listings for a period of 14 days then the listing is expired and should be deleted, my question is; is there some type of way to have the Database delete listings automatically? This is the simple code I have below it works but it is not optimal
protected void Application_Start()
{
openhouse mydate= new openhouse();
if (mydate.expired > DateTime.Now)
{
db.openhouses.Remove(mydate);
}
}
That as you can tell is in my Global.asax but the issue is that listings only get deleted if I Compile the application I am thinking there must be a more efficient way to do this than me compiling every day just for that, any suggestions would be very appreciated ...
The database itself won't provide any timers or scheduled tasks for you (at least SQLLite won't). You have to program a task that cleans up expired listings, for that, you have several options:
Using a task scheduled within your own ASP.net application
Using a task (a separate application) scheduled and managed by your hosting provider. If you are on the cloud, your cloud provider most likely has the capability to do this for you.
If you want to go with the first option, take a look at Quartz. I have a WorkerRole on Azure than uses Quartz to do things like what you need here. It's fairly simple to setup, here is an example:
// Initialize Quartz
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
_scheduler = schedulerFactory.GetScheduler();
_scheduler.JobFactory = new NinjectJobFactory(_kernel);
DateTimeOffset morning = DateBuilder.NewDateInTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))
.AtHourMinuteAndSecond(5, 30, 0)
.Build();
// Schedule task for email being sent to people who have not signed up after their trial expiry
IJobDetail userFeedbackJobDetail = JobBuilder.Create<LostUserFeedbackRequestJob>().WithIdentity("User Feedback Emails").Build();
ITrigger dailyTriggerForUserFeedback = TriggerBuilder.Create()
.WithIdentity("Daily Trigger (User Feedback)")
.StartAt(morning)
.WithSimpleSchedule(schedule => schedule.WithInterval(TimeSpan.FromDays(1)).RepeatForever())
.ForJob(userFeedbackJobDetail)
.Build();
_scheduler.ScheduleJob(userFeedbackJobDetail, dailyTriggerForUserFeedback);
// Finally, start the scheduler
_scheduler.Start();
This sends an email everyday asking for feedback from users who have not elected to use the services of one of my projects after their trial period has finished. The job is run everyday at 5:30 a.m.
Related
The main objective is to guarantee the reliability of the message delivery of our integration events in case of failures with the Application or DB, and in this scenario the new Transactional Outbox seems to be the most indicated.
With the MT Transactional Outbox, the writing (publishing) of our integration events happens atomically in the Commit of our Command Handlers.
Our solution is built as microservices that use one DB per tenant. However, the applications are shared and the DB (connection string) selection is built into the request scope.
The Outbox MT tables (OutboxMessage, In/OutboxState) are created in each tenant DB and with that we have the atomic writing of the operation along the triggering of integration events.
The problem is in the delivery to the Bus. How to make the MT background services (DeliveryService and InboxCleanupService) reach the outbox in the tenant DB, since there is no request to identify the tenant in advance?
It wouldn't be a problem if the application also runs in an environment for each tenant with their respective configuration / connection string, but that's not the case.
An alternative would be to create a third application dedicated only to running delivery/cleanup services for all tenants in separate tasks.
But to use MT delivery, we would have to dynamically create a DbContext instance (with only the Mappings for MT) for each tenant at startup. I don't know if this is the best way and it also doesn't seem possible to use the MassTransit configuration API this way.
Does anyone have an advice, approach or guide that could help us?
We were having exactly the same issue as you are describing, and we've ended up with the solution you are essentially describing yourself, a separate service that does nothing but outbox delivery and inbox cleanup.
For every MassTransit endpoint, we disable both outbox delivery and inbox cleanup
mt.AddEntityFrameworkOutbox<ContextWithOutboxTables>(outbox =>
{
var outboxConfig = outbox.UseSqlServer();
outboxConfig.DisableInboxCleanupService();
outboxConfig.UseBusOutbox(busOutbox =>
{
busOutbox.DisableDeliveryService();
});
}
and the separate service is configured similar to the below (with some code replaced/removed)
builder.ConfigureServices(s =>
{
foreach (var connectionString in distinctTenantConnectionStrings)
{
IServiceCollection outboxServices = new ServiceCollection();
outboxServices.AddDbContext<ContextWithOutboxTables>(options =>
{
options.UseSqlServer(connectionString);
});
var outboxContainer = outboxServices.BuildServiceProvider();
s.AddSingleton<IHostedService>(container =>
{
return new BusOutboxDeliveryService<ContextWithOutboxTables>(
container.GetRequiredService<IBusControl>(),
new OptionsWrapper<OutboxDeliveryServiceOptions>(new OutboxDeliveryServiceOptions()
{
// tweak your options here
}),
new OptionsWrapper<EntityFrameworkOutboxOptions>(new EntityFrameworkOutboxOptions()
{
LockStatementProvider = new SqlServerLockStatementProvider(),
// tweak your options here
}),
logger,
outboxContainer);
});
s.AddSingleton<IHostedService>(container =>
new InboxCleanupService<ContextWithOutboxTables>(new OptionsWrapper<InboxCleanupServiceOptions>(
new InboxCleanupServiceOptions()
{
// tweak your options here
}),
logger,
outboxContainer)
);
}
});
It is necessary to register the hosted service using the AddSingleton<IHostedService> override instead of AddHostedService because MS dependency injection eliminates duplicate service implementations under the covers, which is not the behavior you want, you ARE actually registering the same hosted service multiple times, with different configuration.
Creating a separate container via
IServiceCollection outboxServices = new ServiceCollection();
is necessary due to MT resolving the data context from the container, and you need it to provide a differently configured data context (connection string) for each instance of the hosted service.
I'm trying to find out how to keep an Android service running after the starting app is closed. I've tried looking at samples for background services (e.g this one, and some on the Xamarin site) but in every case the service stops running if the minimised app is 'swiped' off the screen. I don't want the service to accidently stop like this, it should run continually until a confirmed stop is requested. The service does not consume much in the way of resources, just gets a GPS location and posts it to a website every 2 minutes.
By way of background, I am a newbie to Xamarin/Android, but have in the past created several successful services in Windows with C#
(Later)
One sample I tried did leave an item in the Settings list of running apps, but didn't actually perform any service tasks once swiped off the screen. Additionally there was no icon in the status bar. After doing some reading it seems that my androidmanifest file is missing a 'service' attribute (although none of the samples I tried have this); what I have now tried is this
<service
android:name=".LocationService"
android:icon="#drawable/icon"
android:label="#string/service_name"
>
<intent-filter>
<action android:name="android.service.LocationService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
...but still no luck.
Have you had a look at the Xamarin sample here the source is here
They create a service like so:
[Service]
public class SimpleService : Service
{
System.Threading.Timer _timer;
public override StartCommandResult OnStartCommand (Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug ("SimpleService", "SimpleService started");
DoStuff ();
return StartCommandResult.Sticky;
}
public override void OnDestroy ()
{
base.OnDestroy ();
_timer.Dispose ();
Log.Debug ("SimpleService", "SimpleService stopped");
}
public void DoStuff ()
{
_timer = new System.Threading.Timer ((o) => {
Log.Debug ("SimpleService", "hello from simple service");}
, null, 0, 4000);
}
public override Android.OS.IBinder OnBind (Android.Content.Intent intent)
{
throw new NotImplementedException ();
}
}
And start and stop it with this:
StartService (new Intent (this, typeof(SimpleService)));
StopService (new Intent (this, typeof(SimpleService)));
Also it sounds like you want a Sticky service Docs
When the system is under memory pressure, Android may stop any running services. The exceptions to this rule are services explicitly started in the foreground, which are discussed later in this article.
When a service is stopped by the system, Android will use the value returned from OnStartCommand to determine how or if the service should be restarted. This value is of type StartCommandResult, which can be any of the following:
Sticky – A sticky service will be restarted, and a null intent will be delivered to OnStartCommand at restart. Used when the service is continuously performing a long-running operation, such as updating a stock feed.
RedeliverIntent – The service is restarted, and the last intent that was delivered to OnStartCommand before the service was stopped by the system is redelivered. Used to continue a long-running command, such as the completion of a large file upload.
NotSticky – The service is not automatically restarted.
StickyCompatibility – Restart will behave like Sticky on API level 5 or greater, but will downgrade to pre-level 5 behavior on earlier versions.
Hope this helps.
Solved it now. The confusion was mainly due to many samples being out-of-date (using deprecated methods) and different suggestions for 'pure' Android projects and Xamarin ones. Certainly don't need to modify the androidmanifest file as I suggested above.
If anyone is trying to find something similar, my project is here.
Solving the initial issue has now raised some new questions, of course, but I will post separately about that if needed.
I am working on a .NET MVC3 C# Application. This application is hosted on our own Server.
Now I want to Send Scheduled Email in my application like daily(at a specific time),Weekly, monthly and so on...
Currently I am using MVCMailer to send Emails in my application.
I tried Fluent Scheduler to send scheduled Emails, but it doesn't works with MVCMailer. It Works fine if I send mails without MVCMailer and for other scheduling jobs.
It gives me a ERROR NULLReferenceException and says HTTPContext cannot be null.
What can I do to solve this problem.
Also suggest me which will be the best way to send E-mails in my applicaton.
Windows Service (Having own server)
Scheduler (Fluent Scheduler)
SQL Scheduled jobs
I am attaching ERROR snapshot:
It could be that MVCMailer depends on an HttpContext, which will not exist on your scheduled threadlocal's.
You could consider scrapping MvcMailer and implementing your own templating solution. Something like RazorEngine (https://github.com/Antaris/RazorEngine), which gives you the full power of Razor without having to run ontop on an Http stack. You could still source your templates from disk so that your designers could modify it.
Then you could mail the results using the standard classes available from .net.
For e.g.:
string template = File.ReadAllText(fileLocation);//"Hello #Model.Name, welcome to RazorEngine!";
string emailBody = Razor.Parse(template, new { Name = "World" });
SmtpClient client = new SmtpClient();
client.Host = "mail.yourserver.com";
MailMessage mm = new MailMessage();
mm.Sender = new MailAddress("foo#bar.com", "Foo Bar");
mm.From = new MailAddress("foo#bar.com", "Foo Bar");
mm.To.Add = new MailAddress("foo#bar.com", "Foo Bar");
mm.Subject = "Test";
mm.Body = emailBody;
mm.IsBodyHtml = true;
client.Send(mm);
Obviously you could clean this all up. But it wouldn't take to much effort to use the above code and create some reusable classes. :)
Since you already have the FluentScheduler code set up, you may as well stick with that I guess. A windows service does also sound appealing, however I think that it's your call to make. If it's a simple mail service you are after I can't think of any reason not to do it via FluentScheduler.
I have created a full example of this available here: https://bitbucket.org/acleancoder/razorengine-email-example/src/dfee804d526ef3cd17fb448970fbbe33f4e4bb79?at=default
You can download the website to run locally here: https://bitbucket.org/acleancoder/razorengine-email-example/downloads
Just make sure to change the Default.aspx.cs file to have your correct mail server details.
Hope this helps.
Since MVC Mailer works best in the HTTP stack (i.e. from controllers), I've found that a very reliable way to accomplish this is by using Windows Task Schedule from a server somewhere. You could even spin up a micro instance on Amazon Web Server.
Use "curl" to call the URL of your controller that does the work and sends the emails.
Just setup a Scheduled Task (or Cron if you want to use *IX) to call "c:\path_to_curl\curl.exe http://yourserver.com/your_controller/your_action".
You could even spin up a *IX server on AWS to make it even cheaper.
Besides polling, how can I tell when a long-running Amazon EC2 operation is complete? For example, using the CreateImage API function can take upwards of several minutes.
Right now I'm doing this:
// MAKE THE API CALL
var createRequest = new CreateImageRequest().WithInstanceId("i-123456").WithName("MyNewAMI");
var createResponse = myAmazonEC2Client.CreateImage(createRequest);
var imageId = createResponse.CreateImageResult.ImageId;
// ICKY POLLING CODE
bool isImaging = true;
while (isImaging)
{
var describeRequest = new DescribeImagesRequest().WithImageId(imageId);
var describeResponse = myAmazonEC2Client.DescribeImages(describeRequest);
isImaging = describeResponse.DescribeImagesResult.Image.Single().ImageState == "pending";
Thread.Sleep(10000); // sleep for 10 seconds
}
// CreateImage IS COMPLETE; MOVE ON WITH OUR WORK
I hate this. After calling CreateImage, I'd like to just get notified somehow that it's all done and move on. Is this possible? I'm using the AWS .NET SDK in this example, but I'm not looking specifically for a C# solution.
UPDATE: Cross-posted to the AWS Forums
Some events in amazon can be configured to send notifications to an SNS Topic. For example when using auto scaling you can have notifications when a server is launched and terminated. As far as I know there is no way to trigger these notifications for other services such as CreateImage. I've looked for this type of feature in the past with no luck. I was trying to do it to create a script that would launch servers in a specific order. I wound up just polling their API as I couldn't find any way to register to those events.
James Hunter Ross answered this question over on the AWS Forums as follows:
Polling is it. That said, since you have a C# program started, why not let it spawn a polling process that notifies you as you wish? It seems you are almost done, in some respects.
(Of course, it would be nice if such functionality was built-in at AWS.)
I wasn't able to find a StackOverflow profile for him, but if he shows up I'll edit this to give him credit.
Does someone know how we can have Starteam send email notifications when a check in occurs? We are using Starteam 2006 R2.
Unfortunately StarTeam doesn't offer the ability to execute post-checkin actions. You may be able to use an application like Cruise Control to monitor your repository for changes and then take action upon seeing them.
I had a similar need a few months ago, this is what I discovered:
Starteam does not have commit hooks but it does have Starteam MPX (borland.com). From that link,
StarTeamMPX is a framework for publish/subscribe messaging. The StarTeamMPX Server uses an advanced caching and communication technology that both improves the performance of StarTeam clients and extends the scalability of the StarTeam Server.
Ok, so, we can subscribe to events. It's looking promising.
There is a Java API (borland.com) for Starteam, create an app using this API with your own emailing implemention of the CheckinListener interface. The app will then have to connect to Starteam, find any views that you're interested in and register listeners against them. And then wait.
Your listener will receive CheckinEvents and can interrogate these. Unfortunately, it appears to be on a file by file basis. I couldn't see anything in the API to say "commit finished", only "file finished". You are able to discover if a commit was cancelled. I don't know how easy it is to combine file checkin events back into a complete check in event.
*StarteamMPX is an extension (paid) to Starteam, it is available for 2006 R2. All of this is clearly only applicable if it is enabled.
My Experience:
My company didn't have that extension enabled, and to enable it required upgrading i.e. more money. So it didn't happen (I think it's painful enough paying for Starteam to begin with). At this point I abandoned my research and none of the above was ever implemented this. I hope this is some use to someone.
I've been doing some homework into this topic too, so will share what I've learnt.
MicroFocus now offer a Notification Agent tool for this sort of thing:
http://www.youtube.com/watch?v=QTKAT-ufkIs
It's an extra you pay for though.
I've been also pondering how to "roll-your-own" via advice given in Dan's post above. Yes, MPX does seem to be the way to go, although after studying the CheckinListener, this isn't the class you're after. To clarify, CheckinListener is used by the client performing the check-in, so that it can monitor progress of the check-in (perhaps to display a progress bar, that sort of thing).
Here's some sample-code of what listening to MPX events looks like:
Server s = new Server(strAddress, nPort);
s.connect();
s.enableMPX(); // must do this for MPX support
s.logOn(strUsername, strPassword);
Project p = s.findProject("mylovelyproject");
View v = p.s.findView("mylovelyview");
ItemListener listener = new ItemListener()
{
public void itemAdded(ItemEvent e)
{
System.out.println("itemAdd() - " + e.getNewItem().getComment());
}
public void itemMoved(ItemEvent e)
{
System.out.println("itemMoved() - from: " + e.getOldItem().getParentFolderHierarchy() + ", to: " + e.getNewItem().getParentFolderHierarchy());
}
public void itemChanged(ItemEvent e)
{
System.out.println("itemChanged() - " + e.getNewItem().getComment());
System.out.println(" - from: v" + e.getOldItem().getDotNotation().toString());
System.out.println(" - to: v" + e.getNewItem().getDotNotation().toString());
User locker = e.getNewItem().getLocker();
if (locker != null)
System.out.println(" - locked by:" + locker.getDisplayName());
else
System.out.println(" - not locked");
}
public void itemRemoved(ItemEvent e)
{
System.out.println("itemRemoved() - " + e.toString());
}
};
v.addItemListener(listener, s.getTypes().FILE);
The MPX-related items to focus on here are new ItemListener() (what to do about the events you listen to) and v.addItemListener() (which starteam view you want to listen to).
The sample code will spit out various print output to the console as files in your view are added/modified/moved/deleted.
Apart from ItemListener, you also have ViewListener and ProjectListener. Each interface provides a different scope of events to listen for, more info on this in the sdk docs, also a nice article here:
http://conferences.embarcadero.com/article/32231#MPXEventHandling
So if you want to roll-your-own notification emails, these MPX events provide part of your answer (a way to listen to these change-events).
Other aspects you'll need to look into after this are:
How to allow users to subscribe to various servers/projects/views, to decide what they want to listen to.
How to email to the user what they want (StarTeam's Server class offers a .SendMail() method, which can help here).
Once all these bases are covered, you should have something that does the trick. I'll be working on something like this myself over the coming days, I'll share what I can.