From 9beeecce51469e068404c1982052944470300aca Mon Sep 17 00:00:00 2001 From: Sergio Date: Mon, 25 Feb 2019 17:53:58 +0100 Subject: [PATCH 01/26] started LINQ to DB db connector --- BillsManager.App/App.xaml | 7 +- BillsManager.App/BillsManager.App.csproj | 17 +- BillsManager.App/packages.config | 6 +- .../BillsManager.Services.csproj | 41 +- BillsManager.Services/DB/DapperDBService.cs | 12 - BillsManager.Services/DB/LINQToDBDBService.cs | 147 ++ .../LinqToDB.Templates/CopyMe.SQLite.tt.txt | 45 + .../DataAnnotations.ttinclude | 65 + .../LinqToDB.Templates/DataModel.ttinclude | 871 +++++++++ .../EditableObject.ttinclude | 250 +++ .../LinqToDB.Templates/Humanizer.ttinclude | 15 + .../LinqToDB.SQLite.Tools.ttinclude | 3 + .../LinqToDB.SQLite.ttinclude | 44 + .../LinqToDB.Tools.ttinclude | 1 + .../LinqToDB.Templates/LinqToDB.ttinclude | 1044 +++++++++++ .../MultipleFiles.ttinclude | 70 + .../NotifyDataErrorInfo.ttinclude | 133 ++ .../NotifyPropertyChanged.ttinclude | 382 ++++ .../ObsoleteAttributes.ttinclude | 100 ++ .../PluralizationService.ttinclude | 185 ++ .../LinqToDB.Templates/T4Model.ttinclude | 1564 +++++++++++++++++ .../LinqToDB.Templates/Validation.ttinclude | 189 ++ BillsManager.Services/packages.config | 6 + 23 files changed, 5171 insertions(+), 26 deletions(-) delete mode 100644 BillsManager.Services/DB/DapperDBService.cs create mode 100644 BillsManager.Services/DB/LINQToDBDBService.cs create mode 100644 BillsManager.Services/LinqToDB.Templates/CopyMe.SQLite.tt.txt create mode 100644 BillsManager.Services/LinqToDB.Templates/DataAnnotations.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/DataModel.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/EditableObject.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/Humanizer.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/LinqToDB.SQLite.Tools.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/LinqToDB.SQLite.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/LinqToDB.Tools.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/LinqToDB.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/MultipleFiles.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/NotifyDataErrorInfo.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/NotifyPropertyChanged.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/ObsoleteAttributes.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/PluralizationService.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/T4Model.ttinclude create mode 100644 BillsManager.Services/LinqToDB.Templates/Validation.ttinclude create mode 100644 BillsManager.Services/packages.config diff --git a/BillsManager.App/App.xaml b/BillsManager.App/App.xaml index 460575b..e84fccc 100644 --- a/BillsManager.App/App.xaml +++ b/BillsManager.App/App.xaml @@ -1,5 +1,6 @@ - + diff --git a/BillsManager.App/BillsManager.App.csproj b/BillsManager.App/BillsManager.App.csproj index b243cea..2c6d5f2 100644 --- a/BillsManager.App/BillsManager.App.csproj +++ b/BillsManager.App/BillsManager.App.csproj @@ -60,19 +60,22 @@ ..\packages\Autofac.3.5.2\lib\net40\Autofac.dll True - - ..\packages\Caliburn.Micro.Core.2.0.2\lib\net45\Caliburn.Micro.dll - True + + ..\packages\Caliburn.Micro.Core.3.2.0\lib\net45\Caliburn.Micro.dll - - ..\packages\Caliburn.Micro.2.0.2\lib\net45\Caliburn.Micro.Platform.dll - True + + ..\packages\Caliburn.Micro.3.2.0\lib\net45\Caliburn.Micro.Platform.dll + + + ..\packages\Caliburn.Micro.3.2.0\lib\net45\Caliburn.Micro.Platform.Core.dll - + + ..\packages\Caliburn.Micro.3.2.0\lib\net45\System.Windows.Interactivity.dll + diff --git a/BillsManager.App/packages.config b/BillsManager.App/packages.config index 1c638a8..3e9cfdc 100644 --- a/BillsManager.App/packages.config +++ b/BillsManager.App/packages.config @@ -1,7 +1,7 @@  - - - + + + \ No newline at end of file diff --git a/BillsManager.Services/BillsManager.Services.csproj b/BillsManager.Services/BillsManager.Services.csproj index d37f2f0..78e327b 100644 --- a/BillsManager.Services/BillsManager.Services.csproj +++ b/BillsManager.Services/BillsManager.Services.csproj @@ -1,5 +1,6 @@  + Debug AnyCPU @@ -17,6 +18,8 @@ SAK SAK + + true @@ -39,10 +42,17 @@ false + + ..\packages\linq2db.2.6.4\lib\net45\linq2db.dll + + + + ..\packages\System.Data.SQLite.Core.1.0.109.1\lib\net45\System.Data.SQLite.dll + @@ -52,7 +62,7 @@ - + @@ -80,7 +90,36 @@ BillsManager.Models + + + + + + + + + + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + - \ No newline at end of file diff --git a/BillsManager.App/Composition/Bootstrapping/AutofacBootstrapper.cs b/BillsManager.App/Composition/Bootstrapping/AutofacBootstrapper.cs deleted file mode 100644 index e77881e..0000000 --- a/BillsManager.App/Composition/Bootstrapping/AutofacBootstrapper.cs +++ /dev/null @@ -1,123 +0,0 @@ -using Autofac; -using BillsManager.Localization; -using BillsManager.Services; -//using BillsManager.App.Modules; -using BillsManager.Services.DB; -using BillsManager.Services.Feedback; -using BillsManager.Services.Reporting; -using BillsManager.ViewModels; -//using BillsManager.ViewModels.Search; -using BillsManager.Views; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; - -namespace BillsManager.App.Composition.Bootstrapping -{ - // TIP: https://code.google.com/p/autofac/wiki/RelationshipTypes - public class AutofacBootstrapper : BootstrapperEx - { - public AutofacBootstrapper() - { - this.Initialize(); - } - - protected override void ConfigureContainer(ContainerBuilder builder) - { - base.ConfigureContainer(builder); - - // EXTRA MODULES - // builder.RegisterModule(); - - // SERVICES - builder.RegisterType().As().SingleInstance(); - -#if !DEBUG - // DON'T TOUCH - builder.RegisterInstance(new XMLDBConnector(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"DB\db.bmdb"))).AsImplementedInterfaces().SingleInstance(); -#else - builder.RegisterInstance(new XMLDBService(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"DB\db.bmdb"))).AsImplementedInterfaces().SingleInstance(); - builder.RegisterInstance(new MockedDBConnector(0, 7)).AsImplementedInterfaces().SingleInstance(); -#endif - - builder.RegisterGeneric(typeof(ReportPrinter<>)).As(typeof(ReportPrinter<>)).InstancePerDependency(); - - builder.Register( - ctx => new EMailFeedbackService(ctx.Resolve().Settings.FeedbackToEmailAddress)) - //ctx => new EMailFeedbackSender("nalesso.sergio@gmail.com")) - .As().SingleInstance(); - - builder.RegisterInstance( - new ResxTranslationProvider( - typeof(BillsManager.Views.Languages.Resources).FullName, - Assembly.GetAssembly(typeof(BillsManager.Views.ShellView)))) - .As().SingleInstance(); - - builder.RegisterInstance(TranslationManager.Instance) - .AsSelf() - //.PropertiesAutowired() - .AutoActivate() - .OnActivated( - (tm) => - { - tm.Instance.CurrentLanguage = tm.Context.Resolve().Settings.Language; - tm.Instance.TranslationProvider = tm.Context.Resolve(); - }); - - // VIEWMODELS - builder.RegisterType().AsSelf().SingleInstance(); - - builder.RegisterType().AsSelf().SingleInstance(); - - //builder.Register>>( - // c => - // { - // var ctx = c.Resolve(); - - // return - // (filter) => new SearchViewModel(ctx.Resolve(), filter); - // }); - - builder.RegisterType().AsSelf().SingleInstance(); - - builder.RegisterType().AsSelf().InstancePerDependency(); - - builder.RegisterType().InstancePerDependency(); - - builder.RegisterType().InstancePerDependency(); - - builder.RegisterType().InstancePerDependency(); - - builder.RegisterType().InstancePerDependency(); - - builder.Register, string, string, PrintReportViewModel>>( - c => - { - var ctx = c.Resolve(); - - return - (bills, header, comment) => - { - return - new PrintReportViewModel( - ctx.Resolve, ReportPrinter>>(), - bills, - header, - comment); - }; - }); - } - - protected override IEnumerable SelectAssemblies() - { - return new[] - { - this.GetType().Assembly, - typeof(ShellViewModel).Assembly, - typeof(ShellView).Assembly - }; - } - } -} \ No newline at end of file diff --git a/BillsManager.App/Composition/Bootstrapping/BootstrapperExGeneric.cs b/BillsManager.App/Composition/Bootstrapping/BootstrapperExGeneric.cs deleted file mode 100644 index 39e7a9a..0000000 --- a/BillsManager.App/Composition/Bootstrapping/BootstrapperExGeneric.cs +++ /dev/null @@ -1,128 +0,0 @@ -using Autofac; -using BillsManager.App.Composition.Bootstrapping.Modules; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Windows; -using IContainer = Autofac.IContainer; - -namespace BillsManager.App.Composition.Bootstrapping -{ - public class BootstrapperEx : BootstrapperBase - where TRootViewModel : IScreen - { - protected IContainer Container { get; private set; } - - public bool EnforceNamespaceConvention { get; set; } - - public bool AutoSubscribeEventAggegatorHandlers { get; set; } - - public Type ViewModelBaseType { get; set; } - - public Func CreateWindowManager { get; set; } - - public Func CreateEventAggregator { get; set; } - - protected override void Configure() - { - this.ConfigureBootstrapper(); - - if (this.CreateWindowManager == null) - throw new ArgumentNullException("CreateWindowManager"); - - if (this.CreateEventAggregator == null) - throw new ArgumentNullException("CreateEventAggregator"); - - var builder = new ContainerBuilder(); - - // register view models - builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) - // must be a type that ends with ViewModel - .Where(type => type.Name.EndsWith("ViewModel")) - // must be in a namespace ending with ViewModels - .Where(type => !(string.IsNullOrWhiteSpace(type.Namespace)) && type.Namespace.EndsWith("ViewModels")) - // must implement INotifyPropertyChanged (deriving from PropertyChangedBase will statisfy this) - .Where(type => type.GetInterface(this.ViewModelBaseType.Name) != null) - // registered as self - .AsSelf() - // always create a new one - .InstancePerDependency(); - - // register views - builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray()) - // must be a type that ends with View - .Where(type => type.Name.EndsWith("View")) - // must be in a namespace that ends in Views - .Where(type => !(string.IsNullOrWhiteSpace(type.Namespace)) && type.Namespace.EndsWith("Views")) - // registered as self - .AsSelf() - // always create a new one - .InstancePerDependency(); - - // register the single window manager for this container - builder.Register(c => this.CreateWindowManager()).InstancePerLifetimeScope(); - // register the single event aggregator for this container - builder.Register(c => this.CreateEventAggregator()).InstancePerLifetimeScope(); - - if (this.AutoSubscribeEventAggegatorHandlers) - builder.RegisterModule(); - - this.ConfigureContainer(builder); - - this.Container = builder.Build(); - } - - protected override object GetInstance(Type service, string key) - { - if (string.IsNullOrWhiteSpace(key)) - { - object obj; - if (this.Container.TryResolve(service, out obj)) - return obj; - } - else - { - object obj; - if (this.Container.TryResolveNamed(key, service, out obj)) - return obj; - } - throw new Exception(string.Format("Could not locate any instances of contract {0}.", key ?? service.Name)); - } - - protected override IEnumerable GetAllInstances(Type service) - { - return this.Container.Resolve(typeof(IEnumerable<>).MakeGenericType(new[] { service })) as IEnumerable; - } - - protected override void BuildUp(object instance) - { - this.Container.InjectProperties(instance); - } - - protected virtual void ConfigureBootstrapper() - { - this.EnforceNamespaceConvention = true; - this.AutoSubscribeEventAggegatorHandlers = false; - this.ViewModelBaseType = typeof(IScreen); - this.CreateWindowManager = () => (IWindowManager)new MinimalWindowManager(); - this.CreateEventAggregator = () => (IEventAggregator)new EventAggregator(); - } - - protected virtual void ConfigureContainer(ContainerBuilder builder) - { - } - - protected override void OnStartup(object sender, StartupEventArgs e) - { - this.DisplayRootViewFor(new Dictionary - { - { "SizeToContent", SizeToContent.Manual}, - { "Width", 1024}, - { "Height", 680}, - { "StartupLocation", WindowStartupLocation.CenterScreen}, - { "WindowState", WindowState.Maximized} - }); - } - } -} \ No newline at end of file diff --git a/BillsManager.App/Composition/Bootstrapping/Modules/EventAggregationAutoSubscriptionModule.cs b/BillsManager.App/Composition/Bootstrapping/Modules/EventAggregationAutoSubscriptionModule.cs deleted file mode 100644 index 77a82b8..0000000 --- a/BillsManager.App/Composition/Bootstrapping/Modules/EventAggregationAutoSubscriptionModule.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Autofac; -using Autofac.Core; -using Caliburn.Micro; - -namespace BillsManager.App.Composition.Bootstrapping.Modules -{ - public class EventAggregationAutoSubscriptionModule : Module - { - protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration) - { - registration.Activated += OnComponentActivated; - } - - private static void OnComponentActivated(object sender, ActivatedEventArgs e) - { - if (e == null) - return; - var handle = e.Instance as IHandle; - if (handle == null) - return; - e.Context.Resolve().Subscribe(handle); - } - } -} \ No newline at end of file diff --git a/BillsManager.App/Composition/Bootstrapping/Modules/EventAggregationAutoUnsubscriptionModule.cs b/BillsManager.App/Composition/Bootstrapping/Modules/EventAggregationAutoUnsubscriptionModule.cs deleted file mode 100644 index 3d0816f..0000000 --- a/BillsManager.App/Composition/Bootstrapping/Modules/EventAggregationAutoUnsubscriptionModule.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Autofac; -using Autofac.Core; -using Caliburn.Micro; - -namespace BillsManager.App.Composition.Bootstrapping.Modules -{ - public class EventAggregationAutoUnsubscriptionModule : Module - { - protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration) - { - registration.Activated += OnComponentActivated; - } - - private static void OnComponentActivated(object sender, ActivatedEventArgs e) - { - if (e == null) - return; - var handle = e.Instance as IDeactivate; - if (handle == null) - return; - handle.Deactivated += (s, ev) => e.Context.Resolve().Unsubscribe(handle); - } - } -} \ No newline at end of file diff --git a/BillsManager.App/Composition/Bootstrapping/SimpleBootstrapper.cs b/BillsManager.App/Composition/Bootstrapping/SimpleBootstrapper.cs deleted file mode 100644 index a482f78..0000000 --- a/BillsManager.App/Composition/Bootstrapping/SimpleBootstrapper.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Windows; -using BillsManager.Services.Providers; -using BillsManager.Views; -using BillsManager.ViewModels; -//using BillsManager.ViewModels.Factories; -using Caliburn.Micro; - -namespace BillsManager.App.Bootstrappers -{ - //public class SimpleBootstrapper : Bootstrapper - public class SimpleBootstrapper : BootstrapperBase - { - SimpleContainer container; - - protected override void Configure() - { - var config = new TypeMappingConfiguration - { - DefaultSubNamespaceForViews = "Views", - DefaultSubNamespaceForViewModels = "ViewModels" - }; - - ViewLocator.ConfigureTypeMappings(config); - ViewModelLocator.ConfigureTypeMappings(config); - - this.container = new SimpleContainer(); - - // Caliburn.Micro components - this.container.Singleton(); - //this.container.Singleton(); - this.container.Singleton(); - - // Services - //this.container.Singleton(); - //this.container.Singleton(); - //this.container.Singleton(); - //this.container.Singleton(); - //this.container.Singleton(); - - // Factories - //this.container.Singleton, BillsViewModelFactory>(); --> excluded - //this.container.Singleton, SuppliersViewModelFactory>(); --> excluded - //this.container.Singleton, BackupsViewModelFactory>(); --> excluded - - // ViewModels - //this.container.Singleton(); --> IShell removed from ShellViewModel - } - - protected override object GetInstance(Type service, string key) - { - var instance = this.container.GetInstance(service, key); - if (instance != null) - return instance; - - throw new InvalidOperationException("Could not locate any instances."); - } - - protected override IEnumerable GetAllInstances(Type service) - { - return this.container.GetAllInstances(service); - } - - protected override void BuildUp(object instance) - { - this.container.BuildUp(instance); - } - - protected override void OnStartup(object sender, System.Windows.StartupEventArgs e) - { - // ResourceDictionary resource = new ResourceDictionary - // { - // Source = new Uri("/BillsManager.View;component/Dictionaries/Styles/Values.xaml", UriKind.RelativeOrAbsolute) - // }; - - // SolidColorBrush foregroundBrush = resource.MergedDictionaries.; - - //this.DisplayRootViewFor(settings: new Dictionary - this.DisplayRootViewFor(settings: new Dictionary - { - { "WindowState", WindowState.Maximized}, - { "SizeToContent", SizeToContent.Manual}, - { "Width", 1350}, - { "Height", 750} - }); - } - - protected override IEnumerable SelectAssemblies() - { - var assemblies = new List(base.SelectAssemblies()); - - assemblies.Add(Assembly.GetAssembly(typeof(ShellView))); - - return assemblies; - } - } -} \ No newline at end of file diff --git a/BillsManager.App/Composition/MinimalWindowManager.cs b/BillsManager.App/Composition/MinimalWindowManager.cs deleted file mode 100644 index a602609..0000000 --- a/BillsManager.App/Composition/MinimalWindowManager.cs +++ /dev/null @@ -1,420 +0,0 @@ -using BillsManager.Views; -using BillsManager.Views.Controls; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Controls.Primitives; -using System.Windows.Data; -using System.Windows.Media; -using System.Windows.Navigation; - -namespace BillsManager.App.Composition -{ - /// - /// A service that manages windows. - /// - public class MinimalWindowManager : IWindowManager - { - /// - /// Shows a modal dialog for the specified model. - /// - /// The root model. - /// The context. - /// The dialog popup settings. - /// The dialog result. - public virtual bool? ShowDialog(object rootModel, object context = null, IDictionary settings = null) - { - return CreateWindow(rootModel, true, context, settings).ShowDialog(); - } - - /// - /// Shows a window for the specified model. - /// - /// The root model. - /// The context. - /// The optional window settings. - public virtual void ShowWindow(object rootModel, object context = null, IDictionary settings = null) - { - NavigationWindow navWindow = null; - - if (Application.Current != null && Application.Current.MainWindow != null) - { - navWindow = Application.Current.MainWindow as NavigationWindow; - } - - if (navWindow != null) - { - var window = CreatePage(rootModel, context, settings); - navWindow.Navigate(window); - } - else - { - CreateWindow(rootModel, false, context, settings).Show(); - } - } - - /// - /// Shows a popup at the current mouse position. - /// - /// The root model. - /// The view context. - /// The optional popup settings. - public virtual void ShowPopup(object rootModel, object context = null, IDictionary settings = null) - { - var popup = CreatePopup(rootModel, settings); - var view = ViewLocator.LocateForModel(rootModel, popup, context); - - popup.Child = view; - popup.SetValue(Caliburn.Micro.View.IsGeneratedProperty, true); - - ViewModelBinder.Bind(rootModel, popup, null); - Caliburn.Micro.Action.SetTargetWithoutContext(view, rootModel); - - var activatable = rootModel as IActivate; - if (activatable != null) - { - activatable.Activate(); - } - - var deactivator = rootModel as IDeactivate; - if (deactivator != null) - { - popup.Closed += delegate { deactivator.Deactivate(true); }; - } - - popup.IsOpen = true; - popup.CaptureMouse(); - } - - /// - /// Creates a popup for hosting a popup window. - /// - /// The model. - /// The optional popup settings. - /// The popup. - protected virtual Popup CreatePopup(object rootModel, IDictionary settings) - { - var popup = new Popup(); - - if (ApplySettings(popup, settings)) - { - if (!settings.ContainsKey("PlacementTarget") && !settings.ContainsKey("Placement")) - popup.Placement = PlacementMode.MousePoint; - if (!settings.ContainsKey("AllowsTransparency")) - popup.AllowsTransparency = true; - } - else - { - popup.AllowsTransparency = true; - popup.Placement = PlacementMode.MousePoint; - } - - return popup; - } - - /// - /// Creates a window. - /// - /// The view model. - /// Whethor or not the window is being shown as a dialog. - /// The view context. - /// The optional popup settings. - /// The window. - protected virtual WindowEx CreateWindow(object rootModel, bool isDialog, object context, IDictionary settings) - { - var view = EnsureWindow(rootModel, ViewLocator.LocateForModel(rootModel, null, context), isDialog); - ViewModelBinder.Bind(rootModel, view, context); - - var haveDisplayName = rootModel as IHaveDisplayName; - if (haveDisplayName != null && !ConventionManager.HasBinding(view, WindowEx.TitleProperty)) - { - var binding = new Binding("DisplayName"); - //var te = new TranslateExtension(rootModel.GetType().GetProperty("DisplayName").GetValue(rootModel).ToString()); - //var binding = - if (rootModel.GetType().GetProperty("DisplayName").CanWrite) - binding.Mode = BindingMode.TwoWay; - else - binding.Mode = BindingMode.OneWay; - - view.SetBinding(WindowEx.TitleProperty, binding); - } - - ApplySettings(view, settings); - - new WindowConductor(rootModel, view); - - return view; - } - - /// - /// Makes sure the view is a window is is wrapped by one. - /// - /// The view model. - /// The view. - /// Whethor or not the window is being shown as a dialog. - /// The window. - protected virtual WindowEx EnsureWindow(object model, object view, bool isDialog) - { - var window = view as WindowEx; - - if (window == null) - { - window = new ViewWindow - { - Content = view - }; - - RenderOptions.SetClearTypeHint(window, ClearTypeHint.Enabled); - - window.SetValue(Caliburn.Micro.View.IsGeneratedProperty, true); - - var owner = InferOwnerOf(window); - if (owner != null) - { - window.WindowStartupLocation = WindowStartupLocation.CenterOwner; - window.Owner = owner; - } - else - { - window.WindowStartupLocation = WindowStartupLocation.CenterScreen; - } - } - else - { - var owner = InferOwnerOf(window); - if (owner != null && isDialog) - { - window.Owner = owner; - } - } - - if (isDialog) - { - window.WindowStartupLocation = WindowStartupLocation.CenterScreen; - //window.SizeToContent = SizeToContent.Manual; - window.ResizeMode = ResizeMode.NoResize; - window.WindowStyle = WindowStyle.None; - window.AllowsTransparency = true; - window.ShowInTaskbar = false; - window.CanClose = false; - } - - return window; - } - - /// - /// Infers the owner of the window. - /// - /// The window to whose owner needs to be determined. - /// The owner. - protected virtual Window InferOwnerOf(Window window) - { - if (Application.Current == null) - { - return null; - } - - var active = Application.Current.Windows.OfType() - //.Where() - .FirstOrDefault(x => x.IsActive); - active = active ?? Application.Current.MainWindow; - return active == window ? null : active; - } - - /// - /// Creates the page. - /// - /// The root model. - /// The context. - /// The optional popup settings. - /// The page. - public virtual Page CreatePage(object rootModel, object context, IDictionary settings) - { - var view = EnsurePage(rootModel, ViewLocator.LocateForModel(rootModel, null, context)); - ViewModelBinder.Bind(rootModel, view, context); - - var haveDisplayName = rootModel as IHaveDisplayName; - if (haveDisplayName != null && !ConventionManager.HasBinding(view, Page.TitleProperty)) - { - var binding = new Binding("DisplayName") { Mode = BindingMode.TwoWay }; - view.SetBinding(Page.TitleProperty, binding); - } - - ApplySettings(view, settings); - - var activatable = rootModel as IActivate; - if (activatable != null) - { - activatable.Activate(); - } - - var deactivatable = rootModel as IDeactivate; - if (deactivatable != null) - { - view.Unloaded += (s, e) => deactivatable.Deactivate(true); - } - - return view; - } - - /// - /// Ensures the view is a page or provides one. - /// - /// The model. - /// The view. - /// The page. - protected virtual Page EnsurePage(object model, object view) - { - var page = view as Page; - - if (page == null) - { - page = new Page { Content = view }; - page.SetValue(Caliburn.Micro.View.IsGeneratedProperty, true); - } - - return page; - } - - bool ApplySettings(object target, IEnumerable> settings) - { - if (settings != null) - { - var type = target.GetType(); - - foreach (var pair in settings) - { - var propertyInfo = type.GetProperty(pair.Key); - - if (propertyInfo != null) - { - propertyInfo.SetValue(target, pair.Value, null); - } - } - - return true; - } - - return false; - } - - class WindowConductor - { - bool deactivatingFromView; - bool deactivateFromViewModel; - bool actuallyClosing; - readonly Window view; - readonly object model; - - public WindowConductor(object model, Window view) - { - this.model = model; - this.view = view; - - var activatable = model as IActivate; - if (activatable != null) - { - activatable.Activate(); - } - - var deactivatable = model as IDeactivate; - if (deactivatable != null) - { - view.Closed += Closed; - deactivatable.Deactivated += Deactivated; - } - - var guard = model as IGuardClose; - if (guard != null) - { - view.Closing += Closing; - } - } - - void Closed(object sender, EventArgs e) - { - view.Closed -= Closed; - view.Closing -= Closing; - - if (deactivateFromViewModel) - { - return; - } - - var deactivatable = (IDeactivate)model; - - deactivatingFromView = true; - deactivatable.Deactivate(true); - deactivatingFromView = false; - } - - void Deactivated(object sender, DeactivationEventArgs e) - { - if (!e.WasClosed) - { - return; - } - - ((IDeactivate)model).Deactivated -= Deactivated; - - if (deactivatingFromView) - { - return; - } - - deactivateFromViewModel = true; - actuallyClosing = true; - view.Close(); - actuallyClosing = false; - deactivateFromViewModel = false; - } - - void Closing(object sender, CancelEventArgs e) - { - if (e.Cancel) - { - return; - } - - var guard = (IGuardClose)model; - - if (actuallyClosing) - { - actuallyClosing = false; - return; - } - - bool runningAsync = false, shouldEnd = false; - - guard.CanClose(canClose => - { - Execute.OnUIThread(() => - { - if (runningAsync && canClose) - { - actuallyClosing = true; - view.Close(); - } - else - { - e.Cancel = !canClose; - } - - shouldEnd = true; - }); - }); - - if (shouldEnd) - { - return; - } - - runningAsync = e.Cancel = true; - } - } - } -} \ No newline at end of file diff --git a/BillsManager.App/Composition/SingleInstance.cs b/BillsManager.App/Composition/SingleInstance.cs deleted file mode 100644 index 980e296..0000000 --- a/BillsManager.App/Composition/SingleInstance.cs +++ /dev/null @@ -1,484 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// This class checks to make sure that only one instance of -// this application is running at a time. -// -//----------------------------------------------------------------------- - -namespace BillsManager.App.Composition -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.ComponentModel; - using System.IO; - using System.Runtime.InteropServices; - using System.Runtime.Remoting; - using System.Runtime.Remoting.Channels; - using System.Runtime.Remoting.Channels.Ipc; - using System.Runtime.Serialization.Formatters; - using System.Security; - using System.Threading; - using System.Windows; - using System.Windows.Threading; - - internal enum WM - { - NULL = 0x0000, - CREATE = 0x0001, - DESTROY = 0x0002, - MOVE = 0x0003, - SIZE = 0x0005, - ACTIVATE = 0x0006, - SETFOCUS = 0x0007, - KILLFOCUS = 0x0008, - ENABLE = 0x000A, - SETREDRAW = 0x000B, - SETTEXT = 0x000C, - GETTEXT = 0x000D, - GETTEXTLENGTH = 0x000E, - PAINT = 0x000F, - CLOSE = 0x0010, - QUERYENDSESSION = 0x0011, - QUIT = 0x0012, - QUERYOPEN = 0x0013, - ERASEBKGND = 0x0014, - SYSCOLORCHANGE = 0x0015, - SHOWWINDOW = 0x0018, - ACTIVATEAPP = 0x001C, - SETCURSOR = 0x0020, - MOUSEACTIVATE = 0x0021, - CHILDACTIVATE = 0x0022, - QUEUESYNC = 0x0023, - GETMINMAXINFO = 0x0024, - - WINDOWPOSCHANGING = 0x0046, - WINDOWPOSCHANGED = 0x0047, - - CONTEXTMENU = 0x007B, - STYLECHANGING = 0x007C, - STYLECHANGED = 0x007D, - DISPLAYCHANGE = 0x007E, - GETICON = 0x007F, - SETICON = 0x0080, - NCCREATE = 0x0081, - NCDESTROY = 0x0082, - NCCALCSIZE = 0x0083, - NCHITTEST = 0x0084, - NCPAINT = 0x0085, - NCACTIVATE = 0x0086, - GETDLGCODE = 0x0087, - SYNCPAINT = 0x0088, - NCMOUSEMOVE = 0x00A0, - NCLBUTTONDOWN = 0x00A1, - NCLBUTTONUP = 0x00A2, - NCLBUTTONDBLCLK = 0x00A3, - NCRBUTTONDOWN = 0x00A4, - NCRBUTTONUP = 0x00A5, - NCRBUTTONDBLCLK = 0x00A6, - NCMBUTTONDOWN = 0x00A7, - NCMBUTTONUP = 0x00A8, - NCMBUTTONDBLCLK = 0x00A9, - - SYSKEYDOWN = 0x0104, - SYSKEYUP = 0x0105, - SYSCHAR = 0x0106, - SYSDEADCHAR = 0x0107, - COMMAND = 0x0111, - SYSCOMMAND = 0x0112, - - MOUSEMOVE = 0x0200, - LBUTTONDOWN = 0x0201, - LBUTTONUP = 0x0202, - LBUTTONDBLCLK = 0x0203, - RBUTTONDOWN = 0x0204, - RBUTTONUP = 0x0205, - RBUTTONDBLCLK = 0x0206, - MBUTTONDOWN = 0x0207, - MBUTTONUP = 0x0208, - MBUTTONDBLCLK = 0x0209, - MOUSEWHEEL = 0x020A, - XBUTTONDOWN = 0x020B, - XBUTTONUP = 0x020C, - XBUTTONDBLCLK = 0x020D, - MOUSEHWHEEL = 0x020E, - - - CAPTURECHANGED = 0x0215, - - ENTERSIZEMOVE = 0x0231, - EXITSIZEMOVE = 0x0232, - - IME_SETCONTEXT = 0x0281, - IME_NOTIFY = 0x0282, - IME_CONTROL = 0x0283, - IME_COMPOSITIONFULL = 0x0284, - IME_SELECT = 0x0285, - IME_CHAR = 0x0286, - IME_REQUEST = 0x0288, - IME_KEYDOWN = 0x0290, - IME_KEYUP = 0x0291, - - NCMOUSELEAVE = 0x02A2, - - DWMCOMPOSITIONCHANGED = 0x031E, - DWMNCRENDERINGCHANGED = 0x031F, - DWMCOLORIZATIONCOLORCHANGED = 0x0320, - DWMWINDOWMAXIMIZEDCHANGE = 0x0321, - - #region Windows 7 - DWMSENDICONICTHUMBNAIL = 0x0323, - DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326, - #endregion - - USER = 0x0400, - - // This is the hard-coded message value used by WinForms for Shell_NotifyIcon. - // It's relatively safe to reuse. - TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024 - APP = 0x8000, - } - - [SuppressUnmanagedCodeSecurity] - internal static class NativeMethods - { - /// - /// Delegate declaration that matches WndProc signatures. - /// - public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled); - - [DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)] - private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs); - - - [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)] - private static extern IntPtr _LocalFree(IntPtr hMem); - - - public static string[] CommandLineToArgvW(string cmdLine) - { - IntPtr argv = IntPtr.Zero; - try - { - int numArgs = 0; - - argv = _CommandLineToArgvW(cmdLine, out numArgs); - if (argv == IntPtr.Zero) - { - throw new Win32Exception(); - } - var result = new string[numArgs]; - - for (int i = 0; i < numArgs; i++) - { - IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr))); - result[i] = Marshal.PtrToStringUni(currArg); - } - - return result; - } - finally - { - - IntPtr p = _LocalFree(argv); - // Otherwise LocalFree failed. - // Assert.AreEqual(IntPtr.Zero, p); - } - } - - } - - public interface ISingleInstanceApp - { - bool SignalExternalCommandLineArgs(IList args); - } - - /// - /// This class checks to make sure that only one instance of - /// this application is running at a time. - /// - /// - /// Note: this class should be used with some caution, because it does no - /// security checking. For example, if one instance of an app that uses this class - /// is running as Administrator, any other instance, even if it is not - /// running as Administrator, can activate it with command line arguments. - /// For most apps, this will not be much of an issue. - /// - public static class SingleInstance - where TApplication : Application, ISingleInstanceApp - { - #region Private Fields - - /// - /// String delimiter used in channel names. - /// - private const string Delimiter = ":"; - - /// - /// Suffix to the channel name. - /// - private const string ChannelNameSuffix = "SingeInstanceIPCChannel"; - - /// - /// Remote service name. - /// - private const string RemoteServiceName = "SingleInstanceApplicationService"; - - /// - /// IPC protocol used (string). - /// - private const string IpcProtocol = "ipc://"; - - /// - /// Application mutex. - /// - private static Mutex singleInstanceMutex; - - /// - /// IPC channel for communications. - /// - private static IpcServerChannel channel; - - /// - /// List of command line arguments for the application. - /// - private static IList commandLineArgs; - - #endregion - - #region Public Properties - - /// - /// Gets list of command line arguments for the application. - /// - public static IList CommandLineArgs - { - get { return commandLineArgs; } - } - - #endregion - - #region Public Methods - - /// - /// Checks if the instance of the application attempting to start is the first instance. - /// If not, activates the first instance. - /// - /// True if this is the first instance of the application. - public static bool InitializeAsFirstInstance(string uniqueName) - { - commandLineArgs = GetCommandLineArgs(uniqueName); - - // Build unique application Id and the IPC channel name. - string applicationIdentifier = uniqueName + Environment.UserName; - - string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix); - - // Create mutex based on unique application Id to check if this is the first instance of the application. - bool firstInstance; - singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance); - if (firstInstance) - { - CreateRemoteService(channelName); - } - else - { - SignalFirstInstance(channelName, commandLineArgs); - } - - return firstInstance; - } - - /// - /// Cleans up single-instance code, clearing shared resources, mutexes, etc. - /// - public static void Cleanup() - { - if (singleInstanceMutex != null) - { - singleInstanceMutex.Close(); - singleInstanceMutex = null; - } - - if (channel != null) - { - ChannelServices.UnregisterChannel(channel); - channel = null; - } - } - - #endregion - - #region Private Methods - - /// - /// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved. - /// - /// List of command line arg strings. - private static IList GetCommandLineArgs(string uniqueApplicationName) - { - string[] args = null; - if (AppDomain.CurrentDomain.ActivationContext == null) - { - // The application was not clickonce deployed, get args from standard API's - args = Environment.GetCommandLineArgs(); - } - else - { - // The application was clickonce deployed - // Clickonce deployed apps cannot recieve traditional commandline arguments - // As a workaround commandline arguments can be written to a shared location before - // the app is launched and the app can obtain its commandline arguments from the - // shared location - string appFolderPath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName); - - string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt"); - if (File.Exists(cmdLinePath)) - { - try - { - using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode)) - { - args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd()); - } - - File.Delete(cmdLinePath); - } - catch (IOException) - { - } - } - } - - if (args == null) - { - args = new string[] { }; - } - - return new List(args); - } - - /// - /// Creates a remote service for communication. - /// - /// Application's IPC channel name. - private static void CreateRemoteService(string channelName) - { - BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider(); - serverProvider.TypeFilterLevel = TypeFilterLevel.Full; - IDictionary props = new Dictionary(); - - props["name"] = channelName; - props["portName"] = channelName; - props["exclusiveAddressUse"] = "false"; - - // Create the IPC Server channel with the channel properties - channel = new IpcServerChannel(props, serverProvider); - - // Register the channel with the channel services - ChannelServices.RegisterChannel(channel, true); - - // Expose the remote service with the REMOTE_SERVICE_NAME - IPCRemoteService remoteService = new IPCRemoteService(); - RemotingServices.Marshal(remoteService, RemoteServiceName); - } - - /// - /// Creates a client channel and obtains a reference to the remoting service exposed by the server - - /// in this case, the remoting service exposed by the first instance. Calls a function of the remoting service - /// class to pass on command line arguments from the second instance to the first and cause it to activate itself. - /// - /// Application's IPC channel name. - /// - /// Command line arguments for the second instance, passed to the first instance to take appropriate action. - /// - private static void SignalFirstInstance(string channelName, IList args) - { - IpcClientChannel secondInstanceChannel = new IpcClientChannel(); - ChannelServices.RegisterChannel(secondInstanceChannel, true); - - string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName; - - // Obtain a reference to the remoting service exposed by the server i.e the first instance of the application - IPCRemoteService firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl); - - // Check that the remote service exists, in some cases the first instance may not yet have created one, in which case - // the second instance should just exit - if (firstInstanceRemoteServiceReference != null) - { - // Invoke a method of the remote service exposed by the first instance passing on the command line - // arguments and causing the first instance to activate itself - firstInstanceRemoteServiceReference.InvokeFirstInstance(args); - } - } - - /// - /// Callback for activating first instance of the application. - /// - /// Callback argument. - /// Always null. - private static object ActivateFirstInstanceCallback(object arg) - { - // Get command line args to be passed to first instance - IList args = arg as IList; - ActivateFirstInstance(args); - return null; - } - - /// - /// Activates the first instance of the application with arguments from a second instance. - /// - /// List of arguments to supply the first instance of the application. - private static void ActivateFirstInstance(IList args) - { - // Set main window state and process command line args - if (Application.Current == null) - { - return; - } - - ((TApplication)Application.Current).SignalExternalCommandLineArgs(args); - } - - #endregion - - #region Private Classes - - /// - /// Remoting service class which is exposed by the server i.e the first instance and called by the second instance - /// to pass on the command line arguments to the first instance and cause it to activate itself. - /// - private class IPCRemoteService : MarshalByRefObject - { - /// - /// Activates the first instance of the application. - /// - /// List of arguments to pass to the first instance. - public void InvokeFirstInstance(IList args) - { - if (Application.Current != null) - { - // Do an asynchronous call to ActivateFirstInstance function - Application.Current.Dispatcher.BeginInvoke( - DispatcherPriority.Normal, new DispatcherOperationCallback(SingleInstance.ActivateFirstInstanceCallback), args); - } - } - - /// - /// Remoting Object's ease expires after every 5 minutes by default. We need to override the InitializeLifetimeService class - /// to ensure that lease never expires. - /// - /// Always null. - public override object InitializeLifetimeService() - { - return null; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.App/Images/Product-documentation.ico b/BillsManager.App/Images/Product-documentation.ico deleted file mode 100644 index 852627db72dca96d0d73b0b419da390ef9376934..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 372526 zcmeFa37k~bl|Nqj&CF-!H!k1`sQKHOUow+Sq9HMAViGMAm#B#$V>B8y!I;DtXA)du z;z}v9LwC~+4ZYASYd3T^bhATuvjq?Y6h)ChvnePl*;gm`f4;Zgd422E+v`=;EBf*I z9L|0Fz31NV_ndp*dDXGl2V(ym!@m#2ieeuv`p4L#R8Azc?SJ_|td{o0M?*GPOS2p}pY#{B&{eSe2bba$b z#Xd^UpdGQ;|4Hu0W{jQ_{fjIRSs=1NWP!*6kp&_PL>7oF5LqCyKxBc)0+9tG3q%%( zED%{BvOr{k$O4fCA`3(oh%69UAhJMYfye@p1tJSX7KkhmSs=1NWP!*6kp&_PL>7oF z5LqCyKxBc)0+9tG3q%%(ED%{BvOr{k$O4fCA`3(oh%69UAhJMYfye@p1tJSX7Kkhm zSs=1NWP!*6kp&_PL>7oF5LqCyKxBc)0-?3Q*nIjI^?#*~Ak!@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C4Q|Lcw4}~#SadqgJZ@tlX(w51Fm&WysS@R&~tu1Q^#lILa0?cQui`CCultureYouAreCodingWith nel file .csproj -//all'interno di un . Ad esempio, se si utilizza l'inglese (Stati Uniti) -//nei file di origine, impostare su en-US. Rimuovere quindi il commento dall'attributo -//NeutralResourceLanguage riportato di seguito. Aggiornare "en-US" nella -//riga sottostante in modo che corrisponda all'impostazione UICulture nel file di progetto. - -//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] - - -[assembly: ThemeInfo( - ResourceDictionaryLocation.None, //dove si trovano i dizionari delle risorse specifiche del tema - //(in uso se non è possibile trovare una risorsa nella pagina - // oppure nei dizionari delle risorse dell'applicazione) - ResourceDictionaryLocation.SourceAssembly //dove si trova il dizionario delle risorse generiche - //(in uso se non è possibile trovare una risorsa nella pagina, - // nell'applicazione o nei dizionari delle risorse specifiche del tema) -)] - - -// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: -// -// Numero di versione principale -// Numero di versione secondario -// Numero build -// Revisione -// -// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build -// utilizzando l'asterisco (*) come descritto di seguito: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BillsManager.App/Properties/Settings.Designer.cs b/BillsManager.App/Properties/Settings.Designer.cs deleted file mode 100644 index 83aa75e..0000000 --- a/BillsManager.App/Properties/Settings.Designer.cs +++ /dev/null @@ -1,26 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.34003 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace BillsManager.App.Properties { - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default { - get { - return defaultInstance; - } - } - } -} diff --git a/BillsManager.App/Properties/Settings.settings b/BillsManager.App/Properties/Settings.settings deleted file mode 100644 index 033d7a5..0000000 --- a/BillsManager.App/Properties/Settings.settings +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/BillsManager.App/app.config b/BillsManager.App/app.config deleted file mode 100644 index 3ec7c28..0000000 --- a/BillsManager.App/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/BillsManager.App/packages.config b/BillsManager.App/packages.config deleted file mode 100644 index 3e9cfdc..0000000 --- a/BillsManager.App/packages.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/BillsManager.DesignTime/BillsManager.DesignTime.csproj b/BillsManager.DesignTime/BillsManager.DesignTime.csproj deleted file mode 100644 index e5442f4..0000000 --- a/BillsManager.DesignTime/BillsManager.DesignTime.csproj +++ /dev/null @@ -1,85 +0,0 @@ - - - - - Debug - AnyCPU - {BB73C02D-5ADE-4DB3-AB82-C6675E58C122} - Library - Properties - BillsManager.DesignTime - BillsManager.DesignTime - v4.5 - 512 - SAK - SAK - SAK - SAK - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\packages\Caliburn.Micro.Core.2.0.2\lib\net45\Caliburn.Micro.dll - True - - - ..\packages\Caliburn.Micro.2.0.2\lib\net45\Caliburn.Micro.Platform.dll - True - - - - - - - - - - - - - - - - - - - {888f670b-4396-4660-8c5a-0d43fb2c0a1d} - BillsManager.Models - - - {fc8a7a61-d9cf-4ac7-a62d-590c35a28a44} - BillsManager.Services - - - {127368a5-65a5-46c6-a203-33abc22b1edd} - BillsManager.ViewModels - - - - - - - - \ No newline at end of file diff --git a/BillsManager.DesignTime/Properties/AssemblyInfo.cs b/BillsManager.DesignTime/Properties/AssemblyInfo.cs deleted file mode 100644 index b72537c..0000000 --- a/BillsManager.DesignTime/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("BillsManager.DesignTime")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BillsManager.DesignTime")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("85fbbb6f-91c0-43f8-be09-8aa790d9528b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BillsManager.DesignTime/ViewModels/DesignTimeBillDetailsViewModel.cs b/BillsManager.DesignTime/ViewModels/DesignTimeBillDetailsViewModel.cs deleted file mode 100644 index 8d6f5e1..0000000 --- a/BillsManager.DesignTime/ViewModels/DesignTimeBillDetailsViewModel.cs +++ /dev/null @@ -1,83 +0,0 @@ -using BillsManager.Models; -using BillsManager.ViewModels; -using Caliburn.Micro; -using System; - -namespace BillsManager.DesignTime.ViewModels -{ - public sealed partial class DesignTimeBillDetailsViewModel : BillDetailsViewModel - { - #region field - - Supplier _supplier; - Bill _bill; - - #endregion - - #region ctor - - public DesignTimeBillDetailsViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - public DesignTimeBillDetailsViewModel(Bill b) - { - if (Execute.InDesignMode) - { - this.ExposedBill = b; - } - } - - #endregion - - #region methods - - void LoadDesignTimeData() - { - this._supplier = new Supplier( - 53, - "Faber-Castell", - "Via Stromboli", - "14", - "Milano", - "20144", - "MI", - "Italia", - "faber-castell@faber-castell.it", - "http://www.faber-castell.it", - "02/43069601", - "02/43069601", - "sconti 10/06 - 24/09.", - "Barbara", - "Robecchi", - "347-7892234" - ); - - this._bill = new Bill( - 0, - this._supplier.ID, - DateTime.Today.AddDays(-2), - DateTime.Today.AddDays(14), - DateTime.Today.AddDays(-8), - DateTime.Today, - 723.61, - 66, - 0, - "X3V-KDM", - "call agent for reduction @additional comments to trigger validation rule"); - - this.ExposedBill = this._bill; - } - - public new string SupplierName - { - get { return this._supplier.Name; } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.DesignTime/ViewModels/DesignTimeBillsViewModel.cs b/BillsManager.DesignTime/ViewModels/DesignTimeBillsViewModel.cs deleted file mode 100644 index f2e9812..0000000 --- a/BillsManager.DesignTime/ViewModels/DesignTimeBillsViewModel.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System.Linq; -using BillsManager.Services.DB; -using System.Collections.ObjectModel; -using BillsManager.ViewModels; - -namespace BillsManager.DesignTime.ViewModels -{ - public sealed partial class DesignTimeBillsViewModel : BillsViewModel - { - #region ctor - - public DesignTimeBillsViewModel() - { - var mbp = new MockedDBConnector(2, 3); - - var bills = mbp.GetAllBills(); - - var billViewModels = bills.Select(b => new DesignTimeBillDetailsViewModel(b)); - - this.BillViewModels = new ObservableCollection(billViewModels); - } - - #endregion - - #region methods - - //private void LoadDesignTimeData() - //{ - // Supplier supp = new Supplier( - // 0, - // "Faber-Castell", - // "Via Stromboli", - // "14", - // "Milano", - // "20144", - // "MI", - // "Italia", - // "faber-castell@faber-castell.it", - // "http://www.faber-castell.it", - // "02/43069601", - // "02/43069601", - // "sconti 10/06 - 24/09.", - // "Barbara", - // "Robecchi", - // "347-7892234"); - - // Bill newBill = new Bill( - // 0, - // supp.ID, - // DateTime.Today, - // DateTime.Today.AddDays(14), - // DateTime.Today.AddDays(-2), - // DateTime.Today, - // 723.61, - // 0, - // 21.3, - // "X3V-KDM", - // "call agent for reduction"); - - // Bill newBill2 = new Bill( - // 1, - // supp.ID, - // DateTime.Today.AddDays(-30), - // DateTime.Today.AddDays(-20), - // DateTime.Today.AddDays(-32), - // null, - // 54.06, - // 0, - // 0.5, - // "DK23595", - // "ask for catalog"); - - // Bill newBill3 = new Bill( - // 2, - // supp.ID, - // DateTime.Today, - // DateTime.Today.AddDays(7), - // DateTime.Today.AddDays(-3), - // null, - // 54.06, - // 9, - // 0, - // "AZ381EY", - // "call agent for reductions and new winter orders"); - - // Bill newBill4 = new Bill( - // 3, - // supp.ID, - // DateTime.Today.AddDays(-30), - // DateTime.Today.AddDays(-1), - // DateTime.Today.AddDays(-32), - // null, - // 54.06, - // 15.7, - // 0, - // "DK23595", - // "ask for catalog"); - - // var bills = new List(); - - // //bills.Add(new BillDetailsViewModel(newBill) /*{ SupplierName = "faewf" }*/); - // //bills.Add(new BillDetailsViewModel(newBill2) /*{ SupplierName = "fawef" }*/); - // //bills.Add(new BillDetailsViewModel(newBill3) /*{ SupplierName = "gres" }*/); - // //bills.Add(new BillDetailsViewModel(newBill4) /*{ SupplierName = "erg" }*/); - - // this.BillViewModels = new ObservableCollection(bills); - - // this.SelectedBillViewModel = this.FilteredBillViewModels.FirstOrDefault(); - //} - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.DesignTime/ViewModels/DesignTimeSupplierDetailsViewModel.cs b/BillsManager.DesignTime/ViewModels/DesignTimeSupplierDetailsViewModel.cs deleted file mode 100644 index 3e708fe..0000000 --- a/BillsManager.DesignTime/ViewModels/DesignTimeSupplierDetailsViewModel.cs +++ /dev/null @@ -1,56 +0,0 @@ -using BillsManager.Models; -using BillsManager.ViewModels; -using Caliburn.Micro; - -namespace BillsManager.DesignTime.ViewModels -{ - public sealed partial class DesignTimeSupplierDetailsViewModel : SupplierDetailsViewModel - { - #region field - - Supplier supplier; - - #endregion - - #region ctor - - public DesignTimeSupplierDetailsViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - #endregion - - #region methods - - private void LoadDesignTimeData() - { - this.supplier = new Supplier( - 0, - "Faber-Castell", - "Via Stromboli", - "14", - "Milano", - "20144", - "MI", - "Italia", - "faber-castell@faber-castell.it", - "http://www.faber-castell.it", - "02/43069601", - "02/26367774", - "sconti 10/06 - 24/09.", - "Barbara", - "Robecchi", - "347-7892234"); - - this.ExposedSupplier = this.supplier; - - this.ObligationAmount = -1936.27; - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.DesignTime/packages.config b/BillsManager.DesignTime/packages.config deleted file mode 100644 index 8a808a9..0000000 --- a/BillsManager.DesignTime/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/BillsManager.Localization/Attributes/LocalizeAttribute.cs b/BillsManager.Localization/Attributes/LocalizeAttribute.cs deleted file mode 100644 index c781652..0000000 --- a/BillsManager.Localization/Attributes/LocalizeAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; - -namespace BillsManager.Localization.Attributes -{ - // TODO: review modality -> string == null ? use type : use provided key -> .Translation - [Obsolete] - [AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] - class LocalizeAttribute : Attribute - { - public LocalizeAttribute(string key) - { - this.key = key; - } - - private readonly string key; - public string Key - { - get { return this.key; } - } - - public string Translation - { - get - { - return TranslationManager.Instance.Translate(this.Key) as string; - } - } - } -} \ No newline at end of file diff --git a/BillsManager.Localization/Attributes/LocalizedDisplayNameAttribute.cs b/BillsManager.Localization/Attributes/LocalizedDisplayNameAttribute.cs deleted file mode 100644 index a4a017d..0000000 --- a/BillsManager.Localization/Attributes/LocalizedDisplayNameAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.ComponentModel; - -namespace BillsManager.Localization.Attributes -{ - [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] - public class LocalizedDisplayNameAttribute : DisplayNameAttribute - { - private readonly string resourceName; - public LocalizedDisplayNameAttribute(string resourceName) - : base() - { - this.resourceName = resourceName; - } - - public override string DisplayName - { - get - { - return TranslationManager.Instance.Translate(this.resourceName) as string; - } - } - } -} \ No newline at end of file diff --git a/BillsManager.Localization/Attributes/LocalizedRequiredAttribute.cs b/BillsManager.Localization/Attributes/LocalizedRequiredAttribute.cs deleted file mode 100644 index 3d0e000..0000000 --- a/BillsManager.Localization/Attributes/LocalizedRequiredAttribute.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; -using System.Diagnostics.CodeAnalysis; - -namespace BillsManager.Localization.Attributes -{ - //[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] - public class LocalizedRequiredAttribute : RequiredAttribute - //public class LocalizedRequiredAttribute : ValidationAttribute - { - public LocalizedRequiredAttribute() - { - //this.UpdateErrorMessage(); -> sends validationRulesTracker to null, haven't checked why - - TranslationManager.Instance.LanguageChanged += - (s, e) => - { - this.UpdateErrorMessage(); - }; - } - - //public bool AllowEmptyStrings { get; set; } - - private string errorMessageKey; - public string ErrorMessageKey - { - get - { - return this.errorMessageKey; - } - set - { - this.errorMessageKey = value; - this.UpdateErrorMessage(); - } - } - - private void UpdateErrorMessage() - { - this.ErrorMessage = TranslationManager.Instance.Translate(this.ErrorMessageKey) as string; - } - - //public override bool IsValid(object value) - //{ - // if (value == null) - // return false; - - // var stringValue = value as string; - // if (stringValue != null && !AllowEmptyStrings) - // { - // return stringValue.Trim().Length != 0; - // } - - // return true; - //} - } -} \ No newline at end of file diff --git a/BillsManager.Localization/Attributes/LocalizedStringLengthAttribute.cs b/BillsManager.Localization/Attributes/LocalizedStringLengthAttribute.cs deleted file mode 100644 index f48365e..0000000 --- a/BillsManager.Localization/Attributes/LocalizedStringLengthAttribute.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; -using System.Diagnostics.CodeAnalysis; - -namespace BillsManager.Localization.Attributes -{ - public class LocalizedStringLengthAttribute : StringLengthAttribute - { - public LocalizedStringLengthAttribute(int maximumLength) : - base(maximumLength) - { - TranslationManager.Instance.LanguageChanged += - (s, e) => - { - this.UpdateErrorMessageFormat(); - }; - } - - private string errorMessageFormatKey; - public string ErrorMessageFormatKey - { - get - { - return this.errorMessageFormatKey; - } - set - { - this.errorMessageFormatKey = value; - this.UpdateErrorMessageFormat(); - } - } - - private void UpdateErrorMessageFormat() - { - this.ErrorMessage = string.Format(TranslationManager.Instance.Translate(this.ErrorMessageFormatKey) as string, this.MinimumLength, this.MaximumLength); - } - } -} \ No newline at end of file diff --git a/BillsManager.Localization/BillsManager.Localization.csproj b/BillsManager.Localization/BillsManager.Localization.csproj deleted file mode 100644 index 15d1b73..0000000 --- a/BillsManager.Localization/BillsManager.Localization.csproj +++ /dev/null @@ -1,84 +0,0 @@ - - - - - Debug - AnyCPU - {5387DB3B-6EC1-42CF-A72B-CEF5ADFB541A} - Library - Properties - BillsManager.Localization - BillsManager.Localization - v4.5 - 512 - SAK - SAK - SAK - SAK - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AnyCPU - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\packages\Caliburn.Micro.Core.2.0.2\lib\net45\Caliburn.Micro.dll - True - - - ..\packages\Caliburn.Micro.2.0.2\lib\net45\Caliburn.Micro.Platform.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/BillsManager.Localization/BillsManagerTranslationDictionary.cs b/BillsManager.Localization/BillsManagerTranslationDictionary.cs deleted file mode 100644 index 26aab3d..0000000 --- a/BillsManager.Localization/BillsManagerTranslationDictionary.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; - -namespace BillsManager.Localization -{ - public class BillsManagerTranslationDictionary : SimpleTranslationDictionary, IBillsManagerTranslationDictionary - { - public BillsManagerTranslationDictionary(string translationDictionaryFilePath) : base(translationDictionaryFilePath) { } - - public string Ok - { - get { return base.GetTranslation(); } - } - - public string Cancel - { - get { return base.GetTranslation(); } - } - - public string Exit - { - get { return base.GetTranslation(); } - } - - public string Connect - { - get { return base.GetTranslation(); } - } - - public string Disconnect - { - get { return base.GetTranslation(); } - } - - public string Open - { - get { return base.GetTranslation(); } - } - - public string Close - { - get { return base.GetTranslation(); } - } - - public string Supplier - { - get { return base.GetTranslation(); } - } - - public string Bill - { - get { return base.GetTranslation(); } - } - - public string Suppliers - { - get { return base.GetTranslation(); } - } - - public string Bills - { - get { return base.GetTranslation(); } - } - } -} \ No newline at end of file diff --git a/BillsManager.Localization/IBillsManagerTranslationDictionary.cs b/BillsManager.Localization/IBillsManagerTranslationDictionary.cs deleted file mode 100644 index e88e338..0000000 --- a/BillsManager.Localization/IBillsManagerTranslationDictionary.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace BillsManager.Localization -{ - public interface IBillsManagerTranslationDictionary : ITranslationDictionary - { - string Ok { get; } - string Cancel { get; } - string Exit { get; } - string Connect { get; } - string Disconnect { get; } - string Open { get; } - string Close { get; } - string Supplier { get; } - string Bill { get; } - string Suppliers { get; } - string Bills { get; } - } -} \ No newline at end of file diff --git a/BillsManager.Localization/ITranslationDictionary.cs b/BillsManager.Localization/ITranslationDictionary.cs deleted file mode 100644 index 3b3dbea..0000000 --- a/BillsManager.Localization/ITranslationDictionary.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Globalization; - -namespace BillsManager.Localization -{ - public interface ITranslationDictionary - { - CultureInfo Language { get; } - } -} \ No newline at end of file diff --git a/BillsManager.Localization/ITranslationProvider.cs b/BillsManager.Localization/ITranslationProvider.cs deleted file mode 100644 index 8870bb2..0000000 --- a/BillsManager.Localization/ITranslationProvider.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections.Generic; -using System.Globalization; - -namespace BillsManager.Localization -{ - public interface ITranslationProvider - { - string Translate(string key); - - IEnumerable Languages { get; } - } -} \ No newline at end of file diff --git a/BillsManager.Localization/LanguageChangedEventManager.cs b/BillsManager.Localization/LanguageChangedEventManager.cs deleted file mode 100644 index 533f238..0000000 --- a/BillsManager.Localization/LanguageChangedEventManager.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Windows; - -namespace BillsManager.Localization -{ - public class LanguageChangedEventManager : WeakEventManager - { - #region methods - - private void OnLanguageChanged(object sender, EventArgs e) - { - this.DeliverEvent(sender, e); - } - - protected override void StartListening(object source) - { - var manager = (TranslationManager)source; - manager.LanguageChanged += this.OnLanguageChanged; - } - - protected override void StopListening(Object source) - { - var manager = (TranslationManager)source; - manager.LanguageChanged -= this.OnLanguageChanged; - } - - #region static methods - - public static void AddListener(TranslationManager source, IWeakEventListener listener) - { - LanguageChangedEventManager.CurrentManager.ProtectedAddListener(source, listener); - } - - public static void RemoveListener(TranslationManager source, IWeakEventListener listener) - { - LanguageChangedEventManager.CurrentManager.ProtectedRemoveListener(source, listener); - } - - private static LanguageChangedEventManager CurrentManager - { - get - { - Type managerType = typeof(LanguageChangedEventManager); - var manager = (LanguageChangedEventManager)LanguageChangedEventManager.GetCurrentManager(managerType); - - if (manager == null) - { - manager = new LanguageChangedEventManager(); - LanguageChangedEventManager.SetCurrentManager(managerType, manager); - } - return manager; - } - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Localization/Properties/AssemblyInfo.cs b/BillsManager.Localization/Properties/AssemblyInfo.cs deleted file mode 100644 index 5587a87..0000000 --- a/BillsManager.Localization/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("BillsManager.Localization")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BillsManager.Localization")] -[assembly: AssemblyCopyright("Copyright © Nalesso Sergio 2014-2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("ba74dd91-49f4-43f1-88d6-2be6b5fa6d8c")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BillsManager.Localization/ResxTranslationProvider.cs b/BillsManager.Localization/ResxTranslationProvider.cs deleted file mode 100644 index bb9990c..0000000 --- a/BillsManager.Localization/ResxTranslationProvider.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Reflection; -using System.Resources; -using System.Threading; - -namespace BillsManager.Localization -{ - public class ResxTranslationProvider : ITranslationProvider - { - #region Private Members - - private readonly ResourceManager resourceManager; - - #endregion - - #region Construction - - public ResxTranslationProvider(string baseName, Assembly assembly) - { - this.resourceManager = new ResourceManager(baseName, assembly); - - var avLangs = CultureInfo.GetCultures(CultureTypes.SpecificCultures) - .Where(culture => - { - try - { - assembly.GetSatelliteAssembly(culture); - return true; - } - catch (Exception) - { - return false; - } - }) - .Concat( - new CultureInfo[] - { - CultureInfo.GetCultureInfo(Assembly.GetEntryAssembly().GetCustomAttribute().CultureName) - }) - /*.ToList()*/; - - this.availableLanguages = avLangs; - } - - #endregion - - #region ITranslationProvider Members - - public string Translate(string key) - { - var value = resourceManager.GetString(key, Thread.CurrentThread.CurrentUICulture); - return value; - } - - #endregion - - #region ITranslationProvider Members - - private readonly IEnumerable availableLanguages; - public IEnumerable Languages - { - get - { - return this.availableLanguages; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Localization/SimpleTranslationDictionary.cs b/BillsManager.Localization/SimpleTranslationDictionary.cs deleted file mode 100644 index a33c883..0000000 --- a/BillsManager.Localization/SimpleTranslationDictionary.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; - -namespace BillsManager.Localization -{ - public abstract class SimpleTranslationDictionary : ITranslationDictionary - { - private const char KeyValueSeparator = '\t'; - - private readonly Dictionary _translationsDictionary; - - public SimpleTranslationDictionary(string translationDictionaryFilePath) - { - if (string.IsNullOrWhiteSpace(translationDictionaryFilePath)) - throw new ArgumentNullException("translationDictionaryFilePath"); - - if (!File.Exists(translationDictionaryFilePath)) - throw new FileNotFoundException("Couldn't locate the translation dictionary file.", translationDictionaryFilePath); - - this._translationsDictionary = new Dictionary(); - - var lines = new List(File.ReadAllLines(translationDictionaryFilePath)); - - if (lines.Count > 0) - { - var lcid = int.Parse(lines[0]); - this._language = new CultureInfo(lcid); - lines.RemoveAt(0); - - lines.ForEach(line => - { - var kv = line.Split(SimpleTranslationDictionary.KeyValueSeparator); - this._translationsDictionary.Add(kv[0], kv[1]); - }); - } - } - - private readonly CultureInfo _language; - public CultureInfo Language - { - get { return this._language; } - } - - protected string GetTranslation([CallerMemberName] string key = null) - { - var translation = this._translationsDictionary[key]; - return translation ?? "!" + key + "!"; - } - } -} \ No newline at end of file diff --git a/BillsManager.Localization/TranslateExtension.cs b/BillsManager.Localization/TranslateExtension.cs deleted file mode 100644 index a1cfd24..0000000 --- a/BillsManager.Localization/TranslateExtension.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Linq.Expressions; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Markup; - -namespace BillsManager.Localization -{ - public class TranslateExtension : MarkupExtension - { - #region ctor - - //#if DEBUG - - // private static ITranslationProvider traslationProvider = new ResxTranslationProvider( - // Assembly.GetAssembly(typeof(; - - //#endif - - public TranslateExtension(string key) - { - this.key = key; - } - - #endregion - - #region properties - - private string key; - [ConstructorArgument("key")] - public string Key - { - get { return this.key; } - set { this.key = value; } - } - - #endregion - - #region methods - - public override object ProvideValue(IServiceProvider serviceProvider) - { - var td = new TranslationData(this.key); - BindingMode bindingMode = BindingMode.OneWay; - - var pvt = (serviceProvider as IProvideValueTarget); // TODO: add design time support: serviceProvider == null - if (pvt != null) - { - var targetType = pvt.TargetObject.GetType(); - - if (targetType != typeof(Run)) - bindingMode = BindingMode.Default; - } - - var propertyName = this.GetPropertyName(() => td.Value); // TODO nameof - - var binding = - new Binding(propertyName) - { - Source = td, - Mode = bindingMode - }; - - return binding.ProvideValue(serviceProvider); - } - - String GetPropertyName(Expression> propertyId) - { - return ((MemberExpression)propertyId.Body).Member.Name; - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Localization/TranslationData.cs b/BillsManager.Localization/TranslationData.cs deleted file mode 100644 index 56e3f8a..0000000 --- a/BillsManager.Localization/TranslationData.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Caliburn.Micro; -using System; -using System.Windows; - -namespace BillsManager.Localization -{ - public class TranslationData : PropertyChangedBase, IWeakEventListener - { - #region fields - - private readonly string key; - - #endregion - - #region ctor - - public TranslationData(string key) - { - this.key = key; - LanguageChangedEventManager.AddListener(TranslationManager.Instance, this); - } - - #endregion - - #region properties - - public string Value - { - get { return TranslationManager.Instance.Translate(this.key); } - } - - #endregion - - #region IWeakEventListener Members - - public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) - { - if (managerType == typeof(LanguageChangedEventManager)) - { - this.NotifyOfPropertyChange(() => this.Value); - return true; - } - return false; - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Localization/TranslationManager.cs b/BillsManager.Localization/TranslationManager.cs deleted file mode 100644 index 1fc279a..0000000 --- a/BillsManager.Localization/TranslationManager.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Threading; -using System.Windows; -using System.Windows.Markup; - -namespace BillsManager.Localization -{ - public class TranslationManager - { - #region ctor - - private TranslationManager() - { - } - - #endregion - - #region properties - - private static TranslationManager instance; - public static TranslationManager Instance - { - get { return instance ?? (instance = new TranslationManager()); } - } - - public CultureInfo CurrentLanguage - { - get { return Thread.CurrentThread.CurrentUICulture; } - set - { - if (value != Thread.CurrentThread.CurrentUICulture) - { - Thread.CurrentThread.CurrentUICulture = value; - this.OnLanguageChanged(); - FrameworkElement.LanguageProperty.OverrideMetadata( - typeof(FrameworkElement), - new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(value.IetfLanguageTag))); - } - } - } - - public IEnumerable Languages - { - get { return this.TranslationProvider.Languages ?? Enumerable.Empty(); } - } - - // TODO: if translation provider changes, available languages have to be updated - public ITranslationProvider TranslationProvider { get; set; } - - #endregion - - #region methods - - public string Translate(string key) - { - if (this.TranslationProvider != null) - { - var translatedValue = this.TranslationProvider.Translate(key); - - if (translatedValue != null) - return translatedValue; - } - return string.Format("!{0}!", key); - } - - #endregion - - #region events - - public event EventHandler LanguageChanged; - - private void OnLanguageChanged() - { - if (this.LanguageChanged != null) - { - this.LanguageChanged(this, EventArgs.Empty); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Localization/packages.config b/BillsManager.Localization/packages.config deleted file mode 100644 index 8a808a9..0000000 --- a/BillsManager.Localization/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/BillsManager.Models/Address/Address.ICloneable.cs b/BillsManager.Models/Address/Address.ICloneable.cs deleted file mode 100644 index 37a0d0f..0000000 --- a/BillsManager.Models/Address/Address.ICloneable.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace BillsManager.Models -{ - public partial class Address : ICloneable - { - #region ICloneable - - #region methods - - public object Clone() - { - return this.MemberwiseClone(); - } - - #endregion - - #endregion - } -} diff --git a/BillsManager.Models/Address/Address.cs b/BillsManager.Models/Address/Address.cs deleted file mode 100644 index 8e9da5a..0000000 --- a/BillsManager.Models/Address/Address.cs +++ /dev/null @@ -1,131 +0,0 @@ -namespace BillsManager.Models -{ - public partial class Address - { - #region ctor - - public Address() - { - } - - public Address( - string street, - string number, - string city, - string zip, - string province, - string country) - { - this.Street = street; - this.Number = number; - this.City = city; - this.Zip = zip; - this.Province = province; - this.Country = country; - } - - #endregion - - #region properties - - private string street; - public string Street - { - get { return this.street; } - set - { - if (this.Street != value) - { - this.street = value; - } - } - } - - private string number; - public string Number - { - get { return this.number; } - set - { - if (this.Number != value) - { - this.number = value; - } - } - } - - private string city; - public string City - { - get { return this.city; } - set - { - if (this.City != value) - { - this.city = value; - } - } - } - - private string zip; - public string Zip - { - get { return this.zip; } - set - { - if (this.Zip != value) - { - this.zip = value; - } - } - } - - private string province; - public string Province - { - get { return this.province; } - set - { - if (this.Province != value) - { - this.province = value; - } - } - } - - private string country; - public string Country - { - get { return this.country; } - set - { - if (this.Country != value) - { - this.country = value; - } - } - } - - #endregion - - #region methods - - #region override - - public override string ToString() - { - return - this.Street + - " " + this.Number + - ", " + this.Zip + - " " + this.City + - " (" + this.Province + ")" + - " - " + this.Country; - //return base.ToString(); - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Models/Agent.cs b/BillsManager.Models/Agent.cs deleted file mode 100644 index dc4c2f4..0000000 --- a/BillsManager.Models/Agent.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; - -namespace BillsManager.Models -{ - public partial class Agent - { - #region ctor - - public Agent() - { - } - - public Agent( - uint id, - string name, - string surname, - string firstPhoneNumber, - string secondPhoneNumber) - { - this.ID = id; - this.Name = name; - this.Surname = surname; - this.FirstPhoneNumber = firstPhoneNumber; - this.SecondPhoneNumber = secondPhoneNumber; - } - - #endregion - - #region properties - - private uint id = 0; - public uint ID - { - get { return this.id; } - private set - { - this.id = value; - } - } - - private string name; - public string Name - { - get - { - return this.name; - } - set - { - if (this.Name != value) - { - this.name = value; - } - } - } - - private string surname; - public string Surname - { - get - { - return this.surname; - } - set - { - if (this.Surname != value) - { - this.surname = value; - } - } - } - - private string firstPhoneNumber; - public string FirstPhoneNumber - { - get - { - return this.firstPhoneNumber; - } - set - { - if (this.FirstPhoneNumber != value) - { - this.firstPhoneNumber = value; - } - } - } - - private string secondPhoneNumber; - public string SecondPhoneNumber - { - get - { - return this.secondPhoneNumber; - } - set - { - if (this.SecondPhoneNumber != value) - { - this.secondPhoneNumber = value; - } - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Models/BillsManager.Models.csproj b/BillsManager.Models/BillsManager.Models.csproj deleted file mode 100644 index 84d3120..0000000 --- a/BillsManager.Models/BillsManager.Models.csproj +++ /dev/null @@ -1,80 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {888F670B-4396-4660-8C5A-0D43FB2C0A1D} - Library - Properties - BillsManager.Models - BillsManager.Models - v4.5 - 512 - SAK - SAK - SAK - SAK - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - AnyCPU - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {5387db3b-6ec1-42cf-a72b-cef5adfb541a} - BillsManager.Localization - - - - - \ No newline at end of file diff --git a/BillsManager.Models/Collections/ObjectModel/ReadOnlyObservableCollectionEx.cs b/BillsManager.Models/Collections/ObjectModel/ReadOnlyObservableCollectionEx.cs deleted file mode 100644 index 705768c..0000000 --- a/BillsManager.Models/Collections/ObjectModel/ReadOnlyObservableCollectionEx.cs +++ /dev/null @@ -1,726 +0,0 @@ -using System.Collections.Generic; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace System.Collections.ObjectModel -{ - [Serializable] - [DebuggerDisplay("Count = {Count}, HasFilters = {Filters != null}, HasComparer = {Comparer != null}")] - public class ReadOnlyObservableCollectionEx : IList, IList, IReadOnlyList, INotifyCollectionChanged, INotifyPropertyChanged - where T : class, INotifyPropertyChanged - { - #region fields - - private readonly ObservableCollection source; - private IList filteredSource; - - [NonSerialized] - private Object _syncRoot; - - #endregion - - #region ctor - - public ReadOnlyObservableCollectionEx(ObservableCollection source, IEnumerable> filters, IComparer comparer) - { - if (source == null) - throw new ArgumentNullException(); - - this.source = source; - this.filters = filters; - this.comparer = comparer; - - this.UpdateItemsAndSort(); - - this.SubscribeToSourceINCC(this.source); - this.SubscribeToItemsINPC(this.source); - - } - - public ReadOnlyObservableCollectionEx(ObservableCollection source) - : this(source, null, null) - { - } - - #endregion ctor - - #region properties - - private IEnumerable> filters; - public IEnumerable> Filters - { - get { return this.filters; } - set - { - if (this.filters == value & value == null) return; - - this.filters = value; - this.NotifyOfPropertyChange(); - - this.UpdateItemsAndSort(); - - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - } - } - - private IComparer comparer; - public IComparer Comparer - { - get { return this.comparer; } - set - { - if (this.comparer == value) return; - - this.comparer = value; - this.NotifyOfPropertyChange("Comparer"); - - if (this.Comparer != null) - { - this.UpdateItemsOrder(); - } - else - { - this.UpdateItems(); - this.NotifyOfPropertyChange("Count[]"); - } - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - } - } - - #endregion properties - - #region methods - - private void UpdateItems() - { - var fs = this.source.AsEnumerable(); - - if (this.Filters != null) - fs = fs.Where(i => this.Filters.All(f => f(i))); - - this.filteredSource = fs.ToList(); - } - - private void UpdateItemsOrder() - { - if (this.Comparer != null) - { - var x = this.filteredSource.AsEnumerable(); - var ox = x.OrderBy(t => t, this.Comparer); - this.filteredSource = ox.ToList(); - } - } - - private void UpdateItemsAndSort() - { - var fs = this.source.AsEnumerable(); - - if (this.Filters != null) - fs = fs.Where(i => this.Filters.All(f => f(i))); - - if (this.Comparer != null) - fs = fs.OrderBy(t => t, this.Comparer); - - this.filteredSource = fs.ToList(); - } - - private bool IsItemAllowed(T item) - { - return (this.Filters == null || (this.Filters != null && this.Filters.All(f => f(item)))); - } - - private void SubscribeToSourceINCC(INotifyCollectionChanged source) - { - ((INotifyCollectionChanged)source).CollectionChanged += new NotifyCollectionChangedEventHandler(HandleCollectionChanged); - ((INotifyPropertyChanged)source).PropertyChanged += new PropertyChangedEventHandler(HandlePropertyChanged); - } - - private void SubscribeToItemsINPC(IEnumerable items) - { - foreach (var i in this.source) - { - i.PropertyChanged += ItemPropertyChanged; - } - } - - private void UnsubscribeFromItemsINPC(IEnumerable items) - { - foreach (var i in this.source) - { - i.PropertyChanged -= ItemPropertyChanged; - } - } - - #endregion methods - - #region implementations - - #region IList, IList, IReadOnlyList - - public int Count - { - get { return this.filteredSource.Count; } - } - - public T this[int index] - { - get { return this.filteredSource[index]; } - } - - public bool Contains(T value) - { - return this.filteredSource.Contains(value); - } - - public void CopyTo(T[] array, int index) - { - this.filteredSource.CopyTo(array, index); - } - - public IEnumerator GetEnumerator() - { - return this.filteredSource.GetEnumerator(); - } - - public int IndexOf(T value) - { - return this.filteredSource.IndexOf(value); - } - - protected IList Items - { - get - { - return this.filteredSource; - } - } - - bool ICollection.IsReadOnly - { - get { return true; } - } - - T IList.this[int index] - { - get { return this.filteredSource[index]; } - set - { - throw new NotSupportedException(); - } - } - - void ICollection.Add(T value) - { - throw new NotSupportedException(); - } - - void ICollection.Clear() - { - throw new NotSupportedException(); - } - - void IList.Insert(int index, T value) - { - throw new NotSupportedException(); - } - - bool ICollection.Remove(T value) - { - throw new NotSupportedException(); - } - - void IList.RemoveAt(int index) - { - throw new NotSupportedException(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)this.filteredSource).GetEnumerator(); - } - - bool ICollection.IsSynchronized - { - get { return false; } - } - - object ICollection.SyncRoot - { - get - { - if (_syncRoot == null) - { - ICollection c = this.filteredSource as ICollection; - if (c != null) - { - _syncRoot = c.SyncRoot; - } - else - { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); - } - } - return _syncRoot; - } - } - - void ICollection.CopyTo(Array array, int index) - { - if (array == null) - { - throw new ArgumentNullException(); - } - - if (array.Rank != 1) - { - throw new ArgumentException(); - } - - if (array.GetLowerBound(0) != 0) - { - throw new ArgumentException(); - } - - if (index < 0) - { - throw new ArgumentException(); - } - - if (array.Length - index < Count) - { - throw new ArgumentException(); - } - - T[] items = array as T[]; - if (items != null) - { - this.filteredSource.CopyTo(items, index); - } - else - { - // - // Catch the obvious case assignment will fail. - // We can found all possible problems by doing the check though. - // For example, if the element type of the Array is derived from T, - // we can't figure out if we can successfully copy the element beforehand. - // - Type targetType = array.GetType().GetElementType(); - Type sourceType = typeof(T); - if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) - { - throw new ArgumentException(); - } - - // - // We can't cast array of value type to object[], so we don't support - // widening of primitive types here. - // - object[] objects = array as object[]; - if (objects == null) - { - throw new ArgumentException(); - } - - int count = this.filteredSource.Count; - try - { - for (int i = 0; i < count; i++) - { - objects[index++] = this.filteredSource[i]; - } - } - catch (ArrayTypeMismatchException) - { - throw new ArgumentException(); - } - } - } - - bool IList.IsFixedSize - { - get { return true; } - } - - bool IList.IsReadOnly - { - get { return true; } - } - - object IList.this[int index] - { - get { return this.filteredSource[index]; } - set - { - throw new NotSupportedException(); - } - } - - int IList.Add(object value) - { - throw new NotSupportedException(); - } - - void IList.Clear() - { - throw new NotSupportedException(); - } - - private static bool IsCompatibleObject(object value) - { - // Non-null values are fine. Only accept nulls if T is a class or Nullable. - // Note that default(T) is not equal to null for value types except when T is Nullable. - return ((value is T) || (value == null && default(T) == null)); - } - - bool IList.Contains(object value) - { - if (IsCompatibleObject(value)) - { - return this.Contains((T)value); - } - return false; - } - - int IList.IndexOf(object value) - { - if (IsCompatibleObject(value)) - { - return this.IndexOf((T)value); - } - return -1; - } - - void IList.Insert(int index, object value) - { - throw new NotSupportedException(); - } - - void IList.Remove(object value) - { - throw new NotSupportedException(); - } - - void IList.RemoveAt(int index) - { - throw new NotSupportedException(); - } - - #endregion IList, IList, IReadOnlyList - - #region INotifyCollectionChanged - - event NotifyCollectionChangedEventHandler INotifyCollectionChanged.CollectionChanged - { - add { this.CollectionChanged += value; } - remove { this.CollectionChanged -= value; } - } - - [field: NonSerialized] - protected virtual event NotifyCollectionChangedEventHandler CollectionChanged; - - protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) - { - if (this.CollectionChanged != null) - { - this.CollectionChanged(this, args); - } - } - - private void HandleCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) - { - switch (e.Action) - { - case NotifyCollectionChangedAction.Add: - { - var newItem = e.NewItems[0] as T; - - newItem.PropertyChanged += this.ItemPropertyChanged; - - // TODO: try invert if conditions order -> might remove the repeated check in this.IsItemAllowed - if (this.IsItemAllowed(newItem)) // if it has to be added - { - int addIndex = e.NewStartingIndex; - - if (this.Comparer != null) // if it has to be sorted - { - this.filteredSource.Insert(0, newItem); // add it anywhere and sort - this.UpdateItemsOrder(); - - addIndex = this.IndexOf(newItem); - } - else // if it doesn't have to be sorted - { - if (this.Filters != null) // if there are filters - { - this.UpdateItems(); // update the whole list to put it in the right index - - addIndex = this.IndexOf(newItem); - } - else // if no filtering and no sorting - this.filteredSource.Insert(addIndex, newItem); - } - - this.NotifyOfPropertyChange("Item[]"); - this.NotifyOfPropertyChange("Count"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, e.NewItems, addIndex)); - } - break; - } - - case NotifyCollectionChangedAction.Move: - { - var movedItem = e.OldItems[0] as T; - - if (this.Comparer == null) // if the item IS contained AND sorting is NOT ACTIVE - { - if (this.Filters != null) // if there are filters - { - if (this.Filters.All(f => f(movedItem))) // if the it is contained - { - var oldIndex = this.IndexOf(movedItem); - this.UpdateItems(); // TODO: check if there's a way to calculate the new index - var newIndex = this.IndexOf(movedItem); - - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, e.OldItems, newIndex, oldIndex)); - } - else - { - // this condition is never reached - } - } - else // if no filtering and no sorting - { - this.filteredSource.RemoveAt(e.OldStartingIndex); - this.filteredSource.Insert(e.NewStartingIndex, movedItem); - - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(e); - } - } - break; - } - - case NotifyCollectionChangedAction.Remove: - { - var removedItem = e.OldItems[0] as T; - - removedItem.PropertyChanged -= this.ItemPropertyChanged; - - if (this.IsItemAllowed(removedItem)) // if it is contained, remove it - { - var removeIndex = e.OldStartingIndex; - - if (this.Filters != null || this.Comparer != null) // if the index might be different - removeIndex = this.IndexOf(removedItem); - - this.filteredSource.RemoveAt(removeIndex); - - this.NotifyOfPropertyChange("Item[]"); - this.NotifyOfPropertyChange("Count"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, e.OldItems, removeIndex)); - } - break; - } - - case NotifyCollectionChangedAction.Replace: - { - var oldItem = e.OldItems[0] as T; - var newItem = e.NewItems[0] as T; - - oldItem.PropertyChanged -= this.ItemPropertyChanged; - newItem.PropertyChanged += this.ItemPropertyChanged; - - if (this.Filters != null) - { - int addIndex = e.NewStartingIndex; - var removeIndex = this.IndexOf(oldItem); // remove it - - bool oldRemoved = false; - bool newAdded = false; - - if (this.Filters.All(f => f(oldItem))) // if the old item was contained - { - this.filteredSource.RemoveAt(removeIndex); - oldRemoved = true; - } - - if (this.Filters.All(f => f(newItem))) // if the new item has to be inserted - { - if (this.Comparer != null) // if it has to be sorted - { - this.filteredSource.Insert(0, newItem); // add it anywhere and sort - this.UpdateItemsOrder(); - } - else // if it doesn't have to be sorted - { - this.UpdateItems(); // update the whole list to put it in the right index - } - - addIndex = this.IndexOf(newItem); - newAdded = true; - } - - if (oldRemoved) - { - if (newAdded) - if (removeIndex == addIndex) - { - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, e.NewItems, e.OldItems, removeIndex)); - } - else - { - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, e.OldItems, removeIndex)); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, e.NewItems, addIndex)); - } - else - { - this.NotifyOfPropertyChange("Item[]"); - this.NotifyOfPropertyChange("Count[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, e.OldItems, removeIndex)); - } - } - else - { - if (newAdded) - { - this.NotifyOfPropertyChange("Item[]"); - this.NotifyOfPropertyChange("Count[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, e.NewItems, addIndex)); - } - } - } - else // if there are no filters - { - var removeIndex = e.OldStartingIndex; - var insertIndex = e.NewStartingIndex; - - if (this.Comparer != null) // if sorting is active - { - removeIndex = this.IndexOf(oldItem); - this.filteredSource.RemoveAt(removeIndex); - this.filteredSource.Insert(0, newItem); - this.UpdateItemsOrder(); - insertIndex = this.IndexOf(newItem); - - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, e.OldItems, removeIndex)); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, e.NewItems, insertIndex)); - } - else - { - removeIndex = this.IndexOf(oldItem); - this.filteredSource.RemoveAt(removeIndex); - this.filteredSource.Insert(insertIndex, newItem); - insertIndex = this.IndexOf(newItem); - - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, e.NewItems, e.OldItems, removeIndex)); - } - } - break; - } - - case NotifyCollectionChangedAction.Reset: - { - // URGENT: this doesn't remove subscriptions from removed items, just adds to new ones - - // when the source collection is reset, we must refresh subscriptions, in order to unsubscribe from removed elements - this.UnsubscribeFromItemsINPC(this.source); - this.UpdateItemsAndSort(); - this.SubscribeToItemsINPC(this.source); - - this.OnCollectionChanged(e); - break; - } - - default: - throw new InvalidEnumArgumentException(@"Unknown collection action: " + e.Action); - } - } - - #endregion INotifyCollectionChanged - - #region INotifyPropertyChanged - - event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged - { - add { this.PropertyChanged += value; } - remove { this.PropertyChanged -= value; } - } - - [field: NonSerialized] - protected virtual event PropertyChangedEventHandler PropertyChanged; - - protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, args); - } - } - - void HandlePropertyChanged(object sender, PropertyChangedEventArgs e) - { - this.OnPropertyChanged(e); - } - - public virtual void NotifyOfPropertyChange([CallerMemberName] string propertyName = null) - { - this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); - } - - private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e) - { - var changedItem = sender as T; - if (sender == null) - throw new InvalidOperationException("sender is not of type " + typeof(T).Name); - - if (this.IsItemAllowed(changedItem)) // if the item is allowed - { - if (this.Contains(changedItem)) - { - this.UpdateItemsOrder(); - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - } - else // if it has to be added - { - if (this.Comparer != null) - { - // TODO: check whether add is more performant than insert(0) - this.filteredSource.Insert(0, changedItem); // add it anywhere an sort - this.UpdateItemsOrder(); - } - else - { - this.UpdateItems(); - } - var addIndex = this.IndexOf(changedItem); - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, changedItem, addIndex)); - } - } - else - { - if (this.Contains(changedItem)) - { - var removeIndex = this.IndexOf(changedItem); - this.filteredSource.Remove(changedItem); - this.NotifyOfPropertyChange("Item[]"); - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, changedItem, removeIndex)); - } - } - } - - #endregion INotifyPropertyChanged - - #endregion implementations - } -} \ No newline at end of file diff --git a/BillsManager.Models/Database/Database.cs b/BillsManager.Models/Database/Database.cs deleted file mode 100644 index df70d67..0000000 --- a/BillsManager.Models/Database/Database.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace BillsManager.Models -{ - public class Database // TODO: re-evaluate the idea - { - public Database(string path) - { - this.Path = path; - this.Name = System.IO.Path.GetFileNameWithoutExtension(path); - } - - public string Path { get; private set; } - - public string Name { get; private set; } - } -} \ No newline at end of file diff --git a/BillsManager.Models/Entities/Bill/Bill.ICloneable.cs b/BillsManager.Models/Entities/Bill/Bill.ICloneable.cs deleted file mode 100644 index ee79a1a..0000000 --- a/BillsManager.Models/Entities/Bill/Bill.ICloneable.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace BillsManager.Models -{ - public partial class Bill : ICloneable - { - #region ICloneable - - #region methods - - public object Clone() - { - return this.MemberwiseClone(); - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Models/Entities/Bill/Bill.cs b/BillsManager.Models/Entities/Bill/Bill.cs deleted file mode 100644 index 7fd3a60..0000000 --- a/BillsManager.Models/Entities/Bill/Bill.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; - -namespace BillsManager.Models -{ - public partial class Bill - { - #region ctor - - public Bill(uint id) - : this( - id, - 0, - DateTime.Today, - DateTime.Today, - DateTime.Today, - null, - 0, - 0, - 0, - null, - null) - { - } - - public Bill( - uint id, - uint supplierID, - DateTime registrationDate, - DateTime dueDate, - DateTime releaseDate, - DateTime? paymentDate, - Double amount, - Double agio, - Double costs, - string code, - string notes) - { - this.AdditionalCosts = costs; - this.Agio = agio; - this.Amount = amount; - this.Code = code; - this.DueDate = dueDate; - this.id = id; - this.Notes = notes; - this.PaymentDate = paymentDate; - this.RegistrationDate = registrationDate; - this.ReleaseDate = releaseDate; - this.SupplierID = supplierID; - } - - #endregion - - #region properties - - private readonly uint id = 0; - public uint ID - { - get { return this.id; } - } - - public DateTime RegistrationDate { get; set; } - - public DateTime DueDate { get; set; } - - public DateTime? PaymentDate { get; set; } - - public DateTime ReleaseDate { get; set; } - - public Double Amount { get; set; } - - public Double Agio { get; set; } - - public Double AdditionalCosts { get; set; } - - public uint SupplierID { get; set; } - - public string Notes { get; set; } - - public string Code { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Models/Entities/Settings/ISettings.cs b/BillsManager.Models/Entities/Settings/ISettings.cs deleted file mode 100644 index 6529b0f..0000000 --- a/BillsManager.Models/Entities/Settings/ISettings.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace BillsManager.Models -{ - public interface ISettings - { - CultureInfo Language { get; set; } - } -} \ No newline at end of file diff --git a/BillsManager.Models/Entities/Settings/Settings.ICloneable.cs b/BillsManager.Models/Entities/Settings/Settings.ICloneable.cs deleted file mode 100644 index 1225ee1..0000000 --- a/BillsManager.Models/Entities/Settings/Settings.ICloneable.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Globalization; - -namespace BillsManager.Models -{ - public partial class Settings : ICloneable - { - #region ICloneable Members - - public object Clone() - { - return - new Settings( - (CultureInfo)this.Language.Clone(), - this.StartupDBLoad, - this.FeedbackToEmailAddress); - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Models/Entities/Settings/Settings.cs b/BillsManager.Models/Entities/Settings/Settings.cs deleted file mode 100644 index 983a3d3..0000000 --- a/BillsManager.Models/Entities/Settings/Settings.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Globalization; - -namespace BillsManager.Models -{ - // TODO: add digits separator style - public partial class Settings : ISettings - { - public Settings( - CultureInfo language, - bool startupDBLoad, - string feedbackToEmailAddress - ) - { - this.Language = language; - this.StartupDBLoad = startupDBLoad; - this.FeedbackToEmailAddress = feedbackToEmailAddress; - } - - public CultureInfo Language { get; set; } - - // TODO: remove - public bool StartupDBLoad { get; set; } - - public string FeedbackToEmailAddress { get; set; } - } -} \ No newline at end of file diff --git a/BillsManager.Models/Entities/Supplier/Supplier.ICloneable.cs b/BillsManager.Models/Entities/Supplier/Supplier.ICloneable.cs deleted file mode 100644 index 04026d0..0000000 --- a/BillsManager.Models/Entities/Supplier/Supplier.ICloneable.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace BillsManager.Models -{ - public partial class Supplier : ICloneable - { - #region ICloneable - - #region methods - - public object Clone() - { - - Supplier suppCopy = (Supplier)this.MemberwiseClone(); - - //suppCopy.Address = (Address)this.Address.Clone(); - - return suppCopy; - } - - #endregion - - #endregion - } -} diff --git a/BillsManager.Models/Entities/Supplier/Supplier.cs b/BillsManager.Models/Entities/Supplier/Supplier.cs deleted file mode 100644 index a7795f7..0000000 --- a/BillsManager.Models/Entities/Supplier/Supplier.cs +++ /dev/null @@ -1,114 +0,0 @@ -namespace BillsManager.Models -{ - public partial class Supplier - { - #region ctor - - public Supplier(uint id) - : this( - id, - null, - null, - null, - null, - null, - null, - "Italia", - null, - null, - null, - null, - null, - null, - null, - null) - { - } - - public Supplier( - uint id, - string name, - string street, - string number, - string city, - string zip, - string province, - string country, - string eMail, - string webSite, - string phone, - string fax, - string notes, - string agentName, - string agentSurname, - string agentPhone) - { - this.id = id; - - this.Name = name; - this.eMail = eMail; - this.Website = webSite; - this.Phone = phone; - this.Fax = fax; - this.Notes = notes; - - this.AgentName = agentName; - this.AgentSurname = agentSurname; - this.AgentPhone = agentPhone; - - // Address - this.Street = street; - this.Number = number; - this.City = city; - this.Zip = zip; - this.Province = province; - this.Country = country; - } - - #endregion - - #region properties - - private readonly uint id; - public uint ID - { - get { return this.id; } - } - - public string Name { get; set; } - - public string AgentName { get; set; } - - public string AgentSurname { get; set; } - - public string AgentPhone { get; set; } - - public string eMail { get; set; } - - public string Website { get; set; } - - public string Phone { get; set; } - - public string Fax { get; set; } - - public string Notes { get; set; } - - #region address - - public string Street { get; set; } - - public string Number { get; set; } - - public string City { get; set; } - - public string Zip { get; set; } - - public string Province { get; set; } - - public string Country { get; set; } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Models/Enums/DBConnectionState.cs b/BillsManager.Models/Enums/DBConnectionState.cs deleted file mode 100644 index 8247160..0000000 --- a/BillsManager.Models/Enums/DBConnectionState.cs +++ /dev/null @@ -1,14 +0,0 @@ -using BillsManager.Localization.Attributes; - -namespace BillsManager.Models -{ - public enum DBConnectionState // TODO: consider mapping full type name to res value - { - [LocalizedDisplayName("Disconnected_toDB")] - Disconnected = 0, - [LocalizedDisplayName("Connected_toDB")] - Connected = 1, - [LocalizedDisplayName("Unsaved_toDB")] - Unsaved = 2 - } -} \ No newline at end of file diff --git a/BillsManager.Models/Enums/DueAlert.cs b/BillsManager.Models/Enums/DueAlert.cs deleted file mode 100644 index 04a8231..0000000 --- a/BillsManager.Models/Enums/DueAlert.cs +++ /dev/null @@ -1,18 +0,0 @@ -using BillsManager.Localization.Attributes; - -namespace BillsManager.Models -{ - public enum DueAlert - { - [LocalizedDisplayName("None_toDueLevel")] - None = 0, - [LocalizedDisplayName("Low_toDueLevel")] - Low = 1, - [LocalizedDisplayName("Medium_toDueLevel")] - Medium = 2, - [LocalizedDisplayName("High_toDueLevel")] - High = 3, - [LocalizedDisplayName("Critical_toDueLevel")] - Critical = 4 - } -} \ No newline at end of file diff --git a/BillsManager.Models/Enums/Obligation.cs b/BillsManager.Models/Enums/Obligation.cs deleted file mode 100644 index 57636d2..0000000 --- a/BillsManager.Models/Enums/Obligation.cs +++ /dev/null @@ -1,14 +0,0 @@ -using BillsManager.Localization.Attributes; - -namespace BillsManager.Models -{ - public enum Obligation - { - [LocalizedDisplayName("Creditor_toSupplier")] - Creditor = -1, - [LocalizedDisplayName("Unbound_toSupplier")] - Unbound = 0, - [LocalizedDisplayName("Debtor_toSupplier")] - Debtor = 1 - } -} \ No newline at end of file diff --git a/BillsManager.Models/Properties/AssemblyInfo.cs b/BillsManager.Models/Properties/AssemblyInfo.cs deleted file mode 100644 index 59543bb..0000000 --- a/BillsManager.Models/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// Le informazioni generali relative a un assembly sono controllate dal seguente -// set di attributi. Per modificare le informazioni associate a un assembly -// occorre quindi modificare i valori di questi attributi. -[assembly: AssemblyTitle("BillsManager.Models")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BillsManager.Models")] -[assembly: AssemblyCopyright("Copyright © Nalesso Sergio 2013-2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili -// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da -// COM, impostare su true l'attributo ComVisible per tale tipo. -[assembly: ComVisible(false)] - -// Se il progetto viene esposto a COM, il GUID che segue verrà utilizzato per creare l'ID della libreria dei tipi -[assembly: Guid("854a1bef-4fb4-4006-a71c-9178ff7785af")] - -// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: -// -// Numero di versione principale -// Numero di versione secondario -// Numero build -// Revisione -// -// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build -// utilizzando l'asterisco (*) come descritto di seguito: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BillsManager.Services/BillsManager.Services.csproj b/BillsManager.Services/BillsManager.Services.csproj deleted file mode 100644 index 78e327b..0000000 --- a/BillsManager.Services/BillsManager.Services.csproj +++ /dev/null @@ -1,130 +0,0 @@ - - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {FC8A7A61-D9CF-4AC7-A62D-590C35A28A44} - Library - Properties - BillsManager.Services - BillsManager.Services - v4.5 - 512 - SAK - SAK - SAK - SAK - - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - AnyCPU - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - - ..\packages\linq2db.2.6.4\lib\net45\linq2db.dll - - - - - - - - ..\packages\System.Data.SQLite.Core.1.0.109.1\lib\net45\System.Data.SQLite.dll - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - {5387db3b-6ec1-42cf-a72b-cef5adfb541a} - BillsManager.Localization - - - {888F670B-4396-4660-8C5A-0D43FB2C0A1D} - BillsManager.Models - - - - - - - - - - - - - - - - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - \ No newline at end of file diff --git a/BillsManager.Services/BillsManager.Services.csproj.user b/BillsManager.Services/BillsManager.Services.csproj.user deleted file mode 100644 index 6cbe588..0000000 --- a/BillsManager.Services/BillsManager.Services.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - ProjectFiles - - \ No newline at end of file diff --git a/BillsManager.Services/DB/IBillsRepository.cs b/BillsManager.Services/DB/IBillsRepository.cs deleted file mode 100644 index 389b04c..0000000 --- a/BillsManager.Services/DB/IBillsRepository.cs +++ /dev/null @@ -1,20 +0,0 @@ -using BillsManager.Models; -using System.Collections.Generic; - -namespace BillsManager.Services.DB -{ - public interface IBillsRepository - { - uint GetLastBillID(); - - IEnumerable GetAllBills(); - - bool Add(Bill bill); - - bool Edit(Bill bill); - //bool Edit(IEnumerable bills); // TODO: obsolete? - - bool Delete(Bill bill); - //bool Delete(IEnumerable bills); // TODO: obsolete? - } -} \ No newline at end of file diff --git a/BillsManager.Services/DB/IDBService.cs b/BillsManager.Services/DB/IDBService.cs deleted file mode 100644 index c8cb460..0000000 --- a/BillsManager.Services/DB/IDBService.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace BillsManager.Services.DB -{ - public interface IDBService : - IBillsRepository, - ISuppliersRepository - { - bool Connect(); - - bool Save(); - - void Disconnect(); - } -} \ No newline at end of file diff --git a/BillsManager.Services/DB/ISuppliersRepository.cs b/BillsManager.Services/DB/ISuppliersRepository.cs deleted file mode 100644 index e5d6460..0000000 --- a/BillsManager.Services/DB/ISuppliersRepository.cs +++ /dev/null @@ -1,20 +0,0 @@ -using BillsManager.Models; -using System.Collections.Generic; - -namespace BillsManager.Services.DB -{ - public interface ISuppliersRepository - { - uint GetLastSupplierID(); - - IEnumerable GetAllSuppliers(); - - bool Add(Supplier supplier); - - bool Edit(Supplier supplier); - //bool Edit(IEnumerable suppliers); // TODO: obsolete? - - bool Delete(Supplier supplier); - //bool Delete(IEnumerable suppliers); // TODO: obsolete? - } -} \ No newline at end of file diff --git a/BillsManager.Services/DB/LINQToDBDBService.cs b/BillsManager.Services/DB/LINQToDBDBService.cs deleted file mode 100644 index 31288ae..0000000 --- a/BillsManager.Services/DB/LINQToDBDBService.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Data.Common; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using BillsManager.Models; -using LinqToDB.Data; -using LinqToDB.DataProvider; -using LinqToDB; -using LinqToDB.Data; -using LinqToDB.Mapping; - -namespace BillsManager.Services.DB -{ - public class LINQToDBDBService : IDBService, IDisposable - { - public const string DBFileName = "db.sqlite"; - - //private LinqToDB.DataProvider.SQLite.SQLiteTools xx = null; - //private readonly LinqToDB.DataProvider.SQLite.SQLiteDataProvider _dbConnection; - private readonly ConnectionStringSettings _connectionString = new ConnectionStringSettings - { - Name = "Database", - ProviderName = LinqToDB.ProviderName.SQLite, - ConnectionString = "Data Source=" + DBFileName - }; - private readonly IDataProvider _dataProvider; - - private DataConnection _dataConnection; - private uint? _lastBillID; - private uint? _lastSupplierID; - - - public LINQToDBDBService() - { - //this._dataProvider = new LinqToDB.DataProvider.SQLite.SQLiteDataProvider(); - } - - public bool Add(Bill bill) - { - return this._dataConnection.Insert(bill) > 0; - } - - public bool Add(Supplier supplier) - { - return this._dataConnection.Insert(supplier) > 0; - } - - public bool Connect() - { - if (this._dataConnection == null) - { - this._dataConnection = LinqToDB.DataProvider.SQLite.SQLiteTools.CreateDataConnection(this._connectionString.ConnectionString); - //this._dataConnection.Connection.Open(); - - return this._dataConnection != null; - } - - - switch (this._dataConnection.Connection.State) - { - case ConnectionState.Open: - return true; - - case ConnectionState.Closed: - case ConnectionState.Broken: - this._dataConnection.Connection.Open(); - return true; - - case ConnectionState.Connecting: - case ConnectionState.Fetching: - case ConnectionState.Executing: - return true; - - default: - return true; - } - - } - - public bool Delete(Bill bill) - { - return this._dataConnection.Delete(bill) > 0; - } - - public bool Delete(Supplier supplier) - { - return this._dataConnection.Delete(supplier) > 0; - } - - public void Disconnect() - { - if (this._dataConnection != null) - { - this._dataConnection.Close(); - } - } - - public void Dispose() - { - if (this._dataConnection != null) - { - this._dataConnection.Close(); - this._dataConnection.Dispose(); - //this._dbConnection = null; - } - } - - public bool Edit(Bill bill) - { - return this._dataConnection.Update(bill) > 0; - } - - public bool Edit(Supplier supplier) - { - return this._dataConnection.Update(supplier) > 0; - } - - public IEnumerable GetAllBills() - { - return this._dataConnection.GetTable().ToList().AsReadOnly(); - } - - public IEnumerable GetAllSuppliers() - { - return this._dataConnection.GetTable().ToList().AsReadOnly(); - } - - public uint GetLastBillID() - { - return this._dataConnection.GetTable().Max(b => b.ID); - } - - public uint GetLastSupplierID() - { - return this._dataConnection.GetTable().Max(s => s.ID); - } - - public bool Save() - { - throw new NotSupportedException(); - } - } -} diff --git a/BillsManager.Services/DB/MockedDBService.cs b/BillsManager.Services/DB/MockedDBService.cs deleted file mode 100644 index 546d1d2..0000000 --- a/BillsManager.Services/DB/MockedDBService.cs +++ /dev/null @@ -1,217 +0,0 @@ -using BillsManager.Models; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace BillsManager.Services.DB -{ - public partial class MockedDBConnector : IDBService - { - private readonly int suppliersCount, billsPerSupplierCount; - - private IList bills; - private IList suppliers; - - public MockedDBConnector(int suppliersCount, int billsPerSupplierCount) - { - this.billsPerSupplierCount = billsPerSupplierCount; - this.suppliersCount = suppliersCount; - } - - public MockedDBConnector() - : this(8, 13) - { - } - - #region IDBConnector Members - - public bool Connect() - { - this.CreateFakeData(); - - return true; - } - - private void CreateFakeData() - { - this.CreateFakeSuppliers(); - this.CreateFakeBills(); - this.PaySomeBills(); - } - - private void CreateFakeBills() - { - if (this.bills == null) - this.bills = new List(); - - var r = new Random(); - - foreach (Supplier supplier in this.suppliers) - { - for (int i = 1; i <= this.billsPerSupplierCount; i++) - { - this.bills.Add( - new Bill( - (uint)i, - supplier.ID, - DateTime.Today, - DateTime.Today.AddDays(r.Next(-2, 17 + 1)), // due - DateTime.Today.AddDays(-r.Next(7 + 1)), // release - (DateTime?)null, // payment - (double)r.Next(-2000, 2000 + 1), - (double)r.Next(40), - (double)r.Next(50), - string.Format("{0:00}{1:0000}", supplier.ID, i), - string.Format("Notes {0}-{1}", supplier.ID, i))); - } - } - } - - private void CreateFakeSuppliers() - { - if (this.suppliers == null) - this.suppliers = new List(); - - for (int i = 1; i <= this.suppliersCount; i++) - { - this.suppliers.Add( - new Supplier( - (uint)i, - string.Format("Name of Supplier #{0:0000}", i), - i + "st.", - i.ToString(), - "City #" + i, - string.Format("{0:00000}", i), - "PV", - "Country #" + i, - string.Format("{0}@suppliers.bm", i), - string.Format("www.{0}.suppliers.bm", i), - string.Format("TEL {0:000 000 000 000}", i), - string.Format("FAX {0:000 000 000 000}", i), - "Notes of Supplier #" + i, - "AN #" + i, - "AS #" + i, - "AP #" + i - )); - } - } - - private void PaySomeBills() - { - if (suppliers.Count > 1) - { - var r = new Random(); - - //var minPerc = (int)Math.Floor(this.suppliers.Count * 0.61); - //var maxPerc = (int)Math.Floor(this.suppliers.Count * 0.78); - - //var suppliersToPayCount = r.Next(minPerc, maxPerc + 1); - var suppliersToPayCount = (int)Math.Floor(this.suppliers.Count * 0.82); - - var paidSuppliers = new List(); - - while (paidSuppliers.Count < suppliersToPayCount) - { - var s = this.suppliers[r.Next(this.suppliers.Count)]; - if (s == null) - { - throw new ArgumentNullException(); - } - if (!paidSuppliers.Contains(s)) - { - var sBills = this.bills.Where(b => b.SupplierID == s.ID); - foreach (Bill b in sBills) - { - b.PaymentDate = DateTime.Today; //b.ReleaseDate.AddDays(r.Next(0, DateTime.Today.Subtract(b.ReleaseDate).Days + 1)); - if (b.PaymentDate < b.ReleaseDate) - throw new ArgumentOutOfRangeException(); - } - - paidSuppliers.Add(s); - } - } - } - } - - public bool Save() - { - return true; - } - - public void Disconnect() - { - this.bills = null; - this.suppliers = null; - } - - #endregion - - #region IBillsProvider Members - - public uint GetLastBillID() - { - var last = this.bills.LastOrDefault(); - - if (last != null) - return last.ID; - - return 0; - } - - public IEnumerable GetAllBills() - { - return this.bills; - } - - public bool Add(Models.Bill bill) - { - return true; - } - - public bool Edit(Models.Bill bill) - { - return true; - } - - public bool Delete(Models.Bill bill) - { - return true; - } - - #endregion - - #region ISuppliersProvider Members - - public uint GetLastSupplierID() - { - var last = this.suppliers.LastOrDefault(); - - if (last != null) - return last.ID; - - return 0; - } - - public IEnumerable GetAllSuppliers() - { - return this.suppliers; - } - - public bool Add(Models.Supplier supplier) - { - return true; - } - - public bool Edit(Models.Supplier supplier) - { - return true; - } - - public bool Delete(Models.Supplier supplier) - { - return true; - } - - #endregion - } -} diff --git a/BillsManager.Services/DB/XMLDBService.cs b/BillsManager.Services/DB/XMLDBService.cs deleted file mode 100644 index bfe2d53..0000000 --- a/BillsManager.Services/DB/XMLDBService.cs +++ /dev/null @@ -1,563 +0,0 @@ -using BillsManager.Models; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Xml.Linq; - -namespace BillsManager.Services.DB -{ - public class XMLDBService : IDBService - { - #region fields - - private const string EXT_DB_DOTTED = @"bmdb"; - - private const short START_INDEX = 0; - - private const string NS_DATABASE_ROOT = @"Database"; - - private const string NS_BILLS = @"Bills"; - private const string ITEM_BILL = @"Bill"; - - private const string NS_SUPPLIERS = @"Suppliers"; - private const string ITEM_SUPPLIER = @"Supplier"; - - private const string NS_AGENTS = @"Agents"; - private const string ITEM_AGENT = @"Agent"; - - private const string ATT_CREATION_DATE = @"CreationDate"; - private const string ATT_LAST_ID = @"LastID"; - - private readonly string dbPath; - - private XDocument xmlDB; - - #endregion - - #region ctor - - public XMLDBService(string dbPath) - { - this.dbPath = dbPath; - this.EnsureDbFileExists(); - } - - #endregion - - #region methods - - #region connector level methods - - public bool Connect() - { - try - { -#if DEBUG - var sw = new Stopwatch(); - sw.Start(); -#endif - this.xmlDB = XDocument.Load(this.dbPath); -#if DEBUG - sw.Stop(); - Debug.WriteLine(string.Empty); - Debug.WriteLine(this.GetType().Name + " Connect() executed in " + sw.ElapsedMilliseconds + " ms"); - Debug.WriteLine(string.Empty); -#endif - } - catch - { - return false; - } - return true; - } - - public bool Save() - { - try - { - this.xmlDB.Save(this.dbPath); - } - catch - { - return false; - } - return true; - } - - public void Disconnect() - { - this.xmlDB = null; - } - - #endregion - - #region bills provider - - public uint GetLastBillID() - { - return (uint)this.xmlDB.Root.Element(NS_BILLS).Attribute(ATT_LAST_ID); - } - - public IEnumerable GetAllBills() - { - var q = - this.xmlDB.Root - .Element(NS_BILLS) - .Elements(ITEM_BILL) - .Select( - i => - { - return - new Bill( - (uint)i.Attribute("ID"), - (uint)i.Attribute("SupplierID"), - (DateTime)i.Attribute("RegistrationDate"), - (DateTime)i.Attribute("DueDate"), - (DateTime)i.Attribute("ReleaseDate"), - (DateTime?)i.Attribute("PaymentDate"), - (Double)i.Attribute("Amount"), - (Double)i.Attribute("Agio"), - (Double)i.Attribute("AdditionalCosts"), - (string)i.Attribute("Code"), - (string)i.Attribute("Notes")); - }); - - return q; - - //var query = from XBill in this.xmlDB.Root.Element(NS_BILLS).Elements(ITEM_BILL) - // select new - // Bill( - // (uint)XBill.Attribute("ID"), - // (uint)XBill.Attribute("SupplierID"), - // (DateTime)XBill.Attribute("RegistrationDate"), - // (DateTime)XBill.Attribute("DueDate"), - // (DateTime)XBill.Attribute("ReleaseDate"), - // (DateTime?)XBill.Attribute("PaymentDate"), - // (Double)XBill.Attribute("Amount"), - // (Double)XBill.Attribute("Agio"), - // (Double)XBill.Attribute("AdditionalCosts"), - // (string)XBill.Attribute("Code"), - // (string)XBill.Attribute("Notes") - // ); - - //return query; - } - - public bool Add(Bill bill) - { - this.xmlDB.Root.Element(NS_BILLS).Add(this.GetXBill(bill)); - - this.IncreaseLastIDValue(NS_BILLS); - - return true; - } - - public bool Edit(Bill bill) - { - var XBill = this.xmlDB.Root.Element(NS_BILLS) - .Elements(ITEM_BILL) - .FirstOrDefault(elem => elem.Attribute("ID").Value == bill.ID.ToString()); - - if (XBill == null) - return false; - - XBill.ReplaceWith(this.GetXBill(bill)); - - return true; - } - - //public bool Edit(IEnumerable bills) - //{ - // foreach (Bill b in bills) - // { - // var XBill = this.xmlDB.Root.Element(NS_BILLS) - // .Elements(ITEM_BILL) - // .Single(elem => elem.Attribute("ID").Value == b.ID.ToString()); - - // typeof(Bill).GetProperties(BindingFlags.Public | BindingFlags.Instance) - // .Where(pi => pi.Name != "ID") - // .ToList() - // .ForEach(pi => XBill.SetAttributeValue(pi.Name, pi.GetValue(b))); - // } - - // return true; - //} - - public bool Delete(Bill bill) - { - var xBill = this.xmlDB.Root.Element(NS_BILLS) - .Elements() - .FirstOrDefault(elem => elem.Attribute("ID").Value == bill.ID.ToString()); - - if (xBill != null) - xBill.Remove(); - - return true; - } - - //public bool Delete(IEnumerable bills) - //{ - // foreach (Bill b in bills) - // { - // this.xmlDB.Root.Element(NS_BILLS) - // .Elements() - // .Single(elem => elem.Attribute("ID").Value == b.ID.ToString()) - // .Remove(); - // } - - // return true; - //} - - private XElement GetXBill(Bill bill) - { - return - new XElement(ITEM_BILL, - typeof(Bill).GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Where(pi => pi.GetValue(bill) != null) - .Select(pi => new XAttribute(pi.Name, pi.GetValue(bill)))); - } - - #endregion - - #region suppliers provider - - public uint GetLastSupplierID() - { - return (uint)this.xmlDB.Root.Element(NS_SUPPLIERS).Attribute(ATT_LAST_ID); - } - - public IEnumerable GetAllSuppliers() - { - var q = - this.xmlDB.Root - .Element(NS_SUPPLIERS) - .Elements(ITEM_SUPPLIER) - .Select( - i => - { - return - new Supplier( - (uint)i.Attribute("ID"), - (string)i.Attribute("Name"), - (string)i.Attribute("Street"), - (string)i.Attribute("Number"), - (string)i.Attribute("City"), - (string)i.Attribute("Zip"), - (string)i.Attribute("Province"), - (string)i.Attribute("Country"), - (string)i.Attribute("eMail"), - (string)i.Attribute("Website"), - (string)i.Attribute("Phone"), - (string)i.Attribute("Fax"), - (string)i.Attribute("Notes"), - (string)i.Attribute("AgentName"), - (string)i.Attribute("AgentSurname"), - (string)i.Attribute("AgentPhone")); - }); - - return q; - - //var query = from XSupplier in this.xmlDB.Root.Element(NS_SUPPLIERS) - // .Elements(ITEM_SUPPLIER) - // select new - // Supplier( - // (uint)XSupplier.Attribute("ID"), - // (string)XSupplier.Attribute("Name"), - // (string)XSupplier.Attribute("Street"), - // (string)XSupplier.Attribute("Number"), - // (string)XSupplier.Attribute("City"), - // (string)XSupplier.Attribute("Zip"), - // (string)XSupplier.Attribute("Province"), - // (string)XSupplier.Attribute("Country"), - // (string)XSupplier.Attribute("eMail"), - // (string)XSupplier.Attribute("Website"), - // (string)XSupplier.Attribute("Phone"), - // (string)XSupplier.Attribute("Fax"), - // (string)XSupplier.Attribute("Notes"), - // (string)XSupplier.Attribute("AgentName"), - // (string)XSupplier.Attribute("AgentSurname"), - // (string)XSupplier.Attribute("AgentPhone") - // ); - - //return query; - } - - public bool Add(Supplier supplier) - { - this.xmlDB.Root.Element(NS_SUPPLIERS).Add(this.GetXSupplier(supplier)); - - this.IncreaseLastIDValue(NS_SUPPLIERS); - - return true; - } - - public bool Edit(Supplier supplier) - { - var XSupplier = this.xmlDB.Root.Element(NS_SUPPLIERS) - .Elements(ITEM_SUPPLIER) - .FirstOrDefault(elem => elem.Attribute("ID").Value == supplier.ID.ToString()); - - if (XSupplier == null) - return false; - - XSupplier.ReplaceWith(this.GetXSupplier(supplier)); - - return true; - } - - //public bool Edit(IEnumerable suppliers) - //{ - // throw new NotImplementedException(); - //} - - public bool Delete(Supplier supplier) - { - var xSupplier = this.xmlDB.Root.Element(NS_SUPPLIERS) - .Elements() - .FirstOrDefault(elem => elem.Attribute("ID").Value == supplier.ID.ToString()); - - if (xSupplier != null) - xSupplier.Remove(); - - //this.DecreaseSuppliersCount(); - - return true; - } - - //public bool Delete(IEnumerable suppliers) - //{ - // throw new NotImplementedException(); - //} - - private XElement GetXSupplier(Supplier supplier) - { - return - new XElement(ITEM_SUPPLIER, - typeof(Supplier) - .GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Where(pi => pi.GetValue(supplier) != null) - .Select(pi => new XAttribute(pi.Name, pi.GetValue(supplier)))); - } - - #endregion - - //#region tags provider - - //public uint GetLastTagID() - //{ - // return (uint)this.xmlDB.Root.Element(NS_TAGS).Attribute(ATT_LAST_ID); - //} - - //public IEnumerable GetAll() - //{ - // var query = from XTAG in this.xmlDB.Root.Element(NS_TAGS) - // .Elements(ITEM_TAG) - // select new - // Tag( - // (uint)XTAG.Attribute("ID"), - // (string)XTAG.Attribute("Name"), - // (string)XTAG.Attribute("Color")); - - // return query; - //} - - //public bool Add(Tag tag) - //{ - // this.xmlDB.Root.Element(NS_TAGS).Add( - // new XElement(ITEM_TAG, - // typeof(Tag) - // .GetProperties(BindingFlags.Public | BindingFlags.Instance) - // .Where(pi => pi.GetValue(tag) != null) - // .Select(pi => new XAttribute(pi.Name, pi.GetValue(tag))))); - - // this.IncreaseLastIDValue(NS_TAGS); - - // return true; - //} - - //public bool Edit(Tag tag) - //{ - // var XTAG = this.xmlDB.Root.Element(NS_TAGS) - // .Elements(ITEM_TAG) - // .Single(elem => elem.Attribute("ID").Value == tag.ID.ToString()); - - // typeof(Bill).GetProperties(BindingFlags.Public | BindingFlags.Instance) - // .Where(pi => pi.Name != "ID") - // .ToList() - // .ForEach(pi => XTAG.SetAttributeValue(pi.Name, pi.GetValue(tag))); - - // return true; - //} - - ////public bool Edit(IEnumerable tags) - ////{ - //// foreach (Tag b in tags) - //// { - //// var XTag = this.xmlDB.Root.Element(NS_TAGS) - //// .Elements(ITEM_TAG) - //// .Single(elem => elem.Attribute("ID").Value == b.ID.ToString()); - - //// typeof(Bill) - //// .GetProperties(BindingFlags.Public | BindingFlags.Instance) - //// .Where(pi => pi.Name != "ID") - //// .ToList() - //// .ForEach(pi => XTag.SetAttributeValue(pi.Name, pi.GetValue(b))); - //// } - - //// return true; - ////} - - //public bool Delete(Tag tag) // URGENT: add fail logic - //{ - // this.xmlDB.Root.Element(NS_TAGS) - // .Elements() - // .Single(elem => elem.Attribute("ID").Value == tag.ID.ToString()) - // .Remove(); - - // return true; - //} - - ////public bool Delete(IEnumerable tags) - ////{ - //// foreach (Tag b in tags) - //// { - //// this.xmlDB.Root.Element(NS_TAGS) - //// .Elements() - //// .Single(elem => elem.Attribute("ID").Value == b.ID.ToString()) - //// .Remove(); - //// } - - //// return true; - ////} - - //#endregion - - /*#region agents provider - - public uint GetLastAgentID() - { - return (uint)this.xmlDB.Root.Element(ITEM_AGENT).Attribute(ATT_LAST_ID); - } - - public IEnumerable GetAllAgents() - { - var query = from XAgent in this.xmlDB.Root.Element(NS_AGENTS).Elements(ITEM_AGENT) - select new - Agent( - (uint)XAgent.Attribute("ID"), - (string)XAgent.Attribute("Name"), - (string)XAgent.Attribute("Surname"), - (string)XAgent.Attribute("FirstPhoneNumber"), - (string)XAgent.Attribute("SecondPhoneNumber") - ); - - return query; - } - - public Agent GetAgentByID(uint agentID) - { - var agent = from XAgent in this.xmlDB.Root.Element(NS_AGENTS).Elements(ITEM_AGENT) - where XAgent.Attribute("ID").Value == agentID.ToString() - select new - Agent( - (uint)XAgent.Attribute("ID"), - (string)XAgent.Attribute("Name"), - (string)XAgent.Attribute("Surname"), - (string)XAgent.Attribute("FirstPhoneNumber"), - (string)XAgent.Attribute("SecondPhoneNumber") - ); - - return agent.FirstOrDefault(); - } - - public bool Add(Agent agent) - { - this.xmlDB.Root.Element(NS_AGENTS).Add(new XElement(ITEM_AGENT, typeof(Agent).GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Select(pi => - { - if (pi.GetValue(agent, null) != null) - return new XAttribute(pi.Name, pi.GetValue(agent, null)); - else - return null; - }))); - - this.IncreaseLastIDValue(NS_AGENTS); - - return true; - } - - public bool Edit(Agent agent) - { - var XAgent = this.xmlDB.Root.Element(NS_AGENTS).Elements(ITEM_AGENT) - .Single(elem => elem.Attribute("ID").Value == agent.ID.ToString()); - - typeof(Agent).GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Where(pi => pi.Name != "ID") - .ToList() - .ForEach(pi => - { - XAgent.SetAttributeValue(pi.Name, pi.GetValue(agent, null)); - }); - - return true; - } - - //public bool Edit(IEnumerable agents) - //{ - // throw new NotImplementedException(); - //} - - public bool Delete(Agent agent) - { - this.xmlDB.Root.Element(NS_AGENTS) - .Elements() - .Single(elem => elem.Attribute("ID").Value == agent.ID.ToString()) - .Remove(); - - return true; - } - - //public bool Delete(IEnumerable agents) - //{ - // throw new NotImplementedException(); - //} - -#endregion*/ - - #region support methods - - void IncreaseLastIDValue(string ns) - { - this.xmlDB.Root.Element(ns).Attribute(ATT_LAST_ID) - .SetValue(uint.Parse(this.xmlDB.Root.Element(ns).Attribute(ATT_LAST_ID).Value) + 1); - } - - private void EnsureDbFileExists() - { - if (File.Exists(this.dbPath)) return; - - var newXDoc = new XDocument(); - - newXDoc.Declaration = new XDeclaration("1.0", "utf-8", null); - newXDoc.Add( - new XElement( - NS_DATABASE_ROOT, - new XAttribute(ATT_CREATION_DATE, DateTime.Today), - new XElement(NS_BILLS, new XAttribute(ATT_LAST_ID, START_INDEX)), - new XElement(NS_SUPPLIERS, new XAttribute(ATT_LAST_ID, START_INDEX))/*, - new XElement(NS_TAGS, new XAttribute(ATT_LAST_ID, START_INDEX))/*, - new XElement(NS_AGENTS, new XAttribute(ATT_LAST_ID, START_INDEX))*/)); - - Directory.CreateDirectory(Path.GetDirectoryName(this.dbPath)); - - newXDoc.Save(this.dbPath); - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Services/Feedback/EMailFeedbackService.cs b/BillsManager.Services/Feedback/EMailFeedbackService.cs deleted file mode 100644 index 3f06535..0000000 --- a/BillsManager.Services/Feedback/EMailFeedbackService.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System.Net.Mail; -using System.Text.RegularExpressions; - -namespace BillsManager.Services.Feedback -{ - public class EMailFeedbackService : IFeedbackService - { - #region fields - - private readonly string toEmailAddress; - - #endregion - - #region ctor - - public EMailFeedbackService(string toEmailAddress) - { - this.toEmailAddress = toEmailAddress; - } - - #endregion - - #region IFeedbackSender Members - - public bool SendFeedback(string subject, string message) - { - if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) - { - return false; - } - - var emailRegex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); - - if (!emailRegex.IsMatch(this.toEmailAddress)) - { - return false; - } - - try - { - using (var mail = new MailMessage()) - { - mail.From = new MailAddress("feedback@billsmanager.com", "Bills Manager Feedback"); - mail.Body = message; - mail.Subject = subject; - mail.To.Add(new MailAddress(toEmailAddress)); - mail.Priority = MailPriority.High; - - using (var mailSender = new SmtpClient()) - { - mailSender.Host = "out.aliceposta.it"; - //mailSender.EnableSsl = true; - mailSender.Port = 25; - - mailSender.Send(mail); - - return true; - } - } - } - catch - { - return false; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Services/Feedback/IFeedbackService.cs b/BillsManager.Services/Feedback/IFeedbackService.cs deleted file mode 100644 index 005d777..0000000 --- a/BillsManager.Services/Feedback/IFeedbackService.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace BillsManager.Services.Feedback -{ - public interface IFeedbackService - { - // TODO: add not sent explanation support, or CanSend - - bool SendFeedback(string subject, string message); - } -} \ No newline at end of file diff --git a/BillsManager.Services/LinqToDB.Templates/CopyMe.SQLite.tt.txt b/BillsManager.Services/LinqToDB.Templates/CopyMe.SQLite.tt.txt deleted file mode 100644 index d0d8f08..0000000 --- a/BillsManager.Services/LinqToDB.Templates/CopyMe.SQLite.tt.txt +++ /dev/null @@ -1,45 +0,0 @@ -<#@ template language="C#" debug="True" hostSpecific="True" #> -<#@ output extension=".generated.cs" #> -<#@ include file="$(LinqToDBT4SQLiteTemplatesDirectory)LinqToDB.SQLite.Tools.ttinclude" #> -<#@ include file="$(LinqToDBT4SQLiteTemplatesDirectory)PluralizationService.ttinclude" #> -<# //@ include file="$(ProjectDir)LinqToDB.Templates\LinqToDB.SQLite.Tools.ttinclude" #> -<# //@ include file="$(ProjectDir)LinqToDB.Templates\PluralizationService.ttinclude" #> -<# - /* - 1. Create new *.tt file (e.g. MyDatabase.tt) in a folder where you would like to generate your data model - and copy content from this file to it. For example: - - MyProject - DataModels - MyDatabase.tt - - 2. Modify the connection settings below to connect to your database. - - 3. Add connection string to the web/app.config file: - - - - - - 4. To access your database use the following code: - - using (var db = new MyDatabaseDB()) - { - var q = - from c in db.Customers - select c; - - foreach (var c in q) - Console.WriteLine(c.ContactName); - } - - 5. See more at https://github.com/linq2db/t4models - */ - - NamespaceName = "DataModels"; - - LoadSQLiteMetadata(@"C:\Data", "MyDatabase.sqlite"); -// LoadSQLiteMetadata(string connectionString); - - GenerateModel(); -#> diff --git a/BillsManager.Services/LinqToDB.Templates/DataAnnotations.ttinclude b/BillsManager.Services/LinqToDB.Templates/DataAnnotations.ttinclude deleted file mode 100644 index a98aea2..0000000 --- a/BillsManager.Services/LinqToDB.Templates/DataAnnotations.ttinclude +++ /dev/null @@ -1,65 +0,0 @@ -<# - { - var beforeGenerateModel = BeforeGenerateModel; - BeforeGenerateModel = () => - { - beforeGenerateModel(); - DataAnnotationsImpl(); - }; - } -#> -<#+ -void DataAnnotationsImpl() -{ - foreach (Class cl in GetTreeNodes(Model).OfType()) - { - foreach (var p in GetTreeNodes(cl).OfType()) - { - if (p.DisplayName != null) - { - p.Attributes.Add(new Attribute("Display", "Name=" + ToStringLiteral(p.DisplayName)) { IsSeparated = true }); - } - - if (p.IsRequired) - { - var attr = new Attribute("Required") { IsSeparated = true }; - - if (p.IsRequiredMessage != null) - attr.Parameters.Add(string.Format("ErrorMessage=" + ToStringLiteral(p.IsRequiredMessage), p.DisplayName ?? p.Name)); - - p.Attributes.Add(attr); - } - - if (p.StringLength > 0) - { - var attr = new Attribute("StringLength", p.StringLength.ToString()) { IsSeparated = true }; - - if (p.StringLengthMessage != null) - attr.Parameters.Add(string.Format("ErrorMessage=" + ToStringLiteral(p.StringLengthMessage), p.DisplayName ?? p.Name)); - - p.Attributes.Add(attr); - -// p.Attributes.Add( -// new Attribute("StringLength", -// p.StringLength.ToString(), -// "ErrorMessage=" + ToStringLiteral(string.Format( -// "The {0} must be a string with a maximum length of {1}.", -// p.DisplayName ?? "field", -// p.StringLength))) -// { -// IsSeparated = true -// }); - } - } - } -} - -partial class Property -{ - public string DisplayName; - public bool IsRequired; - public string IsRequiredMessage; - public int StringLength; - public string StringLengthMessage; -} -#> diff --git a/BillsManager.Services/LinqToDB.Templates/DataModel.ttinclude b/BillsManager.Services/LinqToDB.Templates/DataModel.ttinclude deleted file mode 100644 index b28013d..0000000 --- a/BillsManager.Services/LinqToDB.Templates/DataModel.ttinclude +++ /dev/null @@ -1,871 +0,0 @@ -<#@ assembly name="System.Data" #> -<#@ import namespace="System.Data" #> -<#@ import namespace="LinqToDB.SchemaProvider" #> -<#@ import namespace="LinqToDB.Data" #> -<#@ include file="T4Model.ttinclude" #> -<# - { - var beforeGenerateModel = BeforeGenerateModel; - BeforeGenerateModel = () => - { - GenerateTypesFromMetadata(); - beforeGenerateModel(); - }; - } -#><#+ - -string NamespaceName -{ - get { return Model.Namespace.Name; } - set { Model.Namespace.Name = value; } -} - -string DatabaseName = null; -string DataContextName = null; -string BaseDataContextClass = null; -string BaseEntityClass = null; -string OneToManyAssociationType = "IEnumerable<{0}>"; - -bool GenerateDatabaseName = false; -bool GenerateConstructors = true; -string DefaultConfiguration = null; -bool GenerateAssociations = true; -bool GenerateBackReferences = true; -bool GenerateAssociationExtensions = false; -bool ReplaceSimilarTables = true; -bool IncludeDefaultSchema = true; - -Class DataContextObject; - -bool PluralizeClassNames = false; -bool SingularizeClassNames = true; -bool PluralizeDataContextPropertyNames = true; -bool SingularizeDataContextPropertyNames = false; - -bool NormalizeNames = true; - -private Func _toValidName; -Func ToValidName -{ - get { return _toValidName ?? ToValidNameDefault; } - set { _toValidName = value; } -} - -private Func _convertToCompilabl; -Func ConvertToCompilable -{ - get { return _convertToCompilabl ?? ConvertToCompilableDefault; } - set { _convertToCompilabl = value; } -} - -private Func _getAssociationExtensionPluralName; -Func GetAssociationExtensionPluralName -{ - get { return _getAssociationExtensionPluralName ?? GetAssociationExtensionPluralNameDefault; } - set { _getAssociationExtensionPluralName = value; } -} - -private Func _getAssociationExtensionSingularName; -Func GetAssociationExtensionSinglularName -{ - get { return _getAssociationExtensionSingularName ?? GetAssociationExtensionSinglularNameDefault; } - set { _getAssociationExtensionSingularName = value; } -} - -LinqToDB.SchemaProvider.GetSchemaOptions GetSchemaOptions = - new LinqToDB.SchemaProvider.GetSchemaOptions(); - -LinqToDB.SqlProvider.ISqlBuilder SqlBuilder; - -Func LoadProviderSpecificTable = tableSchema => null; - -static Func ConvertColumnMemberType = (c) => c.MemberType; -static Func ConvertTableColumnMemberType = (t,c) => ConvertColumnMemberType(c); -static Func ConvertProcedureColumnMemberType = (t,c) => ConvertColumnMemberType(c); - -HashSet KeyWords = new HashSet -{ - "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", - "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", - "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", - "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "new", - "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", - "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "struct", "switch", - "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", - "using", "virtual", "volatile", "void", "while", "namespace", "string" -}; - -void LoadServerMetadata(DataConnection dataConnection) -{ - SqlBuilder = dataConnection.DataProvider.CreateSqlBuilder(); - - var sp = dataConnection.DataProvider.GetSchemaProvider(); - var db = sp.GetSchema(dataConnection, GetSchemaOptions); - - if (DatabaseName == null && GenerateDatabaseName) - DatabaseName = db.Database; - - if (DataContextName == null) - DataContextObject.Name = DataContextName = ToValidName(db.Database, true) + "DB"; - - DataContextObject.Comment.Add("/ "); - DataContextObject.Comment.Add("/ Database : " + db.Database); - DataContextObject.Comment.Add("/ Data Source : " + db.DataSource); - DataContextObject.Comment.Add("/ Server Version : " + db.ServerVersion); - DataContextObject.Comment.Add("/ "); - - var tables = db.Tables - .Where(t => !t.IsProviderSpecific) - .Select(t => new - { - t, - key = t.IsDefaultSchema ? t.TableName : t.SchemaName + "." + t.TableName, - table = new Table - { - TableSchema = t, - IsDefaultSchema = t.IsDefaultSchema, - Schema = t.IsDefaultSchema && !IncludeDefaultSchema || string.IsNullOrEmpty(t.SchemaName)? null : t.SchemaName, - BaseClass = BaseEntityClass, - TableName = t.TableName, - TypeName = t.TypeName, - DataContextPropertyName = t.TypeName, - IsView = t.IsView, - IsProviderSpecific = false, - Description = t.Description, - Columns = t.Columns.ToDictionary( - c => c.ColumnName, - c => new Column - { - ColumnName = c.ColumnName, - ColumnType = c.ColumnType, - DataType = "DataType." + c.DataType, - Length = c.Length, - Precision = c.Precision, - Scale = c.Scale, - IsNullable = c.IsNullable, - IsIdentity = c.IsIdentity, - IsPrimaryKey = c.IsPrimaryKey, - PrimaryKeyOrder = c.PrimaryKeyOrder, - MemberName = CheckType(c.SystemType, c.MemberName), - TypeBuilder = () => ConvertTableColumnMemberType(t, c), - SkipOnInsert = c.SkipOnInsert, - SkipOnUpdate = c.SkipOnUpdate, - Description = c.Description, - }) - } - }) - .ToList(); - - if (PluralizeClassNames || SingularizeClassNames) - { - var foundNames = new HashSet(tables.Select(t => t.table.Schema + '.' + t.table.TypeName)); - - foreach (var t in tables) - { - var newName = t.table.TypeName; - newName = - PluralizeClassNames ? ToPlural (newName) : - SingularizeClassNames ? ToSingular(newName) : newName; - - if (newName != t.table.TypeName) - { - if (!foundNames.Contains(t.table.Schema + '.' + newName)) - { - t.table.TypeName = newName; - foundNames.Add(t.table.Schema + '.' + newName); - } - } - } - } - - if (PluralizeDataContextPropertyNames || SingularizeDataContextPropertyNames) - { - var foundNames = new HashSet(tables.Select(t => t.table.Schema + '.' + t.table.DataContextPropertyName)); - - foreach (var t in tables) - { - var newName = t.table.DataContextPropertyName; - newName = - PluralizeDataContextPropertyNames ? ToPlural (newName) : - SingularizeDataContextPropertyNames ? ToSingular(newName) : newName; - - if (newName != t.table.TypeName) - { - if (!foundNames.Contains(t.table.Schema + '.' + newName)) - { - t.table.DataContextPropertyName = newName; - foundNames.Add(t.table.Schema + '.' + newName); - } - } - } - } - - tables.AddRange(db.Tables - .Where(t => t.IsProviderSpecific) - .Select(t => new - { - t, - key = t.IsDefaultSchema ? t.TableName : t.SchemaName + "." + t.TableName, - table = LoadProviderSpecificTable(t) - }) - .Where(t => t.table != null)); - - foreach (var t in tables) - Tables.Add(t.key, t.table); - - var keys = - ( - from t in tables - from k in t.t.ForeignKeys - let otherTable = tables.Where(tbl => tbl.t == k.OtherTable).Select(tbl => tbl.table).Single() - select new - { - k, - k.KeyName, - t, - key = new ForeignKey - { - KeyName = k.KeyName, - OtherTable = otherTable, - OtherColumns = k.OtherColumns.Select(c => otherTable.Columns[c.ColumnName]).ToList(), - ThisColumns = k.ThisColumns. Select(c => t.table. Columns[c.ColumnName]).ToList(), - CanBeNull = k.CanBeNull, - MemberName = k.MemberName, - AssociationType = (AssociationType)(int)k.AssociationType, - } - } - ).ToList(); - - foreach (var key in keys) - { - key.t.table.ForeignKeys.Add( - key.k.OtherTable.IsDefaultSchema ? key.KeyName : key.k.OtherTable.SchemaName + "." + key.KeyName, - key.key); - - if (key.k.BackReference != null) - key.key.BackReference = keys.First(k => k.k == key.k.BackReference).key; - - key.key.MemberName = key.key.MemberName.Replace(".", string.Empty); - - key.key.MemberName = key.key.AssociationType == AssociationType.OneToMany ? - ToPlural(key.key.MemberName) : ToSingular(key.key.MemberName); - } - - var procedures = db.Procedures - .Select(p => new - { - p, - key = p.IsDefaultSchema ? p.ProcedureName : p.SchemaName + "." + p.ProcedureName, - proc = new Procedure - { - Schema = (p.IsDefaultSchema && !IncludeDefaultSchema) || string.IsNullOrEmpty(p.SchemaName)? null : p.SchemaName, - ProcedureName = p.ProcedureName, - Name = ToValidName(p.MemberName, true), - IsFunction = p.IsFunction, - IsTableFunction = p.IsTableFunction, - IsAggregateFunction = p.IsAggregateFunction, - IsDefaultSchema = p.IsDefaultSchema, - IsLoaded = p.IsLoaded, - ResultTable = p.ResultTable == null ? null : - new Table - { - TypeName = ToValidName( - PluralizeClassNames ? ToPlural (p.ResultTable.TypeName) : - SingularizeClassNames ? ToSingular(p.ResultTable.TypeName) : p.ResultTable.TypeName, true), - Columns = ToDictionary( - p.ResultTable.Columns, - c => c.ColumnName, - c => new Column - { - ColumnName = c.ColumnName, - ColumnType = c.ColumnType, - IsNullable = c.IsNullable, - IsIdentity = c.IsIdentity, - IsPrimaryKey = c.IsPrimaryKey, - PrimaryKeyOrder = c.PrimaryKeyOrder, - MemberName = CheckColumnName(CheckType(c.SystemType, c.MemberName)), - TypeBuilder = () => ConvertProcedureColumnMemberType(p, c), - SkipOnInsert = c.SkipOnInsert, - SkipOnUpdate = c.SkipOnUpdate, - Description = c.Description, - }, - (c,n) => - { - c.IsDuplicateOrEmpty = true; - return "$" + (c.MemberName = "Column" + n); - }) - }, - ResultException = p.ResultException, - SimilarTables = p.SimilarTables == null ? new List() : - p.SimilarTables - .Select(t => tables.Single(tbl => tbl.t == t).table) - .ToList(), - ProcParameters = p.Parameters - .Select(pr => new Parameter - { - SchemaName = pr.SchemaName, - SchemaType = pr.SchemaType, - IsIn = pr.IsIn, - IsOut = pr.IsOut, - IsResult = pr.IsResult, - Size = pr.Size, - ParameterName = CheckParameterName(CheckType(pr.SystemType, pr.ParameterName)), - ParameterType = pr.ParameterType, - SystemType = pr.SystemType, - DataType = pr.DataType.ToString(), - }) - .ToList(), - } - }) - .ToList(); - - foreach (var p in procedures) - { - if (ReplaceSimilarTables) - if (p.proc.SimilarTables.Count() == 1 || p.proc.SimilarTables.Count(t => !t.IsView) == 1) - p.proc.ResultTable = p.proc.SimilarTables.Count() == 1 ? - p.proc.SimilarTables[0] : - p.proc.SimilarTables.First(t => !t.IsView); - - Procedures[p.key] = p.proc; - } -} - -Dictionary ToDictionary(IEnumerable source, Func keyGetter, Func objGetter, Func getKeyName) -{ - var dic = new Dictionary(); - var current = 1; - - foreach (var item in source) - { - var key = keyGetter(item); - var obj = objGetter(item); - - if (string.IsNullOrEmpty(key) || dic.ContainsKey(key)) - key = getKeyName(obj, current); - - dic.Add(key, obj); - - current++; - } - - return dic; -} - -string CheckType(Type type, string typeName) -{ - if (!Model.Usings.Contains(type.Namespace)) - Model.Usings.Add(type.Namespace); - return typeName; -} - -string CheckColumnName(string memberName) -{ - if (string.IsNullOrEmpty(memberName)) - memberName = "Empty"; - else - { - memberName = memberName - .Replace("%", "Percent") - .Replace(">", "Greater") - .Replace("<", "Lower") - .Replace("+", "Plus") - .Replace('(', '_') - .Replace(')', '_') - .Replace('-', '_') - .Replace('|', '_') - .Replace(',', '_') - .Replace('"', '_') - .Replace("'", "_") - .Replace(".", "_") - .Replace("\u00A3", "Pound"); - - if (KeyWords.Contains(memberName)) - memberName = "@" + memberName; - } - return memberName; -} - -string CheckParameterName(string parameterName) -{ - var invalidParameterNames = new List - { - "@DataType" - }; - - var result = parameterName; - while (invalidParameterNames.Contains(result)) - { - result = result + "_"; - } - return result; -} - -Action AfterLoadMetadata = () => {}; - -void LoadMetadata(DataConnection dataConnection) -{ - if (DataContextObject == null) - { - DataContextObject = new Class(DataContextName) { BaseClass = BaseDataContextClass, }; - - Model.Types.Add(DataContextObject); - } - - LoadServerMetadata(dataConnection); - - if (Tables.Values.SelectMany(_ => _.ForeignKeys.Values).Any(_ => _.AssociationType == AssociationType.OneToMany)) - Model.Usings.Add("System.Collections.Generic"); - - foreach (var t in Tables.Values) - { - if (KeyWords.Contains(t.TypeName)) - t.TypeName = "@" + t.TypeName; - - if (KeyWords.Contains(t.DataContextPropertyName)) - t.DataContextPropertyName = "@" + t.DataContextPropertyName; - - t.TypeName = ConvertToCompilable(t.TypeName, true); - t.DataContextPropertyName = ConvertToCompilable(t.DataContextPropertyName, true); - - foreach (var col in t.Columns.Values) - { - if (KeyWords.Contains(col.MemberName)) - col.MemberName = "@" + col.MemberName; - - col.MemberName = ConvertToCompilable(col.MemberName, true); - - if (col.MemberName == t.TypeName) - col.MemberName += "_Column"; - } - - foreach (var fk in t.ForeignKeys.Values) - { - if (KeyWords.Contains(fk.MemberName)) - fk.MemberName = "@" + fk.MemberName; - - fk.MemberName = ConvertToCompilable(fk.MemberName, true); - - if (fk.MemberName == t.TypeName) - fk.MemberName += "_FK"; - } - } - - foreach (var t in Tables.Values) - { - var hasDuplicates = t.Columns.Values - .Select(c => c.MemberName) - .Concat(t.ForeignKeys.Values.Select(f => f.MemberName)) - .ToLookup(n => n) - .Any(g => g.Count() > 1); - - if (hasDuplicates) - { - foreach (var fk in t.ForeignKeys.Values) - { - var mayDuplicate = t.Columns.Values - .Select(c => c.MemberName) - .Concat(t.ForeignKeys.Values.Where(f => f != fk).Select(f => f.MemberName)); - - fk.MemberName = SuggestNoDuplicate(mayDuplicate, fk.MemberName, "FK"); - } - - foreach (var col in t.Columns.Values) - { - var mayDuplicate = t.Columns.Values - .Where(c => c != col) - .Select(c => c.MemberName) - .Concat(t.ForeignKeys.Values.Select(fk => fk.MemberName)); - - col.MemberName = SuggestNoDuplicate(mayDuplicate, col.MemberName, null); - } - } - } - - foreach (var proc in Procedures.Values) - { - proc.Name = ConvertToCompilable(proc.Name, false); - - if (KeyWords.Contains(proc.Name)) - proc.Name = "@" + proc.Name; - - foreach (var param in proc.ProcParameters) - { - if (KeyWords.Contains(param.ParameterName)) - param.ParameterName = ConvertToCompilable("@" + param.ParameterName, true); - } - } - - AfterLoadMetadata(); -} - -string SuggestNoDuplicate(IEnumerable currentNames, string newName, string prefix) -{ - var names = new HashSet(currentNames); - var result = newName; - if (names.Contains(result)) - { - if (!string.IsNullOrEmpty(prefix)) - result = prefix + result; - if (names.Contains(result)) - { - var counter = 0; - var number = string.Concat(result.Reverse().Take(6).TakeWhile(c => Char.IsDigit(c)).Reverse()); - if (!string.IsNullOrEmpty(number)) - { - if (int.TryParse(number, out counter)) - { - result = result.Remove(result.Length - number.Length); - } - } - - do - { - ++counter; - if (!names.Contains(result + counter)) - { - result = result + counter; - break; - } - } - while(true); - } - } - - return result; -} - -string ConvertToCompilableDefault(string name, bool mayRemoveUnderscore) -{ - var query = - from c in name - select char.IsLetterOrDigit(c) || c == '@' ? c : '_'; - - return ToValidName(new string(query.ToArray()), mayRemoveUnderscore); -} - -Table GetTable(string name) -{ - Table tbl; - - if (Tables.TryGetValue(name, out tbl)) - return tbl; - - WriteLine("#error Table '" + name + "' not found."); - WriteLine("/*"); - WriteLine("\tExisting tables:"); - WriteLine(""); - - foreach (var key in Tables.Keys) - WriteLine("\t" + key); - - WriteLine(" */"); - - throw new ArgumentException("Table '" + name + "' not found."); -} - -Procedure GetProcedure(string name) -{ - Procedure proc; - - if (Procedures.TryGetValue(name, out proc)) - return proc; - - WriteLine("#error Procedure '" + name + "' not found."); - WriteLine(""); - WriteLine("/*"); - WriteLine("\tExisting procedures:"); - WriteLine(""); - - foreach (var key in Procedures.Keys) - WriteLine("\t" + key); - - WriteLine(" */"); - - throw new ArgumentException("Procedure '" + name + "' not found."); -} - -Column GetColumn(string tableName, string columnName) -{ - var tbl = GetTable(tableName); - - Column col; - - if (tbl.Columns.TryGetValue(columnName, out col)) - return col; - - WriteLine("#error Column '" + tableName + "'.'" + columnName + "' not found."); - WriteLine(""); - WriteLine("/*"); - WriteLine("\tExisting '" + tableName + "'columns:"); - WriteLine(""); - - foreach (var key in tbl.Columns.Keys) - WriteLine("\t" + key); - - WriteLine(" */"); - - throw new ArgumentException("Column '" + tableName + "'.'" + columnName + "' not found."); -} - -ForeignKey GetFK(string tableName, string fkName) -{ - return GetForeignKey(tableName, fkName); -} - -ForeignKey GetForeignKey(string tableName, string fkName) -{ - var tbl = GetTable(tableName); - - ForeignKey col; - - if (tbl.ForeignKeys.TryGetValue(fkName, out col)) - return col; - - WriteLine("#error FK '" + tableName + "'.'" + fkName + "' not found."); - WriteLine(""); - WriteLine("/*"); - WriteLine("\tExisting '" + tableName + "'FKs:"); - WriteLine(""); - - foreach (var key in tbl.ForeignKeys.Keys) - WriteLine("\t" + key); - - WriteLine(" */"); - - throw new ArgumentException("FK '" + tableName + "'.'" + fkName + "' not found."); -} - - -public TableContext SetTable(string tableName, - string TypeName = null, - string DataContextPropertyName = null) -{ - var ctx = new TableContext { Transformation = this, TableName = tableName }; - - if (TypeName != null || DataContextPropertyName != null) - { - var t = GetTable(tableName); - - if (TypeName != null) t.TypeName = TypeName; - if (DataContextPropertyName != null) t.DataContextPropertyName = DataContextPropertyName; - } - - return ctx; -} - -public class TableContext -{ - public GeneratedTextTransformation Transformation; - public string TableName; - - public TableContext Column(string columnName, - string MemberName = null, - string Type = null, - bool? IsNullable = null, - string Conditional = null) - { - var c = Transformation.GetColumn(TableName, columnName); - - if (MemberName != null) c.MemberName = MemberName; - if (Type != null) c.TypeBuilder = () => Type; - if (IsNullable != null) c.IsNullable = IsNullable.Value; - if (Conditional != null) c.Conditional = Conditional; - - return this; - } - - public TableContext FK(string fkName, - string MemberName = null, - AssociationType? AssociationType = null, - bool? CanBeNull = null) - { - var c = Transformation.GetFK(TableName, fkName); - - if (MemberName != null) c.MemberName = MemberName; - if (AssociationType != null) c.AssociationType = AssociationType.Value; - if (CanBeNull != null) c.CanBeNull = CanBeNull.Value; - - return this; - } -} - - -Dictionary Tables = new Dictionary (); -Dictionary Procedures = new Dictionary(); - -public partial class Table : Class -{ - public TableSchema TableSchema { get; set; } - public string Schema { get; set; } - public string TableName { get; set; } - public string DataContextPropertyName { get; set; } - public MemberBase DataContextProperty { get; set; } - public bool IsView { get; set; } - public bool IsProviderSpecific { get; set; } - public bool IsDefaultSchema { get; set; } - public string Description { get; set; } - public string AliasPropertyName { get; set; } - public string AliasTypeName { get; set; } - public string TypePrefix { get; set; } - - public string TypeName - { - get { return Name; } - set { Name = value; } - } - - public Dictionary Columns; - public Dictionary ForeignKeys = new Dictionary(); -} - -public partial class Column : Property -{ - public string ColumnName; // Column name in database - public bool IsNullable; - public bool IsIdentity; - public string ColumnType; // Type of the column in database - public string DataType; - public long? Length; - public int? Precision; - public int? Scale; - public DbType DbType; - public string Description; - public bool IsPrimaryKey; - public int PrimaryKeyOrder; - public bool SkipOnUpdate; - public bool SkipOnInsert; - public bool IsDuplicateOrEmpty; - public bool IsDiscriminator; - public string AliasName; - - public string MemberName - { - get { return Name; } - set { Name = value; } - } -} - -public enum AssociationType -{ - Auto, - OneToOne, - OneToMany, - ManyToOne, -} - -public partial class ForeignKey : Property -{ - public string KeyName; - public Table OtherTable; - public List ThisColumns; - public List OtherColumns; - public bool CanBeNull; - public ForeignKey BackReference; - - public string MemberName - { - get { return Name; } - set { Name = value; } - } - - private AssociationType _associationType = AssociationType.Auto; - public AssociationType AssociationType - { - get { return _associationType; } - set - { - _associationType = value; - - if (BackReference != null) - { - switch (value) - { - case AssociationType.Auto : BackReference.AssociationType = AssociationType.Auto; break; - case AssociationType.OneToOne : BackReference.AssociationType = AssociationType.OneToOne; break; - case AssociationType.OneToMany : BackReference.AssociationType = AssociationType.ManyToOne; break; - case AssociationType.ManyToOne : BackReference.AssociationType = AssociationType.OneToMany; break; - } - } - } - } -} - -public partial class Procedure : Method -{ - public string Schema { get; set; } - public string ProcedureName { get; set; } - public bool IsFunction { get; set; } - public bool IsTableFunction { get; set; } - public bool IsAggregateFunction { get; set; } - public bool IsDefaultSchema { get; set; } - public bool IsLoaded { get; set; } - - public Table ResultTable { get; set; } - public Exception ResultException { get; set; } - public List
SimilarTables { get; set; } - public List ProcParameters { get; set; } -} - -public class Parameter -{ - public string SchemaName { get; set; } - public string SchemaType { get; set; } - public bool IsIn { get; set; } - public bool IsOut { get; set; } - public bool IsResult { get; set; } - public long? Size { get; set; } - - public string ParameterName { get; set; } - public string ParameterType { get; set; } - public Type SystemType { get; set; } - public string DataType { get; set; } -} - -private int _counter = 0; - -string ToValidNameDefault(string name, bool mayRemoveUnderscore) -{ - if (NormalizeNames && mayRemoveUnderscore && name.Contains("_")) - { - name = SplitAndJoin(name, "", '_'); - } - - if (name.Contains(".")) - { - name = SplitAndJoin(name, "", '.'); - } - - if (name.Length > 0 && char.IsDigit(name[0])) - name = "_" + name; - - if (string.IsNullOrEmpty(name)) - name = "_" + _counter++; - - if (NormalizeNames) - { - name = char.ToUpper(name[0]) + name.Substring(1); - } - - return name; -} - -static string SplitAndJoin(string value, string join, params char[] split) -{ - var ss = value.Split(split, StringSplitOptions.RemoveEmptyEntries) - .Select(s => char.ToUpper(s[0]) + (s.Substring(1).All(char.IsUpper) ? s.Substring(1).ToLower() : s.Substring(1))); - - return string.Join(join, ss.ToArray()); -} - -private string GetAssociationExtensionSinglularNameDefault(ForeignKey key) -{ - return ToSingular(key.Name); -} - -private string GetAssociationExtensionPluralNameDefault(ForeignKey key) -{ - return ToPlural(ToSingular(key.Name)); -} - -#> diff --git a/BillsManager.Services/LinqToDB.Templates/EditableObject.ttinclude b/BillsManager.Services/LinqToDB.Templates/EditableObject.ttinclude deleted file mode 100644 index e9506c2..0000000 --- a/BillsManager.Services/LinqToDB.Templates/EditableObject.ttinclude +++ /dev/null @@ -1,250 +0,0 @@ -<# - { - var beforeGenerateModel = BeforeGenerateModel; - BeforeGenerateModel = () => - { - EditableObjectImpl(); - beforeGenerateModel(); - }; - - SetPropertyValueAction += (obj,prop,val) => - { - if (prop == "IsEditable") - obj.IsEditable = (bool)val; - }; - } -#> -<#+ -void EditableObjectImpl() -{ - foreach (Property prop in GetTreeNodes(Model).OfType().Where(p => p.IsEditable).ToList()) - { - SetPropertyValue(prop, "IsNotifying", true); - - List parentMembers; - - MemberGroup gr = null; - - if (prop.Parent is Class) - { - var parent = (Class)prop.Parent; - parentMembers = parent.Members; - } - else - { - var parent = (MemberGroup)prop.Parent; - parentMembers = parent.Members; - - parent.IsCompact = false; - } - - var name = prop.Name.Trim(); - var type = prop.BuildType().Trim(); - - if (gr == null) - { - gr = new MemberGroup - { - Region = name + " : " + type, - Members = { prop }, - IsPropertyGroup = true, - }; - - var index = parentMembers.IndexOf(prop); - - parentMembers.RemoveAt(index); - parentMembers.Insert (index, gr); - } - - var originalField = new Field(() => type, "_original" + name) - { - AccessModifier = AccessModifier.Private, - InsertBlankLineAfter = false, - }; - - gr.Members.Insert(0, originalField); - - var currentField = new Field(() => type, " _current" + name) - { - AccessModifier = AccessModifier.Private, - InsertBlankLineAfter = false, - }; - - if (prop.InitValue != null) - currentField.InitValue = prop.InitValue; - - gr.Members.Insert(0, currentField); - - prop.Name = " " + name; - prop.TypeBuilder = () => " " + type; - prop.IsAuto = false; - - if (prop.HasGetter) prop.GetBodyBuilders.Add(() => new [] { "return " + currentField.Name.Trim() + ";" }); - if (prop.HasSetter) prop.SetBodyBuilders.Add(() => new [] { currentField.Name.Trim() + " = value;" }); - - var ac = new Method (() => "void", "Accept" + name + "Changes", null, () => new[] { string.Format("_original{0} = _current{0};", name) }); - var rc = new Method (() => "void", "Reject" + name + "Changes", null, () => new[] { string.Format("{0} = _original{0};", name) }); - var id = new Property(() => "bool", "Is" + name + "Dirty") - .InitGetter(() => new [] { string.Format(prop.IsDirtyText, "_current" + name, "_original" + name) }); - - gr.Members.Add(new MemberGroup - { - Region = "EditableObject support", - Members = { ac, rc, id }, - }); - - prop.Parent.SetTree(); - } - - foreach (Class cl in GetTreeNodes(Model).OfType()) - { - var props = GetTreeNodes(cl).OfType().Where(p => p.IsEditable).ToList(); - - if (props.Count > 0) - { - if (props.Any(p => p.IsEditable)) - { - var ctor = GetTreeNodes(cl) - .OfType() - .FirstOrDefault(m => m.Name == cl.Name && m.ParameterBuilders.Count == 0); - - if (ctor == null) - { - ctor = new Method(null, cl.Name); - cl.Members.Insert(0, ctor); - } - - ctor.BodyBuilders.Add(() => new [] { "AcceptChanges();" }); - } - - var maxLen = props.Max(p => p.Name.Trim().Length); - - var ac = new Method(() => "void", "AcceptChanges") { IsVirtual = true }; - var rc = new Method(() => "void", "RejectChanges") { IsVirtual = true }; - var id = new Property(() => "bool", "IsDirty") { IsAuto = false, HasSetter = false, IsVirtual = true }; - - ac.BodyBuilders.Add(() => new [] - { - "BeforeAcceptChanges();", - "" - }); - rc.BodyBuilders.Add(() => new [] - { - "BeforeRejectChanges();", - "" - }); - id.GetBodyBuilders.Add(() => new [] { "return" }); - - foreach (var p in props) - { - var name = p.Name.Trim(); - - ac.BodyBuilders.Add(() => new [] { string.Format("Accept{0}Changes();", name) }); - rc.BodyBuilders.Add(() => new [] { string.Format("Reject{0}Changes();", name) }); - id.GetBodyBuilders.Add(() => new [] { string.Format("\tIs{0}Dirty{1} ||", name, LenDiff(maxLen, name)) }); - } - - ac.BodyBuilders.Add(() => new[] - { - "", - "AfterAcceptChanges();" - }); - rc.BodyBuilders.Add(() => new[] - { - "", - "AfterRejectChanges();" - }); - var getBody = id.BuildGetBody().ToArray(); - getBody[getBody.Length - 1] = getBody[getBody.Length - 1].Trim(' ' , '|') + ";"; - id.GetBodyBuilders.Clear(); - id.GetBodyBuilders.Add(() => getBody); - - cl.Members.Add(new MemberGroup - { - Region = "EditableObject support", - Members = - { - new MemberGroup - { - IsCompact = true, - Members = - { - new Method(() => "void", "BeforeAcceptChanges") { AccessModifier = AccessModifier.Partial }, - new Method(() => "void", "AfterAcceptChanges") { AccessModifier = AccessModifier.Partial }, - } - }, - ac, - new MemberGroup - { - IsCompact = true, - Members = - { - new Method(() => "void", "BeforeRejectChanges") { AccessModifier = AccessModifier.Partial }, - new Method(() => "void", "AfterRejectChanges") { AccessModifier = AccessModifier.Partial }, - } - }, - rc, - id - }, - }); - - if (!cl.Interfaces.Contains("IEditableObject")) - { - if (!Model.Usings.Contains("System.ComponentModel")) - Model.Usings.Add("System.ComponentModel"); - - cl.Interfaces.Add("IEditableObject"); - - cl.Members.Add(new MemberGroup - { - Region = "IEditableObject support", - Members = - { - new MemberGroup - { - IsCompact = true, - Members = - { - new Field (() => "bool", "_isEditing") { AccessModifier = AccessModifier.Private }, - new Property(() => "bool", " IsEditing").InitGetter(() => new [] { "_isEditing" }), - } - }, - new MemberGroup - { - IsCompact = true, - Members = - { - new Method(() => "void", "BeginEdit", null, () => new[] { "AcceptChanges();", "_isEditing = true;" }) { IsVirtual = true }, - new Method(() => "void", "CancelEdit", null, () => new[] { "_isEditing = false;", "RejectChanges();", }) { IsVirtual = true }, - new Method(() => "void", "EndEdit", null, () => new[] { "_isEditing = false;", "AcceptChanges();", }) { IsVirtual = true }, - } - }, - } - }); - } - } - - cl.SetTree(); - } -} - -partial class Property -{ - public bool IsEditable; - public string IsDirtyText = "{0} != {1}"; -} - -class EditableProperty : Property -{ - public EditableProperty() - { - IsEditable = true; - } - - public EditableProperty(string type, string name) - : base(() => type, name, null, null) - { - IsEditable = true; - } -} -#> diff --git a/BillsManager.Services/LinqToDB.Templates/Humanizer.ttinclude b/BillsManager.Services/LinqToDB.Templates/Humanizer.ttinclude deleted file mode 100644 index 17be091..0000000 --- a/BillsManager.Services/LinqToDB.Templates/Humanizer.ttinclude +++ /dev/null @@ -1,15 +0,0 @@ -<# -/* -To use this extension you should: -1) Reference Humanizer NuGet package into your project -2) Include Humanizer.ttinclude -3) Reference assembly like <_#@ assembly name="$(SolutionDir)\packages\Humanizer.Core.2.2.0\lib\netstandard1.0\Humanizer.dll" #_> -*/ -#> -<#@ import namespace="Humanizer" #> -<# - NormalizeNames = true; - ToPlural = s => s.Pluralize (inputIsKnownToBeSingular: false); - ToSingular = s => s.Singularize(inputIsKnownToBePlural: false); - ToValidName = (s, r) => s.Pascalize(); -#> diff --git a/BillsManager.Services/LinqToDB.Templates/LinqToDB.SQLite.Tools.ttinclude b/BillsManager.Services/LinqToDB.Templates/LinqToDB.SQLite.Tools.ttinclude deleted file mode 100644 index 71eb281..0000000 --- a/BillsManager.Services/LinqToDB.Templates/LinqToDB.SQLite.Tools.ttinclude +++ /dev/null @@ -1,3 +0,0 @@ -<#@ assembly name="$(LinqToDBT4SQLiteToolsDirectory)System.Data.SQLite.dll" #> -<#@ include file="LinqToDB.Tools.ttinclude" #> -<#@ include file="LinqToDB.SQLite.ttinclude" #> diff --git a/BillsManager.Services/LinqToDB.Templates/LinqToDB.SQLite.ttinclude b/BillsManager.Services/LinqToDB.Templates/LinqToDB.SQLite.ttinclude deleted file mode 100644 index 1b7e65c..0000000 --- a/BillsManager.Services/LinqToDB.Templates/LinqToDB.SQLite.ttinclude +++ /dev/null @@ -1,44 +0,0 @@ -<#@ include file="LinqToDB.ttinclude" #> -<# - LinqToDB.DataProvider.SQLite.SQLiteTools.ResolveSQLite(typeof(System.Data.SQLite.SQLiteConnection).Assembly); - - { - var beforeGenerateLinqToDBModel = BeforeGenerateLinqToDBModel; - BeforeGenerateLinqToDBModel = () => - { - ConvertSQLiteMetadata(); - beforeGenerateLinqToDBModel(); - }; - } -#> -<#+ -void ConvertSQLiteMetadata() -{ - foreach (var t in Tables.Values) - foreach (var fk in t.ForeignKeys.Values) - if (fk.MemberName.Length == 0 || char.IsDigit(fk.MemberName[0])) - fk.MemberName = "FK_" + fk.MemberName; -} - -LinqToDB.Data.DataConnection GetSQLiteConnection(string connectionString) -{ - return LinqToDB.DataProvider.SQLite.SQLiteTools.CreateDataConnection(connectionString); -} - -LinqToDB.Data.DataConnection GetSQLiteConnection(string path, string database) -{ - return GetSQLiteConnection(string.Format("Data Source={0}", System.IO.Path.Combine(path, database))); -} - -void LoadSQLiteMetadata(string connectionString) -{ - using (var dataConnection = GetSQLiteConnection(connectionString)) - LoadMetadata(dataConnection); -} - -void LoadSQLiteMetadata(string path, string database) -{ - using (var dataConnection = GetSQLiteConnection(path, database)) - LoadMetadata(dataConnection); -} -#> diff --git a/BillsManager.Services/LinqToDB.Templates/LinqToDB.Tools.ttinclude b/BillsManager.Services/LinqToDB.Templates/LinqToDB.Tools.ttinclude deleted file mode 100644 index d804bb8..0000000 --- a/BillsManager.Services/LinqToDB.Templates/LinqToDB.Tools.ttinclude +++ /dev/null @@ -1 +0,0 @@ -<#@ assembly name="$(LinqToDBT4ToolsDirectory)linq2db.dll" #> diff --git a/BillsManager.Services/LinqToDB.Templates/LinqToDB.ttinclude b/BillsManager.Services/LinqToDB.Templates/LinqToDB.ttinclude deleted file mode 100644 index 0aa897a..0000000 --- a/BillsManager.Services/LinqToDB.Templates/LinqToDB.ttinclude +++ /dev/null @@ -1,1044 +0,0 @@ -<#@ assembly name="System.Data" #> -<#@ import namespace="System.Data" #> -<#@ import namespace="LinqToDB.Data" #> -<#@ import namespace="System.Text" #> -<#@ include file="DataModel.ttinclude" #> -<# - if (BaseDataContextClass == null) - BaseDataContextClass = "LinqToDB.Data.DataConnection"; -#> -<#+ -Action BeforeGenerateLinqToDBModel = () => {}; -Action AfterGenerateLinqToDBModel = () => {}; - -Func GenerateProviderSpecificTable = t => null; -Func GenerateProcedureDbType = p => false; - -bool GenerateObsoleteAttributeForAliases = false; -bool GenerateFindExtensions = true; -bool IsCompactColumns = true; -bool IsCompactColumnAliases = true; -bool GenerateDataTypes = false; -bool? GenerateLengthProperty = null; -bool? GeneratePrecisionProperty = null; -bool? GenerateScaleProperty = null; -bool GenerateDbTypes = false; -bool GenerateSchemaAsType = false; -bool GenerateViews = true; -bool GenerateProcedureResultAsList = false; -bool PrefixTableMappingWithSchema = true; -string SchemaNameSuffix = "Schema"; -string SchemaDataContextTypeName = "DataContext"; - -Dictionary SchemaNameMapping = new Dictionary(); - -Func> GetConstructors = (conf, name) => GetConstructorsImpl(conf, name); - -Func BuildColumnComparison = (c, padding1, padding2, last) => -{ - return string.Format("\tt.{0}{1} == {0}{3}{2}", c.MemberName, padding1, last ? ");" : " &&", last ? "" : padding2); -}; - -static IEnumerable GetConstructorsImpl(string defaultConfiguration, string name) -{ - if (defaultConfiguration == null) - yield return new Method((Func)null, name); - else - yield return new Method((Func)null, name) { AfterSignature = { ": base(" + ToStringLiteral(defaultConfiguration) + ")" } }; - yield return new Method((Func)null, name, new Func[] { () => "string configuration" }) { AfterSignature = { ": base(configuration)" } }; -} - -void GenerateTypesFromMetadata() -{ - BeforeGenerateLinqToDBModel(); - - Model.Usings.Add("LinqToDB"); - Model.Usings.Add("LinqToDB.Mapping"); - - if (NamespaceName == null) - NamespaceName = "DataModel"; - - string schemaName; - - var schemas = - ( - from t in Tables.Values - where GenerateSchemaAsType && t.Schema != null && !t.TableSchema.IsDefaultSchema - group t by t.Schema into gr - orderby gr.Key - let typeName = SchemaNameMapping.TryGetValue(gr.Key, out schemaName) ? schemaName : gr.Key - select new - { - Name = gr.Key, - TypeName = typeName + SchemaNameSuffix, - PropertyName = typeName, - Props = new MemberGroup { IsCompact = true }, - Aliases = new MemberGroup { IsCompact = true, Region = "Alias members" }, - TableExtensions = new MemberGroup { Region = "Table Extensions" }, - Type = new Class(typeName + SchemaNameSuffix) { IsStatic = true }, - Tables = gr.ToList(), - DataContext = new Class(SchemaDataContextTypeName), - Procedures = new MemberGroup(), - Functions = new MemberGroup(), - TableFunctions = new MemberGroup { Region = "Table Functions" }, - } - ).ToDictionary(t => t.Name); - - var procSchemas = - ( - from p in Procedures.Values - where GenerateSchemaAsType && p.Schema != null && !p.IsDefaultSchema && !schemas.ContainsKey(p.Schema) - group p by p.Schema into gr - orderby gr.Key - let typeName = SchemaNameMapping.TryGetValue(gr.Key, out schemaName) ? schemaName : gr.Key - select new - { - Name = gr.Key, - TypeName = typeName + SchemaNameSuffix, - PropertyName = typeName, - Props = new MemberGroup { IsCompact = true }, - Aliases = new MemberGroup { IsCompact = true, Region = "Alias members" }, - TableExtensions = new MemberGroup { Region = "Table Extensions" }, - Type = new Class(typeName + SchemaNameSuffix) { IsStatic = true }, - Tables = new List
(), - DataContext = new Class(SchemaDataContextTypeName), - Procedures = new MemberGroup(), - Functions = new MemberGroup(), - TableFunctions = new MemberGroup { Region = "Table Functions" }, - } - ).ToDictionary(s => s.Name); - - foreach(var schema in procSchemas) - schemas.Add(schema.Key, schema.Value); - - var defProps = new MemberGroup { IsCompact = true }; - var defAliases = new MemberGroup { IsCompact = true, Region = "Alias members" }; - var defTableExtensions = new MemberGroup { }; - - if (schemas.Count > 0) - { - var body = new List>>(); - - var schemaGroup = new MemberGroup { Region = "Schemas" }; - var schemaMembers = new MemberGroup { IsCompact = true }; - - var maxLen1 = schemas.Values.Max(schema => schema.PropertyName.Trim().Length); - var maxLen2 = schemas.Values.Max(schema => schema.TypeName. Trim().Length); - - foreach (var schema in schemas.Values) - { - schemaMembers.Members.Add(new Property(() => schema.TypeName + "." + SchemaDataContextTypeName, schema.PropertyName)); - body.Add(() => new string[] { - schema.PropertyName + LenDiff(maxLen1, schema.PropertyName) + - " = new " + schema.TypeName + "." + LenDiff(maxLen2, schema.TypeName) + - SchemaDataContextTypeName + "(this);"}); - } - - schemaGroup.Members.Add(schemaMembers); - schemaGroup.Members.Add(new Method(() => "void", "InitSchemas", new Func[0], body.ToArray())); - - DataContextObject.Members.Add(schemaGroup); - } - - if (GenerateConstructors) - { - foreach (var c in GetConstructors(DefaultConfiguration, DataContextObject.Name)) - { - if (c.BodyBuilders.Count > 0) - c.BodyBuilders.Add(() => new[] { "" }); - - if (schemas.Count > 0) - c.BodyBuilders.Add(() => new[] { "InitSchemas();" }); - - c.BodyBuilders.Add(() => new [] {"InitDataContext();", "InitMappingSchema();" }); - - DataContextObject.Members.Add(c); - } - } - - DataContextObject.Members.Add(new MemberGroup - { - IsCompact = true, - Members = - { - new Method(() => "void", "InitDataContext" ) { AccessModifier = AccessModifier.Partial }, - new Method(() => "void", "InitMappingSchema") { AccessModifier = AccessModifier.Partial } - } - }); - - if (Tables.Count > 0) - DataContextObject.Members.Insert(0, defProps); - - foreach (var schema in schemas.Values) - { - schema.Type.Members.Add(schema.DataContext); - schema.DataContext.Members.Insert(0, schema.Props); - - schema.DataContext.Members.Add(new Field (() => "IDataContext", "_dataContext") { AccessModifier = AccessModifier.Private, IsReadonly = true }); - schema.DataContext.Members.Add(new Method(() => null, schema.DataContext.Name, new Func[] { () => "IDataContext dataContext" }, () => new[] { "_dataContext = dataContext;" })); - - foreach (var t in schema.Tables) - { - t.TypePrefix = schema.TypeName + "."; - } - } - - var associationExtensions = new MemberGroup() {Region = "Associations"}; - - foreach (var t in Tables.Values.OrderBy(tbl => tbl.IsProviderSpecific).ThenBy(tbl => tbl.TypeName)) - { - Action addType = tp => Model.Types.Add(tp); - var props = defProps; - var aliases = defAliases; - var tableExtensions = defTableExtensions; - - if (t.IsView && !GenerateViews) { - continue; - } - - var schema = t.Schema != null && schemas.ContainsKey(t.Schema) ? schemas[t.Schema] : null; - - if (schema != null) - { - var si = schemas[t.Schema]; - - addType = tp => si.Type.Members.Add(tp); - props = si.Props; - aliases = si.Aliases; - tableExtensions = si.TableExtensions; - } - - MemberBase dcProp = t.IsProviderSpecific ? - GenerateProviderSpecificTable(t) : - new Property( - () => string.Format("ITable<{0}>", t.TypeName), - t.DataContextPropertyName, - () => new[] { string.Format((schema == null ? "this" : "_dataContext") + ".GetTable<{0}>()", t.TypeName) }, - null); - - if (dcProp == null) continue; - - t.DataContextProperty = dcProp; - - props.Members.Add(dcProp); - - Property aProp = null; - - if (t.AliasPropertyName != null && t.AliasPropertyName != t.DataContextPropertyName) - { - aProp = new Property( - () => string.Format("ITable<{0}>", t.TypeName), - t.AliasPropertyName, - () => new[] { t.DataContextPropertyName }, - null); - - if (GenerateObsoleteAttributeForAliases) - aProp.Attributes.Add(new Attribute("Obsolete", ToStringLiteral("Use " + t.DataContextPropertyName + " instead."))); - - aliases.Members.Add(aProp); - } - - var tableAttrs = new List(); - - if (DatabaseName != null) tableAttrs.Add("Database=" + ToStringLiteral(DatabaseName)); - if (t.Schema != null) tableAttrs.Add("Schema=" + ToStringLiteral(t.Schema)); - - tableAttrs.Add((tableAttrs.Count == 0 ? "" : "Name=") + ToStringLiteral(t.TableName)); - - if (t.IsView) - tableAttrs.Add("IsView=true"); - - t.Attributes.Add(new Attribute("Table", tableAttrs.ToArray()) { IsSeparated = true } ); - - var comments = new List(); - - if (!string.IsNullOrWhiteSpace(t.Description)) - { - comments.Add("/ "); - foreach (var line in t.Description.Split('\n')) - comments.Add("/ " + line.TrimEnd()); - comments.Add("/ "); - } - - if (comments.Count > 0) - { - t. Comment.AddRange(comments); - dcProp.Comment.AddRange(comments); - - if (aProp != null) - aProp.Comment.AddRange(comments); - } - - var columns = new MemberGroup { IsCompact = IsCompactColumns }; - var columnAliases = new MemberGroup { IsCompact = IsCompactColumnAliases, Region = "Alias members" }; - var nPKs = t.Columns.Values.Count(c => c.IsPrimaryKey); - var allNullable = t.Columns.Values.All (c => c.IsNullable || c.IsIdentity); - var nameMaxLen = t.Columns.Values.Max (c => (int?)(c.MemberName == c.ColumnName - ? 0 - : ToStringLiteral(c.ColumnName).Length)) ?? 0; - var dbTypeMaxLen = t.Columns.Values.Max (c => (int?)(c.ColumnType.Length)) ?? 0; - var dataTypeMaxLen = t.Columns.Values.Where(c => c.DataType != null).Max (c => (int?)(c.DataType.Length)) ?? 0; - var dataTypePrefix = t.Columns.Values.Any (c => c.MemberName == "DataType") ? "LinqToDB." : ""; - - foreach (var c in t.Columns.Values) - { - // Column. - // - var ca = new Attribute("Column"); - var canBeReplaced = true; - - if (c.MemberName != c.ColumnName) - { - var columnNameInAttr = ToStringLiteral(c.ColumnName); - - var space = new string(' ', nameMaxLen - columnNameInAttr.Length); - - ca.Parameters.Add(columnNameInAttr + space); - canBeReplaced = false; - } - else if (nameMaxLen > 0) - { - ca.Parameters.Add(new string(' ', nameMaxLen)); - canBeReplaced = false; - } - - if (GenerateDbTypes) - { - var space = new string(' ', dbTypeMaxLen - c.ColumnType.Length); - - ca.Parameters.Add("DbType=" + ToStringLiteral(c.ColumnType) + space); - canBeReplaced = false; - } - - if (GenerateDataTypes) - { - var space = new string(' ', dataTypeMaxLen - c.DataType.Length); - ca.Parameters.Add("DataType=" + dataTypePrefix + c.DataType + space); - canBeReplaced = false; - } - - if (GenerateDataTypes && !GenerateLengthProperty.HasValue || GenerateLengthProperty == true) - { - if (c.Length != null) ca.Parameters.Add("Length=" + (c.Length == int.MaxValue ? "int.MaxValue" : c.Length.ToString())); - canBeReplaced = false; - } - - if (GenerateDataTypes && !GeneratePrecisionProperty.HasValue || GeneratePrecisionProperty == true) - { - if (c.Precision != null) ca.Parameters.Add("Precision=" + c.Precision); - canBeReplaced = false; - } - - if (GenerateDataTypes && !GenerateScaleProperty.HasValue || GenerateScaleProperty == true) - { - if (c.Scale != null) ca.Parameters.Add("Scale=" + c.Scale); - canBeReplaced = false; - } - - if (c.SkipOnInsert && !c.IsIdentity) - { - ca.Parameters.Add("SkipOnInsert=true"); - canBeReplaced = false; - } - - if (c.SkipOnUpdate && !c.IsIdentity) - { - ca.Parameters.Add("SkipOnUpdate=true"); - canBeReplaced = false; - } - - if (c.IsDiscriminator) - { - ca.Parameters.Add("IsDiscriminator=true"); - canBeReplaced = false; - } - - c.Attributes.Add(ca); - - // PK. - // - if (c.IsPrimaryKey) - { - var pka = new Attribute("PrimaryKey"); - - if (nPKs > 1) - pka.Parameters.Add(c.PrimaryKeyOrder.ToString()); - - if (canBeReplaced) - c.Attributes[0] = pka; - else - c.Attributes.Add(pka); - - canBeReplaced = false; - } - - // Identity. - // - if (c.IsIdentity) - { - var ida = new Attribute("Identity"); - - if (canBeReplaced) - c.Attributes[0] = ida; - else - c.Attributes.Add(ida); - - canBeReplaced = false; - } - - // Nullable. - // - if (c.IsNullable) - c.Attributes.Add(new Attribute((allNullable ? "" : " ") + "Nullable")); - else if (!c.IsIdentity) - c.Attributes.Add(new Attribute("NotNull")); - - var columnComments = new List(); - - if (!string.IsNullOrWhiteSpace(c.Description)) - { - columnComments.Add("/ "); - foreach (var line in c.Description.Split('\n')) - columnComments.Add("/ " + line.TrimEnd()); - columnComments.Add("/ "); - } - - if (columnComments.Count > 0) - c.Comment.AddRange(columnComments); - - // End line comment. - // - c.EndLineComment = c.ColumnType; - - SetPropertyValue(c, "IsNotifying", true); - SetPropertyValue(c, "IsEditable", true); - - columns.Members.Add(c); - - // Alias. - // - if (c.AliasName != null && c.AliasName != c.MemberName) - { - var caProp = new Property( - c.TypeBuilder, - c.AliasName, - () => new[] { c.MemberName }, - () => new[] { c.MemberName + " = value;"}); - - caProp.Comment.AddRange(columnComments); - - if (GenerateObsoleteAttributeForAliases) - caProp.Attributes.Add(new Attribute("Obsolete", ToStringLiteral("Use " + c.MemberName + " instead."))); - - caProp.Attributes.Add(new Attribute("ColumnAlias" , ToStringLiteral(c.MemberName))); - - columnAliases.Members.Add(caProp); - } - } - - t.Members.Add(columns); - - if (columnAliases.Members.Count > 0) - t.Members.Add(columnAliases); - - if (GenerateAssociations || GenerateAssociationExtensions) - { - var keys = t.ForeignKeys.Values.ToList(); - - if (!GenerateBackReferences) - keys = keys.Where(k => k.BackReference != null).ToList(); - - if (keys.Count > 0) - { - var associations = new MemberGroup { Region = "Associations" }; - var extensionAssociations = new MemberGroup { Region = t.Name + " Associations"}; - - foreach (var key in keys.OrderBy(k => k.MemberName)) - { - key.Comment.Add("/ "); - key.Comment.Add("/ " + key.KeyName); - key.Comment.Add("/ "); - - if (key.AssociationType == AssociationType.OneToMany) - key.TypeBuilder = () => string.Format(OneToManyAssociationType, key.OtherTable.TypePrefix + key.OtherTable.TypeName); - else - key.TypeBuilder = () => key.OtherTable.TypePrefix + key.OtherTable.TypeName; - - var aa = new Attribute("Association"); - - aa.Parameters.Add("ThisKey=" + ToStringLiteral(string.Join(", ", (from c in key.ThisColumns select c.MemberName).ToArray()))); - aa.Parameters.Add("OtherKey=" + ToStringLiteral(string.Join(", ", (from c in key.OtherColumns select c.MemberName).ToArray()))); - aa.Parameters.Add("CanBeNull=" + (key.CanBeNull ? "true" : "false")); - - switch (key.AssociationType) - { - case AssociationType.OneToOne : aa.Parameters.Add("Relationship=Relationship.OneToOne"); break; - case AssociationType.OneToMany : aa.Parameters.Add("Relationship=Relationship.OneToMany"); break; - case AssociationType.ManyToOne : aa.Parameters.Add("Relationship=Relationship.ManyToOne"); break; - } - - if (key.BackReference != null) - { - if (!string.IsNullOrEmpty(key.KeyName)) - aa.Parameters.Add("KeyName=" + ToStringLiteral(key.KeyName)); - if (GenerateBackReferences && !string.IsNullOrEmpty(key.BackReference.MemberName)) - aa.Parameters.Add("BackReferenceName=" + ToStringLiteral(key.BackReference.MemberName)); - } - else - { - aa.Parameters.Add("IsBackReference=true"); - } - - key.Attributes.Add(aa); - - SetPropertyValue(key, "IsNotifying", true); - SetPropertyValue(key, "IsEditable", true); - - associations.Members.Add(key); - - var extension = new Method(() => string.Format("IQueryable<{0}>", key.OtherTable.TypePrefix + key.OtherTable.TypeName), GetAssociationExtensionPluralName(key)); - extension.Name = GetAssociationExtensionPluralName(key); - - extension.ParameterBuilders.Add(() => string.Format("this {0}{1} obj", t.TypePrefix, t.TypeName)); - - extension.ParameterBuilders.Add(() => "IDataContext db"); - extension.Attributes.Add(aa); - extension.IsStatic = true; - - extension.Comment.Add("/ "); - extension.Comment.Add("/ " + key.KeyName); - extension.Comment.Add("/ "); - - Func builder = () => - { - var sb = new StringBuilder(); - sb - .Append("return db.GetTable<") - .Append(key.OtherTable.TypePrefix + key.OtherTable.TypeName) - .Append(">().Where(c => "); - for (var i = 0; i < key.OtherColumns.Count; i++) - { - sb.Append("c.") - .Append(key.OtherColumns[i].MemberName) - .Append(" == obj.") - .Append(key.ThisColumns[i].MemberName) - .Append(" && "); - } - sb.Length -= 4; - sb.Append(");"); - - return sb.ToString(); - }; - - extension.BodyBuilders.Add(() => new[] { builder() }); - - extensionAssociations.Members.Add(extension); - - if (key.AssociationType != AssociationType.OneToMany) - { - var single = new Method(() => t.TypePrefix + t.TypeName, GetAssociationExtensionSinglularName(key)); - - single.ParameterBuilders.Add(() => string.Format("this {0}{1} obj", key.OtherTable.TypePrefix, key.OtherTable.TypeName)); - - single.ParameterBuilders.Add(() => "IDataContext db"); - single.Attributes.Add(aa); - single.IsStatic = true; - - single.Comment.Add("/ "); - single.Comment.Add("/ " + key.KeyName); - single.Comment.Add("/ "); - - Func builderSingle = () => - { - var sb = new StringBuilder(); - sb - .Append("return db.GetTable<") - .Append(t.TypePrefix + t.TypeName) - .Append(">().Where(c => "); - for (var i = 0; i < key.OtherColumns.Count; i++) - { - sb.Append("c.") - .Append(key.ThisColumns[i].MemberName) - .Append(" == obj.") - .Append(key.OtherColumns[i].MemberName) - .Append(" && "); - } - sb.Length -= 4; - sb.Append(");"); - - return sb.ToString(); - }; - - single.BodyBuilders.Add(() => - { - var sb = new StringBuilder(builderSingle()); - sb.Length -= 1; - - if (key.CanBeNull) - sb.Append(".FirstOrDefault();"); - else - sb.Append(".First();"); - - return new [] { sb.ToString() }; - }); - - extensionAssociations.Members.Add(single); - } - } - - if (GenerateAssociations) - t.Members.Add(associations); - if (GenerateAssociationExtensions) - associationExtensions.Members.Add(extensionAssociations); - } - } - - if (GenerateFindExtensions && nPKs > 0) - { - var PKs = t.Columns.Values.Where(c => c.IsPrimaryKey).ToList(); - var maxNameLen1 = PKs.Max(c => (int?)c.MemberName.Length) ?? 0; - var maxNameLen2 = PKs.Take(nPKs - 1).Max(c => (int?)c.MemberName.Length) ?? 0; - - tableExtensions.Members.Add( - new Method( - () => t.TypeName, - "Find", - new Func[] { () => (string.Format("this ITable<{0}> table", t.TypeName)) } - .Union(PKs.Select(c => (Func)(() => c.BuildType() + " " + c.MemberName))), - () => new[] { "return table.FirstOrDefault(t =>" } - .Union(PKs.SelectMany((c,i) => - { - var ss = new List(); - - if (c.Conditional != null) - ss.Add("#if " + c.Conditional); - - ss.Add(BuildColumnComparison(c, LenDiff(maxNameLen1, c.MemberName), LenDiff(maxNameLen2, c.MemberName), i == nPKs - 1)); - - if (c.Conditional != null) - { - if (ss[1].EndsWith(");")) - { - ss[1] = ss[1].Substring(0, ss[1].Length - 2); - ss.Add("#endif"); - ss.Add("\t\t);"); - } - else - { - ss.Add("#endif"); - } - } - - return ss; - }))) - { - IsStatic = true - }); - } - - addType(t); - - if (!string.IsNullOrWhiteSpace(t.AliasTypeName)) - { - var aClass = new Class(t.AliasTypeName) - { - BaseClass = t.TypeName - }; - - if (comments.Count > 0) - aClass.Comment.AddRange(comments); - - if (GenerateObsoleteAttributeForAliases) - aClass.Attributes.Add(new Attribute("Obsolete", ToStringLiteral("Use " + t.TypeName + " instead."))); - - Model.Types.Add(aClass); - } - } - - if (associationExtensions.Members.Count > 0) - defTableExtensions.Members.Add(associationExtensions); - - if (defAliases.Members.Count > 0) - DataContextObject.Members.Add(defAliases); - - foreach (var schema in schemas.Values) - if (schema.Aliases.Members.Count > 0) - schema.Type.Members.Add(defAliases); - - if (Procedures.Count > 0) - { - Model.Usings.Add("System.Collections.Generic"); - Model.Usings.Add("System.Data"); - Model.Usings.Add("LinqToDB.Data"); - Model.Usings.Add("LinqToDB.Common"); - - if (Procedures.Values.Any(p => p.IsTableFunction)) - Model.Usings.Add("System.Reflection"); - - if (Procedures.Values.Any(p => p.IsAggregateFunction)) - Model.Usings.Add("System.Linq.Expressions"); - - var procs = new MemberGroup(); - var funcs = new MemberGroup(); - var tabfs = new MemberGroup { Region = "Table Functions" }; - - foreach (var p in Procedures.Values.Where( - proc => proc.IsLoaded || proc.IsFunction && !proc.IsTableFunction || - proc.IsTableFunction && proc.ResultException != null - )) - { - Action addProcs = tp => procs.Members.Add(tp); - Action addFuncs = tp => funcs.Members.Add(tp); - Action addTabfs = tp => tabfs.Members.Add(tp); - - var thisDataContext = "this"; - - var schema = p.Schema != null && schemas.ContainsKey(p.Schema) ? schemas[p.Schema] : null; - - if (schema != null) - { - var si = schemas[p.Schema]; - - addProcs = tp => si.Procedures. Members.Add(tp); - addFuncs = tp => si.Functions. Members.Add(tp); - addTabfs = tp => si.TableFunctions.Members.Add(tp); - thisDataContext = "_dataContext"; - } - - var proc = new MemberGroup { Region = p.Name }; - - if (!p.IsFunction) addProcs(proc); - else if (p.IsTableFunction) addTabfs(proc); - else addFuncs(proc); - - if (p.ResultException != null) - { - proc.Errors.Add(p.ResultException.Message); - continue; - } - - proc.Members.Add(p); - - if (p.IsTableFunction) - { - var tableAttrs = new List(); - - if (DatabaseName != null) tableAttrs.Add("Database=" + ToStringLiteral(DatabaseName)); - if (p.Schema != null) tableAttrs.Add("Schema=" + ToStringLiteral(p.Schema)); - - tableAttrs.Add("Name=" + ToStringLiteral(p.ProcedureName)); - - p.Attributes.Add(new Attribute("Sql.TableFunction", tableAttrs.ToArray())); - - p.TypeBuilder = () => "ITable<" + p.ResultTable.TypeName + ">"; - } - else if (p.IsAggregateFunction) - { - p.IsStatic = true; - p.TypeBuilder = () => p.ProcParameters.Single(pr => pr.IsResult).ParameterType; - var paramCount = p.ProcParameters.Count(pr => !pr.IsResult); - p.Attributes.Add(new Attribute("Sql.Function", "Name=" + ToStringLiteral((p.Schema != null ? p.Schema + "." : null) + p.ProcedureName), "ServerSideOnly=true, IsAggregate = true" + (paramCount > 0 ? (", ArgIndices = new[] { " + string.Join(", ", Enumerable.Range(0, p.ProcParameters.Count(pr => !pr.IsResult))) + " }") : null))); - - if (p.IsDefaultSchema || !GenerateSchemaAsType) - p.ParameterBuilders.Add(() => "this IEnumerable src"); - else // otherwise function will be generated in nested class, which doesn't support extension methods - p.ParameterBuilders.Add(() => "IEnumerable src"); - - foreach (var inp in p.ProcParameters.Where(pr => !pr.IsResult)) - p.ParameterBuilders.Add(() => $"Expression> " + inp.ParameterName); - - p.Name += ""; - } - else if (p.IsFunction) - { - p.IsStatic = true; - p.TypeBuilder = () => p.ProcParameters.Single(pr => pr.IsResult).ParameterType; - p.Attributes.Add(new Attribute("Sql.Function", "Name=" + ToStringLiteral((p.Schema != null ? p.Schema + "." : null) + p.ProcedureName), "ServerSideOnly=true")); - } - else - { - p.IsStatic = true; - p.TypeBuilder = () => p.ResultTable == null - ? "int" - : GenerateProcedureResultAsList - ? "List<" + p.ResultTable.TypeName + ">" - : "IEnumerable<" + p.ResultTable.TypeName + ">"; - - if (p.IsDefaultSchema || !GenerateSchemaAsType) - p.ParameterBuilders.Add(() => "this DataConnection dataConnection"); - else - p.ParameterBuilders.Add(() => "DataConnection dataConnection"); - } - - if (!p.IsAggregateFunction) - foreach (var pr in p.ProcParameters.Where(par => !par.IsResult)) - p.ParameterBuilders.Add(() => string.Format("{0}{1} {2}", - pr.IsOut ? pr.IsIn ? "ref " : "out " : "", pr.ParameterType, pr.ParameterName)); - - if (p.IsTableFunction) - { - p.BodyBuilders.Add(() => new[] - { - string.Format("return " + thisDataContext + ".GetTable<{0}>(this, (MethodInfo)MethodBase.GetCurrentMethod()", p.ResultTable.TypeName) - + (p.ProcParameters.Count == 0 ? ");" : ",") - }); - - for (var idx = 0; idx < p.ProcParameters.Count; idx++) - { - var i = idx; - p.BodyBuilders.Add(() => new []{ "\t" + p.ProcParameters[i].ParameterName + (i + 1 == p.ProcParameters.Count ? ");" : ",") }); - } - } - else if (p.IsFunction) - { - p.BodyBuilders.Add(() => new [] { "throw new InvalidOperationException();" }); - } - else - { - var spName = - SqlBuilder.BuildTableName( - new System.Text.StringBuilder(), - (string)SqlBuilder.Convert(DatabaseName, LinqToDB.SqlProvider.ConvertType.NameToDatabase), - (string)SqlBuilder.Convert(p.Schema, LinqToDB.SqlProvider.ConvertType.NameToSchema), - (string)SqlBuilder.Convert(p.ProcedureName, LinqToDB.SqlProvider.ConvertType.NameToQueryTable) - ).ToString(); - - spName = ToStringLiteral(spName); - - var inputParameters = p.ProcParameters.Where(pp => pp.IsIn). ToList(); - var outputParameters = p.ProcParameters.Where(pp => pp.IsOut). ToList(); - var inOrOutputParameters = p.ProcParameters.Where(pp => pp.IsIn || pp.IsOut).ToList(); - - spName += inOrOutputParameters.Count == 0 - ? (p.ResultTable == null || !GenerateProcedureResultAsList ? ");" : ").ToList();") - : ","; - - var retName = "ret"; - var retNo = 0; - - while (p.ProcParameters.Any(pp => pp.ParameterName == retName)) - retName = "ret" + ++retNo; - - var hasOut = outputParameters.Any(pr => pr.IsOut); - var prefix = hasOut ? "var " + retName + " = " : "return "; - - if (p.ResultTable == null) - p.BodyBuilders.Add(() => new [] { prefix + "dataConnection.ExecuteProc(" + spName }); - else - { - if (p.ResultTable.Columns.Values.Any(c => c.IsDuplicateOrEmpty)) - { - p.BodyBuilders.Add(() => new [] - { - "var ms = dataConnection.MappingSchema;", - "", - prefix + "dataConnection.QueryProc(dataReader =>", - "\tnew " + p.ResultTable.TypeName, - "\t{" - }); - - var n = 0; - var maxNameLen = p.ResultTable.Columns.Values.Max(c => (int?)c.MemberName .Length) ?? 0; - var maxTypeLen = p.ResultTable.Columns.Values.Max(c => (int?)c.BuildType().Length) ?? 0; - - foreach (var c in p.ResultTable.Columns.Values) - { - p.BodyBuilders.Add(() => new [] {string.Format("\t\t{0}{1} = Converter.ChangeTypeTo<{2}>{3}(dataReader.GetValue({4}), ms),", - c.MemberName, LenDiff(maxNameLen, c.MemberName), c.BuildType(), LenDiff(maxTypeLen, c.BuildType()), n++) }); - } - - p.BodyBuilders.Add(() => new [] {"\t},", "\t" + spName }); - } - else - { - p.BodyBuilders.Add(() => new [] { prefix + "dataConnection.QueryProc<" + p.ResultTable.TypeName + ">(" + spName }); - } - } - - var maxLenSchema = inputParameters.Max(pr => (int?)pr.SchemaName. Length) ?? 0; - var maxLenParam = inputParameters.Max(pr => (int?)pr.ParameterName.Length) ?? 0; - var maxLenType = inputParameters.Max(pr => (int?)("DataType." + pr.DataType).Length) ?? 0; - - for (var idx = 0; idx < inOrOutputParameters.Count; idx++) - { - var i = idx; - var pr = inOrOutputParameters[i]; - - p.BodyBuilders.Add(() => - { - var str = string.Format( - !pr.IsIn && pr.IsOut - ? "\tnew DataParameter({0}, null, {3}{4})" - : "\tnew DataParameter({0}, {1}{2}, {3}{4})" + (GenerateProcedureDbType(pr) ? "{{ DbType = {5} }}" : null), - ToStringLiteral(pr.SchemaName), - LenDiff(maxLenSchema, pr.SchemaName), - pr.ParameterName, - LenDiff(maxLenParam, pr.ParameterName), - "DataType." + pr.DataType, - ToStringLiteral(pr.SchemaType)); - - if (pr.IsOut) - { - str += LenDiff(maxLenType, "DataType." + pr.DataType); - str += " { Direction = " + (pr.IsIn ? "ParameterDirection.InputOutput" : "ParameterDirection.Output"); - - if (pr.Size != null && pr.Size.Value != 0) - str += ", Size = " + pr.Size.Value; - - str += " }"; - } - - // we need to call ToList(), because otherwise output parameters will not be updated - // with values. See https://msdn.microsoft.com/en-us/library/ms971497#gazoutas_topic6 - str += i + 1 == inOrOutputParameters.Count - ? ((GenerateProcedureResultAsList || outputParameters.Count > 0) && p.ResultTable != null ? ").ToList();" : ");") - : ","; - - return new [] { str }; - }); - } - - if (hasOut) - { - maxLenSchema = outputParameters.Max(pr => (int?)pr.SchemaName. Length) ?? 0; - maxLenParam = outputParameters.Max(pr => (int?)pr.ParameterName.Length) ?? 0; - maxLenType = outputParameters.Max(pr => (int?)pr.ParameterType.Length) ?? 0; - - p.BodyBuilders.Add(() => new [] { string.Empty }); - - foreach (var pr in p.ProcParameters.Where(_ => _.IsOut)) - { - p.BodyBuilders.Add(() => new [] { string.Format("{0} {1}= Converter.ChangeTypeTo<{2}>{3}(((IDbDataParameter)dataConnection.Command.Parameters[{4}]).{5}Value);", - pr.ParameterName, - LenDiff(maxLenParam, pr.ParameterName), - pr.ParameterType, - LenDiff(maxLenType, pr.ParameterType), - ToStringLiteral(pr.SchemaName), - LenDiff(maxLenSchema, pr.SchemaName)) }); - } - - p.BodyBuilders.Add(() => new [] {"", "return " + retName + ";" }); - } - } - - if (p.ResultTable != null && p.ResultTable.DataContextPropertyName == null) - { - var columns = new MemberGroup { IsCompact = true }; - - foreach (var c in p.ResultTable.Columns.Values) - { - if (c.MemberName != c.ColumnName) - c.Attributes.Add(new Attribute("Column") { Parameters = { ToStringLiteral(c.ColumnName) } }); - columns.Members.Add(c); - } - - p.ResultTable.Members.Add(columns); - proc.Members.Add(p.ResultTable); - } - } - - if (procs.Members.Count > 0) - Model.Types.Add(new Class(DataContextObject.Name + "StoredProcedures", procs) { IsStatic = true }); - - if (funcs.Members.Count > 0) - Model.Types.Add(new Class("SqlFunctions", funcs) { IsStatic = true }); - - if (tabfs.Members.Count > 0) - DataContextObject.Members.Add(tabfs); - - MakeTypeMembersNamesUnique(DataContextObject, "InitDataContext", "InitMappingSchema"); - MakeMembersNamesUnique(Model.Types, "Table"); - foreach (var type in Model.Types.OfType()) - MakeTypeMembersNamesUnique(type, exceptMethods: new [] { "Find", "InitDataContext", "InitMappingSchema" }); - - foreach (var schema in schemas.Values) - { - if (schema.Procedures.Members.Count > 0) - schema.Type.Members.Add(new Class(DataContextObject.Name + "StoredProcedures", schema.Procedures) { IsStatic = true }); - - if (schema.Functions.Members.Count > 0) - schema.Type.Members.Add(new Class("SqlFunctions", schema.Functions) { IsStatic = true }); - - if (schema.TableFunctions.Members.Count > 0) - schema.DataContext.Members.Add(schema.TableFunctions); - - MakeTypeMembersNamesUnique(schema.DataContext, "InitDataContext", "InitMappingSchema"); - foreach (var type in schema.Type.Members.OfType()) - MakeTypeMembersNamesUnique(type); - } - } - - if (defTableExtensions.Members.Count > 0) - { - Model.Usings.Add("System.Linq"); - var tableExtensions = new Class("TableExtensions", defTableExtensions) { IsStatic = true }; - Model.Types.Add(tableExtensions); - MakeTypeMembersNamesUnique(tableExtensions, exceptMethods: new [] { "Find" }); - } - - foreach (var schema in schemas.Values) - { - Model.Types.Add(schema.Type); - - if (schema.TableExtensions.Members.Count > 0) - { - Model.Usings.Add("System.Linq"); - schema.Type.Members.Add(schema.TableExtensions); - } - } - - Tables. Clear(); - Procedures.Clear(); - - Model.SetTree(); - - AfterGenerateLinqToDBModel(); -} - -void MakeTypeMembersNamesUnique(Class type, string defaultName = "Member", params string[] exceptMethods) -{ - var reservedNames = new [] { type.Name }; - if (exceptMethods != null && exceptMethods.Length > 0) - reservedNames = reservedNames.Concat(exceptMethods).ToArray(); - - MakeMembersNamesUnique(GetAllClassMembers(type.Members, exceptMethods), defaultName, reservedNames); -} - -void MakeMembersNamesUnique(IEnumerable members, string defaultName, params string[] reservedNames) -{ - LinqToDB.Common.Utils.MakeUniqueNames( - members, - reservedNames, - m => m is Table tbl ? (tbl.Schema != null && !tbl.IsDefaultSchema && PrefixTableMappingWithSchema ? tbl.Schema + "_" : null) + tbl.Name : (m is TypeBase t ? t.Name : ((MemberBase)m).Name), - (m, newName) => - { - if (m is TypeBase t) - t.Name = newName; - else - ((MemberBase)m).Name = newName; - }, - defaultName); -} - -IEnumerable GetAllClassMembers(IEnumerable members, params string[] exceptMethods) -{ - foreach (var member in members) - { - if (member is MemberGroup mg) - foreach (var m in GetAllClassMembers(mg.Members, exceptMethods)) - yield return m; - // constructors don't have own type/flag - else if (member is Method method && (method.BuildType() == null || (exceptMethods != null && exceptMethods.Contains(method.Name)))) - continue; - else - yield return member; - } -} - -// left for backward compatibility -string NormalizeStringName(string name) -{ - return ToStringLiteral(name); -} - -#> diff --git a/BillsManager.Services/LinqToDB.Templates/MultipleFiles.ttinclude b/BillsManager.Services/LinqToDB.Templates/MultipleFiles.ttinclude deleted file mode 100644 index 4b43ba0..0000000 --- a/BillsManager.Services/LinqToDB.Templates/MultipleFiles.ttinclude +++ /dev/null @@ -1,70 +0,0 @@ -<#@ assembly name="System.Core" #> -<#@ assembly name="EnvDTE" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="EnvDTE" #> -<#+ -DTE _dte; -DTE DTE => _dte ?? (_dte = (DTE)((IServiceProvider)Host).GetService(typeof(DTE))); - -ProjectItem _templateProjectItem; -ProjectItem TemplateProjectItem => _templateProjectItem ?? (_templateProjectItem = DTE.Solution.FindProjectItem(Host.TemplateFile)); - -readonly Dictionary _fileNames = new Dictionary(); - -Func CompareContent = (s1,s2) => s1 == s2; - -void SaveOutput(string fileName, int fileType = 1) -{ - var dir = Path.GetDirectoryName(Host.TemplateFile); - var output = Path.Combine(dir, fileName); - var newContent = GenerationEnvironment.ToString(); - var oldContent = File.Exists(output) ? File.ReadAllText(output) : ""; - - if (!CompareContent(newContent, oldContent)) - { - if (DTE.SourceControl != null && DTE.SourceControl.IsItemUnderSCC(output) && !DTE.SourceControl.IsItemCheckedOut(output)) - DTE.SourceControl.CheckOutItem(output); - - File.WriteAllText(output, newContent); - } - - GenerationEnvironment.Length = 0; - - _fileNames.Add(output, fileType); -} - -void SyncProject() -{ - var keepFileNames = _fileNames.ToDictionary(f => f.Key); - var projectFiles = new Dictionary(); - var templateFileName = TemplateProjectItem.FileNames[0]; - var originalFilePrefix = Path.GetFileNameWithoutExtension(templateFileName) + "."; - - foreach (ProjectItem projectItem in TemplateProjectItem.ProjectItems) - { - projectFiles.Add(projectItem.FileNames[0], projectItem); - } - - foreach (var pair in projectFiles) - { - if (!keepFileNames.ContainsKey(pair.Key)) - if (!(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix)) - //if (pair.Key != templateFileName) - pair.Value.Delete(); - } - - // Add missing files to the project. - // - foreach (var fileName in keepFileNames) - { - if (!projectFiles.ContainsKey(fileName.Value.Key)) - if (File.Exists(fileName.Value.Key)) - { - var newItem = TemplateProjectItem.ProjectItems.AddFromFile(fileName.Value.Key); - newItem.Properties.Item("BuildAction").Value = fileName.Value.Value; - } - } -} -#> diff --git a/BillsManager.Services/LinqToDB.Templates/NotifyDataErrorInfo.ttinclude b/BillsManager.Services/LinqToDB.Templates/NotifyDataErrorInfo.ttinclude deleted file mode 100644 index 06e72af..0000000 --- a/BillsManager.Services/LinqToDB.Templates/NotifyDataErrorInfo.ttinclude +++ /dev/null @@ -1,133 +0,0 @@ -<# - { - var beforeGenerateModel = BeforeGenerateModel; - BeforeGenerateModel = () => - { - beforeGenerateModel(); - NotifyDataErrorInfoImpl(); - }; - } -#> -<#+ -void NotifyDataErrorInfoImpl() -{ - foreach (var prop in GetTreeNodes(Model).OfType().Where(p => p.CustomValidation).ToList()) - { - ITree p = prop.Parent; - - while (!(p is Class) && p != null) - p = p.Parent; - - if (p != null) - { - var cl = (Class)p; - - if (!cl.Interfaces.Contains("INotifyDataErrorInfo")) - { - if (!Model.Usings.Contains("System.ComponentModel")) Model.Usings.Add("System.ComponentModel"); - if (!Model.Usings.Contains("System.Collections")) Model.Usings.Add("System.Collections"); - if (!Model.Usings.Contains("System.Linq")) Model.Usings.Add("System.Linq"); - - cl.Interfaces.Add("INotifyDataErrorInfo"); - - cl.Members.Add(new MemberGroup - { - Region = "INotifyDataErrorInfo support", - Members = - { - new Event(() => "EventHandler", "ErrorsChanged") - { - IsVirtual = true, - Attributes = { new Attribute("field : NonSerialized") { Conditional = "!SILVERLIGHT" } } - }, - new Field(() => "Dictionary>", "_validationErrors") - { - InitValue = "new Dictionary>()", - AccessModifier = AccessModifier.Private, - IsReadonly = true, - Attributes = { new Attribute("field : NonSerialized") { Conditional = "!SILVERLIGHT" } } - }, - new Method(() => "void", "AddError", - new Func[] - { - () => "string propertyName", - () => "string error" - }, - () => new[] - { - "List errors;", - "", - "if (!_validationErrors.TryGetValue(propertyName, out errors))", - "{", - "\t_validationErrors[propertyName] = new List { error };", - "}", - "else if (!errors.Contains(error))", - "{", - "\terrors.Add(error);", - "}", - "else", - "\treturn;", - "", - "OnErrorsChanged(propertyName);", - }) - { - AccessModifier = AccessModifier.Public - }, - new Method(() => "void", "RemoveError", - new Func[] - { - () => "string propertyName", - }, - () => new[] - { - "List errors;", - "", - "if (_validationErrors.TryGetValue(propertyName, out errors) && errors.Count > 0)", - "{", - "\t_validationErrors.Clear();", - "\tOnErrorsChanged(propertyName);", - "}", - }) - { - AccessModifier = AccessModifier.Public - }, - new Method(() => "void", "OnErrorsChanged", - new Func[] - { - () => "string propertyName", - }, - () => new[] - { - "if (ErrorsChanged != null)", - "{", - "\tif (System.Windows.Deployment.Current.Dispatcher.CheckAccess())", - "\t\tErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));", - "\telse", - "\t\tSystem.Windows.Deployment.Current.Dispatcher.BeginInvoke(", - "\t\t\t() => ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName)));", - "}", - }) - { - AccessModifier = AccessModifier.Protected - }, - new Method(() => "IEnumerable", "GetErrors", - new Func[] - { - () => "string propertyName", - }, - () => new[] - { - "List errors;", - "return propertyName != null && _validationErrors.TryGetValue(propertyName, out errors) ? errors : null;", - }) - { - AccessModifier = AccessModifier.Public - }, - new Property(() => "bool", "HasErrors").InitGetter(() => new [] { "_validationErrors.Values.Any(e => e.Count > 0)" }) - } - }); - } - } - } -} -#> diff --git a/BillsManager.Services/LinqToDB.Templates/NotifyPropertyChanged.ttinclude b/BillsManager.Services/LinqToDB.Templates/NotifyPropertyChanged.ttinclude deleted file mode 100644 index 49234e7..0000000 --- a/BillsManager.Services/LinqToDB.Templates/NotifyPropertyChanged.ttinclude +++ /dev/null @@ -1,382 +0,0 @@ -<# - { - var beforeGenerateModel = BeforeGenerateModel; - BeforeGenerateModel = () => - { - beforeGenerateModel(); - NotifyPropertyChangedImpl(); - }; - - SetPropertyValueAction += (obj,prop,val) => - { - if (prop == "IsNotifying") - obj.IsNotifying = (bool)val; - }; - } -#><#+ -public bool ImplementNotifyPropertyChanging; -public bool SkipNotifyPropertyChangedImplementation = false; - -void NotifyPropertyChangedImpl() -{ - foreach (Property prop in GetTreeNodes(Model).OfType().Where(p => p.IsNotifying).ToList()) - { - List parentMembers; - - MemberGroup gr = null; - - if (prop.Parent is Class) - { - var parent = (Class)prop.Parent; - parentMembers = parent.Members; - } - else - { - var parent = (MemberGroup)prop.Parent; - - parent.IsCompact = false; - - parentMembers = parent.Members; - - if (parent.IsPropertyGroup) - gr = parent; - } - - var name = prop.Name.Trim(); - var type = prop.BuildType().Trim(); - - if (gr == null) - { - gr = new MemberGroup - { - Region = name + " : " + type, - Members = { prop }, - IsPropertyGroup = true, - }; - - var index = parentMembers.IndexOf(prop); - - parentMembers.RemoveAt(index); - parentMembers.Insert (index, gr); - } - - if (prop.IsAuto) - { - var field = new Field(() => type, "_" + ToCamelCase(name)) - { - AccessModifier = AccessModifier.Private, - InsertBlankLineAfter = false, - }; - - if (prop.InitValue != null) - field.InitValue = prop.InitValue; - - gr.Members.Insert(0, field); - - prop.Name = " " + name; - prop.TypeBuilder = () => " " + type; - prop.IsAuto = false; - - if (prop.HasGetter) prop.GetBodyBuilders.Add(() => new [] { "return " + field.Name + ";" }); - if (prop.HasSetter) prop.SetBodyBuilders.Add(() => new [] { field.Name + " = value;" }); - } - - var methods = new MemberGroup - { - Region = "INotifyPropertyChanged support", - Members = - { - new Field(() => "const string", "NameOf" + name) - { - InitValue = ToStringLiteral(name), - AccessModifier = AccessModifier.Public, - }, - new Field(() => "PropertyChangedEventArgs", "_" + ToCamelCase(name) + "ChangedEventArgs") - { - InitValue = "new PropertyChangedEventArgs(NameOf" + name + ")", - AccessModifier = AccessModifier.Private, - IsStatic = true, - IsReadonly = true, - }, - new Method(() => "void", "On" + name + "Changed", null, - () => new[] { "OnPropertyChanged(_" + ToCamelCase(name) + "ChangedEventArgs);" }) - { - AccessModifier = AccessModifier.Private - } - } - }; - - gr.Members.Add(methods); - - if (prop.Dependents.Count == 0) - prop.Dependents.Add(name); - - if (ImplementNotifyPropertyChanging) - { - gr.Members.Add(new MemberGroup - { - Region = "INotifyPropertyChanging support", - Members = - { - new Field(() => "PropertyChangingEventArgs", "_" + ToCamelCase(name) + "ChangingEventArgs") - { - InitValue = "new PropertyChangingEventArgs(NameOf" + name + ")", - AccessModifier = AccessModifier.Private, - IsStatic = true, - IsReadonly = true, - }, - new Method(() => "void", "On" + name + "Changing", null, - () => new[] { "OnPropertyChanging(_" + ToCamelCase(name) + "ChangingEventArgs);" }) - { - AccessModifier = AccessModifier.Private - } - } - }); - } - - if (prop.HasSetter) - { - var setBody = prop.BuildSetBody().Select(s => "\t" + s).ToArray(); - prop.SetBodyBuilders.Clear(); - prop.SetBodyBuilders.Add(() => setBody); - - string getValue; - - var getBody = prop.BuildGetBody().ToArray(); - if (getBody.Length == 1 && getBody[0].StartsWith("return")) - { - getValue = getBody[0].Substring("return".Length).Trim(' ', '\t', ';'); - } - else - { - getValue = name; - } - - var insSpaces = setBody.Length > 1; - var n = 0; - - prop.SetBodyBuilders.Insert(n++, () => new [] {"if (" + getValue + " != value)", "{" }); - - if (ImplementNotifyPropertyChanging) - { - foreach (var dp in prop.Dependents) - prop.SetBodyBuilders.Insert(n++, () => new [] { "\tOn" + dp + "Changing();" }); - prop.SetBodyBuilders.Insert(n++, () => new [] { "" }); - } - - prop.SetBodyBuilders.Insert(n++, () => new [] { "\tBefore" + name + "Changed(value);" }); - - if (insSpaces) - { - prop.SetBodyBuilders.Insert(3, () => new [] { "" }); - prop.SetBodyBuilders.Add(() => new [] { "" }); - } - - prop.SetBodyBuilders.Add(() => new [] { "\tAfter" + name + "Changed();" }); - prop.SetBodyBuilders.Add(() => new [] { "" }); - - foreach (var dp in prop.Dependents) - prop.SetBodyBuilders.Add(() => new [] { "\tOn" + dp + "Changed();" }); - - prop.SetBodyBuilders.Add(() => new [] { "}" }); - - methods.Members.Insert(0, new MemberGroup - { - IsCompact = true, - Members = - { - new Method(() => "void", "Before" + name + "Changed", new Func[] { () => type + " newValue" }) { AccessModifier = AccessModifier.Partial }, - new Method(() => "void", "After" + name + "Changed") { AccessModifier = AccessModifier.Partial }, - } - }); - } - - prop.Parent.SetTree(); - - ITree p = prop.Parent; - - while (!(p is Class) && p != null) - p = p.Parent; - - if (p != null) - { - var cl = (Class)p; - - if (!SkipNotifyPropertyChangedImplementation && !cl.Interfaces.Contains("INotifyPropertyChanged")) - { - if (!Model.Usings.Contains("System.ComponentModel")) - Model.Usings.Add("System.ComponentModel"); - - cl.Interfaces.Add("INotifyPropertyChanged"); - - cl.Members.Add(new MemberGroup - { - Region = "INotifyPropertyChanged support", - Members = - { - new Event(() => "PropertyChangedEventHandler", "PropertyChanged") - { - IsVirtual = true, - Attributes = { new Attribute("field : NonSerialized") { Conditional = "!SILVERLIGHT" } } - }, - new Method(() => "void", "OnPropertyChanged", new Func[] { () => "string propertyName" }, () => OnPropertyChangedBody) - { - AccessModifier = AccessModifier.Protected - }, - new Method(() => "void", "OnPropertyChanged", new Func[] { () => "PropertyChangedEventArgs arg" }, () => OnPropertyChangedArgBody) - { - AccessModifier = AccessModifier.Protected - }, - } - }); - } - - if (ImplementNotifyPropertyChanging && !cl.Interfaces.Contains("INotifyPropertyChanging")) - { - if (!Model.Usings.Contains("System.ComponentModel")) - Model.Usings.Add("System.ComponentModel"); - - cl.Interfaces.Add("INotifyPropertyChanging"); - - cl.Members.Add(new MemberGroup - { - Region = "INotifyPropertyChanging support", - Members = - { - new Event(() => "PropertyChangingEventHandler", "PropertyChanging") - { - IsVirtual = true, - Attributes = { new Attribute("field : NonSerialized") { Conditional = "!SILVERLIGHT" } } - }, - new Method(() => "void", "OnPropertyChanging", new Func[] { () => "string propertyName" }, () => OnPropertyChangingBody) - { - AccessModifier = AccessModifier.Protected - }, - new Method(() => "void", "OnPropertyChanging", new Func[] { () => "PropertyChangingEventArgs arg" }, () => OnPropertyChangingArgBody) - { - AccessModifier = AccessModifier.Protected - }, - } - }); - } - } - } -} - -public string[] OnPropertyChangedBody = new[] -{ - "var propertyChanged = PropertyChanged;", - "", - "if (propertyChanged != null)", - "{", - "#if SILVERLIGHT", - "\tif (System.Windows.Deployment.Current.Dispatcher.CheckAccess())", - "\t\tpropertyChanged(this, new PropertyChangedEventArgs(propertyName));", - "\telse", - "\t\tSystem.Windows.Deployment.Current.Dispatcher.BeginInvoke(", - "\t\t\t() =>", - "\t\t\t{", - "\t\t\t\tvar pc = PropertyChanged;", - "\t\t\t\tif (pc != null)", - "\t\t\t\t\tpc(this, new PropertyChangedEventArgs(propertyName));", - "\t\t\t});", - "#else", - "\tpropertyChanged(this, new PropertyChangedEventArgs(propertyName));", - "#endif", - "}", -}; - -public string[] OnPropertyChangedArgBody = new[] -{ - "var propertyChanged = PropertyChanged;", - "", - "if (propertyChanged != null)", - "{", - "#if SILVERLIGHT", - "\tif (System.Windows.Deployment.Current.Dispatcher.CheckAccess())", - "\t\tpropertyChanged(this, arg);", - "\telse", - "\t\tSystem.Windows.Deployment.Current.Dispatcher.BeginInvoke(", - "\t\t\t() =>", - "\t\t\t{", - "\t\t\t\tvar pc = PropertyChanged;", - "\t\t\t\tif (pc != null)", - "\t\t\t\t\tpc(this, arg);", - "\t\t\t});", - "#else", - "\tpropertyChanged(this, arg);", - "#endif", - "}", -}; - -public string[] OnPropertyChangingBody = new[] -{ - "var propertyChanging = PropertyChanging;", - "", - "if (propertyChanging != null)", - "{", - "#if SILVERLIGHT", - "\tif (System.Windows.Deployment.Current.Dispatcher.CheckAccess())", - "\t\tpropertyChanging(this, new PropertyChangingEventArgs(propertyName));", - "\telse", - "\t\tSystem.Windows.Deployment.Current.Dispatcher.BeginInvoke(", - "\t\t\t() =>", - "\t\t\t{", - "\t\t\t\tvar pc = PropertyChanging;", - "\t\t\t\tif (pc != null)", - "\t\t\t\t\tpc(this, new PropertyChangingEventArgs(propertyName));", - "\t\t\t});", - "#else", - "\tpropertyChanging(this, new PropertyChangingEventArgs(propertyName));", - "#endif", - "}", -}; - -public string[] OnPropertyChangingArgBody = new[] -{ - "var propertyChanging = PropertyChanging;", - "", - "if (propertyChanging != null)", - "{", - "#if SILVERLIGHT", - "\tif (System.Windows.Deployment.Current.Dispatcher.CheckAccess())", - "\t\tpropertyChanging(this, arg);", - "\telse", - "\t\tSystem.Windows.Deployment.Current.Dispatcher.BeginInvoke(", - "\t\t\t() =>", - "\t\t\t{", - "\t\t\t\tvar pc = PropertyChanging;", - "\t\t\t\tif (pc != null)", - "\t\t\t\t\tpc(this, arg);", - "\t\t\t});", - "#else", - "\tpropertyChanging(this, arg);", - "#endif", - "}", -}; - -partial class Property -{ - public bool IsNotifying; - public List Dependents = new List(); -} - -class NotifyingProperty : Property -{ - public NotifyingProperty() - { - IsNotifying = true; - } - - public NotifyingProperty(string type, string name, params string[] dependents) - : base(() => type, name, null, null) - { - IsNotifying = true; - - if (dependents.Length == 0) - Dependents.Add(name); - else - Dependents.AddRange(dependents); - } -} -#> diff --git a/BillsManager.Services/LinqToDB.Templates/ObsoleteAttributes.ttinclude b/BillsManager.Services/LinqToDB.Templates/ObsoleteAttributes.ttinclude deleted file mode 100644 index b95b0d8..0000000 --- a/BillsManager.Services/LinqToDB.Templates/ObsoleteAttributes.ttinclude +++ /dev/null @@ -1,100 +0,0 @@ -<# - { - var beforeGenerateLinqToDBModel = BeforeGenerateLinqToDBModel; - var afterGenerateLinqToDBModel = AfterGenerateLinqToDBModel; - - var obsoleteTables = new List>(); - - BeforeGenerateLinqToDBModel = () => - { - beforeGenerateLinqToDBModel(); - - foreach (var table in Tables.Values) - { - var idx = table.Description.IndexOf("[Obsolete"); - - if (idx >= 0) - { - var idx2 = table.Description.IndexOf(']', idx); - - if (idx2 > idx) - { - var text = table.Description.Substring(idx + 1, idx2 - idx - 1); - var attr = new Attribute(text); - var info = Tuple.Create(table.Schema, table.Name, text); - - if (obsoleteTables.All(a => a != info)) - obsoleteTables.Add(info); - table.Attributes.Add(attr); - table.Description = table.Description.Substring(0, idx) + table.Description.Substring(idx2 + 1); - } - } - - foreach (var c in table.Columns.Values) - { - idx = c.Description.IndexOf("[Obsolete"); - - if (idx >= 0) - { - var idx2 = c.Description.IndexOf(']', idx); - - if (idx2 > idx) - { - var attr = new Attribute(c.Description.Substring(idx + 1, idx2 - idx - 1)); - - c.Attributes.Add(attr); - c.Description = c.Description.Substring(0, idx) + c.Description.Substring(idx2 + 1); - } - } - } - } - }; - - AfterGenerateLinqToDBModel = () => - { - foreach (var tableInfo in obsoleteTables) - { - var schema = tableInfo.Item1; - var name = tableInfo.Item2; - var text = tableInfo.Item3; - var obsoleteAttr = new Attribute(text); - - foreach (var cm in GetTreeNodes(Model) - .OfType() - .Where(t => t.BuildType() != null) - .Where(t => t.BuildType() == name || t.BuildType().Contains("<" + name + ">"))) - { - // check schema - - if (cm.Parent != null && cm.Parent.Parent != null) - { - var parent = cm.Parent.Parent; - - if (parent is Table) - { - var table = (Table)parent; - - if (schema == table.Schema) - if (cm.Attributes.All(a => a.Name != text)) - cm.Attributes.Add(obsoleteAttr); - } - else if (parent is Class) - { - var cls = (Class)parent; - - bool parentClassIncludesSchemaName = cls.Name.Equals(schema + "Schema", StringComparison.InvariantCultureIgnoreCase); - bool classIsForDefaultSchema = cls.Name == DataContextName; - bool isExtensionMethod = cls.Parent is Namespace || cls.Name == "TableExtensions"; - - if (classIsForDefaultSchema || parentClassIncludesSchemaName || isExtensionMethod) - if (cm.Attributes.All(a => a.Name != text)) - cm.Attributes.Add(obsoleteAttr); - } - } - } - } - - afterGenerateLinqToDBModel(); - }; - } -#> diff --git a/BillsManager.Services/LinqToDB.Templates/PluralizationService.ttinclude b/BillsManager.Services/LinqToDB.Templates/PluralizationService.ttinclude deleted file mode 100644 index 2bed1d6..0000000 --- a/BillsManager.Services/LinqToDB.Templates/PluralizationService.ttinclude +++ /dev/null @@ -1,185 +0,0 @@ -<#@ assembly name="System.Data.Entity.Design" #> -<#@ import namespace="System.Data.Entity.Design.PluralizationServices" #> -<# - { - ToPlural = Pluralization.ToPlural; - ToSingular = Pluralization.ToSingular; - } -#> -<#+ -static class Pluralization -{ - public static string CultureInfo = "en"; - - static PluralizationService _service; - - public static Dictionary Dictionary = new Dictionary - { - { "access", "accesses" }, { "afterlife", "afterlives" }, { "alga", "algae" }, - { "alumna", "alumnae" }, { "alumnus", "alumni" }, { "analysis", "analyses" }, - { "antenna", "antennae" }, { "appendix", "appendices" }, { "axis", "axes" }, - { "bacillus", "bacilli" }, { "basis", "bases" }, { "Bedouin", "Bedouin" }, - { "cactus", "cacti" }, { "calf", "calves" }, { "cherub", "cherubim" }, - { "child", "children" }, { "cod", "cod" }, { "cookie", "cookies" }, - { "criterion", "criteria" }, { "curriculum", "curricula" }, { "data", "data" }, - { "deer", "deer" }, { "diagnosis", "diagnoses" }, { "die", "dice" }, - { "dormouse", "dormice" }, { "elf", "elves" }, { "elk", "elk" }, - { "erratum", "errata" }, { "esophagus", "esophagi" }, { "fauna", "faunae" }, - { "fish", "fish" }, { "flora", "florae" }, { "focus", "foci" }, - { "foot", "feet" }, { "formula", "formulae" }, { "fundus", "fundi" }, - { "fungus", "fungi" }, { "genie", "genii" }, { "genus", "genera" }, - { "goose", "geese" }, { "grouse", "grouse" }, { "hake", "hake" }, - { "half", "halves" }, { "headquarters", "headquarters" }, { "hippo", "hippos" }, - { "hippopotamus", "hippopotami" }, { "hoof", "hooves" }, { "housewife", "housewives" }, - { "hypothesis", "hypotheses" }, { "index", "indices" }, { "info", "info" }, - { "jackknife", "jackknives" }, - { "knife", "knives" }, { "labium", "labia" }, { "larva", "larvae" }, - { "leaf", "leaves" }, { "life", "lives" }, { "loaf", "loaves" }, - { "louse", "lice" }, { "magus", "magi" }, { "man", "men" }, - { "memorandum", "memoranda" }, { "midwife", "midwives" }, { "millennium", "millennia" }, - { "moose", "moose" }, { "mouse", "mice" }, { "nebula", "nebulae" }, - { "neurosis", "neuroses" }, { "nova", "novas" }, { "nucleus", "nuclei" }, - { "oesophagus", "oesophagi" }, { "offspring", "offspring" }, { "ovum", "ova" }, - { "ox", "oxen" }, { "papyrus", "papyri" }, { "passerby", "passersby" }, - { "penknife", "penknives" }, { "person", "people" }, { "phenomenon", "phenomena" }, - { "placenta", "placentae" }, { "pocketknife", "pocketknives" }, { "process", "processes" }, - { "pupa", "pupae" }, { "radius", "radii" }, { "reindeer", "reindeer" }, - { "retina", "retinae" }, { "rhinoceros", "rhinoceros" }, { "roe", "roe" }, - { "salmon", "salmon" }, { "scarf", "scarves" }, { "self", "selves" }, - { "seraph", "seraphim" }, { "series", "series" }, { "sheaf", "sheaves" }, - { "sheep", "sheep" }, { "shelf", "shelves" }, { "species", "species" }, - { "spectrum", "spectra" }, { "status", "status" }, { "stimulus", "stimuli" }, - { "stratum", "strata" }, { "supernova", "supernovas" }, { "swine", "swine" }, - { "terminus", "termini" }, { "thesaurus", "thesauri" }, { "thesis", "theses" }, - { "thief", "thieves" }, { "trout", "trout" }, { "vulva", "vulvae" }, - { "wife", "wives" }, { "wildebeest", "wildebeest" }, { "wolf", "wolves" }, - { "woman", "women" }, { "yen", "yen" }, - }; - - static string GetLastWord(string str) - { - if (string.IsNullOrWhiteSpace(str)) - return string.Empty; - - var i = str.Length - 1; - var isLower = char.IsLower(str[i]); - - while (i > 0 && char.IsLetter(str[i - 1]) && char.IsLower(str[i - 1]) == isLower) - i--; - - return str.Substring(isLower && i > 0 && char.IsLetter(str[i - 1]) ? i - 1 : i); - } - - public static string ToPlural(string str) - { - if (_service == null) - _service = PluralizationService.CreateService(System.Globalization.CultureInfo.GetCultureInfo(CultureInfo)); - - var word = GetLastWord(str); - - string newWord; - - if (!Dictionary.TryGetValue(word.ToLower(), out newWord)) - newWord = _service.IsPlural(word) ? word : _service.Pluralize(word); - - if (string.Compare(word, newWord, true) != 0) - { - if (char.IsUpper(word[0])) - newWord = char.ToUpper(newWord[0]) + newWord.Substring(1, newWord.Length - 1).ToLower(); - - return word == str ? newWord : str.Substring(0, str.Length - word.Length) + newWord; - } - - return str; - } - - public static string ToSingular(string str) - { - if (_service == null) - _service = PluralizationService.CreateService(System.Globalization.CultureInfo.GetCultureInfo(CultureInfo)); - - var word = GetLastWord(str); - - var newWord = - Dictionary - .Where(dic => string.Compare(dic.Value, word, true) == 0) - .Select(dic => dic.Key) - .FirstOrDefault() - ?? - (_service.IsSingular(word) ? word : _service.Singularize(word)); - - if (string.Compare(word, newWord, true) != 0) - { - if (char.IsUpper(word[0])) - newWord = char.ToUpper(newWord[0]) + newWord.Substring(1, newWord.Length - 1); - - return word == str ? newWord : str.Substring(0, str.Length - word.Length) + newWord; - } - - return str; - } - - static string GetLastWordVersion1(string str) - { - if (string.IsNullOrWhiteSpace(str)) - return string.Empty; - - var i = str.Length - 1; - var isLower = char.IsLower(str[i]); - - while (i > 0 && char.IsLower(str[i-1]) == isLower) - i--; - - return str.Substring(isLower && i > 0 ? i - 1 : i); - } - - public static string ToPluralVersion1(string str) - { - if (_service == null) - _service = PluralizationService.CreateService(System.Globalization.CultureInfo.GetCultureInfo(CultureInfo)); - - var word = GetLastWordVersion1(str); - - string newWord; - - if (!Dictionary.TryGetValue(word.ToLower(), out newWord)) - newWord = _service.IsPlural(word) ? word : _service.Pluralize(word); - - if (string.Compare(word, newWord, true) != 0) - { - if (char.IsUpper(word[0])) - newWord = char.ToUpper(newWord[0]) + newWord.Substring(1, newWord.Length - 1); - - return word == str ? newWord : str.Substring(0, str.Length - word.Length) + newWord; - } - - return str; - } - - public static string ToSingularVersion1(string str) - { - if (_service == null) - _service = PluralizationService.CreateService(System.Globalization.CultureInfo.GetCultureInfo(CultureInfo)); - - var word = GetLastWordVersion1(str); - - var newWord = - Dictionary - .Where(dic => string.Compare(dic.Value, word, true) == 0) - .Select(dic => dic.Key) - .FirstOrDefault() - ?? - (_service.IsSingular(word) ? word : _service.Singularize(word)); - - if (string.Compare(word, newWord, true) != 0) - { - if (char.IsUpper(word[0])) - newWord = char.ToUpper(newWord[0]) + newWord.Substring(1, newWord.Length - 1); - - return word == str ? newWord : str.Substring(0, str.Length - word.Length) + newWord; - } - - return str; - } -} -#> diff --git a/BillsManager.Services/LinqToDB.Templates/T4Model.ttinclude b/BillsManager.Services/LinqToDB.Templates/T4Model.ttinclude deleted file mode 100644 index d164aae..0000000 --- a/BillsManager.Services/LinqToDB.Templates/T4Model.ttinclude +++ /dev/null @@ -1,1564 +0,0 @@ -<#@ assembly name="System.Core" #> -<#@ import namespace="System" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Text" #> -<#+ -static Action WriteComment = (tt,s) => tt.WriteLine("//{0}", s); - -Action BeforeGenerateModel = () => {}; - -bool GenerateProcedureErrors = true; - -void GenerateModel() -{ - Model.SetTree(); - - if (GenerationEnvironment.Length > 0 && GenerationEnvironment.ToString().Trim().Length == 0) - GenerationEnvironment.Length = 0; - - WriteComment(this, "---------------------------------------------------------------------------------------------------"); - WriteComment(this, " "); - WriteComment(this, " This code was generated by T4Model template for T4 (https://github.com/linq2db/linq2db)."); - WriteComment(this, " Changes to this file may cause incorrect behavior and will be lost if the code is regenerated."); - WriteComment(this, " "); - WriteComment(this, "---------------------------------------------------------------------------------------------------"); - - WriteLine(""); - WriteLine("#pragma warning disable 1591"); - WriteLine(""); - - BeforeGenerateModel(); - - Model.Render(this); - - WriteLine(""); - WriteLine("#pragma warning restore 1591"); - -} - -void Trim() -{ - var arr = new[] { '\r', '\n', ' ' }; - while (GenerationEnvironment.Length > 0 && arr.Contains(GenerationEnvironment[GenerationEnvironment.Length - 1])) - GenerationEnvironment.Length--; - - WriteLine(""); -} - -static Action WriteUsing = (tt,s) => tt.WriteLine("using {0};", s); - -void RenderUsings(List usings) -{ - var q = - from ns in usings.Distinct() - group ns by ns.Split('.')[0]; - - var groups = - (from ns in q where ns.Key == "System" select ns).Concat - (from ns in q where ns.Key != "System" orderby ns.Key select ns); - - foreach (var gr in groups) - { - foreach (var ns in from s in gr orderby s select s) - WriteUsing(this, ns); - - WriteLine(""); - } - - Trim(); -} - -// Base data types. -// -public interface ITree -{ - ITree Parent { get; set; } - IEnumerable GetNodes(); - void SetTree(); -} - -ModelSource Model = new ModelSource(); - -public partial class ModelSource : ITree -{ - public int CurrentNamespace = 0; - - public List Usings = new List { "System" }; - public List Namespaces = new List { new Namespace() }; - - public Namespace Namespace { get { return Namespaces[CurrentNamespace]; } } - public List Types { get { return Namespaces[CurrentNamespace].Types; } } - - public virtual void Render(GeneratedTextTransformation tt) - { - tt.RenderUsings(Usings); - tt.WriteLine(""); - - foreach (var nm in Namespaces) - { - nm.Render(tt); - tt.WriteLine(""); - } - - tt.Trim(); - } - - public ITree Parent { get; set; } - public IEnumerable GetNodes() { return Namespaces; } - - public void SetTree() - { - foreach (var ch in GetNodes()) - { - ch.Parent = this; - ch.SetTree(); - } - } -} - -static Action WriteBeginNamespace = (tt,s) => { tt.WriteLine("namespace {0}", s); tt.WriteLine("{"); }; -static Action WriteEndNamespace = tt => tt.WriteLine("}"); - -public partial class Namespace : ITree -{ - public string Name; - public List Types = new List(); - public List Usings = new List(); - - public virtual void Render(GeneratedTextTransformation tt) - { - if (!string.IsNullOrEmpty(Name)) - { - WriteBeginNamespace(tt, Name); - tt.PushIndent("\t"); - } - - tt.RenderUsings(Usings); - - foreach (var t in Types) - { - t.Render(tt); - tt.WriteLine(""); - } - - tt.Trim(); - - if (!string.IsNullOrEmpty(Name)) - { - tt.PopIndent(); - WriteEndNamespace(tt); - } - } - - public ITree Parent { get; set; } - public IEnumerable GetNodes() { return Types; } - - public void SetTree() - { - foreach (var ch in GetNodes()) - { - ch.Parent = this; - ch.SetTree(); - } - } -} - -public interface IClassMember : ITree -{ -} - -public enum AccessModifier -{ - Public, - Protected, - Internal, - Private, - Partial -} - -public abstract partial class TypeBase : IClassMember -{ - public AccessModifier AccessModifier = AccessModifier.Public; - public string Name; - public bool IsPartial = true; - public List Comment = new List(); - public List Attributes = new List(); - public string Conditional; - - public abstract void Render(GeneratedTextTransformation tt); - - protected virtual void BeginConditional(GeneratedTextTransformation tt) - { - if (Conditional != null) - { - tt.RemoveSpace(); - tt.WriteLine("#if " + Conditional); - tt.WriteLine(""); - } - } - - protected virtual void EndConditional(GeneratedTextTransformation tt) - { - if (Conditional != null) - { - tt.RemoveSpace(); - tt.WriteLine(""); - tt.RemoveSpace(); - tt.WriteLine("#endif"); - } - } - - public ITree Parent { get; set; } - public abstract IEnumerable GetNodes(); - public abstract void SetTree (); -} - -static Action WriteBeginClass = (tt,cl) => -{ - tt.Write(cl.AccessModifier.ToString().ToLower() + " "); - if (cl.IsStatic) tt.Write("static "); - if (cl.IsPartial) tt.Write("partial ", cl.Name); - tt.Write("class {0}{1}", cl.Name, cl.GenericArguments.Count > 0 ? $"<{string.Join(", ", cl.GenericArguments)}>" : string.Empty); - - if (!string.IsNullOrEmpty(cl.BaseClass) || cl.Interfaces.Count > 0) - { - var arr = new[] { cl.BaseClass }.Concat(cl.Interfaces) - .Where(n => n != null) - .ToArray(); - - tt.Write(" : "); - tt.Write(string.Join(", ", arr)); - } - - tt.WriteLine(""); - tt.WriteLine("{"); -}; - -static Action WriteEndClass = tt => tt.WriteLine("}"); - -public partial class Class : TypeBase -{ - public string BaseClass; - public List GenericArguments = new List(); - public bool IsStatic = false; - public List Interfaces = new List(); - public List Members = new List(); - - public Class() - { - } - - public Class(string name, params IClassMember[] members) - { - Name = name; - Members.AddRange(members); - } - - public override void Render(GeneratedTextTransformation tt) - { - BeginConditional(tt); - - foreach (var c in Comment) - tt.WriteLine("//" + c); - - if (Attributes.Count > 0) - { - var aa = Attributes.Where(a => !a.IsSeparated).ToList(); - - if (aa.Count > 0) - { - tt.Write("["); - - for (var i = 0; i < aa.Count; i++) - { - if (i > 0) SkipSpacesAndInsert(tt, ", "); - aa[i].Render(tt); - } - - tt.WriteLine("]"); - } - - aa = Attributes.Where(a => a.IsSeparated).ToList(); - - foreach (var a in aa) - { - tt.Write("["); - a.Render(tt); - tt.WriteLine("]"); - } - } - - WriteBeginClass(tt, this); - tt.PushIndent("\t"); - - foreach (var cm in Members) - { - if (cm is MemberBase) - { - var m = (MemberBase)cm; - - if (!(m is MemberGroup)) - m.BeginConditional(tt, false); - - foreach (var c in m.Comment) - WriteComment(tt, c); - - if (m.Attributes.Count > 0) - { - var q = - from a in m.Attributes - group a by a.Conditional ?? ""; - - foreach (var g in q) - { - if (g.Key.Length > 0) - { - tt.RemoveSpace(); - tt.WriteLine("#if " + g.Key); - } - - var attrs = g.ToList(); - - tt.Write("["); - - for (var i = 0; i < attrs.Count; i++) - { - if (i > 0) SkipSpacesAndInsert(tt, ", "); - attrs[i].Render(tt); - } - - tt.WriteLine("]"); - - if (g.Key.Length > 0) - { - tt.RemoveSpace(); - tt.WriteLine("#endif"); - } - } - } - - m.Render(tt, false); - if (m.InsertBlankLineAfter) - tt.WriteLine(""); - - if (!(m is MemberGroup)) - m.EndConditional(tt, false); - } - else if (cm is TypeBase) - { - var t = (TypeBase)cm; - - t.Render(tt); - tt.WriteLine(""); - } - } - - tt.Trim(); - - tt.PopIndent(); - WriteEndClass(tt); - - EndConditional(tt); - } - - public override IEnumerable GetNodes() - { - return Members; - } - - public override void SetTree() - { - foreach (var ch in GetNodes()) - { - ch.Parent = this; - ch.SetTree(); - } - } -} - -public abstract partial class MemberBase : IClassMember -{ - public string ID; - public AccessModifier AccessModifier = AccessModifier.Public; - public string Name; - public Func TypeBuilder; - public List Comment = new List(); - public string EndLineComment; - public List Attributes = new List(); - public bool InsertBlankLineAfter = true; - public string Conditional; - - public int AccessModifierLen; - public int ModifierLen; - public int TypeLen; - public int NameLen; - public int ParamLen; - public int BodyLen; - - public string Type - { - get { return TypeBuilder?.Invoke(); } - set { TypeBuilder = () => value; } - } - - public string BuildType() { return TypeBuilder?.Invoke(); } - - public virtual int CalcModifierLen() { return 0; } - public abstract int CalcBodyLen (); - public virtual int CalcParamLen () { return 0; } - public abstract void Render (GeneratedTextTransformation tt, bool isCompact); - - public virtual void BeginConditional(GeneratedTextTransformation tt, bool isCompact) - { - if (Conditional != null) - { - tt.RemoveSpace(); - tt.WriteLine("#if " + Conditional); - if (!isCompact) - tt.WriteLine(""); - } - } - - public virtual void EndConditional(GeneratedTextTransformation tt, bool isCompact) - { - if (Conditional != null) - { - tt.RemoveSpace(); - tt.WriteLine("#endif"); - if (!isCompact) - tt.WriteLine(""); - } - } - - public ITree Parent { get; set; } - public virtual IEnumerable GetNodes() { return Enumerable.Empty(); } - public virtual void SetTree () {} -} - -static Action BeginRegion = (tt,s) => { tt.WriteLine("#region {0}", s); }; -static Action EndRegion = (tt) => { tt.WriteLine("#endregion"); }; - -public partial class MemberGroup : MemberBase -{ - public string Region; - public bool IsCompact; - public bool IsPropertyGroup; - public List Members = new List(); - public List Errors = new List(); - - public override int CalcBodyLen() { return 0; } - - public override void Render(GeneratedTextTransformation tt, bool isCompact) - { - if (!string.IsNullOrEmpty(Region)) - { - BeginRegion(tt, Region); - tt.WriteLine(""); - } - - BeginConditional(tt, isCompact); - - if (Errors.Count > 0 && tt.GenerateProcedureErrors) - { - tt.RemoveSpace(); - WriteComment(tt, " Use 'GenerateProcedureErrors=false' to disable errors."); - foreach (var error in Errors) - { - tt.Error(error); - - foreach (var e in error.Split('\n')) - { - tt.RemoveSpace(); - tt.WriteLine("#error " + e.Trim('\r')); - } - } - - tt.WriteLine(""); - } - - if (IsCompact) - { - var allMembers = GetTreeNodes(this).OfType().Where(m => !(m is MemberGroup)).ToList(); - - if (allMembers.Count > 0) - { - int max = allMembers.Max(m => m.AccessModifier.ToString().Length); - foreach (var m in allMembers) - m.AccessModifierLen = max; - - max = allMembers.Max(m => m.CalcModifierLen()); - foreach (var m in allMembers) - m.ModifierLen = max; - - max = allMembers.Max(m => (m.BuildType() ?? "").Length); - foreach (var m in allMembers) - m.TypeLen = max; - - var notHasGetter = allMembers.OfType().Any(m => m.IsAuto && !m.HasGetter); - var notHasSetter = allMembers.OfType().Any(m => m.IsAuto && !m.HasSetter); - - foreach (var p in allMembers.OfType()) - { - if (notHasGetter) p.GetterLen = 13; - if (notHasSetter) p.SetterLen = 13; - } - - max = allMembers.Max(m => m.Name.Length); - foreach (var m in allMembers) - m.NameLen = max; - - max = allMembers.Max(m => m.CalcParamLen()); - foreach (var m in allMembers) - m.ParamLen = max; - - max = allMembers.Max(m => m.CalcBodyLen()); - foreach (var m in allMembers) - m.BodyLen = max; - - var members = - ( - from m in allMembers - select new - { - m, - attrs = - ( - from a in m.Attributes - group a by a.Name into gr - select gr.Select((a,i) => new { a, name = a.Name + "." + i }).ToList() into s - from a in s - select a - ).ToList() - } - ).ToList(); - - var attrWeight = - ( - from m in members - from a in m.attrs - group a by a.name into gr - select new { gr.Key, Count = gr.Count() } - ).ToDictionary(a => a.Key, a => a.Count); - - var q = - from m in members - where m.attrs.Count > 0 - select new { m, w = m.attrs.Sum(aa => attrWeight[aa.name]) } into m - orderby m.w descending - select m.m; - - var attrs = new List(); - - foreach (var m in q) - { - var list = m.attrs.Select(a => a.name).ToList(); - - if (attrs.Count == 0) - attrs.AddRange(list); - else - { - for (var i = 0; i < list.Count; i++) - { - var nm = list[i]; - - if (!attrs.Contains(nm)) - { - for (var j = i + 1; j < list.Count; j++) - { - var idx = attrs.IndexOf(list[j]); - - if (idx >= 0) - { - attrs.Insert(idx, nm); - break; - } - } - } - - if (!attrs.Contains(nm)) - attrs.Add(nm); - } - } - } - - var mms = members.Select(m => - { - var arr = new Attribute[attrs.Count]; - - foreach (var a in m.attrs) - arr[attrs.IndexOf(a.name)] = a.a; - - return new { m.m, attrs = arr.ToList() }; - }).ToList(); - - var idxs = Enumerable.Range(0, attrs.Count).Select(_ => new List()).ToList(); - - for (var i = 0; i < mms.Count; i++) - for (var j = 0; j < mms[i].attrs.Count; j++) - if (mms[i].attrs[j] != null) - idxs[j].Add(i); - - var toRemove = new List(); - - for (int i = 1; i < idxs.Count; i++) - { - for (int j = 0; j < i; j++) - { - if (idxs[j] == null) - continue; - - if (idxs[i].Intersect(idxs[j]).Count() == 0) - { - foreach (var m in mms) - { - if (m.attrs[i] != null) - { - m.attrs[j] = m.attrs[i]; - m.attrs[i] = null; - } - } - - idxs[j].AddRange(idxs[i]); - idxs[i] = null; - toRemove.Add(i); - break; - } - } - - } - - foreach (var n in toRemove.OrderByDescending(i => i)) - foreach (var m in mms) - m.attrs.RemoveAt(n); - - var lens = new int[attrs.Count - toRemove.Count]; - - foreach (var m in mms) - { - for (var i = 0; i < m.attrs.Count; i++) - { - var a = m.attrs[i]; - - if (a != null) - { - var len = a.Name.Length; - - if (a.Parameters.Count >= 0) - len += a.Parameters.Sum(p => 2 + p.Length); - - lens[i] = Math.Max(lens[i], len); - } - } - } - - foreach (var m in allMembers) - { - if (!(m is MemberGroup)) - m.BeginConditional(tt, IsCompact); - - foreach (var c in m.Comment) - WriteComment(tt, c); - - if (attrs.Count > 0) - { - var ma = mms.First(mr => mr.m == m); - - if (m.Attributes.Count > 0) - { - tt.Write("["); - - for (var i = 0; i < ma.attrs.Count; i++) - { - var a = ma.attrs[i]; - - if (a == null) - { - tt.WriteSpaces(lens[i]); - if (i + 1 < ma.attrs.Count) - tt.Write(" "); - } - else - { - var len = tt.GenerationEnvironment.Length; - a.Render(tt); - len = (tt.GenerationEnvironment.Length - len); - - var commaAdded = false; - - for (var j = i + 1; j < ma.attrs.Count; j++) - { - if (ma.attrs[j] != null) - { - SkipSpacesAndInsert(tt, ", "); - commaAdded = true; - break; - } - } - - if (i + 1 < ma.attrs.Count && !commaAdded) - tt.Write(" "); - - tt.WriteSpaces(lens[i] - len); - } - } - - tt.Write("] "); - } - else - { - tt.WriteSpaces(lens.Sum() + ma.attrs.Count * 2 + 1); - } - } - - m.Render(tt, true); - - if (!IsCompact) - tt.WriteLine(""); - - if (!(m is MemberGroup)) - m.EndConditional(tt, IsCompact); - } - } - } - else - { - foreach (var cm in Members) - { - if (cm is MemberBase) - { - var m = (MemberBase)cm; - - if (!(m is MemberGroup)) - m.BeginConditional(tt, IsCompact); - - foreach (var c in m.Comment) - WriteComment(tt, c); - - if (m.Attributes.Count > 0) - { - var q = - from a in m.Attributes - group a by a.Conditional ?? ""; - - foreach (var g in q) - { - if (g.Key.Length > 0) - { - tt.RemoveSpace(); - tt.WriteLine("#if " + g.Key); - } - - var attrs = g.ToList(); - - var aa = attrs.Where(a => !a.IsSeparated).ToList(); - - if (aa.Count > 0) - { - tt.Write("["); - - for (var i = 0; i < aa.Count; i++) - { - if (i > 0) tt.Write(", "); - aa[i].Render(tt); - } - - tt.WriteLine("]"); - } - - aa = attrs.Where(a => a.IsSeparated).ToList(); - - foreach (var a in aa) - { - tt.Write("["); - a.Render(tt); - tt.WriteLine("]"); - } - - if (g.Key.Length > 0) - { - tt.RemoveSpace(); - tt.WriteLine("#endif"); - } - } - } - - m.Render(tt, false); - - if (m.InsertBlankLineAfter) - tt.WriteLine(""); - - if (!(m is MemberGroup)) - m.EndConditional(tt, IsCompact); - } - else if (cm is TypeBase) - { - var t = (TypeBase)cm; - - t.Render(tt); - tt.WriteLine(""); - } - } - } - - tt.Trim(); - - EndConditional(tt, isCompact); - - if (!string.IsNullOrEmpty(Region)) - { - tt.WriteLine(""); - EndRegion(tt); - } - } - - public override IEnumerable GetNodes() { return Members; } - - public override void SetTree() - { - foreach (var ch in GetNodes()) - { - ch.Parent = this; - ch.SetTree(); - } - } -} - -static Action WriteField = (tt,f) => -{ - var am = f.AccessModifier.ToString().ToLower(); - var mdf = - (f.IsStatic ? " static" : "") + - (f.IsReadonly ? " readonly" : "") ; - - tt.Write("{0}{1}{2}{3} {4}{5} {6}", - am, LenDiff(f.AccessModifierLen, am), - mdf, LenDiff(f.ModifierLen, mdf), - f.BuildType(), LenDiff(f.TypeLen, f.BuildType()), - f.Name); - - if (f.InitValue != null) - { - tt.Write(" = {0}", f.InitValue); - } - - tt.Write(";"); - - if (!string.IsNullOrEmpty(f.EndLineComment)) - { - tt.WriteSpaces(f.NameLen - f.Name.Length + f.BodyLen + f.ParamLen - 1); - tt.Write(" "); - WriteComment(tt, " " + f.EndLineComment); - } - else - tt.WriteLine(""); -}; - -public partial class Field : MemberBase -{ - public bool IsStatic; - public bool IsReadonly; - public string InitValue; - - public Field() - { - } - - public Field(Func typeBuilder, string name) - { - TypeBuilder = typeBuilder; - Name = name; - } - - public override int CalcModifierLen() - { - return - (IsStatic ? " static". Length : 0) + - (IsReadonly ? " readonly".Length : 0) ; - } - - public override int CalcBodyLen() { return InitValue == null ? 1 : 4 + InitValue.Length; } - - public override void Render(GeneratedTextTransformation tt, bool isCompact) - { - WriteField(tt, this); - } -} - -static Action WriteEvent = (tt,m) => -{ - var am = m.AccessModifier.ToString().ToLower(); - var mdf = - (m.IsStatic ? " static" : "") + - (m.IsVirtual ? " virtual" : "") + - " event"; - - tt.Write("{0}{1}{2}{3} {4}{5} {6};", - am, LenDiff(m.AccessModifierLen, am), - mdf, LenDiff(m.ModifierLen, mdf), - m.BuildType(), LenDiff(m.TypeLen, m.BuildType()), - m.Name); - - if (!string.IsNullOrEmpty(m.EndLineComment)) - { - tt.WriteSpaces(m.NameLen - m.Name.Length + m.BodyLen + m.ParamLen - 1); - tt.Write(" "); - WriteComment(tt, " " + m.EndLineComment); - } - else - tt.WriteLine(""); -}; - -public partial class Event : MemberBase -{ - public bool IsStatic; - public bool IsVirtual; - - public Event() - { - } - - public Event(Func typeBuilder, string name) - { - TypeBuilder = typeBuilder; - Name = name; - } - - public override int CalcModifierLen() - { - return - (IsStatic ? " static". Length : 0) + - (IsVirtual ? " virtual".Length : 0) + - " event".Length; - } - - public override int CalcBodyLen() { return 1; } - - public override void Render(GeneratedTextTransformation tt, bool isCompact) - { - WriteEvent(tt, this); - } -} - -static Action WriteProperty = (tt,p,compact) => -{ - var am = p.AccessModifier.ToString().ToLower(); -// var mdf = p.IsVirtual ? " virtual" : ""; - var mdf = p.IsAbstract ? " abstract" : p.IsVirtual ? " virtual" : p.IsOverride ? " override" : p.IsStatic ? " static" : ""; - - tt.Write("{0}{1}{2}{3} {4}{5} {6}", - am, LenDiff(p.AccessModifierLen, am), - mdf, LenDiff(p.ModifierLen, mdf), - p.BuildType(), LenDiff(p.TypeLen, p.BuildType()), - p.Name); - - Action writeComment = () => - { - if (!string.IsNullOrEmpty(p.EndLineComment)) - { - tt.Write(" "); - WriteComment(tt, " " + p.EndLineComment); - } - else - tt.WriteLine(""); - }; - - if (p.IsAuto) - { - tt.Write(LenDiff(p.NameLen + p.ParamLen, p.Name)); - - var len = tt.GenerationEnvironment.Length; - - tt.Write(" { "); - - if (!p.HasGetter) - tt.Write("private "); - else if (p.GetterLen == 13) - tt.Write(" "); - tt.Write("get; "); - - if (!p.HasSetter) - tt.Write("private "); - else if (p.SetterLen == 13) - tt.Write(" "); - tt.Write("set; "); - - tt.Write("}"); - - if (!string.IsNullOrEmpty(p.EndLineComment)) - tt.WriteSpaces(p.BodyLen - (tt.GenerationEnvironment.Length - len)); - writeComment(); - } - else - { - if (compact) - { - tt.Write(LenDiff(p.NameLen + p.ParamLen, p.Name)); - - var len = tt.GenerationEnvironment.Length; - - tt.Write(" { "); - - if (p.HasGetter) - { - tt.Write("get { "); - foreach (var t in p.BuildGetBody()) - tt.Write("{0} ", t); - tt.Write("} "); - } - - if (p.HasSetter) - { - tt.Write("set { "); - foreach (var t in p.BuildSetBody()) - tt.Write("{0} ", t); - tt.Write("} "); - } - - tt.Write("}"); - - if (!string.IsNullOrEmpty(p.EndLineComment)) - tt.WriteSpaces(p.BodyLen - (tt.GenerationEnvironment.Length - len)); - writeComment(); - } - else - { - writeComment(); - - tt.WriteLine("{"); - tt.PushIndent("\t"); - - if (p.HasGetter) - { - var getBody = p.BuildGetBody().ToArray(); - if (getBody.Length == 1) - { - tt.WriteLine("get {{ {0} }}", getBody[0]); - } - else - { - tt.WriteLine("get"); - tt.WriteLine("{"); - tt.PushIndent("\t"); - - foreach (var t in getBody) - tt.WriteLine(t); - - tt.PopIndent(); - tt.WriteLine("}"); - } - } - - if (p.HasSetter) - { - var setBody = p.BuildSetBody().ToArray(); - if (setBody.Length == 1) - { - tt.WriteLine("set {{ {0} }}", setBody[0]); - } - else - { - tt.WriteLine("set"); - tt.WriteLine("{"); - tt.PushIndent("\t"); - - foreach (var t in setBody) - tt.WriteLine(t); - - tt.PopIndent(); - tt.WriteLine("}"); - } - } - - tt.PopIndent(); - tt.WriteLine("}"); - } - } -}; - -public partial class Property : MemberBase -{ - public bool IsAuto = true; - public string InitValue; - public bool IsVirtual; - public bool IsOverride; - public bool IsAbstract; - public bool IsStatic; - public bool HasGetter = true; - public bool HasSetter = true; - public List>> GetBodyBuilders = new List>>(); - public List>> SetBodyBuilders = new List>>(); - - public int GetterLen = 5; - public int SetterLen = 5; - - public Property() - { - } - - public Property(Func typeBuilder, string name, Func> getBodyBuilder = null, Func> setBodyBuilder = null) - { - TypeBuilder = typeBuilder; - Name = name; - - InitBody(getBodyBuilder, setBodyBuilder); - } - - public override int CalcModifierLen() - { - return IsVirtual ? " virtual".Length : 0; - } - - public override int CalcBodyLen() - { - if (IsAuto) - return 4 + GetterLen + SetterLen; // ' { get; set; }' - - var len = " {".Length; - - if (HasGetter) - { - len += " get {".Length; - foreach (var t in BuildGetBody()) - len += 1 + t.Length; - len += " }".Length; - } - - if (HasSetter) - { - len += " set {".Length; - foreach (var t in BuildSetBody()) - len += 1 + t.Length; - len += " }".Length; - } - - len += " }".Length; - - return len; - } - - public override void Render(GeneratedTextTransformation tt, bool isCompact) - { - if (!IsAuto && HasGetter) - { - var getBody = BuildGetBody().ToArray(); - if (getBody.Length == 1) - { - var t = getBody[0]; - - if (!t.StartsWith("return")) - { - t = "return " + t; - - if (!t.EndsWith(";")) - t += ";"; - - GetBodyBuilders.Clear(); - GetBodyBuilders.Add(() => new [] { t }); - } - } - } - - WriteProperty(tt, this, isCompact); - } - - public Property InitBody(Func> getBodyBuilder = null, Func> setBodyBuilder = null) - { - IsAuto = getBodyBuilder == null && setBodyBuilder == null; - - if (getBodyBuilder != null) GetBodyBuilders.Add(getBodyBuilder); - if (setBodyBuilder != null) SetBodyBuilders.Add(setBodyBuilder); - - if (!IsAuto) - { - HasGetter = getBodyBuilder != null; - HasSetter = setBodyBuilder != null; - } - - return this; - } - - public Property InitGetter(Func> getBodyBuilder) - { - return InitBody(getBodyBuilder, null); - } - - public IEnumerable BuildGetBody() - { - return GetBodyBuilders.SelectMany(builder => builder?.Invoke() ?? Array.Empty()); - } - - public IEnumerable BuildSetBody() - { - return SetBodyBuilders.SelectMany(builder => builder?.Invoke() ?? Array.Empty()); - } -} - -static Action WriteMethod = (tt,m,compact) => -{ - var am1 = m.AccessModifier.ToString().ToLower(); - var len1 = m.AccessModifierLen; - var am2 = ""; - var len2 = 0; - var mdf = m.IsAbstract ? " abstract" : m.IsVirtual ? " virtual" : m.IsOverride ? " override" : m.IsStatic ? " static" : ""; - var mlen = m.ModifierLen; - - if (am1 == "partial" && mdf.Length > 0) - { - am2 = " " + am1; len2 = len1 + 1; - am1 = ""; len1 = 0; - mdf = mdf.Trim(); - mlen--; - } - - tt.Write("{0}{1}{2}{3}{4}{5}{6}{7}{8} {9}{10}", - am1, LenDiff(len1, am1), - mdf, LenDiff(mlen, mdf), - am2, LenDiff(len2, am2), - m.BuildType() == null ? "" : " ", - m.BuildType(), LenDiff(m.TypeLen, m.BuildType() ?? ""), - m.Name, - m.GenericArguments.Count > 0 ? $"<{string.Join(", ", m.GenericArguments)}>" : string.Empty); - - Action writeComment = () => - { - if (!string.IsNullOrEmpty(m.EndLineComment)) - { - tt.Write(" "); - WriteComment(tt, " " + m.EndLineComment); - } - else - tt.WriteLine(""); - }; - - Action writeParams = () => - { - tt.Write("("); - - for (int i = 0; i < m.ParameterBuilders.Count; i++) - { - if (i > 0) - tt.Write(", "); - tt.Write(m.ParameterBuilders[i]()); - } - - tt.Write(")"); - }; - - if (compact) - { - tt.Write(LenDiff(m.NameLen, m.Name)); - - var len = tt.GenerationEnvironment.Length; - - writeParams(); - - foreach (var s in m.AfterSignature) - { - tt.Write(" "); - tt.Write(s); - } - - len = tt.GenerationEnvironment.Length - len; - - if (m.IsAbstract || m.AccessModifier == AccessModifier.Partial) - { - tt.Write(";"); - len = 0; - } - else - { - tt.WriteSpaces(m.ParamLen - len); - - len = tt.GenerationEnvironment.Length; - - tt.Write(" {"); - - foreach (var t in m.BuildBody()) - tt.Write(" {0}", t); - - tt.Write(" }"); - } - - if (!string.IsNullOrEmpty(m.EndLineComment)) - tt.WriteSpaces(m.BodyLen - (tt.GenerationEnvironment.Length - len)); - writeComment(); - } - else - { - writeParams (); - writeComment(); - - tt.PushIndent("\t"); - foreach (var s in m.AfterSignature) - tt.WriteLine(s); - tt.PopIndent(); - - tt.WriteLine("{"); - tt.PushIndent("\t"); - - foreach (var t in m.BuildBody()) - { - if (t.Length > 1 && t[0] == '#') - { - tt.RemoveSpace(); - } - - tt.WriteLine(t); - } - - tt.PopIndent(); - tt.WriteLine("}"); - } -}; - -public partial class Method : MemberBase -{ - public bool IsAbstract; - public bool IsVirtual; - public bool IsOverride; - public bool IsStatic; - public List GenericArguments = new List(); - public List AfterSignature = new List(); - public List> ParameterBuilders = new List>(); - public List>> BodyBuilders = new List>>(); - - public Method() - { - } - - public Method(Func typeBuilder, string name, IEnumerable> parameterBuilders = null, params Func>[] bodyBuilders) - { - TypeBuilder = typeBuilder; - Name = name; - - if (parameterBuilders != null) ParameterBuilders.AddRange(parameterBuilders); - if (bodyBuilders != null) BodyBuilders.AddRange(bodyBuilders); - } - - public static Method Create(string type, string name, IEnumerable parameters = null, IEnumerable body = null) - { - return new Method( - () => type, - name, - parameters?.Select>((string p) => () => p), - body?.Select>>(p => () => new[] { p }).ToArray()); - } - - public IEnumerable BuildBody() - { - return BodyBuilders.SelectMany(builder => builder?.Invoke() ?? Array.Empty()); - } - - public override int CalcModifierLen() - { - return - IsAbstract ? " abstract".Length : - IsVirtual ? " virtual".Length : - IsStatic ? " static".Length : 0; - } - - public override int CalcBodyLen() - { - if (IsAbstract || AccessModifier == AccessModifier.Partial) - return 1; - - var len = " {".Length; - - foreach (var t in BuildBody()) - len += 1 + t.Length; - - len += " }".Length; - - return len; - } - - public override int CalcParamLen() - { - return ParameterBuilders.Sum(p => p().Length + 2); - } - - public override void Render(GeneratedTextTransformation tt, bool isCompact) - { - WriteMethod(tt, this, isCompact); - } -} - -static Action WriteAttribute = (tt,a) => -{ - tt.Write(a.Name); - - if (a.Parameters.Count > 0) - { - tt.Write("("); - - for (var i = 0; i < a.Parameters.Count; i++) - { - if (i > 0) - if (a.Parameters[i - 1].All(c => c == ' ')) - tt.Write(" "); - else - SkipSpacesAndInsert(tt, ", "); - tt.Write(a.Parameters[i]); - } - - SkipSpacesAndInsert(tt, ")"); - } -}; - -public partial class Attribute -{ - public string Name; - public List Parameters = new List(); - public string Conditional; - public bool IsSeparated; - - public Attribute() - { - } - - public Attribute(string name, params string[] ps) - { - Name = name; - Parameters.AddRange(ps); - } - - public virtual void Render(GeneratedTextTransformation tt) - { - WriteAttribute(tt, this); - } -} - -// Helpers. -// - -Func ToPlural = s => s + "s"; -Func ToSingular = s => s; - -static string LenDiff(int max, string str) -{ - var s = ""; - - while (max-- > str.Length) - s += " "; - - return s; -} - -public void WriteSpaces(int len) -{ - while (len-- > 0) - Write(" "); -} - -void RemoveSpace() -{ - Write(" "); - - while (GenerationEnvironment.Length > 0 && - (GenerationEnvironment[GenerationEnvironment.Length - 1] == ' ' || - GenerationEnvironment[GenerationEnvironment.Length - 1] == '\t')) - GenerationEnvironment.Length--; -} - -public static IEnumerable GetTreeNodes(ITree parent) -{ - foreach (var node in parent.GetNodes()) - { - yield return node; - - foreach (var grandNode in GetTreeNodes(node)) - yield return grandNode; - } -} - -public static ITree FindNode(ITree parent, Func func) -{ - foreach (var node in parent.GetNodes()) - { - if (func(node)) - return node; - - var n = FindNode(node, func); - - if (n != null) - return n; - } - - return null; -} - -static void SkipSpacesAndInsert(GeneratedTextTransformation tt, string value) -{ - var l = tt.GenerationEnvironment.Length; - - for (; l > 0 && tt.GenerationEnvironment[l - 1] == ' '; l--) - { - } - - tt.GenerationEnvironment.Insert(l, value); -} - - -string ToCamelCase(string name) -{ - var n = 0; - - foreach (var c in name) - { - if (char.IsUpper(c)) - n++; - else - break; - } - - if (n == 0) - return name; - - if (n == name.Length) - return name.ToLower(); - - n = Math.Max(1, n - 1); - - return name.Substring(0, n).ToLower() + name.Substring(n); -} - -event Action SetPropertyValueAction; - -void SetPropertyValue(Property propertyObject, string propertyName, object value) -{ - if (SetPropertyValueAction != null) - SetPropertyValueAction(propertyObject, propertyName, value); -} - -static string ToStringLiteral(string value) -{ - if (value == null) - return "null"; - - var sb = new StringBuilder("\""); - - foreach (var chr in value) - { - switch (chr) - { - case '\t': sb.Append("\\t"); break; - case '\n': sb.Append("\\n"); break; - case '\r': sb.Append("\\r"); break; - case '\\': sb.Append("\\\\"); break; - case '"' : sb.Append("\\\""); break; - case '\0': sb.Append("\\0"); break; - case '\u0085': - case '\u2028': - case '\u2029': - sb.Append($"\\u{(ushort)chr:X4}"); break; - default: sb.Append(chr); break; - } - } - - sb.Append('"'); - - return sb.ToString(); -} - -#> diff --git a/BillsManager.Services/LinqToDB.Templates/Validation.ttinclude b/BillsManager.Services/LinqToDB.Templates/Validation.ttinclude deleted file mode 100644 index 45a7e84..0000000 --- a/BillsManager.Services/LinqToDB.Templates/Validation.ttinclude +++ /dev/null @@ -1,189 +0,0 @@ -<# - { - var beforeGenerateModel = BeforeGenerateModel; - BeforeGenerateModel = () => - { - beforeGenerateModel(); - ValidationImpl(); - }; - } -#> -<#+ -void ValidationImpl() -{ - foreach (Class cl in GetTreeNodes(Model).OfType()) - { - var validationGroup = new MemberGroup - { - Region = "Validation", - }; - - var props = GetTreeNodes(cl).OfType().Where(p => p.CustomValidation).ToList(); - - if (props.Count > 0) - { - if (!Model.Usings.Contains("System.Collections.Generic")) - Model.Usings.Add("System.Collections.Generic"); - - var isValid = new Method(() => "bool", "IsValid", new Func[] { () => cl.Name + " obj" }) { IsStatic = true }; - var validator = new Class("CustomValidator", isValid) { IsStatic = true, }; - var partialGroup = new MemberGroup { IsCompact = true }; - - validationGroup.Members.Add(new Field(() => "int", "_isValidCounter") { Attributes = { new Attribute("field : NonSerialized") { Conditional = "!SILVERLIGHT" } } }); - validationGroup.Members.Add(validator); - validationGroup.Members.Add(partialGroup); - - isValid.BodyBuilders.Add(() => new [] - { - "try", - "{", - "\tobj._isValidCounter++;", - "" - }); - - var ret = "\treturn "; - - for (var idx = 0; idx < props.Count; idx++) - { - var i = idx; - var p = props[i]; - - var name = p.Name.Trim(); - var mname = "Validate" + name; - - cl.Attributes.Add( - new Attribute("CustomValidation", - "typeof(" + cl.Name + ".CustomValidator)", - ToStringLiteral(mname)) - { - IsSeparated = true - }); - - isValid.BodyBuilders.Add(() => new [] { - "\tvar flag" + i + " = ValidationResult.Success == " + mname + "(obj, obj." + name + ");" }); - - ret += (i == 0 ? "" : " || ") + "flag" + i; - - var validate = new Method(() => "ValidationResult", mname, - new Func[] { () => cl.Name + " obj", () => p.BuildType().Trim() + " value" }) { IsStatic = true }; - - validate.BodyBuilders.Add(() => new [] - { - "var list = new List();", - "", - "Validator.TryValidateProperty(", - "\tvalue,", - "\tnew ValidationContext(obj, null, null) { MemberName = NameOf" + name + " }, list);", - "", - "obj." + mname + "(value, list);", - "", - "if (list.Count > 0)", - "{", - "\tforeach (var result in list)", - "\t\tforeach (var name in result.MemberNames)", - "\t\t\tobj.AddError(name, result.ErrorMessage);", - "", - "\treturn list[0];", - "}", - "", - "obj.RemoveError(NameOf" + name + ");", - "", - "return ValidationResult.Success;" - }); - - validator.Members.Add(validate); - - partialGroup.Members.Add(new Method( - () => "void", - mname, - new Func[] - { - () => p.BuildType().Trim() + " value", - () => "List validationResults", - }) - { - AccessModifier = AccessModifier.Partial, - }); - } - - isValid.BodyBuilders.Add(() => new [] - { - "", - ret + ";", - "}", - "finally", - "{", - "\tobj._isValidCounter--;", - "}" - }); - } - - props = GetTreeNodes(cl).OfType().Where(p => p.ValidateProperty && p.HasSetter).ToList(); - - if (props.Count > 0) - { - foreach (var p in props) - { - var setBody = p.BuildSetBody().ToList(); - if (setBody.Count > 0) - setBody.Insert(0, ""); - - setBody.Insert(0, "if (_validationLockCounter == 0)"); - setBody.Insert(1, "{"); - - if (p.CustomValidation) - { - setBody.Insert(2, "\tvar validationResult = CustomValidator.Validate" + p.Name.Trim() + "(this, value);"); - setBody.Insert(3, "\tif (validationResult != ValidationResult.Success)"); - setBody.Insert(4, "\t\tthrow new ValidationException(validationResult, null, null);"); - setBody.Insert(5, "}"); - } - else - { - setBody.Insert(2, "\tValidator.ValidateProperty("); - setBody.Insert(3, "\t\tvalue,"); - setBody.Insert(4, string.Format("\t\tnew ValidationContext(this, null, null) {{ MemberName = NameOf{0} }});", p.Name.Trim())); - setBody.Insert(5, "}"); - } - - p.SetBodyBuilders.Clear(); - p.SetBodyBuilders.Add(() => setBody.ToArray()); - } - - validationGroup.Members.Add(new Field(() => "int", "_validationLockCounter") - { - AccessModifier = AccessModifier.Private, - InitValue = "0", - Attributes = { new Attribute("field : NonSerialized") { Conditional = "!SILVERLIGHT" } } - }); - - validationGroup.Members.Add(new Method (() => "void", "LockValidation", null, () => new[] { "_validationLockCounter++;" })); - validationGroup.Members.Add(new Method (() => "void", "UnlockValidation", null, () => new[] { "_validationLockCounter--;" })); - } - - if (validationGroup.Members.Count > 0) - { - if (!Model.Usings.Contains("System.ComponentModel.DataAnnotations")) - Model.Usings.Add("System.ComponentModel.DataAnnotations"); - - cl.Members.Add(validationGroup); - cl.SetTree(); - } - } -} - -partial class Property -{ - public bool CustomValidation; - public bool ValidateProperty; - - public bool Validate - { - set - { - CustomValidation = value; - ValidateProperty = value; - } - } -} -#> diff --git a/BillsManager.Services/Properties/AssemblyInfo.cs b/BillsManager.Services/Properties/AssemblyInfo.cs deleted file mode 100644 index 1fdf562..0000000 --- a/BillsManager.Services/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// Le informazioni generali relative a un assembly sono controllate dal seguente -// set di attributi. Per modificare le informazioni associate a un assembly -// occorre quindi modificare i valori di questi attributi. -[assembly: AssemblyTitle("BillsManager.Services")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BillsManager.Services")] -[assembly: AssemblyCopyright("Copyright © Nalesso Sergio 2013-2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili -// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da -// COM, impostare su true l'attributo ComVisible per tale tipo. -[assembly: ComVisible(false)] - -// Se il progetto viene esposto a COM, il GUID che segue verrà utilizzato per creare l'ID della libreria dei tipi -[assembly: Guid("91a62068-6a75-48fc-9ea5-ea82eea9046f")] - -// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: -// -// Numero di versione principale -// Numero di versione secondario -// Numero build -// Revisione -// -// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build -// utilizzando l'asterisco (*) come descritto di seguito: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BillsManager.Services/Settings/ISettingsService.cs b/BillsManager.Services/Settings/ISettingsService.cs deleted file mode 100644 index 7490ee6..0000000 --- a/BillsManager.Services/Settings/ISettingsService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.Services -{ - public interface ISettingsService - { - Models.Settings Settings { get; } - - bool Save(); - } -} \ No newline at end of file diff --git a/BillsManager.Services/Settings/XMLSettingsService.cs b/BillsManager.Services/Settings/XMLSettingsService.cs deleted file mode 100644 index 88d20c1..0000000 --- a/BillsManager.Services/Settings/XMLSettingsService.cs +++ /dev/null @@ -1,118 +0,0 @@ -using BillsManager.Models; -using System; -using System.Globalization; -using System.IO; -using System.Xml.Linq; - -namespace BillsManager.Services -{ - public class XMLSettingsService : ISettingsService - { - #region fields - - // FILE PATHS - private const string SettingsFileDotExtension = ".bmse"; - private const string SettingsFileNameWithoutExtension = "settings"; - private readonly string settingsFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SettingsFileNameWithoutExtension + SettingsFileDotExtension); - - // NAMESPACES - private const string Namespace_SettingsRoot = "settings"; - private const string Item_StartupDBLoad = "startup_db_load"; - private const string Item_Language = "language"; - private const string Item_FeedbackToEmailAddress = "feedback_to_email_address"; - - // DEFAULT VALUES - private const string Default_Language = "it-IT"; - private const string Default_FeedbackEmailAddressee = "nalessosergio@gmail.com"; - private const bool Default_LoadDbAtStartup = true; - - private readonly XDocument xmlSettings; - - #endregion - - #region ctor - - public XMLSettingsService() - { - if (File.Exists(settingsFilePath)) - this.xmlSettings = this.LoadXSettings(); - else - { - this.xmlSettings = this.CreateDefaultXSettings(); - this.Settings = this.ExtractSettings(this.xmlSettings); - this.Save(); - } - - this.Settings = this.ExtractSettings(this.xmlSettings); - } - - #endregion - - #region properties - - public Models.Settings Settings { get; protected set; } - - #endregion - - #region methods - - protected XDocument LoadXSettings() - { - try - { - return XDocument.Load(settingsFilePath); - } - catch (Exception) - { - return this.CreateDefaultXSettings(); - } - } - - public bool Save() - { - this.xmlSettings.Root.Element(Item_Language).SetValue(this.Settings.Language.Name); - this.xmlSettings.Root.Element(Item_StartupDBLoad).SetValue(this.Settings.StartupDBLoad); - this.xmlSettings.Root.Element(Item_FeedbackToEmailAddress).SetValue(this.Settings.FeedbackToEmailAddress); - - try - { - this.xmlSettings.Save(settingsFilePath); - return true; - } - catch (Exception) - { - return false; - } - } - - protected XDocument CreateDefaultXSettings() - { - var newXMLSetts = new XDocument(); - - newXMLSetts.Declaration = new XDeclaration("1.0", "utf-8", null); - - newXMLSetts.Add( - new XElement(Namespace_SettingsRoot, - new XElement(Item_Language, Default_Language), - new XElement(Item_StartupDBLoad, Default_LoadDbAtStartup), - new XElement(Item_FeedbackToEmailAddress, Default_FeedbackEmailAddressee))); - - return newXMLSetts; - } - - protected Models.Settings ExtractSettings(XDocument XSettings) - { - var ci = CultureInfo.GetCultureInfo(XSettings.Root.Element(Item_Language).Value); - var load = (bool)XSettings.Root.Element(Item_StartupDBLoad); - var toEmAdd = XSettings.Root.Element(Item_FeedbackToEmailAddress).Value; - - return - new Models.Settings( - ci, - load, - toEmAdd); - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Services/packages.config b/BillsManager.Services/packages.config deleted file mode 100644 index 4416ea9..0000000 --- a/BillsManager.Services/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/BillsManager.ViewModels/BillViewModels/BilItemViewModel/BillItemViewModel.cs b/BillsManager.ViewModels/BillViewModels/BilItemViewModel/BillItemViewModel.cs deleted file mode 100644 index 3e84986..0000000 --- a/BillsManager.ViewModels/BillViewModels/BilItemViewModel/BillItemViewModel.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using BillsManager.Model; -using BillsManager.ViewModel.Messages; -using Caliburn.Micro; - -namespace BillsManager.ViewModel -{ - public partial class BillItemViewModel : - BillViewModel - { - #region fields - - private readonly IWindowManager windowManager; - protected readonly IEventAggregator eventAggregator; - - #endregion - - #region ctor - - public BillItemViewModel( - Bill bill, - IWindowManager windowManager, - IEventAggregator eventAggregator) - { - if (bill == null) - throw new ArgumentNullException("bill cannot be null"); - - this.exposedBill = bill; - - this.windowManager = windowManager; - this.eventAggregator = eventAggregator; - - this.eventAggregator.Subscribe(this); - } - - #endregion - - #region properties - - #region wrapped from bill - - public override DateTime DueDate - { - set - { - if (this.DueDate != value) - { - this.ExposedBill.DueDate = value; - this.NotifyOfPropertyChange(() => this.DueDate); - this.NotifyOfPropertyChange(() => this.IsDued); - this.NotifyOfPropertyChange(() => this.DuesIn); - } - } - } - - public override DateTime? PaymentDate - { - set - { - if (this.PaymentDate != value) - { - this.ExposedBill.PaymentDate = value; - this.NotifyOfPropertyChange(() => this.PaymentDate); - this.NotifyOfPropertyChange(() => this.IsPaid); - this.NotifyOfPropertyChange(() => this.IsNotPaid); - this.NotifyOfPropertyChange(() => this.IsDued); - this.NotifyOfPropertyChange(() => this.DuesIn); - } - } - } - - #endregion - - #region added - - private Supplier supplier; - public Supplier Supplier - { - get { return this.supplier; } - set - { - if (this.supplier != value) - { - this.supplier = value; - this.NotifyOfPropertyChange(() => this.Supplier); - } - } - } - - public bool IsPaid - { - get { return this.PaymentDate.HasValue; } - set - { - if (this.IsPaid != value) - { - if (value) this.PaymentDate = DateTime.Today; - else this.PaymentDate = null; - // changing only PaymentDate will Refresh IsPaid and similars - } - } - } - - public bool IsNotPaid - { - get { return !this.IsPaid; } - } - - public DateTime DisplayDateEndForPaymentDate - { - get { return DateTime.Today; } - } - - public bool IsDued - { - get { return this.DueDate < DateTime.Today; } - } - - public string DuesIn - { - get - { - var timeleft = this.DueDate.Subtract(DateTime.Today); - - if (timeleft.TotalDays >= 0) - { - if (timeleft.TotalDays == 0) return "Overdues today"; // TODO: language - if (timeleft.TotalDays == 1) return "Overdues tomorrow"; - return timeleft.TotalDays.ToString() + " days left"; - } - else - { - if (timeleft.TotalDays == -1) return "Overdue yesterday"; - return "Overdue " + (timeleft.TotalDays * -1).ToString() + " days ago"; // TODO: language - } - } - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.IDataErrorInfo.cs b/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.IDataErrorInfo.cs deleted file mode 100644 index 85dc6d9..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.IDataErrorInfo.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.ComponentModel; -using BillsManager.ViewModels.Validation; -using System; - -namespace BillsManager.ViewModels -{ - public partial class BillAddEditViewModel : IDataErrorInfo - { - #region IDataErrorInfo - - private readonly ValidationRulesTracker rulesTracker; - - public bool IsValid // TODO: make cached? - { - get { return this.HasChanges & string.IsNullOrEmpty(this.Error); } - } - - public string Error - { - get { return string.Join(Environment.NewLine, this.rulesTracker.GetAllErrors()); } - } - - public string this[string columnName] - { - get - { - //if (this.rulesTracker == null) - // this.rulesTracker = new ValidationRulesTracker(this); - - var errors = this.rulesTracker.GetErrorsForProperty(columnName); - return string.Join(Environment.NewLine, errors); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.IEditableObject.cs b/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.IEditableObject.cs deleted file mode 100644 index 3b88e6b..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.IEditableObject.cs +++ /dev/null @@ -1,81 +0,0 @@ -using BillsManager.Models; -using System.ComponentModel; - -namespace BillsManager.ViewModels -{ - public partial class BillAddEditViewModel : IEditableObject - { - #region IEditableObject - - private Bill _uneditedBill; - - private bool isInEditMode = false; - public bool IsInEditMode - { - get { return this.isInEditMode; } - protected set - { - if (this.isInEditMode != value) - { - this.isInEditMode = value; - this.NotifyOfPropertyChange(() => this.IsInEditMode); - } - } - } - - private bool hasChanges = false; - public bool HasChanges - { - get { return this.hasChanges; } - protected set - { - if (this.hasChanges != value) - { - this.hasChanges = value; - this.NotifyOfPropertyChange(() => this.HasChanges); - this.NotifyOfPropertyChange(() => this.DisplayName); - } - } - } - - public void BeginEdit() - { - this._uneditedBill = (Bill)this.ExposedBill.Clone(); // TODO: ICloneable ? - - this.IsInEditMode = true; - } - - private void RevertChanges() - { - // TODO: check for full coverage - this.AdditionalCosts = this._uneditedBill.AdditionalCosts; - this.Agio = this._uneditedBill.Agio; - this.Amount = this._uneditedBill.Amount; - this.Code = this._uneditedBill.Code; - this.DueDate = this._uneditedBill.DueDate; - this.Notes = this._uneditedBill.Notes; - this.PaymentDate = this._uneditedBill.PaymentDate; - this.RegistrationDate = this._uneditedBill.RegistrationDate; - this.ReleaseDate = this._uneditedBill.ReleaseDate; - this.SupplierID = this._uneditedBill.SupplierID; - } - - public void CancelEdit() - { - this.RevertChanges(); - - this.EndEdit(); - } - - public void EndEdit() - { - this.HasChanges = false; - - this._uneditedBill = null; - - this.IsInEditMode = false; - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.cs b/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.cs deleted file mode 100644 index 22a2527..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillAddEditViewModel/BillAddEditViewModel.cs +++ /dev/null @@ -1,390 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Localization.Attributes; -using BillsManager.Models; -using BillsManager.ViewModels.Commanding; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public partial class BillAddEditViewModel : - BillViewModel/*, - IHandle, - IHandle*/ - { - #region fields - - protected readonly IWindowManager windowManager; - protected readonly IEventAggregator globalEventAggregator; - - #endregion - - #region ctor - - public BillAddEditViewModel( - IWindowManager windowManager, - IEventAggregator globalEventAggregator, - IEnumerable availableSuppliers, - Bill bill) - { - if (bill == null) - throw new ArgumentNullException("bill cannot be null"); // TODO: is check needed? any other point to do it? - - this.exposedBill = bill; - - this.windowManager = windowManager; - this.globalEventAggregator = globalEventAggregator; - - this.globalEventAggregator.Subscribe(this); - - this.AvailableSuppliers = availableSuppliers; - //this.HasChanges = false; // TODO: check if mandatory - this.SelectedSupplier = this.AvailableSuppliers.FirstOrDefault(s => s.ID == this.SupplierID); - - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - this.globalEventAggregator.Unsubscribe(this); - }; - - this.rulesTracker = new Validation.ValidationRulesTracker(this); - } - - #endregion - - #region properties - - #region add/edit support - - private IEnumerable availableSuppliers; - public IEnumerable AvailableSuppliers - { - get { return this.availableSuppliers; } - protected set - { - if (this.availableSuppliers == value) return; - - this.availableSuppliers = value; - this.NotifyOfPropertyChange(() => this.AvailableSuppliers); - } - } - - private Supplier selectedSupplier; // TODO: if SQL, remove and make the get to point to the bill? - [LocalizedRequired(ErrorMessageKey = "SupplierRequired")] - public Supplier SelectedSupplier - { - get { return this.selectedSupplier; } - set - { - if (this.selectedSupplier == value) return; - - this.selectedSupplier = value; - this.NotifyOfPropertyChange(() => this.SelectedSupplier); - this.NotifyOfPropertyChange(() => this.IsValid); - if (value != null) - this.SupplierID = this.SelectedSupplier.ID; - } - } - - public DateTime DisplayDateEndForReleaseDate - { - get { return DateTime.Today; } - } - - #endregion - - #region wrapped from bill - - //[LocalizedRequired(ErrorMessageKey = "You must specify a supplier.")] // TODO: language - //[Range(0, uint.MaxValue, ErrorMessage = "Chosen supplier ID is out of range.")] // TODO: language - public override uint SupplierID - { - get { return base.SupplierID; } - set - { - if (this.SupplierID != value) - { - base.SupplierID = value; - this.NotifyOfPropertyChange(); - - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - - //this.SelectedSupplier = this.GetSupplier(this.SupplierID); - } - } - } - - /* TODO: registration date should be read only - * this means no validation and no override here */ - public override DateTime RegistrationDate - { - get { return base.RegistrationDate; } - set - { - if (this.RegistrationDate == value) return; - - base.RegistrationDate = value; - this.NotifyOfPropertyChange(); - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - - [LocalizedRequired(ErrorMessageKey = "DateRequired")] - public override DateTime DueDate - { - get { return base.DueDate; } - set - { - if (this.DueDate != value) - { - base.DueDate = value; - this.NotifyOfPropertyChange(); - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - [LocalizedRequired(ErrorMessageKey = "ReleaseDateRequired")] - public override DateTime ReleaseDate - { - get { return base.ReleaseDate; } - set - { - if (this.ReleaseDate != value) - { - base.ReleaseDate = value; - this.NotifyOfPropertyChange(); - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - public override DateTime? PaymentDate - { - get { return base.PaymentDate; } - set - { - if (this.PaymentDate != value) - { - base.PaymentDate = value; - this.NotifyOfPropertyChange(); - this.NotifyOfPropertyChange(() => this.IsPaid); - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - [LocalizedRequired(ErrorMessageKey = "AmountRequired")] - public override Double Amount - { - get { return base.Amount; } - set - { - //if (this.Amount != value) - //{ - base.Amount = value; - this.NotifyOfPropertyChange(); - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - //} - } - } - - public override double Agio - { - get { return base.Agio; } - set - { - base.Agio = value; - this.NotifyOfPropertyChange(); - this.HasChanges = true; - } - } - - public override double AdditionalCosts - { - get { return base.AdditionalCosts; } - set - { - base.AdditionalCosts = value; - this.NotifyOfPropertyChange(); - this.HasChanges = true; - } - } - - //[Required(ErrorMessage = "You must specify a code.")] // TODO: language - public override string Code - { - get { return base.Code; } - set - { - if (this.Code != value) - { - base.Code = value; - this.NotifyOfPropertyChange(); - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - [LocalizedStringLength(200, ErrorMessageFormatKey = "CannotExceedChars_format")] - public override string Notes - { - get { return base.Notes; } - set - { - if (this.Notes != value) - { - base.Notes = value; - this.NotifyOfPropertyChange(); - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - #endregion - - #region added - - public bool IsPaid - { - get { return this.PaymentDate.HasValue; } - set - { - if (this.IsPaid != value) - { - if (value) this.PaymentDate = DateTime.Today; - else this.PaymentDate = null; - } - } - } - - #endregion - - #region overrides - - public new string DisplayName - { - get - { - return this.IsInEditMode - ? (TranslationManager.Instance.Translate("EditBill").ToString() + (this.IsInEditMode & this.HasChanges ? " *" : string.Empty)) - : TranslationManager.Instance.Translate("NewBill").ToString(); - } - set // TODO: review - { - - } - } - - #endregion - - #endregion - - #region methods - - //private IEnumerable GetAvailableSuppliers() - //{ - // IEnumerable suppliers = null; - - // this.globalEventAggregator.PublishOnUIThread(new AvailableSuppliersRequest(s => suppliers = s)); - - // return suppliers; - //} - - private void ConfirmAndClose() - { - if (this.IsInEditMode) - this.EndEdit(); - - this.TryClose(true); - } - - private void CancelAndClose() - { - // TODO: optimize - if (this.HasChanges) - { - DialogViewModel question = - DialogViewModel.Show( - DialogType.Question, - this.IsInEditMode ? - TranslationManager.Instance.Translate("CancelEdit") : - TranslationManager.Instance.Translate("CancelAdd"), - TranslationManager.Instance.Translate("DiscardChangesQuestion")) - .YesNo(); - - this.windowManager.ShowDialog(question); - - if (question.FinalResponse == ResponseType.Yes) - { - if (this.IsInEditMode) - this.CancelEdit(); - - this.TryClose(false); - } - } - else - { - if (this.IsInEditMode) - this.CancelEdit(); - - this.TryClose(false); - } - } - - #region message handlers - - //public void Handle(SuppliersListChangedMessage message) - //{ - // this.AvailableSuppliers = message.Suppliers; - //} - - //public void Handle(SupplierAddedMessage message) - //{ - // // available suppliers references to the same instance of suppliersvm - // this.NotifyOfPropertyChange(() => this.AvailableSuppliers); - //} - - #endregion - - #endregion - - #region commands - - protected RelayCommand confirmAddEditAndCloseCommand; - public RelayCommand ConfirmAddEditAndCloseCommand - { - get - { - return this.confirmAddEditAndCloseCommand ?? (this.confirmAddEditAndCloseCommand = - new RelayCommand( - () => this.ConfirmAndClose(), - () => this.IsValid)); - } - } - - protected RelayCommand cancelAddEditAndCloseCommand; - public RelayCommand CancelAddEditAndCloseCommand - { - get - { - return this.cancelAddEditAndCloseCommand ?? (this.cancelAddEditAndCloseCommand = - new RelayCommand( - () => this.CancelAndClose())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModel.IComparable.cs b/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModel.IComparable.cs deleted file mode 100644 index b936dde..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModel.IComparable.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -namespace BillsManager.ViewModels -{ - public partial class BillDetailsViewModel : IComparable - { - #region IComparable Members - - public int CompareTo(BillDetailsViewModel other) - { - var paid = this.IsPaid.CompareTo(other.IsPaid); - if (paid != 0) return paid; - - var due = other.DueDate.CompareTo(this.DueDate); - if (due != 0) return due * (-1); - - var amount = this.Amount.CompareTo(other.Amount); - if (amount != 0) return amount; - - var supplierName = this.SupplierName.CompareTo(other.SupplierName); - if (supplierName != 0) return supplierName; - - var code = string.Compare(this.Code, other.Code); - if (code != 0) return code; - - return 0; - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModel.cs b/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModel.cs deleted file mode 100644 index 667d255..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModel.cs +++ /dev/null @@ -1,264 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Localization.Attributes; -using BillsManager.Models; -using BillsManager.ViewModels.Commanding; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System; -using System.Diagnostics; -using System.Linq; - -namespace BillsManager.ViewModels -{ - [DebuggerDisplay("Code = {Code}")] - public partial class BillDetailsViewModel : - BillViewModel, - IHandle> - { - #region fields - - protected readonly IWindowManager _windowManager; - protected readonly IEventAggregator _globalEventAggregator; - - #endregion - - #region ctor - - protected BillDetailsViewModel() { } - - public BillDetailsViewModel( - IWindowManager windowManager, - IEventAggregator globalEventAggregator, - Bill bill) - { - // TODO: review - //if (bill == null) - // throw new ArgumentNullException("bill cannot be null"); - - this.exposedBill = bill; - - this._windowManager = windowManager; - this._globalEventAggregator = globalEventAggregator; - - this._globalEventAggregator.Subscribe(this); - - //this.SupplierName = this.GetSupplierName(this.SupplierID); - - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - { - this._globalEventAggregator.Unsubscribe(this); - } - }; - } - - #endregion - - #region properties - - #region wrapped from bill - - public override DateTime RegistrationDate - { - get { return base.RegistrationDate; } - } - - public override DateTime DueDate - { - get { return base.DueDate; } - } - - public override DateTime ReleaseDate - { - get { return base.ReleaseDate; } - } - - public override DateTime? PaymentDate - { - get { return base.PaymentDate; } - } - - public override double Amount - { - get { return base.Amount; } - } - - public override double Agio - { - get { return base.Agio; } - } - - public override double AdditionalCosts - { - get { return base.AdditionalCosts; } - } - - public override string Code - { - get { return base.Code; } - } - - public override string Notes - { - get { return base.Notes; } - } - - #endregion - - #region added - - public string SupplierName - { - get { return this.GetSupplierName(); } - } - - public bool IsPaid - { - get { return this.PaymentDate.HasValue; } - } - - public bool IsNotPaid - { - get { return !this.IsPaid; } - } - - public DateTime DisplayDateEndForPaymentDate - { - get { return DateTime.Today; } - } - - public bool IsDued - { - get { return this.DueDate < DateTime.Today; } - } - - public string DuesIn - { - get - { - // TODO: optimization benchmark (overdue + s ...) - var timeleft = this.DueDate.Subtract(DateTime.Today); - - if (timeleft.TotalDays >= 0) - { - if (timeleft.TotalDays == 0) return TranslationManager.Instance.Translate("OverduesToday_toBill").ToString(); - if (timeleft.TotalDays == 1) return TranslationManager.Instance.Translate("OverduesTomorrow_toBill").ToString(); - return string.Format(TranslationManager.Instance.Translate("OverduesInXDays_toBill_format").ToString(), timeleft.TotalDays); - } - else - { - if (timeleft.TotalDays == -1) - return TranslationManager.Instance.Translate("OverdueYesterday_toBill").ToString(); - return string.Format(TranslationManager.Instance.Translate("OverdueXDaysAgo_toBill_format").ToString(), timeleft.TotalDays * -1); - } - } - } - - public DueAlert DueAlert - { - get - { - if (this.IsPaid) - return DueAlert.None; - - var remDays = (this.DueDate - DateTime.Today).TotalDays; - - if /*(remDays >= 15) - return DueAlert.None; - else if*/ (remDays >= 7) - return DueAlert.Low; - else if (remDays >= 3) - return DueAlert.Medium; - else if (remDays >= 0) - return DueAlert.High; - else - return DueAlert.Critical; - } - } - - public string DueLevelString - { - get - { - return - /*TranslationManager.Instance.Translate(*/ - typeof(DueAlert) - .GetMember(this.DueAlert.ToString())[0] - .GetAttributes(true).FirstOrDefault().DisplayName - /*).ToString()*/; - } - } - - #endregion - - #region override - - public new string DisplayName - { - get { return this.Code + " - " + this.SupplierName; } - set { } - } - - #endregion - - #endregion - - #region methods - - private string GetSupplierName() - { - // TODO: move supplier logic to BillsViewModel (same for supp's obligation amount) - string supp = string.Empty; - this._globalEventAggregator.PublishOnUIThread(new SupplierNameRequest(this.SupplierID, s => supp = s)); - return supp; - } - - private void SwitchToEdit() - { - this.TryClose(); - this._globalEventAggregator.PublishOnUIThread(new EditBillOrder(this.ExposedBill)); - } - - #region message handlers - - public void Handle(EditedMessage message) - { - if (this.SupplierID == message.OldItem.ID) - { - this.NotifyOfPropertyChange(() => this.SupplierName); - } - } - - #endregion - - #endregion - - #region commands - - private RelayCommand switchToEditCommand; - public RelayCommand SwitchToEditCommand - { - get - { - return this.switchToEditCommand ?? (this.switchToEditCommand = - new RelayCommand( - () => this.SwitchToEdit())); - } - } - - private RelayCommand closeDetailsViewCommand; - public RelayCommand CloseDetailsViewCommand - { - get - { - return this.closeDetailsViewCommand ?? (this.closeDetailsViewCommand = - new RelayCommand( - () => this.TryClose())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModelComparer.cs b/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModelComparer.cs deleted file mode 100644 index ebd9284..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillDetailsViewModel/BillDetailsViewModelComparer.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; - -namespace BillsManager.ViewModels -{ - public class BillDetailsViewModelComparer : IComparer - { - #region IComparer Members - - public int Compare(BillDetailsViewModel x, BillDetailsViewModel y) - { - var change = x.CompareTo(y); - - return change; - } - - #endregion - - public BillDetailsViewModelComparer() { } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/BillViewModels/BillViewModel.IDataErrorInfo.cs b/BillsManager.ViewModels/BillViewModels/BillViewModel.IDataErrorInfo.cs deleted file mode 100644 index ec7adfe..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillViewModel.IDataErrorInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.ComponentModel; -using BillsManager.ViewModel.Validation; -using Caliburn.Micro; - -namespace BillsManager.ViewModel -{ - public partial class BillViewModel : Screen, IDataErrorInfo - { - #region IDataErrorInfo - - private ValidationRulesTracker rulesTracker; - - public bool IsValid - { - get { return string.IsNullOrEmpty(this.Error); } - } - - public string Error - { - get { return this.rulesTracker.GetAllErrors(); } - } - - public string this[string columnName] - { - get - { - if (this.rulesTracker == null) - this.rulesTracker = new ValidationRulesTracker(this); - - return this.rulesTracker.GetErrorsForProperty(columnName); - } - } - - #endregion - } -} diff --git a/BillsManager.ViewModels/BillViewModels/BillViewModel.IEditableObject.cs b/BillsManager.ViewModels/BillViewModels/BillViewModel.IEditableObject.cs deleted file mode 100644 index a7fbf42..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillViewModel.IEditableObject.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System.Collections.Generic; -using System.ComponentModel; -using BillsManager.Model; -using BillsManager.ViewModel.Messages; -using Caliburn.Micro; - -namespace BillsManager.ViewModel -{ - public partial class BillViewModel : Screen, IEditableObject - { - #region IEditableObject - - private Bill exposedBillBackup; - - private bool isInEditMode = false; - public bool IsInEditMode - { - get { return this.isInEditMode; } - set - { - if (this.isInEditMode != value) - { - this.isInEditMode = value; - this.NotifyOfPropertyChange(() => this.IsInEditMode); - } - } - } - - private bool hasChanges = false; - public bool HasChanges - { - get { return this.hasChanges; } - protected set - { - if (this.hasChanges != value) - { - this.hasChanges = value; - this.NotifyOfPropertyChange(() => this.HasChanges); - this.NotifyOfPropertyChange(() => this.DisplayName); - } - } - } - - private IEnumerable GetAvailableSuppliers() - { - IEnumerable suppliers = null; - - this.eventAggregator.Publish(new AskForAvailableSuppliersMessage(s => suppliers = s)); - - return suppliers; - } - - public void BeginEdit() - { - this.exposedBillBackup = (Bill)this.ExposedBill.Clone(); - - this.IsInEditMode = true; - - this.SetupForAddEdit(); - } - - protected void RevertChanges() - { - this.Amount = this.exposedBillBackup.Amount; - this.Code = this.exposedBillBackup.Code; - this.DueDate = this.exposedBillBackup.DueDate; - this.Notes = this.exposedBillBackup.Notes; - this.PaymentDate = this.exposedBillBackup.PaymentDate; - this.RegistrationDate = this.exposedBillBackup.RegistrationDate; - this.ReleaseDate = this.exposedBillBackup.ReleaseDate; - this.SupplierID = this.exposedBillBackup.SupplierID; - } - - public void CancelEdit() - { - this.RevertChanges(); - - this.EndEdit(); - } - - public void EndEdit() - { - this.HasChanges = false; - - this.exposedBillBackup = null; - - this.IsInEditMode = false; - } - - #endregion - } -} diff --git a/BillsManager.ViewModels/BillViewModels/BillViewModel.cs b/BillsManager.ViewModels/BillViewModels/BillViewModel.cs deleted file mode 100644 index 96b0085..0000000 --- a/BillsManager.ViewModels/BillViewModels/BillViewModel.cs +++ /dev/null @@ -1,168 +0,0 @@ -using BillsManager.Models; -using Caliburn.Micro; -using System; - -namespace BillsManager.ViewModels -{ - public abstract class BillViewModel : Screen - { - #region properties - - // TODO: make readonly -> add ctor - protected Bill exposedBill; - public Bill ExposedBill - { - get { return this.exposedBill; } - protected set - { - if (this.exposedBill != value) - { - this.exposedBill = value; - this.NotifyOfPropertyChange(); - this.Refresh(); /* TODO: this double refreshes this property, and properties that don't need refresh too - * also, it refreshes in the ctor, when the object is created - * and every time the value changes: eg. on edit (?) */ - } - } - } - - #region wrapped from bill - - public uint ID - { - get { return this.ExposedBill.ID; } - } - - public virtual uint SupplierID - { - get { return this.ExposedBill.SupplierID; } - set - { - if (this.SupplierID != value) - { - this.ExposedBill.SupplierID = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual DateTime RegistrationDate - { - get { return this.ExposedBill.RegistrationDate; } - set - { - if (this.RegistrationDate != value) - { - this.ExposedBill.RegistrationDate = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual DateTime DueDate - { - get { return this.ExposedBill.DueDate; } - set - { - if (this.DueDate != value) - { - this.ExposedBill.DueDate = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual DateTime ReleaseDate - { - get { return this.ExposedBill.ReleaseDate; } - set - { - if (this.ReleaseDate != value) - { - this.ExposedBill.ReleaseDate = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual DateTime? PaymentDate - { - get { return this.ExposedBill.PaymentDate; } - set - { - if (this.PaymentDate != value) - { - this.ExposedBill.PaymentDate = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual Double Amount - { - get { return this.ExposedBill.Amount; } - set - { - if (this.Amount != value) - { - this.ExposedBill.Amount = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual Double Agio - { - get { return this.ExposedBill.Agio; } - set - { - if (this.ExposedBill.Agio == value) return; - - this.ExposedBill.Agio = value; - this.NotifyOfPropertyChange(); - } - } - - public virtual Double AdditionalCosts - { - get { return this.ExposedBill.AdditionalCosts; } - set - { - if (this.ExposedBill.AdditionalCosts == value) return; - - this.ExposedBill.AdditionalCosts = value; - this.NotifyOfPropertyChange(); - } - } - - public virtual string Code - { - get { return this.ExposedBill.Code; } - set - { - if (this.Code != value) - { - this.ExposedBill.Code = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string Notes - { - get { return this.ExposedBill.Notes; } - set - { - if (this.Notes != value) - { - this.ExposedBill.Notes = value; - this.NotifyOfPropertyChange(); - } - } - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/BillsManager.ViewModels.csproj b/BillsManager.ViewModels/BillsManager.ViewModels.csproj deleted file mode 100644 index 8b9e217..0000000 --- a/BillsManager.ViewModels/BillsManager.ViewModels.csproj +++ /dev/null @@ -1,175 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {127368A5-65A5-46C6-A203-33ABC22B1EDD} - Library - Properties - BillsManager.ViewModels - BillsManager.ViewModels - v4.5 - 512 - SAK - SAK - SAK - SAK - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - AnyCPU - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - - ..\packages\Caliburn.Micro.Core.2.0.2\lib\net45\Caliburn.Micro.dll - True - - - ..\packages\Caliburn.Micro.2.0.2\lib\net45\Caliburn.Micro.Platform.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - {5387db3b-6ec1-42cf-a72b-cef5adfb541a} - BillsManager.Localization - - - {888F670B-4396-4660-8C5A-0D43FB2C0A1D} - BillsManager.Models - - - {FC8A7A61-D9CF-4AC7-A62D-590C35A28A44} - BillsManager.Services - - - - - - \ No newline at end of file diff --git a/BillsManager.ViewModels/BillsManager.ViewModels.csproj.user b/BillsManager.ViewModels/BillsManager.ViewModels.csproj.user deleted file mode 100644 index 6cbe588..0000000 --- a/BillsManager.ViewModels/BillsManager.ViewModels.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - ProjectFiles - - \ No newline at end of file diff --git a/BillsManager.ViewModels/BillsViewModel.cs b/BillsManager.ViewModels/BillsViewModel.cs deleted file mode 100644 index e4357e7..0000000 --- a/BillsManager.ViewModels/BillsViewModel.cs +++ /dev/null @@ -1,481 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Models; -using BillsManager.Services.DB; -using BillsManager.ViewModels.Commanding; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public partial class BillsViewModel : - Screen, - IHandle>, - IHandle>, - IHandle, - IHandle - { - #region fields - - private readonly IWindowManager _windowManager; - private readonly IEventAggregator _globalEventAggregator; - private readonly IBillsRepository _billsProvider; - - private readonly Func, Bill, BillAddEditViewModel> _billAddEditViewModelFactory; - private readonly Func _billDetailsViewModelFactory; - - private readonly IComparer _billDetailsVMComparer = new BillDetailsViewModelComparer(); - - #endregion - - #region ctors - - /// - /// Provides a way for design time mocking - /// - protected BillsViewModel() { } - - public BillsViewModel( - IWindowManager windowManager, - IEventAggregator globalEventAggregator, - IBillsRepository billsProvider, - Func, Bill, BillAddEditViewModel> billAddEditViewModelFactory, - Func billDetailsViewModelFactory) - { - // SERVICES - this._windowManager = windowManager; - this._globalEventAggregator = globalEventAggregator; - this._billsProvider = billsProvider; - - // FACTORIES - this._billAddEditViewModelFactory = billAddEditViewModelFactory; - this._billDetailsViewModelFactory = billDetailsViewModelFactory; - - // SUBSCRIPTIONS - this._globalEventAggregator.Subscribe(this); - - // HANDLERS - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - this._globalEventAggregator.Unsubscribe(this); - }; - - // UI - this.DisplayName = TranslationManager.Instance.Translate("Bills").ToString(); - - // START - this.LoadBills(); - } - - #endregion - - #region properties - - private ObservableCollection billViewModels; - protected ObservableCollection BillViewModels - { - get { return this.billViewModels; } - set - { - if (this.billViewModels != value) - { - this.billViewModels = value; - this.NotifyOfPropertyChange(() => this.BillViewModels); - this.FilteredBillViewModels = - new ReadOnlyObservableCollectionEx( - this.BillViewModels, - this.Filters != null ? this.Filters.Select(f => f.Execute) : null, - this._billDetailsVMComparer); - - // IDEA: #IF !DEBUG ? - if (!Execute.InDesignMode) - this._globalEventAggregator.PublishOnUIThread(new BillsListChangedMessage(this.BillViewModels.Select(bvm => bvm.ExposedBill).ToList())); // TODO: move to filtered? - } - } - } - - private ReadOnlyObservableCollectionEx filteredBillViewModels; - public ReadOnlyObservableCollectionEx FilteredBillViewModels - { - get { return this.filteredBillViewModels; } - protected set - { - // TODO: remove set / make lazy get? - - if (this.filteredBillViewModels == value) return; - - this.filteredBillViewModels = value; - this.NotifyOfPropertyChange(); - } - } - - private BillDetailsViewModel selectedBillViewModel; - public BillDetailsViewModel SelectedBillViewModel - { - get { return this.selectedBillViewModel; } - set - { - if (this.selectedBillViewModel == value) return; - - this.selectedBillViewModel = value; - this.NotifyOfPropertyChange(); - - } - } - - // IDEA: remove filter class and make it possibile to add or not a comment at print time? - private IEnumerable> filters; - public IEnumerable> Filters - { - get { return this.filters; } - private set - { - if (this.filters == value) return; - - this.filters = value; - this.NotifyOfPropertyChange(); - this.UpdateCollectionFilters(); - this.NotifyOfPropertyChange(() => this.FiltersDescription); - } - } - - public string FiltersDescription - { - get - { - var filtersDescription = string.Empty; - if (this.Filters == null) return TranslationManager.Instance.Translate("AllTheBills").ToString(); - - foreach (var filter in this.Filters) - { - filtersDescription += ", " + filter.Description().ToLower(TranslationManager.Instance.CurrentLanguage); - } - - return TranslationManager.Instance.Translate("Bills").ToString() + filtersDescription.Substring(1); - } - } - - #endregion - - #region methods - - public void LoadBills() - { - var bills = this._billsProvider.GetAllBills(); - - var billVMs = bills.Select(bill => this._billDetailsViewModelFactory.Invoke(bill)).ToList(); - - billVMs.Sort(); - - this.BillViewModels = new ObservableCollection(billVMs); - } - - private string GetBillSummary(Bill bill) - { - var currencyFormat = TranslationManager.Instance.Translate("_currency_format"); - - var formattedAmount = string.Format(currencyFormat, bill.Amount); - - return - this.GetSupplierName(bill.SupplierID) + - Environment.NewLine + - bill.Code + - Environment.NewLine + - formattedAmount; - } - - private string GetSupplierName(uint supplierID) - { - string supp = null; - if (!Execute.InDesignMode) - this._globalEventAggregator.PublishOnUIThread(new SupplierNameRequest(supplierID, s => supp = s)); - return supp; - } - - #region CRUD - - private void AddBill(Supplier supplier = null) - { - var availableSuppliers = this.GetAvailableSuppliers(); - var addBillVM = this._billAddEditViewModelFactory.Invoke(availableSuppliers, new Bill(this._billsProvider.GetLastBillID() + 1)); - - // TODO: check availableSuppliers.Contains(supplier) ?? - addBillVM.SelectedSupplier = supplier; - - tryAdd: - if (this._windowManager.ShowDialog(addBillVM) == true) - { - // TODO: make it possible to show the view through a dialogviewmodel (evaluate the idea) - if (this._billsProvider.Add(addBillVM.ExposedBill)) - { - var newBillDetailsVM = this._billDetailsViewModelFactory.Invoke(addBillVM.ExposedBill); - - this.BillViewModels.Add(newBillDetailsVM); - - this.SelectedBillViewModel = newBillDetailsVM; - - if (!Execute.InDesignMode) - this._globalEventAggregator.PublishOnUIThread(new AddedMessage(newBillDetailsVM.ExposedBill)); - } - else - { - var dialog = DialogViewModel.Show( - DialogType.Error, - TranslationManager.Instance.Translate("AddBillFailed"), - TranslationManager.Instance.Translate("AddBillFailedMessage") + - Environment.NewLine + - TranslationManager.Instance.Translate("TryAgain")) - .Ok(); - - this._windowManager.ShowDialog(dialog); - - goto tryAdd; - } - } - } - - private void EditBill(Bill bill) - { - var supps = this.GetAvailableSuppliers(); - Bill oldBill = (Bill)bill.Clone(); - var editBillVM = this._billAddEditViewModelFactory.Invoke(supps, bill); - - editBillVM.BeginEdit(); - - if (this._windowManager.ShowDialog(editBillVM) == true) - { - if (this._billsProvider.Edit(editBillVM.ExposedBill)) // URGENT: if the DB action fails, changes have to be rolled back!! - { - var editedBillDetailsVM = this.BillViewModels.FirstOrDefault(bvm => bvm.ExposedBill == bill); - editedBillDetailsVM.Refresh(); - - this.SelectedBillViewModel = null; - - if (!Execute.InDesignMode) - this._globalEventAggregator.PublishOnUIThread(new EditedMessage(oldBill, editBillVM.ExposedBill)); // TODO: move to confirm add edit command in addeditbvm - } - else - { - var dialog = DialogViewModel.Show( - DialogType.Error, - TranslationManager.Instance.Translate("EditFailed"), - TranslationManager.Instance.Translate("EditFailedMessage") + - Environment.NewLine + - TranslationManager.Instance.Translate("TryAgain")) - .Ok(); - - this._windowManager.ShowDialog(dialog); - } - } - } - - private void DeleteBill(Bill bill) - { - DialogViewModel deleteBillConfirmationDialog = - DialogViewModel.Show( - DialogType.Question, - TranslationManager.Instance.Translate("DeleteBill"), - TranslationManager.Instance.Translate("DeleteBillQuestion") + - Environment.NewLine + - Environment.NewLine + - this.GetBillSummary(bill)) - .YesNo(TranslationManager.Instance.Translate("Delete")); - - this._windowManager.ShowDialog(deleteBillConfirmationDialog); - - if (deleteBillConfirmationDialog.FinalResponse == ResponseType.Yes) - { - if (this._billsProvider.Delete(bill)) - { - this.BillViewModels.Remove(this.BillViewModels.FirstOrDefault(bvm => bvm.ExposedBill == bill)); - //this.NotifyOfPropertyChange(() => this.FilteredBillViewModels); - - this.SelectedBillViewModel = null; - - if (!Execute.InDesignMode) - this._globalEventAggregator.PublishOnUIThread(new DeletedMessage(bill)); - } - } - } - - private void PayBill(Bill bill) - { - DialogViewModel payBillConfirmationDialog = - DialogViewModel.Show( - DialogType.Question, - TranslationManager.Instance.Translate("PayBill"), - TranslationManager.Instance.Translate("PayBillQuestion") + - Environment.NewLine + - Environment.NewLine + - this.GetBillSummary(bill)) - .YesNo( - TranslationManager.Instance.Translate("PayBill")); - - if (this._windowManager.ShowDialog(payBillConfirmationDialog) == true) - { - Bill oldVersion = (Bill)bill.Clone(); - - bill.PaymentDate = DateTime.Today; - - if (this._billsProvider.Edit(bill)) - { - var editedVM = this.BillViewModels.FirstOrDefault(bvm => bvm.ExposedBill == bill); - editedVM.Refresh(); - - this.SelectedBillViewModel = null; - - if (!Execute.InDesignMode) - this._globalEventAggregator.PublishOnUIThread(new EditedMessage(oldVersion, bill)); - } - } - } - - private void ShowBillDetails(BillDetailsViewModel billDetailsViewModel) - { - this._windowManager.ShowDialog(billDetailsViewModel, settings: new Dictionary() { { "CanClose", true } }); - } - - #endregion - - #region message handlers - - public void Handle(FilterMessage message) - { - this.Filters = message.Filters; - - if (!this.FilteredBillViewModels.Contains(this.SelectedBillViewModel)) - this.SelectedBillViewModel = null; - } - - public void Handle(DeletedMessage message) - { - var bvmsToDelete = this.BillViewModels.Where(bvm => bvm.SupplierID == message.DeletedItem.ID).ToArray(); - - foreach (var bvm in bvmsToDelete) - { - if (this._billsProvider.Delete(bvm.ExposedBill)) - this.BillViewModels.Remove(bvm); - else - throw new ApplicationException("Couldn't delete this bill: " + Environment.NewLine + Environment.NewLine + this.GetBillSummary(bvm.ExposedBill)); // TODO handle with rollback - } - - if (!Execute.InDesignMode) - this._globalEventAggregator.PublishOnUIThread(new BillsListChangedMessage(this.BillViewModels.Select(bvm => bvm.ExposedBill).ToList())); - - // if there was an error during the remove operation on the db - // this point wouldn't be reached - //if (this.Filters == null) - // this.NotifyOfPropertyChange(() => this.FilteredBillViewModels); - } - - public void Handle(EditBillOrder message) - { - this.EditBill(message.Bill); /* TODO: is it better to pass only the ID and let this VM to get the bill? - * (this would check whether the bill is contained or is a lost one) */ - } - - public void Handle(AddBillToSupplierOrder message) - { - this.AddBill(message.Supplier); - } - - #endregion - - #region overrides - - protected override void OnActivate() - { - base.OnActivate(); - //this.eventAggregator.Subscribe(this); - } - - #endregion - - #region support - - private void UpdateCollectionFilters() - { - this.FilteredBillViewModels.Filters = (this.Filters != null ? this.Filters.Select(f => f.Execute) : null); - } - - private IEnumerable GetAvailableSuppliers() - { - IEnumerable supps = Enumerable.Empty(); - if (!Execute.InDesignMode) - this._globalEventAggregator.PublishOnUIThread(new AvailableSuppliersRequest((s) => supps = s)); - return supps; - } - - #endregion - - #endregion - - #region commands - - private RelayCommand addNewBillCommand; - public RelayCommand AddNewBillCommand - { - get - { - return this.addNewBillCommand ?? (this.addNewBillCommand = - new RelayCommand( - () => this.AddBill())); - } - } - - private RelayCommand editBillCommand; - public RelayCommand EditBillCommand - { - get - { - return this.editBillCommand ?? (this.editBillCommand = - new RelayCommand( - p => this.EditBill(p.ExposedBill), - p => p != null)); - } - } - - private RelayCommand deleteBillCommand; - public RelayCommand DeleteBillCommand - { - get - { - return this.deleteBillCommand ?? (this.deleteBillCommand = - new RelayCommand( - p => this.DeleteBill(p.ExposedBill), - p => p != null)); - } - } - - private RelayCommand payBillCommand; - public RelayCommand PayBillCommand - { - get - { - return this.payBillCommand ?? (this.payBillCommand = - new RelayCommand( - p => this.PayBill(p.ExposedBill), - p => p != null && !p.IsPaid)); - } - } - - private RelayCommand showBillDetailsCommand; - public RelayCommand ShowBillDetailsCommand - { - get - { - return this.showBillDetailsCommand ?? (this.showBillDetailsCommand = - new RelayCommand( - p => this.ShowBillDetails(p), - p => p != null)); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Commanding/EventToCommand/BehaviorBinding.cs b/BillsManager.ViewModels/Commanding/EventToCommand/BehaviorBinding.cs deleted file mode 100644 index b7f2e92..0000000 --- a/BillsManager.ViewModels/Commanding/EventToCommand/BehaviorBinding.cs +++ /dev/null @@ -1,216 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Input; - -namespace BillsManager.ViewModels.Commanding -{ - /// - /// Defines a Command Binding - /// This inherits from freezable so that it gets inheritance context for DataBinding to work - /// - public class BehaviorBinding : Freezable - { - CommandBehaviorBinding behavior; - /// - /// Stores the Command Behavior Binding - /// - internal CommandBehaviorBinding Behavior - { - get - { - if (behavior == null) - behavior = new CommandBehaviorBinding(); - return behavior; - } - } - - DependencyObject owner; - /// - /// Gets or sets the Owner of the binding - /// - public DependencyObject Owner - { - get { return owner; } - set - { - owner = value; - ResetEventBinding(); - } - } - - #region Command - - /// - /// Command Dependency Property - /// - public static readonly DependencyProperty CommandProperty = - DependencyProperty.Register("Command", typeof(ICommand), typeof(BehaviorBinding), - new FrameworkPropertyMetadata((ICommand)null, - new PropertyChangedCallback(OnCommandChanged))); - - /// - /// Gets or sets the Command property. - /// - public ICommand Command - { - get { return (ICommand)GetValue(CommandProperty); } - set { SetValue(CommandProperty, value); } - } - - /// - /// Handles changes to the Command property. - /// - private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - ((BehaviorBinding)d).OnCommandChanged(e); - } - - /// - /// Provides derived classes an opportunity to handle changes to the Command property. - /// - protected virtual void OnCommandChanged(DependencyPropertyChangedEventArgs e) - { - Behavior.Command = Command; - } - - #endregion - - #region Action - - /// - /// Action Dependency Property - /// - public static readonly DependencyProperty ActionProperty = - DependencyProperty.Register("Action", typeof(Action), typeof(BehaviorBinding), - new FrameworkPropertyMetadata((Action)null, - new PropertyChangedCallback(OnActionChanged))); - - /// - /// Gets or sets the Action property. - /// - public Action Action - { - get { return (Action)GetValue(ActionProperty); } - set { SetValue(ActionProperty, value); } - } - - /// - /// Handles changes to the Action property. - /// - private static void OnActionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - ((BehaviorBinding)d).OnActionChanged(e); - } - - /// - /// Provides derived classes an opportunity to handle changes to the Action property. - /// - protected virtual void OnActionChanged(DependencyPropertyChangedEventArgs e) - { - Behavior.Action = Action; - } - - #endregion - - #region CommandParameter - - /// - /// CommandParameter Dependency Property - /// - public static readonly DependencyProperty CommandParameterProperty = - DependencyProperty.Register("CommandParameter", typeof(object), typeof(BehaviorBinding), - new FrameworkPropertyMetadata((object)null, - new PropertyChangedCallback(OnCommandParameterChanged))); - - /// - /// Gets or sets the CommandParameter property. - /// - public object CommandParameter - { - get { return (object)GetValue(CommandParameterProperty); } - set { SetValue(CommandParameterProperty, value); } - } - - /// - /// Handles changes to the CommandParameter property. - /// - private static void OnCommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - ((BehaviorBinding)d).OnCommandParameterChanged(e); - } - - /// - /// Provides derived classes an opportunity to handle changes to the CommandParameter property. - /// - protected virtual void OnCommandParameterChanged(DependencyPropertyChangedEventArgs e) - { - Behavior.CommandParameter = CommandParameter; - } - - #endregion - - #region Event - - /// - /// Event Dependency Property - /// - public static readonly DependencyProperty EventProperty = - DependencyProperty.Register("Event", typeof(string), typeof(BehaviorBinding), - new FrameworkPropertyMetadata((string)null, - new PropertyChangedCallback(OnEventChanged))); - - /// - /// Gets or sets the Event property. - /// - public string Event - { - get { return (string)GetValue(EventProperty); } - set { SetValue(EventProperty, value); } - } - - /// - /// Handles changes to the Event property. - /// - private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - ((BehaviorBinding)d).OnEventChanged(e); - } - - /// - /// Provides derived classes an opportunity to handle changes to the Event property. - /// - protected virtual void OnEventChanged(DependencyPropertyChangedEventArgs e) - { - ResetEventBinding(); - } - - #endregion - - static void OwnerReset(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - ((BehaviorBinding)d).ResetEventBinding(); - } - - private void ResetEventBinding() - { - if (Owner != null) //only do this when the Owner is set - { - //check if the Event is set. If yes we need to rebind the Command to the new event and unregister the old one - if (Behavior.Event != null && Behavior.Owner != null) - Behavior.Dispose(); - - //bind the new event to the command - Behavior.BindEvent(Owner, Event); - } - } - - /// - /// This is not actually used. This is just a trick so that this object gets WPF Inheritance Context - /// - /// - protected override Freezable CreateInstanceCore() - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehavior.cs b/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehavior.cs deleted file mode 100644 index d501edf..0000000 --- a/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehavior.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Input; - -namespace BillsManager.ViewModels.Commanding -{ - /// - /// Defines the attached properties to create a CommandBehaviorBinding - /// - public class CommandBehavior - { - #region Behavior - - /// - /// Behavior Attached Dependency Property - /// - private static readonly DependencyProperty BehaviorProperty = - DependencyProperty.RegisterAttached("Behavior", typeof(CommandBehaviorBinding), typeof(CommandBehavior), - new FrameworkPropertyMetadata((CommandBehaviorBinding)null)); - - /// - /// Gets the Behavior property. - /// - private static CommandBehaviorBinding GetBehavior(DependencyObject d) - { - return (CommandBehaviorBinding)d.GetValue(BehaviorProperty); - } - - /// - /// Sets the Behavior property. - /// - private static void SetBehavior(DependencyObject d, CommandBehaviorBinding value) - { - d.SetValue(BehaviorProperty, value); - } - - #endregion - - #region Command - - /// - /// Command Attached Dependency Property - /// - public static readonly DependencyProperty CommandProperty = - DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandBehavior), - new FrameworkPropertyMetadata((ICommand)null, - new PropertyChangedCallback(OnCommandChanged))); - - /// - /// Gets the Command property. - /// - public static ICommand GetCommand(DependencyObject d) - { - return (ICommand)d.GetValue(CommandProperty); - } - - /// - /// Sets the Command property. - /// - public static void SetCommand(DependencyObject d, ICommand value) - { - d.SetValue(CommandProperty, value); - } - - /// - /// Handles changes to the Command property. - /// - private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - CommandBehaviorBinding binding = FetchOrCreateBinding(d); - binding.Command = (ICommand)e.NewValue; - } - - #endregion - - #region Action - - /// - /// Action Attached Dependency Property - /// - public static readonly DependencyProperty ActionProperty = - DependencyProperty.RegisterAttached("Action", typeof(Action), typeof(CommandBehavior), - new FrameworkPropertyMetadata((Action)null, - new PropertyChangedCallback(OnActionChanged))); - - /// - /// Gets the Action property. - /// - public static Action GetAction(DependencyObject d) - { - return (Action)d.GetValue(ActionProperty); - } - - /// - /// Sets the Action property. - /// - public static void SetAction(DependencyObject d, Action value) - { - d.SetValue(ActionProperty, value); - } - - /// - /// Handles changes to the Action property. - /// - private static void OnActionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - CommandBehaviorBinding binding = FetchOrCreateBinding(d); - binding.Action = (Action)e.NewValue; - } - - #endregion - - #region CommandParameter - - /// - /// CommandParameter Attached Dependency Property - /// - public static readonly DependencyProperty CommandParameterProperty = - DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(CommandBehavior), - new FrameworkPropertyMetadata((object)null, - new PropertyChangedCallback(OnCommandParameterChanged))); - - /// - /// Gets the CommandParameter property. - /// - public static object GetCommandParameter(DependencyObject d) - { - return (object)d.GetValue(CommandParameterProperty); - } - - /// - /// Sets the CommandParameter property. - /// - public static void SetCommandParameter(DependencyObject d, object value) - { - d.SetValue(CommandParameterProperty, value); - } - - /// - /// Handles changes to the CommandParameter property. - /// - private static void OnCommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - CommandBehaviorBinding binding = FetchOrCreateBinding(d); - binding.CommandParameter = e.NewValue; - } - - #endregion - - #region Event - - /// - /// Event Attached Dependency Property - /// - public static readonly DependencyProperty EventProperty = - DependencyProperty.RegisterAttached("Event", typeof(string), typeof(CommandBehavior), - new FrameworkPropertyMetadata((string)String.Empty, - new PropertyChangedCallback(OnEventChanged))); - - /// - /// Gets the Event property. This dependency property - /// indicates .... - /// - public static string GetEvent(DependencyObject d) - { - return (string)d.GetValue(EventProperty); - } - - /// - /// Sets the Event property. This dependency property - /// indicates .... - /// - public static void SetEvent(DependencyObject d, string value) - { - d.SetValue(EventProperty, value); - } - - /// - /// Handles changes to the Event property. - /// - private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - CommandBehaviorBinding binding = FetchOrCreateBinding(d); - //check if the Event is set. If yes we need to rebind the Command to the new event and unregister the old one - if (binding.Event != null && binding.Owner != null) - binding.Dispose(); - //bind the new event to the command - binding.BindEvent(d, e.NewValue.ToString()); - } - - #endregion - - #region Helpers - //tries to get a CommandBehaviorBinding from the element. Creates a new instance if there is not one attached - private static CommandBehaviorBinding FetchOrCreateBinding(DependencyObject d) - { - CommandBehaviorBinding binding = CommandBehavior.GetBehavior(d); - if (binding == null) - { - binding = new CommandBehaviorBinding(); - CommandBehavior.SetBehavior(d, binding); - } - return binding; - } - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehaviorBinding.cs b/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehaviorBinding.cs deleted file mode 100644 index 5a203cd..0000000 --- a/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehaviorBinding.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Reflection; -using System.Windows; -using System.Windows.Input; - -namespace BillsManager.ViewModels.Commanding -{ - /// - /// Defines the command behavior binding - /// - public class CommandBehaviorBinding : IDisposable - { - #region Properties - /// - /// Get the owner of the CommandBinding ex: a Button - /// This property can only be set from the BindEvent Method - /// - public DependencyObject Owner { get; private set; } - /// - /// The event name to hook up to - /// This property can only be set from the BindEvent Method - /// - public string EventName { get; private set; } - /// - /// The event info of the event - /// - public EventInfo Event { get; private set; } - /// - /// Gets the EventHandler for the binding with the event - /// - public Delegate EventHandler { get; private set; } - - #region Execution - //stores the strategy of how to execute the event handler - IExecutionStrategy strategy; - - /// - /// Gets or sets a CommandParameter - /// - public object CommandParameter { get; set; } - - ICommand command; - /// - /// The command to execute when the specified event is raised - /// - public ICommand Command - { - get { return command; } - set - { - command = value; - //set the execution strategy to execute the command - strategy = new CommandExecutionStrategy { Behavior = this }; - } - } - - Action action; - /// - /// Gets or sets the Action - /// - public Action Action - { - get { return action; } - set - { - action = value; - // set the execution strategy to execute the action - strategy = new ActionExecutionStrategy { Behavior = this }; - } - } - #endregion - - #endregion - - //Creates an EventHandler on runtime and registers that handler to the Event specified - public void BindEvent(DependencyObject owner, string eventName) - { - EventName = eventName; - Owner = owner; - Event = Owner.GetType().GetEvent(EventName, BindingFlags.Public | BindingFlags.Instance); - if (Event == null) - throw new InvalidOperationException(String.Format("Could not resolve event name {0}", EventName)); - - //Create an event handler for the event that will call the ExecuteCommand method - EventHandler = EventHandlerGenerator.CreateDelegate( - Event.EventHandlerType, typeof(CommandBehaviorBinding).GetMethod("Execute", BindingFlags.Public | BindingFlags.Instance), this); - //Register the handler to the Event - Event.AddEventHandler(Owner, EventHandler); - } - - /// - /// Executes the strategy - /// - public void Execute() - { - strategy.Execute(CommandParameter); - } - - #region IDisposable Members - bool disposed = false; - /// - /// Unregisters the EventHandler from the Event - /// - public void Dispose() - { - if (!disposed) - { - Event.RemoveEventHandler(Owner, EventHandler); - disposed = true; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehaviorCollection.cs b/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehaviorCollection.cs deleted file mode 100644 index ddb79fb..0000000 --- a/BillsManager.ViewModels/Commanding/EventToCommand/CommandBehaviorCollection.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Specialized; -using System.Windows; - -namespace BillsManager.ViewModels.Commanding -{ - public class CommandBehaviorCollection - { - #region Behaviors - - /// - /// Behaviors Read-Only Dependency Property - /// As you can see the Attached readonly property has a name registered different (BehaviorsInternal) than the property name, this is a tricks os that we can construct the collection as we want - /// Read more about this here http://wekempf.spaces.live.com/blog/cns!D18C3EC06EA971CF!468.entry - /// - private static readonly DependencyPropertyKey BehaviorsPropertyKey - = DependencyProperty.RegisterAttachedReadOnly("BehaviorsInternal", typeof(BehaviorBindingCollection), typeof(CommandBehaviorCollection), - new FrameworkPropertyMetadata((BehaviorBindingCollection)null)); - - public static readonly DependencyProperty BehaviorsProperty - = BehaviorsPropertyKey.DependencyProperty; - - /// - /// Gets the Behaviors property. - /// Here we initialze the collection and set the Owner property - /// - public static BehaviorBindingCollection GetBehaviors(DependencyObject d) - { - if (d == null) - throw new InvalidOperationException("The dependency object trying to attach to is set to null"); - - BehaviorBindingCollection collection = d.GetValue(CommandBehaviorCollection.BehaviorsProperty) as BehaviorBindingCollection; - if (collection == null) - { - collection = new BehaviorBindingCollection(); - collection.Owner = d; - SetBehaviors(d, collection); - } - return collection; - } - - /// - /// Provides a secure method for setting the Behaviors property. - /// This dependency property indicates .... - /// - private static void SetBehaviors(DependencyObject d, BehaviorBindingCollection value) - { - d.SetValue(BehaviorsPropertyKey, value); - INotifyCollectionChanged collection = (INotifyCollectionChanged)value; - collection.CollectionChanged += new NotifyCollectionChangedEventHandler(CollectionChanged); - } - - static void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) - { - BehaviorBindingCollection sourceCollection = (BehaviorBindingCollection)sender; - switch (e.Action) - { - //when an item(s) is added we need to set the Owner property implicitly - case NotifyCollectionChangedAction.Add: - if (e.NewItems != null) - foreach (BehaviorBinding item in e.NewItems) - item.Owner = sourceCollection.Owner; - break; - //when an item(s) is removed we should Dispose the BehaviorBinding - case NotifyCollectionChangedAction.Remove: - if (e.OldItems != null) - foreach (BehaviorBinding item in e.OldItems) - item.Behavior.Dispose(); - break; - - //here we have to set the owner property to the new item and unregister the old item - case NotifyCollectionChangedAction.Replace: - if (e.NewItems != null) - foreach (BehaviorBinding item in e.NewItems) - item.Owner = sourceCollection.Owner; - - if (e.OldItems != null) - foreach (BehaviorBinding item in e.OldItems) - item.Behavior.Dispose(); - break; - - //when an item(s) is removed we should Dispose the BehaviorBinding - case NotifyCollectionChangedAction.Reset: - if (e.OldItems != null) - foreach (BehaviorBinding item in e.OldItems) - item.Behavior.Dispose(); - break; - - case NotifyCollectionChangedAction.Move: - default: - break; - } - } - - #endregion - } - - /// - /// Collection to store the list of behaviors. This is done so that you can intiniate it from XAML - /// This inherits from freezable so that it gets inheritance context for DataBinding to work - /// - public class BehaviorBindingCollection : FreezableCollection - { - /// - /// Gets or sets the Owner of the binding - /// - public DependencyObject Owner { get; set; } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Commanding/EventToCommand/EventHandlerGenerator.cs b/BillsManager.ViewModels/Commanding/EventToCommand/EventHandlerGenerator.cs deleted file mode 100644 index a860beb..0000000 --- a/BillsManager.ViewModels/Commanding/EventToCommand/EventHandlerGenerator.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Reflection; -using System.Reflection.Emit; - -namespace BillsManager.ViewModels.Commanding -{ - /// - /// Generates delegates according to the specified signature on runtime - /// - public static class EventHandlerGenerator - { - /// - /// Generates a delegate with a matching signature of the supplied eventHandlerType - /// This method only supports Events that have a delegate of type void - /// - /// The delegate type to wrap. Note that this must always be a void delegate - /// The method to invoke - /// The object where the method resides - /// Returns a delegate with the same signature as eventHandlerType that calls the methodToInvoke inside - public static Delegate CreateDelegate(Type eventHandlerType, MethodInfo methodToInvoke, object methodInvoker) - { - //Get the eventHandlerType signature - var eventHandlerInfo = eventHandlerType.GetMethod("Invoke"); - Type returnType = eventHandlerInfo.ReturnParameter.ParameterType; - if (returnType != typeof(void)) - throw new ApplicationException("Delegate has a return type. This only supprts event handlers that are void"); - - ParameterInfo[] delegateParameters = eventHandlerInfo.GetParameters(); - //Get the list of type of parameters. Please note that we do + 1 because we have to push the object where the method resides i.e methodInvoker parameter - Type[] hookupParameters = new Type[delegateParameters.Length + 1]; - hookupParameters[0] = methodInvoker.GetType(); - for (int i = 0; i < delegateParameters.Length; i++) - hookupParameters[i + 1] = delegateParameters[i].ParameterType; - - DynamicMethod handler = new DynamicMethod("", null, - hookupParameters, typeof(EventHandlerGenerator)); - - ILGenerator eventIL = handler.GetILGenerator(); - - //load the parameters or everything will just BAM :) - LocalBuilder local = eventIL.DeclareLocal(typeof(object[])); - eventIL.Emit(OpCodes.Ldc_I4, delegateParameters.Length + 1); - eventIL.Emit(OpCodes.Newarr, typeof(object)); - eventIL.Emit(OpCodes.Stloc, local); - - //start from 1 because the first item is the instance. Load up all the arguments - for (int i = 1; i < delegateParameters.Length + 1; i++) - { - eventIL.Emit(OpCodes.Ldloc, local); - eventIL.Emit(OpCodes.Ldc_I4, i); - eventIL.Emit(OpCodes.Ldarg, i); - eventIL.Emit(OpCodes.Stelem_Ref); - } - - eventIL.Emit(OpCodes.Ldloc, local); - - //Load as first argument the instance of the object for the methodToInvoke i.e methodInvoker - eventIL.Emit(OpCodes.Ldarg_0); - - //Now that we have it all set up call the actual method that we want to call for the binding - eventIL.EmitCall(OpCodes.Call, methodToInvoke, null); - - eventIL.Emit(OpCodes.Pop); - eventIL.Emit(OpCodes.Ret); - - //create a delegate from the dynamic method - return handler.CreateDelegate(eventHandlerType, methodInvoker); - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Commanding/EventToCommand/ExecutionStrategy.cs b/BillsManager.ViewModels/Commanding/EventToCommand/ExecutionStrategy.cs deleted file mode 100644 index 218bdba..0000000 --- a/BillsManager.ViewModels/Commanding/EventToCommand/ExecutionStrategy.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; - -namespace BillsManager.ViewModels.Commanding -{ - /// - /// Defines the interface for a strategy of execution for the CommandBehaviorBinding - /// - public interface IExecutionStrategy - { - /// - /// Gets or sets the Behavior that we execute this strategy - /// - CommandBehaviorBinding Behavior { get; set; } - - /// - /// Executes according to the strategy type - /// - /// The parameter to be used in the execution - void Execute(object parameter); - } - - /// - /// Executes a command - /// - public class CommandExecutionStrategy : IExecutionStrategy - { - #region IExecutionStrategy Members - /// - /// Gets or sets the Behavior that we execute this strategy - /// - public CommandBehaviorBinding Behavior { get; set; } - - /// - /// Executes the Command that is stored in the CommandProperty of the CommandExecution - /// - /// The parameter for the command - public void Execute(object parameter) - { - if (Behavior == null) - throw new InvalidOperationException("Behavior property cannot be null when executing a strategy"); - - if (Behavior.Command.CanExecute(Behavior.CommandParameter)) - Behavior.Command.Execute(Behavior.CommandParameter); - } - - #endregion - } - - /// - /// executes a delegate - /// - public class ActionExecutionStrategy : IExecutionStrategy - { - #region IExecutionStrategy Members - - /// - /// Gets or sets the Behavior that we execute this strategy - /// - public CommandBehaviorBinding Behavior { get; set; } - - /// - /// Executes an Action delegate - /// - /// The parameter to pass to the Action - public void Execute(object parameter) - { - Behavior.Action(parameter); - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Commanding/RelayCommand/RelayCommand.cs b/BillsManager.ViewModels/Commanding/RelayCommand/RelayCommand.cs deleted file mode 100644 index 5666847..0000000 --- a/BillsManager.ViewModels/Commanding/RelayCommand/RelayCommand.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Windows.Input; -using BillsManager.ViewModels.Helpers; - -namespace BillsManager.ViewModels.Commanding -{ - /// - /// A command whose sole purpose is to relay its functionality to other - /// objects by invoking delegates. The default return value for the CanExecute - /// method is 'true'. This class does not allow you to accept command parameters in the - /// Execute and CanExecute callback methods. - /// - ////[ClassInfo(typeof(RelayCommand), - //// VersionString = "4.0.11", - //// DateString = "201206191330", - //// Description = "A command whose sole purpose is to relay its functionality to other objects by invoking delegates.", - //// UrlContacts = "http://www.galasoft.ch/contact_en.html", - //// Email = "laurent@galasoft.ch")] - public class RelayCommand : ICommand - { - - private readonly WeakAction _execute; - - private readonly WeakFunc _canExecute; - - /// - /// Initializes a new instance of the RelayCommand class that - /// can always execute. - /// - /// The execution logic. - /// If the execute argument is null. - public RelayCommand(Action execute) - : this(execute, null) - { - } - - /// - /// Initializes a new instance of the RelayCommand class. - /// - /// The execution logic. - /// The execution status logic. - /// If the execute argument is null. - public RelayCommand(Action execute, Func canExecute) - { - if (execute == null) - { - throw new ArgumentNullException("execute"); - } - - _execute = new WeakAction(execute); - - if (canExecute != null) - { - _canExecute = new WeakFunc(canExecute); - } - } - - /// - /// Occurs when changes occur that affect whether the command should execute. - /// - public event EventHandler CanExecuteChanged - { - add - { - if (_canExecute != null) - { - CommandManager.RequerySuggested += value; - } - } - - remove - { - if (_canExecute != null) - { - CommandManager.RequerySuggested -= value; - } - } - } - - /// - /// Raises the event. - /// - [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", - Justification = "The this keyword is used in the Silverlight version")] - [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", - Justification = "This cannot be an event")] - public void RaiseCanExecuteChanged() - { - CommandManager.InvalidateRequerySuggested(); - } - - /// - /// Defines the method that determines whether the command can execute in its current state. - /// - /// This parameter will always be ignored. - /// true if this command can be executed; otherwise, false. - public bool CanExecute(object parameter) - { - return _canExecute == null - ? true - : (_canExecute.IsStatic || _canExecute.IsAlive) - ? _canExecute.Execute() - : false; - } - - /// - /// Defines the method to be called when the command is invoked. - /// - /// This parameter will always be ignored. - public virtual void Execute(object parameter) - { - if (CanExecute(parameter) - && _execute != null - && (_execute.IsStatic || _execute.IsAlive)) - { - _execute.Execute(); - } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Commanding/RelayCommand/RelayCommandGeneric.cs b/BillsManager.ViewModels/Commanding/RelayCommand/RelayCommandGeneric.cs deleted file mode 100644 index 1818a96..0000000 --- a/BillsManager.ViewModels/Commanding/RelayCommand/RelayCommandGeneric.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Windows.Input; -using BillsManager.ViewModels.Helpers; - -namespace BillsManager.ViewModels.Commanding -{ - /// - /// A generic command whose sole purpose is to relay its functionality to other - /// objects by invoking delegates. The default return value for the CanExecute - /// method is 'true'. This class allows you to accept command parameters in the - /// Execute and CanExecute callback methods. - /// - /// The type of the command parameter. - //// [ClassInfo(typeof(RelayCommand)] - public class RelayCommand : ICommand - { - private readonly WeakAction _execute; - - private readonly WeakFunc _canExecute; - - /// - /// Initializes a new instance of the RelayCommand class that - /// can always execute. - /// - /// The execution logic. - /// If the execute argument is null. - public RelayCommand(Action execute) - : this(execute, null) - { - } - - /// - /// Initializes a new instance of the RelayCommand class. - /// - /// The execution logic. - /// The execution status logic. - /// If the execute argument is null. - public RelayCommand(Action execute, Func canExecute) - { - if (execute == null) - { - throw new ArgumentNullException("execute"); - } - - _execute = new WeakAction(execute); - - if (canExecute != null) - { - _canExecute = new WeakFunc(canExecute); - } - } - - /// - /// Occurs when changes occur that affect whether the command should execute. - /// - public event EventHandler CanExecuteChanged - { - add - { - if (_canExecute != null) - { - CommandManager.RequerySuggested += value; - } - } - - remove - { - if (_canExecute != null) - { - CommandManager.RequerySuggested -= value; - } - } - } - - /// - /// Raises the event. - /// - [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", - Justification = "The this keyword is used in the Silverlight version")] - [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", - Justification = "This cannot be an event")] - public void RaiseCanExecuteChanged() - { - CommandManager.InvalidateRequerySuggested(); - } - - /// - /// Defines the method that determines whether the command can execute in its current state. - /// - /// Data used by the command. If the command does not require data - /// to be passed, this object can be set to a null reference - /// true if this command can be executed; otherwise, false. - public bool CanExecute(object parameter) - { - if (_canExecute == null) - { - return true; - } - - if (_canExecute.IsStatic || _canExecute.IsAlive) - { - if (parameter == null && typeof(T).IsValueType) - { - return _canExecute.Execute(default(T)); - } - - return _canExecute.Execute((T)parameter); - } - - return false; - } - - /// - /// Defines the method to be called when the command is invoked. - /// - /// Data used by the command. If the command does not require data - /// to be passed, this object can be set to a null reference - public virtual void Execute(object parameter) - { - var val = parameter; - - if (parameter != null - && parameter.GetType() != typeof(T)) - { - if (parameter is IConvertible) - { - val = Convert.ChangeType(parameter, typeof(T), null); - } - } - - if (CanExecute(val) - && _execute != null - && (_execute.IsStatic || _execute.IsAlive)) - { - if (val == null) - { - if (typeof(T).IsValueType) - { - _execute.Execute(default(T)); - } - else - { - _execute.Execute((T)val); - } - } - else - { - _execute.Execute((T)val); - } - } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DBViewModel.cs b/BillsManager.ViewModels/DBViewModel.cs deleted file mode 100644 index 74993ce..0000000 --- a/BillsManager.ViewModels/DBViewModel.cs +++ /dev/null @@ -1,464 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Models; -using BillsManager.Services.DB; -using BillsManager.ViewModels.Commanding; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Windows; - -namespace BillsManager.ViewModels -{ - public partial class DBViewModel : Conductor.Collection.AllActive, - IHandle, - IHandle - { - #region fields - - private readonly IWindowManager windowManager; - private readonly IEventAggregator globalEventAggregator; - private readonly IDBService dbConnector; - - private readonly Func suppliersViewModelFactory; - private readonly Func billsViewModelFactory; - //private readonly Func tagsViewModelFactory; - - private readonly Func searchSuppliersViewModelFactory; - private readonly Func searchBillsViewModelFactory; - - private readonly Func, string, string, PrintReportViewModel> reportCenterViewModelFactory; - - #endregion - - #region ctor - - public DBViewModel( - IWindowManager windowManager, - IEventAggregator dbEventAggregator, - IDBService dbConnector, - Func suppliersViewModelFactory, - Func billsViewModelFactory, - //Func tagsViewModelFactory, - Func searchSuppliersViewModelFactory, - Func searchBillsViewModelFactory, - // IDEA: move report to tools? - Func, string, string, PrintReportViewModel> reportCenterViewModelFactory) - { - // SERVICES - this.windowManager = windowManager; - this.globalEventAggregator = dbEventAggregator; - this.dbConnector = dbConnector; - - // FACTORIES - this.suppliersViewModelFactory = suppliersViewModelFactory; - this.billsViewModelFactory = billsViewModelFactory; - //this.tagsViewModelFactory = tagsViewModelFactory; - - this.searchSuppliersViewModelFactory = searchSuppliersViewModelFactory; - this.searchBillsViewModelFactory = searchBillsViewModelFactory; - - this.reportCenterViewModelFactory = reportCenterViewModelFactory; - - // SUBSCRIPTIONS - this.globalEventAggregator.Subscribe(this); - - // HANDLERS - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - this.globalEventAggregator.Unsubscribe(this); - }; - - //UI - this.DisplayName = @"Bills Manager Database"; - - // START - //if (this.settingsProvider.Settings.StartupDBLoad) - //{ - // this.SuppliersViewModel.LoadSuppliers(); - // this.BillsViewModel.LoadBills(); - //} - } - - #endregion - - #region properties - - private BillsViewModel billsViewModel; - public BillsViewModel BillsViewModel - { - get { return this.billsViewModel; } - private set - { - if (this.billsViewModel == value) return; - - this.billsViewModel = value; - this.NotifyOfPropertyChange(() => this.BillsViewModel); - } - } - - private SuppliersViewModel suppliersViewModel; - public SuppliersViewModel SuppliersViewModel - { - get { return this.suppliersViewModel; } - private set - { - if (this.suppliersViewModel == value) return; - - this.suppliersViewModel = value; - this.NotifyOfPropertyChange(() => this.SuppliersViewModel); - } - } - - //private TagsViewModel tagsViewModel; - //public TagsViewModel TagsViewModel - //{ - // get { return this.tagsViewModel; } - // private set - // { - // if (this.tagsViewModel == value) return; - - // this.tagsViewModel = value; - // this.NotifyOfPropertyChange(() => this.TagsViewModel); - // } - //} - - private SearchSuppliersViewModel searchSuppliersViewModel; - public SearchSuppliersViewModel SearchSuppliersViewModel - { - get - { - //if (this.searchSuppliersViewModel == null) - // this.searchSuppliersViewModel = this.searchSuppliersViewModelFactory.Invoke(this.dbEventAggregator.Value); - - return this.searchSuppliersViewModel; - } - private set - { - if (this.searchSuppliersViewModel == value) return; - - this.searchSuppliersViewModel = value; - this.NotifyOfPropertyChange(() => this.SearchSuppliersViewModel); - } - } - - private SearchBillsViewModel searchBillsViewModel; - public SearchBillsViewModel SearchBillsViewModel - { - get - { - //if (this.searchBillsViewModel == null) - // this.searchBillsViewModel = this.searchBillsViewModelFactory.Invoke(this.dbEventAggregator.Value); - - return this.searchBillsViewModel; - } - private set - { - if (this.searchBillsViewModel == value) return; - - this.searchBillsViewModel = value; - this.NotifyOfPropertyChange(() => this.SearchBillsViewModel); - } - } - - private DBConnectionState dbConnectionState = DBConnectionState.Disconnected; - public DBConnectionState ConnectionState - { - get { return this.dbConnectionState; } - set - { - if (this.dbConnectionState != value) - { - this.dbConnectionState = value; - this.NotifyOfPropertyChange(() => this.ConnectionState); - this.globalEventAggregator.PublishOnUIThread(new DBConnectionStateChangedMessage(this.ConnectionState)); - - this.NotifyOfPropertyChange(() => this.IsConnectionActive); - } - } - } - - public bool IsConnectionActive - { - get - { - return this.ConnectionState != DBConnectionState.Disconnected; - } - } - - private bool showFilters; - public bool ShowFilters - { - get { return this.showFilters; } - set - { - if (this.showFilters == value) return; - - this.showFilters = value; - this.NotifyOfPropertyChange(() => this.ShowFilters); - } - } - - #region overrides - - public override void CanClose(System.Action callback) - { - if (this.ConnectionState != DBConnectionState.Disconnected) - callback(this.Disconnect()); - else - callback(true); - } - - #endregion - - #endregion - - #region methods - - public bool Connect() - { - // TODO: give control to UI thread - - //var progressDialog = new ProgressViewModel("Loading ..."); - //this.windowManager.ShowWindow(progressDialog); - - if (this.dbConnector.Connect()) - { - this.ConnectionState = DBConnectionState.Connected; - - this.SuppliersViewModel = this.suppliersViewModelFactory.Invoke(); - this.BillsViewModel = this.billsViewModelFactory.Invoke(); - - this.SearchSuppliersViewModel = this.searchSuppliersViewModelFactory.Invoke(); - this.SearchBillsViewModel = this.searchBillsViewModelFactory.Invoke(); - - this.ActivateItem(this.SearchSuppliersViewModel); - this.ActivateItem(this.SearchBillsViewModel); - - this.ActivateItem(this.SuppliersViewModel); - this.ActivateItem(this.BillsViewModel); - - //progressDialog.TryClose(); - - return true; - } - - //progressDialog.TryClose(); - - DialogViewModel dbConnectionErrorDialog = - DialogViewModel.Show( - DialogType.Error, - TranslationManager.Instance.Translate("DatabaseConnectionFailed"), - TranslationManager.Instance.Translate("DatabaseConnectionFailedMessage") + - Environment.NewLine + - TranslationManager.Instance.Translate("TryAgain")) - .Ok(); - - this.windowManager.ShowDialog(dbConnectionErrorDialog); - - return false; - } - - public bool Disconnect() - { - if (this.ConnectionState == DBConnectionState.Unsaved) - { - DialogViewModel saveBeforeDisconnectDialog = - DialogViewModel.Show( - DialogType.Question, - TranslationManager.Instance.Translate("SaveQuestion"), - TranslationManager.Instance.Translate("ChangesNotSavedMessage") + - Environment.NewLine + - Environment.NewLine + - TranslationManager.Instance.Translate("SaveBeforeClosingQuestion")) - .YesNoCancel( - TranslationManager.Instance.Translate("SaveAndExit"), - TranslationManager.Instance.Translate("DontSave"), - TranslationManager.Instance.Translate("CancelExit")); - - this.windowManager.ShowDialog(saveBeforeDisconnectDialog); - - switch (saveBeforeDisconnectDialog.FinalResponse) - { - case ResponseType.Yes: - if (!this.Save()) - { - DialogViewModel errorDialog = - DialogViewModel.Show( - DialogType.Error, - TranslationManager.Instance.Translate("DatabaseSaveFailed"), - TranslationManager.Instance.Translate("DatabaseSaveFailedMessage") + - Environment.NewLine + - TranslationManager.Instance.Translate("TryAgain")) - .Ok(); - - this.windowManager.ShowDialog(errorDialog); - - return false; - } - break; - - case ResponseType.No: - this.ConnectionState = DBConnectionState.Connected; - break; - - case ResponseType.Cancel: - return false; - } - } - - this.dbConnector.Disconnect(); - - this.ConnectionState = DBConnectionState.Disconnected; - - this.SearchSuppliersViewModel.TryClose(); - this.SearchBillsViewModel.TryClose(); - - this.SearchSuppliersViewModel = null; - this.SearchBillsViewModel = null; - - //this.TagsViewModel.TryClose(); - this.SuppliersViewModel.TryClose(); - this.BillsViewModel.TryClose(); /* TODO: review closing order, since this is an AllActive - * a check is needed on whether the canclose automatically closes - * activeitems or these 2 lines are required anyhow */ - this.SuppliersViewModel = null; - this.BillsViewModel = null; - //this.TagsViewModel = null; - - return true; - } - - private bool Save() - { - if (this.dbConnector.Save()) - { - this.ConnectionState = DBConnectionState.Connected; - return true; - } - - return false; - } - - private void ShowReportCenter() - { - var billReports = this.BillsViewModel.FilteredBillViewModels.Select(bvm => new BillReportViewModel(bvm)); - - var header = @"Bills Manager"; - var comment = string.Empty; - if (!string.IsNullOrWhiteSpace(this.BillsViewModel.FiltersDescription)) - comment += this.BillsViewModel.FiltersDescription; - - this.windowManager.ShowDialog( - this.reportCenterViewModelFactory.Invoke(billReports, header, comment), - settings: new Dictionary() - { - { "CanClose", true }, - { "WindowState", WindowState.Maximized}, - { "SizeToContent", SizeToContent.Manual}, - { "ResizeMode", ResizeMode.CanResize }, - { "AllowsTransparency", false }, - { "WindowStyle", WindowStyle.SingleBorderWindow } - }); - } - - private void ToggleShowFilters() - { - this.ShowFilters = !this.ShowFilters; - } - - #region message handlers - - //public void Handle(SuppliersListChangedMessage message) - //{ - // this.IsDirty = true; // TODO: why is it called 3 times? - //} - - //public void Handle(BillsListChangedMessage message) - //{ - // this.IsDirty = true; // TODO: why is it called 3 times? - //} - - public void Handle(CRUDMessage message) - { - this.ConnectionState = DBConnectionState.Unsaved; - } - - public void Handle(ShowSuppliersBillsOrder message) - { - if (!this.ShowFilters) - this.ShowFilters = true; - } - - #endregion - - #endregion - - #region commands - - private RelayCommand connectCommand; - public RelayCommand ConnectCommand - { - get - { - return this.connectCommand ?? (this.connectCommand = - new RelayCommand( - () => this.Connect(), - () => this.ConnectionState == DBConnectionState.Disconnected)); - } - } - - private RelayCommand disconnectCommand; - public RelayCommand DisconnectCommand - { - get - { - return this.disconnectCommand ?? (this.disconnectCommand = - new RelayCommand( - () => this.Disconnect(), - () => this.ConnectionState != DBConnectionState.Disconnected)); - } - } - - private RelayCommand saveCommand; - public RelayCommand SaveCommand - { - get - { - return this.saveCommand ?? (this.saveCommand = - new RelayCommand( - () => this.Save(), - () => this.ConnectionState == DBConnectionState.Unsaved)); - } - } - - private RelayCommand showReportCenterCommand; - public RelayCommand ShowReportCenterCommand - { - get - { - return this.showReportCenterCommand ?? (this.showReportCenterCommand = - new RelayCommand( - () => this.ShowReportCenter(), - () => this.IsConnectionActive)); - } - } - - private RelayCommand toggleShowFiltersCommand; - public RelayCommand ToggleShowFiltersCommand - { - get - { - return this.toggleShowFiltersCommand ?? (this.toggleShowFiltersCommand = - new RelayCommand( - () => this.ToggleShowFilters())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DBsViewModel.cs b/BillsManager.ViewModels/DBsViewModel.cs deleted file mode 100644 index c0de8a2..0000000 --- a/BillsManager.ViewModels/DBsViewModel.cs +++ /dev/null @@ -1,457 +0,0 @@ -using BillsManager.Services.Providers; -using BillsManager.ViewModels.Commanding; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public partial class DBsViewModel : Conductor.Collection.OneActive, - IHandle - { - #region fields - - private readonly IWindowManager windowManager; - private readonly IEventAggregator eventAggregator; - private readonly IDBsProvider dbsProvider; - - private readonly Func dbViewModelFactory; - private readonly Func, string, DBAddEditViewModel> dbAddViewModelFactory; - - #endregion - - #region ctor - - public DBsViewModel( - IWindowManager windowManager, - IEventAggregator eventAggregator, - IDBsProvider dbsProvider, - Func dbViewModelFactory, - Func, string, DBAddEditViewModel> dbAddEditViewModelFactory) - { - // SERVICES - this.windowManager = windowManager; - this.eventAggregator = eventAggregator; - this.dbsProvider = dbsProvider; - - // FACTORIES - this.dbViewModelFactory = dbViewModelFactory; - this.dbAddViewModelFactory = dbAddEditViewModelFactory; - - // SUBSCRIPTIONS - this.eventAggregator.Subscribe(this); - - // HANDLERS - this.Deactivated += - (s, e) => - { - if (e.WasClosed) this.eventAggregator.Unsubscribe(this); - }; - - this.ActivationProcessed += - (s, e) => - { - this.eventAggregator.Publish(new ActiveDBChangedMessage(this.ActiveItem)); - }; - - // START - this.RefreshDBsList(); - } - - #endregion - - #region properties - - private ObservableCollection notOpenedDBs; // TODO: readonly property that filter from all dbs those that are in this.items? - public ObservableCollection NotOpenedDBs - { - get - { - if (this.notOpenedDBs == null) - { - this.notOpenedDBs = new ObservableCollection(); - } - - return this.notOpenedDBs; - } - //private set - //{ - // if (this.notOpenedDBs == value) return; - - // this.notOpenedDBs = value; - // this.NotifyOfPropertyChange(() => this.NotOpenedDBs); - - //} - } - - private DBViewModel selectedDB; - public DBViewModel SelectedDB - { - get { return this.selectedDB; } - set - { - if (this.selectedDB == value) return; - - this.selectedDB = null; - this.NotifyOfPropertyChange(() => this.SelectedDB); - - //if (value == null) return; - - this.selectedDB = value; - this.NotifyOfPropertyChange(() => this.SelectedDB); - - if (!this.NotOpenedDBs.Contains(value)) - { - if (value != this.ActiveItem) - this.ActiveItem = value; - } - } - } - - public override void CanClose(Action callback) - { - //base.CanClose(callback); - - //foreach (var dbvm in this.Items.ToList()) // URGENT: dbs can be gc'd if ram is oom - //{ - // if (!dbvm.IsConnected) - // this.MoveToNotOpened(dbvm); - //} - - //if (this.ActiveItem != null & !this.Items.Contains(this.ActiveItem)) - //{ - // if (this.SelectedDB != null & !this.NotOpenedDBs.Contains(this.SelectedDB)) - // { - // this.SelectedDB = this.Items.FirstOrDefault(); - // } - // else - // this.ActiveItem = this.Items.FirstOrDefault(); - //} - - CloseStrategy.Execute(this.Items.ToList(), (canClose, closeables) => - { - if (!canClose && closeables.Any()) - { - if (closeables.Contains(this.ActiveItem)) - { - var itemsCopy = this.Items.ToList(); - var next = this.ActiveItem; - - do - { - var previous = next; - next = this.DetermineNextItemToActivate(itemsCopy, itemsCopy.IndexOf(previous)); - itemsCopy.Remove(previous); - } - while (closeables.Contains(next)); - - var previousActive = this.ActiveItem; - ChangeActiveItem(next, true); - //this.Items.Remove(previousActive); - this.MoveToNotOpened(previousActive); - - var stillToClose = closeables.ToList(); - stillToClose.Remove(previousActive); - closeables = stillToClose; - } - - closeables.OfType().Apply(x => x.Deactivate(true)); - //this.Items.RemoveRange(closeables); - closeables.Apply(c => this.MoveToNotOpened(c)); - } - - callback(canClose); - }); - - } - - #endregion - - #region methods - - private void RefreshDBsList() - { - var availableDBPaths = this.dbsProvider.GetAll(); - - // remove the dbs that are loaded (and not opened) but no longer exist - var loadedDBPaths = this.NotOpenedDBs.Select(dbvm => dbvm.Path).Concat(this.Items.Select(dbvm => dbvm.Path)); - var disappearedDBs = loadedDBPaths.Where(path => !availableDBPaths.Contains(path)); - - foreach (var disDBPath in disappearedDBs.ToList()) - { - var toRemoveDB = this.NotOpenedDBs.Single(dbvm => dbvm.Path == disDBPath); - toRemoveDB.TryClose(); - this.NotOpenedDBs.Remove(toRemoveDB); - } - - // add newly found dbs to the notopenedbs list - var toAddDBPaths = availableDBPaths.Where(avDBPath => !loadedDBPaths.Contains(avDBPath)); - toAddDBPaths.Apply(newDBPath => this.NotOpenedDBs.Add(this.dbViewModelFactory.Invoke(newDBPath))); - } - - #region CRUD - - private void CreateDB() - { - var takenNames = this.Items.Select(dbvm => dbvm.DBName).Concat(this.NotOpenedDBs.Select(dbvm => dbvm.DBName)); - var newDBVM = this.dbAddViewModelFactory.Invoke(takenNames, null); - - if (this.windowManager.ShowDialog(newDBVM).Value == true) - { - if (this.dbsProvider.CreateDB(newDBVM.NewDBName.Trim())) // TODO: move trim to adddbvm while typing - { - this.RefreshDBsList(); - var justAddedDB = this.NotOpenedDBs.Single(dbvm => dbvm.DBName == newDBVM.NewDBName); - if (justAddedDB != null && newDBVM.AddAndOpen) - this.OpenDB(justAddedDB); - } - else - this.windowManager.ShowDialog( - new DialogViewModel( - "Create database failed", // TODO: language - "There was a problem during the DB creation process. Please try again.")); - } - } - - // TODO: create parallel db loading while using another one - private void OpenDB(DBViewModel dbViewModel) - { - if (!this.NotOpenedDBs.Contains(dbViewModel)) return; - - if (dbViewModel.TryConnectDB()) - { - var wasSelected = this.SelectedDB == dbViewModel; - - this.MoveToOpened(dbViewModel); - - if (this.Items.Contains(this.SelectedDB) | wasSelected | !this.NotOpenedDBs.Contains(this.SelectedDB)) - this.SelectedDB = dbViewModel; - else - this.ActiveItem = dbViewModel; - - this.eventAggregator.Publish(new ActiveDBChangedMessage(this.ActiveItem)); - } - } - - private void CloseDB(DBViewModel dbViewModel) - { - if (!this.Items.Contains(dbViewModel)) return; - - if (dbViewModel.TryDisconnectDB()) - { - var wasActive = this.ActiveItem == dbViewModel; - var wasSelected = this.SelectedDB == this.ActiveItem; - if (this.SelectedDB == dbViewModel) - this.SelectedDB = null; - else - if (dbViewModel == this.ActiveItem) - this.ActiveItem = null; - - this.MoveToNotOpened(dbViewModel); - - if (wasActive) - { - var newActive = this.Items.LastOrDefault(); - if (wasSelected) - this.SelectedDB = newActive; - else - this.ActiveItem = newActive; - } - - this.eventAggregator.Publish(new ActiveDBChangedMessage(this.ActiveItem)); - } - } - - private void RenameDB(DBViewModel dbViewModel) - { - var takenNames = this.Items.Select(dbvm => dbvm.DBName).Concat(this.NotOpenedDBs.Select(dbvm => dbvm.DBName)); - var renameDBVM = this.dbAddViewModelFactory.Invoke(takenNames, dbViewModel.DBName); - var oldName = dbViewModel.DBName; - - if (this.windowManager.ShowDialog(renameDBVM).Value == true) - { - if (this.dbsProvider.RenameDB(oldName, renameDBVM.NewDBName.Trim())) // TODO: move trim to adddbvm while typing - this.RefreshDBsList(); - else - this.windowManager.ShowDialog( - new DialogViewModel( - "Rename database failed", // TODO: language - "There was a problem during the DB renaming process, please try again.")); - } - } - - private void DeleteDB(DBViewModel dbViewModel) - { - var firstConfirmDialog = new DialogViewModel( // TODO: language - "Delete database", - "Are you sure you want to delete database '" + dbViewModel.DBName + "' ?" + - Environment.NewLine + - Environment.NewLine + - "WARNING: the database will be deleted permanently, " + - "with no chance to revert the operation.", - new[] { new DialogResponse(ResponseType.Yes, "DELETE", "Delete '" + dbViewModel.DBName + "'"), new DialogResponse(ResponseType.Cancel) }); - - this.windowManager.ShowDialog( - firstConfirmDialog/*, - settings: new Dictionary { { "MaxWidth", 500 } }*/); - - if (firstConfirmDialog.FinalResponse == ResponseType.Yes) // TODO: dialogView needs a width limit - { - var secondConfirmDialog = - new DialogViewModel( - "Delete database final confirm", // TODO: language - "Do you confirm you want to delete database '" + dbViewModel.DBName + "' ?" + - Environment.NewLine + - Environment.NewLine + - "WARNING: the database will be deleted permanently, " + - "with no chance to revert the operation.", - new[] { new DialogResponse(ResponseType.Yes, "DELETE", "Delete '" + dbViewModel.DBName + "'"), new DialogResponse(ResponseType.Cancel) }); - - this.windowManager.ShowDialog(secondConfirmDialog); - - if (secondConfirmDialog.FinalResponse == ResponseType.Yes) - { - if (this.dbsProvider.DeleteDB(dbViewModel.DBName)) - { - this.CloseDB(dbViewModel); - - this.RefreshDBsList(); - } - else - this.windowManager.ShowDialog( - new DialogViewModel( - "Database delete failed", // TODO: language - "Database '" + dbViewModel.DBName + "' couldn't be deleted because an error occurred." + - Environment.NewLine + - "Please try again.")); - } - } - } - - #endregion - - #region utilities - - private void MoveToOpened(DBViewModel dbViewModel) - { - this.NotOpenedDBs.Remove(dbViewModel); - var i = this.GetInsertIndex(dbViewModel, this.Items); - this.Items.Insert(i, dbViewModel); - } - - private void MoveToNotOpened(DBViewModel dbViewModel) - { - this.Items.Remove(dbViewModel); - var i = this.GetInsertIndex(dbViewModel, this.NotOpenedDBs); - this.NotOpenedDBs.Insert(i, dbViewModel); - } - - private int GetInsertIndex(DBViewModel dbvm, IList dbvmList) - { - if (dbvm == null) - throw new ArgumentNullException("dbvm cannot be null"); - - if (dbvmList == null) - throw new ArgumentNullException("dbvmList cannot be null"); - - if (dbvmList.Count == 0) - return 0; - - var names = dbvmList.Select(vm => vm.DBName).Concat(new[] { dbvm.DBName }); - var sortedNames = names.OrderBy(n => n); - return sortedNames.ToList().IndexOf(dbvm.DBName); - } - - #endregion - - #region message handlers - - public void Handle(RollbackAuthorizationRequestMessage rollbackAuthorizationRequest) - { - if (!this.Items.Select(dbvm => dbvm.DBName).Contains(rollbackAuthorizationRequest.DBName)) - rollbackAuthorizationRequest.ConfirmAuthorization(); - else - rollbackAuthorizationRequest.NegateAuthorization(); - } - - #endregion - - #endregion - - #region commands - - private RelayCommand createDBCommand; - public RelayCommand CreateDBCommand - { - get - { - if (this.createDBCommand == null) - this.createDBCommand = new RelayCommand( - () => this.CreateDB()); - - return this.createDBCommand; - } - } - - private RelayCommand openDBCommand; - public RelayCommand OpenDBCommand - { - get - { - if (this.openDBCommand == null) - this.openDBCommand = new RelayCommand( - p => this.OpenDB(p), - p => p != null); - - return this.openDBCommand; - } - } - - private RelayCommand closeDBCommand; - public RelayCommand CloseDBCommand - { - get - { - if (this.closeDBCommand == null) - this.closeDBCommand = new RelayCommand( - p => this.CloseDB(p), - p => p != null); - - return this.closeDBCommand; - } - } - - private RelayCommand deleteDBCommand; - public RelayCommand DeleteDBCommand - { - get - { - if (this.deleteDBCommand == null) - this.deleteDBCommand = new RelayCommand( - p => this.DeleteDB(p), - p => this.NotOpenedDBs.Contains(p)); - - return this.deleteDBCommand; - } - } - - private RelayCommand renameDBCommand; - public RelayCommand RenameDBCommand - { - get - { - if (this.renameDBCommand == null) - this.renameDBCommand = new RelayCommand( - p => this.RenameDB(p), - p => this.NotOpenedDBs.Contains(p)); - - return this.renameDBCommand; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/BillAddEditViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/BillAddEditViewModel.DesignTime.cs deleted file mode 100644 index 5b5c29d..0000000 --- a/BillsManager.ViewModels/DesignTime/BillAddEditViewModel.DesignTime.cs +++ /dev/null @@ -1,73 +0,0 @@ -using BillsManager.Models; -using Caliburn.Micro; -using System; -using System.Linq; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class BillAddEditViewModel - { - #region ctor - - public BillAddEditViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - public BillAddEditViewModel(Bill exposedBill) - { - if (Execute.InDesignMode) - { - this.ExposedBill = exposedBill; - } - } - - #endregion - - #region methods - - private void LoadDesignTimeData() - { - Supplier supp = new Supplier( - 0, - "Faber-Castell", - "Via Stromboli", - "14", - "Milano", - "20144", - "MI", - "Italia", - "faber-castell@faber-castell.it", - "http://www.faber-castell.it", - "02/43069601", - "02/26367774", - "sconti 10/06 - 24/09.", - "Barbara", - "Robecchi", - "347-7892234"); - - this.ExposedBill = new Bill( - 0, - supp.ID, - DateTime.Today.AddDays(-2), - DateTime.Today.AddDays(14), - DateTime.Today.AddDays(-8), - DateTime.Today, - 723.61, - 32, - 0, - null, - "call agent for reduction @additional comments to trigger validation rule"); - - this.AvailableSuppliers = new[] { supp }; - this.SelectedSupplier = this.AvailableSuppliers.FirstOrDefault(); - } - - #endregion - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/BillsViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/BillsViewModel.DesignTime.cs deleted file mode 100644 index 1bf0aec..0000000 --- a/BillsManager.ViewModels/DesignTime/BillsViewModel.DesignTime.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using BillsManager.Models; -using Caliburn.Micro; -using System.Linq; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class BillsViewModel - { - #region ctor - - public BillsViewModel() - { - if (Execute.InDesignMode) - this.LoadDesignTimeData(); - } - - #endregion - - #region methods - - private void LoadDesignTimeData() - { - Supplier supp = new Supplier( - 0, - "Faber-Castell", - "Via Stromboli", - "14", - "Milano", - "20144", - "MI", - "Italia", - "faber-castell@faber-castell.it", - "http://www.faber-castell.it", - "02/43069601", - "02/43069601", - "sconti 10/06 - 24/09.", - "Barbara", - "Robecchi", - "347-7892234"); - - Bill newBill = new Bill( - 0, - supp.ID, - DateTime.Today, - DateTime.Today.AddDays(14), - DateTime.Today.AddDays(-2), - DateTime.Today, - 723.61, - 0, - 21.3, - "X3V-KDM", - "call agent for reduction"); - - Bill newBill2 = new Bill( - 1, - supp.ID, - DateTime.Today.AddDays(-30), - DateTime.Today.AddDays(-20), - DateTime.Today.AddDays(-32), - null, - 54.06, - 0, - 0.5, - "DK23595", - "ask for catalog"); - - Bill newBill3 = new Bill( - 2, - supp.ID, - DateTime.Today, - DateTime.Today.AddDays(7), - DateTime.Today.AddDays(-3), - null, - 54.06, - 9, - 0, - "AZ381EY", - "call agent for reductions and new winter orders"); - - Bill newBill4 = new Bill( - 3, - supp.ID, - DateTime.Today.AddDays(-30), - DateTime.Today.AddDays(-1), - DateTime.Today.AddDays(-32), - null, - 54.06, - 15.7, - 0, - "DK23595", - "ask for catalog"); - - var bills = new List(); - - //bills.Add(new BillDetailsViewModel(newBill) /*{ SupplierName = "faewf" }*/); - //bills.Add(new BillDetailsViewModel(newBill2) /*{ SupplierName = "fawef" }*/); - //bills.Add(new BillDetailsViewModel(newBill3) /*{ SupplierName = "gres" }*/); - //bills.Add(new BillDetailsViewModel(newBill4) /*{ SupplierName = "erg" }*/); - - this.BillViewModels = new ObservableCollection(bills); - - this.SelectedBillViewModel = this.BillViewModels.FirstOrDefault(); - } - - #endregion - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/DBAddViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/DBAddViewModel.DesignTime.cs deleted file mode 100644 index e6ffb74..0000000 --- a/BillsManager.ViewModels/DesignTime/DBAddViewModel.DesignTime.cs +++ /dev/null @@ -1,31 +0,0 @@ -using BillsManager.Models; -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class DBAddEditViewModel - { - public DBAddEditViewModel() - { - if (Execute.InDesignMode) - { - this.takenDBNames = new[] - { - @"C:\Bills Manager\Databases\Spese.bmdb", /* C:\Bills Manager\Databases\ .bmdb */ - @"C:\Bills Manager\Databases\Acquisti.bmdb", - @"C:\Bills Manager\Databases\Casa montagna.bmdb", - @"C:\Bills Manager\Databases\Casa mare.bmdb" - }; - - this.LoadDesignTimeData(); - } - } - - private void LoadDesignTimeData() - { - this.NewDBName = "This is the new name!"; - } - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/DBViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/DBViewModel.DesignTime.cs deleted file mode 100644 index f5d195a..0000000 --- a/BillsManager.ViewModels/DesignTime/DBViewModel.DesignTime.cs +++ /dev/null @@ -1,190 +0,0 @@ -using BillsManager.Services.Data; -using Caliburn.Micro; -using System; -using System.Collections.Generic; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class DBViewModel - { - public DBViewModel() - { - if (Execute.InDesignMode) - { - this.dbConnector = new DesignTimeDBConnector(); - this.LoadDesignTimeData(); - } - } - - public DBViewModel(IDBConnector dbConnector) - { - if (Execute.InDesignMode) - { - this.dbConnector = dbConnector; - this.LoadDesignTimeData(); - } - } - - public void LoadDesignTimeData() - { - this.SuppliersViewModel = new SuppliersViewModel(); - this.BillsViewModel = new BillsViewModel(); - } - - private class DesignTimeDBConnector : IDBConnector - { - #region IDBConnector Members - - public bool Connect() - { - throw new NotImplementedException(); - } - - public bool Save() - { - throw new NotImplementedException(); - } - - public void Disconnect() - { - throw new NotImplementedException(); - } - - public string DBPath - { - get { return "Design time Path"; } - } - - public string DBName - { - get { return "Design time Name"; } - } - - #endregion - - #region IBillsProvider Members - - public uint GetLastBillID() - { - throw new NotImplementedException(); - } - - public IEnumerable GetAllBills() - { - throw new NotImplementedException(); - } - - public bool Add(Models.Bill bill) - { - throw new NotImplementedException(); - } - - public bool Edit(Models.Bill bill) - { - throw new NotImplementedException(); - } - - public bool Edit(IEnumerable bills) - { - throw new NotImplementedException(); - } - - public bool Delete(Models.Bill bill) - { - throw new NotImplementedException(); - } - - public bool Delete(IEnumerable bills) - { - throw new NotImplementedException(); - } - - #endregion - - #region ISuppliersProvider Members - - public uint GetLastSupplierID() - { - throw new NotImplementedException(); - } - - public IEnumerable GetAllSuppliers() - { - throw new NotImplementedException(); - } - - public bool Add(Models.Supplier supplier) - { - throw new NotImplementedException(); - } - - public bool Edit(Models.Supplier supplier) - { - throw new NotImplementedException(); - } - - public bool Edit(IEnumerable suppliers) - { - throw new NotImplementedException(); - } - - public bool Delete(Models.Supplier supplier) - { - throw new NotImplementedException(); - } - - public bool Delete(IEnumerable suppliers) - { - throw new NotImplementedException(); - } - - #endregion - - //#region IAgentsProvider Members - - //public uint GetLastAgentID() - //{ - // throw new NotImplementedException(); - //} - - //public IEnumerable GetAllAgents() - //{ - // throw new NotImplementedException(); - //} - - //public Models.Agent GetAgentByID(uint agentID) - //{ - // throw new NotImplementedException(); - //} - - //public bool Add(Models.Agent agent) - //{ - // throw new NotImplementedException(); - //} - - //public bool Edit(Models.Agent agent) - //{ - // throw new NotImplementedException(); - //} - - //public bool Edit(IEnumerable agents) - //{ - // throw new NotImplementedException(); - //} - - //public bool Delete(Models.Agent agent) - //{ - // throw new NotImplementedException(); - //} - - //public bool Delete(IEnumerable agents) - //{ - // throw new NotImplementedException(); - //} - - //#endregion - } - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/DBsViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/DBsViewModel.DesignTime.cs deleted file mode 100644 index 3057ae6..0000000 --- a/BillsManager.ViewModels/DesignTime/DBsViewModel.DesignTime.cs +++ /dev/null @@ -1,239 +0,0 @@ -#if DEBUG - -using BillsManager.Services.Providers; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public partial class DBsViewModel - { - public DBsViewModel() - { - if (Execute.InDesignMode) - { - this.dbsProvider = new DesignTimeXMLDBsProvider(); - this.dbViewModelFactory = (s) => new DBViewModel(new DesignTimeXMLDBConnector(s)); - this.LoadDesignTimeData(); - } - } - - private void LoadDesignTimeData() - { - this.RefreshDBsList(); - - var openedDB = this.NotOpenedDBs.FirstOrDefault(); - this.NotOpenedDBs.Remove(openedDB); - this.Items.Add(openedDB); - - this.ActiveItem = this.Items.FirstOrDefault(); - this.SelectedDB = this.NotOpenedDBs.FirstOrDefault(); - } - - private class DesignTimeXMLDBsProvider : IDBsProvider - { - #region IDBsProvider Members - - public string Location - { - get { return AppDomain.CurrentDomain.BaseDirectory + @"\Databases\"; } - } - - public IEnumerable GetAll() - { - return new[] - { - @"C:\Bills Manager\Databases\Spese.bmdb", /* C:\Bills Manager\Databases\ .bmdb */ - @"C:\Bills Manager\Databases\Acquisti.bmdb", - @"C:\Bills Manager\Databases\Casa montagna.bmdb", - @"C:\Bills Manager\Databases\Casa mare.bmdb" - }; - } - - public bool CreateDB(string name) - { - throw new NotImplementedException(); - } - - public bool DeleteDB(string name) - { - throw new NotImplementedException(); - } - - public bool RenameDB(string oldName, string newName) - { - throw new NotImplementedException(); - } - - #endregion - } - - private class DesignTimeXMLDBConnector : IDBConnector - { - #region ctor - - public DesignTimeXMLDBConnector(string path) - { - this.path = path; - } - - #endregion - - #region IDBConnector Members - - private readonly string path; - public string Path - { - get { return this.path; } - } - - public string DBName - { - get { return System.IO.Path.GetFileNameWithoutExtension(this.Path); } - } - - public bool Open() - { - return true; - } - - public bool Save() - { - return true; - } - - public void Close() - { - } - - #endregion - - #region IBillsProvider Members - - public uint GetLastBillID() - { - throw new NotImplementedException(); - } - - public IEnumerable GetAllBills() - { - return null; - } - - public bool Add(Models.Bill bill) - { - throw new NotImplementedException(); - } - - public bool Edit(Models.Bill bill) - { - throw new NotImplementedException(); - } - - public bool Edit(IEnumerable bills) - { - throw new NotImplementedException(); - } - - public bool Delete(Models.Bill bill) - { - throw new NotImplementedException(); - } - - public bool Delete(IEnumerable bills) - { - throw new NotImplementedException(); - } - - #endregion - - #region ISuppliersProvider Members - - public uint GetLastSupplierID() - { - throw new NotImplementedException(); - } - - public IEnumerable GetAllSuppliers() - { - return null; - } - - public bool Add(Models.Supplier supplier) - { - throw new NotImplementedException(); - } - - public bool Edit(Models.Supplier supplier) - { - throw new NotImplementedException(); - } - - public bool Edit(IEnumerable suppliers) - { - throw new NotImplementedException(); - } - - public bool Delete(Models.Supplier supplier) - { - throw new NotImplementedException(); - } - - public bool Delete(IEnumerable suppliers) - { - throw new NotImplementedException(); - } - - #endregion - - #region IAgentsProvider Members - - public uint GetLastAgentID() - { - throw new NotImplementedException(); - } - - public IEnumerable GetAllAgents() - { - throw new NotImplementedException(); - } - - public Models.Agent GetAgentByID(uint agentID) - { - throw new NotImplementedException(); - } - - public bool Add(Models.Agent agent) - { - throw new NotImplementedException(); - } - - public bool Edit(Models.Agent agent) - { - throw new NotImplementedException(); - } - - public bool Edit(IEnumerable agents) - { - throw new NotImplementedException(); - } - - public bool Delete(Models.Agent agent) - { - throw new NotImplementedException(); - } - - public bool Delete(IEnumerable agents) - { - throw new NotImplementedException(); - } - - #endregion - } - - } -} - -#endif \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/DialogViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/DialogViewModel.DesignTime.cs deleted file mode 100644 index 0e6d5ca..0000000 --- a/BillsManager.ViewModels/DesignTime/DialogViewModel.DesignTime.cs +++ /dev/null @@ -1,42 +0,0 @@ -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class DialogViewModel - { - #region ctor - - public DialogViewModel() - { - if (Execute.InDesignMode) - { - //this.caption = "Test"; - this.message = "This is a test"; - this.DisplayName = "Test"; - - // TODO: move to a designdata project - this.responses = new[] - { - new DialogResponse(ResponseType.Yes, "go on", "Confirm"), - new DialogResponse(ResponseType.No, "Nein", "I say") {IsEnabled = true}, - new DialogResponse(ResponseType.Retry), - new DialogResponse(ResponseType.Cancel), - }; - - this.LoadDesignTimeData(); - } - } - - #endregion - - #region methods - - void LoadDesignTimeData() - { - } - - #endregion - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/ProgressViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/ProgressViewModel.DesignTime.cs deleted file mode 100644 index d3d6217..0000000 --- a/BillsManager.ViewModels/DesignTime/ProgressViewModel.DesignTime.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ - public partial class ProgressViewModel - { - public ProgressViewModel() - { - if (Execute.InDesignMode) - { - this.message = "Loading ..."; - this.LoadDesignTimeData(); - } - } - - private void LoadDesignTimeData() - { - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/SearchBillsViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/SearchBillsViewModel.DesignTime.cs deleted file mode 100644 index 4c8bc78..0000000 --- a/BillsManager.ViewModels/DesignTime/SearchBillsViewModel.DesignTime.cs +++ /dev/null @@ -1,64 +0,0 @@ -using BillsManager.Models; -using Caliburn.Micro; -using System; -using System.Linq; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class SearchBillsViewModel : Screen - { - #region ctor - - public SearchBillsViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - #endregion - - #region methods - - void LoadDesignTimeData() - { - var supps = new[] - { - new Supplier( - 538, - "Faber-Castell", - "Via Stromboli", - "14", - "Milano", - "20144", - "MI", - "Italia", - "faber-castell@faber-castell.it", - "http://www.faber-castell.it", - "02/43069601", - "02/43069601", - "sconti 10/06 - 24/09.", - "Barbara", - "Robecchi", - "347-7892234") - }; - - this.AvailableSuppliers = supps; - this.SelectedSupplier = this.AvailableSuppliers.FirstOrDefault(); - - this.UseDueDateFilter = true; - this.UseReleaseDateFilter = true; - this.UseSupplierFilter = true; - - this.DueDateFilterValue = DateTime.Today.AddDays(15); - this.ReleaseDateFilterValue = DateTime.Today.AddDays(-22); - - this.IsPaidFilterValue = null; - } - - #endregion - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/SearchSuppliersViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/SearchSuppliersViewModel.DesignTime.cs deleted file mode 100644 index 85b1e6c..0000000 --- a/BillsManager.ViewModels/DesignTime/SearchSuppliersViewModel.DesignTime.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Caliburn.Micro; -using System.Linq; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class SearchSuppliersViewModel - { - #region ctor - - public SearchSuppliersViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - #endregion - - #region methods - - void LoadDesignTimeData() - { - this.UseObligationStateFilter = true; - this.ObligationStateFilterValue = this.ObligationStates.FirstOrDefault(); - } - - #endregion - } -#endif -} diff --git a/BillsManager.ViewModels/DesignTime/SearchViewModelGeneric.DesignTime.cs b/BillsManager.ViewModels/DesignTime/SearchViewModelGeneric.DesignTime.cs deleted file mode 100644 index 51b242c..0000000 --- a/BillsManager.ViewModels/DesignTime/SearchViewModelGeneric.DesignTime.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace BillsManager.ViewModels.DesignTime -{ -#if DEBUG - public partial class SearchViewModel : Screen - where T : class - { - public SearchViewModel() - { - } - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/SettingsViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/SettingsViewModel.DesignTime.cs deleted file mode 100644 index 9baadd4..0000000 --- a/BillsManager.ViewModels/DesignTime/SettingsViewModel.DesignTime.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ - public partial class SettingsViewModel - { - public SettingsViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - private void LoadDesignTimeData() - { - - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/ShellViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/ShellViewModel.DesignTime.cs deleted file mode 100644 index 20318fc..0000000 --- a/BillsManager.ViewModels/DesignTime/ShellViewModel.DesignTime.cs +++ /dev/null @@ -1,19 +0,0 @@ -#if DEBUG - -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ - public partial class ShellViewModel - { - #region ctor - - public ShellViewModel() - { - } - - #endregion - } -} - -#endif \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/StatusBarViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/StatusBarViewModel.DesignTime.cs deleted file mode 100644 index bcb91b8..0000000 --- a/BillsManager.ViewModels/DesignTime/StatusBarViewModel.DesignTime.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class StatusBarViewModel - { - public StatusBarViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - private void LoadDesignTimeData() - { - } - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/SupplierAddEditViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/SupplierAddEditViewModel.DesignTime.cs deleted file mode 100644 index c1bde8f..0000000 --- a/BillsManager.ViewModels/DesignTime/SupplierAddEditViewModel.DesignTime.cs +++ /dev/null @@ -1,66 +0,0 @@ -using BillsManager.Models; -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class SupplierAddEditViewModel - { - #region ctor - - public SupplierAddEditViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - public SupplierAddEditViewModel(Supplier supplier) - { - if (Execute.InDesignMode) - { - this.ExposedSupplier = supplier; - } - } - - #endregion - - #region methods - - private void LoadDesignTimeData() - { - this.ExposedSupplier = new Supplier( - 0, - "Faber-Castell", - "Via Stromboli", - "14", - "Milano", - "20144", - "MI", - "Italia", - "faber-castell@faber-castell.it", - "http://www.faber-castell.it", - "02/43069601", - "02/26367774", - "sconti 10/06 - 24/09.", - "Barbara", - "Robecchi", - "347-7892234"); - - //this.ExposedSupplier.Bills.Add(new Bill( - // 0, - // DateTime.Today.AddDays(-2), - // DateTime.Today.AddDays(14), - // DateTime.Today, - // DateTime.Today.AddDays(-8), - // 723.61, - // this.ExposedSupplier.Name, - // "call agent for reduction", - // "X3V-KDM")); - } - - #endregion - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/DesignTime/SuppliersViewModel.DesignTime.cs b/BillsManager.ViewModels/DesignTime/SuppliersViewModel.DesignTime.cs deleted file mode 100644 index 0c7d455..0000000 --- a/BillsManager.ViewModels/DesignTime/SuppliersViewModel.DesignTime.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System.Collections.ObjectModel; -using System.Linq; -using BillsManager.Models; -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ -#if DEBUG - public partial class SuppliersViewModel : Screen - { - #region ctor - - public SuppliersViewModel() - { - if (Execute.InDesignMode) - { - this.LoadDesignTimeData(); - } - } - - #endregion - - #region methods - - private void LoadDesignTimeData() - { - //var svm1 = new SupplierDetailsViewModel(new Supplier( - // 0, - // "Faber-Castell", - // "Via Stromboli", - // "14", - // "Milano", - // "20144", - // "MI", - // "Italia", - // "faber-castell@faber-castell.it", - // "http://www.faber-castell.it", - // "02/43069601", - // "02/43069601", - // "sconti 10/06 - 24/09.", - // "Barbara", - //"Robecchi", - //"347-7892234")) { ObligationAmount = -1 }; - - //svm1.ExposedSupplier.Bills.Add(new Bill( - // DateTime.Today.AddDays(-2), - // DateTime.Today.AddDays(14), - // DateTime.Today, - // DateTime.Today.AddDays(-8), - // 723.61, - // svm1.ExposedSupplier, - // "call agent for reduction", - // "X3V-KDM")); - - //var svm2 = new SupplierDetailsViewModel(new Supplier( - // 1, - // "Faber-Castell", - // "Via Stromboli", - // "14", - // "Milano", - // "20144", - // "MI", - // "Italia", - // "faber-castell@faber-castell.it", - // "http://www.faber-castell.it", - // "02/43069601", - // "02/26367774", - // "sconti 10/06 - 24/09.", - // "Barbara", - // "Robecchi", - // "347-7892234")); - - //var svm3 = new SupplierDetailsViewModel(new Supplier( - // 2, - // "Faber-Castell", - // "Via Stromboli", - // "14", - // "Milano", - // "20144", - // "MI", - // "Italia", - // "faber-castell@faber-castell.it", - // "http://www.faber-castell.it", - // "02/43069601", - // "02/26367774", - // "sconti 10/06 - 24/09.", - // "Barbara", - // "Robecchi", - // "347-7892234")) { ObligationAmount = 1 }; // TODO: change obligation set way, add bills instead - - //svm3.ExposedSupplier.Bills.Add(new Bill( - // DateTime.Today.AddDays(-2), - // DateTime.Today.AddDays(14), - // DateTime.Today, - // DateTime.Today.AddDays(-8), - // -48.35, - // svm1.ExposedSupplier, - // "for changed order", - // "AB 325 MY")); - - this.SupplierViewModels = new ObservableCollection(); - //this.SupplierViewModels.Add(svm1); - //this.SupplierViewModels.Add(svm2); - //this.SupplierViewModels.Add(svm3); - - this.SelectedSupplierViewModel = this.SupplierViewModels.FirstOrDefault(); - } - - #endregion - } -#endif -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Dialog/DialogResponse.cs b/BillsManager.ViewModels/Dialog/DialogResponse.cs deleted file mode 100644 index 01927e5..0000000 --- a/BillsManager.ViewModels/Dialog/DialogResponse.cs +++ /dev/null @@ -1,86 +0,0 @@ -using BillsManager.Localization.Attributes; -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ - public class DialogResponse : PropertyChangedBase - { - #region ctor - - public DialogResponse(ResponseType response, string text, string confirmCheckText) - { - this.response = response; - this.text = text; - this.confirmCheckText = confirmCheckText; - } - - public DialogResponse(ResponseType response, string text) - : this(response, text, null) - { - } - - public DialogResponse(ResponseType response) - : this(ResponseType.Ok, null, null) - { - } - - #endregion - - #region properties - - private readonly ResponseType response; - public ResponseType Response - { - get { return response; } - } - - private readonly string text; - public string Text - { - get - { - if (!string.IsNullOrEmpty(this.text)) - { - return this.text; - } - else - { - var rtInfo = typeof(ResponseType).GetMember(response.ToString()); - var attributes = rtInfo[0].GetCustomAttributes(typeof(LocalizedDisplayNameAttribute), true); - return (attributes[0] as LocalizedDisplayNameAttribute).DisplayName; - } - } - } - - private readonly string confirmCheckText; - public string ConfirmCheckText - { - get { return this.confirmCheckText; } - } - - public bool UseConfirmCheck - { - get { return !string.IsNullOrEmpty(this.ConfirmCheckText); } - } - - public bool IsDefault { get; set; } - - public bool IsCancel { get; set; } - - private bool isEnabled = true; - public bool IsEnabled - { - get { return this.isEnabled; } - set - { - if (this.IsEnabled != value) - { - this.isEnabled = value; - this.NotifyOfPropertyChange(() => this.IsEnabled); - } - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Dialog/DialogType.cs b/BillsManager.ViewModels/Dialog/DialogType.cs deleted file mode 100644 index 7d54de0..0000000 --- a/BillsManager.ViewModels/Dialog/DialogType.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace BillsManager.ViewModels -{ - public enum DialogType - { - None, - Question, - Information, - Error, - Warning - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Dialog/DialogViewModel.cs b/BillsManager.ViewModels/Dialog/DialogViewModel.cs deleted file mode 100644 index 0cbbf44..0000000 --- a/BillsManager.ViewModels/Dialog/DialogViewModel.cs +++ /dev/null @@ -1,170 +0,0 @@ -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public partial class DialogViewModel : Screen, IDialogViewModelFactory - { - #region ctor - - private DialogViewModel( - DialogType dialogType, - string title, - string message) - { - this.responses = new[] { new DialogResponse(ResponseType.Ok) }; - - this.dialogType = dialogType; - this.DisplayName = title; - this.message = message; - } - - #endregion - - #region properties - - private readonly DialogType dialogType; - public DialogType DialogType - { - get { return this.dialogType; } - } - - //private readonly string caption; - //public string Caption - //{ - // get { return this.caption; } - //} - - private readonly string message; - public string Message - { - get { return this.message; } - } - - private IEnumerable responses; - public IEnumerable Responses - { - get { return this.responses; } - private set - { - if ((value != null & value.Count() > 0) & - (this.responses != value)) - { - this.responses = value; - - foreach (var resp in this.responses) - { - resp.IsDefault = false; - resp.IsCancel = false; - } - this.Responses.First().IsDefault = true; - this.Responses.Last().IsCancel = true; - } - } - } - - private ResponseType finalResponse = ResponseType.Unset; - public ResponseType FinalResponse - { - get { return this.finalResponse; } - protected set - { - this.finalResponse = value; - } - } - - #endregion - - #region methods - - #region creation - - public static IDialogViewModelFactory Show(DialogType dialogType, string title, string text) - { - return new DialogViewModel(dialogType, title, text); - } - - #region IDialogViewModelFactory Members - - DialogViewModel IDialogViewModelFactory.Ok(string okText) - { - this.Responses = new DialogResponse[] - { - new DialogResponse(ResponseType.Ok, okText) - }; - - return this; - } - - DialogViewModel IDialogViewModelFactory.OkCancel(string okText, string cancelText) - { - this.Responses = new DialogResponse[] - { - new DialogResponse(ResponseType.Ok, okText), - new DialogResponse(ResponseType.Cancel, cancelText) - }; - - return this; - } - - DialogViewModel IDialogViewModelFactory.YesNo(string yesText, string noText) - { - this.Responses = new DialogResponse[] - { - new DialogResponse(ResponseType.Yes, yesText), - new DialogResponse(ResponseType.No, noText) - }; - - return this; - } - - DialogViewModel IDialogViewModelFactory.YesNoCancel(string yesText, string noText, string cancelText) - { - this.Responses = new DialogResponse[] - { - new DialogResponse(ResponseType.Yes, yesText), - new DialogResponse(ResponseType.No, noText), - new DialogResponse(ResponseType.Cancel, cancelText) - }; - - return this; - } - - DialogViewModel IDialogViewModelFactory.RetryCancel(string retryText, string cancelText) - { - this.Responses = new DialogResponse[] - { - new DialogResponse(ResponseType.Retry, retryText), - new DialogResponse(ResponseType.Cancel, cancelText) - }; - - return this; - } - - #endregion - - #endregion - - public void Respond(DialogResponse dialogResponse) - { - this.FinalResponse = dialogResponse.Response; - - bool? result = null; - if (dialogResponse.IsDefault) - result = true; - if (dialogResponse.IsCancel) - result = false; - - this.TryClose(result); - } - - public override void CanClose(Action callback) - { - callback(this.FinalResponse != ResponseType.Unset); - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Dialog/IDialogViewModelFactory.cs b/BillsManager.ViewModels/Dialog/IDialogViewModelFactory.cs deleted file mode 100644 index 9677681..0000000 --- a/BillsManager.ViewModels/Dialog/IDialogViewModelFactory.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace BillsManager.ViewModels -{ - public interface IDialogViewModelFactory - { - DialogViewModel Ok(string okText = null); - DialogViewModel OkCancel(string okText = null, string cancelText = null); - DialogViewModel YesNo(string yesText = null, string noText = null); - DialogViewModel YesNoCancel(string yesText = null, string noText = null, string cancelText = null); - DialogViewModel RetryCancel(string retryText = null, string cancelText = null); - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Dialog/ProgressViewModel.cs b/BillsManager.ViewModels/Dialog/ProgressViewModel.cs deleted file mode 100644 index e69708d..0000000 --- a/BillsManager.ViewModels/Dialog/ProgressViewModel.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ - public partial class ProgressViewModel : Screen - { - #region ctor - - public ProgressViewModel(string message) - { - this.message = message; - - this.DisplayName = message; - } - - #endregion - - #region properties - - private readonly string message; - public string Message - { - get { return this.message; } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Dialog/ResponseType.cs b/BillsManager.ViewModels/Dialog/ResponseType.cs deleted file mode 100644 index b1075d8..0000000 --- a/BillsManager.ViewModels/Dialog/ResponseType.cs +++ /dev/null @@ -1,29 +0,0 @@ -using BillsManager.Localization.Attributes; - -namespace BillsManager.ViewModels -{ - public enum ResponseType - { - [LocalizedDisplayName("Unset")] - Unset - - , - [LocalizedDisplayName("Yes")] - Yes - , - [LocalizedDisplayName("No")] - No - , - [LocalizedDisplayName("Ok")] - Ok - , - [LocalizedDisplayName("Cancel")] - Cancel - , - [LocalizedDisplayName("Retry")] - Retry - //, - //[LocalizedDisplayName("Abort")] - //Abort - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/ExtensionMethods/ExtendedObservableCollectionGeneric.cs b/BillsManager.ViewModels/ExtensionMethods/ExtendedObservableCollectionGeneric.cs deleted file mode 100644 index 0ca0d30..0000000 --- a/BillsManager.ViewModels/ExtensionMethods/ExtendedObservableCollectionGeneric.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; - -namespace BillsManager.ViewModel -{ - public class ExtendedObservableCollection : ObservableCollection - { - #region ctor - - public ExtendedObservableCollection() - : base() - { - } - - public ExtendedObservableCollection(IEnumerable collection) - : base(collection) - { - } - - public ExtendedObservableCollection(List list) - : base(list) - { - } - - #endregion - - #region ranged - - public void AddRange(IEnumerable newItems) - { - this.CheckReentrancy(); - - foreach (T item in newItems) - { - this.Items.Add(item); - } - - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems)); - this.OnPropertyChanged(new PropertyChangedEventArgs("Count")); - } - - public void RemoveRange(IEnumerable deleteItems) - { - this.CheckReentrancy(); - - var deleted = new List(deleteItems); - - foreach (T item in deleteItems) - { - this.Items.Remove(item); - } - - this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, deleted)); - this.OnPropertyChanged(new PropertyChangedEventArgs("Count")); - } - - #endregion - - //#region auto sorting - - //private bool autoSort; - //public bool AutoSort - //{ - // get { return this.autoSort; } - // set - // { - // if (this.autoSort != value) - // { - // this.autoSort = value; - // } - - // if (this.AutoSort) - // this.Sort(); - // } - //} - - //protected Comparer sorter; - //public Comparer Sorter - //{ - // get { return this.sorter; } - // set - // { - // if (this.sorter != value) - // { - // this.sorter = value; - // this.OnPropertyChanged(new PropertyChangedEventArgs("Sorter")); - - // if (this.AutoSort) - // this.Sort(); - // } - // } - //} - - //public void Sort() - //{ - // this.CheckReentrancy(); - - // this.Items.OrderBy(item => item, this.Sorter); - - // this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move)); - //} - - //#endregion - } -} diff --git a/BillsManager.ViewModels/ExtensionMethods/ExtensionMethods.cs b/BillsManager.ViewModels/ExtensionMethods/ExtensionMethods.cs deleted file mode 100644 index 64f7563..0000000 --- a/BillsManager.ViewModels/ExtensionMethods/ExtensionMethods.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public static class ExtensionMethods - { - public static IEnumerable Where(this IEnumerable data, IEnumerable> predicates) - { - return data.Where(i => predicates.All(p => p(i))); - - //if (predicates == null) - //{ - // foreach (T item in data) - // yield return item; - //} - //else - //{ - // bool respects; - - // foreach (T item in data) - // { - // respects = true; - - // foreach (Predicate pred in predicates) - // { - // if (!pred.Invoke(item)) - // { - // respects = false; - // break; - // } - // } - - // if (respects) - // yield return item; - // } - //} - } - - [Obsolete] - public static void AddSorted(this IList list, T item, IComparer comparer = null) - { - if (comparer == null) - comparer = Comparer.Default; - - int i = 0; - while (i < list.Count && comparer.Compare(list[i], item) < 0) - i++; - - list.Insert(i, item); - } - - [Obsolete] - public static void SortEdited(this IList list, T item, IComparer comparer = null) - { - if (comparer == null) - comparer = Comparer.Default; - - list.Remove(item); - - int i = 0; - while (i < list.Count && comparer.Compare(list[i], item) < 0) - i++; - - var obs = list as ObservableCollection; - if (obs != null) - obs.Move(obs.IndexOf(item), i); - else - list.Insert(i, item); - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Helpers/IExecuteWithObject.cs b/BillsManager.ViewModels/Helpers/IExecuteWithObject.cs deleted file mode 100644 index 4208c85..0000000 --- a/BillsManager.ViewModels/Helpers/IExecuteWithObject.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace BillsManager.ViewModels.Helpers -{ - - /// - /// This interface is meant for the class and can be - /// useful if you store multiple WeakAction{T} instances but don't know in advance - /// what type T represents. - /// - ////[ClassInfo(typeof(WeakAction))] - public interface IExecuteWithObject - { - - /// - /// The target of the WeakAction. - /// - object Target - { - get; - } - - /// - /// Executes an action. - /// - /// A parameter passed as an object, - /// to be casted to the appropriate type. - void ExecuteWithObject(object parameter); - - /// - /// Deletes all references, which notifies the cleanup method - /// that this entry must be deleted. - /// - void MarkForDeletion(); - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Helpers/IExecuteWithObjectAndResult.cs b/BillsManager.ViewModels/Helpers/IExecuteWithObjectAndResult.cs deleted file mode 100644 index d6b45fa..0000000 --- a/BillsManager.ViewModels/Helpers/IExecuteWithObjectAndResult.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace BillsManager.ViewModels.Helpers -{ - - /// - /// This interface is meant for the class and can be - /// useful if you store multiple WeakFunc{T} instances but don't know in advance - /// what type T represents. - /// - ////[ClassInfo(typeof(WeakAction))] - public interface IExecuteWithObjectAndResult - { - - /// - /// Executes a func and returns the result. - /// - /// A parameter passed as an object, - /// to be casted to the appropriate type. - object ExecuteWithObject(object parameter); - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Helpers/WeakAction.cs b/BillsManager.ViewModels/Helpers/WeakAction.cs deleted file mode 100644 index 9151784..0000000 --- a/BillsManager.ViewModels/Helpers/WeakAction.cs +++ /dev/null @@ -1,223 +0,0 @@ -using System; -using System.Reflection; - -namespace BillsManager.ViewModels.Helpers -{ - - /// - /// Stores an without causing a hard reference - /// to be created to the Action's owner. The owner can be garbage collected at any time. - /// - ////[ClassInfo(typeof(WeakAction), - //// VersionString = "4.0.15", - //// DateString = "201206191330", - //// Description = "A class allowing to store and invoke actions without keeping a hard reference to the action's target.", - //// UrlContacts = "http://www.galasoft.ch/contact_en.html", - //// Email = "laurent@galasoft.ch")] - public class WeakAction - { - - private Action _staticAction; - - /// - /// Gets or sets the corresponding to this WeakAction's - /// method passed in the constructor. - /// - protected MethodInfo Method - { - get; - set; - } - - /// - /// Gets the name of the method that this WeakAction represents. - /// - public virtual string MethodName - { - get - { - if (_staticAction != null) - { - return _staticAction.Method.Name; - } - return Method.Name; - } - } - - /// - /// Gets or sets a WeakReference to this WeakAction's action's target. - /// This is not necessarily the same as - /// , for example if the - /// method is anonymous. - /// - protected WeakReference ActionReference - { - get; - set; - } - - /// - /// Gets or sets a WeakReference to the target passed when constructing - /// the WeakAction. This is not necessarily the same as - /// , for example if the - /// method is anonymous. - /// - protected WeakReference Reference - { - get; - set; - } - - /// - /// Gets a value indicating whether the WeakAction is static or not. - /// - public bool IsStatic - { - get - { - return _staticAction != null; - } - } - - /// - /// Initializes an empty instance of the class. - /// - protected WeakAction() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The action that will be associated to this instance. - public WeakAction(Action action) - : this(action.Target, action) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The action's owner. - /// The action that will be associated to this instance. - public WeakAction(object target, Action action) - { - if (action.Method.IsStatic) - { - _staticAction = action; - - if (target != null) - { - // Keep a reference to the target to control the - // WeakAction's lifetime. - Reference = new WeakReference(target); - } - - return; - } - - Method = action.Method; - ActionReference = new WeakReference(action.Target); - - Reference = new WeakReference(target); - } - - /// - /// Gets a value indicating whether the Action's owner is still alive, or if it was collected - /// by the Garbage Collector already. - /// - public virtual bool IsAlive - { - get - { - if (_staticAction == null - && Reference == null) - { - return false; - } - - if (_staticAction != null) - { - if (Reference != null) - { - return Reference.IsAlive; - } - - return true; - } - - return Reference.IsAlive; - } - } - - /// - /// Gets the Action's owner. This object is stored as a - /// . - /// - public object Target - { - get - { - if (Reference == null) - { - return null; - } - - return Reference.Target; - } - } - - /// - /// - /// - protected object ActionTarget - { - get - { - if (ActionReference == null) - { - return null; - } - - return ActionReference.Target; - } - } - - /// - /// Executes the action. This only happens if the action's owner - /// is still alive. - /// - public void Execute() - { - if (_staticAction != null) - { - _staticAction(); - return; - } - - var actionTarget = ActionTarget; - - if (IsAlive) - { - if (Method != null - && ActionReference != null - && actionTarget != null) - { - Method.Invoke(ActionTarget, null); - return; - } - } - } - - /// - /// Sets the reference that this instance stores to null. - /// - public void MarkForDeletion() - { - Reference = null; - ActionReference = null; - Method = null; - _staticAction = null; - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Helpers/WeakActionGeneric.cs b/BillsManager.ViewModels/Helpers/WeakActionGeneric.cs deleted file mode 100644 index c128fa6..0000000 --- a/BillsManager.ViewModels/Helpers/WeakActionGeneric.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; - -namespace BillsManager.ViewModels.Helpers -{ - - /// - /// Stores an Action without causing a hard reference - /// to be created to the Action's owner. The owner can be garbage collected at any time. - /// - /// The type of the Action's parameter. - ////[ClassInfo(typeof(WeakAction))] - public class WeakAction : WeakAction, IExecuteWithObject - { - - private Action _staticAction; - - /// - /// Gets the name of the method that this WeakAction represents. - /// - public override string MethodName - { - get - { - if (_staticAction != null) - { - return _staticAction.Method.Name; - } - return Method.Name; - } - } - - /// - /// Gets a value indicating whether the Action's owner is still alive, or if it was collected - /// by the Garbage Collector already. - /// - public override bool IsAlive - { - get - { - if (_staticAction == null - && Reference == null) - { - return false; - } - - if (_staticAction != null) - { - if (Reference != null) - { - return Reference.IsAlive; - } - - return true; - } - - return Reference.IsAlive; - } - } - - /// - /// Initializes a new instance of the WeakAction class. - /// - /// The action that will be associated to this instance. - public WeakAction(Action action) - : this(action.Target, action) - { - } - - /// - /// Initializes a new instance of the WeakAction class. - /// - /// The action's owner. - /// The action that will be associated to this instance. - public WeakAction(object target, Action action) - { - if (action.Method.IsStatic) - { - _staticAction = action; - - if (target != null) - { - // Keep a reference to the target to control the - // WeakAction's lifetime. - Reference = new WeakReference(target); - } - - return; - } - - Method = action.Method; - ActionReference = new WeakReference(action.Target); - - Reference = new WeakReference(target); - } - - /// - /// Executes the action. This only happens if the action's owner - /// is still alive. The action's parameter is set to default(T). - /// - public new void Execute() - { - Execute(default(T)); - } - - /// - /// Executes the action. This only happens if the action's owner - /// is still alive. - /// - /// A parameter to be passed to the action. - public void Execute(T parameter) - { - if (_staticAction != null) - { - _staticAction(parameter); - return; - } - - if (IsAlive) - { - if (Method != null - && ActionReference != null) - { - Method.Invoke( - ActionTarget, - new object[] - { - parameter - }); - } - } - } - - /// - /// Executes the action with a parameter of type object. This parameter - /// will be casted to T. This method implements - /// and can be useful if you store multiple WeakAction{T} instances but don't know in advance - /// what type T represents. - /// - /// The parameter that will be passed to the action after - /// being casted to T. - public void ExecuteWithObject(object parameter) - { - var parameterCasted = (T)parameter; - Execute(parameterCasted); - } - - /// - /// Sets all the actions that this WeakAction contains to null, - /// which is a signal for containing objects that this WeakAction - /// should be deleted. - /// - public new void MarkForDeletion() - { - _staticAction = null; - base.MarkForDeletion(); - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Helpers/WeakFunc.cs b/BillsManager.ViewModels/Helpers/WeakFunc.cs deleted file mode 100644 index f2b7d32..0000000 --- a/BillsManager.ViewModels/Helpers/WeakFunc.cs +++ /dev/null @@ -1,219 +0,0 @@ -using System; -using System.Reflection; - -namespace BillsManager.ViewModels.Helpers -{ - - /// - /// Stores a Func<T> without causing a hard reference - /// to be created to the Func's owner. The owner can be garbage collected at any time. - /// - ////[ClassInfo(typeof(WeakAction)] - public class WeakFunc - { - - private Func _staticFunc; - - /// - /// Gets or sets the corresponding to this WeakFunc's - /// method passed in the constructor. - /// - protected MethodInfo Method - { - get; - set; - } - - /// - /// Get a value indicating whether the WeakFunc is static or not. - /// - public bool IsStatic - { - get - { - return _staticFunc != null; - } - } - - /// - /// Gets the name of the method that this WeakFunc represents. - /// - public virtual string MethodName - { - get - { - if (_staticFunc != null) - { - return _staticFunc.Method.Name; - } - - return Method.Name; - } - } - - /// - /// Gets or sets a WeakReference to this WeakFunc's action's target. - /// This is not necessarily the same as - /// , for example if the - /// method is anonymous. - /// - protected WeakReference FuncReference - { - get; - set; - } - - /// - /// Gets or sets a WeakReference to the target passed when constructing - /// the WeakFunc. This is not necessarily the same as - /// , for example if the - /// method is anonymous. - /// - protected WeakReference Reference - { - get; - set; - } - - /// - /// Initializes an empty instance of the WeakFunc class. - /// - protected WeakFunc() - { - } - - /// - /// Initializes a new instance of the WeakFunc class. - /// - /// The func that will be associated to this instance. - public WeakFunc(Func func) - : this(func.Target, func) - { - } - - /// - /// Initializes a new instance of the WeakFunc class. - /// - /// The func's owner. - /// The func that will be associated to this instance. - public WeakFunc(object target, Func func) - { - if (func.Method.IsStatic) - { - _staticFunc = func; - - if (target != null) - { - // Keep a reference to the target to control the - // WeakAction's lifetime. - Reference = new WeakReference(target); - } - - return; - } - - Method = func.Method; - FuncReference = new WeakReference(func.Target); - - Reference = new WeakReference(target); - } - - /// - /// Gets a value indicating whether the Func's owner is still alive, or if it was collected - /// by the Garbage Collector already. - /// - public virtual bool IsAlive - { - get - { - if (_staticFunc == null - && Reference == null) - { - return false; - } - - if (_staticFunc != null) - { - if (Reference != null) - { - return Reference.IsAlive; - } - - return true; - } - - return Reference.IsAlive; - } - } - - /// - /// Gets the Func's owner. This object is stored as a - /// . - /// - public object Target - { - get - { - if (Reference == null) - { - return null; - } - - return Reference.Target; - } - } - - /// - /// Gets the owner of the Func that was passed as parameter. - /// This is not necessarily the same as - /// , for example if the - /// method is anonymous. - /// - protected object FuncTarget - { - get - { - if (FuncReference == null) - { - return null; - } - - return FuncReference.Target; - } - } - - /// - /// Executes the action. This only happens if the func's owner - /// is still alive. - /// - public TResult Execute() - { - if (_staticFunc != null) - { - return _staticFunc(); - } - - if (IsAlive) - { - if (Method != null - && FuncReference != null) - { - return (TResult)Method.Invoke(FuncTarget, null); - } - } - - return default(TResult); - } - - /// - /// Sets the reference that this instance stores to null. - /// - public void MarkForDeletion() - { - Reference = null; - FuncReference = null; - Method = null; - _staticFunc = null; - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Helpers/WeakFuncGeneric.cs b/BillsManager.ViewModels/Helpers/WeakFuncGeneric.cs deleted file mode 100644 index 19c1c0a..0000000 --- a/BillsManager.ViewModels/Helpers/WeakFuncGeneric.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System; - -namespace BillsManager.ViewModels.Helpers -{ - - /// - /// Stores an Func without causing a hard reference - /// to be created to the Func's owner. The owner can be garbage collected at any time. - /// - /// The type of the Func's parameter. - /// The type of the Func's return value. - ////[ClassInfo(typeof(WeakAction))] - public class WeakFunc : WeakFunc, IExecuteWithObjectAndResult - { - - private Func _staticFunc; - - /// - /// Gets or sets the name of the method that this WeakFunc represents. - /// - public override string MethodName - { - get - { - if (_staticFunc != null) - { - return _staticFunc.Method.Name; - } - - return Method.Name; - } - } - - /// - /// Gets a value indicating whether the Func's owner is still alive, or if it was collected - /// by the Garbage Collector already. - /// - public override bool IsAlive - { - get - { - if (_staticFunc == null - && Reference == null) - { - return false; - } - - if (_staticFunc != null) - { - if (Reference != null) - { - return Reference.IsAlive; - } - - return true; - } - - return Reference.IsAlive; - } - } - - /// - /// Initializes a new instance of the WeakFunc class. - /// - /// The func that will be associated to this instance. - public WeakFunc(Func func) - : this(func.Target, func) - { - } - - /// - /// Initializes a new instance of the WeakFunc class. - /// - /// The func's owner. - /// The func that will be associated to this instance. - public WeakFunc(object target, Func func) - { - if (func.Method.IsStatic) - { - _staticFunc = func; - - if (target != null) - { - // Keep a reference to the target to control the - // WeakAction's lifetime. - Reference = new WeakReference(target); - } - - return; - } - - Method = func.Method; - FuncReference = new WeakReference(func.Target); - - Reference = new WeakReference(target); - } - - /// - /// Executes the func. This only happens if the func's owner - /// is still alive. The func's parameter is set to default(T). - /// - public new TResult Execute() - { - return Execute(default(T)); - } - - /// - /// Executes the func. This only happens if the func's owner - /// is still alive. - /// - /// A parameter to be passed to the action. - public TResult Execute(T parameter) - { - if (_staticFunc != null) - { - return _staticFunc(parameter); - } - - if (IsAlive) - { - if (Method != null - && FuncReference != null) - { - return (TResult)Method.Invoke( - FuncTarget, - new object[] - { - parameter - }); - } - - } - - return default(TResult); - } - - /// - /// Executes the func with a parameter of type object. This parameter - /// will be casted to T. This method implements - /// and can be useful if you store multiple WeakFunc{T} instances but don't know in advance - /// what type T represents. - /// - /// The parameter that will be passed to the func after - /// being casted to T. - /// The result of the execution as object, to be casted to T. - public object ExecuteWithObject(object parameter) - { - var parameterCasted = (T)parameter; - return Execute(parameterCasted); - } - - /// - /// Sets all the funcs that this WeakFunc contains to null, - /// which is a signal for containing objects that this WeakFunc - /// should be deleted. - /// - public new void MarkForDeletion() - { - _staticFunc = null; - base.MarkForDeletion(); - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Interfaces/IShell.cs b/BillsManager.ViewModels/Interfaces/IShell.cs deleted file mode 100644 index a6ec180..0000000 --- a/BillsManager.ViewModels/Interfaces/IShell.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace BillsManager.ViewModels -{ - public interface IShell - { - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/AvailableSuppliersRequest.cs b/BillsManager.ViewModels/Messages/Database/AvailableSuppliersRequest.cs deleted file mode 100644 index ff28464..0000000 --- a/BillsManager.ViewModels/Messages/Database/AvailableSuppliersRequest.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class AvailableSuppliersRequest - { - public AvailableSuppliersRequest(Action> acquireSuppliersAction) - { - this.acquireSuppliersAction = acquireSuppliersAction; - } - - private readonly Action> acquireSuppliersAction; - public Action> AcquireSuppliersAction - { - get { return this.acquireSuppliersAction; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/Bills Events/BillAddedMessage.cs b/BillsManager.ViewModels/Messages/Database/Bills Events/BillAddedMessage.cs deleted file mode 100644 index c3631b2..0000000 --- a/BillsManager.ViewModels/Messages/Database/Bills Events/BillAddedMessage.cs +++ /dev/null @@ -1,12 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class BillAddedMessage : BillCRUDEvent - { - public BillAddedMessage(Bill addedBill) - : base(addedBill) - { - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/Bills Events/BillCRUDEvent.cs b/BillsManager.ViewModels/Messages/Database/Bills Events/BillCRUDEvent.cs deleted file mode 100644 index 36b6789..0000000 --- a/BillsManager.ViewModels/Messages/Database/Bills Events/BillCRUDEvent.cs +++ /dev/null @@ -1,18 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public abstract class BillCRUDEvent - { - public BillCRUDEvent(Bill bill) - { - this.bill = bill; - } - - private readonly Bill bill; - public Bill Bill - { - get { return this.bill; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/Bills Events/BillDeletedMessage.cs b/BillsManager.ViewModels/Messages/Database/Bills Events/BillDeletedMessage.cs deleted file mode 100644 index eab7fab..0000000 --- a/BillsManager.ViewModels/Messages/Database/Bills Events/BillDeletedMessage.cs +++ /dev/null @@ -1,12 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class BillDeletedMessage : BillCRUDEvent - { - public BillDeletedMessage(Bill deletedBill) - : base(deletedBill) - { - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/Bills Events/BillEditedMessage.cs b/BillsManager.ViewModels/Messages/Database/Bills Events/BillEditedMessage.cs deleted file mode 100644 index 247c150..0000000 --- a/BillsManager.ViewModels/Messages/Database/Bills Events/BillEditedMessage.cs +++ /dev/null @@ -1,19 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class BillEditedMessage : BillCRUDEvent - { - public BillEditedMessage(Bill newBill, Bill oldBill) - : base(newBill) - { - this.oldBill = oldBill; - } - - private readonly Bill oldBill; - public Bill OldBill - { - get { return this.oldBill; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/AddBillToSupplierOrder.cs b/BillsManager.ViewModels/Messages/Database/CRUD/AddBillToSupplierOrder.cs deleted file mode 100644 index c3eb536..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/AddBillToSupplierOrder.cs +++ /dev/null @@ -1,18 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class AddBillToSupplierOrder - { - public AddBillToSupplierOrder(Supplier supplier) - { - this.supplier = supplier; - } - - private readonly Supplier supplier; - public Supplier Supplier - { - get { return this.supplier; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/AddNewSupplierOrder.cs b/BillsManager.ViewModels/Messages/Database/CRUD/AddNewSupplierOrder.cs deleted file mode 100644 index f554dc0..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/AddNewSupplierOrder.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace BillsManager.ViewModels.Messages -{ - public class AddNewSupplierOrder - { - public AddNewSupplierOrder() - { - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/AddedMessageGeneric.cs b/BillsManager.ViewModels/Messages/Database/CRUD/AddedMessageGeneric.cs deleted file mode 100644 index 2b822d6..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/AddedMessageGeneric.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace BillsManager.ViewModels.Messages -{ - public partial class AddedMessage : CRUDMessage - where T : class - { - public AddedMessage(T addedItem) - { - this.addedItem = addedItem; - } - - private readonly T addedItem; - public T AddedItem - { - get { return this.addedItem; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/CRUDMessage.cs b/BillsManager.ViewModels/Messages/Database/CRUD/CRUDMessage.cs deleted file mode 100644 index 2f1a13d..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/CRUDMessage.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace BillsManager.ViewModels.Messages -{ - public abstract partial class CRUDMessage - { - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/CRUDMessageGeneric.cs b/BillsManager.ViewModels/Messages/Database/CRUD/CRUDMessageGeneric.cs deleted file mode 100644 index 4801324..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/CRUDMessageGeneric.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace BillsManager.ViewModels.Messages -{ - public abstract partial class CRUDMessage : CRUDMessage - where T : class - { - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/DeletedMessageGeneric.cs b/BillsManager.ViewModels/Messages/Database/CRUD/DeletedMessageGeneric.cs deleted file mode 100644 index 592b9ca..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/DeletedMessageGeneric.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace BillsManager.ViewModels.Messages -{ - public partial class DeletedMessage : CRUDMessage - where T : class - { - public DeletedMessage(T deletedItem) - { - this.deletedItem = deletedItem; - } - - private readonly T deletedItem; - public T DeletedItem - { - get { return this.deletedItem; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/EditBillOrder.cs b/BillsManager.ViewModels/Messages/Database/CRUD/EditBillOrder.cs deleted file mode 100644 index 2befb3f..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/EditBillOrder.cs +++ /dev/null @@ -1,29 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class EditBillOrder - { - public EditBillOrder(Bill bill) - { - this.bill = bill; - } - - public EditBillOrder(uint billID) - { - this.billID = billID; - } - - private readonly Bill bill; - public Bill Bill - { - get { return this.bill; } - } - - private readonly uint billID; - public uint BillID - { - get { return this.billID; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/EditSupplierOrder.cs b/BillsManager.ViewModels/Messages/Database/CRUD/EditSupplierOrder.cs deleted file mode 100644 index 8833acd..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/EditSupplierOrder.cs +++ /dev/null @@ -1,29 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class EditSupplierOrder - { - public EditSupplierOrder(Supplier supplier) - { - this.supplier = supplier; - } - - public EditSupplierOrder(uint supplierID) - { - this.supplierID = supplierID; - } - - private readonly Supplier supplier; - public Supplier Supplier - { - get { return this.supplier; } - } - - private readonly uint supplierID; - public uint SupplierID - { - get { return this.supplierID; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/CRUD/EditedMessageGeneric.cs b/BillsManager.ViewModels/Messages/Database/CRUD/EditedMessageGeneric.cs deleted file mode 100644 index c340339..0000000 --- a/BillsManager.ViewModels/Messages/Database/CRUD/EditedMessageGeneric.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace BillsManager.ViewModels.Messages -{ - public partial class EditedMessage : CRUDMessage - where T : class - { - public EditedMessage(T oldItem, T newItem) - { - this.oldItem = oldItem; - this.newItem = newItem; - } - - private readonly T oldItem; - public T OldItem - { - get { return this.oldItem; } - } - - private readonly T newItem; - public T NewItem - { - get { return this.newItem; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/DBConnectionStateChangedMessage.cs b/BillsManager.ViewModels/Messages/Database/DBConnectionStateChangedMessage.cs deleted file mode 100644 index 70f76fe..0000000 --- a/BillsManager.ViewModels/Messages/Database/DBConnectionStateChangedMessage.cs +++ /dev/null @@ -1,17 +0,0 @@ -using BillsManager.Models; -namespace BillsManager.ViewModels.Messages -{ - public class DBConnectionStateChangedMessage - { - public DBConnectionStateChangedMessage(DBConnectionState dbState) - { - this.dbState = dbState; - } - - private readonly DBConnectionState dbState; - public DBConnectionState DBState - { - get { return this.dbState; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/Search/BillsFilterMessage.cs b/BillsManager.ViewModels/Messages/Database/Search/BillsFilterMessage.cs deleted file mode 100644 index 58e04d8..0000000 --- a/BillsManager.ViewModels/Messages/Database/Search/BillsFilterMessage.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System.Collections.Generic; - -namespace BillsManager.ViewModels.Messages -{ - public class BillsFilterMessage : FilterMessage - { - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/Search/FilterMessageGeneric.cs b/BillsManager.ViewModels/Messages/Database/Search/FilterMessageGeneric.cs deleted file mode 100644 index c2b28ff..0000000 --- a/BillsManager.ViewModels/Messages/Database/Search/FilterMessageGeneric.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Collections.Generic; - -namespace BillsManager.ViewModels.Messages -{ - public partial class FilterMessage - where T : class - { - public FilterMessage(IEnumerable> filters) - { - this.filters = filters; - } - - private readonly IEnumerable> filters; - public IEnumerable> Filters - { - get { return this.filters; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/Search/SuppliersFilterMessage.cs b/BillsManager.ViewModels/Messages/Database/Search/SuppliersFilterMessage.cs deleted file mode 100644 index d8b87fa..0000000 --- a/BillsManager.ViewModels/Messages/Database/Search/SuppliersFilterMessage.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Collections.Generic; - -namespace BillsManager.ViewModels.Messages -{ - public class SuppliersFilterMessage - { - //public SuppliersFilterMessage(Func filter) - //{ - // this.filter = filter; - //} - - public SuppliersFilterMessage(IEnumerable> filters) - { - this.filters = filters; - } - - //private readonly Func filter; - //public Func Filter - //{ - // get { return this.filter; } - //} - - private readonly IEnumerable> filters; - public IEnumerable> Filters - { - get { return this.filters; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/Search/SuppliersFilterNeedsRefreshMessage.cs b/BillsManager.ViewModels/Messages/Database/Search/SuppliersFilterNeedsRefreshMessage.cs deleted file mode 100644 index afe7f8c..0000000 --- a/BillsManager.ViewModels/Messages/Database/Search/SuppliersFilterNeedsRefreshMessage.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace BillsManager.ViewModel.Messages -{ - public class SuppliersFilterNeedsRefreshMessage - { - public SuppliersFilterNeedsRefreshMessage() - { - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/ShowSuppliersBillsOrder.cs b/BillsManager.ViewModels/Messages/Database/ShowSuppliersBillsOrder.cs deleted file mode 100644 index 0058650..0000000 --- a/BillsManager.ViewModels/Messages/Database/ShowSuppliersBillsOrder.cs +++ /dev/null @@ -1,19 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - // TODO: update orders and requests classes' names - public class ShowSuppliersBillsOrder - { - public ShowSuppliersBillsOrder(Supplier supplier) - { - this.supplier = supplier; - } - - private readonly Supplier supplier; - public Supplier Supplier - { - get { return this.supplier; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/SupplierNameRequest.cs b/BillsManager.ViewModels/Messages/Database/SupplierNameRequest.cs deleted file mode 100644 index 5361a30..0000000 --- a/BillsManager.ViewModels/Messages/Database/SupplierNameRequest.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class SupplierNameRequest - { - public SupplierNameRequest(uint supplierID, Action giveSupplier) - { - this.supplierID = supplierID; - this.giveSupplier = giveSupplier; - } - - private readonly uint supplierID; - public uint SupplierID - { - get { return this.supplierID; } - } - - private readonly Action giveSupplier; - public Action GiveSupplier - { - get { return this.giveSupplier; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/View events/BillsListChangedMessage.cs b/BillsManager.ViewModels/Messages/Database/View events/BillsListChangedMessage.cs deleted file mode 100644 index d717edc..0000000 --- a/BillsManager.ViewModels/Messages/Database/View events/BillsListChangedMessage.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Collections.Generic; -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class BillsListChangedMessage - { - public BillsListChangedMessage(ICollection bills) - { - this.bills = bills; - } - - private ICollection bills; - public ICollection Bills - { - get { return this.bills; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/View events/SelectedSupplierChangedMessage.cs b/BillsManager.ViewModels/Messages/Database/View events/SelectedSupplierChangedMessage.cs deleted file mode 100644 index d55358c..0000000 --- a/BillsManager.ViewModels/Messages/Database/View events/SelectedSupplierChangedMessage.cs +++ /dev/null @@ -1,19 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class SelectedSupplierChangedMessage - { - public SelectedSupplierChangedMessage(Supplier selectedSupplier) - { - this.selectedSupplier = selectedSupplier; - } - - private readonly Supplier selectedSupplier; - public Supplier SelectedSupplier - { - get { return this.selectedSupplier; } - } - - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/View events/SupplierAddedMessage.cs b/BillsManager.ViewModels/Messages/Database/View events/SupplierAddedMessage.cs deleted file mode 100644 index 1e2d15e..0000000 --- a/BillsManager.ViewModels/Messages/Database/View events/SupplierAddedMessage.cs +++ /dev/null @@ -1,18 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class SupplierAddedMessage : SupplierCRUDEvent - { - public SupplierAddedMessage(Supplier addedSupplier) - { - this.addedSupplier = addedSupplier; - } - - private readonly Supplier addedSupplier; - public Supplier AddedSupplier - { - get { return this.addedSupplier; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/View events/SupplierCRUDEvent.cs b/BillsManager.ViewModels/Messages/Database/View events/SupplierCRUDEvent.cs deleted file mode 100644 index 53af785..0000000 --- a/BillsManager.ViewModels/Messages/Database/View events/SupplierCRUDEvent.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace BillsManager.ViewModels.Messages -{ - public abstract class SupplierCRUDEvent - { - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/View events/SupplierDeletedMessage.cs b/BillsManager.ViewModels/Messages/Database/View events/SupplierDeletedMessage.cs deleted file mode 100644 index c71c5a1..0000000 --- a/BillsManager.ViewModels/Messages/Database/View events/SupplierDeletedMessage.cs +++ /dev/null @@ -1,18 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class SupplierDeletedMessage : SupplierCRUDEvent - { - public SupplierDeletedMessage(Supplier deletedSupplier) - { - this.deletedSupplier = deletedSupplier; - } - - private readonly Supplier deletedSupplier; - public Supplier DeletedSupplier - { - get { return deletedSupplier; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/View events/SupplierEditedMessage.cs b/BillsManager.ViewModels/Messages/Database/View events/SupplierEditedMessage.cs deleted file mode 100644 index 35a2205..0000000 --- a/BillsManager.ViewModels/Messages/Database/View events/SupplierEditedMessage.cs +++ /dev/null @@ -1,25 +0,0 @@ -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class SupplierEditedMessage : SupplierCRUDEvent - { - public SupplierEditedMessage(Supplier newSupplierVersion, Supplier oldSupplierVersion) - { - this.newSupplierVersion = newSupplierVersion; - this.oldSupplierVersion = oldSupplierVersion; - } - - private readonly Supplier newSupplierVersion; - public Supplier NewSupplierVersion - { - get { return this.newSupplierVersion; } - } - - private readonly Supplier oldSupplierVersion; - public Supplier OldSupplierVersion - { - get { return this.oldSupplierVersion; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/View events/SupplierNameChangedMessage.cs b/BillsManager.ViewModels/Messages/Database/View events/SupplierNameChangedMessage.cs deleted file mode 100644 index eba6682..0000000 --- a/BillsManager.ViewModels/Messages/Database/View events/SupplierNameChangedMessage.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace BillsManager.ViewModel.Messages -{ - public class SupplierNameChangedMessage - { - public SupplierNameChangedMessage(string oldName, string newName) - { - this.oldName = oldName; - this.newName = newName; - } - - private readonly string oldName; - public string OldName - { - get { return this.oldName; } - } - - private readonly string newName; - public string NewName - { - get { return this.newName; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Messages/Database/View events/SuppliersListChangedMessage.cs b/BillsManager.ViewModels/Messages/Database/View events/SuppliersListChangedMessage.cs deleted file mode 100644 index c40569c..0000000 --- a/BillsManager.ViewModels/Messages/Database/View events/SuppliersListChangedMessage.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; -using BillsManager.Models; - -namespace BillsManager.ViewModels.Messages -{ - public class SuppliersListChangedMessage - { - public SuppliersListChangedMessage( - ICollection suppliers) - { - this.suppliers = suppliers; - } - - private readonly ICollection suppliers; - public ICollection Suppliers - { - get { return this.suppliers; } - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Properties/AssemblyInfo.cs b/BillsManager.ViewModels/Properties/AssemblyInfo.cs deleted file mode 100644 index bb53d0b..0000000 --- a/BillsManager.ViewModels/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// Le informazioni generali relative a un assembly sono controllate dal seguente -// set di attributi. Per modificare le informazioni associate a un assembly -// occorre quindi modificare i valori di questi attributi. -[assembly: AssemblyTitle("BillsManager.ViewModels")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BillsManager.ViewModels")] -[assembly: AssemblyCopyright("Copyright © Nalesso Sergio 2013-2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili -// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da -// COM, impostare su true l'attributo ComVisible per tale tipo. -[assembly: ComVisible(false)] - -// Se il progetto viene esposto a COM, il GUID che segue verrà utilizzato per creare l'ID della libreria dei tipi -[assembly: Guid("eb43a378-b1a7-4cf9-8ee9-925f7f49fc48")] - -// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: -// -// Numero di versione principale -// Numero di versione secondario -// Numero build -// Revisione -// -// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build -// utilizzando l'asterisco (*) come descritto di seguito: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BillsManager.ViewModels/Reporting/BillReportViewModel.cs b/BillsManager.ViewModels/Reporting/BillReportViewModel.cs deleted file mode 100644 index 502584b..0000000 --- a/BillsManager.ViewModels/Reporting/BillReportViewModel.cs +++ /dev/null @@ -1,75 +0,0 @@ -using BillsManager.Localization.Attributes; -using BillsManager.Services.Reporting; -using System.Windows; - -namespace BillsManager.ViewModels -{ - // TODO: review base class - public class BillReportViewModel - { - #region fields - - private readonly BillDetailsViewModel billDetailsViewModel; - - #endregion - - #region ctor - - public BillReportViewModel(BillDetailsViewModel billDetailsViewModel) - { - this.billDetailsViewModel = billDetailsViewModel; - } - - #endregion - - #region properties - - [LocalizedDisplayName("Supplier")] - public string SupplierName - { - get { return this.billDetailsViewModel.SupplierName; } - } - - [LocalizedDisplayName("Code")] - [TextAlignment(TextAlignment.Center)] - public string Code - { - get - { - if (this.billDetailsViewModel.Code != null) - return this.billDetailsViewModel.Code; - return string.Empty; - } - } - - [LocalizedDisplayName("Amount")] - [TextAlignment(TextAlignment.Right)] - public string Amount - { - get { return string.Format("{0:N2} €", this.billDetailsViewModel.Amount); } - } - - [LocalizedDisplayName("Agio")] - [TextAlignment(TextAlignment.Right)] - public string Agio - { - get { return string.Format("{0:N2} €", this.billDetailsViewModel.Agio); } - } - - [LocalizedDisplayName("DueDate")] - [TextAlignment(TextAlignment.Center)] - public string DueDate - { - get { return this.billDetailsViewModel.DueDate.ToShortDateString(); } - } - - [LocalizedDisplayName("ReleaseDate")] - [TextAlignment(TextAlignment.Center)] - public string ReleaseDate - { - get { return this.billDetailsViewModel.ReleaseDate.ToShortDateString(); } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Reporting/PrintReportViewModel.cs b/BillsManager.ViewModels/Reporting/PrintReportViewModel.cs deleted file mode 100644 index 2f4e3aa..0000000 --- a/BillsManager.ViewModels/Reporting/PrintReportViewModel.cs +++ /dev/null @@ -1,220 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Services.Reporting; -using BillsManager.ViewModels.Commanding; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Windows.Controls; -using System.Windows.Media; - -namespace BillsManager.ViewModels -{ - public class PrintReportViewModel/**/ : Screen - /*where T : class*/ - { - #region fields - - private readonly ReportPrinter reportPrinter; - private readonly Func, ReportPrinter> reportPrinterFactory; - - #endregion - - #region ctor - - public PrintReportViewModel( - Func, ReportPrinter> reportPrinterFactory, - IEnumerable billReportList, - string header, - string comment) - { - this.reportPrinterFactory = reportPrinterFactory; - - this.reportPrinter = reportPrinterFactory.Invoke(billReportList); - this.reportPrinter.Header = header; - this.reportPrinter.Comment = comment; - - this.DisplayName = TranslationManager.Instance.Translate("PrintReport").ToString(); - - //this.Deactivated += - // (s, e) => - // { - // if (e.WasClosed) - // this.reportPrinterFactory.Dispose(); // TODO: remember to dispose dbconnector - // }; - - this.GoToFirstPage(); - } - - #endregion - - #region properties - - public string Header - { - get { return this.reportPrinter.Header; } - set - { - if (this.reportPrinter.Header == value) return; - - this.reportPrinter.Header = value; - this.NotifyOfPropertyChange(() => this.Header); - - if (this.CurrentPageNumber == 1) - this.NotifyOfPropertyChange(() => this.CurrentPage); - } - } - - private int currentPageNumber; - public int CurrentPageNumber - { - get { return this.currentPageNumber; } - set - { - if (value < 1) - value = 1; - else if (value > this.reportPrinter.PageCount) - value = this.reportPrinter.PageCount; - - if (this.currentPageNumber == value) return; - - this.currentPageNumber = value; - this.NotifyOfPropertyChange(() => this.CurrentPageNumber); - this.NotifyOfPropertyChange(() => this.CurrentPage); - this.NotifyOfPropertyChange(() => this.CanGoToPreviousPage); - this.NotifyOfPropertyChange(() => this.CanGoToNextPage); - } - } - - public int PageCount - { - get - { - return this.reportPrinter.PageCount; - } - } - - public Visual CurrentPage - { - get - { - return this.reportPrinter.GetPage(this.CurrentPageNumber - 1).Visual; - } - } - - #region page navigation - - public bool CanGoToPreviousPage - { - get { return this.CurrentPageNumber > 1; } - } - - public bool CanGoToNextPage - { - get - { - var can = (this.CurrentPageNumber < this.reportPrinter.PageCount); - return can; - } - } - - #endregion - - #endregion - - #region methods - - #region page navigation - - private void GoToPreviousPage() - { - this.CurrentPageNumber--; - } - - private void GoToNextPage() - { - this.CurrentPageNumber++; - } - - private void GoToFirstPage() - { - this.CurrentPageNumber = 1; - } - - private void GoToLastPage() - { - this.CurrentPageNumber = this.reportPrinter.PageCount; - } - - public void Print() - { - new PrintDialog().PrintDocument(this.reportPrinter, "Bills Manager Report"); - } - - #endregion - - #endregion - - #region commands - - private RelayCommand goToFirstPageCommand; - public RelayCommand GoToFirstPageCommand - { - get - { - return this.goToFirstPageCommand ?? (this.goToFirstPageCommand = - new RelayCommand( - () => this.GoToFirstPage(), - () => this.CanGoToPreviousPage)); - } - } - - private RelayCommand goToPreviousPageCommand; - public RelayCommand GoToPreviousPageCommand - { - get - { - return this.goToPreviousPageCommand ?? (this.goToPreviousPageCommand = - new RelayCommand( - () => this.GoToPreviousPage(), - () => this.CanGoToPreviousPage)); - } - } - - private RelayCommand goToNextPageCommand; - public RelayCommand GoToNextPageCommand - { - get - { - return this.goToNextPageCommand ?? (this.goToNextPageCommand = - new RelayCommand( - () => this.GoToNextPage(), - () => this.CanGoToNextPage)); - } - } - - private RelayCommand goToLastPageCommand; - public RelayCommand GoToLastPageCommand - { - get - { - return this.goToLastPageCommand ?? (this.goToLastPageCommand = - new RelayCommand( - () => this.GoToLastPage(), - () => this.CanGoToNextPage)); - } - } - - private RelayCommand printCommand; - public RelayCommand PrintCommand - { - get - { - return this.printCommand ?? (this.printCommand = - new RelayCommand( - () => this.Print())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Search/FilterGeneric.cs b/BillsManager.ViewModels/Search/FilterGeneric.cs deleted file mode 100644 index 40fde3f..0000000 --- a/BillsManager.ViewModels/Search/FilterGeneric.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; - -namespace BillsManager.ViewModels -{ - public class Filter - where T : class - { - #region ctor - - public Filter( - Predicate filterPredicate, - Func description) - { - this.execute = filterPredicate; - this.description = description; - } - - #endregion - - #region properties - - private readonly Predicate execute; - public Predicate Execute - { - get { return this.execute; } - } - - private readonly Func description; - public Func Description - { - get { return this.description; } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Search/SearchBillsViewModel.cs b/BillsManager.ViewModels/Search/SearchBillsViewModel.cs deleted file mode 100644 index c114319..0000000 --- a/BillsManager.ViewModels/Search/SearchBillsViewModel.cs +++ /dev/null @@ -1,397 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Models; -using BillsManager.ViewModels.Commanding; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace BillsManager.ViewModels -{ - // TODO: create a filter class with a description for the report subtitle - public partial class SearchBillsViewModel : - Screen, - IHandle, - IHandle>, - IHandle>, - IHandle>, - IHandle>, - IHandle, - IHandle - { - #region fields - - private IEventAggregator globalEventAggregator; - - private Filter supplierNameFilter; - private Filter isPaidFilter; - private Filter releaseDateFilter; - private Filter dueDateFilter; - - #endregion - - #region ctor - - // TODO: should available suppliers be injected? As observable, maybe? - public SearchBillsViewModel( - IEventAggregator globalEventAggregator) - { - // SERVICES - this.globalEventAggregator = globalEventAggregator; - - // SUBSCRIPTIONS - this.globalEventAggregator.Subscribe(this); - - // FILTERS - this.ConfigureFilters(); - //this.isPaidFilter = bvm => bvm.PaymentDate.HasValue == this.IsPaidFilterValue; - //this.supplierNameFilter = bvm => bvm.SupplierID == this.SelectedSupplier.ID; - //this.releaseDateFilter = bvm => bvm.ReleaseDate == this.ReleaseDateFilterValue; - //this.dueDateFilter = bvm => bvm.DueDate == this.dueDateFilterValue; - - // handlers - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - this.globalEventAggregator.Unsubscribe(this); - }; - } - - private void ConfigureFilters() - { - this.supplierNameFilter = - new Filter( - bdvm => /*this.SelectedSupplier != null ?*/ bdvm.SupplierID == this.SelectedSupplier.ID /*: true*/, - () => - TranslationManager.Instance.Translate("By").ToString().ToLower(TranslationManager.Instance.CurrentLanguage) + - " " + this.SelectedSupplier.Name); - - this.isPaidFilter = - new Filter( - bdvm => this.IsPaidFilterValue.HasValue ? bdvm.IsPaid == this.IsPaidFilterValue : true, - () => - this.IsPaidFilterValue.HasValue ? - (this.IsPaidFilterValue == true ? TranslationManager.Instance.Translate("Paid_toBills").ToString() : - TranslationManager.Instance.Translate("NotPaid_toBills").ToString()) : - TranslationManager.Instance.Translate("All_toBills").ToString()); - - this.dueDateFilter = - new Filter( - bdvm => this.DueDateFilterValue.HasValue ? bdvm.DueDate == this.DueDateFilterValue : true, - () => TranslationManager.Instance.Translate("DuedOn_toBills").ToString() + " " + this.DueDateFilterValue.Value.ToShortDateString()); - - this.releaseDateFilter = - new Filter( - bdvm => this.ReleaseDateFilterValue.HasValue ? bdvm.ReleaseDate == this.ReleaseDateFilterValue : true, - () => TranslationManager.Instance.Translate("ReleasedOn_toBills").ToString() + " " + this.ReleaseDateFilterValue.Value.ToShortDateString()); - } - - #endregion - - #region properties - - private bool useSupplierFilter; - public bool UseSupplierFilter - { - get { return this.useSupplierFilter; } - set - { - if (this.AvailableSuppliers == null) value = false; - - if (this.useSupplierFilter == value) return; - - - this.useSupplierFilter = value; - this.NotifyOfPropertyChange(() => this.UseSupplierFilter); - this.SelectedSupplier = (value ? this.AvailableSuppliers.FirstOrDefault() : null); - } - } - - private IEnumerable availableSuppliers; - public IEnumerable AvailableSuppliers - { - get - { - if (this.availableSuppliers == null) - this.globalEventAggregator.PublishOnUIThread( - new AvailableSuppliersRequest(suppliers => this.availableSuppliers = suppliers)); - - return this.availableSuppliers; - } - set - { - if (this.availableSuppliers != value) - { - this.availableSuppliers = value; - this.NotifyOfPropertyChange(() => this.AvailableSuppliers); - } - } - } - - private Supplier selectedSupplier; - public Supplier SelectedSupplier - { - get { return this.selectedSupplier; } - set - { - if (this.selectedSupplier == value) return; - - this.selectedSupplier = value; - this.NotifyOfPropertyChange(() => this.SelectedSupplier); - this.useSupplierFilter = (value != null); - this.NotifyOfPropertyChange(() => this.UseSupplierFilter); - } - } - - private bool? isPaidFilterValue; - public bool? IsPaidFilterValue - { - get { return this.isPaidFilterValue; } - set - { - if (this.isPaidFilterValue != value) - { - this.isPaidFilterValue = value; - this.NotifyOfPropertyChange(() => this.IsPaidFilterValue); - this.NotifyOfPropertyChange(() => this.IsPaidFilterState); - } - } - } - - public string IsPaidFilterState - { - get - { - switch (this.IsPaidFilterValue) - { - case true: - return TranslationManager.Instance.Translate("Paid_toBills").ToString(); - case false: - return TranslationManager.Instance.Translate("NotPaid_toBills").ToString(); - default: - return TranslationManager.Instance.Translate("All_toBills").ToString(); - } - } - } - - private bool useReleaseDateFilter; - public bool UseReleaseDateFilter - { - get { return this.useReleaseDateFilter; } - set - { - if (this.useReleaseDateFilter != value) - { - this.useReleaseDateFilter = value; - this.NotifyOfPropertyChange(() => this.UseReleaseDateFilter); - this.ReleaseDateFilterValue = (value ? DateTime.Today : (DateTime?)null); - } - } - } - - private DateTime? releaseDateFilterValue = null; - public DateTime? ReleaseDateFilterValue - { - get { return this.releaseDateFilterValue; } - set - { - if (this.releaseDateFilterValue != value) - { - this.releaseDateFilterValue = value; - this.NotifyOfPropertyChange(() => this.ReleaseDateFilterValue); - this.useReleaseDateFilter = (value != null); - this.NotifyOfPropertyChange(() => this.UseReleaseDateFilter); - } - } - } - - private bool useDueDateFilter; - public bool UseDueDateFilter - { - get { return this.useDueDateFilter; } - set - { - if (this.useDueDateFilter != value) - { - this.useDueDateFilter = value; - this.NotifyOfPropertyChange(() => this.UseDueDateFilter); - this.DueDateFilterValue = (value ? DateTime.Today : (DateTime?)null); - } - } - } - - private DateTime? dueDateFilterValue = null; - public DateTime? DueDateFilterValue - { - get { return this.dueDateFilterValue; } - set - { - if (this.dueDateFilterValue != value) - { - this.dueDateFilterValue = value; - this.NotifyOfPropertyChange(() => this.DueDateFilterValue); - this.useDueDateFilter = (value != null); - this.NotifyOfPropertyChange(() => this.UseDueDateFilter); - } - } - } - - #endregion - - #region methods - - private void SendFilters() - { - List> filters = new List>(); - - if (this.UseSupplierFilter) filters.Add(this.supplierNameFilter); - if (this.IsPaidFilterValue.HasValue) filters.Add(this.isPaidFilter); - if (this.UseReleaseDateFilter) filters.Add(this.releaseDateFilter); - if (this.UseDueDateFilter) filters.Add(this.dueDateFilter); - - if (filters.Count > 0) - this.globalEventAggregator.PublishOnUIThread(new FilterMessage(filters)); - else - this.globalEventAggregator.PublishOnUIThread(new FilterMessage(null)); - } - - private void DeactivateAllFilters() - { - this.UseDueDateFilter = false; - this.UseReleaseDateFilter = false; - this.UseSupplierFilter = false; - this.IsPaidFilterValue = null; - } - - #region message handlers - - public void Handle(SuppliersListChangedMessage message) - { - this.AvailableSuppliers = message.Suppliers; - - if (!this.UseSupplierFilter) return; - - if (!this.AvailableSuppliers.Contains(this.SelectedSupplier)) - { - this.UseSupplierFilter = false; - this.SendFilters(); - } - } - - public void Handle(AddedMessage message) - { - this.AvailableSuppliers = this.AvailableSuppliers.Concat(new[] { message.AddedItem }); - } - - public void Handle(EditedMessage message) - { - if (message.OldItem.Name != message.NewItem.Name) - { - var supps = this.AvailableSuppliers; - var selSupp = this.SelectedSupplier; - - this.AvailableSuppliers = null; // TODO: avoid a wasted refresh - this.SelectedSupplier = null; - - this.AvailableSuppliers = supps; - this.SelectedSupplier = selSupp; - } - } - - public void Handle(DeletedMessage message) - { - this.AvailableSuppliers = this.AvailableSuppliers.Where(supplier => supplier != message.DeletedItem); - - if (this.SelectedSupplier == message.DeletedItem) - { - this.SelectedSupplier = null; - this.UseSupplierFilter = false; - this.SendFilters(); - } - } - - - public void Handle(EditedMessage message) - { - bool refreshNeeded = false; - - if (this.UseSupplierFilter) - refreshNeeded |= (message.OldItem.SupplierID != message.NewItem.SupplierID); - - if (this.UseReleaseDateFilter) - refreshNeeded |= (message.OldItem.ReleaseDate != message.NewItem.ReleaseDate); - - if (this.UseDueDateFilter) - refreshNeeded |= (message.OldItem.DueDate != message.NewItem.DueDate); - - if (this.IsPaidFilterValue != null) - refreshNeeded |= (message.OldItem.PaymentDate.HasValue != message.NewItem.PaymentDate.HasValue); - - if (refreshNeeded) - this.SendFilters(); - } - - - public void Handle(ShowSuppliersBillsOrder message) - { - if (message.Supplier == this.SelectedSupplier) return; - - if (!this.AvailableSuppliers.Contains(message.Supplier)) return; - - this.SelectedSupplier = message.Supplier; - this.SendFilters(); - } - - public void Handle(SelectedSupplierChangedMessage message) - { - if (!this.UseSupplierFilter) return; - - if (!this.AvailableSuppliers.Contains(message.SelectedSupplier)) - { - this.UseSupplierFilter = false; - } - else - { - this.SelectedSupplier = message.SelectedSupplier; - } - - this.SendFilters(); - } - - #endregion - - #endregion - - #region commands - - private RelayCommand sendFilerCommand; - public RelayCommand SendFilterCommand - { - get - { - return this.sendFilerCommand ?? (this.sendFilerCommand = - new RelayCommand( - () => this.SendFilters())); - } - } - - private RelayCommand exitSearchCommand; - public RelayCommand ExitSearchCommand - { - get - { - return this.exitSearchCommand ?? (this.exitSearchCommand = - new RelayCommand( - () => - { - this.DeactivateAllFilters(); - this.SendFilters(); - })); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Search/SearchSuppliersViewModel.cs b/BillsManager.ViewModels/Search/SearchSuppliersViewModel.cs deleted file mode 100644 index 61dedbd..0000000 --- a/BillsManager.ViewModels/Search/SearchSuppliersViewModel.cs +++ /dev/null @@ -1,194 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Models; -using BillsManager.ViewModels.Commanding; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public partial class SearchSuppliersViewModel : Screen, - IHandle>, - IHandle>, - IHandle> - { - #region fields - - private readonly IEventAggregator globalEventAggregator; - - private Filter obligationStateFilter; - - #endregion - - #region ctor - - public SearchSuppliersViewModel( - IEventAggregator globalEventAggregator) - { - // SERVICES - this.globalEventAggregator = globalEventAggregator; - - // SUBSCRIPTIONS - this.globalEventAggregator.Subscribe(this); - - // HANDLERS - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - { - this.globalEventAggregator.Unsubscribe(this); - } - }; - - // FILTERS - this.ConfigureFilters(); - //this.obligationStateFilter = s => s.ObligationState == this.ObligationStateFilterValue; - } - - private void ConfigureFilters() - { - this.obligationStateFilter = - new Filter( - sdvm => sdvm.ObligationState == this.ObligationStateFilterValue, - () => - { - switch (this.ObligationStateFilterValue) - { - case Obligation.Unbound: - return TranslationManager.Instance.Translate("Unbound_toSuppliers").ToString(); - case Obligation.Creditor: - return TranslationManager.Instance.Translate("Creditor_toSuppliers").ToString(); - default: - return TranslationManager.Instance.Translate("Debtor_toSuppliers").ToString(); - } - }); - } - - #endregion - - #region properties - - private bool useObligationStateFilter; - public bool UseObligationStateFilter - { - get { return this.useObligationStateFilter; } - set - { - if (this.useObligationStateFilter != value) - { - this.useObligationStateFilter = value; - this.NotifyOfPropertyChange(() => this.UseObligationStateFilter); - this.obligationStateFilterValue = value ? this.ObligationStates.FirstOrDefault() : (Obligation?)null; - this.NotifyOfPropertyChange(() => this.ObligationStateFilterValue); - } - } - } - - private Obligation? obligationStateFilterValue; - public Obligation? ObligationStateFilterValue - { - get { return this.obligationStateFilterValue; } - set - { - if (this.obligationStateFilterValue != value) - { - this.obligationStateFilterValue = value; - this.NotifyOfPropertyChange(() => this.ObligationStateFilterValue); - if (!this.UseObligationStateFilter & value != null) - { - this.useObligationStateFilter = true; - this.NotifyOfPropertyChange(() => this.UseObligationStateFilter); - } - } - } - } - - public IEnumerable ObligationStates - { - get { return Enum.GetValues(typeof(Obligation)).Cast(); } - } - - #endregion - - #region methods - - void SendFilters() - { - List> filters = new List>(); - - if (this.UseObligationStateFilter) filters.Add(this.obligationStateFilter); - - if (filters.Count > 0) - this.globalEventAggregator.PublishOnUIThread(new FilterMessage(filters)); - else - this.globalEventAggregator.PublishOnUIThread(new FilterMessage(null)); - } - - void DeactivateAllFilters() - { - this.UseObligationStateFilter = false; - } - - #region message handlers - - public void Handle(AddedMessage message) - { - if (!this.UseObligationStateFilter) return; - - this.SendFilters(); - } - - public void Handle(EditedMessage message) - { - if (!this.UseObligationStateFilter) return; - - if ((message.NewItem.Amount != message.OldItem.Amount) | - (message.NewItem.PaymentDate.HasValue != message.OldItem.PaymentDate.HasValue)) - this.SendFilters(); - } - - public void Handle(DeletedMessage message) - { - if (!this.UseObligationStateFilter) return; - - this.SendFilters(); - } - - #endregion - - #endregion - - #region commands - - private RelayCommand sendFilerCommand; - public RelayCommand SendFilterCommand - { - get - { - return this.sendFilerCommand ?? (this.sendFilerCommand = - new RelayCommand( - () => this.SendFilters())); - } - } - - private RelayCommand exitSearchCommand; - public RelayCommand ExitSearchCommand - { - get - { - return this.exitSearchCommand ?? (this.exitSearchCommand = - new RelayCommand( - () => - { - this.DeactivateAllFilters(); - this.SendFilters(); - })); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Search/SearchViewModelGeneric.cs b/BillsManager.ViewModels/Search/SearchViewModelGeneric.cs deleted file mode 100644 index 5090e3e..0000000 --- a/BillsManager.ViewModels/Search/SearchViewModelGeneric.cs +++ /dev/null @@ -1,83 +0,0 @@ -//using BillsManager.ViewModels.Commanding; -//using BillsManager.ViewModels.Messages; -//using Caliburn.Micro; - -//namespace BillsManager.ViewModels.Search -//{ -// public abstract partial class SearchViewModel : Screen -// where T : class -// { -// #region fields - -// private readonly IEventAggregator globalEventAggregator; - -// #endregion - -// #region ctor - -// public SearchViewModel(IEventAggregator globalEventAggregator, Filter filter) -// { -// this.globalEventAggregator = globalEventAggregator; - -// this.globalEventAggregator.Subscribe(this); - -// // handlers -// this.Deactivated += -// (s, e) => -// { -// if (e.WasClosed) -// this.globalEventAggregator.Unsubscribe(this); -// }; - -// this.Filter = filter; -// } - -// #endregion - -// #region properties - -// private string searchText; -// public string SearchText -// { -// get { return this.searchText; } -// set -// { -// if (this.searchText == value) return; - -// this.searchText = value; -// this.NotifyOfPropertyChange(() => this.SearchText); -// } -// } - -// public Filter Filter { protected set; get; } - -// #endregion - -// #region methods - -// public void Search() -// { -// if (!string.IsNullOrEmpty(this.SearchText)) -// this.globalEventAggregator.PublishOnUIThread(new FilterMessage(new Filter[] { this.Filter })); -// else -// this.globalEventAggregator.PublishOnUIThread(new FilterMessage(null)); -// } - -// #endregion - -// #region commands - -// private RelayCommand searchCommand; -// public RelayCommand SearchCommand -// { -// get -// { -// return this.searchCommand ?? (this.searchCommand = -// new RelayCommand( -// () => this.Search())); -// } -// } - -// #endregion -// } -//} \ No newline at end of file diff --git a/BillsManager.ViewModels/Search/SimpleSearchBillsViewModel.cs b/BillsManager.ViewModels/Search/SimpleSearchBillsViewModel.cs deleted file mode 100644 index e2696c5..0000000 --- a/BillsManager.ViewModels/Search/SimpleSearchBillsViewModel.cs +++ /dev/null @@ -1,17 +0,0 @@ -//using Caliburn.Micro; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Text; -//using System.Threading.Tasks; - -//namespace BillsManager.ViewModels.Search -//{ -// public partial class SimpleSearchBillsViewModel : SearchViewModel -// { -// public SimpleSearchBillsViewModel(IEventAggregator globalEventAggregator, Filter filter) -// { - -// } -// } -//} \ No newline at end of file diff --git a/BillsManager.ViewModels/SendFeedbackViewModel.cs b/BillsManager.ViewModels/SendFeedbackViewModel.cs deleted file mode 100644 index d517711..0000000 --- a/BillsManager.ViewModels/SendFeedbackViewModel.cs +++ /dev/null @@ -1,123 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Services.Feedback; -using BillsManager.ViewModels.Commanding; -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ - public class SendFeedbackViewModel : Screen - { - #region fields - - private readonly IWindowManager windowManager; - private readonly IFeedbackService feedbackSender; - - #endregion - - #region ctor - - public SendFeedbackViewModel( - IWindowManager windowManager, - IFeedbackService feedbackSender) - { - this.windowManager = windowManager; - this.feedbackSender = feedbackSender; - - this.DisplayName = TranslationManager.Instance.Translate("SendFeedback").ToString(); - } - - #endregion - - #region properties - - private string subject; - public string Subject - { - get { return this.subject; } - set - { - if (this.subject == value) return; - - this.subject = value; - this.NotifyOfPropertyChange(() => this.Subject); - } - } - - private string message; - public string Message - { - get { return this.message; } - set - { - if (this.message == value) return; - - this.message = value; - this.NotifyOfPropertyChange(() => this.Message); - } - } - - private bool closeAfterSend = true; - public bool CloseAfterSend - { - get { return this.closeAfterSend; } - set - { - if (this.closeAfterSend == value) return; - - this.closeAfterSend = value; - this.NotifyOfPropertyChange(() => this.CloseAfterSend); - } - } - - #endregion - - #region methods - - private void SendFeedback() - { - // TODO: feedback serialization for delayed send in case of error. send retries in a second moment (restart/countdown) - var sent = this.feedbackSender.SendFeedback(this.Subject, this.Message); - - DialogViewModel resultDialog = - DialogViewModel.Show( - sent ? DialogType.Information : DialogType.Error, - sent ? TranslationManager.Instance.Translate("FeedbackSent") : TranslationManager.Instance.Translate("FeedbackNotSent"), - sent ? TranslationManager.Instance.Translate("FeedbackSentMessage") : TranslationManager.Instance.Translate("FeedbackNotSentMessage")) - .Ok(); - - this.windowManager.ShowDialog(resultDialog); - - if (sent & this.CloseAfterSend) - this.TryClose(); - } - - #endregion - - #region commands - - private RelayCommand sendFeedbackCommand; - public RelayCommand SendFeedbackCommand - { - get - { - return this.sendFeedbackCommand ?? (this.sendFeedbackCommand = - new RelayCommand( - () => this.SendFeedback(), - () => !string.IsNullOrWhiteSpace(this.Message))); - } - } - - private RelayCommand cancelCommand; - public RelayCommand CancelCommand - { - get - { - return this.cancelCommand ?? (this.cancelCommand = - new RelayCommand( - () => this.TryClose())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SettingsViewModel.cs b/BillsManager.ViewModels/SettingsViewModel.cs deleted file mode 100644 index 80bb93c..0000000 --- a/BillsManager.ViewModels/SettingsViewModel.cs +++ /dev/null @@ -1,135 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Models; -using BillsManager.Services; -using BillsManager.ViewModels.Commanding; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Globalization; - -namespace BillsManager.ViewModels -{ - public partial class SettingsViewModel : Screen - { - #region fields - - private readonly ISettingsService settingsProvider; - - private readonly Settings oldSettings; - - #endregion - - #region ctor - - public SettingsViewModel( - ISettingsService settingsProvider) - { - this.settingsProvider = settingsProvider; - - this.oldSettings = (Settings)this.settingsProvider.Settings.Clone(); - - this.DisplayName = TranslationManager.Instance.Translate("Settings").ToString(); - } - - #endregion - - #region properties - - public IEnumerable AvailableLanguages - { - get { return TranslationManager.Instance.Languages; } - } - - public CultureInfo CurrentLanguage - { - get { return this.settingsProvider.Settings.Language; } - set - { - if (this.CurrentLanguage == value) return; - - this.settingsProvider.Settings.Language = value; - this.NotifyOfPropertyChange(() => this.CurrentLanguage); - TranslationManager.Instance.CurrentLanguage = value; - } - } - - public bool StartupDBLoad - { - get { return this.settingsProvider.Settings.StartupDBLoad; } - set - { - if (this.StartupDBLoad == value) return; - - this.settingsProvider.Settings.StartupDBLoad = value; - this.NotifyOfPropertyChange(() => this.StartupDBLoad); - } - } - - public string FeedbackToEmailAddress - { - get { return this.settingsProvider.Settings.FeedbackToEmailAddress; } - set - { - if (this.FeedbackToEmailAddress == value) return; - - this.settingsProvider.Settings.FeedbackToEmailAddress = value; - this.NotifyOfPropertyChange(() => this.FeedbackToEmailAddress); - } - } - - #endregion - - #region methods - - protected void RevertChanges() - { - try - { - this.CurrentLanguage = this.oldSettings.Language; - this.StartupDBLoad = this.oldSettings.StartupDBLoad; - this.FeedbackToEmailAddress = this.oldSettings.FeedbackToEmailAddress; - } - catch (Exception) { } - } - - protected void SaveAndClose() - { - this.settingsProvider.Save(); - this.TryClose(); - } - - protected void CancelAndClose() - { - this.RevertChanges(); - this.SaveAndClose(); - } - - #endregion - - #region commands - - private RelayCommand saveAndCloseCommand; - public RelayCommand SaveAndCloseCommand - { - get - { - return this.saveAndCloseCommand ?? (this.saveAndCloseCommand = - new RelayCommand( - () => this.SaveAndClose())); - } - } - - private RelayCommand cancelAndCloseCommand; - public RelayCommand CancelAndCloseCommand - { - get - { - return this.cancelAndCloseCommand ?? (this.cancelAndCloseCommand = - new RelayCommand( - () => this.CancelAndClose())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/ShellViewModel.cs b/BillsManager.ViewModels/ShellViewModel.cs deleted file mode 100644 index 4755d7b..0000000 --- a/BillsManager.ViewModels/ShellViewModel.cs +++ /dev/null @@ -1,165 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Services; -using BillsManager.ViewModels.Commanding; -//using BillsManager.ViewModels.Search; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Windows; - -namespace BillsManager.ViewModels -{ - public partial class ShellViewModel : Conductor - //,IHandle - { - #region fields - - private readonly IWindowManager windowManager; - private readonly IEventAggregator globalEventAggregator; - private readonly ISettingsService settingsProvider; - // main region - private readonly Func dbViewModelFactory; - // tools - private readonly Func sendFeedbackViewModelFactory; - private readonly Func settingsViewModelFactory; - // other UI regions - //private readonly Func> searchBillsViewModelFactory; - private readonly Func statusBarViewModelFactory; - - #endregion - - #region ctor - - public ShellViewModel( - IWindowManager windowManager, - IEventAggregator globalEventAggregator, - ISettingsService settingsProvider, - Func dbViewModelFactory, - //Func> searchBillsViewModelFactory, - Func statusBarViewModelFactory, - Func sendFeedbackViewModelFactory, - Func settingsViewModelFactory) - { - - // SERVICES - this.windowManager = windowManager; - this.globalEventAggregator = globalEventAggregator; - this.settingsProvider = settingsProvider; - - // FACTORIES - this.dbViewModelFactory = dbViewModelFactory; - //this.searchBillsViewModelFactory = searchBillsViewModelFactory; - this.statusBarViewModelFactory = statusBarViewModelFactory; - this.sendFeedbackViewModelFactory = sendFeedbackViewModelFactory; - this.settingsViewModelFactory = settingsViewModelFactory; - - // SUBSCRIPTIONS - this.globalEventAggregator.Subscribe(this); - - // HANDLERS - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - this.globalEventAggregator.Unsubscribe(this); - }; - - // UI - var sb = this.StatusBarViewModel; // initialize the status bar in order to receive db first load notifications - this.DisplayName = TranslationManager.Instance.Translate("BillsManager"); - - // START - this.ActivateItem(this.DBViewModel); - - if (this.settingsProvider.Settings.StartupDBLoad) // URGENT: remove the option: there is no connect button anymore - this.DBViewModel.Connect(); - } - - #endregion - - #region properties - - private DBViewModel dbViewModel; - public DBViewModel DBViewModel - { - get - { - return this.dbViewModel ?? (this.dbViewModel = this.dbViewModelFactory.Invoke()); - } - } - - - //private SearchViewModel searchViewModel; - //public SearchViewModel SearchViewModel - //{ - // get - // { - // if (this.searchViewModel == null) - // this.searchViewModel = this.searchBillsViewModelFactory.Invoke(); - - // return this.searchViewModel; - // } - //} - - private StatusBarViewModel statusBarViewModel; - public StatusBarViewModel StatusBarViewModel - { - get - { - return this.statusBarViewModel ?? (this.statusBarViewModel = this.statusBarViewModelFactory.Invoke()); - } - } - - #endregion - - #region methods - - private void ShowSendFeedback() - { - this.windowManager.ShowDialog( - this.sendFeedbackViewModelFactory.Invoke(), - settings: new Dictionary() - { - {"CanClose", true} - }); - } - - private void ShowSettings() - { - this.windowManager.ShowDialog( - this.settingsViewModelFactory.Invoke(), - settings: new Dictionary() - { - {"CanClose", false} - }); - } - - #endregion - - #region commands - - private RelayCommand showSendFeedbackCommand; - public RelayCommand ShowSendFeedbackCommand - { - get - { - return this.showSendFeedbackCommand ?? (this.showSendFeedbackCommand = - new RelayCommand( - () => this.ShowSendFeedback())); - } - } - - private RelayCommand showSettingsCommand; - public RelayCommand ShowSettingsCommand - { - get - { - return this.showSettingsCommand ?? (this.showSettingsCommand = - new RelayCommand( - () => this.ShowSettings())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/StatusBarViewModel.cs b/BillsManager.ViewModels/StatusBarViewModel.cs deleted file mode 100644 index 4ff62b5..0000000 --- a/BillsManager.ViewModels/StatusBarViewModel.cs +++ /dev/null @@ -1,155 +0,0 @@ -using BillsManager.Models; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System.ComponentModel; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public partial class StatusBarViewModel : Screen, - IHandle, - IHandle, - IHandle, - IHandle>, - IHandle>, - IHandle>, - IHandle> - { - #region fields - - private readonly IEventAggregator gloablEventAggregator; - - #endregion - - #region ctor - - public StatusBarViewModel(IEventAggregator gloablEventAggregator) - { - this.gloablEventAggregator = gloablEventAggregator; - this.gloablEventAggregator.Subscribe(this); - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - this.gloablEventAggregator.Unsubscribe(this); - }; - } - - #endregion - - #region properties - - private DBConnectionState connectionState = DBConnectionState.Disconnected; - public DBConnectionState ConnectionState - { - get { return this.connectionState; } - set - { - if (this.connectionState == value) return; - - this.connectionState = value; - this.NotifyOfPropertyChange(() => this.ConnectionState); - this.NotifyOfPropertyChange(() => this.ConnectionStateString); - - this.NotifyOfPropertyChange(() => this.IsConnected); - this.NotifyOfPropertyChange(() => this.IsDirty); - } - } - - public string ConnectionStateString - { - get - { - var tcs = - /*TranslationManager.Instance.Translate(*/ - typeof(DBConnectionState) - .GetMember(this.ConnectionState.ToString())[0] - .GetAttributes(true).FirstOrDefault().DisplayName - /*).ToString()*/; - - return tcs; - } - } - - public bool IsConnected - { - get { return this.ConnectionState != DBConnectionState.Disconnected; } - } - - public bool IsDirty - { - get { return this.ConnectionState != DBConnectionState.Unsaved; } - } - - private int suppliersCount; - public int SuppliersCount - { - get { return this.suppliersCount; } - set - { - if (this.suppliersCount == value) return; - - this.suppliersCount = value; - this.NotifyOfPropertyChange(() => this.SuppliersCount); - } - } - - private int billsCount; - public int BillsCount - { - get { return this.billsCount; } - set - { - if (this.billsCount == value) return; - - this.billsCount = value; - this.NotifyOfPropertyChange(() => this.BillsCount); - } - } - - #endregion - - #region methods - - #region message handlers - - public void Handle(DBConnectionStateChangedMessage message) - { - this.ConnectionState = message.DBState; - } - - public void Handle(SuppliersListChangedMessage message) - { - this.SuppliersCount = message.Suppliers.Count; - } - - public void Handle(BillsListChangedMessage message) - { - this.BillsCount = message.Bills.Count; - } - - public void Handle(AddedMessage message) - { - this.BillsCount++; - } - - public void Handle(DeletedMessage message) - { - this.BillsCount--; - } - - public void Handle(AddedMessage message) - { - this.SuppliersCount++; - } - - public void Handle(DeletedMessage message) - { - this.SuppliersCount--; - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.IDataErrorInfo.cs b/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.IDataErrorInfo.cs deleted file mode 100644 index f108f10..0000000 --- a/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.IDataErrorInfo.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.ComponentModel; -using BillsManager.ViewModels.Validation; -using System; - -namespace BillsManager.ViewModels -{ - public partial class SupplierAddEditViewModel : IDataErrorInfo - { - #region IDataErrorInfo - - private readonly ValidationRulesTracker rulesTracker; - - // TODO: a simpler way to notify IsValid might be to check if the notifying property has a validation rule - public bool IsValid - { - get { return this.HasChanges & string.IsNullOrEmpty(this.Error); } - } - - public string Error - { - get { return string.Join(Environment.NewLine, this.rulesTracker.GetAllErrors()); } - } - - public string this[string columnName] - { - get - { - //if (this.rulesTracker == null) - // this.rulesTracker = new ValidationRulesTracker(this); - - var errors = this.rulesTracker.GetErrorsForProperty(columnName); - return string.Join(Environment.NewLine, errors); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.IEditableObject.cs b/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.IEditableObject.cs deleted file mode 100644 index 90092fd..0000000 --- a/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.IEditableObject.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System.ComponentModel; -using BillsManager.Models; - -namespace BillsManager.ViewModels -{ - public partial class SupplierAddEditViewModel : IEditableObject - { - #region IEditableObject - - #region fields - - private Supplier _uneditedSupplier; - - #endregion - - #region properties - - private bool isInEditMode = false; - public bool IsInEditMode - { - get { return this.isInEditMode; } - private set - { - if (this.isInEditMode != value) - { - this.isInEditMode = value; - this.NotifyOfPropertyChange(() => this.IsInEditMode); - } - } - } - - private bool hasChanges = false; - public bool HasChanges - { - get { return this.hasChanges; } - private set - { - if (this.hasChanges != value) - { - this.hasChanges = value; - this.NotifyOfPropertyChange(() => this.HasChanges); - this.NotifyOfPropertyChange(() => this.DisplayName); - } - } - } - - #endregion - - #region methods - - public void BeginEdit() - { - this._uneditedSupplier = (Supplier)this.ExposedSupplier.Clone(); - - this.IsInEditMode = true; - } - - private void RevertChanges() - { - this.eMail = this._uneditedSupplier.eMail; - this.Name = this._uneditedSupplier.Name; - this.Notes = this._uneditedSupplier.Notes; - this.Phone = this._uneditedSupplier.Phone; - this.Fax = this._uneditedSupplier.Fax; - this.Website = this._uneditedSupplier.Website; - - //this.Address = this._uneditedSupplier.Address; // TODO: review - this.Street = this._uneditedSupplier.Street; - this.Number = this._uneditedSupplier.Number; - this.Zip = this._uneditedSupplier.Zip; - this.City = this._uneditedSupplier.City; - this.Province = this._uneditedSupplier.Province; - this.Country = this._uneditedSupplier.Country; - - this.AgentName = this._uneditedSupplier.AgentName; - this.AgentSurname = this._uneditedSupplier.AgentSurname; - this.AgentPhone = this._uneditedSupplier.AgentPhone; - } - - public void CancelEdit() - { - this.RevertChanges(); - - this.EndEdit(); - } - - public void EndEdit() - { - this.HasChanges = false; - - this._uneditedSupplier = null; - - this.IsInEditMode = false; - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.cs b/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.cs deleted file mode 100644 index a497390..0000000 --- a/BillsManager.ViewModels/SupplierViewModels/SupplierAddEditViewModel/SupplierAddEditViewModel.cs +++ /dev/null @@ -1,343 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Localization.Attributes; -using BillsManager.Models; -using BillsManager.ViewModels.Commanding; -using Caliburn.Micro; -using System; - -namespace BillsManager.ViewModels -{ - public partial class SupplierAddEditViewModel : SupplierViewModel - { - #region fields - - private readonly IWindowManager windowManager; - private readonly IEventAggregator dbEventAggregator; - - #endregion - - #region ctor - - public SupplierAddEditViewModel( - IWindowManager windowManager, - IEventAggregator dbEventAggregator, - Supplier supplier) - { - if (supplier == null) - throw new ArgumentNullException("supplier cannot be null."); - - // SERVICES - this.exposedSupplier = supplier; - this.windowManager = windowManager; - this.dbEventAggregator = dbEventAggregator; - - // SUBSCRIPTIONS - this.dbEventAggregator.Subscribe(this); - - // HANDLERS - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - { - this.dbEventAggregator.Unsubscribe(this); - } - }; - - this.rulesTracker = new Validation.ValidationRulesTracker(this); - } - - #endregion - - #region properties - - #region wrapped from supplier - - [LocalizedRequired(ErrorMessageKey = "NameRequired")] - public override string Name - { - get { return base.Name; } - set - { - if (this.Name != value) - { - base.Name = value; - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - public override string eMail - { - get { return base.eMail; } - set - { - if (this.eMail != value) - { - base.eMail = value; - this.HasChanges = true; - } - } - } - - public override string Website - { - get { return base.Website; } - set - { - if (this.Website != value) - { - base.Website = value; - this.HasChanges = true; - } - } - } - - public override string Phone - { - get { return base.Phone; } - set - { - base.Phone = value; - this.HasChanges = true; - } - } - - public override string Fax - { - get { return base.Fax; } - set - { - base.Fax = value; - this.HasChanges = true; - } - } - - [LocalizedStringLength(200, ErrorMessageFormatKey = "CannotExceedChars_format")] - public override string Notes - { - get { return base.Notes; } - set - { - base.Notes = value; - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - - public override string AgentName - { - get { return base.AgentName; } - set - { - base.AgentName = value; - this.NotifyOfPropertyChange(() => this.AgentName); - this.HasChanges = true; - } - } - - public override string AgentSurname - { - get { return base.AgentSurname; } - set - { - base.AgentSurname = value; - this.NotifyOfPropertyChange(() => this.AgentSurname); - this.HasChanges = true; - } - } - - public override string AgentPhone - { - get { return base.AgentPhone; } - set - { - base.AgentPhone = value; - this.NotifyOfPropertyChange(() => this.AgentPhone); - this.HasChanges = true; - } - } - - #region address - - public override string Street - { - get { return base.Street; } - set - { - if (this.Street != value) - { - base.Street = value; - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - public override string Number - { - get { return base.Number; } - set - { - if (this.Number != value) - { - base.Number = value; - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - public override string City - { - get { return base.City; } - set - { - if (this.City != value) - { - base.City = value; - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - //[Required(ErrorMessage = "You must specify a zip.")] - [LocalizedStringLength(5, MinimumLength = 5, ErrorMessageFormatKey = "MustBeNChars_format")] - //[CustomValidation(typeof(UInt32), "Parse", ErrorMessage = "The zip can only contain digits.")] // TODO: complete constraints - public override string Zip - { - get { return base.Zip; } - set - { - if (this.Zip == value) return; - - base.Zip = value; - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - - //[Required(ErrorMessage = "You must specify a province.")] - [LocalizedStringLength(2, MinimumLength = 2, ErrorMessageFormatKey = "MustBeNChars_format")] - public override string Province - { - get { return base.Province; } - set - { - if (this.Province == value) return; - - base.Province = value; - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - - public override string Country - { - get { return base.Country; } - set - { - if (this.Country != value) - { - base.Country = value; - this.NotifyOfPropertyChange(() => this.IsValid); - this.HasChanges = true; - } - } - } - - #endregion - - #endregion - - #region overrides - - public new string DisplayName - { - // TODO: move the change to IsInEditMode & HasChanges - get - { - return this.IsInEditMode - ? (TranslationManager.Instance.Translate("EditSupplier").ToString() + (this.IsInEditMode & this.HasChanges ? " *" : string.Empty)) - : TranslationManager.Instance.Translate("NewSupplier").ToString(); - } - } - - #endregion - - #endregion - - #region methods - - private void CancelddEditAndClose() - { - if (this.HasChanges) - { - DialogViewModel discardChangesDialog = - DialogViewModel.Show( - DialogType.Question, - this.IsInEditMode ? - TranslationManager.Instance.Translate("CancelEdit") : - TranslationManager.Instance.Translate("CancelAdd"), - TranslationManager.Instance.Translate("DiscardChangesQuestion")) - .YesNo(); - - this.windowManager.ShowDialog(discardChangesDialog); - - if (discardChangesDialog.FinalResponse == ResponseType.Yes) - { - if (this.IsInEditMode) - this.CancelEdit(); - - this.TryClose(false); - } - } - else - { - if (this.IsInEditMode) - this.CancelEdit(); - - this.TryClose(false); - } - } - - private void ConfirmAddEditAndClose() - { - if (this.IsInEditMode) - this.EndEdit(); - - this.TryClose(true); - } - - #endregion - - #region commands - - private RelayCommand confirmAddEditAndCloseCommand; - public RelayCommand ConfirmAddEditAndCloseCommand - { - get - { - return this.confirmAddEditAndCloseCommand ?? (this.confirmAddEditAndCloseCommand = - new RelayCommand( - () => this.ConfirmAddEditAndClose(), - () => this.IsValid)); - } - } - - private RelayCommand cancelAddEditAndCloseCommand; - public RelayCommand CancelAddEditAndCloseCommand - { - get - { - return this.cancelAddEditAndCloseCommand ?? (this.cancelAddEditAndCloseCommand = - new RelayCommand( - () => this.CancelddEditAndClose())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModel.IComparable.cs b/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModel.IComparable.cs deleted file mode 100644 index e6f3573..0000000 --- a/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModel.IComparable.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace BillsManager.ViewModels -{ - public partial class SupplierDetailsViewModel : IComparable - { - #region IComparable Members - - public int CompareTo(SupplierDetailsViewModel other) - { - return this.Name.CompareTo(other.Name); - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModel.cs b/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModel.cs deleted file mode 100644 index 5e85b59..0000000 --- a/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModel.cs +++ /dev/null @@ -1,315 +0,0 @@ -using BillsManager.Localization.Attributes; -using BillsManager.Models; -using BillsManager.ViewModels.Commanding; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System; -using System.Linq; - -namespace BillsManager.ViewModels -{ - public partial class SupplierDetailsViewModel : - SupplierViewModel, - IHandle, - IHandle>, - IHandle>, - IHandle> - { - #region fields - - protected readonly IWindowManager windowManager; - protected readonly IEventAggregator dbEventAggregator; - - #endregion - - #region ctor - - protected SupplierDetailsViewModel() { } - - public SupplierDetailsViewModel( - IWindowManager windowManager, - IEventAggregator dbEventAggregator, - Supplier supplier) - { - if (supplier == null) - throw new ArgumentNullException("supplier cannot be null"); - - this.ExposedSupplier = supplier; - - this.windowManager = windowManager; - this.dbEventAggregator = dbEventAggregator; - - this.dbEventAggregator.Subscribe(this); - - // HANDLERS - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - this.dbEventAggregator.Unsubscribe(this); - }; - } - - #endregion - - #region properties - - #region wrapped from supplier - - public override string AgentName - { - get { return base.AgentName; } - } - - public override string AgentPhone - { - get { return base.AgentPhone; } - } - - public override string AgentSurname - { - get { return base.AgentSurname; } - } - - public override string City - { - get { return base.City; } - } - - public override string Country - { - get { return base.Country; } - } - - public override string eMail - { - get { return base.eMail; } - } - - public override string Fax - { - get { return base.Fax; } - } - - public override string Name - { - get { return base.Name; } - } - - public override string Notes - { - get { return base.Notes; } - } - - public override string Number - { - get { return base.Number; } - } - - #endregion - - #region added - - private double obligationAmount = 0; - public double ObligationAmount - { - get { return obligationAmount; } - set - { - if (this.obligationAmount != value) - { - this.obligationAmount = value; - this.NotifyOfPropertyChange(() => this.ObligationAmount); - this.NotifyOfPropertyChange(() => this.ObligationState); - this.NotifyOfPropertyChange(() => this.ObligationStateString); - } - } - } - - public Obligation ObligationState - { - get - { - if (this.ObligationAmount < 0) return Obligation.Creditor; - if (this.ObligationAmount > 0) return Obligation.Debtor; - return Obligation.Unbound; - } - } - - public string ObligationStateString - { - get - { - return - /*TranslationManager.Instance.Translate(*/ - typeof(Obligation) - .GetMember(this.ObligationState.ToString())[0] - .GetAttributes(true).FirstOrDefault().DisplayName - /*).ToString()*/; - } - } - - public string FullAddress - { - get - { - var fullAddress = string.Empty; - - fullAddress += this.Street; - - fullAddress += (fullAddress.Length > 0 & !string.IsNullOrWhiteSpace(this.Number)) ? " " : string.Empty; - fullAddress += this.Number; - - fullAddress += - (fullAddress.Length > 0 & (!string.IsNullOrWhiteSpace(this.Zip) | !string.IsNullOrWhiteSpace(this.City))) ? - ", " : string.Empty; - fullAddress += this.Zip; - - fullAddress += - (fullAddress.Length > 0 & !string.IsNullOrWhiteSpace(this.City) & !string.IsNullOrWhiteSpace(this.Zip)) ? - " " : string.Empty; - fullAddress += this.City; - - var hasProv = !string.IsNullOrWhiteSpace(this.Province); - fullAddress += (fullAddress.Length > 0 & hasProv) ? " " : string.Empty; - if (hasProv) fullAddress += "(" + this.Province + ")"; - - fullAddress += (fullAddress.Length > 0 & !string.IsNullOrWhiteSpace(this.Country)) ? " - " : string.Empty; - fullAddress += this.Country; - - return fullAddress; - } - } - - #endregion - - #region overrides - - public new string DisplayName - { - get { return this.Name; } - } - - #endregion - - #endregion - - #region methods - - // TODO: evaluate move to SuppliersViewModel.cs - private void AddBill() - { - this.dbEventAggregator.PublishOnUIThread(new AddBillToSupplierOrder(this.ExposedSupplier)); - } - - #region message handlers - - public void Handle(BillsListChangedMessage message) - { - double newOblAmount = 0; - - foreach (var bill in message.Bills) - { - if (bill.SupplierID == this.ID & !bill.PaymentDate.HasValue) - newOblAmount += -bill.Amount; - } - - this.ObligationAmount = newOblAmount; - } - - public void Handle(AddedMessage message) - { - if (this.ID == message.AddedItem.SupplierID) - if (!message.AddedItem.PaymentDate.HasValue) - { - if (double.IsNaN(this.obligationAmount)) - this.ObligationAmount = 0; - this.ObligationAmount += -message.AddedItem.Amount; - } - } - - public void Handle(DeletedMessage message) - { - if (this.ID == message.DeletedItem.SupplierID) - if (!message.DeletedItem.PaymentDate.HasValue) - this.ObligationAmount += message.DeletedItem.Amount; - } - - public void Handle(EditedMessage message) - { - bool supplierChanged = message.NewItem.SupplierID != message.OldItem.SupplierID; - - if (supplierChanged) - { - if (this.ID == message.OldItem.SupplierID) - if (!message.OldItem.PaymentDate.HasValue) - { - this.ObligationAmount += message.OldItem.Amount; - } - else { } - else - { - if (this.ID == message.NewItem.SupplierID) - if (!message.NewItem.PaymentDate.HasValue) - this.ObligationAmount -= message.NewItem.Amount; - } - } - else - { - if (this.ID == message.NewItem.SupplierID) - { - if (!message.OldItem.PaymentDate.HasValue) - this.ObligationAmount += message.OldItem.Amount; - - if (!message.NewItem.PaymentDate.HasValue) - this.ObligationAmount -= message.NewItem.Amount; - } - } - } - - #endregion - - #endregion - - #region commands - - private RelayCommand switchToEditCommand; - public RelayCommand SwitchToEditCommand - { - get - { - return this.switchToEditCommand ?? (this.switchToEditCommand = - new RelayCommand( - () => - { - this.TryClose(); - this.dbEventAggregator.PublishOnUIThread(new EditSupplierOrder(this.ExposedSupplier)); - })); - } - } - - private RelayCommand closeDetailsViewCommand; - public RelayCommand CloseDetailsViewCommand - { - get - { - return this.closeDetailsViewCommand ?? (this.closeDetailsViewCommand = - new RelayCommand( - () => this.TryClose())); - } - } - - private RelayCommand addBillCommand; - public RelayCommand AddBillCommand - { - get - { - return this.addBillCommand ?? (addBillCommand = - new RelayCommand( - () => this.AddBill())); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModelComparer.cs b/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModelComparer.cs deleted file mode 100644 index 470621a..0000000 --- a/BillsManager.ViewModels/SupplierViewModels/SupplierDetailsViewModel/SupplierDetailsViewModelComparer.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; - -namespace BillsManager.ViewModels -{ - public class SupplierDetailsViewModelComparer : IComparer - { - #region IComparer Members - - public int Compare(SupplierDetailsViewModel x, SupplierDetailsViewModel y) - { - var change = x.CompareTo(y); - - return change; - } - - #endregion - - public SupplierDetailsViewModelComparer() { } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SupplierViewModels/SupplierViewModel.cs b/BillsManager.ViewModels/SupplierViewModels/SupplierViewModel.cs deleted file mode 100644 index 031ccee..0000000 --- a/BillsManager.ViewModels/SupplierViewModels/SupplierViewModel.cs +++ /dev/null @@ -1,263 +0,0 @@ -using BillsManager.Models; -using Caliburn.Micro; - -namespace BillsManager.ViewModels -{ - public abstract class SupplierViewModel : Screen - { - #region properties - - protected Supplier exposedSupplier; - public Supplier ExposedSupplier - { - get { return this.exposedSupplier; } - protected set - { - if (this.exposedSupplier != value) - { - this.exposedSupplier = value; - this.NotifyOfPropertyChange(); - } - } - } - - #region wrapped from supplier - - public uint ID - { - get { return this.ExposedSupplier.ID; } - } - - public virtual string Name - { - get { return this.ExposedSupplier.Name; } - set - { - if (this.Name != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.Name = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string eMail - { - get { return this.ExposedSupplier.eMail; } - set - { - if (this.eMail != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.eMail = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string Website - { - get { return this.ExposedSupplier.Website; } - set - { - if (this.Website != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.Website = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string Phone - { - get { return this.ExposedSupplier.Phone; } - set - { - if (this.Phone != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.Phone = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string Fax - { - get { return this.ExposedSupplier.Fax; } - set - { - if (this.Fax == value) return; - - if (value == string.Empty) - value = null; - this.ExposedSupplier.Fax = value; - this.NotifyOfPropertyChange(); - } - } - - public virtual string Notes - { - get { return this.ExposedSupplier.Notes; } - set - { - if (this.Notes != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.Notes = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string AgentName - { - get { return this.ExposedSupplier.AgentName; } - set - { - if (this.AgentName != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.AgentName = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string AgentSurname - { - get { return this.ExposedSupplier.AgentSurname; } - set - { - if (this.AgentSurname != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.AgentSurname = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string AgentPhone - { - get { return this.ExposedSupplier.AgentPhone; } - set - { - if (this.AgentPhone != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.AgentPhone = value; - this.NotifyOfPropertyChange(); - } - } - } - - #region address - - public virtual string Street - { - get { return this.ExposedSupplier.Street; } - set - { - if (this.Street != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.Street = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string Number - { - get { return this.ExposedSupplier.Number; } - set - { - if (this.Number != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.Number = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string City - { - get { return this.ExposedSupplier.City; } - set - { - if (this.City != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.City = value; - this.NotifyOfPropertyChange(); - } - } - } - - public virtual string Zip - { - get { return this.ExposedSupplier.Zip; } - set - { - if (this.Zip == value) return; - - if (value == string.Empty) - value = null; - - this.ExposedSupplier.Zip = value; - this.NotifyOfPropertyChange(); - } - } - - public virtual string Province - { - get { return this.ExposedSupplier.Province; } - set - { - if (this.Province == value) return; - - if (value == string.Empty) - value = null; - - this.ExposedSupplier.Province = value; - this.NotifyOfPropertyChange(); - } - } - - public virtual string Country - { - get { return this.ExposedSupplier.Country; } - set - { - if (this.Country != value) - { - if (value == string.Empty) - value = null; - this.ExposedSupplier.Country = value; - this.NotifyOfPropertyChange(); - } - } - } - - #endregion - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/SuppliersViewModel.cs b/BillsManager.ViewModels/SuppliersViewModel.cs deleted file mode 100644 index 424faf8..0000000 --- a/BillsManager.ViewModels/SuppliersViewModel.cs +++ /dev/null @@ -1,428 +0,0 @@ -using BillsManager.Localization; -using BillsManager.Models; -using BillsManager.Services.DB; -using BillsManager.ViewModels.Commanding; -using BillsManager.ViewModels.Messages; -using Caliburn.Micro; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Windows; - -namespace BillsManager.ViewModels -{ - public sealed partial class SuppliersViewModel : - Screen, - IHandle, - IHandle>, - IHandle, - IHandle, - IHandle, - IHandle> - { - #region fields - - private readonly IWindowManager windowManager; - private readonly IEventAggregator globalEventAggregator; - private readonly ISuppliersRepository suppliersProvider; - - private readonly Func supplierAddEditViewModelFactory; - private readonly Func supplierDetailsViewModelFactory; - - private readonly IComparer supplierDetailsVMComparer = new SupplierDetailsViewModelComparer(); - - #endregion - - #region ctor - - public SuppliersViewModel( - IWindowManager windowManager, - IEventAggregator globalEventAggregator, - ISuppliersRepository suppliersProvider, - Func supplierAddEditViewModelFactory, - Func supplierDetailsViewModelFactory) - { - // SERVICES - this.suppliersProvider = suppliersProvider; - this.windowManager = windowManager; - this.globalEventAggregator = globalEventAggregator; - - // FACTORIES - this.supplierAddEditViewModelFactory = supplierAddEditViewModelFactory; - this.supplierDetailsViewModelFactory = supplierDetailsViewModelFactory; - - // SUBSCRIPTIONS - this.globalEventAggregator.Subscribe(this); - - // HANDLERS - this.Deactivated += - (s, e) => - { - if (e.WasClosed) - this.globalEventAggregator.Unsubscribe(this); - }; - - // UI - this.DisplayName = @"Suppliers"; - - // START - this.LoadSuppliers(); - } - - #endregion - - #region properties - - private ObservableCollection supplierViewModels; - public ObservableCollection SupplierViewModels - { - get { return this.supplierViewModels; } - set - { - if (this.supplierViewModels != value) - { - this.supplierViewModels = value; - this.NotifyOfPropertyChange(() => this.SupplierViewModels); - this.FilteredSupplierViewModels = - new ReadOnlyObservableCollectionEx( - this.SupplierViewModels, - this.Filters != null ? this.Filters.Select(f => f.Execute) : null, - this.supplierDetailsVMComparer); - - // IDEA: #IF !DEBUG ? - if (!Execute.InDesignMode) - this.globalEventAggregator.PublishOnUIThread(new SuppliersListChangedMessage(this.SupplierViewModels.Select(svm => svm.ExposedSupplier).ToList())); - } - } - } - - private ReadOnlyObservableCollectionEx filteredSupplierViewModels; - public ReadOnlyObservableCollectionEx FilteredSupplierViewModels - { - get { return this.filteredSupplierViewModels; } - private set - { - // TODO: remove set / make lazy get? - - if (this.filteredSupplierViewModels == value) return; - - this.filteredSupplierViewModels = value; - this.NotifyOfPropertyChange(() => this.FilteredSupplierViewModels); - } - } - - private SupplierDetailsViewModel selectedSupplierViewModel; - public SupplierDetailsViewModel SelectedSupplierViewModel - { - get { return this.selectedSupplierViewModel; } - set - { - if (this.selectedSupplierViewModel != value) - { - this.selectedSupplierViewModel = value; - this.NotifyOfPropertyChange(); - - var newSelSupp = value != null ? value.ExposedSupplier : null; - this.globalEventAggregator.PublishOnUIThread(new SelectedSupplierChangedMessage(newSelSupp)); - } - } - } - - private IEnumerable> filters; - public IEnumerable> Filters - { - get { return this.filters; } - private set - { - if (this.filters != value) - { - this.filters = value; - this.NotifyOfPropertyChange(); - this.UpdateFilters(); - } - } - } - - #endregion - - #region methods - - public void LoadSuppliers() - { - var supps = this.suppliersProvider.GetAllSuppliers(); - - var suppVMs = supps.Select(supplier => this.supplierDetailsViewModelFactory.Invoke(supplier)).ToList(); - - suppVMs.Sort(); - - this.SupplierViewModels = new ObservableCollection(suppVMs); - } - - private string GetSupplierSummary(Supplier supplier) - { - return - supplier.Name + - Environment.NewLine + - supplier.Street + - " " + supplier.Number + - ", " + supplier.Zip + - " " + supplier.City + - " (" + supplier.Province + ")" + - " - " + supplier.Country; - } - - #region CRUD - - private void AddSupplier() - { - { - var addSupplierVM = this.supplierAddEditViewModelFactory.Invoke(new Supplier(this.suppliersProvider.GetLastSupplierID() + 1)); - - tryAdd: // TODO: optimize - if (this.windowManager.ShowDialog(addSupplierVM) == true) - { - if (this.suppliersProvider.Add(addSupplierVM.ExposedSupplier)) - { - var newSupplierDetailsVM = this.supplierDetailsViewModelFactory.Invoke(addSupplierVM.ExposedSupplier); - - this.SupplierViewModels.Add(newSupplierDetailsVM); - - this.SelectedSupplierViewModel = newSupplierDetailsVM; - - this.globalEventAggregator.PublishOnUIThread(new AddedMessage(addSupplierVM.ExposedSupplier)); - } - else // TODO: reshow the dialog with this suppVM - { - var dialog = - DialogViewModel - .Show( - DialogType.Error, - TranslationManager.Instance.Translate("AddSupplierFailed").ToString(), - TranslationManager.Instance.Translate("AddSupplierFailedMessage").ToString() + - Environment.NewLine + - TranslationManager.Instance.Translate("TryAgain").ToString()) - .Ok(); - - this.windowManager.ShowDialog(dialog); - - goto tryAdd; - } - } - } - } - - private void EditSupplier(Supplier supplier) - { - Supplier oldSupplier = (Supplier)supplier.Clone(); - var editSupplierVM = this.supplierAddEditViewModelFactory.Invoke(supplier); - - editSupplierVM.BeginEdit(); - - if (this.windowManager.ShowDialog(editSupplierVM) == true) - { - if (this.suppliersProvider.Edit(editSupplierVM.ExposedSupplier)) - { - // TODO: move to this.EditSupplier - var editedSupplierDetailsVM = this.SupplierViewModels.FirstOrDefault(svm => svm.ExposedSupplier == supplier); - editedSupplierDetailsVM.Refresh(); - - this.SelectedSupplierViewModel = null; - - this.globalEventAggregator.PublishOnUIThread(new EditedMessage(oldSupplier, editSupplierVM.ExposedSupplier)); - } - else - { - // URGENT: dont exit if changes are not saved - var dialog = - DialogViewModel.Show( - DialogType.Error, - TranslationManager.Instance.Translate("EditFailed").ToString(), - TranslationManager.Instance.Translate("EditFailedMessage").ToString()) - .Ok(); - - this.windowManager.ShowDialog(dialog); - } - } - } - - private void DeleteSupplier(Supplier supplier) - { - DialogViewModel deleteSupplierQuestion = - DialogViewModel.Show( - DialogType.Question, - TranslationManager.Instance.Translate("DeleteSupplier").ToString(), - TranslationManager.Instance.Translate("DeleteSupplierQuestion").ToString() + - Environment.NewLine + - Environment.NewLine + - this.GetSupplierSummary(supplier)) - .YesNo(); - - this.windowManager.ShowDialog(deleteSupplierQuestion); - - if (deleteSupplierQuestion.FinalResponse == ResponseType.Yes) - { - if (this.suppliersProvider.Delete(supplier)) - { - if (this.SelectedSupplierViewModel.ExposedSupplier == supplier) - this.SelectedSupplierViewModel = null; - - this.SupplierViewModels.Remove(this.SupplierViewModels.FirstOrDefault(svm => svm.ExposedSupplier == supplier)); - - this.NotifyOfPropertyChange(() => this.FilteredSupplierViewModels); - this.globalEventAggregator.PublishOnUIThread(new DeletedMessage(supplier)); - - //this.globalEventAggregator.PublishOnUIThread(new SuppliersListChangedMessage(this.SupplierViewModels.Select(svm => svm.ExposedSupplier).ToList())); - } - } - } - - private void ShowSupplierDetails(SupplierDetailsViewModel supplierViewModel) - { - // TODO: make paramter use only supplier - // TODO: decide if CanClose of window is enabled on edit views - this.windowManager.ShowDialog(supplierViewModel, settings: new Dictionary { { "CanClose", true } }); - } - - #endregion - - #region extras - - private void ShowSupplierBills(Supplier supplier) - { - this.globalEventAggregator.PublishOnUIThread(new ShowSuppliersBillsOrder(supplier)); - } - - private void CopyEMail(SupplierDetailsViewModel supplierVM) - { - Clipboard.SetText(supplierVM.eMail); - } - - #endregion - - #region message handlers - - public void Handle(AvailableSuppliersRequest message) - { - message.AcquireSuppliersAction(this.SupplierViewModels.Select(svm => svm.ExposedSupplier)); - } - - public void Handle(FilterMessage message) - { - this.Filters = message.Filters; - - if (!this.FilteredSupplierViewModels.Contains(this.SelectedSupplierViewModel)) - this.SelectedSupplierViewModel = null; - } - - public void Handle(AddNewSupplierOrder message) - { - //if (this.suppliersProvider.Name == message.DBName) - //{ - this.AddSupplier(); - //} - } - - public void Handle(SupplierNameRequest message) - { - message.GiveSupplier(this.SupplierViewModels.FirstOrDefault(svm => svm.ID == message.SupplierID).ExposedSupplier.Name); - } - - public void Handle(EditSupplierOrder message) - { - this.EditSupplier(message.Supplier); - } - - public void Handle(FilterMessage message) - { - // TODO: when bills are filtered by a supplier, select that supplier - } - - #endregion - - #region support - private void UpdateFilters() - { - this.FilteredSupplierViewModels.Filters = (this.Filters != null ? this.Filters.Select(f => f.Execute) : null); - } - - #endregion - - #endregion - - #region commands - - private RelayCommand addNewSupplierCommand; - public RelayCommand AddNewSupplierCommand - { - get - { - return this.addNewSupplierCommand ?? (this.addNewSupplierCommand = - new RelayCommand( - () => this.AddSupplier())); - } - } - - private RelayCommand editSupplierCommand; - public RelayCommand EditSupplierCommand - { - get - { - return this.editSupplierCommand ?? (this.editSupplierCommand = - new RelayCommand( - p => this.EditSupplier(p.ExposedSupplier), - p => p != null)); - } - } - - private RelayCommand deleteSupplierCommand; - public RelayCommand DeleteSupplierCommand - { - get - { - return this.deleteSupplierCommand ?? (this.deleteSupplierCommand = - new RelayCommand( - p => this.DeleteSupplier(p.ExposedSupplier), - p => p != null)); - } - } - - private RelayCommand showSuppliersBillsCommand; - public RelayCommand ShowSuppliersBillsCommand - { - get - { - return this.showSuppliersBillsCommand ?? (this.showSuppliersBillsCommand = - new RelayCommand( - p => this.ShowSupplierBills(p.ExposedSupplier), - p => p != null)); - } - } - - private RelayCommand showSupplierDetailsCommand; - public RelayCommand ShowSupplierDetailsCommand - { - get - { - return this.showSupplierDetailsCommand ?? (this.showSupplierDetailsCommand = - new RelayCommand( - p => this.ShowSupplierDetails(p), - p => p != null)); - } - } - - private RelayCommand copyEMailCommand; - public RelayCommand CopyEMailCommand - { - get - { - return this.copyEMailCommand ?? (this.copyEMailCommand = - new RelayCommand( - p => this.CopyEMail(p), - p => p != null && !string.IsNullOrWhiteSpace(p.eMail))); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/Validation/ValidationRulesTrackerGeneric.cs b/BillsManager.ViewModels/Validation/ValidationRulesTrackerGeneric.cs deleted file mode 100644 index c0e41f2..0000000 --- a/BillsManager.ViewModels/Validation/ValidationRulesTrackerGeneric.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Reflection; - -namespace BillsManager.ViewModels.Validation -{ - public class ValidationRulesTracker - where T : class - { - private readonly T trackedObject; - private readonly Dictionary validationRules; - - public ValidationRulesTracker(T trackedObject) - { - if (trackedObject == null) - throw new ArgumentNullException("trackedObject"); - - this.trackedObject = trackedObject; - this.validationRules = new Dictionary(); - - this.MapValidationRules(); - } - - protected void MapValidationRules() - { - foreach (PropertyInfo pi in this.trackedObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) - { - ValidationAttribute[] valAtts = (ValidationAttribute[])pi.GetCustomAttributes(typeof(ValidationAttribute), true); - - if (valAtts.Any()) // TODO: what if no validation rules? - this.validationRules.Add(pi.Name, valAtts); - } - } - - protected object GetPropertyValue(string propertyName) - { - return typeof(T).GetProperty(propertyName).GetValue(this.trackedObject); - } - - public IEnumerable GetErrorsForProperty(string propertyName) - { - if (this.validationRules.ContainsKey(propertyName)) - { - var validations = this.validationRules[propertyName]; - - var errors = validations - .Where(vr => - { - var v = !vr.IsValid(this.GetPropertyValue(propertyName)); - return v; - }) - .Select(vr => - { - var e = vr.ErrorMessage; - return e; - }) - .ToArray(); - - return errors; - } - return Enumerable.Empty(); - } - - public IEnumerable GetAllErrors() // TODO: optimize for speed - { - return this.validationRules.Keys.SelectMany(k => this.GetErrorsForProperty(k)); - } - } -} \ No newline at end of file diff --git a/BillsManager.ViewModels/app.config b/BillsManager.ViewModels/app.config deleted file mode 100644 index 9e100cf..0000000 --- a/BillsManager.ViewModels/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/BillsManager.ViewModels/packages.config b/BillsManager.ViewModels/packages.config deleted file mode 100644 index 03ddd97..0000000 --- a/BillsManager.ViewModels/packages.config +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/BillsManager.Views/Behaviors/TextBoxBehavior.cs b/BillsManager.Views/Behaviors/TextBoxBehavior.cs deleted file mode 100644 index 78a349c..0000000 --- a/BillsManager.Views/Behaviors/TextBoxBehavior.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System.Collections.Generic; -using System.Text.RegularExpressions; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; - -namespace BillsManager.Views.Behaviors -{ - public class TextBoxBehavior - { - #region input filtering - - #region fields - - private const string DEFAULT_INPUT_FORMAT = "(?s).*"; - - private static Regex inputFormatRegex = new Regex(DEFAULT_INPUT_FORMAT); - - private static readonly Dictionary regexes = new Dictionary(); - - #endregion - - #region filter input - - public static readonly DependencyProperty FilterInputProperty = - DependencyProperty.RegisterAttached( - "FilterInput", - typeof(bool), - typeof(TextBoxBehavior), - new UIPropertyMetadata(false, OnFilterInputChanged)); - - public static bool GetFilterInput(TextBox sender) - { - return (bool)sender.GetValue(TextBoxBehavior.FilterInputProperty); - } - - public static void SetFilterInput(TextBox sender, bool value) - { - sender.SetValue(TextBoxBehavior.FilterInputProperty, value); - } - - private static void OnFilterInputChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e) - { - var txt = depObj as TextBox; - - if (txt == null) return; - - if (e.NewValue is bool == false) return; - - if ((bool)e.NewValue) - { - regexes.Add(txt, new Regex(GetInputFormat(txt))); - - txt.PreviewTextInput += OnPreviewTextInput; - DataObject.AddPastingHandler(txt, OnClipboardPaste); - } - else - { - txt.PreviewTextInput -= OnPreviewTextInput; - DataObject.RemovePastingHandler(txt, OnClipboardPaste); - - regexes.Remove(txt); - } - } - - private static void OnPreviewTextInput(object sender, TextCompositionEventArgs e) - { - var txt = sender as TextBox; - if (txt == null) return; - - if (!IsValid(txt, e.Text)) - e.Handled = true; - } - - private static void OnClipboardPaste(object sender, DataObjectPastingEventArgs e) - { - var txt = sender as TextBox; - if (txt == null) return; - - string text = e.SourceDataObject.GetData(e.FormatToApply) as string; - - if (!IsValid(txt, text)) - e.CancelCommand(); - } - - private static bool IsValid(TextBox txt, string newContent) - { - string testString = string.Empty; - - if (!string.IsNullOrEmpty(txt.SelectedText)) - { - string pre = txt.Text.Substring(0, txt.SelectionStart); - string after = txt.Text.Substring(txt.SelectionStart + txt.SelectionLength, txt.Text.Length - (txt.SelectionStart + txt.SelectionLength)); - testString = pre + newContent + after; - } - else - { - string pre = txt.Text.Substring(0, txt.CaretIndex); - string after = txt.Text.Substring(txt.CaretIndex, txt.Text.Length - txt.CaretIndex); - testString = pre + newContent + after; - } - - if (regexes[txt].IsMatch(testString)) - return true; - - return false; - } - - #endregion - - #region input format - - public static readonly DependencyProperty InputFormatProperty = - DependencyProperty.RegisterAttached( - "InputFormat", - typeof(string), - typeof(TextBoxBehavior), - new PropertyMetadata(DEFAULT_INPUT_FORMAT, OnInputFormatChanged)); // ^\d{5}$ - - public static string GetInputFormat(TextBox sender) - { - return (string)sender.GetValue(TextBoxBehavior.InputFormatProperty); - } - - public static void SetInputFormat(TextBox sender, string value) - { - sender.SetValue(TextBoxBehavior.InputFormatProperty, value); - } - - private static void OnInputFormatChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e) - { - var txt = depObj as TextBox; - if (txt == null) return; - - if (e.NewValue is string == false) return; - - if (regexes.ContainsKey(txt)) - regexes[txt] = new Regex(GetInputFormat(txt)); - } - - #endregion - - #region ValueWhenLeftEmpty - - public static readonly DependencyProperty ValueWhenLeftEmptyProperty = - DependencyProperty.RegisterAttached( - "ValueWhenLeftEmpty", - typeof(string), - typeof(TextBoxBehavior), - new PropertyMetadata(null, OnValueWhenLeftEmptyChanged)); - - public static string GetValueWhenLeftEmpty(TextBox sender) - { - return (string)sender.GetValue(TextBoxBehavior.ValueWhenLeftEmptyProperty); - } - - public static void SetValueWhenLeftEmpty(TextBox sender, string value) - { - sender.SetValue(TextBoxBehavior.ValueWhenLeftEmptyProperty, value); - } - - private static void OnValueWhenLeftEmptyChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e) - { - var txt = depObj as TextBox; - if (txt == null) return; - - if (e.NewValue is string == false) return; - - if (e.NewValue != null) - txt.LostFocus += SetValueWhenLeftEmpty; - else - txt.LostFocus -= SetValueWhenLeftEmpty; - } - - private static void SetValueWhenLeftEmpty(object sender, RoutedEventArgs e) - { - var txt = sender as TextBox; - if (txt == null) return; - - if (txt.Text == string.Empty) - txt.Text = GetValueWhenLeftEmpty(txt); - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/BillsManager.Views/BillAddEditView.xaml b/BillsManager.Views/BillAddEditView.xaml deleted file mode 100644 index a1911fe..0000000 --- a/BillsManager.Views/BillAddEditView.xaml +++ /dev/null @@ -1,289 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/BillsManager.Views/DBsView.xaml.cs b/BillsManager.Views/DBsView.xaml.cs deleted file mode 100644 index 219eafb..0000000 --- a/BillsManager.Views/DBsView.xaml.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; - -namespace BillsManager.Views -{ - /// - /// Interaction logic for DBsView.xaml - /// - public partial class DBsView : UserControl - { - public DBsView() - { - InitializeComponent(); - } - } -} diff --git a/BillsManager.Views/DataTemplates/AgentDataTemplate.xaml b/BillsManager.Views/DataTemplates/AgentDataTemplate.xaml deleted file mode 100644 index 2912580..0000000 --- a/BillsManager.Views/DataTemplates/AgentDataTemplate.xaml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/BillsManager.Views/DataTemplates/AgentDataTemplate.xaml.cs b/BillsManager.Views/DataTemplates/AgentDataTemplate.xaml.cs deleted file mode 100644 index 3955bf6..0000000 --- a/BillsManager.Views/DataTemplates/AgentDataTemplate.xaml.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Windows.Controls; - -namespace BillsManager.View.DataTemplates -{ - /// - /// Logica di interazione per AgentDataTemplate.xaml - /// - public partial class AgentDataTemplate : UserControl - { - public AgentDataTemplate() - { - InitializeComponent(); - } - } -} diff --git a/BillsManager.Views/DataTemplates/BillDataTemplate.xaml b/BillsManager.Views/DataTemplates/BillDataTemplate.xaml deleted file mode 100644 index d9960c3..0000000 --- a/BillsManager.Views/DataTemplates/BillDataTemplate.xaml +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/BillsManager.Views/DataTemplates/BillDataTemplate.xaml.cs b/BillsManager.Views/DataTemplates/BillDataTemplate.xaml.cs deleted file mode 100644 index f7e761d..0000000 --- a/BillsManager.Views/DataTemplates/BillDataTemplate.xaml.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Windows.Controls; - -namespace BillsManager.Views.DataTemplates -{ - /// - /// Logica di interazione per BillDataTemplate.xaml - /// - public partial class BillDataTemplate : UserControl - { - public BillDataTemplate() - { - InitializeComponent(); - } - } -} diff --git a/BillsManager.Views/DataTemplates/DBDataTemplate.xaml b/BillsManager.Views/DataTemplates/DBDataTemplate.xaml deleted file mode 100644 index 48e2893..0000000 --- a/BillsManager.Views/DataTemplates/DBDataTemplate.xaml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/BillsManager.Views/DataTemplates/ResponseDataTemplate.xaml b/BillsManager.Views/DataTemplates/ResponseDataTemplate.xaml deleted file mode 100644 index 6bda955..0000000 --- a/BillsManager.Views/DataTemplates/ResponseDataTemplate.xaml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - -