using ModuleTools.Extensions;
using ModuleTools.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.XPath;
namespace ModuleTools.BusinessLogics
{
///
/// Загрузчик данных
///
public static class ServiceProviderLoader
{
private static readonly string _configFileName = "DepartmentPortal.config";
private static readonly string _pathToImplementationExt = "..\\..\\..\\..\\ImplementationExtensions\\";
private static readonly string _pathToWindowDestopExt = "..\\..\\..\\..\\WindowDestopExtensions\\";
///
/// Получение данных с файла настроек
///
///
///
public static string GetConfigData(string key)
{
var fileName = GetFile(_configFileName);
if (!File.Exists(fileName))
{
return string.Empty;
}
var doc = new XPathDocument(fileName);
var nav = doc.CreateNavigator();
var data = nav.SelectDescendants(key, "", false);
data.MoveNext();
return data.Current.Value;
}
///
/// Загрузка всех классов-реализаций IImplementationExtension
///
///
public static List GetImplementationExtensions()
{
var list = new List();
if(Directory.Exists(_pathToImplementationExt))
{
var files = Directory.GetFiles(_pathToImplementationExt, "*.dll", SearchOption.AllDirectories);
var loadedFiles = new List();
foreach(var file in files.Distinct())
{
if(loadedFiles.Contains(file.GetFileName()))
{
continue;
}
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IImplementationExtension).IsAssignableFrom(t))
{
list.Add((IImplementationExtension)Activator.CreateInstance(t));
}
}
loadedFiles.Add(file.GetFileName());
}
}
return list;
}
///
/// Загрузка всех классов-реализаций IWindowDesktopExtension
///
///
public static List GetWindowDesktopExtensions()
{
var list = new List();
if (Directory.Exists(_pathToWindowDestopExt))
{
var files = Directory.GetFiles(_pathToWindowDestopExt, "*.dll", SearchOption.AllDirectories);
var loadedFiles = new List();
foreach (var file in files.Distinct())
{
if (loadedFiles.Contains(file.GetFileName()))
{
continue;
}
Assembly asm = Assembly.LoadFrom(file);
foreach (var t in asm.GetExportedTypes())
{
if (t.IsClass && typeof(IWindowDesktopExtension).IsAssignableFrom(t))
{
list.Add((IWindowDesktopExtension)Activator.CreateInstance(t));
}
}
loadedFiles.Add(file.GetFileName());
}
}
return list;
}
///
/// Получение имени файла
///
///
///
private static string GetFile(string fileName) => Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), fileName);
}
}