Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added a method SaveOrUpdate to create new Excel file, new worksheet b…

…ut it is not yet functional
  • Loading branch information...
commit 8cc58db5d38c4cb0d489dc4ef6b0546572ce6637 1 parent 3636db3
Shashank Shetty shashankshetty authored
BIN  lib/ExcelToDTOMapper.DTO.dll
View
Binary file not shown
2  src/BuildDTOsFromExcel/Program.cs
View
@@ -46,7 +46,7 @@ private static void DisplayUsage()
public class DefaultSettings
{
public static string AssemblyName = "ExcelToDTOMapper.DTO";
- public static string SuccessMessage = "Successfully created the assembly";
public static string ErrorMessage = "Error in processing. See log for details";
+ public static string SuccessMessage = "Successfully created the assembly";
}
}
6 src/ExcelMapper.Tests/ExcelMapper.Tests.csproj
View
@@ -59,6 +59,10 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\Rhino.Mocks.dll</HintPath>
</Reference>
+ <Reference Include="StructureMap, Version=2.5.4.0, Culture=neutral, PublicKeyToken=e60ad81abae3c223, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\lib\StructureMap.dll</HintPath>
+ </Reference>
<Reference Include="StructureMap.AutoMocking, Version=2.5.3.0, Culture=neutral, PublicKeyToken=e60ad81abae3c223, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\StructureMap.AutoMocking.dll</HintPath>
@@ -83,7 +87,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repository\Connection\ConnectionStringTests.cs" />
<Compile Include="Repository\Connection\ConnectionTests.cs" />
- <Compile Include="Repository\OleDBDataProviderTests.cs" />
+ <Compile Include="Repository\OleDbDataProviderTests.cs" />
<Compile Include="Repository\ExcelRepositoryTests.cs" />
<Compile Include="TestData.cs" />
</ItemGroup>
176 src/ExcelMapper.Tests/Repository/ExcelRepositoryTests.cs
View
@@ -1,59 +1,141 @@
using System;
using System.Collections.Generic;
using System.Linq;
-
+using ExcelMapper.Configuration;
using ExcelMapper.Repository;
using ExcelMapper.Tests.DTO;
-
using NUnit.Framework;
-
using Rhino.Mocks;
-
using StructureMap.AutoMocking;
namespace ExcelMapper.Tests.Repository
{
- public class ExcelRepositoryTests
- {
- [TestFixture]
- public class When_asked_to_retrieve_an_entity_from_an_Excel_file
- {
- private IDataProvider _dataProvider;
- private DateTime _fileModifiedDate;
- private IFileService _fileService;
- private IRepository _repository;
- private List<User> _users;
-
- [SetUp]
- public void SetUp()
- {
- _users = new List<User>
- {
- new User
- {
- Id = 1,
- LastName = "LastName",
- FirstName = "FirstName"
- }
- };
- _fileModifiedDate = Convert.ToDateTime("1/1/2009");
-
- var autoMocker = new RhinoAutoMocker<ExcelRepository>();
- _fileService = autoMocker.Get<IFileService>();
- _dataProvider = autoMocker.Get<IDataProvider>();
- _repository = autoMocker.ClassUnderTest;
-
- _fileService.Expect(x => x.GetLastModifiedDate("")).IgnoreArguments().Return(_fileModifiedDate).Repeat.Any();
- _dataProvider.Expect(x => x.Get<User>("")).IgnoreArguments().Return(_users);
- }
-
- [Test]
- public void Should_get_the_values_from_cache_or_file()
- {
- var result = _repository.Get<User>("").ToList();
- result = _repository.Get<User>("").ToList();
- Assert.AreEqual(_users.Count, result.Count);
- }
- }
- }
+ public class ExcelRepositoryTests
+ {
+ [TestFixture]
+ public class When_asked_to_retrieve_an_entity_from_an_Excel_file
+ {
+ private IDataProvider _dataProvider;
+ private DateTime _fileModifiedDate;
+ private IFileService _fileService;
+ private IRepository _repository;
+ private List<User> _users;
+
+ [SetUp]
+ public void SetUp()
+ {
+ _users = new List<User>
+ {
+ new User
+ {
+ Id = 1,
+ LastName = "LastName",
+ FirstName = "FirstName"
+ }
+ };
+ _fileModifiedDate = Convert.ToDateTime("1/1/2009");
+
+ var autoMocker = new RhinoAutoMocker<ExcelRepository>();
+ _fileService = autoMocker.Get<IFileService>();
+ _dataProvider = autoMocker.Get<IDataProvider>();
+ _repository = autoMocker.ClassUnderTest;
+
+ _fileService.Expect(x => x.GetLastModifiedDate("")).IgnoreArguments().Return(_fileModifiedDate).Repeat.
+ Any();
+ _dataProvider.Expect(x => x.Get<User>("")).IgnoreArguments().Return(_users);
+ }
+
+
+ [Test]
+ public void Should_get_the_values_from_cache_or_file()
+ {
+ List<User> result = _repository.Get<User>("").ToList();
+ result = _repository.Get<User>("").ToList();
+ Assert.AreEqual(_users.Count, result.Count);
+ }
+ }
+
+ [TestFixture]
+ public class When_asked_to_SaveOrUpdate_an_entity_into_an_excel_file
+ {
+ private const string Testfile = "TestFile";
+ private IDataProvider _dataProvider;
+ private IRepository _excelRepository;
+ private IFileConfiguration _fileConfiguration;
+ private IFileService _fileService;
+ private List<User> _users;
+
+ [SetUp]
+ public void SetUp()
+ {
+ _users = new List<User>
+ {
+ new User
+ {
+ Id = 1,
+ LastName = "LastName",
+ FirstName = "FirstName"
+ }
+ };
+ Convert.ToDateTime("1/1/2009");
+
+ var autoMocker = new RhinoAutoMocker<ExcelRepository>();
+ _fileService = autoMocker.Get<IFileService>();
+ _dataProvider = autoMocker.Get<IDataProvider>();
+ _excelRepository = autoMocker.ClassUnderTest;
+ _fileConfiguration = autoMocker.Get<IFileConfiguration>();
+
+ _fileConfiguration.Expect(x => x.FileName).Return(Testfile).Repeat.Any();
+ }
+
+ [Test]
+ public void Should_create_an_Excel_file_if_it_doesnot_exist()
+ {
+ _fileService.Expect(x => x.Exists(Testfile)).Return(false);
+ _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string>());
+ _excelRepository.SaveOrUpdate(_users);
+ _fileService.AssertWasCalled(x => x.Create(Testfile));
+ }
+
+ [Test]
+ public void Should_create_an_Excel_file_if_it_exists()
+ {
+ _fileService.Expect(x => x.Exists(Testfile)).Return(true);
+ _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string>());
+
+ _excelRepository.SaveOrUpdate(_users);
+ _fileService.AssertWasNotCalled(x => x.Create(Testfile));
+ }
+
+ [Test]
+ public void Should_create_the_WorkSheet_if_it_doesnot_exist()
+ {
+ _fileService.Expect(x => x.Exists(Testfile)).Return(true);
+ _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string>());
+
+ _excelRepository.SaveOrUpdate(_users);
+ _dataProvider.AssertWasCalled(x => x.CreateTable<User>());
+ }
+
+ [Test]
+ public void Should_not_create_the_WorkSheet_if_it_exists()
+ {
+ _fileService.Expect(x => x.Exists(Testfile)).Return(true);
+ _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string> {typeof (User).Name});
+
+ _excelRepository.SaveOrUpdate(_users);
+ _dataProvider.AssertWasNotCalled(x => x.CreateTable<User>());
+ }
+
+ [Test]
+ public void Should_save_the_values_in_to_excel()
+ {
+ _fileService.Expect(x => x.Exists(Testfile)).Return(true);
+ _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string> {typeof (User).Name});
+
+ _excelRepository.SaveOrUpdate(_users);
+ _dataProvider.AssertWasCalled(x => x.Put(_users));
+ }
+ }
+ }
}
308 src/ExcelMapper.Tests/Repository/OleDBDataProviderTests.cs
View
@@ -1,157 +1,177 @@
using System;
using System.Collections.Generic;
using System.Linq;
-
using ExcelMapper.Configuration;
using ExcelMapper.Repository;
using ExcelMapper.Repository.Connection;
using ExcelMapper.Tests.DTO;
-
using NUnit.Framework;
-
using Rhino.Mocks;
+using RunTimeCodeGenerator.ClassGeneration;
namespace ExcelMapper.Tests.Repository
{
- public class OleDBDataProviderTests
- {
- public class OleDBDataProviderTestsBase
- {
- private IConnectionString _connectionString;
- protected IDataProvider _dataProvider;
- protected IFileConfiguration _fileConfiguration;
-
- protected string _workSheetName;
- protected string _xlsFile;
- protected string _xlsxFile;
-
- [SetUp]
- public void SetUp()
- {
- _connectionString = MockRepository.GenerateMock<IConnectionString>();
- _fileConfiguration = MockRepository.GenerateMock<IFileConfiguration>();
-
- _dataProvider = new OleDbDataProvider(new ConnectionBuilder(_connectionString), _fileConfiguration);
-
- _xlsxFile = TestData.UsersXlsx;
- _xlsFile = TestData.UsersXls;
- _workSheetName = "User";
-
- _connectionString.Expect(x => x.Get(_xlsxFile)).Return(TestData.UsersXlsxConnectionString);
- _connectionString.Expect(x => x.Get(_xlsFile)).Return(TestData.UsersXlsConnectionString);
- }
- }
-
- [TestFixture]
- public class When_asked_for_the_list_of_worksheets_in_the_given_Excel_File : OleDBDataProviderTestsBase
- {
- [Test]
- public void Should_return_a_list_of_WorkSheet_names()
- {
- _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
- List<string> workSheets = _dataProvider.GetTableNames().ToList();
- Assert.IsTrue(workSheets.Count == 3);
- Assert.IsTrue(workSheets.Exists(x => x.Equals(String.Format("{0}$", _workSheetName))));
- }
- }
-
- [TestFixture]
- public class When_asked_to_get_a_list_of_DTOs_for_the_given_type_from_Excel : OleDBDataProviderTestsBase
- {
- [Test]
- public void Should_map_the_excel_columns_to_the_given_DTO_type()
- {
- _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
- User expectedUser = TestData.GetUsers(_xlsxFile, _workSheetName).FirstOrDefault();
- User actualUser = _dataProvider.Get<User>(_workSheetName).FirstOrDefault();
-
- Assert.IsNotNull(actualUser);
-
- Assert.AreEqual(expectedUser.Id, actualUser.Id);
- Assert.AreEqual(expectedUser.FirstName, actualUser.FirstName);
- Assert.AreEqual(expectedUser.DateOfBirth, actualUser.DateOfBirth);
- Assert.AreEqual(expectedUser.LastName, actualUser.LastName);
- }
-
- [Test]
- public void Should_return_DTO_objects_for_each_row_in_the_Xls_worksheet()
- {
- _fileConfiguration.Expect(x => x.FileName).Return(_xlsFile);
- List<User> expectedUsers = TestData.GetUsers(_xlsFile, _workSheetName).ToList();
- List<User> actualUsers = _dataProvider.Get<User>(_workSheetName).ToList();
- Assert.IsNotNull(actualUsers);
- Assert.AreEqual(expectedUsers.Count, actualUsers.Count);
- }
-
- [Test]
- public void Should_return_DTO_objects_for_each_row_in_the_Xlsx_worksheet()
- {
- _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
- List<User> expectedUsers = TestData.GetUsers(_xlsxFile, _workSheetName).ToList();
- List<User> actualUsers = _dataProvider.Get<User>(_workSheetName).ToList();
- Assert.IsNotNull(actualUsers);
- Assert.AreEqual(expectedUsers.Count, actualUsers.Count);
- }
- }
-
- [TestFixture]
- public class When_asked_to_get_the_column_headers_for_a_given_WorkSheet : OleDBDataProviderTestsBase
- {
- [Test]
- public void Should_return_all_the_column_headers_with_type_in_the_worksheet()
- {
- _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
- var columns = _dataProvider.GetColumns(String.Format("{0}$", _workSheetName)).ToList();
- Assert.IsFalse(columns.Any(x => x.Name == null));
- Assert.IsFalse(columns.Any(x => x.Type == null));
- }
-
- [Test]
- public void Should_return_all_the_column_in_the_worksheet()
- {
- _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
- var columns = _dataProvider.GetColumns(String.Format("{0}$", _workSheetName)).ToList();
- Assert.IsNotNull(columns);
- Assert.IsTrue(columns.Count == 4);
- }
- }
-
- [TestFixture]
- public class When_asked_to_insert_a_list_of_DTOs_into_an_Excel : OleDBDataProviderTestsBase
- {
- [Test]
- public void Should_insert_the_values_in_to_the_Xls_worksheet()
- {
- _fileConfiguration.Expect(x => x.FileName).Return(_xlsFile);
- List<User> users = new List<User>
- {
- new User
- {
- Id = 5,
- FirstName = "John",
- LastName = "Doe",
- DateOfBirth = Convert.ToDateTime("1/1/2008")
- }
- };
- _dataProvider.Put(users);
- }
-
- [Test]
- public void Should_insert_the_values_in_to_the_Xlsx_worksheet()
- {
- _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
- List<User> users = new List<User>
- {
- new User
- {
- Id = 5,
- FirstName = "John",
- LastName = "Doe",
- DateOfBirth = Convert.ToDateTime("1/1/2008")
- }
- };
- _dataProvider.Put(users);
- }
- }
- }
+ public class OleDbDataProviderTests
+ {
+ public class OleDbDataProviderTestsBase
+ {
+ private IConnectionString _connectionString;
+ protected IDataProvider _dataProvider;
+ protected IFileConfiguration _fileConfiguration;
+
+ protected string _workSheetName;
+ protected string _xlsFile;
+ protected string _xlsxFile;
+
+
+ [SetUp]
+ public void SetUp()
+ {
+ _connectionString = MockRepository.GenerateMock<IConnectionString>();
+ _fileConfiguration = MockRepository.GenerateMock<IFileConfiguration>();
+ _dataProvider = new OleDbDataProvider(new ConnectionBuilder(_connectionString), _fileConfiguration);
+
+ _xlsxFile = TestData.UsersXlsx;
+ _xlsFile = TestData.UsersXls;
+ _workSheetName = "User";
+
+ _connectionString.Expect(x => x.Get(_xlsxFile)).Return(TestData.UsersXlsxConnectionString).Repeat.Any();
+ _connectionString.Expect(x => x.Get(_xlsFile)).Return(TestData.UsersXlsConnectionString).Repeat.Any();
+ }
+ }
+
+ [TestFixture]
+ public class When_asked_for_the_list_of_worksheets_in_the_given_Excel_File : OleDbDataProviderTestsBase
+ {
+ [Test]
+ public void Should_return_a_list_of_WorkSheet_names()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
+ List<string> workSheets = _dataProvider.GetTableNames().ToList();
+ Assert.IsTrue(workSheets.Count == 3);
+ Assert.IsTrue(workSheets.Exists(x => x.Equals(String.Format("{0}$", _workSheetName))));
+ }
+ }
+
+ [TestFixture]
+ public class When_asked_to_get_a_list_of_DTOs_for_the_given_type_from_Excel : OleDbDataProviderTestsBase
+ {
+ [Test]
+ public void Should_map_the_excel_columns_to_the_given_DTO_type()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
+ User expectedUser = TestData.GetUsers(_xlsxFile, _workSheetName).FirstOrDefault();
+ User actualUser = _dataProvider.Get<User>(_workSheetName).FirstOrDefault();
+
+ Assert.IsNotNull(actualUser);
+
+ Assert.AreEqual(expectedUser.Id, actualUser.Id);
+ Assert.AreEqual(expectedUser.FirstName, actualUser.FirstName);
+ Assert.AreEqual(expectedUser.DateOfBirth, actualUser.DateOfBirth);
+ Assert.AreEqual(expectedUser.LastName, actualUser.LastName);
+ }
+
+ [Test]
+ public void Should_return_DTO_objects_for_each_row_in_the_Xls_worksheet()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsFile);
+ List<User> expectedUsers = TestData.GetUsers(_xlsFile, _workSheetName).ToList();
+ List<User> actualUsers = _dataProvider.Get<User>(_workSheetName).ToList();
+ Assert.IsNotNull(actualUsers);
+ Assert.AreEqual(expectedUsers.Count, actualUsers.Count);
+ }
+
+ [Test]
+ public void Should_return_DTO_objects_for_each_row_in_the_Xlsx_worksheet()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
+ List<User> expectedUsers = TestData.GetUsers(_xlsxFile, _workSheetName).ToList();
+ List<User> actualUsers = _dataProvider.Get<User>(_workSheetName).ToList();
+ Assert.IsNotNull(actualUsers);
+ Assert.AreEqual(expectedUsers.Count, actualUsers.Count);
+ }
+ }
+
+
+ [TestFixture]
+ public class When_asked_to_create_a_new_table : OleDbDataProviderTestsBase
+ {
+ [Test]
+ public void Should_create_a_new_WorkSheet_in_the_given_file()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile).Repeat.Any();
+ _dataProvider.CreateTable<Demo>();
+ IEnumerable<string> tableNames = _dataProvider.GetTableNames();
+ Assert.IsTrue(tableNames.Any(x => x == typeof (Demo).Name));
+ }
+
+ public class Demo
+ {
+ public int Id { get; set; }
+ public string Name { get; set; }
+ public DateTime StartDate { get; set; }
+ public decimal StartValue { get; set; }
+ }
+ }
+
+ [TestFixture]
+ public class When_asked_to_get_the_column_headers_for_a_given_WorkSheet : OleDbDataProviderTestsBase
+ {
+ [Test]
+ public void Should_return_all_the_column_headers_with_type_in_the_worksheet()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
+ List<Property> columns = _dataProvider.GetColumns(String.Format("{0}$", _workSheetName)).ToList();
+ Assert.IsFalse(columns.Any(x => x.Name == null));
+ Assert.IsFalse(columns.Any(x => x.Type == null));
+ }
+
+ [Test]
+ public void Should_return_all_the_column_in_the_worksheet()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
+ List<Property> columns = _dataProvider.GetColumns(String.Format("{0}$", _workSheetName)).ToList();
+ Assert.IsNotNull(columns);
+ Assert.IsTrue(columns.Count == 4);
+ }
+ }
+
+ [TestFixture]
+ public class When_asked_to_insert_a_list_of_DTOs_into_an_Excel : OleDbDataProviderTestsBase
+ {
+ [Test]
+ public void Should_insert_the_values_in_to_the_Xls_worksheet()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsFile);
+ var users = new List<User>
+ {
+ new User
+ {
+ Id = 5,
+ FirstName = "John",
+ LastName = "Doe",
+ DateOfBirth = Convert.ToDateTime("1/1/2008")
+ }
+ };
+ _dataProvider.Put(users);
+ }
+
+ [Test]
+ public void Should_insert_the_values_in_to_the_Xlsx_worksheet()
+ {
+ _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
+ var users = new List<User>
+ {
+ new User
+ {
+ Id = 5,
+ FirstName = "John",
+ LastName = "Doe",
+ DateOfBirth = Convert.ToDateTime("1/1/2008")
+ }
+ };
+ _dataProvider.Put(users);
+ }
+ }
+ }
}
2  src/ExcelMapper/ExcelMapper.csproj
View
@@ -85,6 +85,8 @@
<Compile Include="Repository\ExcelRepository.cs" />
<Compile Include="Repository\Extensions\DataReaderExtensions.cs" />
<Compile Include="Repository\FileService.cs" />
+ <Compile Include="Repository\IDataProvider.cs" />
+ <Compile Include="Repository\IFileService.cs" />
<Compile Include="Repository\IRepository.cs" />
<Compile Include="Repository\OleDbDataProvider.cs" />
<Compile Include="Repository\StringExtensions.cs" />
2  src/ExcelMapper/Repository/Connection/ConnectionBuilder.cs
View
@@ -13,7 +13,7 @@ public ConnectionBuilder(IConnectionString connectionString)
public OleDbConnection GetConnection(string file)
{
- OleDbConnection connection = new OleDbConnection(_connectionString.Get(file));
+ var connection = new OleDbConnection(_connectionString.Get(file));
connection.Open();
return connection;
}
136 src/ExcelMapper/Repository/ExcelRepository.cs
View
@@ -1,80 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
-
using ExcelMapper.Configuration;
-
using RunTimeCodeGenerator.ClassGeneration;
namespace ExcelMapper.Repository
{
- public class ExcelRepository : IRepository
- {
- private readonly IDataProvider _dataProvider;
- private readonly IFileConfiguration _fileConfiguration;
- private readonly IFileService _fileService;
- private readonly Dictionary<string, CacheValue> _resultCache;
+ public class ExcelRepository : IRepository
+ {
+ private readonly IDataProvider _dataProvider;
+ private readonly IFileConfiguration _fileConfiguration;
+ private readonly IFileService _fileService;
+ private readonly Dictionary<string, CacheValue> _resultCache;
+
+ public ExcelRepository(IDataProvider dataProvider, IFileConfiguration fileConfiguration,
+ IFileService fileService)
+ {
+ _dataProvider = dataProvider;
+ _fileService = fileService;
+ _fileConfiguration = fileConfiguration;
+ _resultCache = new Dictionary<string, CacheValue>();
+ }
- public ExcelRepository(IDataProvider dataProvider, IFileConfiguration fileConfiguration, IFileService fileService)
- {
- _dataProvider = dataProvider;
- _fileService = fileService;
- _fileConfiguration = fileConfiguration;
- _resultCache = new Dictionary<string, CacheValue>();
- }
+ public IEnumerable<string> GetWorkSheetNames()
+ {
+ return _dataProvider.GetTableNames();
+ }
- public IEnumerable<string> GetWorkSheetNames()
- {
- return _dataProvider.GetTableNames();
- }
+ public ClassAttributes GetDTOClassAttributes(string workSheet)
+ {
+ var classAttributes = new ClassAttributes(workSheet.GetClassName());
+ classAttributes.Properties.AddRange(_dataProvider.GetColumns(workSheet));
+ return classAttributes;
+ }
- public ClassAttributes GetDTOClassAttributes(string workSheet)
- {
- ClassAttributes classAttributes = new ClassAttributes(workSheet.GetClassName());
- classAttributes.Properties.AddRange(_dataProvider.GetColumns(workSheet));
- return classAttributes;
- }
+ public IEnumerable<T> Get<T>(string workSheet)
+ {
+ CacheValue cacheValue;
+ if (!_resultCache.TryGetValue(workSheet, out cacheValue))
+ {
+ cacheValue = AddToCache<T>(workSheet);
+ }
- public IEnumerable<T> Get<T>(string workSheet)
- {
- CacheValue cacheValue;
- if (!_resultCache.TryGetValue(workSheet, out cacheValue))
- {
- cacheValue = AddToCache<T>(workSheet);
- }
+ if (cacheValue.LastModifiedDate != GetLastModifiedDate())
+ {
+ _resultCache.Remove(workSheet);
+ cacheValue = AddToCache<T>(workSheet);
+ }
- if (cacheValue.LastModifiedDate != GetLastModifiedDate())
- {
- _resultCache.Remove(workSheet);
- cacheValue = AddToCache<T>(workSheet);
- }
+ var resultList = (IEnumerable<T>) cacheValue.Result;
+ foreach (T result in resultList)
+ {
+ yield return result;
+ }
+ }
- IEnumerable<T> resultList = (IEnumerable<T>)cacheValue.Result;
- foreach (T result in resultList)
- {
- yield return result;
- }
- }
+ public void Update<T>(IEnumerable<T> values)
+ {
+ _dataProvider.Put(values);
+ }
- public void Put<T>(IEnumerable<T> values)
- {
- _dataProvider.Put(values);
- }
+ public void SaveOrUpdate<T>(IEnumerable<T> values)
+ {
+ if (!_fileService.Exists(_fileConfiguration.FileName))
+ {
+ _fileService.Create(_fileConfiguration.FileName);
+ }
+ if (!_dataProvider.GetTableNames().Where(x => x == typeof(T).Name).Any())
+ {
+ _dataProvider.CreateTable<T>();
+ }
+ _dataProvider.Put(values);
+ }
- private CacheValue AddToCache<T>(string workSheet)
- {
- CacheValue cacheValue = new CacheValue
- {
- Result = _dataProvider.Get<T>(workSheet).ToList(),
- LastModifiedDate = GetLastModifiedDate()
- };
- _resultCache.Add(workSheet, cacheValue);
- return cacheValue;
- }
+ private CacheValue AddToCache<T>(string workSheet)
+ {
+ var cacheValue = new CacheValue
+ {
+ Result = _dataProvider.Get<T>(workSheet).ToList(),
+ LastModifiedDate = GetLastModifiedDate()
+ };
+ _resultCache.Add(workSheet, cacheValue);
+ return cacheValue;
+ }
- private DateTime GetLastModifiedDate()
- {
- return _fileService.GetLastModifiedDate(_fileConfiguration.FileName);
- }
- }
+ private DateTime GetLastModifiedDate()
+ {
+ return _fileService.GetLastModifiedDate(_fileConfiguration.FileName);
+ }
+ }
}
34 src/ExcelMapper/Repository/FileService.cs
View
@@ -3,25 +3,21 @@
namespace ExcelMapper.Repository
{
- public interface IFileService
- {
- void CreateNewIfNotExists(string filePath);
- DateTime GetLastModifiedDate(string filePath);
- }
+ public class FileService : IFileService
+ {
+ public bool Exists(string filePath)
+ {
+ return File.Exists(filePath);
+ }
- public class FileService : IFileService
- {
- public void CreateNewIfNotExists(string filePath)
- {
- if (!File.Exists(filePath))
- {
- File.Create(filePath);
- }
- }
+ public void Create(string filePath)
+ {
+ File.Create(filePath);
+ }
- public DateTime GetLastModifiedDate(string filePath)
- {
- return File.GetLastWriteTime(filePath);
- }
- }
+ public DateTime GetLastModifiedDate(string filePath)
+ {
+ return File.GetLastWriteTime(filePath);
+ }
+ }
}
4 src/ExcelMapper/Repository/IRepository.cs
View
@@ -1,5 +1,4 @@
using System.Collections.Generic;
-
using RunTimeCodeGenerator.ClassGeneration;
namespace ExcelMapper.Repository
@@ -9,6 +8,7 @@ public interface IRepository
IEnumerable<string> GetWorkSheetNames();
ClassAttributes GetDTOClassAttributes(string workSheet);
IEnumerable<T> Get<T>(string workSheet);
- void Put<T>(IEnumerable<T> values);
+ void Update<T>(IEnumerable<T> values);
+ void SaveOrUpdate<T>(IEnumerable<T> values);
}
}
243 src/ExcelMapper/Repository/OleDbDataProvider.cs
View
@@ -5,128 +5,151 @@
using System.Linq;
using System.Reflection;
using System.Text;
-
using ExcelMapper.Configuration;
using ExcelMapper.Repository.Connection;
-
using RunTimeCodeGenerator.ClassGeneration;
namespace ExcelMapper.Repository
{
- public interface IDataProvider
- {
- IEnumerable<string> GetTableNames();
- IEnumerable<Property> GetColumns(string workSheet);
- IEnumerable<T> Get<T>(string workSheet);
- void Put<T>(IEnumerable<T> values);
- }
+ public class OleDbDataProvider : IDataProvider
+ {
+ private readonly IConnectionBuilder _connectionBuilder;
+ private readonly IFileConfiguration _fileConfiguration;
+
+ public OleDbDataProvider(IConnectionBuilder connectionBuilder, IFileConfiguration fileConfiguration)
+ {
+ _connectionBuilder = connectionBuilder;
+ _fileConfiguration = fileConfiguration;
+ }
+
+ public IEnumerable<string> GetTableNames()
+ {
+ using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
+ {
+ DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
+ if (schemaTable != null)
+ {
+ for (int i = 0; i < schemaTable.Rows.Count; i++)
+ {
+ yield return schemaTable.Rows[i]["TABLE_NAME"].ToString();
+ }
+ }
+ }
+ }
+
+ public IEnumerable<Property> GetColumns(string workSheet)
+ {
+ using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
+ {
+ using (OleDbCommand command = connection.CreateCommand())
+ {
+ command.CommandText = String.Format("SELECT * FROM [{0}]", workSheet);
+ using (OleDbDataReader reader = command.ExecuteReader())
+ {
+ if (reader.Read())
+ {
+ for (int i = 0; i < reader.FieldCount; i++)
+ {
+ yield return new Property(reader.GetFieldType(i).ToString(),
+ reader.GetName(i));
+ }
+ }
+ }
+ }
+ }
+ }
- public class OleDbDataProvider : IDataProvider
- {
- private readonly IConnectionBuilder _connectionBuilder;
- private readonly IFileConfiguration _fileConfiguration;
+ public IEnumerable<T> Get<T>(string workSheet)
+ {
+ using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
+ {
+ using (OleDbCommand command = connection.CreateCommand())
+ {
+ command.CommandText = String.Format("SELECT * FROM [{0}$]", workSheet);
+ using (OleDbDataReader reader = command.ExecuteReader())
+ {
+ PropertyInfo[] properties = typeof (T).GetProperties();
- public OleDbDataProvider(IConnectionBuilder connectionBuilder, IFileConfiguration fileConfiguration)
- {
- _connectionBuilder = connectionBuilder;
- _fileConfiguration = fileConfiguration;
- }
+ while (reader.Read())
+ {
+ var instance = Activator.CreateInstance<T>();
+ for (int i = 0; i < reader.FieldCount; i++)
+ {
+ int index = i;
+ PropertyInfo property = properties.Single(p => p.Name.Equals(reader.GetName(index)));
+ property.SetValue(instance, reader.GetValue(i), null);
+ }
+ yield return instance;
+ }
+ }
+ }
+ }
+ }
- public IEnumerable<string> GetTableNames()
- {
- using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
- {
- DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
- if (schemaTable != null)
- {
- for (int i = 0; i < schemaTable.Rows.Count; i++)
- {
- yield return schemaTable.Rows[i]["TABLE_NAME"].ToString();
- }
- }
- }
- }
+ public void Put<T>(IEnumerable<T> values)
+ {
+ PropertyInfo[] properties = typeof (T).GetProperties();
+ string query = String.Format("INSERT INTO [{0}$] VALUES ({1})", typeof (T).Name,
+ ConstructQueryValues(properties.Length));
+ using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
+ {
+ using (OleDbCommand command = connection.CreateCommand())
+ {
+ command.CommandText = query;
+ foreach (T value in values)
+ {
+ foreach (PropertyInfo property in properties)
+ {
+ command.Parameters.AddWithValue(property.Name, property.GetValue(value, null));
+ }
+ command.ExecuteNonQuery();
+ }
+ }
+ }
+ }
- public IEnumerable<Property> GetColumns(string workSheet)
- {
- using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
- {
- using (OleDbCommand command = connection.CreateCommand())
- {
- command.CommandText = String.Format("SELECT * FROM [{0}]", workSheet);
- using (OleDbDataReader reader = command.ExecuteReader())
- {
- if (reader.Read())
- {
- for (int i = 0; i < reader.FieldCount; i++)
- {
- yield return new Property(reader.GetFieldType(i).ToString(),
- reader.GetName(i));
- }
- }
- }
- }
- }
- }
+ public void CreateTable<T>()
+ {
+ PropertyInfo[] properties = typeof (T).GetProperties();
+ var tableColumns = new StringBuilder();
+ const string separator = ", ";
- public IEnumerable<T> Get<T>(string workSheet)
- {
- using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
- {
- using (OleDbCommand command = connection.CreateCommand())
- {
- command.CommandText = String.Format("SELECT * FROM [{0}$]", workSheet);
- using (OleDbDataReader reader = command.ExecuteReader())
- {
- PropertyInfo[] properties = typeof(T).GetProperties();
+ foreach (PropertyInfo property in properties)
+ {
+ tableColumns.AppendFormat("{0} {1}{2}", property.Name, property.PropertyType.GetPropertyType(),
+ separator);
+ }
+ tableColumns.Remove(tableColumns.Length - separator.Length, separator.Length);
- while (reader.Read())
- {
- T instance = Activator.CreateInstance<T>();
- for (int i = 0; i < reader.FieldCount; i++)
- {
- int index = i;
- PropertyInfo property = properties.Single(p => p.Name.Equals(reader.GetName(index)));
- property.SetValue(instance, reader.GetValue(i), null);
- }
- yield return instance;
- }
- }
- }
- }
- }
+ string query = String.Format("CREATE TABLE {0} ({1})", typeof (T).Name, tableColumns);
+ using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
+ {
+ using (OleDbCommand command = connection.CreateCommand())
+ {
+ command.CommandText = query;
+ command.ExecuteNonQuery();
+ }
+ }
+ }
- public void Put<T>(IEnumerable<T> values)
- {
- PropertyInfo[] properties = typeof(T).GetProperties();
- string query = String.Format("INSERT INTO [{0}$] VALUES ({1})", typeof(T).Name,
- ConstructQueryValues(properties.Length));
- using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
- {
- using (OleDbCommand command = connection.CreateCommand())
- {
- command.CommandText = query;
- foreach (var value in values)
- {
- foreach (var property in properties)
- {
- command.Parameters.AddWithValue(property.Name, property.GetValue(value, null));
- }
- command.ExecuteNonQuery();
- }
- }
- }
- }
+ private static string ConstructQueryValues(int length)
+ {
+ var query = new StringBuilder();
+ for (int i = 0; i < length - 1; i++)
+ {
+ query.Append("?, ");
+ }
+ query.Append("?");
+ return query.ToString();
+ }
+ }
- private static string ConstructQueryValues(int length)
- {
- StringBuilder query = new StringBuilder();
- for (int i = 0; i < length - 1; i++)
- {
- query.Append("?, ");
- }
- query.Append("?");
- return query.ToString();
- }
- }
+ public static class PropertyTypeExtensions
+ {
+ public static string GetPropertyType(this Type propertyType)
+ {
+ const string integerType = "Int";
+ return propertyType.Name.Contains(integerType) ? integerType : propertyType.Name;
+ }
+ }
}
95 src/Samples.Tests/ReadWriteExistingExcelFileTests.cs
View
@@ -0,0 +1,95 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using ExcelMapper.Configuration;
+using ExcelMapper.Repository;
+using ExcelToDTOMapper.DTO.Users;
+using Microsoft.Practices.ServiceLocation;
+using NUnit.Framework;
+
+namespace Samples.Tests
+{
+ [TestFixture]
+ public class ReadWriteExistingExcelFileTests
+ {
+ private IRepository _repository;
+ private const string UserFile = "Excel\\Users.xlsx";
+ private const string DemoWorkSheetFile = "Excel\\DemoWorkSheet.xlsx";
+
+ [SetUp]
+ public void BeforeEachTest()
+ {
+ File.Delete(DemoWorkSheetFile);
+ ExcelMapper.Configuration.ExcelMapper.SetUp();
+ _repository = ServiceLocator.Current.GetInstance<IRepository>();
+ }
+
+ public class DemoWorkSheet
+ {
+ public int Id { get; set; }
+ public string Name { get; set; }
+ public DateTime StartDate { get; set; }
+ public decimal StartValue { get; set; }
+ }
+
+ [Test]
+ public void ReadFromExcel()
+ {
+ ServiceLocator.Current.GetInstance<IFileConfiguration>().FileName = UserFile;
+ foreach (User user in _repository.Get<User>("User"))
+ {
+ Console.WriteLine("Hello {0} {1}", user.FirstName, user.LastName);
+ }
+ }
+
+ [Test]
+ public void WriteToExcel()
+ {
+ ServiceLocator.Current.GetInstance<IFileConfiguration>().FileName = DemoWorkSheetFile;
+ var expectedDemoWorkSheet = new DemoWorkSheet
+ {
+ Id = 8,
+ Name = "John Doe",
+ StartDate = Convert.ToDateTime("2/2/1990"),
+ StartValue = 10.0m,
+ };
+ var demoWorkSheets = new List<DemoWorkSheet>
+ {
+ expectedDemoWorkSheet
+ };
+
+ _repository.SaveOrUpdate(demoWorkSheets);
+
+ DemoWorkSheet actualDemoWorkSheet = _repository.Get<DemoWorkSheet>(typeof(DemoWorkSheet).Name).Where(x => x.Id == expectedDemoWorkSheet.Id).First();
+ Assert.IsNotNull(actualDemoWorkSheet);
+ Assert.AreEqual(expectedDemoWorkSheet.Name, actualDemoWorkSheet.Name);
+ Assert.AreEqual(expectedDemoWorkSheet.StartDate, actualDemoWorkSheet.StartDate);
+ Assert.AreEqual(expectedDemoWorkSheet.StartValue, actualDemoWorkSheet.StartValue);
+ }
+
+ [Test]
+ public void WriteToExistingExcel()
+ {
+ ServiceLocator.Current.GetInstance<IFileConfiguration>().FileName = UserFile;
+ var expectedUser = new User
+ {
+ Id = 8,
+ LastName = "Doe",
+ FirstName = "John",
+ DateOfBirth = Convert.ToDateTime("2/2/1990")
+ };
+ var users = new List<User>
+ {
+ expectedUser
+ };
+ _repository.Update(users);
+
+ User actualUser = _repository.Get<User>("User").Where(x => x.Id == expectedUser.Id).First();
+ Assert.IsNotNull(actualUser);
+ Assert.AreEqual(expectedUser.LastName, actualUser.LastName);
+ Assert.AreEqual(expectedUser.FirstName, actualUser.FirstName);
+ Assert.AreEqual(expectedUser.DateOfBirth, actualUser.DateOfBirth);
+ }
+ }
+}
63 src/Samples.Tests/ReadWriteTestsonExistingExcelFile.cs
View
@@ -1,63 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-
-using ExcelMapper.Configuration;
-using ExcelMapper.Repository;
-
-using ExcelToDTOMapper.DTO.Users;
-
-using Microsoft.Practices.ServiceLocation;
-
-using NUnit.Framework;
-
-namespace Samples.Tests
-{
- [TestFixture]
- public class ReadWriteExistingExcelFileTests
- {
- private IRepository _repository;
-
- [SetUp]
- public void BeforeEachTest()
- {
- const string file = "Excel\\Users.xlsx";
-
- ExcelMapper.Configuration.ExcelMapper.SetUp();
- ServiceLocator.Current.GetInstance<IFileConfiguration>().FileName = file;
- _repository = ServiceLocator.Current.GetInstance<IRepository>();
- }
-
- [Test]
- public void ReadFromExcel()
- {
- foreach (User user in _repository.Get<User>("User"))
- {
- Console.WriteLine("Hello {0} {1}", user.FirstName, user.LastName);
- }
- }
-
- [Test]
- public void WriteToExcel()
- {
- var expectedUser = new User
- {
- Id = 8,
- LastName = "Doe",
- FirstName = "John",
- DateOfBirth = Convert.ToDateTime("2/2/1990")
- };
- List<User> users = new List<User>
- {
- expectedUser
- };
- _repository.Put(users);
-
- var actualUser = _repository.Get<User>("User").Where(x => x.Id == 8).First();
- Assert.IsNotNull(actualUser);
- Assert.AreEqual(expectedUser.LastName, actualUser.LastName);
- Assert.AreEqual(expectedUser.FirstName, actualUser.FirstName);
- Assert.AreEqual(expectedUser.DateOfBirth, actualUser.DateOfBirth);
- }
- }
-}
2  src/Samples.Tests/Samples.Tests.csproj
View
@@ -57,7 +57,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
- <Compile Include="ReadWriteTestsonExistingExcelFile.cs" />
+ <Compile Include="ReadWriteExistingExcelFileTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
Please sign in to comment.
Something went wrong with that request. Please try again.