Expiration date with template not working - c#

I have configured a template with an exploration date:
Get-AipServiceTemplateProperty -TemplateId 7a3e9ebd-a14e-4520-ba34-434029030633 -ContentExpirationDate -ContentExpirationOption | Format-List
Key : ContentExpirationOption
Value : OnDate
Key : ContentExpirationDate
Value : 12/25/2020 11:56:00 AM
And then I set protection to file with this template
ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor("7a3e9ebd-a14e-4520-ba34-434029030633");
The file successfully encrypted and the permission is set but it looks like the exploration date didn't work. When I open the file Word doesn't show me until when the file is valid.

For this problem, as it shows 12/25/2020 11:56:00 AM for the key ContentExpirationDate but you didn't find it work. So please check the the time zone of the expiration date, check if it matches UTC time zone and doesn't match your local time zone.

Related

Incorrect UTC time in Calendar File for MS Outlook

In my application of event management, i create a calendar file which is sent with the registration confirmation email. The application is in .NET with C#. I use following code to get the time.
sdate = row1.StartTime.ToUniversalTime().ToString("yyyyMMddThhmmssZ");
edate = row1.EndTime.ToUniversalTime().ToString("yyyyMMddThhmmssZ");
...
and then i add it to calendar file
contents.Add("DTSTART:" + sdate);
contents.Add("DTEND:" + edate);
But the problem is that if my end time is 3:59 PM local time then it coverts correctly. But if it ends at 4:00 PM then end time becomes incorrect.
Can anybody guide me?
Please find below the Screens of Outlook Calendar Entry and Calendar File data.
Correct Output
Incorrect Output
I finally found the solution. It is such a simple one that its disappointing that I missed it.
Just to help others. I just need to put capital 'H' in the string format when converting to string. So the correct code is
sdate = row1.StartTime.ToUniversalTime().ToString("yyyyMMddTHHmmssZ");
edate = row1.EndTime.ToUniversalTime().ToString("yyyyMMddTHHmmssZ");

c# SMO Backup - how to use ExpirationDate?

I followed roughly this example to backup a database with Microsofts SMO API and the code crashed with an exception telling invalid parameter ExpirationDate. I checked the documentation which does not contain details on how to set the parameter and my intuition told me it should be in the future, right? I was curious and tested some values:
DateTime.Today.AddDays(10) -> InvalidDataException
DateTime.Today.AddDays(-10) -> works fine
DateTime.Today.AddDays(-5) -> works fine
DateTime.Today.AddDays(-4) -> works fine
DateTime.Today.AddDays(-3) -> InvalidDataException
DateTime.Today.AddDays(-1) -> InvalidDataException
DateTime.Today.AddDays(100) -> InvalidDataException
DateTime.Today.AddDays(500) -> InvalidDataException
DateTime.Today.AddDays(1000) -> works fine
Reading this 5 year-old post it could be that the internal parameter is actually not of the type DateTime? But then it would be a bug, right?
These errors are likely the result of the locale of where the Backup.ExpirationDate property is being set from. Depending on the culture this is being executed in, the DateTime.AddDays method may increment the month instead of the day as expected, leading to the inconsistent results you saw. Of the values that you tested only the negative ones should cause errors, as the range of days for a backup expiration date is 0 - 99999, with 0 indicating that the backup will never expire as stated in the documentation. Try using the CultureInfo class to define a new locale then set the expiration date. This will require a reference to the System.Globalization namespace. Running the following code gave me no errors in setting the expiration date in a backup operation using the US (en-US) culture. Just make sure that the date in the culture you convert this to matches the date you expect it to in your timezone.
using System.Globalization;
string folderPath = #"C:\YourFolder\";
Server serv = new Server(#"YourServer");
Backup bkup = new Backup();
bkup.Database = "YourDatabase";
string bkupFilePath = folderPath + bkup.Database.ToString() + ".bak";
bkup.Action = BackupActionType.Database;
bkup.Devices.AddDevice(bkupFilePath, DeviceType.File);
bkup.BackupSetName = "YourDatabase Full Backup";
bkup.BackupSetDescription = "Full backup of YourDatabase";
DateTime today = DateTime.Now;
//define current date representation with en-US culture
string newLocale = today.ToString(new CultureInfo("en-US"));
//set Backup.ExpirationDate to use new culture
bkup.ExpirationDate = Convert.ToDateTime(newLocale);
bkup.ExpirationDate.AddDays(10);
bkup.ExpirationDate.AddDays(100);
bkup.ExpirationDate.AddDays(500);
bkup.ExpirationDate.AddDays(1000);
bkup.SqlBackup(serv);
edit I am super confused. I thought this solved my issue:
My issue was that I called backup.ExpirationDate.AddDays(X) without assigning it to anything. Therefore, the software was basically using "DateTime.Now".
Solution:
backup.ExpirationDate = backup.ExpirationDate.AddDays(X);
But it didn't completely. I still get the exception if I do this:
backup.ExpirationDate = backup.ExpirationDate.AddDays(1);
No idea why this code is wrong.

Manipulating User IDs in AD with c#

I am seriously confused, I'm a very out of practice software engineer (Last job in the field was 1993!) doing a bit of minor coding to make my sysadmin job go easier. I've picked c# over powershell because of its better debugging. What I'm trying to do, is take a username out of a spreadsheet, if that username exists in Active Directory, check its expiry date and if the one in the spreadsheet is later than the one set in active directory then update active directory to reflect.
I'm using VS 2015 on X64 2012 Server
I've got the following segment of code
using System.DirectoryServices.AccountManagement AuthenticablePrincipal.AccountExpirationDate
foundUser is the AuthenticablePrincipal
Globals.Uservars is a global (I know... please no lectures about global variables) String Array holding data which relates to the AD user object.
Uservars[4] is the expiry date from the spreadsheet.
Uservars[7] is a feedback comment result of operation.
AccountExpires = foundUser.AccountExpirationDate.Value.ToLocalTime();
ThisDay = DateTime.FromOADate(Convert.ToDouble(Globals.UserVars[4]));
if (ThisDay!=null)
{
if (ThisDay > AccountExpires)
{
foundUser.AccountExpirationDate = ThisDay;
foundUser.Save();
Globals.UserVars[7] = "Account End Date Incremented";
OutputResult();
}
else
{
Globals.UserVars[7] = "Existing User No Changes Made";
OutputResult();
}
}`
My confusion stems from the fact that I don't get an error, if I subsequently read the value of foundUser.AccountExpirationDate.Value.ToLocalTime(); from AD it has updated with the value from the spreadsheet, If I re-run the program this new value is in place but the flippin' thing doesn't show as changed in active directory users and computers.
Also If I try to convert DateTime values to FILETIME before updating AD (which I believe I should do, as I suspect I'm actually updating AD with an incorrect value despite what I see if I read it back) it seems to throw an error.
DUH?

Time zone issue with "Malay Peninsula Standard Time"

I have a program that runs the following code on C#:
TimeZoneInfo localZone = TimeZoneInfo.Local;
string timeZone = TimeZoneInfo.FindSystemTimeZoneById(localZone.Id).ToString();
MessageBox.Show("Local Time Zone ID: " + timeZone);
When I run this, I got the following exception:
System.TimeZoneNotFoundException: The time zone ID 'Malay Peninsula Standard Time' was not found on the local computer.
I made a slight modification on the code and used this line:
TimeZoneInfo localZone = TimeZoneInfo.Local;
MessageBox.Show("Local Time Zone ID: " + localZone.StandardName);
And this time I got no exception, and I got the popup message with the time zone "Malay Peninsula Standard Time"
Why the first fragment of code is not working?
After some time (days), I finally found out what was happening.
Debugging the code, I see that TimeZoneInfo.Local.Id was retrieving the following value:
Malay Peninsula Standard Time
I made some investigation, and found out that all the time zones for the server are stored on this registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\
If you browse through them, you will see that no key is called "Malay Peninsula Standard Time", the value that is for that time zone is "Singapore Standard Time". The whole information for that time zone is the following:
ID: Singapore Standard Time
Display Name: (GMT+08:00) Kuala Lumpur, Singapore
Standard Name: Malay Peninsula Standard Time
Daylight Name: Malay Peninsula Daylight Time ***Does Not Have Daylight Saving Time***
Offset from UTC: 8 hours, 0 minutes
Number of adjustment rules: 0
So, as you see, the ID that I was looking for did not exist, and that's why I got that exception. I renamed the registry key to "Malay Peninsula Standard Time" and the problem was gone.

GetLastWriteTime returning 12/31/1600 7:00:00 PM

I am using the following code to write the Date Modified time of a Directory to a label
string selectedPath = comboBox1.SelectedItem.ToString();
DateTime lastdate = Directory.GetLastWriteTime(selectedPath);
datemodified.Text = lastdate.ToString();
It returns the date 12/31/1600 7:00:00 PM which I have no clue where it is getting that date from. Can anyone help me understand why it is returning that date and how I can fix it? I'm using .NET 3.5
From the documentation:
If the directory described in the path parameter does not exist, this method returns 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted to local time.
So presumably your time zone is UTC-5 (in January), and the directory doesn't exist...
first thought is that of is your time set correctly. Second thought is to right click on that folder and see what it says in properties. Lastly I'd make new test folder and run that bit of GetLastWriteTime tests on it so you know what you are getting back.
GetLastWriteTime not always return reliable date time, use this
string selectedPath = comboBox1.SelectedItem.ToString();
DateTime now = DateTime.Now;
TimeSpan localOffset = now - now.ToUniversalTime();
DateTime lastdate = File.GetLastWriteTimeUtc(selectedPath) + localOffset;
datemodified.Text = lastdate.ToString();
Old question, but today I faced this issue. That particular date is also returned when your path is invalid or the file doesn't exists, because there is no built in exception in any of those cases.
An easy way to test for file not found with the result of GetLastWriteTime()/GetLastWriteTimeUtc() without hardcoding the sentinel epoch date/times that are used to indicate a file/dir not found condition, is as follows:
// ##### Local file time version #####
DateTime fileTimeEpochLocal=DateTime.FromFileTime(0);
// Use File.GetLastWriteTime(pathname) for files
// and Directory.GetLastWriteTime(pathname) for directories
DateTime lastWriteTime=Directory.GetLastWriteTime(selectedPath);
// Check for a valid last write time
if (lastWriteTime!=fileTimeEpochLocal) // File found
DoSomethingWith(selectedPath,lastWriteTime);
else // File not found
HandleFileNotFound(selectedPath);
// ##### UTC file time version #####
DateTime fileTimeEpochUtc=DateTime.FromFileTimeUtc(0);
// Use File.GetLastWriteTimeUtc(pathname) for files
// and Directory.GetLastWriteTimeUtc(pathname) for directories
DateTime lastWriteTimeUtc=Directory.GetLastWriteTimeUtc(selectedPath);
// Check for a valid last write time
if (lastWriteTimeUtc!=fileTimeEpochUtc) // File found
DoSomethingWith(selectedPath,lastWriteTimeUtc);
else // File not found
HandleFileNotFound(selectedPath);
In .net core, you will need to get the absolute path of the file.
Add reference to Microsoft.Extensions.Hosting and inject that into your constructor.
The ContentRootPath property will be your web root.
Grab your server path
var Files = FIO.Directory.GetFiles("Unzipped");
This will be your actual path
var Path = string.Format(#"{0}\{1}",WebRootPath, Files[0]);
var CreationDate = File.GetLastWriteTime(Path);

Categories