First Initial
This commit is contained in:
149
Utils/AppIOConfiguration.cs
Normal file
149
Utils/AppIOConfiguration.cs
Normal file
@@ -0,0 +1,149 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
/// <summary>
|
||||
/// Sigleton class to manage folder with configuration file.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Configuration (AppIOConfiguration.json) can be created in advance also be able to create in runtime too.
|
||||
/// </remarks>
|
||||
public sealed class AppIOConfiguration
|
||||
{
|
||||
#region Properties and internal classes
|
||||
public class FilePathInfo {
|
||||
public string RelativePath { get; set; }
|
||||
public FileInfo File { get; set; }
|
||||
}
|
||||
|
||||
public class DirectoryPathInfo {
|
||||
public string RelativePath {get;set;}
|
||||
public DirectoryInfo Directory { get; set; }
|
||||
}
|
||||
|
||||
public Dictionary<string, AppIOConfiguration.FilePathInfo> Files { get; } = new Dictionary<string, AppIOConfiguration.FilePathInfo>();
|
||||
public Dictionary<string, AppIOConfiguration.DirectoryPathInfo> Directories { get; } = new Dictionary<string, AppIOConfiguration.DirectoryPathInfo>();
|
||||
#endregion
|
||||
|
||||
#region Private Member for Singleton and instantiate
|
||||
private static readonly Lazy<AppIOConfiguration> lazy = new Lazy<AppIOConfiguration>(PopulateObject);
|
||||
private const string StaticConfigFileName = @"AppIOConfiguration.json";
|
||||
|
||||
public static AppIOConfiguration Instance => lazy.Value;
|
||||
|
||||
private static string configurationFile => Path.Combine(Directory.GetCurrentDirectory(), StaticConfigFileName);
|
||||
private static string currentDirectory => Directory.GetCurrentDirectory();
|
||||
private AppIOConfiguration(){ }
|
||||
|
||||
private AppIOConfiguration(Dictionary<string, AppIOConfiguration.FilePathInfo> Files, Dictionary<string, AppIOConfiguration.DirectoryPathInfo> Directories) {
|
||||
this.Directories = Directories;
|
||||
this.Files = Files;
|
||||
}
|
||||
|
||||
private static AppIOConfiguration PopulateObject() {
|
||||
if (File.Exists(configurationFile))
|
||||
{
|
||||
using (StreamReader file = System.IO.File.OpenText(configurationFile))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
serializer.Converters.Add(new FileInfoJsonConverter());
|
||||
serializer.Converters.Add(new DirectoryInfoJsonConverter());
|
||||
return (AppIOConfiguration)serializer.Deserialize(file, typeof(AppIOConfiguration));
|
||||
}
|
||||
} else {
|
||||
return new AppIOConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public static void Serialize<T>(string serializeFilePath, T input)
|
||||
{
|
||||
using (StreamWriter file = System.IO.File.CreateText(serializeFilePath))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
serializer.Converters.Add(new FileInfoJsonConverter());
|
||||
serializer.Converters.Add(new DirectoryInfoJsonConverter());
|
||||
serializer.Formatting = Formatting.Indented;
|
||||
serializer.Serialize(file, input, typeof(T));
|
||||
}
|
||||
}
|
||||
|
||||
public static T Deserialize<T>(string serializeFilePath)
|
||||
{
|
||||
using (StreamReader file = System.IO.File.OpenText(serializeFilePath))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
serializer.Converters.Add(new FileInfoJsonConverter());
|
||||
serializer.Converters.Add(new DirectoryInfoJsonConverter());
|
||||
return (T)serializer.Deserialize(file, typeof(T));
|
||||
}
|
||||
}
|
||||
|
||||
private static void Save()
|
||||
{
|
||||
Serialize(configurationFile, Instance);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create Directory and save to configuration file
|
||||
/// </summary>
|
||||
/// <param name="directoryName">Use as a Key in Directories collection</param>
|
||||
/// <param name="parentKeyName">Reference to parent directory referred by Key in Directories collection.(default value is "RootPath")</param>
|
||||
/// <param name="relativePath">Alias(fake) path. If value is empty, value will be assigned by combining parent.RelativePath + directoryName</param>
|
||||
/// <example>
|
||||
/// This is an example for using this method.
|
||||
/// <code>
|
||||
/// AppIOConfiguration.CreateDirectory("Files");
|
||||
/// AppIOConfiguration.CreateDirectory("Logs", relativePath:"/logs");
|
||||
/// AppIOConfiguration.CreateDirectory("Log2018", "Logs", "/logs2018");
|
||||
/// AppIOConfiguration.CreateDirectory("EIC_OrderList", "Files");
|
||||
/// </code>
|
||||
/// </example>
|
||||
public static void CreateDirectory(string directoryName, string parentKeyName = "RootPath", string relativePath = "")
|
||||
{
|
||||
if (parentKeyName.Equals("RootPath") && !Instance.Directories.ContainsKey(parentKeyName))
|
||||
{
|
||||
var appRootDirectory = new DirectoryInfo(currentDirectory);
|
||||
var appRootDirectoryPathInfo = new DirectoryPathInfo() {
|
||||
Directory = appRootDirectory,
|
||||
RelativePath = "/"
|
||||
};
|
||||
Instance.Directories.Add("RootPath", appRootDirectoryPathInfo);
|
||||
Save();
|
||||
}
|
||||
|
||||
if (!Instance.Directories.ContainsKey(parentKeyName))
|
||||
{
|
||||
throw new DirectoryNotFoundException("Parent's keyname is not found");
|
||||
}
|
||||
|
||||
if (!Instance.Directories.ContainsKey(directoryName))
|
||||
{
|
||||
var parentDirectory = Instance.Directories[parentKeyName];
|
||||
var parentPath = parentDirectory.Directory.FullName;
|
||||
var createdDirectory = new DirectoryInfo(Path.Combine(parentPath, directoryName));
|
||||
createdDirectory.Create();
|
||||
var createdDirectoryPathInfo = new DirectoryPathInfo() {
|
||||
Directory = createdDirectory,
|
||||
};
|
||||
|
||||
createdDirectoryPathInfo.RelativePath = string.IsNullOrEmpty(relativePath) ?
|
||||
Path.Combine(parentDirectory.RelativePath, directoryName) :
|
||||
relativePath;
|
||||
|
||||
if (!createdDirectory.Exists)
|
||||
{
|
||||
createdDirectory.Create();
|
||||
}
|
||||
Instance.Directories.Add(directoryName, createdDirectoryPathInfo);
|
||||
Save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
29
Utils/Converters/DirectoryInfoJsonConverter.cs
Normal file
29
Utils/Converters/DirectoryInfoJsonConverter.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
public class DirectoryInfoJsonConverter : JsonConverter
|
||||
{
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType == typeof(DirectoryInfo);
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
if (reader.Value is string s)
|
||||
{
|
||||
return new DirectoryInfo(s);
|
||||
}
|
||||
throw new ArgumentOutOfRangeException(nameof(reader));
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
if (!(value is DirectoryInfo directoryInfo))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(value));
|
||||
}
|
||||
writer.WriteValue(directoryInfo.FullName);
|
||||
}
|
||||
}
|
||||
29
Utils/Converters/FileInfoJsonConverter.cs
Normal file
29
Utils/Converters/FileInfoJsonConverter.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
public class FileInfoJsonConverter : JsonConverter
|
||||
{
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType == typeof(FileInfo);
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||
{
|
||||
if (reader.Value is string s)
|
||||
{
|
||||
return new FileInfo(s);
|
||||
}
|
||||
throw new ArgumentOutOfRangeException(nameof(reader));
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||
{
|
||||
if (!(value is FileInfo fileInfo))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(value));
|
||||
}
|
||||
writer.WriteValue(fileInfo.FullName);
|
||||
}
|
||||
}
|
||||
355
Utils/FileUtil.cs
Normal file
355
Utils/FileUtil.cs
Normal file
@@ -0,0 +1,355 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using TTSW.Constant;
|
||||
using MimeTypes;
|
||||
using System.Net.Http;
|
||||
using Newtonsoft.Json;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public static class FileUtil
|
||||
{
|
||||
public static IConfiguration Configuration { get; set; }
|
||||
|
||||
#region Serialize File
|
||||
|
||||
public static string GetRootPath()
|
||||
{
|
||||
return Directory.GetCurrentDirectory();
|
||||
}
|
||||
|
||||
public static void Serialize(string serializeFilePath, object input)
|
||||
{
|
||||
using (StreamWriter file = System.IO.File.CreateText(serializeFilePath))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
serializer.Converters.Add(new FileInfoJsonConverter());
|
||||
serializer.Converters.Add(new DirectoryInfoJsonConverter());
|
||||
serializer.Serialize(file, input);
|
||||
}
|
||||
}
|
||||
public static T Deserialize<T>(string serializeFilePath)
|
||||
{
|
||||
using (StreamReader file = System.IO.File.OpenText(serializeFilePath))
|
||||
{
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
serializer.Converters.Add(new FileInfoJsonConverter());
|
||||
serializer.Converters.Add(new DirectoryInfoJsonConverter());
|
||||
return (T)serializer.Deserialize(file, typeof(T));
|
||||
}
|
||||
}
|
||||
public static StaticConfigModel GetStaticConfig()
|
||||
{
|
||||
StaticConfigModel s = new StaticConfigModel();
|
||||
|
||||
string logfile = Configuration["Files:LogFile"];
|
||||
string rootpath = Configuration["Directories:RootPath"];
|
||||
string logs = Configuration["Directories:Logs"];
|
||||
string files = Configuration["Directories:Files"];
|
||||
|
||||
if (!Directory.Exists(rootpath)) Directory.CreateDirectory(rootpath);
|
||||
if (!Directory.Exists(logs)) Directory.CreateDirectory(logs);
|
||||
if (!Directory.Exists(files)) Directory.CreateDirectory(files);
|
||||
if (!File.Exists(logfile)) File.CreateText(logfile);
|
||||
|
||||
s.Files = new Dictionary<string, FileInfo>();
|
||||
s.Directories = new Dictionary<string, DirectoryInfo>();
|
||||
|
||||
s.Files.Add("LogFile", new FileInfo(logfile));
|
||||
s.Directories.Add("RootPath", new DirectoryInfo(rootpath));
|
||||
s.Directories.Add("Logs", new DirectoryInfo(logs));
|
||||
s.Directories.Add("Files", new DirectoryInfo(files));
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Steps
|
||||
/// 1. Revise Utils\Models\StaticConfigModel.cs to add more properties
|
||||
/// 2. Edit code in this function on StaticConfigModel to declare more properties
|
||||
/// 3. Update the config file with by running this function to serialize it again
|
||||
/// </summary>
|
||||
// public static void UpdateConfigFile()
|
||||
// {
|
||||
// var configFilePath = FileUtil.GetStaticConfigFilePath();
|
||||
|
||||
// // Declare file info
|
||||
// var fileInfo = new StaticConfigModel();
|
||||
//fileInfo.Files = new System.Collections.Generic.Dictionary<string, FileInfo>();
|
||||
//fileInfo.Directories = new System.Collections.Generic.Dictionary<string, DirectoryInfo>();
|
||||
//fileInfo.Files.Add("appsetting", new FileInfo("./appsetting.json"));
|
||||
//fileInfo.Files.Add("temp", new FileInfo("./tmp.json"));
|
||||
//fileInfo.Directories.Add("images", new DirectoryInfo("./images"));
|
||||
//fileInfo.Directories.Add("pdf", new DirectoryInfo("./pdf"));
|
||||
|
||||
// // Serialize file info to config file
|
||||
// FileUtil.Serialize(configFilePath, fileInfo);
|
||||
|
||||
// // Test getting content int the file
|
||||
// var resultConfig = FileUtil.Deserialize<StaticConfigModel>(configFilePath);
|
||||
// }
|
||||
#endregion
|
||||
|
||||
public static string GetLogPath()
|
||||
{
|
||||
var staticConfig = GetStaticConfig();
|
||||
|
||||
return staticConfig.Directories["Logs"].FullName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get root path
|
||||
/// </summary>
|
||||
/// <param name="filePath"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetAbsolutePath(string filePath)
|
||||
{
|
||||
var staticConfig = GetStaticConfig();
|
||||
var currentDir = staticConfig.Directories["RootPath"];
|
||||
|
||||
return Path.Combine(currentDir.FullName, filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get root path for the specific dir
|
||||
/// </summary>
|
||||
/// <param name="dir"></param>
|
||||
/// <returns></returns>
|
||||
public static FilePathInfo GetDirectoryRootPath(FilePathConstant.DirType dir)
|
||||
{
|
||||
var dirName = StringEnumUtil.GetStringValue(dir);
|
||||
|
||||
var filePathInfo = new FilePathInfo()
|
||||
{
|
||||
RelativePath = dirName,
|
||||
PhysicalPath = FileUtil.GetAbsolutePath(dirName)
|
||||
};
|
||||
|
||||
if (!Directory.Exists(filePathInfo.PhysicalPath))
|
||||
Directory.CreateDirectory(filePathInfo.PhysicalPath);
|
||||
|
||||
return filePathInfo;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get both relative and physical dir path in format {root dir}/{id}/
|
||||
/// </summary>
|
||||
/// <param name="dirType"></param>
|
||||
/// <param name="id"></param>
|
||||
/// <returns></returns>
|
||||
public static FilePathInfo GetDirectoryInfo(FilePathConstant.DirType dirType, object id)
|
||||
{
|
||||
var rootPath = GetDirectoryRootPath(dirType);
|
||||
|
||||
var info = new FilePathInfo()
|
||||
{
|
||||
PhysicalPath = Path.Combine(rootPath.PhysicalPath, id.ToString()),
|
||||
RelativePath = Path.Combine(rootPath.RelativePath, id.ToString())
|
||||
};
|
||||
|
||||
if (!Directory.Exists(info.PhysicalPath))
|
||||
Directory.CreateDirectory(info.PhysicalPath);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get both relative and physical file path in format {root dir}/{id}/{temp filename}
|
||||
/// </summary>
|
||||
/// <param name="dirType"></param>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="fileName"></param>
|
||||
/// <returns></returns>
|
||||
public static FilePathInfo GetFileInfo(FilePathConstant.DirType dirType, object id, string fileName)
|
||||
{
|
||||
var dirInfo = GetDirectoryInfo(dirType, id);
|
||||
|
||||
var info = new FilePathInfo()
|
||||
{
|
||||
PhysicalPath = Path.Combine(dirInfo.PhysicalPath, fileName),
|
||||
RelativePath = Path.Combine(dirInfo.RelativePath, fileName)
|
||||
};
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get temporary path for file uploading
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static FilePathInfo GetTempUploadPath()
|
||||
{
|
||||
// Create temp id for temp dir
|
||||
var tempId = Guid.NewGuid();
|
||||
|
||||
var tempDirInfo = GetDirectoryInfo(FilePathConstant.DirType.TempUpload, tempId);
|
||||
|
||||
if (!Directory.Exists(tempDirInfo.PhysicalPath))
|
||||
Directory.CreateDirectory(tempDirInfo.PhysicalPath);
|
||||
|
||||
return tempDirInfo;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Move file to specific folder in the format {root dir}/{id}/{temp filename}
|
||||
/// </summary>
|
||||
/// <returns>Null is no file moved. Else return filename</returns>
|
||||
public static string MoveTempUploadFileToActualPath(string tempRelativeFilePath, FilePathConstant.DirType dirType, object id)
|
||||
{
|
||||
string fileName = "";
|
||||
|
||||
var tempFilePath = FileUtil.GetAbsolutePath(tempRelativeFilePath);
|
||||
|
||||
// If the temp file does not exist, exit the function.
|
||||
if (File.Exists(tempFilePath))
|
||||
{
|
||||
fileName = Path.GetFileName(tempFilePath);
|
||||
var newFileInfo = GetFileInfo(dirType, id, fileName);
|
||||
|
||||
if (File.Exists(newFileInfo.PhysicalPath) && new FileInfo(tempFilePath).FullName != new FileInfo(newFileInfo.PhysicalPath).FullName)
|
||||
File.Delete(newFileInfo.PhysicalPath);
|
||||
|
||||
File.Move(tempFilePath, newFileInfo.PhysicalPath);
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Move file to specific folder in the format {root dir}/{id}/{temp filename}. It also remove old specific file.
|
||||
/// </summary>
|
||||
/// <returns>Null is no file moved. Else return filename</returns>
|
||||
public static string MoveTempUploadFileToActualPath(string tempRelativeFilePath, FilePathConstant.DirType dirType, object id, string oldFileName)
|
||||
{
|
||||
//Remove old file first
|
||||
if (!string.IsNullOrEmpty(oldFileName))
|
||||
{
|
||||
var oldFileInfo = GetFileInfo(dirType, id, oldFileName);
|
||||
|
||||
if (File.Exists(oldFileInfo.PhysicalPath))
|
||||
File.Delete(oldFileInfo.PhysicalPath);
|
||||
}
|
||||
|
||||
return MoveTempUploadFileToActualPath(tempRelativeFilePath, dirType, id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Move file to specific folder in the format {root dir}/{id}/{temp filename}. It also remove old specific file.
|
||||
/// </summary>
|
||||
/// <returns>Null is no file moved. Else return filename</returns>
|
||||
public static FileBase64Info MoveTempUploadFileToBase64File(string tempRelativeFilePath)
|
||||
{
|
||||
|
||||
var tempFilePath = FileUtil.GetAbsolutePath(tempRelativeFilePath);
|
||||
|
||||
// If the temp file does not exist, exit the function.
|
||||
if (File.Exists(tempFilePath))
|
||||
{
|
||||
var fileName = Path.GetFileName(tempFilePath);
|
||||
var fileExtension = Path.GetExtension(tempFilePath);
|
||||
|
||||
var base64Info = new FileBase64Info();
|
||||
|
||||
// Get mine type to use later to produce data url
|
||||
base64Info.FileName = fileName;
|
||||
base64Info.MimeType = MimeTypeMap.GetMimeType(fileExtension);
|
||||
|
||||
// Convert file content to base64 string
|
||||
Byte[] bytes = File.ReadAllBytes(tempFilePath);
|
||||
base64Info.Content = Convert.ToBase64String(bytes);
|
||||
|
||||
//Delete the file from temp
|
||||
//File.Delete(tempFilePath);
|
||||
|
||||
return base64Info;
|
||||
}
|
||||
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
public static bool AreThereAnyFilesInDirectory(string directoryPath)
|
||||
{
|
||||
if (!Directory.Exists(directoryPath))
|
||||
return false;
|
||||
|
||||
var files = Directory.GetFiles(directoryPath);
|
||||
return (files.Count() > 0) ? true : false;
|
||||
}
|
||||
|
||||
public static void DeleteAllFilesInDirectory(string directoryPath)
|
||||
{
|
||||
if (!Directory.Exists(directoryPath))
|
||||
return;
|
||||
|
||||
DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
|
||||
var files = dirInfo.GetFiles();
|
||||
|
||||
foreach (var file in files)
|
||||
file.Delete();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
public static void DeleteAllFilesInDirectory(FilePathConstant.DirType dirType, Guid id)
|
||||
{
|
||||
var dirInfo = GetDirectoryInfo(dirType, id);
|
||||
|
||||
DeleteAllFilesInDirectory(dirInfo.PhysicalPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get data url with base64 content in format data:{mineType};base64,{content}
|
||||
/// </summary>
|
||||
/// <param name="content"></param>
|
||||
/// <param name="mineType"></param>
|
||||
/// <returns></returns>
|
||||
public static FileBase64Info GetBase64Info(string content, string mineType)
|
||||
{
|
||||
return new FileBase64Info()
|
||||
{
|
||||
Content = content,
|
||||
MimeType = mineType
|
||||
};
|
||||
}
|
||||
|
||||
// Get file stream content
|
||||
public static StreamContent GetFileStream(string filePath)
|
||||
{
|
||||
var fullPath = GetAbsolutePath(filePath);
|
||||
|
||||
var filestream = File.Open(fullPath, FileMode.Open, FileAccess.Read);
|
||||
|
||||
return new StreamContent(filestream);
|
||||
}
|
||||
|
||||
public static string GetFileName(string filePath)
|
||||
{
|
||||
return Path.GetFileName(filePath);
|
||||
}
|
||||
|
||||
public static bool DoesFileExist(string fullPath)
|
||||
{
|
||||
if (File.Exists(fullPath))
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
public static string GetMineType(string fullPath)
|
||||
{
|
||||
var fileExtension = Path.GetExtension(fullPath);
|
||||
|
||||
return MimeTypeMap.GetMimeType(fileExtension);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
20
Utils/IMyDatabase.cs
Normal file
20
Utils/IMyDatabase.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Npgsql;
|
||||
using NpgsqlTypes;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public interface IMyDatabase
|
||||
{
|
||||
DataTable ExecuteDataTableNpgsql(string queryString, List<NpgsqlParameter> para);
|
||||
string ExecuteScalarNpgsql(string queryString, List<NpgsqlParameter> para);
|
||||
int ExecuteNonQueryNpgsql(string queryString, List<NpgsqlParameter> para);
|
||||
List<NpgsqlParameter> GetParameterListNpgsql();
|
||||
NpgsqlParameter GetParameterNpgsql(string name, NpgsqlDbType type, int size, object value);
|
||||
NpgsqlParameter GetParameterNpgsql(string name, NpgsqlDbType type, object value);
|
||||
}
|
||||
}
|
||||
14
Utils/Models/CommonResponseMessage.cs
Normal file
14
Utils/Models/CommonResponseMessage.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class CommonResponseMessage
|
||||
{
|
||||
public string code { get; set; }
|
||||
public string message { get; set; }
|
||||
public object data { get; set; }
|
||||
}
|
||||
}
|
||||
22
Utils/Models/FileBase64Info.cs
Normal file
22
Utils/Models/FileBase64Info.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class FileBase64Info
|
||||
{
|
||||
public string FileName { get; set; }
|
||||
public string Content { get; set; }
|
||||
public string MimeType { get; set; }
|
||||
|
||||
public string DataURL
|
||||
{
|
||||
get
|
||||
{
|
||||
return string.Format("data:{0};base64,{1}", MimeType, Content);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Utils/Models/FilePathInfo.cs
Normal file
13
Utils/Models/FilePathInfo.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class FilePathInfo
|
||||
{
|
||||
public string RelativePath { get; set; }
|
||||
public string PhysicalPath { get; set; }
|
||||
}
|
||||
}
|
||||
12
Utils/Models/GuidModel.cs
Normal file
12
Utils/Models/GuidModel.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class GuidModel
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
}
|
||||
}
|
||||
13
Utils/Models/KeyPairDto.cs
Normal file
13
Utils/Models/KeyPairDto.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class KeyPairDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
||||
15
Utils/Models/KeyPairWithParentDto.cs
Normal file
15
Utils/Models/KeyPairWithParentDto.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class KeyPairWithParentDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public int ParentId { get; set; }
|
||||
public string ParentName { get; set; }
|
||||
}
|
||||
}
|
||||
18
Utils/Models/StaticConfigModel.cs
Normal file
18
Utils/Models/StaticConfigModel.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class StaticConfigModel
|
||||
{
|
||||
#region Properties
|
||||
public Dictionary<string, FileInfo> Files { get; set; }
|
||||
public Dictionary<string, DirectoryInfo> Directories { get; set; }
|
||||
#endregion
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
18
Utils/Models/StringValueAttribute.cs
Normal file
18
Utils/Models/StringValueAttribute.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class StringValueAttribute : Attribute
|
||||
{
|
||||
public StringValueAttribute(string value)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
|
||||
public string Value { get; private set; }
|
||||
|
||||
}
|
||||
}
|
||||
14
Utils/Models/UploadedFilePathInfo.cs
Normal file
14
Utils/Models/UploadedFilePathInfo.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class UploadedFilePathInfo
|
||||
{
|
||||
public int Count { get; set; }
|
||||
public long Size { get; set; }
|
||||
public List<string> FilesUploaded { get; set; }
|
||||
}
|
||||
}
|
||||
24
Utils/Models/UserCredentialModel.cs
Normal file
24
Utils/Models/UserCredentialModel.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TodoAPI2.Models
|
||||
{
|
||||
public class UserCredentialModel
|
||||
{
|
||||
[Required]
|
||||
public string UserName { get; set; }
|
||||
[Required]
|
||||
public string Password { get; set; }
|
||||
}
|
||||
|
||||
public class UserCredentialSocialModel
|
||||
{
|
||||
[Required]
|
||||
public string UserName { get; set; }
|
||||
[Required]
|
||||
public string SocialId { get; set; }
|
||||
}
|
||||
}
|
||||
90
Utils/MyDatabase.cs
Normal file
90
Utils/MyDatabase.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Npgsql;
|
||||
using NpgsqlTypes;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class MyDatabase : IMyDatabase
|
||||
{
|
||||
public IConfiguration Configuration { get; set; }
|
||||
|
||||
public MyDatabase(IConfiguration configuration)
|
||||
{
|
||||
Configuration = configuration;
|
||||
}
|
||||
|
||||
public DataTable ExecuteDataTableNpgsql(string queryString, List<NpgsqlParameter> para)
|
||||
{
|
||||
System.Data.DataSet ds = new DataSet();
|
||||
string connectionString = Configuration.GetConnectionString("externalDBConnectionString");
|
||||
|
||||
using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
|
||||
using (NpgsqlCommand cmd = new NpgsqlCommand(queryString, conn))
|
||||
{
|
||||
if (para != null) cmd.Parameters.AddRange(para.ToArray());
|
||||
using (NpgsqlDataAdapter ad = new NpgsqlDataAdapter(cmd))
|
||||
{
|
||||
ad.Fill(ds, "mytable");
|
||||
}
|
||||
}
|
||||
return ds.Tables["mytable"];
|
||||
}
|
||||
|
||||
public int ExecuteNonQueryNpgsql(string queryString, List<NpgsqlParameter> para)
|
||||
{
|
||||
int rowAffected = -1;
|
||||
string connectionString = Configuration.GetConnectionString("externalDBConnectionString");
|
||||
|
||||
using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
|
||||
using (NpgsqlCommand cmd = new NpgsqlCommand(queryString, conn))
|
||||
{
|
||||
conn.Open();
|
||||
if (para != null) cmd.Parameters.AddRange(para.ToArray());
|
||||
rowAffected = cmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
return rowAffected;
|
||||
}
|
||||
|
||||
public string ExecuteScalarNpgsql(string queryString, List<NpgsqlParameter> para)
|
||||
{
|
||||
string result = "";
|
||||
string connectionString = Configuration.GetConnectionString("externalDBConnectionString");
|
||||
|
||||
using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
|
||||
using (NpgsqlCommand cmd = new NpgsqlCommand(queryString, conn))
|
||||
{
|
||||
conn.Open();
|
||||
if (para != null) cmd.Parameters.AddRange(para.ToArray());
|
||||
result = cmd.ExecuteScalar().ToString();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<NpgsqlParameter> GetParameterListNpgsql()
|
||||
{
|
||||
return new List<NpgsqlParameter>();
|
||||
}
|
||||
|
||||
public NpgsqlParameter GetParameterNpgsql(string name, NpgsqlDbType type, int size, object value)
|
||||
{
|
||||
var i = new NpgsqlParameter(name, type, size);
|
||||
i.Value = value;
|
||||
return i;
|
||||
}
|
||||
|
||||
public NpgsqlParameter GetParameterNpgsql(string name, NpgsqlDbType type, object value)
|
||||
{
|
||||
var i = new NpgsqlParameter(name, type);
|
||||
i.Value = value;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
272
Utils/MyHelper.cs
Normal file
272
Utils/MyHelper.cs
Normal file
@@ -0,0 +1,272 @@
|
||||
using MySql.Data.MySqlClient;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using System.Data;
|
||||
using System.Reflection;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System.Net;
|
||||
|
||||
/// <summary>
|
||||
/// Summary description for MyHelper
|
||||
/// </summary>
|
||||
public class MyHelper
|
||||
{
|
||||
public MyHelper()
|
||||
{
|
||||
//
|
||||
// TODO: Add constructor logic here
|
||||
//
|
||||
}
|
||||
|
||||
public static string GetDecimalStringForReport(decimal? d)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
if (d.HasValue)
|
||||
{
|
||||
result = d.ToString();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string GetDateStringForReport(DateTime? date)
|
||||
{
|
||||
if (date.HasValue)
|
||||
{
|
||||
DateTime d = date.Value;
|
||||
|
||||
string year = "";
|
||||
|
||||
var thaimonth = new string[12]{ "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม" };
|
||||
|
||||
int y = d.Year;
|
||||
if (y <= 2500) y += 543;
|
||||
year = y.ToString();
|
||||
|
||||
return d.Day.ToString() + " " + thaimonth[d.Month-1] + " " + year;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetStringFromDate(DateTime? date)
|
||||
{
|
||||
if (date.HasValue)
|
||||
{
|
||||
DateTime d = date.Value;
|
||||
|
||||
string day = "";
|
||||
string month = "";
|
||||
string year = "";
|
||||
|
||||
int y = d.Year;
|
||||
if (y <= 2500) y += 543;
|
||||
|
||||
if (d.Day < 10) day = "0" + d.Day.ToString(); else day = d.Day.ToString();
|
||||
if (d.Month < 10) month = "0" + d.Month.ToString(); else month = d.Month.ToString();
|
||||
year = y.ToString();
|
||||
|
||||
return day + "/" + month + "/" + year;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static DateTime? GetDateFromString(string date)
|
||||
{
|
||||
if (string.IsNullOrEmpty(date)) return null;
|
||||
if (date.Split('/').Length != 3) return null;
|
||||
|
||||
string[] s = date.Split('/');
|
||||
|
||||
int day = 0;
|
||||
int month = 0;
|
||||
int year = 0;
|
||||
|
||||
day = Convert.ToInt16(s[0]);
|
||||
month = Convert.ToInt16(s[1]);
|
||||
year = Convert.ToInt16(s[2]);
|
||||
|
||||
if (year >= 2500) year -= 543;
|
||||
|
||||
DateTime d = new DateTime(year, month, day);
|
||||
return d;
|
||||
}
|
||||
|
||||
public static string GetPriceThaiBath(decimal? a)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
if (a.HasValue)
|
||||
{
|
||||
result = GetPricePrint((double)a.Value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string GetPriceText(double a)
|
||||
{
|
||||
Dictionary<int, string> index = new Dictionary<int, string>();
|
||||
index[1] = "หนึ่ง";
|
||||
index[2] = "สอง";
|
||||
index[3] = "สาม";
|
||||
index[4] = "สี่";
|
||||
index[5] = "ห้า";
|
||||
index[6] = "หก";
|
||||
index[7] = "เจ็ด";
|
||||
index[8] = "แปด";
|
||||
index[9] = "เก้า";
|
||||
index[0] = "ศูนย์";
|
||||
|
||||
Dictionary<int, string> b = new Dictionary<int, string>();
|
||||
b[1] = "";
|
||||
b[10] = "สิบ";
|
||||
b[100] = "ร้อย";
|
||||
b[1000] = "พัน";
|
||||
b[10000] = "หมื่น";
|
||||
b[100000] = "แสน";
|
||||
b[1000000] = "ล้าน";
|
||||
|
||||
string x = "";
|
||||
int ix = 0;
|
||||
double iy = a;
|
||||
|
||||
int i = 1000000;
|
||||
while (i >= 1)
|
||||
{
|
||||
ix = (int)Math.Floor(Convert.ToDecimal(iy) / Convert.ToDecimal(i));
|
||||
iy = iy - ix * i;
|
||||
if (i == 10 & ix == 2)
|
||||
{
|
||||
x += "ยี่" + b[i];
|
||||
}
|
||||
else if (i == 1 & ix == 1)
|
||||
{
|
||||
x += "เอ็ด";
|
||||
}
|
||||
else if (i == 10 & ix == 1)
|
||||
{
|
||||
x += "สิบ";
|
||||
}
|
||||
else if (ix > 0 & ix < 10)
|
||||
{
|
||||
x += index[ix] + b[i];
|
||||
}
|
||||
|
||||
i = i / 10;
|
||||
}
|
||||
|
||||
//x += "บาท";
|
||||
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
public static string GetPricePrint(double a)
|
||||
{
|
||||
string x1 = GetPriceText(a) + "บาท ";
|
||||
string x2 = GetPriceText(Convert.ToDouble(a.ToString("N2").Split('.')[1]));
|
||||
return x1 + x2 + (x2 == "" ? "ถ้วน" : "สตางค์");
|
||||
}
|
||||
|
||||
public static string GetContentType(string fileType)
|
||||
{
|
||||
//One of the following formats: pdf, html, xls, xlsx, rtf, csv, xml, docx, odt, ods.
|
||||
if (fileType == "pdf")
|
||||
{
|
||||
return "application/pdf";
|
||||
}
|
||||
if (fileType == "xls")
|
||||
{
|
||||
return "application/vnd.ms-excel";
|
||||
}
|
||||
if (fileType == "xlsx")
|
||||
{
|
||||
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
}
|
||||
if (fileType == "rtf")
|
||||
{
|
||||
return "application/rtf";
|
||||
}
|
||||
if (fileType == "csv")
|
||||
{
|
||||
return "text/csv";
|
||||
}
|
||||
if (fileType == "xml")
|
||||
{
|
||||
return "text/xml";
|
||||
}
|
||||
if (fileType == "docx")
|
||||
{
|
||||
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
||||
}
|
||||
if (fileType == "odt")
|
||||
{
|
||||
return "application/vnd.oasis.opendocument.text";
|
||||
}
|
||||
if (fileType == "ods")
|
||||
{
|
||||
return "application/vnd.oasis.opendocument.spreadsheet";
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
public static string GetParameterForJasperReport(object obj)
|
||||
{
|
||||
string parameter = "";
|
||||
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
|
||||
{
|
||||
if (propertyInfo.GetValue(obj, null) != null)
|
||||
{
|
||||
if(propertyInfo.GetValue(obj, null).ToString() != "")
|
||||
{
|
||||
if (parameter != "") parameter += "&";
|
||||
var value = propertyInfo.GetValue(obj, null);
|
||||
if (propertyInfo.PropertyType.ToString().Contains("Date"))
|
||||
{
|
||||
var d = (DateTime)propertyInfo.GetValue(obj, null);
|
||||
value = d.Year + "-" + d.Month + "-" + d.Day;
|
||||
}
|
||||
parameter += propertyInfo.Name + "=" + value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return parameter;
|
||||
}
|
||||
|
||||
public static WebClient getHttpClient(IConfiguration Configuration)
|
||||
{
|
||||
string mainurl = Configuration["JasperReportServer:MainURL"];
|
||||
string loginurl = Configuration["JasperReportServer:LoginURL"];
|
||||
string username = Configuration["JasperReportServer:username"];
|
||||
string password = Configuration["JasperReportServer:password"];
|
||||
|
||||
WebClient httpclient = new WebClient();
|
||||
var result = httpclient.DownloadString($"{loginurl}?j_username={username}&j_password={password}");
|
||||
string session = httpclient.ResponseHeaders.Get("Set-Cookie");
|
||||
httpclient.Headers.Add("Cookie", session);
|
||||
return httpclient;
|
||||
}
|
||||
|
||||
public static bool checkAuth(IConfiguration Configuration, Microsoft.AspNetCore.Http.HttpContext context)
|
||||
{
|
||||
//if (!string.IsNullOrEmpty(context.Request.Cookies["user_id"]))
|
||||
//{
|
||||
// return true;
|
||||
//}
|
||||
|
||||
//return false;
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
62
Utils/StringEnumUtil.cs
Normal file
62
Utils/StringEnumUtil.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using TTSW.Utils;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class StringEnumUtil
|
||||
{
|
||||
private static Hashtable _stringValues = new Hashtable();
|
||||
|
||||
// StringEnumUtil.GetStringValue(DBEnum.Prename)
|
||||
public static string GetStringValue(Enum value)
|
||||
{
|
||||
string output = null;
|
||||
Type type = value.GetType();
|
||||
|
||||
if (_stringValues.ContainsKey(value))
|
||||
output = (_stringValues[value] as StringValueAttribute).Value;
|
||||
else
|
||||
{
|
||||
//Look for our 'StringValueAttribute' in the field's custom attributes
|
||||
FieldInfo fi = type.GetField(value.ToString());
|
||||
StringValueAttribute[] attrs =
|
||||
fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
|
||||
if (attrs.Length > 0)
|
||||
{
|
||||
_stringValues.Add(value, attrs[0]);
|
||||
output = attrs[0].Value;
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public static Array GetEnumList<T>()
|
||||
{
|
||||
return Enum.GetValues(typeof(T));
|
||||
}
|
||||
|
||||
// StringEnumUtil.GetListStringValues(StringEnumUtil.GetEnumList<DBEnum.Prename>())
|
||||
public static List<KeyPairDto> GetListStringValues(Array enumValues)
|
||||
{
|
||||
List<KeyPairDto> result = new List<KeyPairDto>();
|
||||
|
||||
foreach (var x in enumValues)
|
||||
{
|
||||
var item = new KeyPairDto()
|
||||
{
|
||||
Id = (int)x,
|
||||
Name = GetStringValue((Enum)x)
|
||||
};
|
||||
|
||||
result.Add(item);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
35
Utils/StringUtil.cs
Normal file
35
Utils/StringUtil.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using TTSW.Constant;
|
||||
using MimeTypes;
|
||||
using System.Net.Http;
|
||||
using System.Xml.Serialization;
|
||||
using System.Xml;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class StringUtil
|
||||
{
|
||||
public StringUtil()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public static string DeleteLines(string input, int linesToSkip)
|
||||
{
|
||||
int startIndex = 0;
|
||||
for (int i = 0; i < linesToSkip; ++i)
|
||||
startIndex = input.IndexOf('\n', startIndex) + 1;
|
||||
return input.Substring(startIndex);
|
||||
}
|
||||
|
||||
public static string RemoveLastLine(string str)
|
||||
{
|
||||
return str.Remove(str.TrimEnd().LastIndexOf(Environment.NewLine));
|
||||
}
|
||||
}
|
||||
}
|
||||
67
Utils/XmlUtil.cs
Normal file
67
Utils/XmlUtil.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using TTSW.Constant;
|
||||
using MimeTypes;
|
||||
using System.Net.Http;
|
||||
using System.Xml.Serialization;
|
||||
using System.Xml;
|
||||
|
||||
namespace TTSW.Utils
|
||||
{
|
||||
public class XmlUtil
|
||||
{
|
||||
public XmlUtil()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public static string Serialize<T>(T dataToSerialize)
|
||||
{
|
||||
try
|
||||
{
|
||||
XmlSerializer serializer = new XmlSerializer(typeof(T));
|
||||
using (var stringwriter = new System.IO.StringWriter())
|
||||
{
|
||||
serializer.Serialize(stringwriter, dataToSerialize);
|
||||
return stringwriter.ToString();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static string SerializeWithExcludingRootElement<T>(T dataToSerialize)
|
||||
{
|
||||
var result = Serialize<T>(dataToSerialize);
|
||||
|
||||
// Remove first 2 lines
|
||||
result = StringUtil.DeleteLines(result, 2);
|
||||
result = StringUtil.RemoveLastLine(result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static T Deserialize<T>(string xmlText)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var stringReader = new System.IO.StringReader(xmlText))
|
||||
{
|
||||
var serializer = new XmlSerializer(typeof(T));
|
||||
return (T)serializer.Deserialize(stringReader);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user