-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathService1.cs
77 lines (69 loc) · 1.84 KB
/
Service1.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
using FileMonitor.Models;
using MongoDB.Driver;
using System.IO;
using System.ServiceProcess;
using System.Configuration;
using System;
using FileMonitor.Enums;
using FileMonitor.Methods;
namespace FileMonitor
{
public partial class FileMonitor : ServiceBase
{
private FileSystemWatcher _watcher;
private MongoClient _client;
private IMongoDatabase _database;
private IMongoCollection<DataLogModel> _collection;
private MongoDBMethods _mongoDBMethods = new MongoDBMethods();
public FileMonitor()
{
InitializeComponent();
InitWatcher();
InitDatabase();
}
protected override void OnStart(string[] args)
{
_watcher.EnableRaisingEvents = true;
}
protected override void OnStop()
{
_watcher.EnableRaisingEvents = false;
}
private void InitWatcher()
{
try
{
_watcher = new FileSystemWatcher(ConfigurationManager.AppSettings["route"]);
_watcher.Created += WatcherEvent;
_watcher.Renamed += WatcherEvent;
_watcher.Changed += WatcherEvent;
_watcher.Deleted += WatcherEvent;
}
catch (Exception)
{
throw;
}
}
private void InitDatabase()
{
try
{
_client = new MongoClient(ConfigurationManager.AppSettings["mongodb_uri"]);
_database = _client.GetDatabase(ConfigurationManager.AppSettings["mongodb_database"]);
_collection = _database.GetCollection<DataLogModel>(ConfigurationManager.AppSettings["mongodb_collection"]);
}
catch (Exception)
{
throw;
}
}
private void WatcherEvent(object sender, FileSystemEventArgs e)
{
_mongoDBMethods.SaveInDatabase(e, _collection);
}
private void WatcherEvent(object sender, RenamedEventArgs e)
{
_mongoDBMethods.SaveInDatabase(e, _collection);
}
}
}