| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568 | 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<T>()        {            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>(T entity)        {            var result = new List<Guid>();            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<T>(int typeno, int typecount, IProvider source, IProvider target) where T : Entity, new()        //{        //    String name = typeof(T).EntityName().Split('.').Last();        //    //if (!HasDocumentLinks<T>())        //    //    return false;        //    Progress.SetMessage(String.Format("[{0}/{1}] {2}: Loading Source Items..", typeno, typecount, name));        //    var sourceitems = source.Load<T>();        //    Progress.SetMessage(String.Format("[{0}/{1}] {2}: Loading Target Items..", typeno, typecount, name));        //    var targetitems = target.Load<T>();        //    //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<sourceitems.Length; i++)        //    {        //        Progress.SetMessage(String.Format("[{0}/{1}] {2}: Copying Items ({3:F2}% complete)..", typeno, typecount, name, (double)i * 100.0F / (double)sourceitems.Length));        //        var sourceitem = sourceitems[i];        //        if (ClientFactory.IsSupported<AuditTrail>())        //        {        //            var audits = source.Load<AuditTrail>(new Filter<AuditTrail>(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<Document>(x => x.ID).IsEqualTo(entdoc.DocumentLink.ID)).FirstOrDefault();        //                if (doc != null)        //                    target.Save(doc);        //                else        //                    entdoc.DocumentLink.ID = Guid.Empty;        //            }        //        }        //        Guid[] docids = GetDocuments<T>(sourceitem);        //        foreach (var docid in docids)        //        {        //            var doc = source.Load(new Filter<Document>(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<Document>(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<Document>(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<String, Object> 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<string> CompareType<T>(int typeno, int typecount, IProvider source, IProvider target) where T : Entity, new()        {            var result = new List<string>();            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<T>();            Progress.SetMessage(string.Format("[{0}/{1}] {2}: Reloading Target Table..", typeno, typecount, name));            var targettable = target.Query<T>();            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<Guid>("ID");                var targetrow = targettable.Rows.FirstOrDefault(r => r.Get<Guid>("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<Type> 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<Type>();                    foreach (var type in types)                        LoadType(type, orderedtypes,                            new[] { typeof(Document), /* typeof(Comal.Classes.Calendar), */ typeof(Email), typeof(GPSTrackerLocation) });                    var results = new List<string>();                    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<string>();            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<DynamicGridColumns>(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<DynamicGridColumns>(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<DynamicGridColumns>(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<DynamicGridColumns>(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<DynamicGridColumns>(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<DynamicGridColumns>(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<DynamicGridColumns>(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<DynamicGridColumns>(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<DynamicGridColumns>(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<TimeSheet>().Load(        //        new Filter<TimeSheet>(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<Job> jobs = new List<Job>();        //    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;        //    }        //}    }}
 |