How to Debug Window Service Method without attach process - windows

How to debug Window service methods without attach process .

#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new BirthdayService()
};
ServiceBase.Run(ServicesToRun)`#else
// Debug code: this allows the process to run as a non-service.
// It will kick off the service start point, but never kill it.
// Shut down the debugger to exit
BirthdayService service = new BirthdayService();
service.InitializeUsersTable();
service.GetUserAndSendMail();
// Put a breakpoint on the following line to always catch
// your service when it has finished its work
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif

Related

Timer event in web api

I have created a timer event try to running in the background of my web api, I found it works fine when I debugger on local dev machine. However, The timer does not work when I added them to IIS on server. It stops after the first web request finishes( I tested it by writing some text into log files, it seems stopped after a few triggers, once the web request completed)
Here is some example code.
void refreshTimeStart()
{
refreshTimer = new System.Timers.Timer(Convert.ToInt32(ConfigurationManager.AppSettings["TIMER_INTERVAL"]));
refreshTimer.Elapsed += new ElapsedEventHandler(connectionResetEvent);
refreshTimer.AutoReset = true;
refreshTimer.Enabled = true;
}
void connectionResetEvent(object source, ElapsedEventArgs e)
{
testIndex = testIndex + 1;
WriteToFile(testIndex);
}
static void WriteToFile(int i)
{
string text = "This start trigged. ";
System.IO.File.WriteAllText(#"C:\Projects\abc" + i.ToString() + ".txt", text);
}
Any idea of how to achieve this? Thanks a lot.
The question was asked a long time ago but here's an answer anyway.
First of all, using a timer in a Web API is probably not the best idea. A windows service would be more appropriate. That being said, your problem must come from two issues:
a Web API awaits a request and only initializes after the first request. So you'll have to initiate a request for your timer to start.
the default settings of application pools in IIS have a timeout. So even if you initialize the Web API, the application pool will terminate after the timeout period has elapsed. You could disable the timeout.

Do Events causing exception how to trace

I have a code where Application.DoEvents is causing problems and throwing exceptions. When a modal popup is opened and application has to wait for user activity , this code is written to execute in a loop to process background tasks until user's activity . Can someone tell me how can I trace (in debugging) what process is called from DoEvents which causes exception .
Here is some of the code . Can I trace what happens inside DoEvents :
private readonly AutoResetEvent Event = new AutoResetEvent(false);
while (_Event .WaitOne(20, false) == false)
{
Application.DoEvents();
Thread.Sleep(0);
}

How can I add customized strings to the messages displayed by shutdown screen in Windows 7?

How can I add custom text to shutdown screen, like those messages that show when Windows is installing updates before shutting down? For example, you have a backup script that is executed on shutdown, and you want to inform about the progress of the backup just like Windows does when installing updates. Is there any command line tool for that, or some code library, or even something in Windows API?
Note that this is not about how to shutdown a computer, and it is not about whatever way to display a message there in shutdown screen, such as console applications or message boxes. This is not about customizing existing messages either, and it is not about any shutdown dialog that shows before shutdown screen and allows the user to cancel the shutdown or proceed without waiting for the programs to terminate.
This is about understanding how Windows implements the displaying of those messages the way they are displayed there in shutdown, and how to add new messages to be displayed, preferably with progress information. To be clear, below is a screenshot.
There is a function WmsgPostNotifyMessage in wmsgapi.dll which is displaying this message. Undocumented though, but shouldn't be a problem to use.
Here is a C++ code that can shutdown the computer with message.
#include <windows.h>
#pragma comment( lib, "advapi32.lib" )
BOOL MySystemShutdown( LPTSTR lpMsg )
{
HANDLE hToken; // handle to process token
TOKEN_PRIVILEGES tkp; // pointer to token structure
BOOL fResult; // system shutdown flag
// Get the current process token handle so we can get shutdown
// privilege.
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return FALSE;
// Get the LUID for shutdown privilege.
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
&tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Get shutdown privilege for this process.
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES) NULL, 0);
// Cannot test the return value of AdjustTokenPrivileges.
if (GetLastError() != ERROR_SUCCESS)
return FALSE;
// Display the shutdown dialog box and start the countdown.
fResult = InitiateSystemShutdown(
NULL, // shut down local computer
lpMsg, // message for user
30, // time-out period, in seconds
FALSE, // ask user to close apps
TRUE); // reboot after shutdown
if (!fResult)
return FALSE;
// Disable shutdown privilege.
tkp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES) NULL, 0);
return TRUE;
}

wp7 background process during application runs

I have a project which includes many pages. I want to import information to my database periodically whatever the situation of my application is.
I tried to put my code inside App.xaml.cs but it is only saves data for once (I put it inside launching and tried in Constructor. My method is getting device id's location which is like
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
Location loc = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
//Send Data to Database
dclient.CreateUserLocationCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(dclient_CreateUserLocationCompleted);
dclient.CreateUserLocationAsync(1, loc.Latitude, loc.Longitude);
}
and my watcher position changed is inside the constructor.
if (watcher == null)
{
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
}
MovementThreshold = getSelectedDeviceLocationFrequencyFromInternalFolder();
watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
watcher.Start();
and defined globally inside the App.xaml.cs
How can I run this periodically all the time while program runs ? Any other way ? Thanks (To sum up I want to insert the location data periodically to my database.)
You will need to launch a thread when the app launches that sleeps for whatever time it wants to (or wake up on a signal from the app - when the new value is received) and writes the data to your data store inside it.

Background agent task is never executed in Mango

I have a background agent that i would like to be executed in Mango for updating the live tile.
The problem is that it is never executed.
Here is the code that i used:
//start background agent
PeriodicTask periodicTask = new PeriodicTask("BruceWpAgent");
periodicTask.Description = "BruceWp periodic live task";
periodicTask.ExpirationTime = System.DateTime.Now.AddDays(10);
// If the agent is already registered with the system,
if (ScheduledActionService.Find(periodicTask.Name) != null)
{
ScheduledActionService.Remove("BruceWpAgent");
}
ScheduledActionService.Add(periodicTask);
I've found my app name between that Apps that use background jobs but the task is never invoked.
What am i doing wrong?
This code may help you..
string periodicTaskName = "PeriodicAgent";
public bool agentsAreEnabled = true;
private void StartBackgroundAgent()
{
// Variable for tracking enabled status of background agents for this app.
agentsAreEnabled = true;
// Obtain a reference to the period task, if one exists
periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
// If the task already exists and background agents are enabled for the
// application, you must remove the task and then add it again to update
// the schedule
if (periodicTask != null)
{
RemoveAgent(periodicTaskName);
}
periodicTask = new PeriodicTask(periodicTaskName);
// The description is required for periodic agents. This is the string that the user
// will see in the background services Settings page on the device.
periodicTask.Description = "Task to update the Economic times tile.";
// Place the call to Add in a try block in case the user has disabled agents
try
{
ScheduledActionService.Add(periodicTask);
// If debugging is enabled, use LaunchForTest to launch the agent in one minute.
ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromMinutes(2));
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
agentsAreEnabled = false;
}
}
}
Check out this hands on lab for Adding Multitasking to Your Application in Windows Phone 7.5, that should cover it.

Resources