I had a datetime column in a SQL Server table. We needed to encrypt it. So, I cast it to a varbinary in SSMS. I simply edited the table, set the datetime type to varbinary and let SQL Server convert it. Following that, I wrote throwaway C# code to pull it out, encrypt it (using the encryption algorithms in our middle layer) and push it back into the database. Did the same for some nvarchars for names and other string types.
When I pull out the encrypted data (using NHibernate), I pull the varbinary into a byte[] and decrypt it. I then try to convert it back to the original value.
The nvarchar-as-varbinary columns convert fine; for example, I get may names back.
return Encoding.Unicode.GetString(source.FirstName);
However, I'm having a hard time converting the dates back into their original form. I'm using:
long ticks = BitConverter.ToInt64(source.DateOfBirth, 0);
return new DateTime?(new DateTime(1980, 1, 1).AddMilliseconds(ticks));
This does not seem to return the date properly. What's the correct way to cast it back to a DateTime?
Update: A sample value was requested. A datetime that was originally 1/1/1901, when decrypted, yields a byte[] where byte[2]=1 and byte[3]=109, and all others are 0. Another datetime '1941-04-26' yields byte[2]=58 and byte[3]=242 upon decryption.
The date is stored as the number of days since 1900-01-01.
Example:
byte[] data = {0,0,58,242};
if (BitConverter.IsLittleEndian) {
Array.Reverse(data);
}
int days = BitConverter.ToInt32(data, 0);
DateTime date = new DateTime(1900, 1, 1).AddDays(days);
Console.WriteLine(date);
Output:
1941-04-26 00:00:00
Int64 ticks = BitConverter.ToInt64(source.DateOfBirth, 0);
DateTime dt = DateTime.FromBinary(ticks);
After you decrypt the varbinary data, can you get the string value and run it through SSMS? Something like:
SELECT CONVERT(datetime, 0x0000A149016D7FD9)
What does your varbinary data look like in SQL Server? I suspect something is being messed up in translations.
Good luck.
Related
I've a timestamp column in my database which is used as rowversion. At the time of pulling data out of the database we get rowversion also which i converted into byte[]. Upto this stage everything works as expected.
At the time of updating data, i'd like to check (in a stored procedure), if the rowversion is the same or not, that is compare one that is being passed from code with one that is stored in database. If that differs i abort the update otherwise it updates the data.
Now my problem is, how to pass byte[] to a stored procedure. The parameter type in the stored procedure is timestamp.
Note : I make all the db operations in c# using enterprise library. I can't change the stored procedure or datatypes. Its restricted.
See code below :
DateTime now = DateTime.Now;
long bNow = now.ToBinary();
byte[] arrayNow = BitConverter.GetBytes(bNow);
long getLong = BitConverter.ToInt64(arrayNow, 0);
DateTime getNow = DateTime.FromBinary(getLong);
Console.WriteLine(getNow.ToLongTimeString());
Console.ReadLine();
Below code works as expected
public static TestMethod(....,byte[] rowVersion)
{
.........
dbConnection_.AddInParameter(dbcommand, "#row_version", DbType.Binary,rowVersion);
...........
}
Above code is using enterprise library. I think this will help someone.
Thank you all of you who tried to help here. Cheers..!
When I get data from Mysql table the datetime column 2017-09-19 16:14:47 will automatically convert into its own format like 9/19/2017 3:45:50 PM. It happens when I'm getting data into DataTable and convert into string as follows:
DataTable update;
localdb.MysqlQuery(queryUpdate);
update = localdb.QueryEx();
if (update.Rows.Count > 0)
{
onlinedb = new DataAccessOnline();
foreach (DataRow row in update.Rows)
{
row["added"].ToString(); //9/19/2017 3:45:50 PM
but I need get this value as it is in TABLE column 2017-09-19 16:14:47 how can I do that ?
First you need to convert the data you get from the DB into a DateTime object using the Convert.ToDateTime method.
Then you can specify the format you want on the DateTime.toString method.
It would look something like this:
DateTime added = Convert.ToDateTime(row["added"].ToString());
string formatted = added.toString("yyyy-MM-dd HH:mm:ss");
You can format it in your server side query as string.
mySql is giving data to C# as datetime type. C# has slightly different format of interpreting and presenting datetime type value to you. Ultimately, data will work like a datetime field anyways.
If you bring it like a formatted string, you would need to convert it to datetime in C# to make it function like a datetime. On the other hand, if you want it to be converted in C# for presentation purposes, do it in C#, not while bringing data because then it would be a string, not datetime.
You can see more .ToString() conversion details here.
Default format you need is "u", but you can provide your own format string like this one.
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
I need to have C# via Entity Framework save current datetime to sql server into table column of datatype datetime
Was reading that DateTime.Now in C# is not going to be correct ...
so I stumbled across where a guy posted that he was doing this as it saves down to the proper millisecond
System.Data.SqlTypes.SqlDateTime entry2
= new System.Data.SqlTypes.SqlDateTime(new DateTime(dto.LookUpDateTime));
DateTime entry = entry2.Value;
Now I assumed with the Overloads that I should be able to just do this:
System.Data.SqlTypes.SqlDateTime dt
= new System.Data.SqlTypes.SqlDateTime(new DateTime());
However, I get an error in catch block saying 'sqldatatime overflow...`
DateTime dateTime = dt.Value;
rpmuser.lst_pwd_chg_dtm = dateTime;
rpmuser.cre_dtm = dateTime;
Can I use DateTime.Now or what do I need to do to get this SqlDateTime to work?
This is almost certainly because you are trying to store a date that is outside the supported range. On MS SQL Server the datetime field type can hold datetime values in the range 1-Jan-1753 00:00:00 to 31-Dec-9999 23:59:59.997 inclusive. This is narrower than the range explicitly supported by the .NET DateTime type (1-Jan-0001 00:00:00 to 31-Dec-9999 23:59:59 plus a fraction). So any date prior to 1-Jan-1753 will cause that error.
A common problem is when you use either DateTime.MinValue to indicate a specific state of your data but don't filter that to something the SQL field can contain before sending the data to the database. The solution in this case would be to define a suitable lower boundary of the data and define a static value that is lower but still within the SQL range.
If your data needs to include dates and times outside of the valid range for the SQL datetime field type then you might want to use the datetime2 field type which has the same effective range as the .NET DateTime type. Which is unsurprising since it appears to be the same data structure - count of 100ns ticks since 1-1-1.
I have date in format 2013-08-05 12:45:56. But I want to store this in format 2013-08-05 00:00:00 in database.
The thing I want is, I don't want to save the time in database.
I am using:
cmd.Parameters.AddWithValue("#VoucherDate", VoucherDate.Date);
But still it is saving the time. Any suggestions?
If you're using SQL 2008 or above, then you can use the Date data type
http://msdn.microsoft.com/en-us/library/bb675168.aspx
If you want to get the Date part only in C#, then you can use the Date property e.g.
var fullDate = DateTime.Now;
var dateOnly = fullDate.Date;
But, if you're only looking to store the date portion, then consider changing the SQL datatype.
Use the date column type instead of datetime
http://technet.microsoft.com/en-us/library/bb630352.aspx
Even you have Date, or DateTime column in database, when you read data back to your program you can format the display date by giving correct DataTime format string.
like dt.ToString("yyyy-MM-dd) , then you will not get any time as output
Once I too had a similar problem, with the help of this answer I fixed it.
Your C# code:
cmd.Parameters.AddWithValue("VoucherDate", VoucherDate.Date);
Tune your SQL query like below mentioned,
DATEADD(dd, 0, DATEDIFF(dd, 0, #VoucherDate))
Try using:
VoucherDate.Date.ToShortDateString();
What's wrong with this code?
Client c = new Client();
string format = "yyyy/MM/dd HH:mm:ss";
string dateAdded = now.ToString(format);
c.RegistrationDate = DateTime.Parse(dateAdded);
c.RegistrationDate is a dateTime object in the client class and I want it to insert to my database.
However It doesn't convert the freaking date to the format in my mysql database. It always says that string format is incorrect. WHAT have i done wrong???? should I convert my Registration Date to string??? Thanks
**EDIT: Sorry I've forgot to mention. "now" is now = DateTime.Now; it gets the current time of the date and time.
A DateTime doesnt have a format - it's just the date/time. (Whether it's local time, UTC or whatever is a different matter, mind you.)
Firstly, you shouldn't be converting to and from text like you are: that's just a recipe for trouble. Just use:
c.RegistrationDate = now;
... performing any rounding you need to.
You haven't shown how you're trying to insert the value into your database. If you're including the value in the SQL statement directly, that would explain it. You should be using a parameterized SQL statement and passing the value directly in the parameter - no conversion necessary.
If you're already doing that, please show us the code you're trying to use to insert the data, and we'll see what we can do. See the documentation for some examples.
I don't think there is anything wrong with the c# code,except I assume you must be doing
string dateAdded = DateTime.Now.ToString(format);
Otherwise I am not sure what 'now' is.