-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
245 lines (219 loc) · 10.9 KB
/
Copy pathProgram.cs
File metadata and controls
245 lines (219 loc) · 10.9 KB
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
////////////////////////////////////////////////
// © https://github.com/badhitman - @FakeGov
////////////////////////////////////////////////
using Microsoft.EntityFrameworkCore;
using NLog.Extensions.Logging;
using Telegram.Bot.Services;
using StockSharpService;
using RemoteCallLib;
using Telegram.Bot;
using SharedLib;
using DbcLib;
using NLog;
namespace StockSharpDriver;
/// <summary>
/// Program
/// </summary>
public class Program
{
/// <summary>
/// Main
/// </summary>
public static void Main(string[] args)
{
Logger logger = LogManager.GetCurrentClassLogger();
StockSharpClientConfigMainModel _conf = StockSharpClientConfigMainModel.BuildEmpty();
IHostBuilder builderH = Host.CreateDefaultBuilder(args);
string? appBasePath = Path.GetDirectoryName(TelegramBotAppLayerContext.DbPath);
GlobalDiagnosticsContext.Set("appbasepath", appBasePath);
string curr_dir = Directory.GetCurrentDirectory();
string _environmentName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Development";
string appName = typeof(Program).Assembly.GetName().Name ?? "StockSharpDriverAssemblyNameDemo";
builderH
.ConfigureAppConfiguration((bx, builder) =>
{
builder.SetBasePath(curr_dir);
string path_load = Path.Combine(curr_dir, "appsettings.json");
if (File.Exists(path_load))
builder.AddJsonFile(path_load, optional: true, reloadOnChange: true);
path_load = Path.Combine(curr_dir, $"appsettings.{_environmentName}.json");
if (File.Exists(path_load))
builder.AddJsonFile(path_load, optional: true, reloadOnChange: true);
// Secrets
void ReadSecrets(string dirName)
{
string secretPath = Path.Combine("..", dirName);
DirectoryInfo di = new(secretPath);
for (int i = 0; i < 5 && !di.Exists; i++)
{
secretPath = Path.Combine("..", secretPath);
di = new(secretPath);
}
if (Directory.Exists(secretPath))
{
foreach (string secret in Directory.GetFiles(secretPath, $"*.json"))
{
path_load = Path.GetFullPath(secret);
builder.AddJsonFile(path_load, optional: true, reloadOnChange: true);
}
}
}
ReadSecrets($"secrets_{nameof(StockSharpDriver)}");
builder.AddEnvironmentVariables();
builder.AddCommandLine(args);
builder.Build();
//_conf.Reload(bx.Configuration.GetValue<StockSharpClientConfigMainModel>("StockSharpDriverConfig"));
})
.ConfigureServices((bx, services) =>
{
IConfigurationRoot config = new ConfigurationBuilder()
.SetBasePath(basePath: Directory.GetCurrentDirectory()) //From NuGet Package Microsoft.Extensions.Configuration.Json
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
services.AddLogging(loggingBuilder =>
{
// configure Logging with NLog
loggingBuilder.ClearProviders();
loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
loggingBuilder.AddNLog(config);
});
services.AddDbContextFactory<StockSharpAppContext>(opt =>
{
#if DEBUG
opt.EnableSensitiveDataLogging(true);
//opt.ConfigureWarnings(w => w.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.RelationalEventId.PendingModelChangesWarning));
#endif
})
.AddDbContextFactory<TelegramBotAppContext>(opt =>
{
#if DEBUG
opt.EnableSensitiveDataLogging(true);
//opt.ConfigureWarnings(w => w.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.RelationalEventId.PendingModelChangesWarning));
#endif
})
.AddDbContextFactory<PropertiesStorageContext>(opt =>
{
#if DEBUG
opt.EnableSensitiveDataLogging(true);
//opt.ConfigureWarnings(w => w.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.RelationalEventId.PendingModelChangesWarning));
#endif
})
.AddDbContextFactory<NLogsContext>();
// Register Bot configuration
services.Configure<BotConfiguration>(bx.Configuration.GetSection(BotConfiguration.Configuration));
// Register named HttpClient to benefits from IHttpClientFactory
// and consume it with ITelegramBotClient typed client.
// More read:
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0#typed-clients
// https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
services.AddHttpClient("telegram_bot_client")
.AddTypedClient<ITelegramBotClient>((httpClient, sp) =>
{
BotConfiguration botConfig = sp.GetConfiguration<BotConfiguration>();
TelegramBotClientOptions options = new(botConfig.BotToken);
return new TelegramBotClient(options, httpClient);
});
//
services
.AddSingleton<ITelegramBotService, TelegramBotServiceImplement>()
.AddSingleton<ITelegramDialogService, TelegramDialogService>()
.AddSingleton<StoreTelegramService>()
.AddSingleton<IFlushStockSharpService, FlushStockSharpService>()
.AddSingleton<IDataStockSharpService, DataStockSharpService>()
.AddSingleton<IParametersStorage, ParametersStorage>()
.AddSingleton<IDriverStockSharpService, DriverStockSharpService>()
.AddSingleton<IManageStockSharpService, ManageStockSharpService>()
.AddSingleton<IRubricsService, RubricsService>()
.AddScoped<ILogsService, LogsNavigationImpl>()
.AddScoped<UpdateHandler>()
.AddScoped<ReceiverService>()
.AddHostedService<PollingService>()
;
services.AddMemoryCache();
ConnectionLink _connector = new();
_conf.Reload(config.GetSection("StockSharpDriverConfig").Get<StockSharpClientConfigMainModel>());
string? _logLevelEcngValue = config.GetSection("StockSharpDriverConfig:LogLevelEcng").Value;
if (string.IsNullOrWhiteSpace(_logLevelEcngValue))
_conf.LogLevelEcng = Ecng.Logging.LogLevels.Debug;
else
{
Ecng.Logging.LogLevels? _LL = Enum.GetValues<Ecng.Logging.LogLevels>().FirstOrDefault(x => x.ToString().Equals(_logLevelEcngValue, StringComparison.OrdinalIgnoreCase));
_conf.LogLevelEcng = _LL ?? Ecng.Logging.LogLevels.Debug;
}
services
.AddSingleton(sp => _conf)
.AddSingleton(sp => StockSharpClientConfigModel.BuildEmpty())
.AddSingleton(sp => _connector)
;
services
.AddHostedService<MqttServerWorker>()
.AddHostedService<ConnectionStockSharpWorker>()
;
#region MQ Transmission (remote methods call)
services
.AddSingleton<IMQTTClient>(x => new MQttClient(x.GetRequiredService<StockSharpClientConfigMainModel>(), x.GetRequiredService<ILogger<MQttClient>>(), appName))
;
//
services
.AddSingleton<IEventsStockSharp, EventsStockSharpTransmission>()
.AddSingleton<IEventsNotify, EventsNotifyStockSharpTransmission>()
;
services.StockSharpRegisterMqListeners();
#endregion
});
IHost host = builderH.Build();
//IDbContextFactory<NLogsContext> logsDbFactory
IDbContextFactory<NLogsContext> _factNlogs = host.Services.GetRequiredService<IDbContextFactory<NLogsContext>>();
NLogsContext _ctxNlogs = _factNlogs.CreateDbContext();
#if DEMO_SEED_DB
IDbContextFactory<StockSharpAppContext> _factContext = host.Services.GetRequiredService<IDbContextFactory<StockSharpAppContext>>();
StockSharpAppContext _ctxDriver = _factContext.CreateDbContext();
if (!_ctxDriver.Exchanges.Any() && !_ctxDriver.Boards.Any() && !_ctxDriver.Instruments.Any())
{
InstrumentStockSharpModelDB _insSeed = new()
{
CreatedAtUTC = DateTime.UtcNow,
LastUpdatedAtUTC = DateTime.UtcNow,
Board = new()
{
Code = "board-DEMO_SEED_DB",
Exchange = new()
{
Name = "Exchange DEMO_SEED_DB",
CountryCode = CountryCodesEnum.RU,
},
CreatedAtUTC = DateTime.UtcNow,
LastUpdatedAtUTC = DateTime.UtcNow,
},
Code = "code-DEMO_SEED_DB",
Currency = CurrenciesTypesEnum.RUB,
IdRemote = "code-DEMO_SEED_DB@board-DEMO_SEED_DB",
IssueDate = DateTime.UtcNow,
Name = "instrument DEMO_SEED_DB",
TypeInstrument = InstrumentsStockSharpTypesEnum.Bond,
SettlementType = SettlementTypesEnum.Delivery,
BondTypeInstrumentManual = BondsTypesInstrumentsManualEnum.Floater,
CouponRate = 1,
LastFairPrice = 9,
MaturityDate = DateTime.UtcNow,
TypeInstrumentManual = TypesInstrumentsManualEnum.Futures,
ISIN = "RU000A101QE0",
CashFlows = [],
};
_insSeed.CashFlows.Add(new()
{
Instrument = _insSeed,
StartDate = DateTime.UtcNow,
EndDate = DateTime.UtcNow,
CouponRate = 3,
Coupon = 1,
Notional = 5
});
_ctxDriver.Instruments.Add(_insSeed);
_ctxDriver.SaveChanges();
}
#endif
logger.Info($"Program has started (logs count: {_ctxNlogs.Logs.Count()}).");
host.Run();
}
}