Skip to content

Commit

Permalink
Add support for DateTimeOffset with SQLite.
Browse files Browse the repository at this point in the history
  • Loading branch information
bitbound committed Jul 29, 2021
1 parent f73d7c1 commit 1151834
Show file tree
Hide file tree
Showing 27 changed files with 98 additions and 53 deletions.
6 changes: 3 additions & 3 deletions Agent.Installer.Win/Services/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static void Debug(string message)
#if DEBUG
CheckLogFileExists();

File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}");

#endif
System.Diagnostics.Debug.WriteLine(message);
Expand All @@ -35,7 +35,7 @@ public static void Write(string message)
lock (WriteLock)
{
CheckLogFileExists();
File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}");
Console.WriteLine(message);
}
}
Expand All @@ -54,7 +54,7 @@ public static void Write(Exception ex)

while (exception != null)
{
File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}");
Console.WriteLine(exception.Message);
exception = exception.InnerException;
}
Expand Down
6 changes: 3 additions & 3 deletions Agent/Services/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public static void Debug(string message)
#if DEBUG
CheckLogFileExists();

File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}");

#endif
System.Diagnostics.Debug.WriteLine(message);
Expand All @@ -36,7 +36,7 @@ public static void Write(string message)
lock (WriteLock)
{
CheckLogFileExists();
File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}");
Console.WriteLine(message);
}
}
Expand All @@ -55,7 +55,7 @@ public static void Write(Exception ex)

while (exception != null)
{
File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}");
Console.WriteLine(exception.Message);
exception = exception.InnerException;
}
Expand Down
6 changes: 3 additions & 3 deletions ScreenCast.Core/Capture/ScreenCasterBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public async Task BeginScreenCasting(string viewerID,
Logger.Write($"Starting screen cast. Requester: {requesterName}. Viewer ID: {viewerID}. Capturer: {capturer.GetType().ToString()}. App Mode: {mode}");

byte[] encodedImageBytes;
var fpsQueue = new Queue<DateTime>();
var fpsQueue = new Queue<DateTimeOffset>();

var viewer = new Viewer()
{
Expand Down Expand Up @@ -83,11 +83,11 @@ await casterSocket.SendScreenCount(

if (conductor.IsDebug)
{
while (fpsQueue.Any() && DateTime.Now - fpsQueue.Peek() > TimeSpan.FromSeconds(1))
while (fpsQueue.Any() && DateTimeOffset.Now - fpsQueue.Peek() > TimeSpan.FromSeconds(1))
{
fpsQueue.Dequeue();
}
fpsQueue.Enqueue(DateTime.Now);
fpsQueue.Enqueue(DateTimeOffset.Now);
Debug.WriteLine($"Capture FPS: {fpsQueue.Count}");
}

Expand Down
6 changes: 3 additions & 3 deletions ScreenCast.Core/Services/IdleTimer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public IdleTimer(Conductor conductor)

public ConcurrentDictionary<string, Viewer> ViewerList { get; }

public DateTime ViewersLastSeen { get; private set; } = DateTime.Now;
public DateTimeOffset ViewersLastSeen { get; private set; } = DateTimeOffset.Now;

private Timer Timer { get; } = new Timer(100);

Expand All @@ -30,9 +30,9 @@ private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (ViewerList.Count > 0)
{
ViewersLastSeen = DateTime.Now;
ViewersLastSeen = DateTimeOffset.Now;
}
else if (DateTime.Now - ViewersLastSeen > TimeSpan.FromSeconds(10))
else if (DateTimeOffset.Now - ViewersLastSeen > TimeSpan.FromSeconds(10))
{
Logger.Write("No viewers connected after 10 seconds. Shutting down.");
Environment.Exit(0);
Expand Down
6 changes: 3 additions & 3 deletions ScreenCast.Core/Services/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static void Debug(string message)
#if DEBUG
CheckLogFileExists();

File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}");

#endif
System.Diagnostics.Debug.WriteLine(message);
Expand All @@ -32,7 +32,7 @@ public static void Write(string message)
lock (WriteLock)
{
CheckLogFileExists();
File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}");
Console.WriteLine(message);
}
}
Expand All @@ -51,7 +51,7 @@ public static void Write(Exception ex)

while (exception != null)
{
File.AppendAllText(LogPath, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}");
File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}");
Console.WriteLine(exception.Message);
exception = exception.InnerException;
}
Expand Down
2 changes: 1 addition & 1 deletion Server/API/FileSharingController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public ActionResult Get(string id)
{
var sharedFile = DataService.GetSharedFiled(id);
// Shared files expire after a minute and become locked.
if (sharedFile != null && sharedFile.Timestamp.AddMinutes(1) > DateTime.Now)
if (sharedFile != null && sharedFile.Timestamp.AddMinutes(1) > DateTimeOffset.Now)
{
return File(sharedFile.FileContents, sharedFile.ContentType, sharedFile.FileName);
}
Expand Down
10 changes: 5 additions & 5 deletions Server/Areas/Identity/Pages/Account/Manage/ServerLogs.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ private void PopulateViewModel()

if (Input.FromDate.HasValue || Input.ToDate.HasValue)
{
var from = Input.FromDate ?? DateTime.MinValue;
var to = Input.ToDate ?? DateTime.MaxValue;
var from = Input.FromDate ?? DateTimeOffset.MinValue;
var to = Input.ToDate ?? DateTimeOffset.MaxValue;
EventLogs = DataService.GetEventLogs(User.Identity.Name, from, to);
}
else
{
EventLogs = DataService.GetEventLogs(User.Identity.Name, DateTime.Now.AddDays(-10), DateTime.Now);
EventLogs = DataService.GetEventLogs(User.Identity.Name, DateTimeOffset.Now.AddDays(-10), DateTimeOffset.Now);
}

}
Expand All @@ -54,8 +54,8 @@ public void OnPost()

public class InputModel
{
public DateTime? FromDate { get; set; } = DateTime.Now.AddDays(-10);
public DateTime? ToDate { get; set; } = DateTime.Now;
public DateTimeOffset? FromDate { get; set; } = DateTimeOffset.Now.AddDays(-10);
public DateTimeOffset? ToDate { get; set; } = DateTimeOffset.Now;
}
}
}
34 changes: 33 additions & 1 deletion Server/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System.Linq;

namespace Remotely.Server.Data
{
Expand Down Expand Up @@ -38,6 +40,7 @@ public ApplicationDbContext(DbContextOptions<ApplicationDbContext> context)

protected override void OnModelCreating(ModelBuilder builder)
{

base.OnModelCreating(builder);

builder.Entity<IdentityUser>().ToTable("RemotelyUsers");
Expand Down Expand Up @@ -89,8 +92,14 @@ protected override void OnModelCreating(ModelBuilder builder)
x => JsonConvert.SerializeObject(x),
x => JsonConvert.DeserializeObject<List<GenericCommandResult>>(x));

builder.Entity<GenericCommandResult>()
.HasNoKey();

builder.Entity<PSCoreCommandResult>()
.HasNoKey();


builder.Entity<RemotelyUser>()
builder.Entity<RemotelyUser>()
.HasOne(x => x.Organization)
.WithMany(x => x.RemotelyUsers);

Expand All @@ -117,6 +126,29 @@ protected override void OnModelCreating(ModelBuilder builder)

builder.Entity<ApiToken>()
.HasIndex(x => x.Token);

if (Database.ProviderName == "Microsoft.EntityFrameworkCore.Sqlite")
{
// SQLite does not have proper support for DateTimeOffset via Entity Framework Core, see the limitations
// here: https://docs.microsoft.com/en-us/ef/core/providers/sqlite/limitations#query-limitations
// To work around this, when the SQLite database provider is used, all model properties of type DateTimeOffset
// use the DateTimeOffsetToBinaryConverter
// Based on: https://github.com/aspnet/EntityFrameworkCore/issues/10784#issuecomment-415769754
// This only supports millisecond precision, but should be sufficient for most use cases.
foreach (var entityType in builder.Model.GetEntityTypes())
{
var properties = entityType.ClrType.GetProperties().Where(p => p.PropertyType == typeof(DateTimeOffset)
|| p.PropertyType == typeof(DateTimeOffset?));
foreach (var property in properties)
{
builder
.Entity(entityType.Name)
.Property(property.Name)
.HasConversion(new DateTimeOffsetToBinaryConverter());
}
}
}

}
}
}
2 changes: 1 addition & 1 deletion Server/Models/RCSessionInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ public class RCSessionInfo
public string RequesterSocketID { get; set; }
public string RequesterUserName { get; set; }
public string ServiceID { get; set; }
public DateTime StartTime { get; set; }
public DateTimeOffset StartTime { get; set; }
}
}
4 changes: 2 additions & 2 deletions Server/Models/RemoteControlFrame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Remotely.Server.Models
public class RemoteControlFrame
{

public RemoteControlFrame(byte[] frameBytes, int left, int top, int width, int height, string viewerID, string machineName, DateTime startTime)
public RemoteControlFrame(byte[] frameBytes, int left, int top, int width, int height, string viewerID, string machineName, DateTimeOffset startTime)
{
this.FrameBytes = frameBytes;
this.Left = left;
Expand All @@ -25,6 +25,6 @@ public RemoteControlFrame(byte[] frameBytes, int left, int top, int width, int h
public int Height { get; private set; }
public string ViewerID { get; private set; }
public string MachineName { get; private set; }
public DateTime StartTime { get; private set; }
public DateTimeOffset StartTime { get; private set; }
}
}
2 changes: 1 addition & 1 deletion Server/Pages/RemoteControl.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@

<footer>
<div class="footer-wrapper">
<p>&copy; @DateTime.Now.Year - Translucency Software</p>
<p>&copy; @DateTimeOffset.Now.Year - Translucency Software</p>
<p hidden="hidden">
<span>File Transfer:</span>
<progress id="fileTransferProgress"></progress>
Expand Down
2 changes: 1 addition & 1 deletion Server/Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
<div class="container">
<hr />
<div class="footer-wrapper">
<p>&copy; @DateTime.Now.Year - Translucency Software</p>
<p>&copy; @DateTimeOffset.Now.Year - Translucency Software</p>
<p class="text-right">
<a asp-page="/About">About Remotely</a> - <a asp-area="" asp-page="/Privacy">Privacy</a>
</p>
Expand Down
5 changes: 5 additions & 0 deletions Server/Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@
<None Remove="Areas\Identity\Services\**" />
</ItemGroup>

<ItemGroup>
<Compile Remove="Migrations\20200305070438_DateTimeOffsets.cs" />
<Compile Remove="Migrations\20200305070438_DateTimeOffsets.Designer.cs" />
</ItemGroup>

<ItemGroup>
<Content Remove="wwwroot\scripts\BrowserSockets.ts" />
<Content Remove="wwwroot\scripts\Chat.ts" />
Expand Down
2 changes: 1 addition & 1 deletion Server/Services/BrowserSocketHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public Task TransferFiles(List<string> fileIDs, string transferID, string[] devi
{
EventType = EventType.Info,
Message = $"File transfer started by {RemotelyUser.UserName}. File transfer IDs: {string.Join(", ", fileIDs)}.",
TimeStamp = DateTime.Now,
TimeStamp = DateTimeOffset.Now,
OrganizationID = RemotelyUser.OrganizationID
});
deviceIDs = DataService.FilterDeviceIDsByUserPermission(deviceIDs, RemotelyUser);
Expand Down
20 changes: 10 additions & 10 deletions Server/Services/DataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public InviteLink AddInvite(string orgID, Invite invite)

var newInvite = new InviteLink()
{
DateSent = DateTime.Now,
DateSent = DateTimeOffset.Now,
InvitedUser = invite.InvitedUser,
IsAdmin = invite.IsAdmin,
Organization = organization,
Expand Down Expand Up @@ -154,7 +154,7 @@ public bool AddOrUpdateDevice(Device device, out Device updatedDevice)

public string AddSharedFile(IFormFile file, string organizationID)
{
var expirationDate = DateTime.Now.AddDays(-AppConfig.DataRetentionInDays);
var expirationDate = DateTimeOffset.Now.AddDays(-AppConfig.DataRetentionInDays);
var expiredFiles = RemotelyContext.SharedFiles.Where(x => x.Timestamp < expirationDate);
RemotelyContext.RemoveRange(expiredFiles);

Expand Down Expand Up @@ -196,7 +196,7 @@ public void CleanupOldRecords()
if (AppConfig.DataRetentionInDays > 0)
{

var expirationDate = DateTime.Now - TimeSpan.FromDays(AppConfig.DataRetentionInDays);
var expirationDate = DateTimeOffset.Now - TimeSpan.FromDays(AppConfig.DataRetentionInDays);

var eventLogs = RemotelyContext.EventLogs
.Where(x => x.TimeStamp < expirationDate);
Expand Down Expand Up @@ -474,14 +474,14 @@ public IEnumerable<Device> GetDevicesForUser(string userName)
)));
}

public IEnumerable<EventLog> GetEventLogs(string userName, DateTime from, DateTime to)
public IEnumerable<EventLog> GetEventLogs(string userName, DateTimeOffset from, DateTimeOffset to)
{
var orgID = RemotelyContext.Users
.FirstOrDefault(x => x.UserName == userName)
?.OrganizationID;

var fromDate = DateTime.Now.Date;
var toDate = DateTime.Now.Date.AddDays(1);
var fromDate = from.Date;
var toDate = to.Date.AddDays(1);

return RemotelyContext.EventLogs
.Where(x => x.OrganizationID == orgID && x.TimeStamp >= fromDate && x.TimeStamp <= toDate)
Expand Down Expand Up @@ -789,7 +789,7 @@ public bool ValidateApiToken(string apiToken, string apiSecret, string requestPa

if (token != null)
{
token.LastUsed = DateTime.Now;
token.LastUsed = DateTimeOffset.Now;
RemotelyContext.SaveChanges();
}

Expand All @@ -811,7 +811,7 @@ public void WriteEvent(Exception ex)
Message = ex.Message,
Source = ex.Source,
StackTrace = ex.StackTrace,
TimeStamp = DateTime.Now
TimeStamp = DateTimeOffset.Now
});
RemotelyContext.SaveChanges();
}
Expand All @@ -822,7 +822,7 @@ public void WriteEvent(string message, string organizationId)
{
EventType = EventType.Info,
Message = message,
TimeStamp = DateTime.Now,
TimeStamp = DateTimeOffset.Now,
OrganizationID = organizationId
});
RemotelyContext.SaveChanges();
Expand All @@ -834,7 +834,7 @@ public void WriteEvent(string message, EventType eventType, string organizationI
{
EventType = eventType,
Message = message,
TimeStamp = DateTime.Now,
TimeStamp = DateTimeOffset.Now,
OrganizationID = organizationId
});
RemotelyContext.SaveChanges();
Expand Down
2 changes: 1 addition & 1 deletion Server/Services/RCBrowserSocketHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ public async Task<Task> SendScreenCastRequestToDevice(string screenCasterID, str
DataService.WriteEvent(new EventLog()
{
EventType = EventType.Info,
TimeStamp = DateTime.Now,
TimeStamp = DateTimeOffset.Now,
Message = $"Remote control session requested. " +
$"Login ID (if logged in): {Context?.User?.Identity?.Name}. " +
$"Machine Name: {sessionInfo.MachineName}. " +
Expand Down
2 changes: 1 addition & 1 deletion Server/Services/RCDeviceSocketHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public override async Task OnConnectedAsync()
SessionInfo = new RCSessionInfo()
{
RCDeviceSocketID = Context.ConnectionId,
StartTime = DateTime.Now
StartTime = DateTimeOffset.Now
};
SessionInfoList.AddOrUpdate(Context.ConnectionId, SessionInfo, (id, si) => SessionInfo);

Expand Down
2 changes: 1 addition & 1 deletion Server/Services/RemoteControlSessionRecorder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public RemoteControlSessionRecorder(IWebHostEnvironment hostingEnv, DataService
private static ConcurrentDictionary<string, RecordingSessionState> SessionStates { get; } = new ConcurrentDictionary<string, RecordingSessionState>();
private DataService DataService { get; }
private IWebHostEnvironment HostingEnv { get; }
internal void SaveFrame(byte[] frameBytes, int left, int top, int width, int height, string viewerID, string machineName, DateTime startTime)
internal void SaveFrame(byte[] frameBytes, int left, int top, int width, int height, string viewerID, string machineName, DateTimeOffset startTime)
{
var rcFrame = new RemoteControlFrame(frameBytes, left, top, width, height, viewerID, machineName, startTime);
FrameQueue.Enqueue(rcFrame);
Expand Down
Loading

0 comments on commit 1151834

Please sign in to comment.