using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using Comal.Classes; using InABox.Clients; using InABox.Configuration; using InABox.Core; using InABox.Database; using InABox.Database.SQLite; using InABox.DynamicGrid; using InABox.WPF; using Org.BouncyCastle.Math.EC.Multiplier; using Syncfusion.Windows.Controls; using MessageBox = System.Windows.MessageBox; namespace PRSDesktop { public class Utility { //private void UpgradeShipmentLinks(Entity[] notifications) //{ // int i = 1; // foreach (DeliveryNotification notification in notifications) // { // Progress.SetMessage(String.Format("Converting Delivery Notifications {0} / {1}", i, notifications.Length)); // notification.ShipmentLink = new ShipmentLink(); // if (notification.Shipment != null) // { // notification.ShipmentLink.ID = notification.Shipment.ID; // notification.Shipment = null; // } // i++; // } //} private static bool HasDocumentLinks() { var props = typeof(T).GetProperties().Where(x => x.PropertyType.Equals(typeof(DocumentLink)) || x.PropertyType.Equals(typeof(ImageDocumentLink)) || x.PropertyType.Equals(typeof(PDFDocumentLink))); return props.Any(); } private static Guid[] GetDocuments(T entity) { var result = new List(); var props = typeof(T).GetProperties().Where(x => x.PropertyType.Equals(typeof(DocumentLink)) || x.PropertyType.Equals(typeof(ImageDocumentLink)) || x.PropertyType.Equals(typeof(PDFDocumentLink))); foreach (var prop in props) { var link = (IEntityLink)prop.GetValue(entity); if (link.IsValid()) result.Add(link.ID); } return result.ToArray(); } //private static bool CopyType(int typeno, int typecount, IProvider source, IProvider target) where T : Entity, new() //{ // String name = typeof(T).EntityName().Split('.').Last(); // //if (!HasDocumentLinks()) // // return false; // Progress.SetMessage(String.Format("[{0}/{1}] {2}: Loading Source Items..", typeno, typecount, name)); // var sourceitems = source.Load(); // Progress.SetMessage(String.Format("[{0}/{1}] {2}: Loading Target Items..", typeno, typecount, name)); // var targetitems = target.Load(); // //if (sourceitems.Count() == targetitems.Count()) // // return false; // //Progress.SetMessage(String.Format("[{0}/{1}] {2}: Deleting Target Items..", typeno, typecount, name)); // //foreach (var targetitem in targetitems) // // target.Delete(targetitem); // for (int i=0; i()) // { // var audits = source.Load(new Filter(x => x.EntityID).IsEqualTo(sourceitem.ID)); // foreach (var audit in audits) // target.Save(audit); // } // if (sourceitem is IEntityDocument) // { // var entdoc = (IEntityDocument)sourceitem; // if (entdoc.DocumentLink.ID != Guid.Empty) // { // var doc = source.Load(new Filter(x => x.ID).IsEqualTo(entdoc.DocumentLink.ID)).FirstOrDefault(); // if (doc != null) // target.Save(doc); // else // entdoc.DocumentLink.ID = Guid.Empty; // } // } // Guid[] docids = GetDocuments(sourceitem); // foreach (var docid in docids) // { // var doc = source.Load(new Filter(x => x.ID).IsEqualTo(docid)).FirstOrDefault(); // if (doc != null) // target.Save(doc); // } // target.Delete(sourceitem); // target.Save(sourceitem); // } // target.CommitTransaction(); // return true; // #region oldcode // //open.Invoke(target, new object[] { "Duplicate", true }); // ////if (items.Length != orig.Count) // //{ // // Progress.SetMessage(string.Format("{0}/{1} {2}: Clearing..", t + 1, types.Count, type.Name)); // // for (int i = 0; i < orig.Count; i++) // // { // // //Progress.SetMessage(string.Format("{0}/{1} {2}: Resetting ({3:F2}% complete)..", t + 1, types.Length, type.Name, (double)i * 100.0F / (double)orig.Count)); // // delete.Invoke(target, new object[] { orig[i] }); // // } // // Progress.SetMessage(string.Format("{0}/{1} {2}: Rebuilding..", t + 1, types.Count, type.Name)); // // for (int i = 0; i < items.Count; i++) // // { // // //if (i > 10) // // // return; // // var item = items[i]; // // //double progress = (double)i * 100.0F / (double)items.Length; // // ////Progress.SetMessage(string.Format("{0}/{1} {2}: Copying ({3:F2}% complete)..", t + 1, types.Length, type.Name, progress)); // // //// Check and copy source document if required // // //if (item is IEntityDocument) // // //{ // // // var entdoc = (IEntityDocument)item; // // // var doccli = new RemoteClient(URL, Port); // // // doccli.UserID = "FROGSOFTWARE"; // // // doccli.Password = "FROGSOFTWARE"; // // // //Progress.SetMessage(string.Format("{0}/{1} {2}: Copying (Documents)", t + 1, types.Length, type.Name)); // // // var docfilter = new Filter(x => x.ID).IsEqualTo(entdoc.DocumentLink.ID); // // // var document = doccli.Load(docfilter).FirstOrDefault(); ; // // // if (document != null) // // // target.Save(document); // // //} // // //Progress.SetMessage(string.Format("{0}/{1} {2}: Copying ({3:F2}% complete).. (Saving)", t + 1, types.Length, type.Name, progress)); // // save.Invoke(target, new object[] { item }); // // //Dictionary values = item.GetValues(true); // // //var member = CoreUtils.GetMemberExpression(type, "ID"); // // //var filter = Activator.CreateInstance(typeof(Filter<>).MakeGenericType(type)); // // //CoreUtils.SetPropertyValue(filter, "Expression", member); // // //CoreUtils.SetPropertyValue(filter, "Operator", Operator.IsEqualTo); // // //CoreUtils.SetPropertyValue(filter, "Value", item.ID); // // //BaseObject[] compare = (BaseObject[])(load.Invoke(provider, new object[] { filter, null })); // // //BaseObject newitem = compare.FirstOrDefault(); // // //if (newitem != null) // // //{ // // // var changes = newitem.Compare(values); // // // if (changes.Any()) // // // throw new Exception(String.Format("Object Values have changed!\n\n{0}", String.Join("\n", changes))); // // //} // // } // //} // //target.CommitTransaction(); // //close.Invoke(target, new object[] { "Duplicate", true }); // #endregion //} private static List CompareType(int typeno, int typecount, IProvider source, IProvider target) where T : Entity, new() { var result = new List(); var name = typeof(T).EntityName().Split('.').Last(); Progress.SetMessage(string.Format("[{0}/{1}] {2}: Reloading Source Table..", typeno, typecount, name)); //var items = local.Load(); var sourcetable = source.Query(); Progress.SetMessage(string.Format("[{0}/{1}] {2}: Reloading Target Table..", typeno, typecount, name)); var targettable = target.Query(); for (var i = 0; i < sourcetable.Rows.Count; i++) { Progress.SetMessage(string.Format("[{0}/{1}] {2}: Comparing Values ({3:F2}% complete)..", typeno, typecount, name, (double)i * 100.0F / sourcetable.Rows.Count)); var sourcerow = sourcetable.Rows[i]; var id = sourcerow.Get("ID"); var targetrow = targettable.Rows.FirstOrDefault(r => r.Get("ID").Equals(id)); if (targetrow == null) result.Add(string.Format("{0}: Row [{1}] is missing in target database", name, id)); else foreach (var col in targettable.Columns) { var targetvalue = targetrow[col.ColumnName]; var sourcevalue = sourcerow[col.ColumnName]; if (targetvalue == null) { if (sourcevalue != null) result.Add(string.Format("{0}: Row [{1}].{2} is null in target, but [{3}] in source", name, id, col.ColumnName, sourcevalue)); } else if (!targetvalue.Equals(sourcevalue)) { result.Add(string.Format("{0}: Row [{1}].{2} is [{3}] in target, but [{4}] in source", name, id, col.ColumnName, targetvalue, sourcevalue)); } } } return result; } private static void LoadType(Type type, List into, Type[] exclude) { if (exclude.Contains(type) || into.Contains(type)) return; var props = type.GetProperties().Where(x => x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))); if (!props.Any()) { into.Insert(0, type); } else { foreach (var prop in props) { var subtype = prop.PropertyType.BaseType.GetGenericArguments().First(); if (subtype != type) LoadType(subtype, into, exclude); } into.Add(type); } } public static void DuplicateDatabase() { using (var ofd = new OpenFileDialog()) { ofd.Filter = "SQLite Database Files (*.dbs)|*.dbs"; ofd.DefaultExt = "dbs"; ofd.InitialDirectory = Path.GetDirectoryName(DbFactory.Provider.URL); ofd.FileName = ""; ofd.Multiselect = false; ofd.CheckFileExists = true; var result = ofd.ShowDialog(); if (result != DialogResult.OK || string.IsNullOrWhiteSpace(ofd.FileName)) return; BaseObject.GlobalObserving = false; IProvider source = new SQLiteProvider(ofd.FileName); Progress.Show("Opening Source Database"); source.Types = DbFactory.Provider.Types; source.Start(); try { var types = CoreUtils.TypeList( AppDomain.CurrentDomain.GetAssemblies(), x => x.IsClass && !x.IsGenericType && x.IsSubclassOf(typeof(Entity)) && !x.Equals(typeof(AuditTrail)) && x.Equals(typeof(Setout)) && x.GetInterfaces().Contains(typeof(IRemotable)) ); var orderedtypes = new List(); foreach (var type in types) LoadType(type, orderedtypes, new[] { typeof(Document), /* typeof(Comal.Classes.Calendar), */ typeof(Email), typeof(GPSTrackerLocation) }); var results = new List(); orderedtypes = orderedtypes.Where(x => x.Equals(typeof(Setout))).ToList(); for (var i = 0; i < orderedtypes.Count; i++) { var type = orderedtypes[i]; var copy = typeof(Utility).GetMethod("CopyType", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(type); var copied = (bool)copy.Invoke(null, new object[] { i, orderedtypes.Count, source, DbFactory.Provider }); if (copied) { var compare = typeof(Utility).GetMethod("CompareType", BindingFlags.Static | BindingFlags.NonPublic) .MakeGenericMethod(type); compare.Invoke(null, new object[] { i, orderedtypes.Count, source, DbFactory.Provider }); } } File.WriteAllText("compare.text", string.Join("\n", results)); Progress.Close(); MessageBox.Show("All Done"); } catch (Exception e) { Progress.Close(); MessageBox.Show("Import Failed!\n\n" + e.Message + "\n\n" + e.StackTrace); } BaseObject.GlobalObserving = true; } } private static void EmptyStores(params Type[] entities) { foreach (var entity in entities) { var client = ClientFactory.CreateClient(entity); try { var items = client.Load(); if (items != null) foreach (var item in items) client.Delete(item, "Emptying Store"); } catch (Exception e) { throw new Exception(string.Format("{1}\nType: {0}", entity.Name, e.Message)); } } } private static void EmptyStores() { var entities = CoreUtils.TypeList( new[] { typeof(Setout).Assembly }, myType => myType.IsClass && !myType.IsAbstract && !myType.IsGenericType && myType.IsSubclassOf(typeof(Entity)) && myType.GetInterfaces().Contains(typeof(IPersistent)) ).ToArray(); EmptyStores(entities); } public static string[] ProcessNotes(string[] notes, string description) { var Notes = notes != null ? notes.ToList() : new List(); if (!string.IsNullOrWhiteSpace(description) && !description.Equals("Enter Description of Task Here")) { var bFound = false; for (var i = 0; i < Notes.Count; i++) if (!string.IsNullOrWhiteSpace(Notes[i]) && Notes[i].Contains(description)) { Notes[i] = description; bFound = true; } if (!bFound) Notes.Insert(0, description); } return Notes.Select(x => CoreUtils.StripHTML(x)).ToArray(); } public static void SetupColumns() { var usercolumns = new DynamicGridColumns { new() { ColumnName = "UserID", Width = 0, Caption = "User ID" }, new() { ColumnName = "Password", Width = 0, Caption = "Password" } }; new GlobalConfiguration(typeof(User).Name).Save(usercolumns); var empcolumns = new DynamicGridColumns { new() { ColumnName = "Code", Width = 200, Caption = "Code" }, new() { ColumnName = "Name", Width = 0, Caption = "Name" }, new() { ColumnName = "CanAllocateTasks", Width = 40, Caption = "Tasks?" }, new() { ColumnName = "PayrollID", Width = 200, Caption = "Payroll ID" } }; new GlobalConfiguration(typeof(Employee).Name).Save(empcolumns); var jobcolumns = new DynamicGridColumns { new() { ColumnName = "Number", Width = 50, Caption = " Job #", /* Type = typeof(int), */ Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Name", Width = 0, Caption = " Name" /* , Type = typeof(String) */ } }; new GlobalConfiguration(typeof(Job).Name).Save(jobcolumns); var setoutcolumns = new DynamicGridColumns { new() { ColumnName = "Number", Width = 80 /* , Type = typeof(String) */ }, new() { ColumnName = "Title", Width = 200 /* , Type = typeof(String) */ }, new() { ColumnName = "Description", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "Quantity", Width = 50, /* Type=typeof(int), */ Caption = "Qty", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Status", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "DueDate", Width = 60, /* Type = typeof(DateTime), */ Format = "dd/MM/yy", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Forecast.ManufacturingDate", Width = 60, /* Type = typeof(DateTime), */ Caption = "Est Date", Format = "dd/MM/yy", Alignment = Alignment.MiddleCenter } }; new GlobalConfiguration(typeof(Setout).Name).Save(setoutcolumns); var deliverycolumns = new DynamicGridColumns { new() { ColumnName = "Barcode", Width = 100 /* , Type = typeof(String) */ }, new() { ColumnName = "Setout.Job.Name", Width = 200 /* , Type = typeof(String) */ }, new() { ColumnName = "Title", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "Setout.Quantity", Width = 50, /* Type=typeof(int), */ Caption = "Qty", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Setout.Description", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "DueDate", Width = 60, /* Type = typeof(DateTime), */ Caption = "Due Date", Format = "dd/MM/yy", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Setout.Forecast.ManufacturingDate", Width = 60, /* Type = typeof(DateTime), */ Caption = "Est Date", Format = "dd/MM/yy", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "ManufacturedDate", Width = 60, /* Type = typeof(DateTime), */ Caption = "Ready", Format = "dd/MM/yy", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Setout.Status", Width = 150 /* , Type = typeof(String) */ } }; new GlobalConfiguration(typeof(DeliveryItem).Name).Save(deliverycolumns); var shipmentcolumns = new DynamicGridColumns { new() { ColumnName = "Code", Width = 80, /* Type = typeof(String), */ Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Description", Width = 0 /* , Type = typeof(String) */ } }; new GlobalConfiguration(typeof(Shipment).Name).Save(shipmentcolumns); var employeecolumns = new DynamicGridColumns { new() { ColumnName = "Code", Width = 120 /* , Type = typeof(String) */ }, new() { ColumnName = "Name", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "Address.Street", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "Address.City", Width = 150 /* , Type = typeof(String) */ }, new() { ColumnName = "Type.Name", Width = 120 /* , Type = typeof(String) */ }, new() { ColumnName = "StartDate", Width = 60, /* Type = typeof(DateTime), */ Caption = "Started", Format = "dd/MM/yy", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "FinishDate", Width = 60, /* Type = typeof(DateTime), */ Caption = "Finished", Format = "dd/MM/yy", Alignment = Alignment.MiddleCenter } }; new GlobalConfiguration(typeof(Employee).Name).Save(employeecolumns); var customercolumns = new DynamicGridColumns { new() { ColumnName = "Code", Width = 200 /* , Type = typeof(String) */ }, new() { ColumnName = "Name", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "Delivery.Street", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "Delivery.City", Width = 150 /* , Type = typeof(String) */ } }; new GlobalConfiguration(typeof(Customer).Name).Save(customercolumns); var gpstrackercolumns = new DynamicGridColumns { new() { ColumnName = "DeviceID", Width = 200 /* , Type = typeof(String) */ }, new() { ColumnName = "Description", Width = 0 /* , Type = typeof(String) */ }, new() { ColumnName = "Location.Latitude", Width = 100, /* Type = typeof(double), */ Caption = "Latitude", Format = "F6", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Location.Longitude", Width = 100, /* Type = typeof(double), */ Caption = "Longitude", Format = "F6", Alignment = Alignment.MiddleCenter }, new() { ColumnName = "Location.Timestamp", Width = 100, /* Type = typeof(DateTime), */ Caption = "Last Update", Format = "dd/MM/yy HH:mm", Alignment = Alignment.MiddleCenter } }; new GlobalConfiguration(typeof(GPSTracker).Name).Save(gpstrackercolumns); } private class RequisitionItemLine { public Guid ID { get; private set; } public InvoiceLine Line { get; private set; } public CostCentre CostCentre { get; private set; } public double? Charge { get; set; } public RequisitionItemLine(Guid id, CostCentre costcentre, String description, double? charge) { ID = id; Line = new InvoiceLine() { Description = description }; CostCentre = costcentre; Charge = charge; } } //public void InvoiceTimeSheets() //{ // TimeSheet[] times = new Client().Load( // new Filter(x => x.Processed).IsEqualTo(DateTime.MinValue).And(x => x.Approved).IsNotEqualTo(DateTime.MinValue).And(x => x.InvoiceLink.ID).IsEqualTo(Guid.Empty).And(x => x.JobLink.ID).IsNotEqualTo(Guid.Empty) // ); // List jobs = new List(); // foreach (var time in times) // { // if (!jobs.Contains(time.JobLink.ID)) // jobs.Add(time.JobLink.ID); // } // foreach (Guid jobid in jobs) // { // Invoice invoice = new Invoice(); // invoice.JobLink.ID = jobid; // } //} } }