Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
Binary file not shown
2  src/BuildDTOsFromExcel/Program.cs
@@ -46,7 +46,7 @@ private static void DisplayUsage()
46 46 public class DefaultSettings
47 47 {
48 48 public static string AssemblyName = "ExcelToDTOMapper.DTO";
49   - public static string SuccessMessage = "Successfully created the assembly";
50 49 public static string ErrorMessage = "Error in processing. See log for details";
  50 + public static string SuccessMessage = "Successfully created the assembly";
51 51 }
52 52 }
6 src/ExcelMapper.Tests/ExcelMapper.Tests.csproj
@@ -59,6 +59,10 @@
59 59 <SpecificVersion>False</SpecificVersion>
60 60 <HintPath>..\..\lib\Rhino.Mocks.dll</HintPath>
61 61 </Reference>
  62 + <Reference Include="StructureMap, Version=2.5.4.0, Culture=neutral, PublicKeyToken=e60ad81abae3c223, processorArchitecture=MSIL">
  63 + <SpecificVersion>False</SpecificVersion>
  64 + <HintPath>..\..\lib\StructureMap.dll</HintPath>
  65 + </Reference>
62 66 <Reference Include="StructureMap.AutoMocking, Version=2.5.3.0, Culture=neutral, PublicKeyToken=e60ad81abae3c223, processorArchitecture=MSIL">
63 67 <SpecificVersion>False</SpecificVersion>
64 68 <HintPath>..\..\lib\StructureMap.AutoMocking.dll</HintPath>
@@ -83,7 +87,7 @@
83 87 <Compile Include="Properties\AssemblyInfo.cs" />
84 88 <Compile Include="Repository\Connection\ConnectionStringTests.cs" />
85 89 <Compile Include="Repository\Connection\ConnectionTests.cs" />
86   - <Compile Include="Repository\OleDBDataProviderTests.cs" />
  90 + <Compile Include="Repository\OleDbDataProviderTests.cs" />
87 91 <Compile Include="Repository\ExcelRepositoryTests.cs" />
88 92 <Compile Include="TestData.cs" />
89 93 </ItemGroup>
176 src/ExcelMapper.Tests/Repository/ExcelRepositoryTests.cs
... ... @@ -1,59 +1,141 @@
1 1 using System;
2 2 using System.Collections.Generic;
3 3 using System.Linq;
4   -
  4 +using ExcelMapper.Configuration;
5 5 using ExcelMapper.Repository;
6 6 using ExcelMapper.Tests.DTO;
7   -
8 7 using NUnit.Framework;
9   -
10 8 using Rhino.Mocks;
11   -
12 9 using StructureMap.AutoMocking;
13 10
14 11 namespace ExcelMapper.Tests.Repository
15 12 {
16   - public class ExcelRepositoryTests
17   - {
18   - [TestFixture]
19   - public class When_asked_to_retrieve_an_entity_from_an_Excel_file
20   - {
21   - private IDataProvider _dataProvider;
22   - private DateTime _fileModifiedDate;
23   - private IFileService _fileService;
24   - private IRepository _repository;
25   - private List<User> _users;
26   -
27   - [SetUp]
28   - public void SetUp()
29   - {
30   - _users = new List<User>
31   - {
32   - new User
33   - {
34   - Id = 1,
35   - LastName = "LastName",
36   - FirstName = "FirstName"
37   - }
38   - };
39   - _fileModifiedDate = Convert.ToDateTime("1/1/2009");
40   -
41   - var autoMocker = new RhinoAutoMocker<ExcelRepository>();
42   - _fileService = autoMocker.Get<IFileService>();
43   - _dataProvider = autoMocker.Get<IDataProvider>();
44   - _repository = autoMocker.ClassUnderTest;
45   -
46   - _fileService.Expect(x => x.GetLastModifiedDate("")).IgnoreArguments().Return(_fileModifiedDate).Repeat.Any();
47   - _dataProvider.Expect(x => x.Get<User>("")).IgnoreArguments().Return(_users);
48   - }
49   -
50   - [Test]
51   - public void Should_get_the_values_from_cache_or_file()
52   - {
53   - var result = _repository.Get<User>("").ToList();
54   - result = _repository.Get<User>("").ToList();
55   - Assert.AreEqual(_users.Count, result.Count);
56   - }
57   - }
58   - }
  13 + public class ExcelRepositoryTests
  14 + {
  15 + [TestFixture]
  16 + public class When_asked_to_retrieve_an_entity_from_an_Excel_file
  17 + {
  18 + private IDataProvider _dataProvider;
  19 + private DateTime _fileModifiedDate;
  20 + private IFileService _fileService;
  21 + private IRepository _repository;
  22 + private List<User> _users;
  23 +
  24 + [SetUp]
  25 + public void SetUp()
  26 + {
  27 + _users = new List<User>
  28 + {
  29 + new User
  30 + {
  31 + Id = 1,
  32 + LastName = "LastName",
  33 + FirstName = "FirstName"
  34 + }
  35 + };
  36 + _fileModifiedDate = Convert.ToDateTime("1/1/2009");
  37 +
  38 + var autoMocker = new RhinoAutoMocker<ExcelRepository>();
  39 + _fileService = autoMocker.Get<IFileService>();
  40 + _dataProvider = autoMocker.Get<IDataProvider>();
  41 + _repository = autoMocker.ClassUnderTest;
  42 +
  43 + _fileService.Expect(x => x.GetLastModifiedDate("")).IgnoreArguments().Return(_fileModifiedDate).Repeat.
  44 + Any();
  45 + _dataProvider.Expect(x => x.Get<User>("")).IgnoreArguments().Return(_users);
  46 + }
  47 +
  48 +
  49 + [Test]
  50 + public void Should_get_the_values_from_cache_or_file()
  51 + {
  52 + List<User> result = _repository.Get<User>("").ToList();
  53 + result = _repository.Get<User>("").ToList();
  54 + Assert.AreEqual(_users.Count, result.Count);
  55 + }
  56 + }
  57 +
  58 + [TestFixture]
  59 + public class When_asked_to_SaveOrUpdate_an_entity_into_an_excel_file
  60 + {
  61 + private const string Testfile = "TestFile";
  62 + private IDataProvider _dataProvider;
  63 + private IRepository _excelRepository;
  64 + private IFileConfiguration _fileConfiguration;
  65 + private IFileService _fileService;
  66 + private List<User> _users;
  67 +
  68 + [SetUp]
  69 + public void SetUp()
  70 + {
  71 + _users = new List<User>
  72 + {
  73 + new User
  74 + {
  75 + Id = 1,
  76 + LastName = "LastName",
  77 + FirstName = "FirstName"
  78 + }
  79 + };
  80 + Convert.ToDateTime("1/1/2009");
  81 +
  82 + var autoMocker = new RhinoAutoMocker<ExcelRepository>();
  83 + _fileService = autoMocker.Get<IFileService>();
  84 + _dataProvider = autoMocker.Get<IDataProvider>();
  85 + _excelRepository = autoMocker.ClassUnderTest;
  86 + _fileConfiguration = autoMocker.Get<IFileConfiguration>();
  87 +
  88 + _fileConfiguration.Expect(x => x.FileName).Return(Testfile).Repeat.Any();
  89 + }
  90 +
  91 + [Test]
  92 + public void Should_create_an_Excel_file_if_it_doesnot_exist()
  93 + {
  94 + _fileService.Expect(x => x.Exists(Testfile)).Return(false);
  95 + _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string>());
  96 + _excelRepository.SaveOrUpdate(_users);
  97 + _fileService.AssertWasCalled(x => x.Create(Testfile));
  98 + }
  99 +
  100 + [Test]
  101 + public void Should_create_an_Excel_file_if_it_exists()
  102 + {
  103 + _fileService.Expect(x => x.Exists(Testfile)).Return(true);
  104 + _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string>());
  105 +
  106 + _excelRepository.SaveOrUpdate(_users);
  107 + _fileService.AssertWasNotCalled(x => x.Create(Testfile));
  108 + }
  109 +
  110 + [Test]
  111 + public void Should_create_the_WorkSheet_if_it_doesnot_exist()
  112 + {
  113 + _fileService.Expect(x => x.Exists(Testfile)).Return(true);
  114 + _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string>());
  115 +
  116 + _excelRepository.SaveOrUpdate(_users);
  117 + _dataProvider.AssertWasCalled(x => x.CreateTable<User>());
  118 + }
  119 +
  120 + [Test]
  121 + public void Should_not_create_the_WorkSheet_if_it_exists()
  122 + {
  123 + _fileService.Expect(x => x.Exists(Testfile)).Return(true);
  124 + _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string> {typeof (User).Name});
  125 +
  126 + _excelRepository.SaveOrUpdate(_users);
  127 + _dataProvider.AssertWasNotCalled(x => x.CreateTable<User>());
  128 + }
  129 +
  130 + [Test]
  131 + public void Should_save_the_values_in_to_excel()
  132 + {
  133 + _fileService.Expect(x => x.Exists(Testfile)).Return(true);
  134 + _dataProvider.Expect(x => x.GetTableNames()).Return(new List<string> {typeof (User).Name});
  135 +
  136 + _excelRepository.SaveOrUpdate(_users);
  137 + _dataProvider.AssertWasCalled(x => x.Put(_users));
  138 + }
  139 + }
  140 + }
59 141 }
308 src/ExcelMapper.Tests/Repository/OleDBDataProviderTests.cs
... ... @@ -1,157 +1,177 @@
1 1 using System;
2 2 using System.Collections.Generic;
3 3 using System.Linq;
4   -
5 4 using ExcelMapper.Configuration;
6 5 using ExcelMapper.Repository;
7 6 using ExcelMapper.Repository.Connection;
8 7 using ExcelMapper.Tests.DTO;
9   -
10 8 using NUnit.Framework;
11   -
12 9 using Rhino.Mocks;
  10 +using RunTimeCodeGenerator.ClassGeneration;
13 11
14 12 namespace ExcelMapper.Tests.Repository
15 13 {
16   - public class OleDBDataProviderTests
17   - {
18   - public class OleDBDataProviderTestsBase
19   - {
20   - private IConnectionString _connectionString;
21   - protected IDataProvider _dataProvider;
22   - protected IFileConfiguration _fileConfiguration;
23   -
24   - protected string _workSheetName;
25   - protected string _xlsFile;
26   - protected string _xlsxFile;
27   -
28   - [SetUp]
29   - public void SetUp()
30   - {
31   - _connectionString = MockRepository.GenerateMock<IConnectionString>();
32   - _fileConfiguration = MockRepository.GenerateMock<IFileConfiguration>();
33   -
34   - _dataProvider = new OleDbDataProvider(new ConnectionBuilder(_connectionString), _fileConfiguration);
35   -
36   - _xlsxFile = TestData.UsersXlsx;
37   - _xlsFile = TestData.UsersXls;
38   - _workSheetName = "User";
39   -
40   - _connectionString.Expect(x => x.Get(_xlsxFile)).Return(TestData.UsersXlsxConnectionString);
41   - _connectionString.Expect(x => x.Get(_xlsFile)).Return(TestData.UsersXlsConnectionString);
42   - }
43   - }
44   -
45   - [TestFixture]
46   - public class When_asked_for_the_list_of_worksheets_in_the_given_Excel_File : OleDBDataProviderTestsBase
47   - {
48   - [Test]
49   - public void Should_return_a_list_of_WorkSheet_names()
50   - {
51   - _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
52   - List<string> workSheets = _dataProvider.GetTableNames().ToList();
53   - Assert.IsTrue(workSheets.Count == 3);
54   - Assert.IsTrue(workSheets.Exists(x => x.Equals(String.Format("{0}$", _workSheetName))));
55   - }
56   - }
57   -
58   - [TestFixture]
59   - public class When_asked_to_get_a_list_of_DTOs_for_the_given_type_from_Excel : OleDBDataProviderTestsBase
60   - {
61   - [Test]
62   - public void Should_map_the_excel_columns_to_the_given_DTO_type()
63   - {
64   - _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
65   - User expectedUser = TestData.GetUsers(_xlsxFile, _workSheetName).FirstOrDefault();
66   - User actualUser = _dataProvider.Get<User>(_workSheetName).FirstOrDefault();
67   -
68   - Assert.IsNotNull(actualUser);
69   -
70   - Assert.AreEqual(expectedUser.Id, actualUser.Id);
71   - Assert.AreEqual(expectedUser.FirstName, actualUser.FirstName);
72   - Assert.AreEqual(expectedUser.DateOfBirth, actualUser.DateOfBirth);
73   - Assert.AreEqual(expectedUser.LastName, actualUser.LastName);
74   - }
75   -
76   - [Test]
77   - public void Should_return_DTO_objects_for_each_row_in_the_Xls_worksheet()
78   - {
79   - _fileConfiguration.Expect(x => x.FileName).Return(_xlsFile);
80   - List<User> expectedUsers = TestData.GetUsers(_xlsFile, _workSheetName).ToList();
81   - List<User> actualUsers = _dataProvider.Get<User>(_workSheetName).ToList();
82   - Assert.IsNotNull(actualUsers);
83   - Assert.AreEqual(expectedUsers.Count, actualUsers.Count);
84   - }
85   -
86   - [Test]
87   - public void Should_return_DTO_objects_for_each_row_in_the_Xlsx_worksheet()
88   - {
89   - _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
90   - List<User> expectedUsers = TestData.GetUsers(_xlsxFile, _workSheetName).ToList();
91   - List<User> actualUsers = _dataProvider.Get<User>(_workSheetName).ToList();
92   - Assert.IsNotNull(actualUsers);
93   - Assert.AreEqual(expectedUsers.Count, actualUsers.Count);
94   - }
95   - }
96   -
97   - [TestFixture]
98   - public class When_asked_to_get_the_column_headers_for_a_given_WorkSheet : OleDBDataProviderTestsBase
99   - {
100   - [Test]
101   - public void Should_return_all_the_column_headers_with_type_in_the_worksheet()
102   - {
103   - _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
104   - var columns = _dataProvider.GetColumns(String.Format("{0}$", _workSheetName)).ToList();
105   - Assert.IsFalse(columns.Any(x => x.Name == null));
106   - Assert.IsFalse(columns.Any(x => x.Type == null));
107   - }
108   -
109   - [Test]
110   - public void Should_return_all_the_column_in_the_worksheet()
111   - {
112   - _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
113   - var columns = _dataProvider.GetColumns(String.Format("{0}$", _workSheetName)).ToList();
114   - Assert.IsNotNull(columns);
115   - Assert.IsTrue(columns.Count == 4);
116   - }
117   - }
118   -
119   - [TestFixture]
120   - public class When_asked_to_insert_a_list_of_DTOs_into_an_Excel : OleDBDataProviderTestsBase
121   - {
122   - [Test]
123   - public void Should_insert_the_values_in_to_the_Xls_worksheet()
124   - {
125   - _fileConfiguration.Expect(x => x.FileName).Return(_xlsFile);
126   - List<User> users = new List<User>
127   - {
128   - new User
129   - {
130   - Id = 5,
131   - FirstName = "John",
132   - LastName = "Doe",
133   - DateOfBirth = Convert.ToDateTime("1/1/2008")
134   - }
135   - };
136   - _dataProvider.Put(users);
137   - }
138   -
139   - [Test]
140   - public void Should_insert_the_values_in_to_the_Xlsx_worksheet()
141   - {
142   - _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
143   - List<User> users = new List<User>
144   - {
145   - new User
146   - {
147   - Id = 5,
148   - FirstName = "John",
149   - LastName = "Doe",
150   - DateOfBirth = Convert.ToDateTime("1/1/2008")
151   - }
152   - };
153   - _dataProvider.Put(users);
154   - }
155   - }
156   - }
  14 + public class OleDbDataProviderTests
  15 + {
  16 + public class OleDbDataProviderTestsBase
  17 + {
  18 + private IConnectionString _connectionString;
  19 + protected IDataProvider _dataProvider;
  20 + protected IFileConfiguration _fileConfiguration;
  21 +
  22 + protected string _workSheetName;
  23 + protected string _xlsFile;
  24 + protected string _xlsxFile;
  25 +
  26 +
  27 + [SetUp]
  28 + public void SetUp()
  29 + {
  30 + _connectionString = MockRepository.GenerateMock<IConnectionString>();
  31 + _fileConfiguration = MockRepository.GenerateMock<IFileConfiguration>();
  32 + _dataProvider = new OleDbDataProvider(new ConnectionBuilder(_connectionString), _fileConfiguration);
  33 +
  34 + _xlsxFile = TestData.UsersXlsx;
  35 + _xlsFile = TestData.UsersXls;
  36 + _workSheetName = "User";
  37 +
  38 + _connectionString.Expect(x => x.Get(_xlsxFile)).Return(TestData.UsersXlsxConnectionString).Repeat.Any();
  39 + _connectionString.Expect(x => x.Get(_xlsFile)).Return(TestData.UsersXlsConnectionString).Repeat.Any();
  40 + }
  41 + }
  42 +
  43 + [TestFixture]
  44 + public class When_asked_for_the_list_of_worksheets_in_the_given_Excel_File : OleDbDataProviderTestsBase
  45 + {
  46 + [Test]
  47 + public void Should_return_a_list_of_WorkSheet_names()
  48 + {
  49 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
  50 + List<string> workSheets = _dataProvider.GetTableNames().ToList();
  51 + Assert.IsTrue(workSheets.Count == 3);
  52 + Assert.IsTrue(workSheets.Exists(x => x.Equals(String.Format("{0}$", _workSheetName))));
  53 + }
  54 + }
  55 +
  56 + [TestFixture]
  57 + public class When_asked_to_get_a_list_of_DTOs_for_the_given_type_from_Excel : OleDbDataProviderTestsBase
  58 + {
  59 + [Test]
  60 + public void Should_map_the_excel_columns_to_the_given_DTO_type()
  61 + {
  62 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
  63 + User expectedUser = TestData.GetUsers(_xlsxFile, _workSheetName).FirstOrDefault();
  64 + User actualUser = _dataProvider.Get<User>(_workSheetName).FirstOrDefault();
  65 +
  66 + Assert.IsNotNull(actualUser);
  67 +
  68 + Assert.AreEqual(expectedUser.Id, actualUser.Id);
  69 + Assert.AreEqual(expectedUser.FirstName, actualUser.FirstName);
  70 + Assert.AreEqual(expectedUser.DateOfBirth, actualUser.DateOfBirth);
  71 + Assert.AreEqual(expectedUser.LastName, actualUser.LastName);
  72 + }
  73 +
  74 + [Test]
  75 + public void Should_return_DTO_objects_for_each_row_in_the_Xls_worksheet()
  76 + {
  77 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsFile);
  78 + List<User> expectedUsers = TestData.GetUsers(_xlsFile, _workSheetName).ToList();
  79 + List<User> actualUsers = _dataProvider.Get<User>(_workSheetName).ToList();
  80 + Assert.IsNotNull(actualUsers);
  81 + Assert.AreEqual(expectedUsers.Count, actualUsers.Count);
  82 + }
  83 +
  84 + [Test]
  85 + public void Should_return_DTO_objects_for_each_row_in_the_Xlsx_worksheet()
  86 + {
  87 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
  88 + List<User> expectedUsers = TestData.GetUsers(_xlsxFile, _workSheetName).ToList();
  89 + List<User> actualUsers = _dataProvider.Get<User>(_workSheetName).ToList();
  90 + Assert.IsNotNull(actualUsers);
  91 + Assert.AreEqual(expectedUsers.Count, actualUsers.Count);
  92 + }
  93 + }
  94 +
  95 +
  96 + [TestFixture]
  97 + public class When_asked_to_create_a_new_table : OleDbDataProviderTestsBase
  98 + {
  99 + [Test]
  100 + public void Should_create_a_new_WorkSheet_in_the_given_file()
  101 + {
  102 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile).Repeat.Any();
  103 + _dataProvider.CreateTable<Demo>();
  104 + IEnumerable<string> tableNames = _dataProvider.GetTableNames();
  105 + Assert.IsTrue(tableNames.Any(x => x == typeof (Demo).Name));
  106 + }
  107 +
  108 + public class Demo
  109 + {
  110 + public int Id { get; set; }
  111 + public string Name { get; set; }
  112 + public DateTime StartDate { get; set; }
  113 + public decimal StartValue { get; set; }
  114 + }
  115 + }
  116 +
  117 + [TestFixture]
  118 + public class When_asked_to_get_the_column_headers_for_a_given_WorkSheet : OleDbDataProviderTestsBase
  119 + {
  120 + [Test]
  121 + public void Should_return_all_the_column_headers_with_type_in_the_worksheet()
  122 + {
  123 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
  124 + List<Property> columns = _dataProvider.GetColumns(String.Format("{0}$", _workSheetName)).ToList();
  125 + Assert.IsFalse(columns.Any(x => x.Name == null));
  126 + Assert.IsFalse(columns.Any(x => x.Type == null));
  127 + }
  128 +
  129 + [Test]
  130 + public void Should_return_all_the_column_in_the_worksheet()
  131 + {
  132 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
  133 + List<Property> columns = _dataProvider.GetColumns(String.Format("{0}$", _workSheetName)).ToList();
  134 + Assert.IsNotNull(columns);
  135 + Assert.IsTrue(columns.Count == 4);
  136 + }
  137 + }
  138 +
  139 + [TestFixture]
  140 + public class When_asked_to_insert_a_list_of_DTOs_into_an_Excel : OleDbDataProviderTestsBase
  141 + {
  142 + [Test]
  143 + public void Should_insert_the_values_in_to_the_Xls_worksheet()
  144 + {
  145 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsFile);
  146 + var users = new List<User>
  147 + {
  148 + new User
  149 + {
  150 + Id = 5,
  151 + FirstName = "John",
  152 + LastName = "Doe",
  153 + DateOfBirth = Convert.ToDateTime("1/1/2008")
  154 + }
  155 + };
  156 + _dataProvider.Put(users);
  157 + }
  158 +
  159 + [Test]
  160 + public void Should_insert_the_values_in_to_the_Xlsx_worksheet()
  161 + {
  162 + _fileConfiguration.Expect(x => x.FileName).Return(_xlsxFile);
  163 + var users = new List<User>
  164 + {
  165 + new User
  166 + {
  167 + Id = 5,
  168 + FirstName = "John",
  169 + LastName = "Doe",
  170 + DateOfBirth = Convert.ToDateTime("1/1/2008")
  171 + }
  172 + };
  173 + _dataProvider.Put(users);
  174 + }
  175 + }
  176 + }
157 177 }
2  src/ExcelMapper/ExcelMapper.csproj
@@ -85,6 +85,8 @@
85 85 <Compile Include="Repository\ExcelRepository.cs" />
86 86 <Compile Include="Repository\Extensions\DataReaderExtensions.cs" />
87 87 <Compile Include="Repository\FileService.cs" />
  88 + <Compile Include="Repository\IDataProvider.cs" />
  89 + <Compile Include="Repository\IFileService.cs" />
88 90 <Compile Include="Repository\IRepository.cs" />
89 91 <Compile Include="Repository\OleDbDataProvider.cs" />
90 92 <Compile Include="Repository\StringExtensions.cs" />
2  src/ExcelMapper/Repository/Connection/ConnectionBuilder.cs
@@ -13,7 +13,7 @@ public ConnectionBuilder(IConnectionString connectionString)
13 13
14 14 public OleDbConnection GetConnection(string file)
15 15 {
16   - OleDbConnection connection = new OleDbConnection(_connectionString.Get(file));
  16 + var connection = new OleDbConnection(_connectionString.Get(file));
17 17 connection.Open();
18 18 return connection;
19 19 }
136 src/ExcelMapper/Repository/ExcelRepository.cs
... ... @@ -1,80 +1,92 @@
1 1 using System;
2 2 using System.Collections.Generic;
3 3 using System.Linq;
4   -
5 4 using ExcelMapper.Configuration;
6   -
7 5 using RunTimeCodeGenerator.ClassGeneration;
8 6
9 7 namespace ExcelMapper.Repository
10 8 {
11   - public class ExcelRepository : IRepository
12   - {
13   - private readonly IDataProvider _dataProvider;
14   - private readonly IFileConfiguration _fileConfiguration;
15   - private readonly IFileService _fileService;
16   - private readonly Dictionary<string, CacheValue> _resultCache;
  9 + public class ExcelRepository : IRepository
  10 + {
  11 + private readonly IDataProvider _dataProvider;
  12 + private readonly IFileConfiguration _fileConfiguration;
  13 + private readonly IFileService _fileService;
  14 + private readonly Dictionary<string, CacheValue> _resultCache;
  15 +
  16 + public ExcelRepository(IDataProvider dataProvider, IFileConfiguration fileConfiguration,
  17 + IFileService fileService)
  18 + {
  19 + _dataProvider = dataProvider;
  20 + _fileService = fileService;
  21 + _fileConfiguration = fileConfiguration;
  22 + _resultCache = new Dictionary<string, CacheValue>();
  23 + }
17 24
18   - public ExcelRepository(IDataProvider dataProvider, IFileConfiguration fileConfiguration, IFileService fileService)
19   - {
20   - _dataProvider = dataProvider;
21   - _fileService = fileService;
22   - _fileConfiguration = fileConfiguration;
23   - _resultCache = new Dictionary<string, CacheValue>();
24   - }
  25 + public IEnumerable<string> GetWorkSheetNames()
  26 + {
  27 + return _dataProvider.GetTableNames();
  28 + }
25 29
26   - public IEnumerable<string> GetWorkSheetNames()
27   - {
28   - return _dataProvider.GetTableNames();
29   - }
  30 + public ClassAttributes GetDTOClassAttributes(string workSheet)
  31 + {
  32 + var classAttributes = new ClassAttributes(workSheet.GetClassName());
  33 + classAttributes.Properties.AddRange(_dataProvider.GetColumns(workSheet));
  34 + return classAttributes;
  35 + }
30 36
31   - public ClassAttributes GetDTOClassAttributes(string workSheet)
32   - {
33   - ClassAttributes classAttributes = new ClassAttributes(workSheet.GetClassName());
34   - classAttributes.Properties.AddRange(_dataProvider.GetColumns(workSheet));
35   - return classAttributes;
36   - }
  37 + public IEnumerable<T> Get<T>(string workSheet)
  38 + {
  39 + CacheValue cacheValue;
  40 + if (!_resultCache.TryGetValue(workSheet, out cacheValue))
  41 + {
  42 + cacheValue = AddToCache<T>(workSheet);
  43 + }
37 44
38   - public IEnumerable<T> Get<T>(string workSheet)
39   - {
40   - CacheValue cacheValue;
41   - if (!_resultCache.TryGetValue(workSheet, out cacheValue))
42   - {
43   - cacheValue = AddToCache<T>(workSheet);
44   - }
  45 + if (cacheValue.LastModifiedDate != GetLastModifiedDate())
  46 + {
  47 + _resultCache.Remove(workSheet);
  48 + cacheValue = AddToCache<T>(workSheet);
  49 + }
45 50
46   - if (cacheValue.LastModifiedDate != GetLastModifiedDate())
47   - {
48   - _resultCache.Remove(workSheet);
49   - cacheValue = AddToCache<T>(workSheet);
50   - }
  51 + var resultList = (IEnumerable<T>) cacheValue.Result;
  52 + foreach (T result in resultList)
  53 + {
  54 + yield return result;
  55 + }
  56 + }
51 57
52   - IEnumerable<T> resultList = (IEnumerable<T>)cacheValue.Result;
53   - foreach (T result in resultList)
54   - {
55   - yield return result;
56   - }
57   - }
  58 + public void Update<T>(IEnumerable<T> values)
  59 + {
  60 + _dataProvider.Put(values);
  61 + }
58 62
59   - public void Put<T>(IEnumerable<T> values)
60   - {
61   - _dataProvider.Put(values);
62   - }
  63 + public void SaveOrUpdate<T>(IEnumerable<T> values)
  64 + {
  65 + if (!_fileService.Exists(_fileConfiguration.FileName))
  66 + {
  67 + _fileService.Create(_fileConfiguration.FileName);
  68 + }
  69 + if (!_dataProvider.GetTableNames().Where(x => x == typeof(T).Name).Any())
  70 + {
  71 + _dataProvider.CreateTable<T>();
  72 + }
  73 + _dataProvider.Put(values);
  74 + }
63 75
64   - private CacheValue AddToCache<T>(string workSheet)
65   - {
66   - CacheValue cacheValue = new CacheValue
67   - {
68   - Result = _dataProvider.Get<T>(workSheet).ToList(),
69   - LastModifiedDate = GetLastModifiedDate()
70   - };
71   - _resultCache.Add(workSheet, cacheValue);
72   - return cacheValue;
73   - }
  76 + private CacheValue AddToCache<T>(string workSheet)
  77 + {
  78 + var cacheValue = new CacheValue
  79 + {
  80 + Result = _dataProvider.Get<T>(workSheet).ToList(),
  81 + LastModifiedDate = GetLastModifiedDate()
  82 + };
  83 + _resultCache.Add(workSheet, cacheValue);
  84 + return cacheValue;
  85 + }
74 86
75   - private DateTime GetLastModifiedDate()
76   - {
77   - return _fileService.GetLastModifiedDate(_fileConfiguration.FileName);
78   - }
79   - }
  87 + private DateTime GetLastModifiedDate()
  88 + {
  89 + return _fileService.GetLastModifiedDate(_fileConfiguration.FileName);
  90 + }
  91 + }
80 92 }
34 src/ExcelMapper/Repository/FileService.cs
@@ -3,25 +3,21 @@
3 3
4 4 namespace ExcelMapper.Repository
5 5 {
6   - public interface IFileService
7   - {
8   - void CreateNewIfNotExists(string filePath);
9   - DateTime GetLastModifiedDate(string filePath);
10   - }
  6 + public class FileService : IFileService
  7 + {
  8 + public bool Exists(string filePath)
  9 + {
  10 + return File.Exists(filePath);
  11 + }
11 12
12   - public class FileService : IFileService
13   - {
14   - public void CreateNewIfNotExists(string filePath)
15   - {
16   - if (!File.Exists(filePath))
17   - {
18   - File.Create(filePath);
19   - }
20   - }
  13 + public void Create(string filePath)
  14 + {
  15 + File.Create(filePath);
  16 + }
21 17
22   - public DateTime GetLastModifiedDate(string filePath)
23   - {
24   - return File.GetLastWriteTime(filePath);
25   - }
26   - }
  18 + public DateTime GetLastModifiedDate(string filePath)
  19 + {
  20 + return File.GetLastWriteTime(filePath);
  21 + }
  22 + }
27 23 }
4 src/ExcelMapper/Repository/IRepository.cs
... ... @@ -1,5 +1,4 @@
1 1 using System.Collections.Generic;
2   -
3 2 using RunTimeCodeGenerator.ClassGeneration;
4 3
5 4 namespace ExcelMapper.Repository
@@ -9,6 +8,7 @@ public interface IRepository
9 8 IEnumerable<string> GetWorkSheetNames();
10 9 ClassAttributes GetDTOClassAttributes(string workSheet);
11 10 IEnumerable<T> Get<T>(string workSheet);
12   - void Put<T>(IEnumerable<T> values);
  11 + void Update<T>(IEnumerable<T> values);
  12 + void SaveOrUpdate<T>(IEnumerable<T> values);
13 13 }
14 14 }
243 src/ExcelMapper/Repository/OleDbDataProvider.cs
@@ -5,128 +5,151 @@
5 5 using System.Linq;
6 6 using System.Reflection;
7 7 using System.Text;
8   -
9 8 using ExcelMapper.Configuration;
10 9 using ExcelMapper.Repository.Connection;
11   -
12 10 using RunTimeCodeGenerator.ClassGeneration;
13 11
14 12 namespace ExcelMapper.Repository
15 13 {
16   - public interface IDataProvider
17   - {
18   - IEnumerable<string> GetTableNames();
19   - IEnumerable<Property> GetColumns(string workSheet);
20   - IEnumerable<T> Get<T>(string workSheet);
21   - void Put<T>(IEnumerable<T> values);
22   - }
  14 + public class OleDbDataProvider : IDataProvider
  15 + {
  16 + private readonly IConnectionBuilder _connectionBuilder;
  17 + private readonly IFileConfiguration _fileConfiguration;
  18 +
  19 + public OleDbDataProvider(IConnectionBuilder connectionBuilder, IFileConfiguration fileConfiguration)
  20 + {
  21 + _connectionBuilder = connectionBuilder;
  22 + _fileConfiguration = fileConfiguration;
  23 + }
  24 +
  25 + public IEnumerable<string> GetTableNames()
  26 + {
  27 + using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
  28 + {
  29 + DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
  30 + if (schemaTable != null)
  31 + {
  32 + for (int i = 0; i < schemaTable.Rows.Count; i++)
  33 + {
  34 + yield return schemaTable.Rows[i]["TABLE_NAME"].ToString();
  35 + }
  36 + }
  37 + }
  38 + }
  39 +
  40 + public IEnumerable<Property> GetColumns(string workSheet)
  41 + {
  42 + using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
  43 + {
  44 + using (OleDbCommand command = connection.CreateCommand())
  45 + {
  46 + command.CommandText = String.Format("SELECT * FROM [{0}]", workSheet);
  47 + using (OleDbDataReader reader = command.ExecuteReader())
  48 + {
  49 + if (reader.Read())
  50 + {
  51 + for (int i = 0; i < reader.FieldCount; i++)
  52 + {
  53 + yield return new Property(reader.GetFieldType(i).ToString(),
  54 + reader.GetName(i));
  55 + }
  56 + }
  57 + }
  58 + }
  59 + }
  60 + }
23 61
24   - public class OleDbDataProvider : IDataProvider
25   - {
26   - private readonly IConnectionBuilder _connectionBuilder;
27   - private readonly IFileConfiguration _fileConfiguration;
  62 + public IEnumerable<T> Get<T>(string workSheet)
  63 + {
  64 + using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
  65 + {
  66 + using (OleDbCommand command = connection.CreateCommand())
  67 + {
  68 + command.CommandText = String.Format("SELECT * FROM [{0}$]", workSheet);
  69 + using (OleDbDataReader reader = command.ExecuteReader())
  70 + {
  71 + PropertyInfo[] properties = typeof (T).GetProperties();
28 72
29   - public OleDbDataProvider(IConnectionBuilder connectionBuilder, IFileConfiguration fileConfiguration)
30   - {
31   - _connectionBuilder = connectionBuilder;
32   - _fileConfiguration = fileConfiguration;
33   - }
  73 + while (reader.Read())
  74 + {
  75 + var instance = Activator.CreateInstance<T>();
  76 + for (int i = 0; i < reader.FieldCount; i++)
  77 + {
  78 + int index = i;
  79 + PropertyInfo property = properties.Single(p => p.Name.Equals(reader.GetName(index)));
  80 + property.SetValue(instance, reader.GetValue(i), null);
  81 + }
  82 + yield return instance;
  83 + }
  84 + }
  85 + }
  86 + }
  87 + }
34 88
35   - public IEnumerable<string> GetTableNames()
36   - {
37   - using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
38   - {
39   - DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
40   - if (schemaTable != null)
41   - {
42   - for (int i = 0; i < schemaTable.Rows.Count; i++)
43   - {
44   - yield return schemaTable.Rows[i]["TABLE_NAME"].ToString();
45   - }
46   - }
47   - }
48   - }
  89 + public void Put<T>(IEnumerable<T> values)
  90 + {
  91 + PropertyInfo[] properties = typeof (T).GetProperties();
  92 + string query = String.Format("INSERT INTO [{0}$] VALUES ({1})", typeof (T).Name,
  93 + ConstructQueryValues(properties.Length));
  94 + using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
  95 + {
  96 + using (OleDbCommand command = connection.CreateCommand())
  97 + {
  98 + command.CommandText = query;
  99 + foreach (T value in values)
  100 + {
  101 + foreach (PropertyInfo property in properties)
  102 + {
  103 + command.Parameters.AddWithValue(property.Name, property.GetValue(value, null));
  104 + }
  105 + command.ExecuteNonQuery();
  106 + }
  107 + }
  108 + }
  109 + }
49 110
50   - public IEnumerable<Property> GetColumns(string workSheet)
51   - {
52   - using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
53   - {
54   - using (OleDbCommand command = connection.CreateCommand())
55   - {
56   - command.CommandText = String.Format("SELECT * FROM [{0}]", workSheet);
57   - using (OleDbDataReader reader = command.ExecuteReader())
58   - {
59   - if (reader.Read())
60   - {
61   - for (int i = 0; i < reader.FieldCount; i++)
62   - {
63   - yield return new Property(reader.GetFieldType(i).ToString(),
64   - reader.GetName(i));
65   - }
66   - }
67   - }
68   - }
69   - }
70   - }
  111 + public void CreateTable<T>()
  112 + {
  113 + PropertyInfo[] properties = typeof (T).GetProperties();
  114 + var tableColumns = new StringBuilder();
  115 + const string separator = ", ";
71 116
72   - public IEnumerable<T> Get<T>(string workSheet)
73   - {
74   - using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
75   - {
76   - using (OleDbCommand command = connection.CreateCommand())
77   - {
78   - command.CommandText = String.Format("SELECT * FROM [{0}$]", workSheet);
79   - using (OleDbDataReader reader = command.ExecuteReader())
80   - {
81   - PropertyInfo[] properties = typeof(T).GetProperties();
  117 + foreach (PropertyInfo property in properties)
  118 + {
  119 + tableColumns.AppendFormat("{0} {1}{2}", property.Name, property.PropertyType.GetPropertyType(),
  120 + separator);
  121 + }
  122 + tableColumns.Remove(tableColumns.Length - separator.Length, separator.Length);
82 123
83   - while (reader.Read())
84   - {
85   - T instance = Activator.CreateInstance<T>();
86   - for (int i = 0; i < reader.FieldCount; i++)
87   - {
88   - int index = i;
89   - PropertyInfo property = properties.Single(p => p.Name.Equals(reader.GetName(index)));
90   - property.SetValue(instance, reader.GetValue(i), null);
91   - }
92   - yield return instance;
93   - }
94   - }
95   - }
96   - }
97   - }
  124 + string query = String.Format("CREATE TABLE {0} ({1})", typeof (T).Name, tableColumns);
  125 + using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
  126 + {
  127 + using (OleDbCommand command = connection.CreateCommand())
  128 + {
  129 + command.CommandText = query;
  130 + command.ExecuteNonQuery();
  131 + }
  132 + }
  133 + }
98 134
99   - public void Put<T>(IEnumerable<T> values)
100   - {
101   - PropertyInfo[] properties = typeof(T).GetProperties();
102   - string query = String.Format("INSERT INTO [{0}$] VALUES ({1})", typeof(T).Name,
103   - ConstructQueryValues(properties.Length));
104   - using (OleDbConnection connection = _connectionBuilder.GetConnection(_fileConfiguration.FileName))
105   - {
106   - using (OleDbCommand command = connection.CreateCommand())
107   - {
108   - command.CommandText = query;
109   - foreach (var value in values)
110   - {
111   - foreach (var property in properties)
112   - {
113   - command.Parameters.AddWithValue(property.Name, property.GetValue(value, null));
114   - }
115   - command.ExecuteNonQuery();
116   - }
117   - }
118   - }
119   - }
  135 + private static string ConstructQueryValues(int length)
  136 + {
  137 + var query = new StringBuilder();
  138 + for (int i = 0; i < length - 1; i++)
  139 + {
  140 + query.Append("?, ");
  141 + }
  142 + query.Append("?");
  143 + return query.ToString();
  144 + }
  145 + }
120 146
121   - private static string ConstructQueryValues(int length)
122   - {
123   - StringBuilder query = new StringBuilder();
124   - for (int i = 0; i < length - 1; i++)
125   - {
126   - query.Append("?, ");
127   - }
128   - query.Append("?");
129   - return query.ToString();
130   - }
131   - }
  147 + public static class PropertyTypeExtensions
  148 + {
  149 + public static string GetPropertyType(this Type propertyType)
  150 + {
  151 + const string integerType = "Int";
  152 + return propertyType.Name.Contains(integerType) ? integerType : propertyType.Name;
  153 + }
  154 + }
132 155 }
95 src/Samples.Tests/ReadWriteExistingExcelFileTests.cs
... ... @@ -0,0 +1,95 @@
  1 +using System;
  2 +using System.Collections.Generic;
  3 +using System.IO;
  4 +using System.Linq;
  5 +using ExcelMapper.Configuration;
  6 +using ExcelMapper.Repository;
  7 +using ExcelToDTOMapper.DTO.Users;
  8 +using Microsoft.Practices.ServiceLocation;
  9 +using NUnit.Framework;
  10 +
  11 +namespace Samples.Tests
  12 +{
  13 + [TestFixture]
  14 + public class ReadWriteExistingExcelFileTests
  15 + {
  16 + private IRepository _repository;
  17 + private const string UserFile = "Excel\\Users.xlsx";
  18 + private const string DemoWorkSheetFile = "Excel\\DemoWorkSheet.xlsx";
  19 +
  20 + [SetUp]
  21 + public void BeforeEachTest()
  22 + {
  23 + File.Delete(DemoWorkSheetFile);
  24 + ExcelMapper.Configuration.ExcelMapper.SetUp();
  25 + _repository = ServiceLocator.Current.GetInstance<IRepository>();
  26 + }
  27 +
  28 + public class DemoWorkSheet
  29 + {
  30 + public int Id { get; set; }
  31 + public string Name { get; set; }
  32 + public DateTime StartDate { get; set; }
  33 + public decimal StartValue { get; set; }
  34 + }
  35 +
  36 + [Test]
  37 + public void ReadFromExcel()
  38 + {
  39 + ServiceLocator.Current.GetInstance<IFileConfiguration>().FileName = UserFile;
  40 + foreach (User user in _repository.Get<User>("User"))
  41 + {