diff --git a/src/iLoan.Rules.Web/Components/Layout/MainLayout.razor.cs b/src/iLoan.Rules.Web/Components/Layout/MainLayout.razor.cs index dc6cf4d..a6ae771 100644 --- a/src/iLoan.Rules.Web/Components/Layout/MainLayout.razor.cs +++ b/src/iLoan.Rules.Web/Components/Layout/MainLayout.razor.cs @@ -1,13 +1,11 @@ using System.Net.Http; using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Routing; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.Web.Virtualization; using Microsoft.JSInterop; -using Radzen; using Radzen.Blazor; namespace ILoan.Rules.Web.Components.Layout diff --git a/src/iLoan.Rules.Web/Components/Pages/AddCoreRule.razor.cs b/src/iLoan.Rules.Web/Components/Pages/AddCoreRule.razor.cs index 020df20..6414ad0 100644 --- a/src/iLoan.Rules.Web/Components/Pages/AddCoreRule.razor.cs +++ b/src/iLoan.Rules.Web/Components/Pages/AddCoreRule.razor.cs @@ -2,10 +2,9 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using ILoan.Rules.Web.Services; using Microsoft.JSInterop; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using Radzen; using Radzen.Blazor; namespace ILoan.Rules.Web.Components.Pages diff --git a/src/iLoan.Rules.Web/Components/Pages/AddCoreRuleCriteriaOperator.razor.cs b/src/iLoan.Rules.Web/Components/Pages/AddCoreRuleCriteriaOperator.razor.cs index dbb4cb5..cbe9d18 100644 --- a/src/iLoan.Rules.Web/Components/Pages/AddCoreRuleCriteriaOperator.razor.cs +++ b/src/iLoan.Rules.Web/Components/Pages/AddCoreRuleCriteriaOperator.razor.cs @@ -2,10 +2,9 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using ILoan.Rules.Web.Services; using Microsoft.JSInterop; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using Radzen; using Radzen.Blazor; namespace ILoan.Rules.Web.Components.Pages diff --git a/src/iLoan.Rules.Web/Components/Pages/AddCoreRuleCriterion.razor.cs b/src/iLoan.Rules.Web/Components/Pages/AddCoreRuleCriterion.razor.cs index 397cc9c..3b2b1f6 100644 --- a/src/iLoan.Rules.Web/Components/Pages/AddCoreRuleCriterion.razor.cs +++ b/src/iLoan.Rules.Web/Components/Pages/AddCoreRuleCriterion.razor.cs @@ -3,12 +3,10 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DocumentFormat.OpenXml.CustomProperties; +using ILoan.Rules.Web.Services; using Microsoft.JSInterop; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using Radzen; using Radzen.Blazor; -using Microsoft.EntityFrameworkCore; namespace ILoan.Rules.Web.Components.Pages { diff --git a/src/iLoan.Rules.Web/Components/Pages/CoreRules.razor.cs b/src/iLoan.Rules.Web/Components/Pages/CoreRules.razor.cs index 98d97a7..24201ef 100644 --- a/src/iLoan.Rules.Web/Components/Pages/CoreRules.razor.cs +++ b/src/iLoan.Rules.Web/Components/Pages/CoreRules.razor.cs @@ -4,9 +4,7 @@ using System.Linq; using System.Threading.Tasks; using ILoan.Rules.Web.Services; using Microsoft.JSInterop; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using Radzen; using Radzen.Blazor; namespace ILoan.Rules.Web.Components.Pages diff --git a/src/iLoan.Rules.Web/Components/Pages/EditCoreRule.razor.cs b/src/iLoan.Rules.Web/Components/Pages/EditCoreRule.razor.cs index 08a3bd5..9d15dbe 100644 --- a/src/iLoan.Rules.Web/Components/Pages/EditCoreRule.razor.cs +++ b/src/iLoan.Rules.Web/Components/Pages/EditCoreRule.razor.cs @@ -1,7 +1,6 @@ -using Microsoft.AspNetCore.Components; +using ILoan.Rules.Web.Services; using Microsoft.AspNetCore.Components.Web; using Microsoft.JSInterop; -using Radzen; namespace ILoan.Rules.Web.Components.Pages { diff --git a/src/iLoan.Rules.Web/Components/Pages/EditCoreRuleCriteriaOperator.razor.cs b/src/iLoan.Rules.Web/Components/Pages/EditCoreRuleCriteriaOperator.razor.cs index b0595fb..43b09c2 100644 --- a/src/iLoan.Rules.Web/Components/Pages/EditCoreRuleCriteriaOperator.razor.cs +++ b/src/iLoan.Rules.Web/Components/Pages/EditCoreRuleCriteriaOperator.razor.cs @@ -3,11 +3,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.JSInterop; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using Radzen; using Radzen.Blazor; -using ILoan.Rules.Web.Models.Rules; +using ILoan.Rules.Web.Services; namespace ILoan.Rules.Web.Components.Pages { diff --git a/src/iLoan.Rules.Web/Components/Pages/EditCoreRuleCriterion.razor.cs b/src/iLoan.Rules.Web/Components/Pages/EditCoreRuleCriterion.razor.cs index 7849cad..f7e0890 100644 --- a/src/iLoan.Rules.Web/Components/Pages/EditCoreRuleCriterion.razor.cs +++ b/src/iLoan.Rules.Web/Components/Pages/EditCoreRuleCriterion.razor.cs @@ -3,11 +3,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.JSInterop; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using Radzen; using Radzen.Blazor; -using ILoan.Rules.Web.Models.Rules; +using ILoan.Rules.Web.Services; namespace ILoan.Rules.Web.Components.Pages { diff --git a/src/iLoan.Rules.Web/Controllers/ExportController.cs b/src/iLoan.Rules.Web/Controllers/ExportController.cs deleted file mode 100644 index 6d782e7..0000000 --- a/src/iLoan.Rules.Web/Controllers/ExportController.cs +++ /dev/null @@ -1,369 +0,0 @@ -using System; -using System.Linq; -using System.Linq.Dynamic.Core; -using System.Data; -using System.Globalization; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; -using Microsoft.AspNetCore.Mvc; -using System.Text; -using System.IO; -using DocumentFormat.OpenXml; -using DocumentFormat.OpenXml.Packaging; -using DocumentFormat.OpenXml.Spreadsheet; -using System.Reflection; -using Microsoft.AspNetCore.Http; - -namespace ILoan.Rules.Web.Controllers -{ - public partial class ExportController : Controller - { - public IQueryable ApplyQuery(IQueryable items, IQueryCollection query = null, bool keyless = false) where T : class - { - if (query != null) - { - if (query.ContainsKey("$expand")) - { - var propertiesToExpand = query["$expand"].ToString().Split(','); - foreach (var p in propertiesToExpand) - { - items = items.Include(p); - } - } - - var filter = query.ContainsKey("$filter") ? query["$filter"].ToString() : null; - if (!string.IsNullOrEmpty(filter)) - { - if(keyless) - { - items = items.ToList().AsQueryable(); - } - items = items.Where(filter); - } - - if (query.ContainsKey("$orderBy")) - { - items = items.OrderBy(query["$orderBy"].ToString()); - } - - if (query.ContainsKey("$skip")) - { - items = items.Skip(int.Parse(query["$skip"].ToString())); - } - - if (query.ContainsKey("$top")) - { - items = items.Take(int.Parse(query["$top"].ToString())); - } - - if (query.ContainsKey("$select")) - { - return items.Select($"new ({query["$select"].ToString()})"); - } - } - - return items; - } - - public FileStreamResult ToCSV(IQueryable query, string fileName = null) - { - var columns = GetProperties(query.ElementType); - - var sb = new StringBuilder(); - - foreach (var item in query) - { - var row = new List(); - - foreach (var column in columns) - { - row.Add($"{GetValue(item, column.Key)}".Trim()); - } - - sb.AppendLine(string.Join(",", row.ToArray())); - } - - - var result = new FileStreamResult(new MemoryStream(UTF8Encoding.Default.GetBytes($"{string.Join(",", columns.Select(c => c.Key))}{System.Environment.NewLine}{sb.ToString()}")), "text/csv"); - result.FileDownloadName = (!string.IsNullOrEmpty(fileName) ? fileName : "Export") + ".csv"; - - return result; - } - - public FileStreamResult ToExcel(IQueryable query, string fileName = null) - { - var columns = GetProperties(query.ElementType); - var stream = new MemoryStream(); - - using (var document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook)) - { - var workbookPart = document.AddWorkbookPart(); - workbookPart.Workbook = new Workbook(); - - var worksheetPart = workbookPart.AddNewPart(); - worksheetPart.Worksheet = new Worksheet(); - - var workbookStylesPart = workbookPart.AddNewPart(); - GenerateWorkbookStylesPartContent(workbookStylesPart); - - var sheets = workbookPart.Workbook.AppendChild(new Sheets()); - var sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" }; - sheets.Append(sheet); - - workbookPart.Workbook.Save(); - - var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData()); - - var headerRow = new Row(); - - foreach (var column in columns) - { - headerRow.Append(new Cell() - { - CellValue = new CellValue(column.Key), - DataType = new EnumValue(CellValues.String) - }); - } - - sheetData.AppendChild(headerRow); - - foreach (var item in query) - { - var row = new Row(); - - foreach (var column in columns) - { - var value = GetValue(item, column.Key); - var stringValue = $"{value}".Trim(); - - var cell = new Cell(); - - var underlyingType = column.Value.IsGenericType && - column.Value.GetGenericTypeDefinition() == typeof(Nullable<>) ? - Nullable.GetUnderlyingType(column.Value) : column.Value; - - var typeCode = Type.GetTypeCode(underlyingType); - - if (typeCode == TypeCode.DateTime) - { - if (!string.IsNullOrWhiteSpace(stringValue)) - { - cell.CellValue = new CellValue() { Text = ((DateTime)value).ToOADate().ToString(System.Globalization.CultureInfo.InvariantCulture) }; - cell.DataType = new EnumValue(CellValues.Number); - cell.StyleIndex = (UInt32Value)1U; - } - } - else if (typeCode == TypeCode.Boolean) - { - cell.CellValue = new CellValue(stringValue.ToLowerInvariant()); - cell.DataType = new EnumValue(CellValues.Boolean); - } - else if (IsNumeric(typeCode)) - { - if (value != null) - { - stringValue = Convert.ToString(value, CultureInfo.InvariantCulture); - } - cell.CellValue = new CellValue(stringValue); - cell.DataType = new EnumValue(CellValues.Number); - } - else - { - cell.CellValue = new CellValue(stringValue); - cell.DataType = new EnumValue(CellValues.String); - } - - row.Append(cell); - } - - sheetData.AppendChild(row); - } - - - workbookPart.Workbook.Save(); - } - - if (stream?.Length > 0) - { - stream.Seek(0, SeekOrigin.Begin); - } - - var result = new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - result.FileDownloadName = (!string.IsNullOrEmpty(fileName) ? fileName : "Export") + ".xlsx"; - - return result; - } - - - public static object GetValue(object target, string name) - { - return target.GetType().GetProperty(name).GetValue(target); - } - - public static IEnumerable> GetProperties(Type type) - { - return type.GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Where(p => p.CanRead && IsSimpleType(p.PropertyType)).Select(p => new KeyValuePair(p.Name, p.PropertyType)); - } - - public static bool IsSimpleType(Type type) - { - var underlyingType = type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(Nullable<>) ? - Nullable.GetUnderlyingType(type) : type; - - if(underlyingType == typeof(System.Guid) || underlyingType == typeof(System.DateTimeOffset)) - return true; - -#if NET6_0_OR_GREATER - if(underlyingType == typeof(System.DateOnly) || underlyingType == typeof(System.TimeOnly)) - return true; -#endif - var typeCode = Type.GetTypeCode(underlyingType); - - switch (typeCode) - { - case TypeCode.Boolean: - case TypeCode.Byte: - case TypeCode.Char: - case TypeCode.DateTime: - case TypeCode.Decimal: - case TypeCode.Double: - case TypeCode.Int16: - case TypeCode.Int32: - case TypeCode.Int64: - case TypeCode.SByte: - case TypeCode.Single: - case TypeCode.String: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - return true; - default: - return false; - } - } - - private static bool IsNumeric(TypeCode typeCode) - { - switch (typeCode) - { - case TypeCode.Decimal: - case TypeCode.Double: - case TypeCode.Int16: - case TypeCode.Int32: - case TypeCode.Int64: - case TypeCode.UInt16: - case TypeCode.UInt32: - case TypeCode.UInt64: - return true; - default: - return false; - } - } - - private static void GenerateWorkbookStylesPartContent(WorkbookStylesPart workbookStylesPart1) - { - Stylesheet stylesheet1 = new Stylesheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac x16r2 xr" } }; - stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); - stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); - stylesheet1.AddNamespaceDeclaration("x16r2", "http://schemas.microsoft.com/office/spreadsheetml/2015/02/main"); - stylesheet1.AddNamespaceDeclaration("xr", "http://schemas.microsoft.com/office/spreadsheetml/2014/revision"); - - Fonts fonts1 = new Fonts() { Count = (UInt32Value)1U, KnownFonts = true }; - - Font font1 = new Font(); - FontSize fontSize1 = new FontSize() { Val = 11D }; - Color color1 = new Color() { Theme = (UInt32Value)1U }; - FontName fontName1 = new FontName() { Val = "Calibri" }; - FontFamilyNumbering fontFamilyNumbering1 = new FontFamilyNumbering() { Val = 2 }; - FontScheme fontScheme1 = new FontScheme() { Val = FontSchemeValues.Minor }; - - font1.Append(fontSize1); - font1.Append(color1); - font1.Append(fontName1); - font1.Append(fontFamilyNumbering1); - font1.Append(fontScheme1); - - fonts1.Append(font1); - - Fills fills1 = new Fills() { Count = (UInt32Value)2U }; - - Fill fill1 = new Fill(); - PatternFill patternFill1 = new PatternFill() { PatternType = PatternValues.None }; - - fill1.Append(patternFill1); - - Fill fill2 = new Fill(); - PatternFill patternFill2 = new PatternFill() { PatternType = PatternValues.Gray125 }; - - fill2.Append(patternFill2); - - fills1.Append(fill1); - fills1.Append(fill2); - - Borders borders1 = new Borders() { Count = (UInt32Value)1U }; - - Border border1 = new Border(); - LeftBorder leftBorder1 = new LeftBorder(); - RightBorder rightBorder1 = new RightBorder(); - TopBorder topBorder1 = new TopBorder(); - BottomBorder bottomBorder1 = new BottomBorder(); - DiagonalBorder diagonalBorder1 = new DiagonalBorder(); - - border1.Append(leftBorder1); - border1.Append(rightBorder1); - border1.Append(topBorder1); - border1.Append(bottomBorder1); - border1.Append(diagonalBorder1); - - borders1.Append(border1); - - CellStyleFormats cellStyleFormats1 = new CellStyleFormats() { Count = (UInt32Value)1U }; - CellFormat cellFormat1 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U }; - - cellStyleFormats1.Append(cellFormat1); - - CellFormats cellFormats1 = new CellFormats() { Count = (UInt32Value)2U }; - CellFormat cellFormat2 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }; - CellFormat cellFormat3 = new CellFormat() { NumberFormatId = (UInt32Value)14U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyNumberFormat = true }; - - cellFormats1.Append(cellFormat2); - cellFormats1.Append(cellFormat3); - - CellStyles cellStyles1 = new CellStyles() { Count = (UInt32Value)1U }; - CellStyle cellStyle1 = new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U }; - - cellStyles1.Append(cellStyle1); - DifferentialFormats differentialFormats1 = new DifferentialFormats() { Count = (UInt32Value)0U }; - TableStyles tableStyles1 = new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" }; - - StylesheetExtensionList stylesheetExtensionList1 = new StylesheetExtensionList(); - - StylesheetExtension stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" }; - stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); - - StylesheetExtension stylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" }; - stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); - - OpenXmlUnknownElement openXmlUnknownElement4 = workbookStylesPart1.CreateUnknownElement(""); - - stylesheetExtension2.Append(openXmlUnknownElement4); - - stylesheetExtensionList1.Append(stylesheetExtension1); - stylesheetExtensionList1.Append(stylesheetExtension2); - - stylesheet1.Append(fonts1); - stylesheet1.Append(fills1); - stylesheet1.Append(borders1); - stylesheet1.Append(cellStyleFormats1); - stylesheet1.Append(cellFormats1); - stylesheet1.Append(cellStyles1); - stylesheet1.Append(differentialFormats1); - stylesheet1.Append(tableStyles1); - stylesheet1.Append(stylesheetExtensionList1); - - workbookStylesPart1.Stylesheet = stylesheet1; - } - } -} diff --git a/src/iLoan.Rules.Web/Controllers/ExportRulesController.cs b/src/iLoan.Rules.Web/Controllers/ExportRulesController.cs deleted file mode 100644 index b0c631d..0000000 --- a/src/iLoan.Rules.Web/Controllers/ExportRulesController.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using System.Linq; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using System.Threading.Tasks; - -using ILoan.Rules.Web.Data; - -namespace ILoan.Rules.Web.Controllers -{ - public partial class ExportRulesController : ExportController - { - private readonly RulesContext context; - private readonly RulesService service; - - public ExportRulesController(RulesContext context, RulesService service) - { - this.service = service; - this.context = context; - } - - [HttpGet("/export/Rules/corerulecriteriaoperators/csv")] - [HttpGet("/export/Rules/corerulecriteriaoperators/csv(fileName='{fileName}')")] - public async Task ExportCoreRuleCriteriaOperatorsToCSV(string fileName = null) - { - return ToCSV(ApplyQuery(await service.GetCoreRuleCriteriaOperators(), Request.Query, false), fileName); - } - - [HttpGet("/export/Rules/corerulecriteriaoperators/excel")] - [HttpGet("/export/Rules/corerulecriteriaoperators/excel(fileName='{fileName}')")] - public async Task ExportCoreRuleCriteriaOperatorsToExcel(string fileName = null) - { - return ToExcel(ApplyQuery(await service.GetCoreRuleCriteriaOperators(), Request.Query, false), fileName); - } - - [HttpGet("/export/Rules/corerules/csv")] - [HttpGet("/export/Rules/corerules/csv(fileName='{fileName}')")] - public async Task ExportCoreRulesToCSV(string fileName = null) - { - return ToCSV(ApplyQuery(await service.GetCoreRules(), Request.Query, false), fileName); - } - - [HttpGet("/export/Rules/corerules/excel")] - [HttpGet("/export/Rules/corerules/excel(fileName='{fileName}')")] - public async Task ExportCoreRulesToExcel(string fileName = null) - { - return ToExcel(ApplyQuery(await service.GetCoreRules(), Request.Query, false), fileName); - } - - [HttpGet("/export/Rules/corerulecriteria/csv")] - [HttpGet("/export/Rules/corerulecriteria/csv(fileName='{fileName}')")] - public async Task ExportCoreRuleCriteriaToCSV(string fileName = null) - { - return ToCSV(ApplyQuery(await service.GetCoreRuleCriteria(), Request.Query, false), fileName); - } - - [HttpGet("/export/Rules/corerulecriteria/excel")] - [HttpGet("/export/Rules/corerulecriteria/excel(fileName='{fileName}')")] - public async Task ExportCoreRuleCriteriaToExcel(string fileName = null) - { - return ToExcel(ApplyQuery(await service.GetCoreRuleCriteria(), Request.Query, false), fileName); - } - } -} diff --git a/src/iLoan.Rules.Web/Controllers/ReportController.cs b/src/iLoan.Rules.Web/Controllers/ReportController.cs deleted file mode 100644 index dccd5f9..0000000 --- a/src/iLoan.Rules.Web/Controllers/ReportController.cs +++ /dev/null @@ -1,243 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Extensions; -using Microsoft.AspNetCore.Mvc; - -namespace ILoan.Rules.Web.Controllers -{ - public partial class ReportController : Controller - { - [HttpGet("/__ssrsreport")] - public async Task Get(string url) - { - if (!String.IsNullOrEmpty(url)) - { - using (var httpClient = CreateHttpClient()) - { - var responseMessage = await ForwardRequest(httpClient, Request, url); - - CopyResponseHeaders(responseMessage, Response); - - await WriteResponse(Request, url, responseMessage, Response, false); - } - } - } - - [Route("/ssrsproxy/{*url}")] - public async Task Proxy() - { - var urlToReplace = String.Format("{0}://{1}{2}/{3}/", Request.Scheme, Request.Host.Value, Request.PathBase, "ssrsproxy"); - var requestedUrl = Request.GetDisplayUrl().Replace(urlToReplace, "", StringComparison.InvariantCultureIgnoreCase); - var reportServerIndex = requestedUrl.IndexOf("/ReportServer", StringComparison.InvariantCultureIgnoreCase); - if (reportServerIndex == -1) - { - reportServerIndex = requestedUrl.IndexOf("/Reports", StringComparison.InvariantCultureIgnoreCase); - } - var reportUrlParts = requestedUrl.Substring(0, reportServerIndex).Split('/'); - - var url = String.Format("{0}://{1}:{2}{3}", reportUrlParts[0], reportUrlParts[1], reportUrlParts[2], - requestedUrl.Substring(reportServerIndex, requestedUrl.Length - reportServerIndex)); - - using (var httpClient = CreateHttpClient()) - { - var responseMessage = await ForwardRequest(httpClient, Request, url); - - CopyResponseHeaders(responseMessage, Response); - - if (Request.Method == "POST") - { - await WriteResponse(Request, url, responseMessage, Response, true); - } - else - { - if (responseMessage.Content.Headers.ContentType != null && responseMessage.Content.Headers.ContentType.MediaType == "text/html") - { - await WriteResponse(Request, url, responseMessage, Response, false); - } - else - { - using (var responseStream = await responseMessage.Content.ReadAsStreamAsync()) - { - await responseStream.CopyToAsync(Response.Body, 81920, HttpContext.RequestAborted); - } - } - } - } - } - - partial void OnHttpClientHandlerCreate(ref HttpClientHandler handler); - - private HttpClient CreateHttpClient() - { - var httpClientHandler = new HttpClientHandler(); - - httpClientHandler.AllowAutoRedirect = true; - httpClientHandler.UseDefaultCredentials = true; - - if (httpClientHandler.SupportsAutomaticDecompression) - { - httpClientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; - } - - OnHttpClientHandlerCreate(ref httpClientHandler); - - return new HttpClient(httpClientHandler); - } - - partial void OnReportRequest(ref HttpRequestMessage requestMessage); - - async Task ForwardRequest(HttpClient httpClient, HttpRequest currentReqest, string url) - { - var proxyRequestMessage = new HttpRequestMessage(new HttpMethod(currentReqest.Method), url); - - foreach (var header in currentReqest.Headers) - { - if (header.Key != "Host") - { - proxyRequestMessage.Headers.TryAddWithoutValidation(header.Key, new string[] { header.Value }); - } - } - - this.OnReportRequest(ref proxyRequestMessage); - - if (currentReqest.Method == "POST") - { - using (var stream = new MemoryStream()) - { - await currentReqest.Body.CopyToAsync(stream); - stream.Position = 0; - - string body = new StreamReader(stream).ReadToEnd(); - proxyRequestMessage.Content = new StringContent(body); - - if (body.IndexOf("AjaxScriptManager") != -1) - { - proxyRequestMessage.Content.Headers.Remove("Content-Type"); - proxyRequestMessage.Content.Headers.Add("Content-Type", new string[] { currentReqest.ContentType }); - } - } - } - - return await httpClient.SendAsync(proxyRequestMessage); - } - - static void CopyResponseHeaders(HttpResponseMessage responseMessage, HttpResponse response) - { - response.StatusCode = (int)responseMessage.StatusCode; - foreach (var header in responseMessage.Headers) - { - response.Headers[header.Key] = header.Value.ToArray(); - } - - foreach (var header in responseMessage.Content.Headers) - { - response.Headers[header.Key] = header.Value.ToArray(); - } - - response.Headers.Remove("transfer-encoding"); - } - - static async Task WriteResponse(HttpRequest currentReqest, string url, HttpResponseMessage responseMessage, HttpResponse response, bool isAjax) - { - var result = await responseMessage.Content.ReadAsStringAsync(); - - var ReportServer = url.Contains("/ReportServer/", StringComparison.InvariantCultureIgnoreCase) ? "ReportServer" : "Reports"; - - var reportUri = new Uri(url); - var proxyUrl = String.Format("{0}://{1}{2}/ssrsproxy/{3}/{4}/{5}", currentReqest.Scheme, currentReqest.Host.Value, currentReqest.PathBase, - reportUri.Scheme, reportUri.Host, reportUri.Port); - - if (isAjax && result.IndexOf("|") != -1) - { - var builder = new StringBuilder(); - - var delimiterIndex = 0; - var length = 0; - var index = 0; - - var type = ""; - var id = ""; - var content = ""; - - while (index < result.Length) - { - delimiterIndex = result.IndexOf("|", index); - if (delimiterIndex == -1) - { - break; - } - length = int.Parse(result.Substring(index, delimiterIndex - index)); - if ((length % 1) != 0) - { - break; - } - index = delimiterIndex + 1; - delimiterIndex = result.IndexOf("|", index); - if (delimiterIndex == -1) - { - break; - } - type = result.Substring(index, delimiterIndex - index); - index = delimiterIndex + 1; - delimiterIndex = result.IndexOf("|", index); - if (delimiterIndex == -1) - { - break; - } - id = result.Substring(index, delimiterIndex - index); - index = delimiterIndex + 1; - if ((index + length) >= result.Length) - { - break; - } - content = result.Substring(index, length); - index += length; - if (result.Substring(index, 1) != "|") - { - break; - } - index++; - - content = content.Replace($"/{ReportServer}/", $"{proxyUrl}/{ReportServer}/", StringComparison.InvariantCultureIgnoreCase); - if (content.Contains("./ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase)) - { - content = content.Replace("./ReportViewer.aspx", $"{proxyUrl}/{ReportServer}/Pages/ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase); - } - else - { - content = content.Replace("ReportViewer.aspx", $"{proxyUrl}/{ReportServer}/Pages/ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase); - } - - builder.Append(String.Format("{0}|{1}|{2}|{3}|", content.Length, type, id, content)); - } - - result = builder.ToString(); - } - else - { - result = result.Replace($"/{ReportServer}/", $"{proxyUrl}/{ReportServer}/", StringComparison.InvariantCultureIgnoreCase); - - if (result.Contains("./ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase)) - { - result = result.Replace("./ReportViewer.aspx", $"{proxyUrl}/{ReportServer}/Pages/ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase); - } - else - { - result = result.Replace("ReportViewer.aspx", $"{proxyUrl}/{ReportServer}/Pages/ReportViewer.aspx", StringComparison.InvariantCultureIgnoreCase); - } - } - - response.Headers.Remove("Content-Length"); - response.Headers.Append("Content-Length", new string[] { System.Text.Encoding.UTF8.GetByteCount(result).ToString() }); - - await response.WriteAsync(result); - } - } -} diff --git a/src/iLoan.Rules.Web/Controllers/UploadController.cs b/src/iLoan.Rules.Web/Controllers/UploadController.cs deleted file mode 100644 index 898dfa7..0000000 --- a/src/iLoan.Rules.Web/Controllers/UploadController.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.IO; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Hosting; - -namespace ILoan.Rules.Web.Controllers -{ - public partial class UploadController : Controller - { - private readonly IWebHostEnvironment environment; - - public UploadController(IWebHostEnvironment environment) - { - this.environment = environment; - } - - // Single file upload - [HttpPost("upload/single")] - public IActionResult Single(IFormFile file) - { - try - { - // Put your code here - return StatusCode(200); - } - catch (Exception ex) - { - return StatusCode(500, ex.Message); - } - } - - // Multiple files upload - [HttpPost("upload/multiple")] - public IActionResult Multiple(IFormFile[] files) - { - try - { - // Put your code here - return StatusCode(200); - } - catch (Exception ex) - { - return StatusCode(500, ex.Message); - } - } - - // Multiple files upload with parameter - [HttpPost("upload/{id}")] - public IActionResult Post(IFormFile[] files, int id) - { - try - { - // Put your code here - return StatusCode(200); - } - catch (Exception ex) - { - return StatusCode(500, ex.Message); - } - } - - // Image file upload (used by HtmlEditor components) - [HttpPost("upload/image")] - public IActionResult Image(IFormFile file) - { - try - { - var fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}"; - - using (var stream = new FileStream(Path.Combine(environment.WebRootPath, fileName), FileMode.Create)) - { - // Save the file - file.CopyTo(stream); - - // Return the URL of the file - var url = Url.Content($"~/{fileName}"); - - return Ok(new { Url = url }); - } - } - catch (Exception ex) - { - return StatusCode(500, ex.Message); - } - } - } -} diff --git a/src/iLoan.Rules.Web/Data/BlankTriggerAddingConvention.cs b/src/iLoan.Rules.Web/Data/BlankTriggerAddingConvention.cs index f287bef..e04dda1 100644 --- a/src/iLoan.Rules.Web/Data/BlankTriggerAddingConvention.cs +++ b/src/iLoan.Rules.Web/Data/BlankTriggerAddingConvention.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; namespace ILoan.Rules.Web.Data { diff --git a/src/iLoan.Rules.Web/Data/RulesContext.cs b/src/iLoan.Rules.Web/Data/RulesContext.cs index ee9ad3b..a6292df 100644 --- a/src/iLoan.Rules.Web/Data/RulesContext.cs +++ b/src/iLoan.Rules.Web/Data/RulesContext.cs @@ -1,8 +1,6 @@ using System; using System.Linq; using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; -using ILoan.Rules.Web.Models.Rules; namespace ILoan.Rules.Web.Data { diff --git a/src/iLoan.Rules.Web/Program.cs b/src/iLoan.Rules.Web/Program.cs index bdba3b4..f75bd98 100644 --- a/src/iLoan.Rules.Web/Program.cs +++ b/src/iLoan.Rules.Web/Program.cs @@ -1,7 +1,5 @@ -using Radzen; using ILoan.Rules.Web.Components; using ILoan.Rules.Web.Services; -using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. @@ -9,9 +7,9 @@ builder.Services.AddRazorComponents().AddInteractiveServerComponents().AddHubOpt builder.Services.AddControllers(); builder.Services.AddRadzenComponents(); builder.Services.AddHttpClient(); -builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddScoped(); -builder.Services.AddDbContext(options => +builder.Services.AddDbContextFactory(options => { options.UseNpgsql(builder.Configuration.GetConnectionString("RulesConnection")); }); diff --git a/src/iLoan.Rules.Web/Properties/launchSettings.json b/src/iLoan.Rules.Web/Properties/launchSettings.json index 225f478..087c894 100644 --- a/src/iLoan.Rules.Web/Properties/launchSettings.json +++ b/src/iLoan.Rules.Web/Properties/launchSettings.json @@ -8,11 +8,11 @@ } }, "profiles": { - "ILoan.Rules.Web.Server": { + "ILoan.Rules.Web": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, - "applicationUrl": "https://localhost:5001;http://localhost:5000", + "applicationUrl": "https://localhost:7001;http://localhost:7000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/src/iLoan.Rules.Web/Services/RuleFileGeneratorService.cs b/src/iLoan.Rules.Web/Services/RuleFileGeneratorService.cs index 94b8219..9946003 100644 --- a/src/iLoan.Rules.Web/Services/RuleFileGeneratorService.cs +++ b/src/iLoan.Rules.Web/Services/RuleFileGeneratorService.cs @@ -1,7 +1,4 @@ -using ILoan.Rules.Web.Data; -using ILoan.Rules.Web.Models.Rules; -using Microsoft.EntityFrameworkCore; -using System.Text; +using System.Text; namespace ILoan.Rules.Web.Services; @@ -80,7 +77,7 @@ INSERT INTO core.""Core_Rules"" ( sqlBuilder.AppendLine($@" INSERT INTO core.""Core_RuleCriteria"" ( ""ID"", ""RuleID"", ""Property"", ""Comparison"", ""Value"", ""ValueIsProperty"", ""ReturnCount"", ""IsThresholdCriterium"" -) VALUES ( +) OVERRIDING SYSTEM VALUE VALUES ( {criterion.ID}, {criterion.RuleID}, '{EscapeSingleQuote(criterion.Property)}', '{EscapeSingleQuote(criterion.Comparison)}', '{EscapeSingleQuote(criterion.Value)}', {criterion.ValueIsProperty?.ToString().ToUpper() ?? "NULL"}, {criterion.ReturnCount?.ToString().ToUpper() ?? "NULL"}, {criterion.IsThresholdCriterium?.ToString().ToUpper() ?? "NULL"} ); @@ -93,7 +90,7 @@ INSERT INTO core.""Core_RuleCriteria"" ( sqlBuilder.AppendLine($@" INSERT INTO core.""Core_RuleCriteriaOperator"" ( ""ID"", ""RuleID"", ""Operator"" -) VALUES ( +) OVERRIDING SYSTEM VALUE ( {coreRuleCriteriaOperator.ID}, {coreRuleCriteriaOperator.RuleID}, '{EscapeSingleQuote(coreRuleCriteriaOperator.Operator1)}' ); "); diff --git a/src/iLoan.Rules.Web/Services/RulesService.cs b/src/iLoan.Rules.Web/Services/RulesService.cs index ca340f2..f218c54 100644 --- a/src/iLoan.Rules.Web/Services/RulesService.cs +++ b/src/iLoan.Rules.Web/Services/RulesService.cs @@ -1,578 +1,512 @@ -using System; -using System.Data; -using System.Linq; -using System.Linq.Dynamic.Core; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Text.Encodings.Web; -using Microsoft.AspNetCore.Components; -using Microsoft.EntityFrameworkCore; -using Radzen; +namespace ILoan.Rules.Web.Services; -using ILoan.Rules.Web.Data; -using DocumentFormat.OpenXml.InkML; -using ILoan.Rules.Web.Models.Enums; -using ILoan.Rules.Web.Extensions; - -namespace ILoan.Rules.Web +public partial class RulesService(IDbContextFactory factory, NavigationManager navigationManager) { - public partial class RulesService + public void ApplyQuery(ref IQueryable items, Query query = null) { - RulesContext Context + if (query != null) { - get - { - return this.context; - } - } - - private readonly RulesContext context; - private readonly NavigationManager navigationManager; - - public RulesService(RulesContext context, NavigationManager navigationManager) - { - this.context = context; - this.navigationManager = navigationManager; - } - - public void Reset() => Context.ChangeTracker.Entries().Where(e => e.Entity != null).ToList().ForEach(e => e.State = EntityState.Detached); - - public void ApplyQuery(ref IQueryable items, Query query = null) - { - if (query != null) + if (!string.IsNullOrEmpty(query.Filter)) { - if (!string.IsNullOrEmpty(query.Filter)) - { - if (query.FilterParameters != null) - { - items = items.Where(query.Filter, query.FilterParameters); - } - else - { - items = items.Where(query.Filter); - } - } - - if (!string.IsNullOrEmpty(query.OrderBy)) - { - items = items.OrderBy(query.OrderBy); - } - - if (query.Skip.HasValue) - { - items = items.Skip(query.Skip.Value); - } - - if (query.Top.HasValue) - { - items = items.Take(query.Top.Value); - } - } - } - - - public async Task ExportCoreRuleCriteriaOperatorsToExcel(Query query = null, string fileName = null) - { - navigationManager.NavigateTo(query != null ? query.ToUrl($"export/rules/corerulecriteriaoperators/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") : $"export/rules/corerulecriteriaoperators/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", true); - } - - public async Task ExportCoreRuleCriteriaOperatorsToCSV(Query query = null, string fileName = null) - { - navigationManager.NavigateTo(query != null ? query.ToUrl($"export/rules/corerulecriteriaoperators/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") : $"export/rules/corerulecriteriaoperators/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", true); - } - - partial void OnCoreRuleCriteriaOperatorsRead(ref IQueryable items); - - public async Task> GetCoreRuleCriteriaOperators(Query query = null) - { - var items = Context.CoreRuleCriteriaOperators.AsQueryable(); - - items = items.Include(i => i.CoreRule); - - if (query != null) - { - if (!string.IsNullOrEmpty(query.Expand)) - { - var propertiesToExpand = query.Expand.Split(','); - foreach(var p in propertiesToExpand) - { - items = items.Include(p.Trim()); - } - } - - ApplyQuery(ref items, query); + if (query.FilterParameters != null) + items = items.Where(query.Filter, query.FilterParameters); + else + items = items.Where(query.Filter); } - OnCoreRuleCriteriaOperatorsRead(ref items); + if (!string.IsNullOrEmpty(query.OrderBy)) items = items.OrderBy(query.OrderBy); - return await Task.FromResult(items); - } + if (query.Skip.HasValue) items = items.Skip(query.Skip.Value); - partial void OnCoreRuleCriteriaOperatorGet(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator item); - partial void OnGetCoreRuleCriteriaOperatorById(ref IQueryable items); - - - public async Task GetCoreRuleCriteriaOperatorById(int id) - { - var items = Context.CoreRuleCriteriaOperators - .AsNoTracking() - .Where(i => i.ID == id); - - items = items.Include(i => i.CoreRule); - - OnGetCoreRuleCriteriaOperatorById(ref items); - - var itemToReturn = items.FirstOrDefault(); - - OnCoreRuleCriteriaOperatorGet(itemToReturn); - - return await Task.FromResult(itemToReturn); - } - - partial void OnCoreRuleCriteriaOperatorCreated(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator item); - partial void OnAfterCoreRuleCriteriaOperatorCreated(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator item); - - public async Task CreateCoreRuleCriteriaOperator(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator corerulecriteriaoperator) - { - OnCoreRuleCriteriaOperatorCreated(corerulecriteriaoperator); - - var existingItem = Context.CoreRuleCriteriaOperators - .Where(i => i.ID == corerulecriteriaoperator.ID) - .FirstOrDefault(); - - if (existingItem != null) - { - throw new Exception("Item already available"); - } - - try - { - Context.CoreRuleCriteriaOperators.Add(corerulecriteriaoperator); - Context.SaveChanges(); - } - catch - { - Context.Entry(corerulecriteriaoperator).State = EntityState.Detached; - throw; - } - - OnAfterCoreRuleCriteriaOperatorCreated(corerulecriteriaoperator); - - return corerulecriteriaoperator; - } - - public async Task CancelCoreRuleCriteriaOperatorChanges(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator item) - { - var entityToCancel = Context.Entry(item); - if (entityToCancel.State == EntityState.Modified) - { - entityToCancel.CurrentValues.SetValues(entityToCancel.OriginalValues); - entityToCancel.State = EntityState.Unchanged; - } - - return item; - } - - partial void OnCoreRuleCriteriaOperatorUpdated(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator item); - partial void OnAfterCoreRuleCriteriaOperatorUpdated(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator item); - - public async Task UpdateCoreRuleCriteriaOperator(int id, ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator corerulecriteriaoperator) - { - OnCoreRuleCriteriaOperatorUpdated(corerulecriteriaoperator); - - var itemToUpdate = Context.CoreRuleCriteriaOperators - .Where(i => i.ID == corerulecriteriaoperator.ID) - .FirstOrDefault(); - - if (itemToUpdate == null) - { - throw new Exception("Item no longer available"); - } - - var entryToUpdate = Context.Entry(itemToUpdate); - entryToUpdate.CurrentValues.SetValues(corerulecriteriaoperator); - entryToUpdate.State = EntityState.Modified; - - Context.SaveChanges(); - - OnAfterCoreRuleCriteriaOperatorUpdated(corerulecriteriaoperator); - - return corerulecriteriaoperator; - } - - partial void OnCoreRuleCriteriaOperatorDeleted(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator item); - partial void OnAfterCoreRuleCriteriaOperatorDeleted(ILoan.Rules.Web.Models.Rules.CoreRuleCriteriaOperator item); - - public async Task DeleteCoreRuleCriteriaOperator(int id) - { - var itemToDelete = Context.CoreRuleCriteriaOperators - .Where(i => i.ID == id) - .FirstOrDefault(); - - if (itemToDelete == null) - { - throw new Exception("Item no longer available"); - } - - OnCoreRuleCriteriaOperatorDeleted(itemToDelete); - - - Context.CoreRuleCriteriaOperators.Remove(itemToDelete); - - try - { - Context.SaveChanges(); - } - catch - { - Context.Entry(itemToDelete).State = EntityState.Unchanged; - throw; - } - - OnAfterCoreRuleCriteriaOperatorDeleted(itemToDelete); - - return itemToDelete; - } - - public async Task ExportCoreRulesToExcel(Query query = null, string fileName = null) - { - navigationManager.NavigateTo(query != null ? query.ToUrl($"export/rules/corerules/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") : $"export/rules/corerules/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", true); - } - - public async Task ExportCoreRulesToCSV(Query query = null, string fileName = null) - { - navigationManager.NavigateTo(query != null ? query.ToUrl($"export/rules/corerules/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") : $"export/rules/corerules/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", true); - } - - partial void OnCoreRulesRead(ref IQueryable items); - - public async Task> GetCoreRules(Query query = null) - { - var items = Context.CoreRules.AsQueryable(); - - - if (query != null) - { - if (!string.IsNullOrEmpty(query.Expand)) - { - var propertiesToExpand = query.Expand.Split(','); - foreach(var p in propertiesToExpand) - { - items = items.Include(p.Trim()); - } - } - - ApplyQuery(ref items, query); - } - - OnCoreRulesRead(ref items); - - return await Task.FromResult(items); - } - - partial void OnCoreRuleGet(ILoan.Rules.Web.Models.Rules.CoreRule item); - partial void OnGetCoreRuleById(ref IQueryable items); - - - public async Task GetCoreRuleById(int id) - { - var items = Context.CoreRules - .AsNoTracking() - .Where(i => i.ID == id); - - - OnGetCoreRuleById(ref items); - - var itemToReturn = items.FirstOrDefault(); - - OnCoreRuleGet(itemToReturn); - - return await Task.FromResult(itemToReturn); - } - - partial void OnCoreRuleCreated(ILoan.Rules.Web.Models.Rules.CoreRule item); - partial void OnAfterCoreRuleCreated(ILoan.Rules.Web.Models.Rules.CoreRule item); - - public async Task CreateCoreRule(ILoan.Rules.Web.Models.Rules.CoreRule corerule) - { - OnCoreRuleCreated(corerule); - - var existingItem = Context.CoreRules - .Where(i => i.ID == corerule.ID) - .FirstOrDefault(); - - if (existingItem != null) - { - throw new Exception("Item already available"); - } - - try - { - Context.CoreRules.Add(corerule); - Context.SaveChanges(); - } - catch - { - Context.Entry(corerule).State = EntityState.Detached; - throw; - } - - OnAfterCoreRuleCreated(corerule); - - return corerule; - } - - public async Task CancelCoreRuleChanges(ILoan.Rules.Web.Models.Rules.CoreRule item) - { - var entityToCancel = Context.Entry(item); - if (entityToCancel.State == EntityState.Modified) - { - entityToCancel.CurrentValues.SetValues(entityToCancel.OriginalValues); - entityToCancel.State = EntityState.Unchanged; - } - - return item; - } - - partial void OnCoreRuleUpdated(ILoan.Rules.Web.Models.Rules.CoreRule item); - partial void OnAfterCoreRuleUpdated(ILoan.Rules.Web.Models.Rules.CoreRule item); - - public async Task UpdateCoreRule(int id, ILoan.Rules.Web.Models.Rules.CoreRule corerule) - { - OnCoreRuleUpdated(corerule); - - var itemToUpdate = Context.CoreRules - .Where(i => i.ID == corerule.ID) - .FirstOrDefault(); - - if (itemToUpdate == null) - { - throw new Exception("Item no longer available"); - } - - var entryToUpdate = Context.Entry(itemToUpdate); - entryToUpdate.CurrentValues.SetValues(corerule); - entryToUpdate.State = EntityState.Modified; - - Context.SaveChanges(); - - OnAfterCoreRuleUpdated(corerule); - - return corerule; - } - - partial void OnCoreRuleDeleted(ILoan.Rules.Web.Models.Rules.CoreRule item); - partial void OnAfterCoreRuleDeleted(ILoan.Rules.Web.Models.Rules.CoreRule item); - - public async Task DeleteCoreRule(int id) - { - var itemToDelete = Context.CoreRules - .Where(i => i.ID == id) - .Include(i => i.CoreRuleCriteria) - .Include(i => i.CoreRuleCriteriaOperators) - .FirstOrDefault(); - - if (itemToDelete == null) - { - throw new Exception("Item no longer available"); - } - - OnCoreRuleDeleted(itemToDelete); - - - Context.CoreRules.Remove(itemToDelete); - - try - { - Context.SaveChanges(); - } - catch - { - Context.Entry(itemToDelete).State = EntityState.Unchanged; - throw; - } - - OnAfterCoreRuleDeleted(itemToDelete); - - return itemToDelete; - } - - public async Task ExportCoreRuleCriteriaToExcel(Query query = null, string fileName = null) - { - navigationManager.NavigateTo(query != null ? query.ToUrl($"export/rules/corerulecriteria/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") : $"export/rules/corerulecriteria/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", true); - } - - public async Task ExportCoreRuleCriteriaToCSV(Query query = null, string fileName = null) - { - navigationManager.NavigateTo(query != null ? query.ToUrl($"export/rules/corerulecriteria/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") : $"export/rules/corerulecriteria/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", true); - } - - partial void OnCoreRuleCriteriaRead(ref IQueryable items); - - public async Task> GetCoreRuleCriteria(Query query = null) - { - var items = Context.CoreRuleCriteria.AsQueryable(); - - items = items.Include(i => i.CoreRule); - - if (query != null) - { - if (!string.IsNullOrEmpty(query.Expand)) - { - var propertiesToExpand = query.Expand.Split(','); - foreach(var p in propertiesToExpand) - { - items = items.Include(p.Trim()); - } - } - - ApplyQuery(ref items, query); - } - - OnCoreRuleCriteriaRead(ref items); - - return await Task.FromResult(items); - } - - partial void OnCoreRuleCriterionGet(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion item); - partial void OnGetCoreRuleCriterionById(ref IQueryable items); - - - public async Task GetCoreRuleCriterionById(int id) - { - var items = Context.CoreRuleCriteria - .AsNoTracking() - .Where(i => i.ID == id); - - items = items.Include(i => i.CoreRule); - - OnGetCoreRuleCriterionById(ref items); - - var itemToReturn = items.FirstOrDefault(); - - OnCoreRuleCriterionGet(itemToReturn); - - return await Task.FromResult(itemToReturn); - } - - partial void OnCoreRuleCriterionCreated(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion item); - partial void OnAfterCoreRuleCriterionCreated(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion item); - - public async Task CreateCoreRuleCriterion(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion corerulecriterion) - { - OnCoreRuleCriterionCreated(corerulecriterion); - - var existingItem = Context.CoreRuleCriteria - .Where(i => i.ID == corerulecriterion.ID) - .FirstOrDefault(); - - if (existingItem != null) - { - throw new Exception("Item already available"); - } - - try - { - Context.CoreRuleCriteria.Add(corerulecriterion); - Context.SaveChanges(); - } - catch - { - Context.Entry(corerulecriterion).State = EntityState.Detached; - throw; - } - - OnAfterCoreRuleCriterionCreated(corerulecriterion); - - return corerulecriterion; - } - - public async Task CancelCoreRuleCriterionChanges(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion item) - { - var entityToCancel = Context.Entry(item); - if (entityToCancel.State == EntityState.Modified) - { - entityToCancel.CurrentValues.SetValues(entityToCancel.OriginalValues); - entityToCancel.State = EntityState.Unchanged; - } - - return item; - } - - partial void OnCoreRuleCriterionUpdated(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion item); - partial void OnAfterCoreRuleCriterionUpdated(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion item); - - public async Task UpdateCoreRuleCriterion(int id, ILoan.Rules.Web.Models.Rules.CoreRuleCriterion corerulecriterion) - { - OnCoreRuleCriterionUpdated(corerulecriterion); - - var itemToUpdate = Context.CoreRuleCriteria - .Where(i => i.ID == corerulecriterion.ID) - .FirstOrDefault(); - - if (itemToUpdate == null) - { - throw new Exception("Item no longer available"); - } - - var entryToUpdate = Context.Entry(itemToUpdate); - entryToUpdate.CurrentValues.SetValues(corerulecriterion); - entryToUpdate.State = EntityState.Modified; - - Context.SaveChanges(); - - OnAfterCoreRuleCriterionUpdated(corerulecriterion); - - return corerulecriterion; - } - - partial void OnCoreRuleCriterionDeleted(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion item); - partial void OnAfterCoreRuleCriterionDeleted(ILoan.Rules.Web.Models.Rules.CoreRuleCriterion item); - - public async Task DeleteCoreRuleCriterion(int id) - { - var itemToDelete = Context.CoreRuleCriteria - .Where(i => i.ID == id) - .FirstOrDefault(); - - if (itemToDelete == null) - { - throw new Exception("Item no longer available"); - } - - OnCoreRuleCriterionDeleted(itemToDelete); - - - Context.CoreRuleCriteria.Remove(itemToDelete); - - try - { - Context.SaveChanges(); - } - catch - { - Context.Entry(itemToDelete).State = EntityState.Unchanged; - throw; - } - - OnAfterCoreRuleCriterionDeleted(itemToDelete); - - return itemToDelete; - } - - // get properties from CoreRuleCriterion as a disctinct list for type ahead - public List GetProperties() - { - var properties = context.CoreRuleCriteria.Select(c => c.Property).Distinct().OrderBy(x => x).ToList(); - return properties; - } - - public List GetComparisons() - { - return EnumExtensions.ToList(); + if (query.Top.HasValue) items = items.Take(query.Top.Value); } } + partial void OnCoreRuleCriteriaOperatorsRead(ref IQueryable items); + + public async Task> GetCoreRuleCriteriaOperators(Query query = null) + { + var context = await factory.CreateDbContextAsync(); + var items = context.CoreRuleCriteriaOperators.AsQueryable(); + + items = items.Include(i => i.CoreRule); + + if (query != null) + { + if (!string.IsNullOrEmpty(query.Expand)) + { + var propertiesToExpand = query.Expand.Split(','); + foreach (var p in propertiesToExpand) items = items.Include(p.Trim()); + } + + ApplyQuery(ref items, query); + } + + OnCoreRuleCriteriaOperatorsRead(ref items); + + return await Task.FromResult(items); + } + + partial void OnCoreRuleCriteriaOperatorGet(CoreRuleCriteriaOperator item); + partial void OnGetCoreRuleCriteriaOperatorById(ref IQueryable items); + public async Task GetCoreRuleCriteriaOperatorById(int id) + { + var context = await factory.CreateDbContextAsync(); + var items = context.CoreRuleCriteriaOperators + .AsNoTracking() + .Where(i => i.ID == id); + + items = items.Include(i => i.CoreRule); + + OnGetCoreRuleCriteriaOperatorById(ref items); + + var itemToReturn = items.FirstOrDefault(); + + OnCoreRuleCriteriaOperatorGet(itemToReturn); + + return await Task.FromResult(itemToReturn); + } + + partial void OnCoreRuleCriteriaOperatorCreated(CoreRuleCriteriaOperator item); + partial void OnAfterCoreRuleCriteriaOperatorCreated(CoreRuleCriteriaOperator item); + + public async Task CreateCoreRuleCriteriaOperator( + CoreRuleCriteriaOperator corerulecriteriaoperator) + { + OnCoreRuleCriteriaOperatorCreated(corerulecriteriaoperator); + var context = await factory.CreateDbContextAsync(); + + var existingItem = context.CoreRuleCriteriaOperators + .FirstOrDefault(i => i.ID == corerulecriteriaoperator.ID); + + if (existingItem != null) throw new Exception("Item already available"); + + try + { + context.CoreRuleCriteriaOperators.Add(corerulecriteriaoperator); + await context.SaveChangesAsync(); + } + catch + { + context.Entry(corerulecriteriaoperator).State = EntityState.Detached; + throw; + } + + OnAfterCoreRuleCriteriaOperatorCreated(corerulecriteriaoperator); + + return corerulecriteriaoperator; + } + + public async Task CancelCoreRuleCriteriaOperatorChanges(CoreRuleCriteriaOperator item) + { + var context = await factory.CreateDbContextAsync(); + var entityToCancel = context.Entry(item); + if (entityToCancel.State == EntityState.Modified) + { + entityToCancel.CurrentValues.SetValues(entityToCancel.OriginalValues); + entityToCancel.State = EntityState.Unchanged; + } + + return item; + } + + partial void OnCoreRuleCriteriaOperatorUpdated(CoreRuleCriteriaOperator item); + partial void OnAfterCoreRuleCriteriaOperatorUpdated(CoreRuleCriteriaOperator item); + + public async Task UpdateCoreRuleCriteriaOperator(int id, + CoreRuleCriteriaOperator corerulecriteriaoperator) + { + OnCoreRuleCriteriaOperatorUpdated(corerulecriteriaoperator); + + var context = await factory.CreateDbContextAsync(); + var itemToUpdate = context.CoreRuleCriteriaOperators + .FirstOrDefault(i => i.ID == corerulecriteriaoperator.ID); + + if (itemToUpdate == null) throw new Exception("Item no longer available"); + + var entryToUpdate = context.Entry(itemToUpdate); + entryToUpdate.CurrentValues.SetValues(corerulecriteriaoperator); + entryToUpdate.State = EntityState.Modified; + + await context.SaveChangesAsync(); + + OnAfterCoreRuleCriteriaOperatorUpdated(corerulecriteriaoperator); + + return corerulecriteriaoperator; + } + + partial void OnCoreRuleCriteriaOperatorDeleted(CoreRuleCriteriaOperator item); + partial void OnAfterCoreRuleCriteriaOperatorDeleted(CoreRuleCriteriaOperator item); + + public async Task DeleteCoreRuleCriteriaOperator(int id) + { + var context = await factory.CreateDbContextAsync(); + var itemToDelete = context.CoreRuleCriteriaOperators + .FirstOrDefault(i => i.ID == id); + + if (itemToDelete == null) throw new Exception("Item no longer available"); + + OnCoreRuleCriteriaOperatorDeleted(itemToDelete); + + + context.CoreRuleCriteriaOperators.Remove(itemToDelete); + + try + { + await context.SaveChangesAsync(); + } + catch + { + context.Entry(itemToDelete).State = EntityState.Unchanged; + throw; + } + + OnAfterCoreRuleCriteriaOperatorDeleted(itemToDelete); + + return itemToDelete; + } + + public async Task ExportCoreRulesToExcel(Query query = null, string fileName = null) + { + navigationManager.NavigateTo( + query != null + ? query.ToUrl( + $"export/rules/corerules/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") + : $"export/rules/corerules/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", + true); + } + + public async Task ExportCoreRulesToCSV(Query query = null, string fileName = null) + { + navigationManager.NavigateTo( + query != null + ? query.ToUrl( + $"export/rules/corerules/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") + : $"export/rules/corerules/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", + true); + } + + partial void OnCoreRulesRead(ref IQueryable items); + + public async Task> GetCoreRules(Query query = null) + { + var context = await factory.CreateDbContextAsync(); + var items = context.CoreRules.AsQueryable(); + + + if (query != null) + { + if (!string.IsNullOrEmpty(query.Expand)) + { + var propertiesToExpand = query.Expand.Split(','); + foreach (var p in propertiesToExpand) items = items.Include(p.Trim()); + } + + ApplyQuery(ref items, query); + } + + OnCoreRulesRead(ref items); + + return await Task.FromResult(items); + } + + partial void OnCoreRuleGet(CoreRule item); + partial void OnGetCoreRuleById(ref IQueryable items); + + + public async Task GetCoreRuleById(int id) + { + var context = await factory.CreateDbContextAsync(); + var items = context.CoreRules + .AsNoTracking() + .Where(i => i.ID == id); + + + OnGetCoreRuleById(ref items); + + var itemToReturn = items.FirstOrDefault(); + + OnCoreRuleGet(itemToReturn); + + return await Task.FromResult(itemToReturn); + } + + partial void OnCoreRuleCreated(CoreRule item); + partial void OnAfterCoreRuleCreated(CoreRule item); + + public async Task CreateCoreRule(CoreRule corerule) + { + OnCoreRuleCreated(corerule); + + var context = await factory.CreateDbContextAsync(); + var existingItem = context.CoreRules + .FirstOrDefault(i => i.ID == corerule.ID); + + if (existingItem != null) throw new Exception("Item already available"); + + try + { + context.CoreRules.Add(corerule); + await context.SaveChangesAsync(); + } + catch + { + context.Entry(corerule).State = EntityState.Detached; + throw; + } + + OnAfterCoreRuleCreated(corerule); + + return corerule; + } + + public async Task CancelCoreRuleChanges(CoreRule item) + { + var context = await factory.CreateDbContextAsync(); + var entityToCancel = context.Entry(item); + if (entityToCancel.State == EntityState.Modified) + { + entityToCancel.CurrentValues.SetValues(entityToCancel.OriginalValues); + entityToCancel.State = EntityState.Unchanged; + } + + return item; + } + + partial void OnCoreRuleUpdated(CoreRule item); + partial void OnAfterCoreRuleUpdated(CoreRule item); + + public async Task UpdateCoreRule(int id, CoreRule corerule) + { + OnCoreRuleUpdated(corerule); + + var context = await factory.CreateDbContextAsync(); + var itemToUpdate = context.CoreRules + .FirstOrDefault(i => i.ID == corerule.ID); + + if (itemToUpdate == null) throw new Exception("Item no longer available"); + + var entryToUpdate = context.Entry(itemToUpdate); + entryToUpdate.CurrentValues.SetValues(corerule); + entryToUpdate.State = EntityState.Modified; + + await context.SaveChangesAsync(); + + OnAfterCoreRuleUpdated(corerule); + + return corerule; + } + + partial void OnCoreRuleDeleted(CoreRule item); + partial void OnAfterCoreRuleDeleted(CoreRule item); + + public async Task DeleteCoreRule(int id) + { + var context = await factory.CreateDbContextAsync(); + var itemToDelete = context.CoreRules + .Where(i => i.ID == id) + .Include(i => i.CoreRuleCriteria) + .Include(i => i.CoreRuleCriteriaOperators) + .FirstOrDefault(); + + if (itemToDelete == null) throw new Exception("Item no longer available"); + + OnCoreRuleDeleted(itemToDelete); + + + context.CoreRules.Remove(itemToDelete); + + try + { + await context.SaveChangesAsync(); + } + catch + { + context.Entry(itemToDelete).State = EntityState.Unchanged; + throw; + } + + OnAfterCoreRuleDeleted(itemToDelete); + + return itemToDelete; + } + + public async Task ExportCoreRuleCriteriaToExcel(Query query = null, string fileName = null) + { + navigationManager.NavigateTo( + query != null + ? query.ToUrl( + $"export/rules/corerulecriteria/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") + : $"export/rules/corerulecriteria/excel(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", + true); + } + + public async Task ExportCoreRuleCriteriaToCSV(Query query = null, string fileName = null) + { + navigationManager.NavigateTo( + query != null + ? query.ToUrl( + $"export/rules/corerulecriteria/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')") + : $"export/rules/corerulecriteria/csv(fileName='{(!string.IsNullOrEmpty(fileName) ? UrlEncoder.Default.Encode(fileName) : "Export")}')", + true); + } + + partial void OnCoreRuleCriteriaRead(ref IQueryable items); + + public async Task> GetCoreRuleCriteria(Query query = null) + { + var context = await factory.CreateDbContextAsync(); + var items = context.CoreRuleCriteria.AsQueryable(); + + items = items.Include(i => i.CoreRule); + + if (query != null) + { + if (!string.IsNullOrEmpty(query.Expand)) + { + var propertiesToExpand = query.Expand.Split(','); + foreach (var p in propertiesToExpand) items = items.Include(p.Trim()); + } + + ApplyQuery(ref items, query); + } + + OnCoreRuleCriteriaRead(ref items); + + return await Task.FromResult(items); + } + + partial void OnCoreRuleCriterionGet(CoreRuleCriterion item); + partial void OnGetCoreRuleCriterionById(ref IQueryable items); + + + public async Task GetCoreRuleCriterionById(int id) + { + var context = await factory.CreateDbContextAsync(); + var items = context.CoreRuleCriteria + .AsNoTracking() + .Where(i => i.ID == id); + + items = items.Include(i => i.CoreRule); + + OnGetCoreRuleCriterionById(ref items); + + var itemToReturn = items.FirstOrDefault(); + + OnCoreRuleCriterionGet(itemToReturn); + + return await Task.FromResult(itemToReturn); + } + + partial void OnCoreRuleCriterionCreated(CoreRuleCriterion item); + partial void OnAfterCoreRuleCriterionCreated(CoreRuleCriterion item); + + public async Task CreateCoreRuleCriterion(CoreRuleCriterion corerulecriterion) + { + OnCoreRuleCriterionCreated(corerulecriterion); + var context = await factory.CreateDbContextAsync(); + + var existingItem = context.CoreRuleCriteria + .FirstOrDefault(i => i.ID == corerulecriterion.ID); + + if (existingItem != null) throw new Exception("Item already available"); + + try + { + context.CoreRuleCriteria.Add(corerulecriterion); + await context.SaveChangesAsync(); + } + catch + { + context.Entry(corerulecriterion).State = EntityState.Detached; + throw; + } + + OnAfterCoreRuleCriterionCreated(corerulecriterion); + + return corerulecriterion; + } + + public async Task CancelCoreRuleCriterionChanges(CoreRuleCriterion item) + { + var context = await factory.CreateDbContextAsync(); + var entityToCancel = context.Entry(item); + if (entityToCancel.State == EntityState.Modified) + { + entityToCancel.CurrentValues.SetValues(entityToCancel.OriginalValues); + entityToCancel.State = EntityState.Unchanged; + } + + return item; + } + + partial void OnCoreRuleCriterionUpdated(CoreRuleCriterion item); + partial void OnAfterCoreRuleCriterionUpdated(CoreRuleCriterion item); + + public async Task UpdateCoreRuleCriterion(int id, CoreRuleCriterion corerulecriterion) + { + OnCoreRuleCriterionUpdated(corerulecriterion); + var context = await factory.CreateDbContextAsync(); + + var itemToUpdate = context.CoreRuleCriteria + .FirstOrDefault(i => i.ID == corerulecriterion.ID); + + if (itemToUpdate == null) throw new Exception("Item no longer available"); + + var entryToUpdate = context.Entry(itemToUpdate); + entryToUpdate.CurrentValues.SetValues(corerulecriterion); + entryToUpdate.State = EntityState.Modified; + + await context.SaveChangesAsync(); + + OnAfterCoreRuleCriterionUpdated(corerulecriterion); + + return corerulecriterion; + } + + partial void OnCoreRuleCriterionDeleted(CoreRuleCriterion item); + partial void OnAfterCoreRuleCriterionDeleted(CoreRuleCriterion item); + + public async Task DeleteCoreRuleCriterion(int id) + { + var context = await factory.CreateDbContextAsync(); + var itemToDelete = context.CoreRuleCriteria + .FirstOrDefault(i => i.ID == id); + + if (itemToDelete == null) throw new Exception("Item no longer available"); + + OnCoreRuleCriterionDeleted(itemToDelete); + + + context.CoreRuleCriteria.Remove(itemToDelete); + + try + { + await context.SaveChangesAsync(); + } + catch + { + context.Entry(itemToDelete).State = EntityState.Unchanged; + throw; + } + + OnAfterCoreRuleCriterionDeleted(itemToDelete); + + return itemToDelete; + } + + // get properties from CoreRuleCriterion as a disctinct list for type ahead + public List GetProperties() + { + var context = factory.CreateDbContext(); + var properties = context.CoreRuleCriteria.Select(c => c.Property).Distinct().OrderBy(x => x).ToList(); + return properties; + } + + public List GetComparisons() + { + return EnumExtensions.ToList(); + } } \ No newline at end of file diff --git a/src/iLoan.Rules.Web/Usings.cs b/src/iLoan.Rules.Web/Usings.cs new file mode 100644 index 0000000..8f1fc69 --- /dev/null +++ b/src/iLoan.Rules.Web/Usings.cs @@ -0,0 +1,11 @@ +// Global using directives + +global using ILoan.Rules.Web.Data; +global using ILoan.Rules.Web.Extensions; +global using ILoan.Rules.Web.Models.Enums; +global using ILoan.Rules.Web.Models.Rules; +global using Microsoft.AspNetCore.Components; +global using Microsoft.EntityFrameworkCore; +global using Radzen; +global using System.Linq.Dynamic.Core; +global using System.Text.Encodings.Web; diff --git a/src/iLoan.Rules.Web/appsettings.json b/src/iLoan.Rules.Web/appsettings.json index 4ed5d73..5d086b7 100644 --- a/src/iLoan.Rules.Web/appsettings.json +++ b/src/iLoan.Rules.Web/appsettings.json @@ -18,7 +18,7 @@ }, "Parameters": { "GeneratorRoot": "C:\\iloan\\iloan-base-dev\\migrations", - "StartSeqNo": 104, + "StartSeqNo": 117, "StartRuleId": 480 } } \ No newline at end of file