I have a windows application in Dot-net which consists of various Analytics tests. When user select a particular test(Checkbox) and submit it (clicking the button) then at the back-end SQL query gets executed and user gets a result-set of that particular test.
Now a requirement is, user will select a particular test and will give a time-stamp (time at which test will run) to get the output at his email ID using auto scheduler (without any user intervention with application). Auto scheduler will get triggered at specified time and will run the specific selected tests.
How to implement Auto scheduler with Windows application? I am trying to create Windows service in Dot-net but issue is how this service get the instance of Windows application and how it will run the selected tests using scheduler approach?
As per my understanding, I can run only script file using scheduler hence how to achieve this auto-scheduling of these tests of Windows application in Dot-net.
You can use the Task Scheduler Managed Wrapper. Download it manually and reference from your project or install using nuget packages. The example source code and more information are to be found here: Creating Scheduled Tasks
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(#"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
Cheers,
Related
I need to start a windows forms application with admin rights whenever a domain user logs in.
I am trying to start the application with service and task scheduler but the application UI does not show up. However I can see it running in the task manager. and if I add a timer and terminate the app. it terminates after correct interval as well.
Can someone help me on how to develop/deploy an application so that it shows "the UI" when whenever any user logs in to the machine. should I add some registry entry that will start me application or is there any other way to achieve this..
It seems to me that when the user logs in, the task does not really work because there are not enough rights. Try it like this:
you need to create a new task that simply launches the program you want to use without UAC dialogs. When creating this task, in the General tab, enter the name of the task (remember this name, you will need it later) and check the box that says “Run with highest privileges - Run with highest privileges”. This puts the task to run with administrator rights.
To make sure there are no compatibility issues, go to the “Configure for” drop-down list at the bottom of the Create Task window and select Windows ® 7, Windows Server ™ 2008 R2.
On the Actions tab - Actions, you need to create an action that launches the program. Everything is very simple here: select the action “Start a program”, specify the path to the program that will be executed, and click OK.
Your last stop is on the Settings tab. Here you need to make sure that the checkbox “Allow task to be run on demand” is checked. Also, make sure that when the task is already running, another instance will not be started by choosing the option “Do not start a new instance”
The second step in this procedure is to create a shortcut that launches the task you just created, which in turn launches the program of your choice without the UAC line appearing.
An important difference when creating a shortcut to a task compared to a normal shortcut on the desktop is to enter schtasks / run / tn Task Name - Schtasks / run / tn “Task Name” (Task Name must be replaced with the actual task name) in the Item Location field. In this command, the / Run parameter simply performs a specific task, and / tn allows you to enter the name of the task you want to run.
Once the shortcut is created, if you click on it, it will work like the task you created, and this in turn launches the program specified with administrator rights, but without UAC.
Thus, you can create a task to run the created shortcut.
To check if user has logged in into a domain, you can use
System.Security.Principal.WindowsIdentity.GetCurrent.Name which gives you "domain\username".
and for starting your application once user logged in, you have to run your program at start up, try this link.
And to run your app at startup using group policy (recommended) try this.
I want to create some functions in ASP.NET Web API, which should be executed daily at specific time and do specific task like update statuses/Records/Generating Emails, SMS.
Should i create a TaskService in Code
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(#"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
or should i create a .bat file and create a new task in Task Scheduler.
As you have mentioned in the question, you need to do the specific tasks like update statuses/Records/Generating Emails, SMS etc.
So database access comes into the scenario and on the other hand, you will have to send emails and SMS's which may require third party libraries or other configuration setting access.
Thus, to do all this it will be better to go with code implementation via which you can maintain your changes and requirements well enough.
About the ".bat file and windows scheduler", you need to have great skills using the limited batch commands available to fulfill your requirement.
So, my suggestion is code, .exe and windows scheduler task.
Also, this should be a separate application, don't mix it up with Web API code. You can always create a new project in the web API solution with web API project and reuse whatever code is possible.
You should do this outside your web code. This is because your webapp should have no access to the task system or web service. By default IIS 7.5+ runs app's in their own limited user account (https://www.iis.net/learn/manage/configuring-security/application-pool-identities).
If you want to have a reliable tasks scheduling wherein you can apply time interval depend on your choice, I recommend [quartz]: https://www.quartz-scheduler.net/. Quartz allow to add/edit/delete/etc a scheduled task easily, manageable and no CPU overhead.
Moreover Quartz is an open source job scheduling system that can be used from smallest apps to large scale enterprise systems.
I recommend you to try Hangfire. It's free and you can use it for free in commercial app. Ducumentation you can find here.
tl;dr: How do I register a Background Task without having to run the app?
Long version:
I want to register a Background Task to run every time the user logs in using SystemTriggerType.UserPresent .
I've found information about registering the Task, but that is code that has to be executed. That would be fine if the Task only has to be executed after the app runs. But how do I register the Task without running the app?
A Background Task can be registered by
var builder = new BackgroundTaskBuilder();
and then
builder.Name = taskName;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
BackgroundTaskRegistration task = builder.Register();
As mentioned here:
Register a background task .
But as I said - my question is how to run this code before the app has ever been executed.
You can use the preInstalledConfigTask extension in your manifest. This task will be started after your application is installed.
Sometimes your application will need to update immediately after being
installed. This contract will enable you to immediately launch an
update task without any user interaction to make sure your application
is updated immediately.
Here is the full list of all the available extensions.
The preInstalledConfigtask can be set using the manifest editor:
<Extensions>
<Extension Category="windows.preInstalledConfigTask" EntryPoint="PreInstallTask.Task" />
</Extensions>
You will find the extension definition in the manifest schema
I have had the same question lately and what is missing in previous answers is that the Pre-Installed Configuration only triggers for OEMs & MOs. See here.
That being said, it might be impossible to do what you want, as the task never triggers unless you are not managing the OS and shipping the image + having the necessary rights in your developer center. See here.
I have an ASP .NET page which allows users to start programs. These programs and the parameter are stored in a database and a windows service then executes these programs.
The programs are dlls which implements my IPlugin interface, so I can add them at runtime (the dlls are loaded at runtime so I can add them at runtime without compiling or restarting the service).
I created the ASP .NET page, more than 10 programs (plugins) and the windows service. Everything is running fine, but I think the implementation of the windows service is bad.
The windows service periodically queries the database and executes the needed program if it gets a new entry. The service can run multiple programs in parallel (at the moment 3 programs).
Currently my service method looks like this:
while (Alive)
{
// gets all running processes from the database
Processes = Proc.GetRunningProcs();
// if there are less than 3 processes running and
// a process is in queue
if (ReadyToRun())
{
// get next program from queue, sets the status to
// runnig and update the entry in the database
Proc.ProcData proc = GetNextProc();
proc.Status = Proc.ProcStatus.Running;
Proc.Update(proc);
// create a new thread and execute the program
Thread t = new Thread(new ParameterizedThreadStart(ExecuteProc));
t.IsBackground = true;
t.Start(proc);
}
Thread.Sleep(1000);
}
I have a method that queries the database for entries with status 'Canceling' (if a user cancels a program, the status will be set to 'Canceling') and does a Thread.Abort().
Is there a better practice? Like using tasks with the cancel mechanism or is the whole concept (storing the processes in database (program name, parameter, status,... and querying this information periodically) wrong?
As an alternative you can use some existing libraries for your purposes like Quartz.NET http://www.quartz-scheduler.net/. It takes care about job persistence, job scheduling and many other things. All you must do to create an adapter and put it into Windows Service.
I'm working on an MVC .Net web application. I have a database in which i have a table called Tasks, every task is associated to one user and every task has a delay. I want to send emails automatically to the user to whom the task is associated before two days (for example) from its expiration date.
You can use Windows Service to send email automatically.
Please refer below link
http://www.dotnetfunda.com/articles/article931-how-to-send-mail-automatically-for-every-five-minutes-using-csharp.aspx
You can set the timer for 2 days with your logic.
You could write a Windows Service application or a Console application that will be scheduled to run at regular intervals using the Windows Scheduler (for example once a day), it will query your database, extract the records matching the required criteria and, yeah, SmtpClient.
The reason I am saying this is because this task should not be done by your web application. It should be performed by a separate application. Recurring background tasks such as the one you need to perform is a no-no in a web application. The Haacked discussed why this is a very bad idea: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx
Little mock up example:
DateTime today = DateTime.Now;
TimeSpan diff = user.Tasks.ExpirationDate.Subtract(today);
int dateDiff = Convert.ToInt32(diff.TotalDays);
if (dateDiff == 2)
{
//Send Email
}
You could then place this in a Services/Email folder in your mvc app and create a separate console app to request the page everyday, therefore running the query, e.g:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("YOUR PAGE");
string response = new System.IO.StreamReader(req.GetResponse()
.GetResponseStream()).ReadToEnd();
You would use Windows Task Scheduler to run the console app every day which would start the console app > console app requests page > page checks expiration date on tasks > sends emails