How to put your PC in sleep or hibernate via C#
I thought that is impossible to put your PC in sleep or hibernate via C#. I found that is incorrect! Moreover, that is very simple too, just one line of command.
Putting the PC in sleep mode
Code
Application.SetSuspendState(PowerState.Suspend, false, false); |
Putting the PC in Hibernate mode
Code
Application.SetSuspendState(PowerState.Hibernate, false, false); |
That is so simple!!!
Windows Service Tutorial 1
This tutorial is to build a simple Windows Services.
1. Create a Windows Service Project, File->New->Project
2. Please add these codes into Services1.cs
Code
protected override void OnStart(string[] args) | |
{ | |
EventLog.WriteEntry("Example Start"); | |
System.Timers.Timer timer1 = new System.Timers.Timer(); | |
timer1.Enabled = true; | |
timer1.Interval = 60000; | |
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed); | |
timer1.Start(); | |
} | |
| |
void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) | |
{ | |
EventLog.WriteEntry("Timer Triggered:"+DateTime.Now.ToString()); | |
} | |
| |
protected override void OnStop() | |
{ | |
EventLog.WriteEntry("Example Stop"); | |
} |
Commons Library in C#
In the Java World, we have a set of library, Commons, from Apache. They provide a lot of cores functions such as email, logging and validations. In our .Net World, the open source community build a set of Commons Library. They provide a lot of cores functions, such as ORM, CSV Parser and validations. Those are different from the java version. Anyway, there are a strong set of functions. They are useful for building your own web framework. Such as, Logging and CSV Parser are essential functions for a web framework.
"Invalid attempt to call Read when reader is closed" in LINQ DataContext
I got a lot of error from a LINQ DataContext, such as "Invalid attempt to call Read when reader is closed" . That is because I was using a singleton for DataContext in a multi-threads.
The codes like that:
Code
private static ExampleDataContext Context; | |
private static ExampleDataContext GetContext() | |
{ | |
if(Context == null) | |
{ | |
Context = new ExampleDataContext(); | |
} | |
return Context; | |
} |
That is not very thread-safe. A thread will close the DataContext, but others threads are still using DataContext. Then it will throw the error above.
I changed the DataContext in a pre-thread. I initialize the DataContext in each thread. The errors are gone! You also can do the DataContext in a pre-object. That is simpler.
Mutex Lock Example
I have written an example project in C#. This example will shows how to use Mutex Lock. Moreover, it will demonstrate how to create a thread with parameters. Please click here to download.