using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using CAPI.Custom; using CAPI.Custom.Data; using CAPI.Custom.Entities; using System.IO; using CAPI.Custom.Security; using System.Threading; using System.Reflection; using System.Diagnostics; using System.Text.RegularExpressions; using System.Globalization; using System.Data.Entity.Design.PluralizationServices; using System.IO; using CAPI.Custom.Services; using NLog; using framework_business; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using framework_library; namespace CEP.ConsoleTests { class Program { static readonly string EMO_PASSED = ":heavy_check_mark:"; static readonly string EMO_FAILED = ":x:"; static void Main(string[] args) { EnvBootstrap.Load(AppDomain.CurrentDomain.BaseDirectory); SetPrincipal(); List> tests = new List>() { //TestLeadTimes(), //TestReadUserIdFromCurrentThread(), //stSurfaceNames(), //TestProcessQuote(), //TestCreateQuote(), //TestCreateSurfaceItem(), }; new List() { //new TestQuoteProcess().RunTest(), new Quotes.TestQuoteInMemoryProcessing().RunTest() }.ForEach(result => { var outputFilename = $"{result.Name}-output.md"; File.WriteAllText(outputFilename, result.Output); Process.Start(outputFilename); }); foreach(var result in tests) { var outputFilename = $"{result.Item1}-output.md"; File.WriteAllText(outputFilename, result.Item2); Process.Start(outputFilename); } Console.Write("> End of line."); Console.ReadKey(); } static void SetPrincipal() { int userId = 219; var principal = new CustomPrincipal(userId.ToString()) { Id = userId }; Thread.CurrentPrincipal = principal; } static Tuple TestLeadTimes() { var methodName = MethodBase.GetCurrentMethod().Name; Console.WriteLine($"Executing: {methodName} ..."); StringBuilder output = new StringBuilder($"# {methodName}"); var now = DateTime.Now; var outputFilename = $"{methodName}-output.md"; var leadtimesfile = "leadtimes.txt"; var leadTimes = new List(); using (var reader = new StreamReader(leadtimesfile)) { while (!reader.EndOfStream) { var leadTimeString = reader.ReadLine().Trim(); leadTimes.Add(new LeadTime(leadTimeString)); } reader.Close(); } // sort by string input value leadTimes = leadTimes.OrderBy(p => p.OriginalValue).ToList(); // sort by timespan var sortedleadTimes = leadTimes.OrderBy(p => p.ToTimeSpan()).ToList(); Func lineFormat = (lt) => $"| {leadTimes.IndexOf(lt)} | {lt.OriginalValue} | {lt} |"; Func sordedLineFormat = (lt) => $"| {leadTimes.IndexOf(lt)} | {lt.OriginalValue} | {lt} | {lt.ToTimeSpan()} |"; // write output output .AppendLine() .AppendLine($"Executed Date: _{now.ToLongDateString()} {now.ToLongTimeString()}_") .AppendLine() .AppendLine("## Resolving LeadTimes") .AppendLine() .AppendLine("**Input String** is a list of all values existing in the database.") .AppendLine() .AppendLine("## Sorted by Input String") .AppendLine() .AppendLine("| # | Input String | Output String |") .AppendLine("|:-:| ------------ | ------------- |"); leadTimes.ForEach(p => output.AppendLine(lineFormat(p))); output .AppendLine() .AppendLine("## Sorted By LeadTime conversion") .AppendLine() .AppendLine("| # | Input String | Output String | TimeSpan (dd:hh:mm:ss) |") .AppendLine("|:-:| ------------ | ------------- | ----------------------:|"); sortedleadTimes.ForEach(p => output.AppendLine(sordedLineFormat(p))); return new Tuple(methodName, output.ToString()); } static Tuple TestReadUserIdFromCurrentThread() { var methodName = MethodBase.GetCurrentMethod().Name; Console.WriteLine($"Executing: {methodName} ..."); StringBuilder output = new StringBuilder($"# {methodName}"); var now = DateTime.Now; int userId = 219; //var principal = new CustomPrincipal(userId.ToString()) //{ // Id = userId //}; //Thread.CurrentPrincipal = principal; var expected = userId; var actual = BusinessUtils.User.Id; var passed = expected == actual; var icon = passed ? EMO_PASSED : EMO_FAILED; output .AppendLine() .AppendLine($"Executed Date: _{now.ToLongDateString()} {now.ToLongTimeString()}_") .AppendLine() .AppendLine("## Setting UserId as IPrincipal on CurrentThread") .AppendLine() .AppendLine($"Set a CustomPrincipal to the CurrentThread and check if CAPI.Custom.BusinessUtils reads it") .AppendLine() .AppendLine("| Passed | Expected | Actual |") .AppendLine("|:------:|:--------:|:------:|") .AppendLine($"| {icon} | {expected} | {actual} |"); return new Tuple(methodName, output.ToString()); } static Tuple TestSurfaceNames() { var methodName = MethodBase.GetCurrentMethod().Name; Console.WriteLine($"Executing: {methodName} ..."); StringBuilder output = new StringBuilder($"# {methodName}"); var db = QuotesContext.Create(); var surfaces = db.Surfaces.ToList(); var entitiesNamespace = typeof(SurfaceItem).Namespace; var resolveItems = new List(); var entityTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetTypes()) .Where(t => t.IsClass && t.Namespace == entitiesNamespace && t.GetInterfaces().Contains(typeof(ISurfaceEntity)) ) .OrderBy(t => t.Name) .ToList(); entityTypes.ForEach(t => { var surfaceName = db.GetSurfaceName(t.Name); var surface = db.GetSurfaceByName(surfaceName); resolveItems.Add(new SurfaceResolveItem { Resolved = surface.IsNotNull(), SurfaceName = surfaceName, TypeName = t.Name }); }); var now = DateTime.Now; Func rowFormat = (i) => string.Join(" | ", new string[] { "", i.ResolvedIcon, i.TypeName, i.SurfaceName, "" }).Trim(); var newLinePattern = @"[\n\r]+"; string testDescription = @"This test gathers all classes inside the namespace `CAPI.Custom.Entities` which implement the interface `ISurfaceItem`. It then uses the method `Quotes.Context.GetSurfaceName(string typeName)` and `QuotesContext.GetSurfaceByName(string surfaceName)` to ensure all ISurfaceItem classes have a corresponding valid surface name." .Flatten(); output .AppendLine() .AppendLine($"Executed Date: _{now.ToLongDateString()} {now.ToLongTimeString()}_") .AppendLine() .AppendLine("## Resolving Surface names using Entity Type Names") .AppendLine() .AppendLine(testDescription) .AppendLine() .AppendLine("| Passed | Type Name | Surface Name |") .AppendLine("|:------:| --------- | ------------ |"); resolveItems.ForEach(p => output.AppendLine(rowFormat(p))); return new Tuple(methodName, output.ToString()); } static Tuple TestProcessQuote() { var methodName = MethodBase.GetCurrentMethod().Name; Console.WriteLine($"Executing: {methodName} ..."); StringBuilder output = new StringBuilder($"# {methodName}") .AppendLine(); string logFilename = "TestProcessQuote.log"; File.Create(logFilename).Close(); var quoteId = 16244668; var db = QuotesContext.Create(); ILogger logger = LogManager.GetLogger("TestProcessQuote"); var processor = new QuoteProcessor(db, logger); processor.ProcessQuote(quoteId); output.AppendLine("## NLog output") .AppendLine("```bash") .AppendLine(File.ReadAllText(logFilename)) .AppendLine("```"); return new Tuple(methodName, output.ToString()); } //static Tuple TestCreateQuote() //{ // var methodName = MethodBase.GetCurrentMethod().Name; // Console.WriteLine($"Executing: {methodName} ..."); // StringBuilder output = new StringBuilder($"# {methodName}") // .AppendLine(); // string logFilename = $"{methodName}.log"; // File.Create(logFilename).Close(); // ILogger logger = LogManager.GetLogger(methodName); // var db = QuotesContext.Create(); // var customer = db.Customers.FirstOrDefault(p => // p.CustomerDetails_CustomerDetails_CustomerTradingName.Contains("demonstration") // ); // var enquiryItems = new List(); // // read enquiry part numbers and quantities from file // using(var reader = new StreamReader(@"quotes\enquiryparts.txt")) // { // while (!reader.EndOfStream) // { // var line = reader.ReadLine(); // int sequence = 1; // if (line.IsNotEmpty()) // { // var values = line.Split('\t'); // var partNumber = values[0]; // var quantity = values[1].TryParseInt().GetValueOrDefault(); // enquiryItems.Add(new QuoteEnquiryItem // { // QuoteEnquiryItems_QuoteEnquiryItems_PartNumber = partNumber, // QuoteEnquiryItems_QuoteEnquiryItems_Quantity = quantity, // QuoteEnquiryItems_QuoteEnquiryItems_Sequence = sequence++ // }); // } // } // } // var quote = db.Quote_Create(customer.itemID); // logger.Info($"Created Quote: {quote.QuoteInformation_QuoteNumber}"); // // create enquiry items // enquiryItems.ForEach(p => // { // p.ParentSurfaceItemId = quote.itemID; // BusinessUtils.Create(p); // }); // db.Quotes_ProcessEnquiryItems5(quote.itemID); // //var quoteProcessor = new QuoteProcessor(logger: logger); // //quoteProcessor.ProcessQuote(quote.itemID); // //output.AppendLine("## NLog output") // // .AppendLine("```bash") // // .AppendLine(File.ReadAllText(logFilename)) // // .AppendLine("```"); // return new Tuple(methodName, output.ToString()); //} static Tuple TestCreateSurfaceItem() { var methodName = MethodBase.GetCurrentMethod().Name; Console.WriteLine($"Executing: {methodName} ..."); StringBuilder output = new StringBuilder($"# {methodName}") .AppendLine(); var db = new QuotesContext(); var surface = db.GetSurface(); var surfaceItem = new SurfaceItem { surfaceId = surface.recId }; db.SurfaceItems.Add(surfaceItem); db.SaveChanges(); var item = new InventoryManagement() { AverageUnitCost = 111, Area = "Area", TotalOnHandValue = 111, Bay = "Bay", Bin = "Bin", BinLocation = "BinLocation", Brand = "Brand", Condition = "Condition", Description = "Description", Isle = "Isle", PartNumber = "PartNumber", Position = "Position", Shelf = "Shelf", UniqueNumber = "UniqueNumber", WarehouseLocationName = "Warehouse", Available = 111, Committed = 0, OnHand = 111, OnOrder = 0, itemID = surfaceItem.recId, ParentSurfaceItemId = 123456, surfaceId = surface.recId }; //var oManagementItem = new oInventoryManagement() //{ // InventoryManagement_InventoryManagementFinancialDetails_InventoryManagementAverageUnitCost = "111", // InventoryManagement_InventoryManagementLocation_InventoryManagementArea = "Area", // InventoryManagement_InventoryManagementFinancialDetails_InventoryManagementTotalOnHandValue = "111", // InventoryManagement_InventoryManagementLocation_InventoryManagementBay = "Bay", // InventoryManagement_InventoryManagementLocation_InventoryManagementBin = "Bin", // InventoryManagement_InventoryManagementLocation_InventoryManagementBinLocation = "BinLocation", // InventoryManagement_InventoryManagementLocation_InventoryManagementBrand = "Brand", // InventoryManagement_InventoryManagementLocation_InventoryManagementCondition = "Condition", // InventoryManagement_InventoryManagementLocation_InventoryManagementDescription = "Description", // InventoryManagement_InventoryManagementLocation_InventoryManagementIsle = "Isle", // InventoryManagement_InventoryManagementLocation_InventoryManagementPartNumber = "PartNumber", // InventoryManagement_InventoryManagementLocation_InventoryManagementPosition = "Position", // InventoryManagement_InventoryManagementLocation_InventoryManagementShelf = "Shelf", // InventoryManagement_InventoryManagementLocation_InventoryManagementUniqueNumber = "UniqueNumber", // InventoryManagement_InventoryManagementLocation_WarehouseLocationName = "Warehouse", // InventoryManagement_InventoryManagementStockDetails_InventoryManagementAvailable = "111", // InventoryManagement_InventoryManagementStockDetails_InventoryManagementCommitted = "0", // InventoryManagement_InventoryManagementStockDetails_InventoryManagementOnHand = "111", // InventoryManagement_InventoryManagementStockDetails_InventoryManagementOnOrder = "0", // itemID = surfaceItem.recId, // ParentSurfaceItemId = "132456", // surfaceId = surface.recId //}; //int sepa = xDataAlt.SaveTyped("recId", typeof(oInventoryManagement), oManagementItem); //var inserted = xData.SaveTyped(nameof(item.recId), typeof(oInventoryManagement), item, tablePrefix: "qt_"); var surfaceInfo = (from s in db.Surfaces join f in db.SurfaceFields on s.recId equals f.surfaceId join t in db.SurfaceFieldTypes on f.surfaceFieldTypeId equals t.recId where s.recId == surface.recId && !new string[] { "Tab", "Group" }.Contains(t.surfaceFieldType) select new SurfaceFieldInfo { SurfaceId = s.recId, SurfaceName = s.name, SurfaceDisplay = s.surface, IsPublished = s.isPublished ?? false, FieldId = f.recId, FieldName = f.surfaceFieldName, FieldShortName = f.controlText, FieldType = t.surfaceFieldType, FieldTypeId = t.recId, RelationalFields = f.relationalFields }).ToList(); output.AppendLine($"## {surface.name}") .AppendLine("### Fields") .AppendLine("| Field Name | Field Type |") .AppendLine("|:---------- |:----------:|"); var properties = typeof(InventoryManagement).GetProperties(BindingFlags.Public | BindingFlags.Instance); var lookupValues = db.SurfaceLookupCategories.Where(p => new string[] { "Inventory Location Alpha", "Inventory Location Number" }.Contains(p.lookupCategory)) .SelectMany(p => p.SufaceLookups); var rows = new List(); var insertQueries = new Dictionary(); //foreach (var field in surfaceInfo) //{ // rows.Add($"|{field.FieldName}|{field.FieldType}|"); // var prop = properties.FirstOrDefault(p => p.GetCustomAttribute()?.Name == field.FieldName); // var propVal = prop.GetValue(item).ToString(); // string sql = string.Empty; // int lookupId = field.RelationalFields.IsEmpty() // ? 0 : lookupValues.FirstOrDefault(p => p.Display == propVal)?.recId ?? 0; // sql = $@"INSERT INTO [pal_SurfaceFieldData] // ([surfaceId],[surfaceItemId], [surfaceFieldID], [surfaceFieldValueDate] // ,[surfaceFieldValueDecimal], [surfaceFieldValueChar], [surfaceFieldValueNum] // ,[surfaceFieldValueBool], [surfaceFieldValueTime], [surfaceFieldLookupID]) // VALUES // ({item.surfaceId} // ,{item.itemID} // ,{field.FieldId} // ,'1900-01-01' // ,0 // ,'{(!"ParentSurfaceItemId".Equals(field.FieldName) ? propVal : "")}' // ,{("ParentSurfaceItemId".Equals(field.FieldName) ? item.ParentSurfaceItemId : "0")} // ,0 // ,'1900-01-01' // ,{lookupId})".Flatten(); // insertQueries.Add(field.FieldName, sql); //} rows.ForEach(p => output.AppendLine(p)); foreach(var pair in insertQueries) { output.AppendLine($"**{pair.Key}**") .AppendLine("```sql") .AppendLine(pair.Value) .AppendLine("```"); } //xData.SaveSurfaceItemToQueryTable() //var surfaceFields = db.SurfaceFields.Where(p => p.surfaceId == surface.recId); Console.WriteLine(surface.name); //foreach(var field in surfaceFields) //{ // Console.WriteLine($"\t{field.surfaceFieldName}"); //} return new Tuple(methodName, output.ToString()); } #region Nested Classes public class SurfaceFieldInfo { public int SurfaceId { get; set; } public string SurfaceName { get; set; } public string SurfaceDisplay { get; set; } public bool IsPublished { get; set; } public int FieldId { get; set; } public string FieldName { get; set; } public string FieldShortName { get; set; } public string FieldType { get; set; } public int FieldTypeId { get; set; } public string RelationalFields { get; set; } } #endregion } }