-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileUploadHandler.cs
76 lines (71 loc) · 2.65 KB
/
FileUploadHandler.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
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
// code based on Phillip Wagner's File Uploads with Nancy at
// http://bytefish.de/blog/file_upload_nancy/
namespace Nancy.Demos.Figaro
{
/// <summary>
/// Use our FileUploadHandler to upload the data into the database.
/// </summary>
class FileUploadHandler : IFileUploadHandler
{
private readonly string root;
private readonly FigaroDataContext context;
public FileUploadHandler(FigaroDataContext dataContext, IRootPathProvider provider)
{
context = dataContext;
root = provider.GetRootPath();
}
public void HandleUpload(string fileName, Stream stream)
{
var ms = new MemoryStream();
stream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
Console.WriteLine($"uploading {fileName}...");
long l = 0;
var t = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine($"writing data for category {t}...");
var settings = new XmlReaderSettings()
{ CheckCharacters = true, CloseInput = true, ConformanceLevel = ConformanceLevel.Fragment };
var reader = XmlReader.Create(ms, settings);
//{
while (!reader.EOF)
{
if (reader.Name != "row") reader.ReadToFollowing("row");
if (reader.EOF) continue;
var d = Encoding.UTF8.GetString(Encoding.Convert(Encoding.GetEncoding("ISO-8859-1"),
Encoding.Default, Encoding.Default.GetBytes(reader.ReadOuterXml())));
while (true)
{
try
{
context.InsertItem(d, t);
l++;
break;
}
catch (Exception ex)
{
Console.WriteLine("{0} exception caught writing to db: {1}. retrying...", DateTime.Now, ex.Message);
}
}
}
reader.Dispose();
//}
//flush writes to disk
context.Environment.SetEnvironmentTransactionCheckpoint(true,0,0);
context.BeerDb.Sync();
Console.WriteLine($"{l} records written from {fileName}.");
}
}
public interface IFileUploadHandler
{
void HandleUpload(string fileName, Stream stream);
}
public class FileUploadResult
{
public string Identifier { get; set; }
}
}