selecting dates greater than from xml using C# - c#

I am getting myself confused in Powershell in trying to use C# to fill a spreadsheet with two columns. The first is "start" and is what I need help with most. I want this to populate with dates greater than 31st July of a given year as entered as a string at the start. The below is part of what i'm using, and the whole thing is giving me a spreadsheet, but just not the dates I need. It's the line that starts $dr = $DS.Tables which I have been tampering with but to no avail.
$fileyear = "2017";
###Location of default DLLs
$DllsDir = [System.IO.Path]::Combine($PSScriptRoot,"dlls")
Write-Output "Dll Path "+$DllsDir
###Load default DLLs
foreach ($dll in [System.IO.Directory]::GetFiles($DllsDir,"*.dll",
[System.IO.SearchOption]::AllDirectories))
{
[reflection.assembly]::loadfrom($dll);
}
Write-Output "Dlls loaded";
###declare objects
$DS = New-Object System.Data.DataSet;
$DS.ReadXml($DBPath,[System.Data.XmlReadMode]::Auto);
$dt = New-Object System.Data.DataTable;
$dt.Columns.Add("Start");
$dt.Columns.Add("ULIN");
$dr = $DS.Tables["LearningDelivery"].Select("LearnStartDate >
(31/07/"+$fileyear+")");
[datetime]$LearnStartDate = $dr["LearnStartDate"]
Write-Output $dt.Rows.Count;

I guess that the date is not in the correct format. The format depends on the region your machine is configured.
I would build the date using the ISO format. Check for example this question for a reference: DataTable.Select date format problem

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.

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);

C# P/Invoke Attribute

New to C# Compact edition 6.5. I am trying to set the datetime on a file which seems to be off by 5 hours from the actual system time. I am doing only this to create the file:
FileStream fs= File.Create(name);
Just doing this the Created date is 5 hours ahead...if I try and set the CreationTime I get a compile error saying the Attribute is Readonly, seriously?
FileInfo fi = new FileInfo(name);
fi.CreationTime = date;
So my question is since I am new to C# how do you get access to a "readonly" Attribute in the CE framework? I see mentioning of P/Invoke but seems to work on methods only and not attributes. Anyone can given a quick demo on how to do this?
I've tried this solution and still get the file writing UTC even though I send it the current local time
I just ran this:
[MTAThread]
static void Main()
{
var name = "\\foo.txt";
var info = new FileInfo(name);
using (info.Create()) { }
info.Refresh();
var createTime = info.CreationTime;
var now = DateTime.Now;
var delta = now - createTime;
Debug.WriteLine(delta.ToString());
}
And got this output:
00:00:00.0140000
Which seems to be correct to me.
You can't modify the CreationTime of a file. It's set once and only once when the file is created. If you're willing to use P/Invoke to set the time, you can check out this similar question - c# - Change file LastWriteDate in Compact Framework
Instead of hacking the problem, though, you should fix the root cause. If there's an issue with the creation time of the file, I would consider checking your system's time settings (including timezone).

Batch script that can update a file with a date range

I need some assistance changing a date range on line 13 of a file:
01/01/201101/31/2011
I plan on setting the script to run every day from the windows scheduler.
I would like the script to change the begining date -15 days from current date
and the ending date +15 days from the current date.
I found the DateAdd.cmd written by Rob van der Woude (http://www.robvanderwoude.com)
but I am not sure how to pass the values back to my main (calling) script?
Without any ~batch~ assistance, I did the following in C#:
static void Main(string[] args)
{
string inputFile = Path.Combine("C:/temp","textfile.txt");
string outputFile = Path.Combine("C:/temp","textfile2.txt");
using(StreamReader input = File.OpenText(inputFile))
using(Stream output = File.OpenWrite(outputFile))
using(StreamWriter writer = new StreamWriter(output))
{
int count = 1;
while(!input.EndOfStream)
{
// read line
string line = input.ReadLine();
// Get dates 15 days on either side of current date
if(count == 13)
{
DateTime beginRange = DateTime.Today.AddDays(-15);
DateTime endRange = DateTime.Today.AddDays( 15 );
string strBeginDate = beginRange.ToShortDateString();
string strEndDate = endRange.ToShortDateString();
// replace line with new date range
line = "0001" + strBeginDate + strEndDate + "Report submitted by";
}
// increment counter
count++;
// write the file to temp file
writer.WriteLine(line);
}
}
File.Delete(inputFile); // delete original file
File.Move(outputFile,inputFile); // rename temp file to original file name
The batch file language hasn't been significantly updated decades. You still can't do a conventional for loop. I suggest looking into PowerShell. It is just as powerful (if not more) than the *nix shell languages, but can also leverage the entire .NET framework. If you use PowerShell, this problem would be as simple as
Open file, go to line 13
Parse the line as two dates
Subtract 15 days from one date object and add 15 to the next
Write the file back out
The fact that you're trying to do real programming in a batch file is truly honorable (I would have commited Seppuku). Try to switch to a more powerful shell language that is more feature complete. Besides, PowerShell is the future of Windows scripting.
I found the DateAdd.cmd written by Rob van der Woude (http://www.robvanderwoude.com) but I am not sure how to pass the values back to my main (calling) script?
I would agree with others that you're better off using a different scripting language (VBS, PowerShell, ...), but to answer this specific question, the DateAdd.cmd batch file sets an environment variable DATEADD to the result of its deliberations.
You can do something like:
CALL DATEADD -15 >NUL:
SET FROMDATE=%DATEADD%
CALL DATEADD 15 >NUL:
SET TODATE=%DATEADD%
echo %FROMDATE%%TODATE%
Note that DateAdd.cmd uses the current user's short date format from the registry, so will give different results depending on the user's locale.

Categories