Skip to content
This repository has been archived by the owner on Dec 24, 2022. It is now read-only.

Issue #211: Ensure the DateTime is UTC #214

Merged
merged 2 commits into from
Apr 2, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ public override object ConvertDbValue(object value, Type type)
return dateTimeValue - timeSpanOffset; return dateTimeValue - timeSpanOffset;
} }


if (_ensureUtc && type == typeof (DateTime))
{
var result = base.ConvertDbValue(value, type);
if(result is DateTime)
return DateTime.SpecifyKind((DateTime)result, DateTimeKind.Utc);
return result;
}

if (type == typeof(byte[])) if (type == typeof(byte[]))
return value; return value;


Expand All @@ -111,7 +119,7 @@ public override object ConvertDbValue(object value, Type type)
} }




public override string GetQuotedValue(object value, Type fieldType) public override string GetQuotedValue(object value, Type fieldType)
{ {
if (value == null) return "NULL"; if (value == null) return "NULL";


Expand All @@ -122,7 +130,9 @@ public override string GetQuotedValue(object value, Type fieldType)
} }
if (fieldType == typeof(DateTime)) if (fieldType == typeof(DateTime))
{ {
var dateValue = (DateTime)value; var dateValue = (DateTime)value;
if (_ensureUtc && dateValue.Kind == DateTimeKind.Local)
dateValue = dateValue.ToUniversalTime();
const string iso8601Format = "yyyyMMdd HH:mm:ss.fff"; const string iso8601Format = "yyyyMMdd HH:mm:ss.fff";
return base.GetQuotedValue(dateValue.ToString(iso8601Format), typeof(string)); return base.GetQuotedValue(dateValue.ToString(iso8601Format), typeof(string));
} }
Expand All @@ -143,16 +153,22 @@ public override string GetQuotedValue(object value, Type fieldType)
return base.GetQuotedValue(value, fieldType); return base.GetQuotedValue(value, fieldType);




} }


protected bool _useDateTime2; protected bool _useDateTime2;
public void UseDatetime2(bool shouldUseDatetime2) public void UseDatetime2(bool shouldUseDatetime2)
{ {
_useDateTime2 = shouldUseDatetime2; _useDateTime2 = shouldUseDatetime2;
DateTimeColumnDefinition = shouldUseDatetime2 ? "datetime2" : "datetime"; DateTimeColumnDefinition = shouldUseDatetime2 ? "datetime2" : "datetime";
base.DbTypeMap.Set<DateTime>(shouldUseDatetime2 ? DbType.DateTime2 : DbType.DateTime, DateTimeColumnDefinition); base.DbTypeMap.Set<DateTime>(shouldUseDatetime2 ? DbType.DateTime2 : DbType.DateTime, DateTimeColumnDefinition);
base.DbTypeMap.Set<DateTime?>(shouldUseDatetime2 ? DbType.DateTime2 : DbType.DateTime, DateTimeColumnDefinition); base.DbTypeMap.Set<DateTime?>(shouldUseDatetime2 ? DbType.DateTime2 : DbType.DateTime, DateTimeColumnDefinition);
} }

protected bool _ensureUtc;
public void EnsureUtc(bool shouldEnsureUtc)
{
_ensureUtc = shouldEnsureUtc;
}


public override long GetLastInsertId(IDbCommand dbCmd) public override long GetLastInsertId(IDbCommand dbCmd)
{ {
Expand Down
52 changes: 52 additions & 0 deletions src/ServiceStack.OrmLite.SqlServerTests/EnsureUtcTest.cs
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using System.Data;
using System.Linq;
using NUnit.Framework;
using ServiceStack.OrmLite.SqlServer;

namespace ServiceStack.OrmLite.SqlServerTests
{
internal class EnsureUtcTests : OrmLiteTestBase
{
[Test]
public void SaveDateTimeToDatabase()
{
var dbFactory = new OrmLiteConnectionFactory(base.ConnectionString, SqlServerOrmLiteDialectProvider.Instance);
SqlServerOrmLiteDialectProvider.Instance.EnsureUtc(true);

using (var db = dbFactory.OpenDbConnection())
{
var dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Local);
var x = InsertAndSelectDateTime(db, dateTime);
Assert.AreEqual(DateTimeKind.Utc, x.Test.Kind);
Assert.AreEqual(x.Test.ToUniversalTime(), dateTime.ToUniversalTime());
Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime());

dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Utc);
x = InsertAndSelectDateTime(db, dateTime);
Assert.AreEqual(DateTimeKind.Utc, x.Test.Kind);
Assert.AreEqual(x.Test.ToUniversalTime(), dateTime.ToUniversalTime());
Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime());

dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Unspecified);
x = InsertAndSelectDateTime(db, dateTime);
Assert.AreEqual(DateTimeKind.Utc, x.Test.Kind);
Assert.AreEqual(x.Test.ToUniversalTime(), dateTime);
Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime());
}
}

private static DateTimeObject InsertAndSelectDateTime(IDbConnection db, DateTime dateTime)
{
db.DropAndCreateTable<DateTimeObject>();
db.Insert(new DateTimeObject {Test = dateTime});
var x = db.Select<DateTimeObject>().First();
return x;
}

private class DateTimeObject
{
public DateTime Test { get; set; }
}
}
}
Original file line number Original file line Diff line number Diff line change
@@ -1,107 +1,108 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion> <ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{96793C11-2A99-4217-8946-3E0DB9534A4D}</ProjectGuid> <ProjectGuid>{96793C11-2A99-4217-8946-3E0DB9534A4D}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ServiceStack.OrmLite.SqlServerTests</RootNamespace> <RootNamespace>ServiceStack.OrmLite.SqlServerTests</RootNamespace>
<AssemblyName>ServiceStack.OrmLite.SqlServerTests</AssemblyName> <AssemblyName>ServiceStack.OrmLite.SqlServerTests</AssemblyName>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="nunit.framework"> <Reference Include="nunit.framework">
<HintPath>..\..\lib\tests\nunit.framework.dll</HintPath> <HintPath>..\..\lib\tests\nunit.framework.dll</HintPath>
</Reference> </Reference>
<Reference Include="ServiceStack.Common"> <Reference Include="ServiceStack.Common">
<HintPath>..\..\lib\ServiceStack.Common.dll</HintPath> <HintPath>..\..\lib\ServiceStack.Common.dll</HintPath>
</Reference> </Reference>
<Reference Include="ServiceStack.Interfaces"> <Reference Include="ServiceStack.Interfaces">
<HintPath>..\..\lib\ServiceStack.Interfaces.dll</HintPath> <HintPath>..\..\lib\ServiceStack.Interfaces.dll</HintPath>
</Reference> </Reference>
<Reference Include="ServiceStack.Text"> <Reference Include="ServiceStack.Text">
<HintPath>..\..\lib\ServiceStack.Text.dll</HintPath> <HintPath>..\..\lib\ServiceStack.Text.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" /> <Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.configuration" /> <Reference Include="System.configuration" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Datetime2Tests.cs" /> <Compile Include="Datetime2Tests.cs" />
<Compile Include="InsertParam_GetLastInsertId.cs" /> <Compile Include="EnsureUtcTest.cs" />
<Compile Include="NestedTransactions.cs" /> <Compile Include="InsertParam_GetLastInsertId.cs" />
<Compile Include="EnumTests.cs" /> <Compile Include="NestedTransactions.cs" />
<Compile Include="Expressions\AdditiveExpressionsTest.cs" /> <Compile Include="EnumTests.cs" />
<Compile Include="Expressions\Author.cs" /> <Compile Include="Expressions\AdditiveExpressionsTest.cs" />
<Compile Include="Expressions\AuthorUseCase.cs" /> <Compile Include="Expressions\Author.cs" />
<Compile Include="Expressions\ConditionalExpressionTest.cs" /> <Compile Include="Expressions\AuthorUseCase.cs" />
<Compile Include="Expressions\EqualityExpressionsTest.cs" /> <Compile Include="Expressions\ConditionalExpressionTest.cs" />
<Compile Include="Expressions\ExpressionsTestBase.cs" /> <Compile Include="Expressions\EqualityExpressionsTest.cs" />
<Compile Include="Expressions\LogicalExpressionsTest.cs" /> <Compile Include="Expressions\ExpressionsTestBase.cs" />
<Compile Include="Expressions\MultiplicativeExpressionsTest.cs" /> <Compile Include="Expressions\LogicalExpressionsTest.cs" />
<Compile Include="Expressions\OrmLiteCountTests.cs" /> <Compile Include="Expressions\MultiplicativeExpressionsTest.cs" />
<Compile Include="Expressions\PrimaryExpressionsTest.cs" /> <Compile Include="Expressions\OrmLiteCountTests.cs" />
<Compile Include="Expressions\RelationalExpressionsTest.cs" /> <Compile Include="Expressions\PrimaryExpressionsTest.cs" />
<Compile Include="Expressions\StringFunctionTests.cs" /> <Compile Include="Expressions\RelationalExpressionsTest.cs" />
<Compile Include="Expressions\TestType.cs" /> <Compile Include="Expressions\StringFunctionTests.cs" />
<Compile Include="Expressions\UnaryExpressionsTest.cs" /> <Compile Include="Expressions\TestType.cs" />
<Compile Include="ForeignKeyAttributeTests.cs" /> <Compile Include="Expressions\UnaryExpressionsTest.cs" />
<Compile Include="OrmLiteTestBase.cs" /> <Compile Include="ForeignKeyAttributeTests.cs" />
<Compile Include="SqlServerExpressionVisitorQueryTest.cs" /> <Compile Include="OrmLiteTestBase.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="SqlServerExpressionVisitorQueryTest.cs" />
<Compile Include="TypeWithByteArrayFieldTests.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UnicodeTests.cs" /> <Compile Include="TypeWithByteArrayFieldTests.cs" />
<Compile Include="UpdateTests.cs" /> <Compile Include="UnicodeTests.cs" />
<Compile Include="UseCase\SimpleUseCase.cs" /> <Compile Include="UpdateTests.cs" />
<Compile Include="UseCase\TestEntity.cs" /> <Compile Include="UseCase\SimpleUseCase.cs" />
</ItemGroup> <Compile Include="UseCase\TestEntity.cs" />
<ItemGroup> </ItemGroup>
<ProjectReference Include="..\ServiceStack.OrmLite.SqlServer\ServiceStack.OrmLite.SqlServer.csproj"> <ItemGroup>
<Project>{1887DC99-9139-43E3-A7AA-6D74714B3A5D}</Project> <ProjectReference Include="..\ServiceStack.OrmLite.SqlServer\ServiceStack.OrmLite.SqlServer.csproj">
<Name>ServiceStack.OrmLite.SqlServer</Name> <Project>{1887DC99-9139-43E3-A7AA-6D74714B3A5D}</Project>
</ProjectReference> <Name>ServiceStack.OrmLite.SqlServer</Name>
<ProjectReference Include="..\ServiceStack.OrmLite\ServiceStack.OrmLite.csproj"> </ProjectReference>
<Project>{96179AC6-F6F1-40C3-9FDD-4F6582F54C5C}</Project> <ProjectReference Include="..\ServiceStack.OrmLite\ServiceStack.OrmLite.csproj">
<Name>ServiceStack.OrmLite</Name> <Project>{96179AC6-F6F1-40C3-9FDD-4F6582F54C5C}</Project>
</ProjectReference> <Name>ServiceStack.OrmLite</Name>
</ItemGroup> </ProjectReference>
<ItemGroup> </ItemGroup>
<None Include="app.config"> <ItemGroup>
<SubType>Designer</SubType> <None Include="app.config">
</None> <SubType>Designer</SubType>
</ItemGroup> </None>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">
</Target> </Target>
<Target Name="AfterBuild"> <Target Name="AfterBuild">
</Target> </Target>
--> -->
</Project> </Project>