Faking time without changing Windows system clock - datetime

Does anybody know of a Windows tool to report fake dates/times to a process?
Apparently there are Linux programs that can be used to test how the software will react in the future / in a different timezone or to trigger scheduled tasks without actually modifying the system clock. Are there such programs for Windows?

RunAsDate can do this.

Starting about 2 years ago, I always abstract the call to DateTime.Now (C#) through a Utility class. This way I can always fake the date/time if I want to, or just pass it directly through to DateTime.Now.
Sounds similiar to what BillH suggested.
public class MyUtil
{
public static DateTime GetDateTime()
{
return DateTime.Now.AddHours(5);
//return DateTime.Now;
}
}

Wrapper your calls to the 'getCurrentDateTime()' system calls so you can introduce offsets or multipliers into the times your code reads during testing?

Related

Detecting an air-tap-and-hold with OnInputClicked method

I am writing a program that needs to detect the difference between a long air-tap-and-hold vs. a quick air tap. Currently, I am using the following code to detect quick airtaps:
#region IInputClickHandler
public void OnInputClicked(InputClickedEventData eventData)
{
// stuff being done is coded here
}
#endregion IInputClickHandler
which works well, but is there a similar code to detect long taps? Thanks in advance.
There are a number of ways of detecting a hold. For just a generic hold gesture, you can inherit and use the IHoldHandle interface. If you want to get an updated state, you should either use the IManipulationHandler or the INavigationHandler interface.
If you are testing in the editor, use the manipulation handler instead as you can't test the navigation in the editor but it works on the HoloLens.

Running a background process/task updating database

I'm trying to find the way to keep the database updated, but the method which does it consumes a lot of time so I try to create a background task to do it.
I searched for solutions and I read this article of different options to run background processes: https://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx
But I don't know what's is the best solution out of those, like I'm trying to execute it outside the application. I found something about creating a Windows Service too, but I don't know how, I didn't manage to find some good examples.
What is the best way to keep my database updated everytime I access the application without losing the time it consumes? If you can help me to see the light I would appreciate that so much.
I'm really happy with FluentScheduler, which is handling all my mission-critical scheduling. As well as firing jobs on a scheduled basis, it can also do them on demand, like so:
// Define your job in its own class
public abstract class MyJob : IJob
{
public void Execute()
{
// Do stuff here...
}
}
// Schedule your job at startup
var runAt = DateTime.Today.AddHours(1); // 1am
if (runAt<DateTime.Now)
runAt = runAt.AddDays(1);
Schedule<MyJob>()
.WithName("My Job Name") // Job name, required for manually triggering
.NonReentrant() // Only allow one instance to run at a time
.ToRunOnceAt(runAt) // First execution date/time
.AndEvery(1).Days().At(runAt.Hour, runAt.Minute); // Run every day at the same time
// To manually trigger your job
ScheduledJobRegistry.RunTaskAsync("My Job Name");
I have the scheduled jobs running in a windows Service and use SignalR as a means of triggering them remotely from an MVC Web App when required.
You can use an async method. Just use a void instead of Task.
public async void LongRunningMethod () {
...
// Insert long running code here
...
}
Then call it and it will execute in the background. Be aware that you can have hidden exceptions without proper were handling.
You can also use Hangfire which is a pretty awesome background task scheduler
Here is an example of using Hangfire to run a daily task
RecurringJob.AddOrUpdate(() => Console.Write("Easy!"), Cron.Daily);

How to save a timestamp using NodaTime?

I have the following implementation using basic UtcNow, and then converting it back to the UI.
The purpose in this scenario is very simple.
When I insert a new client to the database, I convert it to UtcNow, so I have a timestamp of this record.
When I show it back to the user, I convert it to Local (eg: You are member since "dd/MM/yyyy").
Here is my implementation. I would like to know how do I get this done through NodaTime. And also, if anyone has a better approach for doing it, I'll be glad to hear!
public interface IDateTime
{
DateTime ToUtcNow { get; }
DateTime FromUtc(DateTime dateTimeToConvert);
}
public class DateTimeProvider : IDateTime
{
public DateTime ToUtcNow
{
get { return DateTime.UtcNow; }
}
public DateTime FromUtc(DateTime dateTimeToConvert)
{
return dateTimeToConvert.ToLocalTime();
}
}
Also, how should I save it to database, in this case Sql Server. What data type should I use? DateTime, DateTimeOffset? What about in code? OffsetDateTime, ZonedDateTime I am very confused about that. I have read the userguide, but it shows more complex scenarios that I'am not getting to implement it in such a simple scenario.
Thanks in advance!
It sounds like you're trying to store points in time, regardless of calendar system or time zone. Those are represented by Instant values in Noda Time. So within most of your code, that's probably what you should use to represent the timestamp. (That's also what IClock.Now will give you.)
However, your database is unlikely to know about Noda Time... I would suggest that you should probably store a DateTimeOffset, which you can obtain via Instant.ToDateTimeOffset (and there's Instant.FromDateTimeOffset too). That will always have an offset of 0, but at least then it's not ambiguous about which point in time it represents.

How Can I make async operations of my own with WinRT using IAsyncOperation interface?

I am developing a metro application and I want to create some async operations whose my own classes would implement.
I have found just examples of async using WinRT operations (e.g. CreateFileAsync). I do not find any intance where someone is creating a async method and consuming it.
Now you can do it. Look at this:
http://blogs.msdn.com/b/nativeconcurrency/archive/2011/10/27/try-it-now-use-ppl-to-produce-windows-8-asynchronous-operations.aspx
http://code.msdn.microsoft.com/Windows-8-Asynchronous-08009a0d
WinRT Async Production using C++
Use create_async in C++:
IAsyncOperationWithProgress<IBuffer^, unsigned int>^ RandomAccessStream::ReadAsync(IBuffer^ buffer, unsigned int count, InputStreamOptions options)
{
if (buffer == nullptr)
throw ref new InvalidArgumentException;
auto taskProvider = [=](progress_reporter<unsigned int> progress, cancellation_token token)
{
return ReadBytesAsync(buffer, count, token, progress, options);
};
return create_async(taskProvider);
}
Use AsyncInfo.Run in .NET:
public IAsyncOperation<IInfo> Async()
{
return AsyncInfo.Run(_ =>
Task.Run<AType>(async () =>
{
return await DoAsync();
})
);
}
I posted the same question in Microsoft forums and they gave me two replies. The first was:
Hi Claudio,
In the Developer Preview there isn't an easy way to create your own
async operations. We are aware of this shortcoming and are trying to
solve it for the next pubic release. In the meanwhile, you could
design your API as async and we will provide guidance on how to
convert sync to async.
Thanks
Raman Sharma, Visual C++
When I asked for the hard way to do this, another guy, someone responsible for PPL said me:
We’re planning to do a refresh of the sample pack we released a few
weeks ago and add a few samples on creation of async operations. I
expect that it will happen in a couple of weeks or so. If you keep an
eye on our blog at http://blogs.msdn.com/b/nativeconcurrency, you’ll
be the first to know.
As to how hard it is... The general-purpose solution that we’re
contemplating is about 1000 lines of C++ code making copious use of
template metaprogramming. Most of it will be in the header file so you
can explore it yourself. While a less general solution can be less
complex, you will still need to implement a base class, do the state
management, error handling etc. At this moment I can’t go into more
detail, but I will say that you will love how easy it is to author
async operations with PPL – so hang in there!
Artur Laksberg PPL team
Then, there is no solution at that time. Thank you all.
Yes, see Ben Kuhn's //BUILD/ talk: http://channel9.msdn.com/events/BUILD/BUILD2011/PLAT-203T He shows how to build an asynchronous API.
At the current time, there is no good solution for high level (C++/WX) classes. However if you use the low level C++ interfaces, you can use the WRL::AsyncBase class to help build your async interfaces.
Here is documentation about the AsyncBase class.
It is confusing, but there is a difference between WinRT C++ code and WRL. You can use WRL to code to the ABI layer directly. WRL does not use exceptions, but loves templates. The recommend coding style for WinRT is not the same as WRL.
I am not sure if everyone can do this, but using WRL you in general need to implement a class that inherits:
class CreateAysncOp: public RuntimeClass<IAsyncOperation<result_runtime_class*>,AsyncBase<IAsyncCompletedHandler<result_runtime_class*>>
{
...
Then you can use
hr = MakeAndInitialize<CreateAsyncOp, IAsyncOperation<type_foo*>>(...);
C++ WinRT is now the best way to implement WinRT async methods. This uses co_await and co_return, new C++ language features (in the process of standardization). Read the docs on this page.

What the difference between JobLockService.getLock() & JobLockService.getTransactionLock()

What the difference between JobLockService.getLock() & JobLockService.getTransactionLock() ? from practical perspective and theoretical perspective ?
Thanks
Mohammed Amr
Senior System Developer
Digital Series Co,
Have a look at the two methods signatures:
java.lang.String getLock(org.alfresco.service.namespace.QName lockQName,
long timeToLive)
Returns a String, which is the newly created LockToken. You must use the token in following calls to refreshLock or releaseLock in order to manually manage the lock life span.
void getTransactionalLock(org.alfresco.service.namespace.QName lockQName,
long timeToLive)
void method, only asks for a QName. The same thread, or other threads, can call this method to try to acquire the lock. Following calls to getTransactionalLock will automatically try to refresh the lock in case it's available/expired, without the need to pass the token around.

Resources