Timezone names for .NET application in LINUX - asp.net-core

I have an ASP.NET CORE app.
While this code works in Windows:
var utcNow = DateTime.UtcNow;
var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, "US Eastern Standard Time");
Will this work when deployed on Linux Kubernetes cluster - given the harcoded timezone name "US Eastern Standard Time"
Or do I need to configure a different name?
Thanks
Anand

For LINUX the name to use is "EST"
var utcNow = DateTime.UtcNow;
string estTz = string.Empty;
#if RUN_ON_WINDOWS
estTz = "US Eastern Standard Time";
#else
estTz = "EST";
#endif
var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, estTz); // nyse tz
In case you are interested we have RUN_ON_WINDOWS in .csproj that the TeamCity build process for LINUX or WINDOWS deployment overwrites accordingly.
<ItemGroup Condition="'$(RunOnWindows)'=='true'">

For TimeZoneInfo, it has different ids for Windows and Linux, you could check this issue TimeZoneInfo should have consistent Ids across Windows and Linux #2538.
For a possible workaround, you could try TimeZoneConverter like
var utcNow = DateTime.UtcNow;
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Eastern Standard Time");
var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, tzi.Id);

Related

getting FindFailed issue in sikuli for image on windows server 2019 (ADO VM)

Getting below error when running script on window server 2019 (ADO VM) through pipeline , same script is working fine on windows 10 (having resolution 1920X1080).
I am using screen resolution utility to change the VM resolution to 1920X1080 in pipeline.
I am setup the path Bundle Folder by using below text:
ImagePath.setBundleFolder(new File(System.getProperty("user.dir")+"/SikuliImages"));
using below code
ImagePath.setBundleFolder(new File(System.getProperty("user.dir")+"/SikuliImages"));
System.out.println("Image Bundle Path="+ImagePath.getBundlePath());
Screen screen=new Screen();
String UserName_Image_Path = System.getProperty("user.dir")+"/SikuliImages/UserName_TextBox.png";
String UserPassword_Image_Path = System.getProperty("user.dir")+"/SikuliImages/UserPassword_TextBox.png";
String SignIn_Image_Path = System.getProperty("user.dir")+"/SikuliImages/SignIn_Button.png";
Pattern P_UserName = new Pattern(UserName_Image_Path);
Pattern P_UserPassword = new Pattern(UserPassword_Image_Path);
Pattern P_SignIn = new Pattern(SignIn_Image_Path);
System.out.println("Wait for popup");
screen.wait(P_UserName,30);
Match UserName_Found = screen.exists(UserName_Image_Path);
UserName_Found.highlight(2);
screen.type(P_UserName,UserName);
Match UserPassword_Found = screen.exists(UserPassword_Image_Path);
UserPassword_Found.highlight(2);
screen.type(P_UserPassword,UserPassword);
Match SignIn_Found = screen.exists(SignIn_Image_Path);
SignIn_Found.highlight(2);
screen.click(P_SignIn);
FindFailed : C:\agent\vsts-agent-win-x64-2.200.2_work\1\s\Automation/SikuliImages/UserName_TextBox.png: (378x54) in R[0,0 1920x1080]#S(0)
Line 2226, in file Region.java
Could someone help me please.
This is not valid windows path since it contains both \ and /

How to automate synchronizing Windows 10 guest's time with the Linux host?

On Arch Linux I have a Windows 10 Guest on top of libvirt, kvm and virsh (still having some trouble to connect all these dots mentally together). Every time I suspend the laptop and a day is gone the Windows 10 host goes out of sync. I learned that with the following command I can force a time sync in the host:
➜ ~ virsh qemu-agent-command win10 '{"execute":"guest-set-time"}'
{"return":{}}
In order to make this work I modifed the clock XML block and added a kvm clock entry. This is how the block looks like now:
<clock offset="localtime">
<timer name="tsc" tickpolicy="delay"/>
<timer name="kvmclock"/>
<timer name="rtc" tickpolicy="delay" track="wall"/>
<timer name="pit" tickpolicy="delay"/>
<timer name="hpet" present="yes"/>
</clock>
I would like to know whether I can automate this step or trigger an update everytime I wake up the machine or log-in.
Thanks in advance
I was not able to get anywhere specifically using virsh. Here is how I fixed this issue in a Windows 11 guest on MacOS in UTM 3.6.4 and 4.1.5.
At first I tried many workarounds using w32tm - but this was always flaky.
This helped slightly:
disable "use local time for base clock" (otherwise you can't add a manual -rtc argument if using UTM)
add -rtc base=localtime,driftfix=slew
This wasn't great, because it won't recover a significant delta.
This is the solution I settled on (run in the Windows guest). It creates a scheduled task that runs every 5 minutes, gets the time from NTP, converts it to local time, measures the drift, and if the drift is >30 seconds in either direction it updates the system clock.
function Get-NtpTime
{
[OutputType([datetime])]
[CmdletBinding()]
param
(
[string]$Server = "time.nist.gov",
[int]$Port = 13
)
if (-not $PSBoundParameters.ContainsKey('ErrorAction'))
{
$ErrorActionPreference = 'Stop'
}
$Client = [Net.Sockets.TcpClient]::new($Server, $Port)
$Reader = [IO.StreamReader]::new($Client.GetStream())
try
{
$Response = $Reader.ReadToEnd()
$UtcString = $Response.Substring(7, 17)
$LocalTime = [datetime]::ParseExact(
$UtcString,
"yy-MM-dd HH:mm:ss",
[cultureinfo]::InvariantCulture,
[Globalization.DateTimeStyles]::AssumeUniversal
)
}
finally
{
$Reader.Dispose()
$Client.Dispose()
}
$LocalTime
}
function Register-TimeSync
{
[CmdletBinding()]
param
(
[Parameter()]
[timespan]$RepetitionInterval = (New-TimeSpan -Minutes 5),
[Parameter()]
[timespan]$ExecutionTimeLimit = (New-TimeSpan -Minutes 3)
)
$Invocation = {
$NtpTime = Get-NtpTime
$Delta = [datetime]::Now - $NtpTime
if ([Math]::Abs($Delta.TotalSeconds) -gt 30)
{
Set-Date $NtpTime
}
}
$PSName = if ($PSVersionTable.PSVersion.Major -le 5) {'powershell'} else {'pwsh'}
$Path = (Get-Command $PSName).Source
$Command = Get-Command Get-NtpTime
$Definition = "function Get-NtpTime`n{$($Command.Definition)}"
$Invocation = $Definition, $Invocation -join "`n"
$Bytes = [Text.Encoding]::Unicode.GetBytes($Invocation)
$Encoded = [Convert]::ToBase64String($Bytes)
$TriggerParams = #{
Once = $true
At = [datetime]::Today
RepetitionInterval = $RepetitionInterval
}
$Trigger = New-ScheduledTaskTrigger #TriggerParams
$Action = New-ScheduledTaskAction -Execute $Path -Argument "-NoProfile -EncodedCommand $Encoded"
$Settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit $ExecutionTimeLimit -MultipleInstances IgnoreNew
$Principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$RegisterParams = #{
TaskName = "Update system time from NTP"
Trigger = $Trigger
Action = $Action
Settings = $Settings
Principal = $Principal
Force = $true
}
Register-ScheduledTask #RegisterParams
}
Usage (run as admin):
Register-TimeSync

Exchange Api send incorrect invitation in Israel timezone

I faced to following problem with sending invitation in .net using exchange API
Send invitation in Israel timezone with start time =09/09/2013 4.30 Israel.
But it is displayed in outlook 09/09/2013 6.30 Israel.
It works properly for other time zones for example for EST.
Does anybody has any idea how to fix this?
Sample:
service.AutodiscoverUrl(loginForm.tbEmailAddress.Text, f);
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Israel Standard Time");
Appointment appointment = new Appointment(service);
appointment.Subject = "subj";
appointment.Body = new MessageBody(BodyType.Text, "body");
appointment.StartTimeZone = timeZoneInfo;
appointment.Start = GetDateTime(new DateTime(2013, 09, 09, 04, 0, 0));
appointment.EndTimeZone = timeZoneInfo;
appointment.End = GetDateTime(new DateTime(2013, 09, 09, 04, 30, 0));
appointment.IsAllDayEvent = false;
appointment.Importance = Importance.Normal;
appointment.RequiredAttendees.Add("Lena", "email...");
appointment.Save(SendInvitationsMode.SendOnlyToAll);
...
private static DateTime GetDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute,
dateTime.Second, dateTime.Millisecond, DateTimeKind.Unspecified
);
}
I use Microsoft.Exchange.WebServices.dll 15.0.516.14
it's actually a known issue with Exchange EWS itself. Developer can only trust the date time returned without the timezone information, and the correct timezone for that time should be UTC always.

Mac serial number (system)

I know how to get the serial number of a mac computer using objective c but wondered if there was a way using c# (mono)?
Obviously this is to uniquely identify a machine. I am already using the MAC address but need something which can't be spoofed.
THe following should give you the serial number. Though it is not purely via mono. But this should work.
string serialNumber;
using (var p = new Process())
{
var serialRegex = new Regex("\"IOPlatformSerialNumber\" = \"(\\S+)\"");
p.StartInfo = new ProcessStartInfo("/usr/sbin/ioreg",
"-c IOPlatformExpertDevice");
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
serialNumber = serialRegex.Match(p.StandardOutput.ReadToEnd()).Groups[1].Captures[0].Value;
p.WaitForExit();
}

sharepoint foundation 2010 client object model gives the wrong Last Modified Time of the versions of files

sharepoint foundation 2010 client object model gives the wrong Last Modified Time of the versions of files. How to get the correct modified time.
I am using the below code....
SP.File file = web.GetFileByServerRelativeUrl(serverRelatedUrl);
clientContext.Load(file, fv => fv.Name, fv => fv.Exists, fv => fv.TimeLastModified);
clientContext.ExecuteQuery();
SP.FileVersionCollection fileVersionCollection = file.Versions;
clientContext.Load(fileVersionCollection);
clientContext.ExecuteQuery();
foreach (SP.FileVersion fileVersion in fileVersionCollection)
{
clientContext.Load(fileVersion, fv => fv.Created);
clientContext.ExecuteQuery();
DateTime ModifiedTime = fileVersion.Created;
}
Here fileVersion.Created give the Coordinated Universal Time (UTC).