-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMPS7Data.cs
334 lines (298 loc) · 11.6 KB
/
MPS7Data.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Adhoc.Proto
{
class MPS7Data
{
const string binaryDataFilePath = @"./Assets/txnlog.dat";
public byte VersionNumber { get; set; }
public UInt32 RecordsAmount { get; set; }
internal IDictionary<RecordType, IDictionary<UInt64, IList<IRecord>>> RecordsMap
= new Dictionary<RecordType, IDictionary<UInt64, IList<IRecord>>>();
/// <summary>
/// Get total amount (in dollars) of debits.
/// </summary>
/// <returns>Amount (in dollars) of debits</returns>
public Double GetTotalDebitAmount()
{
return CalculateTotalAmount(RecordType.Debit);
}
/// <summary>
/// Get total amount (in dollars) of credits.
/// </summary>
/// <returns>Amount (in dollars) of credits</returns>
public Double GetTotalCreditAmount()
{
return CalculateTotalAmount(RecordType.Credit);
}
/// <summary>
/// Get total count of StartAutopays.
/// </summary>
/// <returns>Count of StartAutopays</returns>
public int GetStartAutopayCount()
{
return RetrieveAutopayCount(RecordType.StartAutopay);
}
/// <summary>
/// Get total count of EndAutopays.
/// </summary>
/// <returns>Count of EndAutopays</returns>
public int GetEndAutopayCount()
{
return RetrieveAutopayCount(RecordType.EndAutopay);
}
/// <summary>
/// Get balance of a specific user.
/// </summary>
/// <param name="userID">The user id</param>
/// <returns>The final balance (credit - debit) of the user</returns>
public Double GetBalanceForUser(UInt64 userID)
{
Double userDebitAmount = 0.0d;
foreach (AccountRecord record in this.RecordsMap[RecordType.Debit][userID])
{
userDebitAmount += record.Amount;
}
Double userCreditAmount = 0.0d;
foreach (AccountRecord record in this.RecordsMap[RecordType.Credit][userID])
{
userCreditAmount += record.Amount;
}
return userCreditAmount - userDebitAmount;
}
/// <summary>
/// Reads the binary data file, verifies it is the correct format
/// and populates the records.
/// </summary>
public void LoadData()
{
byte[] byteArray = ReadBytesFromFile();
ReadAndValidateHeader(byteArray);
ReadRecords(byteArray);
}
/// <summary>
/// Calculates the total amount for debits or credits, depending on which
/// RecordType has been specified.
/// </summary>
/// <param name="type">
/// The RecordType for which to calculate the total amount.
/// Limited to RecordType.Debit and RecordType.Credit.
/// </param>
/// <returns>The total amount</returns>
internal Double CalculateTotalAmount(RecordType type)
{
if (!(Equals(type, RecordType.Debit) || Equals(type, RecordType.Credit)))
{
throw new ArgumentException("Invalid parameter passed. " + type.ToString());
}
Double totalAmount = 0.0d;
foreach (IList<IRecord> transactionList in this.RecordsMap[type].Values)
{
foreach (AccountRecord record in transactionList)
{
totalAmount += record.Amount;
}
}
return totalAmount;
}
/// <summary>
/// Retrieves the count of the RecordType.
/// </summary>
/// <param name="type">The RecordType to get a count for.</param>
/// <returns>The total count</returns>
internal int RetrieveAutopayCount(RecordType type)
{
IDictionary<UInt64, IList<IRecord>> transactions = null;
if (!this.RecordsMap.TryGetValue(type, out transactions))
{
throw new ArgumentException("RecordType not found");
}
return transactions.Count;
}
/// <summary>
/// Reads the binary data file.
/// </summary>
/// <returns>Returns a byte array of the binary data.</returns>
internal byte[] ReadBytesFromFile()
{
try
{
using (FileStream fs = new FileStream(binaryDataFilePath, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] txnByteArray = new byte[br.BaseStream.Length];
int idx = 0;
while (br.BaseStream.Position != br.BaseStream.Length)
{
txnByteArray[idx] = br.ReadByte();
idx++;
}
return txnByteArray;
}
}
}
catch (FileNotFoundException fEx)
{
throw fEx;
}
catch (IOException ioEx)
{
throw ioEx;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// Reads the header of the MPS7 binary data file to validate it is in the
/// expected file format, and retrieves the version number and number of
/// records.
/// </summary>
/// <param name="byteArray">The byte array of the binary data</param>
internal void ReadAndValidateHeader(byte[] byteArray)
{
StringBuilder sb = new StringBuilder();
for (int idx = 0; idx < 4; idx++)
{
sb.Append(Convert.ToChar(byteArray[idx]));
}
// To validate the file is in the expected format
if (!sb.ToString().Equals("MPS7"))
{
throw new FormatException("Unexpected format.");
}
this.VersionNumber = Convert.ToByte(byteArray[4]);
this.RecordsAmount =
(UInt32)(byteArray[5]) << 24 |
(UInt32)(byteArray[6]) << 16 |
(UInt32)(byteArray[7]) << 8 |
byteArray[8];
}
/// <summary>
/// Reads an individual record.
/// </summary>
/// <param name="recordInfo">A reference to the record to be populated</param>
/// <returns>The index value by which to offset the byte array</returns>
internal int ReadRecordInfo(byte[] recordInfo, ref IRecord record)
{
int idx = 0;
byte recordTypeEnum = Convert.ToByte(recordInfo[idx]);
UInt32 timestamp =
(UInt32)(recordInfo[1]) << 24 |
(UInt32)(recordInfo[2]) << 16 |
(UInt32)(recordInfo[3]) << 8 |
(UInt32)recordInfo[4];
UInt64 userId =
(UInt64)(recordInfo[5]) << 56 |
(UInt64)(recordInfo[6]) << 48 |
(UInt64)(recordInfo[7]) << 40 |
(UInt64)(recordInfo[8]) << 32 |
(UInt64)(recordInfo[9]) << 24 |
(UInt64)(recordInfo[10]) << 16 |
(UInt64)(recordInfo[11]) << 8 |
(UInt64)(recordInfo[12]);
if (recordTypeEnum == 0x0 || recordTypeEnum == 0x1)
{
Int64 temp = (Int64)
((UInt64)(recordInfo[13]) << 56 |
(UInt64)(recordInfo[14]) << 48 |
(UInt64)(recordInfo[15]) << 40 |
(UInt64)(recordInfo[16]) << 32 |
(UInt64)(recordInfo[17]) << 24 |
(UInt64)(recordInfo[18]) << 16 |
(UInt64)(recordInfo[19]) << 8 |
(UInt64)(recordInfo[20]));
double amount = BitConverter.Int64BitsToDouble(temp);
record = new AccountRecord(recordTypeEnum, timestamp, userId, amount);
// increment to bypass the 64-bit floating point
idx += 8;
}
else
{
record = new AutopayRecord(recordTypeEnum, timestamp, userId);
}
// skipping the enum, timestamp, and userid by 12
// and increment by 1 to get to the next record
idx += 13;
return idx;
}
/// <summary>
/// Populates the records map with all the records.
/// The data is structured such that all records of a particular record type
/// are stored under one mapping. Within that records are stored based on a
/// userID.
/// </summary>
/// <param name="record">The record to be stored</param>
internal void PopulateRecordsMap(IRecord record)
{
IDictionary<UInt64, IList<IRecord>> usersTransactionMap = null;
// If a record type is not found in the mapping then create a new transaction map
// and add the record to the mapping.
if (!this.RecordsMap.TryGetValue(record.Type, out usersTransactionMap))
{
IList<IRecord> transactionList = new List<IRecord>
{
record
};
usersTransactionMap = new Dictionary<UInt64, IList<IRecord>>
{
{ record.UserID, transactionList }
};
this.RecordsMap.Add(record.Type, usersTransactionMap);
}
else
{
IList<IRecord> transactionList = null;
// if no transaction list found for the user then create a new one and
// add to it. Otherwise retrieve the one found and append to it.
if (!usersTransactionMap.TryGetValue(record.UserID, out transactionList))
{
transactionList = new List<IRecord>
{
record
};
usersTransactionMap.Add(record.UserID, transactionList);
}
else
{
transactionList.Add(record);
}
}
}
/// <summary>
/// Reads the byte array to retrieve the individual records.
/// </summary>
/// <param name="byteArray">The byte array of the binary data</param>
internal void ReadRecords(byte[] byteArray)
{
int recordCount = 0;
int idx = 9;
while (idx < byteArray.Length)
{
IRecord record = null;
// Copying a block from the original array with the
// potential size of 21 bytes.
// RecordType = 1 byte
// Timestamp = 4 bytes
// UserID = 8 bytes
// Amount = 8 bytes
// Amount only exists if the type is Debit or Credit.
byte[] recordInfo = new byte[21];
Buffer.BlockCopy(byteArray, idx, recordInfo, 0, 21);
idx += ReadRecordInfo(recordInfo, ref record);
PopulateRecordsMap(record);
recordCount++;
}
// In the scenario the records read are not equal to the record amount
// read from the header
if (recordCount != this.RecordsAmount)
{
//throw new Exception();
}
}
}
}