I have developed an application in C# which uses the time of the system. My problem is that if someone changes the time of the system, it affects the application also. The application would then show data of that changed time and not the current time.
How do i avoid this? Is there any other way to get a single universal time?
You can use NTP to ask to an authoritative time server what time it is, for example. If you google for NTP client C# you'll find plenty of examples.
If time is so critical, keep anything that is dependent on the time isolated on the server. Move the actual processing to the server, and just display the result on the client.
Related
I'm creating in-memory local cache of a network filesystem.
I want every directory/file to have LastDownloadedTime attribute, and then compare it with current time to decide whether the directory/file is too old to be used from cache.
But I'm uncertain whether DateTime.Now() is what I need. What happens if the user changes system time? How can simestamps suitable for my task be obtained in .NET?
Take a look at System.DateTime.UTCNow(). It'll return the UTC time. Just make sure you are consistently calling on both ends (when you store the cache as well as when you test it for expiration).
More info: https://msdn.microsoft.com/en-us/library/system.datetime.utcnow(v=vs.110).aspx
You should use DateTimeOffset. According to the docs:
Uniquely and unambiguously identify a single point in time. The DateTimeOffset type can be used to unambiguously define the meaning of "now", to log transaction times, to log the times of system or application events, and to record file creation and modification times.
If your application is running on a user's machine, though, they could change their system time (as you mentioned). The only way to prevent that is to have your application ping a time server to get an authoritative timestamp.
I think I'm going to use Stopwatch for timestamps, because my filesystem cache is in-memory, it does not survive system reboot. Timestamps are going to be relative to the start of the Stopwatch.
Though, Stopwatch is known to be buggy.
But I consider system clock-dependent solutions to be even more dangerous, as the user may set system clock to some date in the past, messing everything up.
If you are staying within bounds of local server then DateTime.UtcNow is the most convenient option for the task. Yes, if user changes local time, then that will invalidate cache and trigger unnecessary update.
You will need to use NTP (time) servers to avoid that problem. So, instead of using local server UTC time, you will obtain UTC time from NTP server (there are plenty of them available around the world).
Please refer to NTP wikipedia article
I am developing a windows application using C# and SQL and i want to store the time of some specific events in the db , i tried using the C# Datetime class but when i change my windows local time it does not give me the real date and then i thought maybe SQL has it's own date system,i searched but nothing comes up so what is the best way to have a secure time system? which the user can not easily manipulate the time that is storing in the data base?
Usually users cannot change the system time without administrator privileges. If your code is running on a untrusted machine where the user is admin, then you need another source of time. (Admittedly, your whole program can be compromised but this is another topic).
You can query MSSQL for current time as described here
SELECT CURRENT_TIMESTAMP
GO
SELECT {fn NOW()}
GO
SELECT GETDATE()
GO
Another way would be to query a NTP server somewhere else on the internet. This requires network programming. There is this SO question about it here
If you don't trust your workstation or the server time you can get the time from a NTP server and if that's not available still fall back to the local clock. An short example how to get the current time from an NTP server can be found here https://stackoverflow.com/a/12150289/2360972
I am actually very late for this answer.
I also had done lots of search for this answer & finally I got the best solution for this.
UTC is thestandard format to store your datatime in your application.
What is UTC?
UTC, or Coordinated Universal Time, is the standard international time that all time zones are expressed as offsets of. UTC does not get adjusted for daylight savings. To compute local time from UTC, simply add the time zone offset and then add an additional hour if daylight savings time is in effect.
Please Refer this link Your all doubts will get clear after refering this :
Click To refer
UTC time will always take server datetime & will not take your system datetime.
Also, If your application is running on different country then there is only one way to remove conflict between Time is to use UTC
This is very good Example for time related Issues :
Click Here
I'm trying to create a website similar to BidCactus and LanceLivre.
The specific part I'm having trouble with is the seconds aspect of the timer.
When an auction starts, a timer of 15 seconds starts counting down, and every time a person bids, the timer is reset and the price of the item is increased by 0,01$.
I've tried using SignalR for this bit, and while it does work well during trials runs in the office, it's just not good enough for real world usage where seconds count. I would get HTTP 503 errors when too many users were bidding and idling on the site.
How can I make the timer on the clients end shows the correct remaining time?
Would HTTP GETting that information with AJAX every second allow me to properly display the missing time? That's a request each second!
And not only that, but when a user requests that GET, I calculate remaining seconds, but until the user see's that response, that time is no longer useful as a second or more might pass between processing and returning. Do you see my conundrum?
Any suggestions on how to approach this problem?
There are a couple problems with the solution you described:
It is extremely wasteful. There is already a fairly high accuracy clock built into every computer on the Internet.
The Internet always has latency. By the time the packet reaches the client, it will be old.
The Internet is a variable-latency network, so the time update packets you get could be as high or higher than one second behind for one packet, and as low as 20ms behind for another packet.
It takes complicated algorithms to deal with #2 and #3.
If you actually need second-level accuracy
There is existing Internet-standard software that solves it - the Network Time Protocol.
Use a real NTP client (not the one built into Windows - it only guarantees it will be accurate to within a couple seconds) to synchronize your server with national standard NTP servers, and build a real NTP client into your application. Sync the time on your server regularly, and sync the time on the client regularly (possibly each time they log in/connect? Maybe every hour?). Then simply use the system clock for time calculations.
Don't try to sync the client's system time - they may not have access to do so, and certainly not from the browser. Instead, you can get a reference time relative to the system time, and simply add the difference as an offset on client-side calculations.
If you don't actually need second-level accuracy
You might not really need to guarantee accuracy to within a second.
If you make this decision, you can simplify things a bit. Simply transmit a relative finish time to the client for each auction, rather than an absolute time. Re-request it on the client side every so often (e.g. every minute). Their global system time may be out of sync, but the second-hand on their clock should pretty accurately tick down seconds.
If you want to make this a little more slick, you could try to determine the (relative) latency for each call to the server. Keep track of how much time has passed between calls to the server, and the time-left value from the previous call. Compare them. Then, calculate whichever is smaller, and base your new time off that calculation.
I'd be careful when engineering such a solution, though. If you get the calculations wrong, or are dealing with inaccurate system clocks, you could break your whole syncing model, or unintentionally cause the client to prefer the higest latency call. Make sure you account for all cases if you write the "slick" version of this code :)
One way to get really good real-time communication is to open a connection from the browser to a special tcp/ip socket server that you write on the server. This is how a lot of chat packages on the web work.
Duplex sockets allow you to push data both directions. Because the connection is already open, you can send quite a bit of very fast data across.
In the past, you needed to use Adobe Flash to accomplish this. I'm not sure if browsers have advanced enough to handle this without a plugin (eg, websockets?)
Another approach worth looking at is long polling. In concept, a connection is made to the server that just doesn't die, and it gives you the opportunity on the server to trickle bits of realtime data down to the clients.
Just some pointers. I have written web software using JavaScript <-> Flash <-> Python/PHP, and was please with how it worked.
Good luck.
I'm developing an application and I need to make a demo version of it that will expire in lets say 30 days.
My idea for now is to store the current time when the application is first started in a simple txt file stored in the projects resource (so it doesen't have to be written on the hard disk or the registry), and every time the program is started check if 30 days have passed.
But, what if the user resets the time to an earlyer state?
Then my app would still start becouse now the "current date" can be 1 day after the "first start"..
Is there any way I can get some info along with the first date (or, insted of) that would assure that specific time that the application is first started?
Thank you for your time.
One of the option is to check the date time from some external server and not from local system. But this is also possible to crack as the user can put a proxy in between which will act as the external server to your app and this proxy can send any time the user want. In case you want the solution for novice users, external server approach is fine, but any smart user can still crack the application. Remember, any code that runs on a client machine can be cracked, you just need to flip the correct bit in the application code :)
I have a simple check in the code of one of my programs when in beta. It pretty much does what you say. In the initial code is a hard coded date. The logic then just tests to see if the current date is earlier than the hard coded date. Pretty primitive and it relies on the users system date. However once it is past the program will not run unless the system date is changed. As I mention I use this for betas not for my production programs that have an evaluation period. For that I use Infralution License Tracker. This is payware but it does allow the setting of evaluation periods and also the actual licensing of the code.
Interesting question - how about encoding the initial datetime somehow - base64 or even encryption of somekind), then also storing the datetime each time your application is run.
That way you can detect inconsistencies by checking each datetime and if there's funny business going on (eg. todays date is older than the last date) you can shut the user out.
How do I send email on daily, weekly and monthly bases using c#.net?
I was thinking of creating a windows service application but I don't know how to do it and if it's the right way to take.
Your thoughts are greatly appreciated.
A windows service is probably the best option.
In your service have a timer that fires with whatever resolution you need (every minute/hour/day etc) and on the timer tick even send your emails.
There are many tutorials for creating windows services with .NET.
A Windows service will do the trick. A good benefit of a Windows service is that it starts up when Windows starts up (or can be set to, anyway). So the machine can be left fairly unattended (as a good server should) and doesn't need anybody logged into it for the service to run. So if that's an important consideration for your scenario then perhaps a Windows service would be the way to go.
If you just want to create a console application instead (which can generally be easier to create/test/debug) then you can schedule it with the native Windows task scheduler. However, unless I'm mistaken, I think a user needs to be logged in to the machine in order for it to run. At least under certain circumstances. So a Windows service is probably your best bet for an unattended task.
As for creating the service, Visual Studio should have a project template for that. The scheduling would be handled with a Timer.
You could also use the Windows Task Scheduler. Quartz.Net seems to be the right tool, too (never used it though).
Windows Service is a good choice.
Remember to save state to disk (file or database) because service restart (for example, due to a reboot) is possible. For example, your next email delivery is a week in the future, you have to save that date to disk. So when your server is down due to a power failure 3 days later and recover after another day, your Windows Service can still set the right timer according to the date saved to disk.
Create a console application, which would be launched from the Windows task scheduler. Creating a windows service is unnecessarily complex, IMO, since you are simply having the program execute in response to time intervals; not other unpredictable external events where you would need a 'listener' type application. KISS!